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.

update groupBy and filter query params

Steven Tey0fb5cdc9f2fb
diff --git a/apps/web/lib/analytics/constants.ts b/apps/web/lib/analytics/constants.ts
index acee5ccf5b..995679e404 100644
--- a/apps/web/lib/analytics/constants.ts
+++ b/apps/web/lib/analytics/constants.ts
@@ -113,7 +113,11 @@ export const VALID_ANALYTICS_ENDPOINTS = [
"referer_urls",
"top_links",
"top_urls",
- "utms",
+ "utm_sources",
+ "utm_mediums",
+ "utm_campaigns",
+ "utm_terms",
+ "utm_contents",
] as const;
export const SINGULAR_ANALYTICS_ENDPOINTS = {
@@ -127,7 +131,11 @@ export const SINGULAR_ANALYTICS_ENDPOINTS = {
referer_urls: "refererUrl",
os: "os",
triggers: "trigger",
- utms: "utm",
+ utm_sources: "utm_source",
+ utm_mediums: "utm_medium",
+ utm_campaigns: "utm_campaign",
+ utm_terms: "utm_term",
+ utm_contents: "utm_content",
};
export const VALID_ANALYTICS_FILTERS = [
@@ -151,6 +159,11 @@ export const VALID_ANALYTICS_FILTERS = [
"tagIds",
"qr",
"root",
+ "utm_source",
+ "utm_medium",
+ "utm_campaign",
+ "utm_term",
+ "utm_content",
];
export const TRIGGER_DISPLAY = {
diff --git a/apps/web/lib/analytics/get-analytics.ts b/apps/web/lib/analytics/get-analytics.ts
index 5cb77d77d1..b83eaab7fa 100644
--- a/apps/web/lib/analytics/get-analytics.ts
+++ b/apps/web/lib/analytics/get-analytics.ts
@@ -1,5 +1,6 @@
import { combineTagIds } from "@/lib/api/tags/combine-tag-ids";
import { tb } from "@/lib/tinybird";
+import { UTM_TAGS_PLURAL_LIST } from "@/lib/zod/schemas/utm";
import { prismaEdge } from "@dub/prisma/edge";
import { linkConstructor, punyEncode } from "@dub/utils";
import { conn } from "../planetscale";
@@ -7,6 +8,7 @@ import { tbDemo } from "../tinybird/demo-client";
import z from "../zod";
import { analyticsFilterTB } from "../zod/schemas/analytics";
import { analyticsResponse } from "../zod/schemas/analytics-response";
+import { SINGULAR_ANALYTICS_ENDPOINTS } from "./constants";
import { AnalyticsFilters } from "./types";
import { getStartEndDates } from "./utils/get-start-end-dates";
@@ -78,16 +80,19 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
// Create a Tinybird pipe
const pipe = (isDemo ? tbDemo : tb).buildPipe({
- pipe: `v2_${groupBy}`,
+ pipe: `v2_${UTM_TAGS_PLURAL_LIST.includes(groupBy) ? "utms" : groupBy}`,
parameters: analyticsFilterTB,
data:
- groupBy === "top_links" || groupBy === "utms"
+ groupBy === "top_links" || UTM_TAGS_PLURAL_LIST.includes(groupBy)
? z.any()
: analyticsResponse[groupBy],
});
const response = await pipe({
...params,
+ ...(UTM_TAGS_PLURAL_LIST.includes(groupBy)
+ ? { groupByUtmTag: SINGULAR_ANALYTICS_ENDPOINTS[groupBy] }
+ : {}),
eventType: event,
workspaceId,
tagIds,
@@ -149,16 +154,15 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
});
})
.filter((d) => d !== null);
- }
- // UTMs
- else if (groupBy === "utms") {
+ // special case for utm tags
+ } else if (UTM_TAGS_PLURAL_LIST.includes(groupBy)) {
const schema = analyticsResponse[groupBy];
return response.data.map((item) =>
schema.parse({
- utm: item.value,
- clicks: item.count,
+ ...item,
+ [SINGULAR_ANALYTICS_ENDPOINTS[groupBy]]: item.utm,
}),
);
}
diff --git a/apps/web/lib/zod/schemas/analytics-response.ts b/apps/web/lib/zod/schemas/analytics-response.ts
index 5856731c66..81b64d21a2 100644
--- a/apps/web/lib/zod/schemas/analytics-response.ts
+++ b/apps/web/lib/zod/schemas/analytics-response.ts
@@ -339,25 +339,113 @@ export const analyticsResponse = {
})
.openapi({ ref: "AnalyticsTopUrls" }),
- utms: z
+ utm_sources: z
.object({
- utm: z.string().describe("The name of the UTM parameter"),
+ utm_source: z.string().describe("The UTM source"),
clicks: z
.number()
- .describe("The number of clicks from this UTM parameter")
+ .describe("The number of clicks with this UTM source")
.default(0),
leads: z
.number()
- .describe("The number of leads from this UTM parameter")
+ .describe("The number of leads with this UTM source")
.default(0),
sales: z
.number()
- .describe("The number of sales from this UTM parameter")
+ .describe("The number of sales with this UTM source")
.default(0),
saleAmount: z
.number()
- .describe("The total amount of sales from this UTM parameter, in cents")
+ .describe("The total amount of sales with this UTM source, in cents")
.default(0),
})
- .openapi({ ref: "AnalyticsUTMs" }),
+ .openapi({ ref: "AnalyticsUTMSources" }),
+
+ utm_mediums: z
+ .object({
+ utm_medium: z.string().describe("The UTM medium"),
+ clicks: z
+ .number()
+ .describe("The number of clicks with this UTM medium")
+ .default(0),
+ leads: z
+ .number()
+ .describe("The number of leads with this UTM medium")
+ .default(0),
+ sales: z
+ .number()
+ .describe("The number of sales with this UTM medium")
+ .default(0),
+ saleAmount: z
+ .number()
+ .describe("The total amount of sales with this UTM medium, in cents")
+ .default(0),
+ })
+ .openapi({ ref: "AnalyticsUTMMediums" }),
+
+ utm_campaigns: z
+ .object({
+ utm_campaign: z.string().describe("The UTM campaign"),
+ clicks: z
+ .number()
+ .describe("The number of clicks with this UTM campaign")
+ .default(0),
+ leads: z
+ .number()
+ .describe("The number of leads with this UTM campaign")
+ .default(0),
+ sales: z
+ .number()
+ .describe("The number of sales with this UTM campaign")
+ .default(0),
+ saleAmount: z
+ .number()
+ .describe("The total amount of sales with this UTM campaign, in cents")
+ .default(0),
+ })
+ .openapi({ ref: "AnalyticsUTMCampaigns" }),
+
+ utm_terms: z
+ .object({
+ utm_term: z.string().describe("The UTM term"),
+ clicks: z
+ .number()
+ .describe("The number of clicks with this UTM term")
+ .default(0),
+ leads: z
+ .number()
+ .describe("The number of leads with this UTM term")
+ .default(0),
+ sales: z
+ .number()
+ .describe("The number of sales with this UTM term")
+ .default(0),
+ saleAmount: z
+ .number()
+ .describe("The total amount of sales with this UTM term, in cents")
+ .default(0),
+ })
+ .openapi({ ref: "AnalyticsUTMTerms" }),
+
+ utm_contents: z
+ .object({
+ utm_content: z.string().describe("The UTM content"),
+ clicks: z
+ .number()
+ .describe("The number of clicks with this UTM content")
+ .default(0),
+ leads: z
+ .number()
+ .describe("The number of leads with this UTM content")
+ .default(0),
+ sales: z
+ .number()
+ .describe("The number of sales with this UTM content")
+ .default(0),
+ saleAmount: z
+ .number()
+ .describe("The total amount of sales with this UTM content, in cents")
+ .default(0),
+ })
+ .openapi({ ref: "AnalyticsUTMContents" }),
} as const;
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index ef19416ef1..07c68fd26a 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -18,6 +18,7 @@ import {
} from "@dub/utils";
import { booleanQuerySchema } from "./misc";
import { parseDateSchema } from "./utils";
+import { utmTagsSchema } from "./utm";
const analyticsEvents = z
.enum([...EVENT_TYPES, "composite"], {
@@ -43,7 +44,7 @@ const analyticsGroupBy = z
})
.default("count")
.describe(
- "The parameter to group the analytics data points by. Defaults to `count` if undefined. Note that `trigger` is deprecated (use `triggers` instead), but kept for backwards compatibility.",
+ "The parameter to group the analytics data points by. Defaults to `count` if undefined.",
);
const oldAnalyticsEndpoints = z
@@ -66,134 +67,134 @@ export const analyticsPathParamsSchema = z.object({
});
// Query schema for /api/analytics endpoint
-export const analyticsQuerySchema = z.object({
- event: analyticsEvents,
- groupBy: analyticsGroupBy,
- domain: z.string().optional().describe("The domain to filter analytics for."),
- key: z.string().optional().describe("The short link slug."),
- linkId: z
- .string()
- .optional()
- .describe("The unique ID of the short link on Dub."),
- externalId: z
- .string()
- .optional()
- .describe(
- "This is the ID of the link in the your database. Must be prefixed with 'ext_' when passed as a query parameter.",
- ),
- interval: z
- .enum(intervals)
- .optional()
- .describe(
- "The interval to retrieve analytics for. If undefined, defaults to 24h.",
- ),
- start: parseDateSchema
- .refine((value: Date) => value >= DUB_FOUNDING_DATE, {
- message: `The start date cannot be earlier than ${formatDate(DUB_FOUNDING_DATE)}.`,
- })
- .optional()
- .describe(
- "The start date and time when to retrieve analytics from. Takes precedence over `interval`.",
- ),
- end: parseDateSchema
- .optional()
- .describe(
- "The end date and time when to retrieve analytics from. If not provided, defaults to the current date. Takes precedence over `interval`.",
- ),
- timezone: z
- .string()
- .optional()
- .describe(
- "The IANA time zone code for aligning timeseries granularity (e.g. America/New_York). Defaults to UTC.",
- )
- .openapi({ example: "America/New_York", default: "UTC" }),
- country: z
- .enum(COUNTRY_CODES)
- .optional()
- .describe("The country to retrieve analytics for.")
- .openapi({ ref: "countryCode" }),
- city: z
- .string()
- .optional()
- .describe("The city to retrieve analytics for.")
- .openapi({ example: "New York" }),
- region: z
- .string()
- .optional()
- .describe("The ISO 3166-2 region code to retrieve analytics for.")
- .openapi({ ref: "regionCode" }),
- continent: z
- .enum(CONTINENT_CODES)
- .optional()
- .describe("The continent to retrieve analytics for.")
- .openapi({ ref: "continentCode" }),
- device: z
- .string()
- .optional()
- .transform((v) => capitalize(v) as string | undefined)
- .describe("The device to retrieve analytics for.")
- .openapi({ example: "Desktop" }),
- browser: z
- .string()
- .optional()
- .transform((v) => capitalize(v) as string | undefined)
- .describe("The browser to retrieve analytics for.")
- .openapi({ example: "Chrome" }),
- os: z
- .string()
- .optional()
- .transform((v) => {
- if (v === "iOS") return "iOS";
- return capitalize(v) as string | undefined;
- })
- .describe("The OS to retrieve analytics for.")
- .openapi({ example: "Windows" }),
- trigger: z
- .enum(TRIGGER_TYPES)
- .optional()
- .describe(
- "The trigger to retrieve analytics for. If undefined, return both QR and link clicks.",
- ),
- referer: z
- .string()
- .optional()
- .describe("The referer to retrieve analytics for.")
- .openapi({ example: "google.com" }),
- refererUrl: z
- .string()
- .optional()
- .describe("The full referer URL to retrieve analytics for.")
- .openapi({ example: "https://dub.co/blog" }),
- url: z.string().optional().describe("The URL to retrieve analytics for."),
- tagId: z
- .string()
- .optional()
- .describe(
- "Deprecated. Use `tagIds` instead. The tag ID to retrieve analytics for.",
- )
- .openapi({ deprecated: true }),
- tagIds: z
- .union([z.string(), z.array(z.string())])
- .transform((v) => (Array.isArray(v) ? v : v.split(",")))
- .optional()
- .describe("The tag IDs to retrieve analytics for."),
- qr: booleanQuerySchema
- .optional()
- .describe(
- "Deprecated. Use the `trigger` field instead. Filter for QR code scans. If true, filter for QR codes only. If false, filter for links only. If undefined, return both.",
- )
- .openapi({ deprecated: true }),
- root: booleanQuerySchema
- .optional()
- .describe(
- "Filter for root domains. If true, filter for domains only. If false, filter for links only. If undefined, return both.",
- ),
- utmTag: z
- .string()
- .default("utm_source")
- .optional()
- .describe("The UTM tag to filter for. Defaults to `utm_source`."),
-});
+export const analyticsQuerySchema = z
+ .object({
+ event: analyticsEvents,
+ groupBy: analyticsGroupBy,
+ domain: z
+ .string()
+ .optional()
+ .describe("The domain to filter analytics for."),
+ key: z.string().optional().describe("The short link slug."),
+ linkId: z
+ .string()
+ .optional()
+ .describe("The unique ID of the short link on Dub."),
+ externalId: z
+ .string()
+ .optional()
+ .describe(
+ "This is the ID of the link in the your database. Must be prefixed with 'ext_' when passed as a query parameter.",
+ ),
+ interval: z
+ .enum(intervals)
+ .optional()
+ .describe(
+ "The interval to retrieve analytics for. If undefined, defaults to 24h.",
+ ),
+ start: parseDateSchema
+ .refine((value: Date) => value >= DUB_FOUNDING_DATE, {
+ message: `The start date cannot be earlier than ${formatDate(DUB_FOUNDING_DATE)}.`,
+ })
+ .optional()
+ .describe(
+ "The start date and time when to retrieve analytics from. Takes precedence over `interval`.",
+ ),
+ end: parseDateSchema
+ .optional()
+ .describe(
+ "The end date and time when to retrieve analytics from. If not provided, defaults to the current date. Takes precedence over `interval`.",
+ ),
+ timezone: z
+ .string()
+ .optional()
+ .describe(
+ "The IANA time zone code for aligning timeseries granularity (e.g. America/New_York). Defaults to UTC.",
+ )
+ .openapi({ example: "America/New_York", default: "UTC" }),
+ country: z
+ .enum(COUNTRY_CODES)
+ .optional()
+ .describe("The country to retrieve analytics for.")
+ .openapi({ ref: "countryCode" }),
+ city: z
+ .string()
+ .optional()
+ .describe("The city to retrieve analytics for.")
+ .openapi({ example: "New York" }),
+ region: z
+ .string()
+ .optional()
+ .describe("The ISO 3166-2 region code to retrieve analytics for.")
+ .openapi({ ref: "regionCode" }),
+ continent: z
+ .enum(CONTINENT_CODES)
+ .optional()
+ .describe("The continent to retrieve analytics for.")
+ .openapi({ ref: "continentCode" }),
+ device: z
+ .string()
+ .optional()
+ .transform((v) => capitalize(v) as string | undefined)
+ .describe("The device to retrieve analytics for.")
+ .openapi({ example: "Desktop" }),
+ browser: z
+ .string()
+ .optional()
+ .transform((v) => capitalize(v) as string | undefined)
+ .describe("The browser to retrieve analytics for.")
+ .openapi({ example: "Chrome" }),
+ os: z
+ .string()
+ .optional()
+ .transform((v) => {
+ if (v === "iOS") return "iOS";
+ return capitalize(v) as string | undefined;
+ })
+ .describe("The OS to retrieve analytics for.")
+ .openapi({ example: "Windows" }),
+ trigger: z
+ .enum(TRIGGER_TYPES)
+ .optional()
+ .describe(
+ "The trigger to retrieve analytics for. If undefined, return both QR and link clicks.",
+ ),
+ referer: z
+ .string()
+ .optional()
+ .describe("The referer to retrieve analytics for.")
+ .openapi({ example: "google.com" }),
+ refererUrl: z
+ .string()
+ .optional()
+ .describe("The full referer URL to retrieve analytics for.")
+ .openapi({ example: "https://dub.co/blog" }),
+ url: z.string().optional().describe("The URL to retrieve analytics for."),
+ tagId: z
+ .string()
+ .optional()
+ .describe(
+ "Deprecated. Use `tagIds` instead. The tag ID to retrieve analytics for.",
+ )
+ .openapi({ deprecated: true }),
+ tagIds: z
+ .union([z.string(), z.array(z.string())])
+ .transform((v) => (Array.isArray(v) ? v : v.split(",")))
+ .optional()
+ .describe("The tag IDs to retrieve analytics for."),
+ qr: booleanQuerySchema
+ .optional()
+ .describe(
+ "Deprecated. Use the `trigger` field instead. Filter for QR code scans. If true, filter for QR codes only. If false, filter for links only. If undefined, return both.",
+ )
+ .openapi({ deprecated: true }),
+ root: booleanQuerySchema
+ .optional()
+ .describe(
+ "Filter for root domains. If true, filter for domains only. If false, filter for links only. If undefined, return both.",
+ ),
+ })
+ .merge(utmTagsSchema);
// Analytics filter params for Tinybird endpoints
export const analyticsFilterTB = z
@@ -217,6 +218,10 @@ export const analyticsFilterTB = z
end: z.string(),
granularity: z.enum(["minute", "hour", "day", "month"]).optional(),
timezone: z.string().optional(),
+ groupByUtmTag: z
+ .string()
+ .optional()
+ .describe("The UTM tag to group by. Defaults to `utm_source`."),
})
.merge(
analyticsQuerySchema.pick({
@@ -233,7 +238,11 @@ export const analyticsFilterTB = z
refererUrl: true,
tagIds: true,
url: true,
- utmTag: true,
+ utm_source: true,
+ utm_medium: true,
+ utm_campaign: true,
+ utm_term: true,
+ utm_content: true,
}),
);
diff --git a/apps/web/lib/zod/schemas/utm.ts b/apps/web/lib/zod/schemas/utm.ts
index 28f50b4ed3..c08cc1a642 100644
--- a/apps/web/lib/zod/schemas/utm.ts
+++ b/apps/web/lib/zod/schemas/utm.ts
@@ -47,3 +47,51 @@ export const createUTMTemplateBodySchema = z.object({
});
export const updateUTMTemplateBodySchema = createUTMTemplateBodySchema;
+
+export const utmTagsSchema = z.object({
+ utm_source: z
+ .string()
+ .trim()
+ .max(190)
+ .nullish()
+ .describe("The UTM source of the short link."),
+ utm_medium: z
+ .string()
+ .trim()
+ .max(190)
+ .nullish()
+ .describe("The UTM medium of the short link."),
+ utm_campaign: z
+ .string()
+ .trim()
+ .max(190)
+ .nullish()
+ .describe("The UTM campaign of the short link."),
+ utm_term: z
+ .string()
+ .trim()
+ .max(190)
+ .nullish()
+ .describe("The UTM term of the short link."),
+ utm_content: z
+ .string()
+ .trim()
+ .max(190)
+ .nullish()
+ .describe("The UTM content of the short link."),
+});
+
+export const UTM_TAGS_PLURAL_LIST = [
+ "utm_sources",
+ "utm_mediums",
+ "utm_campaigns",
+ "utm_terms",
+ "utm_contents",
+];
+
+export type UTM_TAGS_PLURAL =
+ | "utm_sources"
+ | "utm_mediums"
+ | "utm_campaigns"
+ | "utm_terms"
+ | "utm_contents";
diff --git a/apps/web/ui/analytics/locations.tsx b/apps/web/ui/analytics/locations.tsx
index df8381a001..cbcd43f7e5 100644
--- a/apps/web/ui/analytics/locations.tsx
+++ b/apps/web/ui/analytics/locations.tsx
@@ -25,7 +25,7 @@ export default function Locations() {
"countries" | "cities" | "continents" | "regions"
>("countries");
- const { data, loading } = useAnalyticsFilterOption(tab);
+ const { data } = useAnalyticsFilterOption(tab);
const singularTabName = SINGULAR_ANALYTICS_ENDPOINTS[tab];
return (
diff --git a/apps/web/ui/analytics/referer.tsx b/apps/web/ui/analytics/referer.tsx
index 2675aa1586..8e47fef4d3 100644
--- a/apps/web/ui/analytics/referer.tsx
+++ b/apps/web/ui/analytics/referer.tsx
@@ -1,7 +1,8 @@
import { SINGULAR_ANALYTICS_ENDPOINTS } from "@/lib/analytics/constants";
+import { UTM_TAGS_PLURAL, UTM_TAGS_PLURAL_LIST } from "@/lib/zod/schemas/utm";
import { BlurImage, useRouterStuff, UTM_PARAMETERS } from "@dub/ui";
import { Note, ReferredVia } from "@dub/ui/icons";
-import { getApexDomain, GOOGLE_FAVICON_URL } from "@dub/utils";
+import { capitalize, getApexDomain, GOOGLE_FAVICON_URL } from "@dub/utils";
import { Link2 } from "lucide-react";
import { useContext, useMemo, useState } from "react";
import { AnalyticsCard } from "./analytics-card";
@@ -17,27 +18,29 @@ export default function Referer() {
const dataKey = selectedTab === "sales" ? saleUnit : "count";
const [tab, setTab] = useState<"referers" | "utms">("referers");
- const [utmTag, setUtmTag] = useState<string>("utm_source");
+ const [utmTag, setUtmTag] = useState<UTM_TAGS_PLURAL>("utm_sources");
const [refererType, setRefererType] = useState<"referers" | "referer_urls">(
"referers",
);
const { data } = useAnalyticsFilterOption({
- groupBy: tab === "referers" ? refererType : tab,
- utmTag: tab === "utms" ? utmTag : undefined,
+ groupBy: tab === "utms" ? utmTag : refererType,
});
+
const singularTabName =
- SINGULAR_ANALYTICS_ENDPOINTS[tab === "referers" ? refererType : tab];
+ SINGULAR_ANALYTICS_ENDPOINTS[tab === "utms" ? utmTag : refererType];
- const { icon: UTMTagIcon } = UTM_PARAMETERS.find((p) => p.key === utmTag)!;
+ const { icon: UTMTagIcon } = UTM_PARAMETERS.find(
+ (p) => p.key === utmTag.slice(0, -1),
+ )!;
const subTabProps = useMemo(() => {
return (
{
utms: {
- subTabs: UTM_PARAMETERS.filter((p) => p.key !== "ref").map((p) => ({
- id: p.key,
- label: p.label,
+ subTabs: UTM_TAGS_PLURAL_LIST.map((u) => ({
+ id: u,
+ label: capitalize(u.replace("utm_", "")) as string,
})),
selectedSubTabId: utmTag,
onSelectSubTab: setUtmTag,
@@ -94,19 +97,16 @@ export default function Referer() {
/>
),
title: d[singularTabName],
- href:
- tab === "utms"
- ? undefined
- : (queryParams({
- ...(searchParams.has(singularTabName)
- ? { del: singularTabName }
- : {
- set: {
- [singularTabName]: d[singularTabName],
- },
- }),
- getNewPath: true,
- }) as string),
+ 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) || []