Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Analytics: UTM tags

Kiran Kde5d4bdac051
diff --git a/apps/web/lib/analytics/constants.ts b/apps/web/lib/analytics/constants.ts
index b1dfc9d16f..acee5ccf5b 100644
--- a/apps/web/lib/analytics/constants.ts
+++ b/apps/web/lib/analytics/constants.ts
@@ -113,6 +113,7 @@ export const VALID_ANALYTICS_ENDPOINTS = [
"referer_urls",
"top_links",
"top_urls",
+ "utms",
] as const;
export const SINGULAR_ANALYTICS_ENDPOINTS = {
@@ -126,6 +127,7 @@ export const SINGULAR_ANALYTICS_ENDPOINTS = {
referer_urls: "refererUrl",
os: "os",
triggers: "trigger",
+ utms: "utm",
};
export const VALID_ANALYTICS_FILTERS = [
diff --git a/apps/web/lib/analytics/get-analytics.ts b/apps/web/lib/analytics/get-analytics.ts
index b01b4846da..11028e1d5c 100644
--- a/apps/web/lib/analytics/get-analytics.ts
+++ b/apps/web/lib/analytics/get-analytics.ts
@@ -80,9 +80,14 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
const pipe = (isDemo ? tbDemo : tb).buildPipe({
pipe: `v2_${groupBy}`,
parameters: analyticsFilterTB,
- data: groupBy === "top_links" ? z.any() : analyticsResponse[groupBy],
+ data:
+ groupBy === "top_links" || groupBy === "utms"
+ ? z.any()
+ : analyticsResponse[groupBy],
});
+ console.log("params", params);
+
const response = await pipe({
...params,
eventType: event,
@@ -148,6 +153,18 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
.filter((d) => d !== null);
}
+ // UTMs
+ else if (groupBy === "utms") {
+ const schema = analyticsResponse[groupBy];
+
+ return response.data.map((item) =>
+ schema.parse({
+ utm: item.value,
+ clicks: item.count,
+ }),
+ );
+ }
+
// Return array for other endpoints
return response.data;
};
diff --git a/apps/web/lib/zod/schemas/analytics-response.ts b/apps/web/lib/zod/schemas/analytics-response.ts
index d4d3f7eece..5856731c66 100644
--- a/apps/web/lib/zod/schemas/analytics-response.ts
+++ b/apps/web/lib/zod/schemas/analytics-response.ts
@@ -338,4 +338,26 @@ export const analyticsResponse = {
.default(0),
})
.openapi({ ref: "AnalyticsTopUrls" }),
+
+ utms: z
+ .object({
+ utm: z.string().describe("The name of the UTM parameter"),
+ clicks: z
+ .number()
+ .describe("The number of clicks from this UTM parameter")
+ .default(0),
+ leads: z
+ .number()
+ .describe("The number of leads from this UTM parameter")
+ .default(0),
+ sales: z
+ .number()
+ .describe("The number of sales from this UTM parameter")
+ .default(0),
+ saleAmount: z
+ .number()
+ .describe("The total amount of sales from this UTM parameter, in cents")
+ .default(0),
+ })
+ .openapi({ ref: "AnalyticsUTMs" }),
} as const;
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index 20bb2b0191..bee0be18e1 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -188,6 +188,11 @@ export const analyticsQuerySchema = z.object({
.describe(
"Filter for root domains. If true, filter for domains only. If false, filter for links only. If undefined, return both.",
),
+ utmTag: z
+ .string()
+ .optional()
+ .default("utm_source")
+ .describe("The UTM tag to filter for. Defaults to `utm_source`."),
});
// Analytics filter params for Tinybird endpoints
diff --git a/apps/web/ui/analytics/analytics-provider.tsx b/apps/web/ui/analytics/analytics-provider.tsx
index 1fb5dae7b3..f6d12dfabc 100644
--- a/apps/web/ui/analytics/analytics-provider.tsx
+++ b/apps/web/ui/analytics/analytics-provider.tsx
@@ -22,8 +22,8 @@ import { fetcher } from "@dub/utils";
import { endOfDay, startOfDay, subDays } from "date-fns";
import { useParams, usePathname, useSearchParams } from "next/navigation";
import {
- PropsWithChildren,
createContext,
+ PropsWithChildren,
useEffect,
useMemo,
useState,
@@ -65,6 +65,8 @@ export const AnalyticsContext = createContext<{
showConversions?: boolean;
requiresUpgrade?: boolean;
dashboardProps?: AnalyticsDashboardProps;
+ utmTag?: string;
+ setUtmTag?: (key: string) => void;
}>({
basePath: "",
baseApiPath: "",
@@ -82,6 +84,8 @@ export const AnalyticsContext = createContext<{
showConversions: false,
requiresUpgrade: false,
dashboardProps: undefined,
+ utmTag: "utm_source",
+ setUtmTag: () => {},
});
export default function AnalyticsProvider({
@@ -121,6 +125,8 @@ export default function AnalyticsProvider({
tagIds: searchParams?.get("tagIds")?.split(","),
})?.join(",");
+ const [utmTag, setUtmTag] = useState<string>("utm_source");
+
// Default to last 24 hours
const { start, end } = useMemo(() => {
const hasRange = searchParams?.has("start") && searchParams?.has("end");
@@ -271,8 +277,19 @@ export default function AnalyticsProvider({
...(tagIds && { tagIds }),
...(root && { root: root.toString() }),
event: selectedTab,
+ ...(utmTag && { utmTag }),
}).toString();
- }, [workspaceId, domain, key, searchParams, start, end, tagIds, selectedTab]);
+ }, [
+ workspaceId,
+ domain,
+ key,
+ searchParams,
+ start,
+ end,
+ tagIds,
+ selectedTab,
+ utmTag,
+ ]);
// Reset requiresUpgrade when query changes
useEffect(() => setRequiresUpgrade(false), [queryString]);
@@ -339,6 +356,8 @@ export default function AnalyticsProvider({
dashboardProps,
showConversions, // Whether to show conversions tabs/data
requiresUpgrade, // whether an upgrade is required to perform the query
+ utmTag,
+ setUtmTag,
}}
>
{children}
diff --git a/apps/web/ui/analytics/referer.tsx b/apps/web/ui/analytics/referer.tsx
index 848d2bff6b..4d3a1af8f5 100644
--- a/apps/web/ui/analytics/referer.tsx
+++ b/apps/web/ui/analytics/referer.tsx
@@ -1,6 +1,11 @@
import { SINGULAR_ANALYTICS_ENDPOINTS } from "@/lib/analytics/constants";
-import { BlurImage, useRouterStuff } from "@dub/ui";
-import { ReferredVia } from "@dub/ui/icons";
+import {
+ BlurImage,
+ ToggleGroup,
+ useRouterStuff,
+ UTM_PARAMETERS,
+} from "@dub/ui";
+import { Note, ReferredVia } from "@dub/ui/icons";
import { getApexDomain, GOOGLE_FAVICON_URL } from "@dub/utils";
import { Link2 } from "lucide-react";
import { useContext, useState } from "react";
@@ -13,17 +18,23 @@ import { useAnalyticsFilterOption } from "./utils";
export default function Referer() {
const { queryParams, searchParams } = useRouterStuff();
- const { selectedTab, saleUnit } = useContext(AnalyticsContext);
+ const { selectedTab, saleUnit, utmTag, setUtmTag } =
+ useContext(AnalyticsContext);
const dataKey = selectedTab === "sales" ? saleUnit : "count";
- const [tab, setTab] = useState<"referers" | "referer_urls">("referers");
- const { data, loading } = useAnalyticsFilterOption(tab);
+ const [tab, setTab] = useState<"referers" | "utms" | "referer_urls">(
+ "referers",
+ );
+ const { data } = useAnalyticsFilterOption(tab);
const singularTabName = SINGULAR_ANALYTICS_ENDPOINTS[tab];
+ const { icon: UTMTagIcon } = UTM_PARAMETERS.find((p) => p.key === utmTag)!;
+
return (
<AnalyticsCard
tabs={[
{ id: "referers", label: "Referrers", icon: ReferredVia },
+ { id: "utms", label: "UTM Parameters", icon: Note },
{ id: "referer_urls", label: "Referrer URLs", icon: ReferredVia },
]}
selectedTabId={tab}
@@ -31,63 +42,94 @@ export default function Referer() {
expandLimit={8}
hasMore={(data?.length ?? 0) > 8}
>
- {({ limit, setShowModal }) =>
- data ? (
- data.length > 0 ? (
- <BarList
- tab="Referrer"
- data={
- data
- ?.map((d) => ({
- icon:
- d[singularTabName] === "(direct)" ? (
- <Link2 className="h-4 w-4" />
- ) : (
- <BlurImage
- src={`${GOOGLE_FAVICON_URL}${
- tab === "referers"
- ? d[singularTabName]
- : getApexDomain(d[singularTabName])
- }`}
- alt={d[singularTabName]}
- width={20}
- height={20}
- className="h-4 w-4 rounded-full"
- />
- ),
- title: d[singularTabName],
- href: queryParams({
- ...(searchParams.has(singularTabName)
- ? { del: singularTabName }
- : {
- set: {
- [singularTabName]: d[singularTabName],
- },
- }),
- getNewPath: true,
- }) as string,
- value: d[dataKey] || 0,
- }))
- ?.sort((a, b) => b.value - a.value) || []
- }
- unit={selectedTab}
- maxValue={Math.max(...data?.map((d) => d[dataKey] ?? 0)) ?? 0}
- barBackground="bg-red-100"
- hoverBackground="hover:bg-gradient-to-r hover:from-red-50 hover:to-transparent hover:border-red-500"
- setShowModal={setShowModal}
- {...(limit && { limit })}
+ {({ limit, setShowModal }) => (
+ <>
+ {tab === "utms" && (
+ <UtmTabs
+ selectedTab={utmTag || "utm_source"}
+ onSelectTab={setUtmTag || (() => {})}
/>
+ )}
+ {data ? (
+ data.length > 0 ? (
+ <BarList
+ tab="Referrer"
+ data={
+ data
+ ?.map((d) => ({
+ icon:
+ tab === "utms" ? (
+ <UTMTagIcon />
+ ) : d[singularTabName] === "(direct)" ? (
+ <Link2 className="h-4 w-4" />
+ ) : (
+ <BlurImage
+ src={`${GOOGLE_FAVICON_URL}${
+ tab === "referers"
+ ? d[singularTabName]
+ : getApexDomain(d[singularTabName])
+ }`}
+ alt={d[singularTabName]}
+ width={20}
+ height={20}
+ className="h-4 w-4 rounded-full"
+ />
+ ),
+ title: d[singularTabName],
+ href: queryParams({
+ ...(searchParams.has(singularTabName)
+ ? { del: singularTabName }
+ : {
+ set: {
+ [singularTabName]: d[singularTabName],
+ },
+ }),
+ getNewPath: true,
+ }) as string,
+ value: d[dataKey] || 0,
+ }))
+ ?.sort((a, b) => b.value - a.value) || []
+ }
+ unit={selectedTab}
+ maxValue={Math.max(...data?.map((d) => d[dataKey] ?? 0)) ?? 0}
+ barBackground="bg-red-100"
+ hoverBackground="hover:bg-gradient-to-r hover:from-red-50 hover:to-transparent hover:border-red-500"
+ setShowModal={setShowModal}
+ {...(limit && { limit })}
+ />
+ ) : (
+ <div className="flex h-[300px] items-center justify-center">
+ <p className="text-sm text-gray-600">No data available</p>
+ </div>
+ )
) : (
- <div className="flex h-[300px] items-center justify-center">
- <p className="text-sm text-gray-600">No data available</p>
+ <div className="absolute inset-0 flex h-[300px] w-full items-center justify-center bg-white/50">
+ <AnalyticsLoadingSpinner />
</div>
- )
- ) : (
- <div className="absolute inset-0 flex h-[300px] w-full items-center justify-center bg-white/50">
- <AnalyticsLoadingSpinner />
- </div>
- )
- }
+ )}
+ </>
+ )}
</AnalyticsCard>
);
}
+
+interface UtmTabsProps {
+ selectedTab: string;
+ onSelectTab: (key: string) => void;
+}
+
+const UtmTabs: React.FC<UtmTabsProps> = ({ selectedTab, onSelectTab }) => {
+ return (
+ <div className="my-2 w-full px-4">
+ <ToggleGroup
+ options={UTM_PARAMETERS.map((p) => ({
+ value: p.key,
+ label: p.label,
+ }))}
+ selected={selectedTab}
+ selectAction={(period) => onSelectTab(period)}
+ className="flex w-full flex-wrap rounded-md sm:flex-nowrap"
+ />
+ </div>
+ );
+};
diff --git a/apps/web/ui/modals/link-builder/utm-templates-button.tsx b/apps/web/ui/modals/link-builder/utm-templates-button.tsx
index 30f33f78b2..b0013c9e1a 100644
--- a/apps/web/ui/modals/link-builder/utm-templates-button.tsx
+++ b/apps/web/ui/modals/link-builder/utm-templates-button.tsx
@@ -129,8 +129,6 @@ function UTMTemplateOption({
template: UtmTemplateProps;
onClick: () => void;
}) {
- const [deleting, setDeleting] = useState(false);
-
return (
<div className="group relative">
<button