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.

test(advanced-filters): fix and create new tests

Pedro Ladeiraa2e03b036eb7
diff --git a/apps/web/app/(ee)/api/cron/usage/utils.ts b/apps/web/app/(ee)/api/cron/usage/utils.ts
index 78a01a6033..a3eb0f1898 100644
--- a/apps/web/app/(ee)/api/cron/usage/utils.ts
+++ b/apps/web/app/(ee)/api/cron/usage/utils.ts
@@ -122,7 +122,7 @@ export const updateUsage = async () => {
event: "clicks",
groupBy: "top_links",
interval: "30d",
- root: false,
+ root: { values: ["false"], operator: "IS", sqlOperator: "IN" },
});
const topFive = topLinks.slice(0, 5);
diff --git a/apps/web/lib/analytics/get-analytics.ts b/apps/web/lib/analytics/get-analytics.ts
index f2482ab10b..366e100c2c 100644
--- a/apps/web/lib/analytics/get-analytics.ts
+++ b/apps/web/lib/analytics/get-analytics.ts
@@ -99,7 +99,7 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
// Create a Tinybird pipe
const pipe = tb.buildPipe({
- pipe: ["count", "timeseries"].includes(groupBy)
+ pipe: ["count", "timeseries"].includes(groupBy!)
? `v3_${groupBy}`
: [
"top_folders",
@@ -107,7 +107,7 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
"top_domains",
"top_partners",
"top_groups",
- ].includes(groupBy)
+ ].includes(groupBy!)
? "v3_group_by_link_metadata"
: "v3_group_by",
parameters: analyticsFilterTB,
@@ -180,7 +180,7 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
const { groupByField, ...rest } = response.data[0];
// Return the count value for deprecated count endpoints
if (isDeprecatedClicksEndpoint) {
- return rest[event];
+ return rest[event!];
// Return the object for regular count endpoints
} else {
return rest;
@@ -344,12 +344,12 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
}
// Return array for other endpoints
- const schema = analyticsResponse[groupBy];
+ const schema = analyticsResponse[groupBy!];
return response.data.map((item) =>
schema.parse({
...item,
- [SINGULAR_ANALYTICS_ENDPOINTS[groupBy]]: item.groupByField,
+ [SINGULAR_ANALYTICS_ENDPOINTS[groupBy!]]: item.groupByField,
}),
);
};
diff --git a/apps/web/lib/analytics/types.ts b/apps/web/lib/analytics/types.ts
index 564025f657..813b20f97b 100644
--- a/apps/web/lib/analytics/types.ts
+++ b/apps/web/lib/analytics/types.ts
@@ -37,18 +37,15 @@ export type AnalyticsSaleUnit = (typeof ANALYTICS_SALE_UNIT)[number];
export type DeviceTabs = "devices" | "browsers" | "os" | "triggers";
-export type AnalyticsFilters = Override<
- z.infer<typeof analyticsQuerySchema>,
- {
- workspaceId?: string;
- dataAvailableFrom?: Date;
- isDeprecatedClicksEndpoint?: boolean;
- linkIds?: string[];
- folderIds?: string[]; // TODO: remove this once it's been added to the public API
- start?: Date | null;
- end?: Date | null;
- }
->;
+export type AnalyticsFilters = Partial<Omit<z.infer<typeof analyticsQuerySchema>, 'start' | 'end'>> & {
+ workspaceId?: string;
+ dataAvailableFrom?: Date;
+ isDeprecatedClicksEndpoint?: boolean;
+ linkIds?: string[];
+ folderIds?: string[]; // TODO: remove this once it's been added to the public API
+ start?: Date | null;
+ end?: Date | null;
+};
export type EventsFilters = z.infer<typeof eventsQuerySchema> & {
workspaceId?: string;
diff --git a/apps/web/lib/zod/schemas/partners.ts b/apps/web/lib/zod/schemas/partners.ts
index 3bf1660582..05707d1503 100644
--- a/apps/web/lib/zod/schemas/partners.ts
+++ b/apps/web/lib/zod/schemas/partners.ts
@@ -8,10 +8,11 @@ import {
ProgramEnrollmentStatus,
SalesChannel,
} from "@dub/prisma/client";
-import { COUNTRY_CODES } from "@dub/utils";
+import { COUNTRY_CODES, DUB_FOUNDING_DATE, formatDate } from "@dub/utils";
import * as z from "zod/v4";
-import { analyticsQuerySchema } from "./analytics";
+import { DATE_RANGE_INTERVAL_PRESETS } from "@/lib/analytics/constants";
import { analyticsResponse } from "./analytics-response";
+import { parseDateSchema } from "./utils";
import { createLinkBodySchema } from "./links";
import {
base64ImageSchema,
@@ -688,25 +689,51 @@ export const upsertPartnerLinkSchema = createPartnerLinkSchema.extend({
});
// For /api/partners/analytics
-export const partnerAnalyticsQuerySchema = analyticsQuerySchema
- .pick({
- partnerId: true,
- tenantId: true,
- interval: true,
- start: true,
- end: true,
- timezone: true,
- query: true,
- })
- .extend(partnerIdTenantIdSchema.shape)
- .extend({
- groupBy: z
- .enum(["top_links", "timeseries", "count"])
- .default("count")
- .describe(
- "The parameter to group the analytics data points by. Defaults to `count` if undefined.",
- ),
- });
+export const partnerAnalyticsQuerySchema = z.object({
+ partnerId: z
+ .string()
+ .nullish()
+ .describe("The ID of the partner to retrieve analytics for."),
+ tenantId: z
+ .string()
+ .nullish()
+ .describe("The ID of the tenant to retrieve analytics for."),
+ interval: z
+ .enum(DATE_RANGE_INTERVAL_PRESETS)
+ .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. If set, 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. If set along with `start`, 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.",
+ ),
+ query: z
+ .string()
+ .optional()
+ .describe("Custom metadata filter query string."),
+ groupBy: z
+ .enum(["top_links", "timeseries", "count"])
+ .default("count")
+ .describe(
+ "The parameter to group the analytics data points by. Defaults to `count` if undefined.",
+ ),
+});
const earningsSchema = z.object({
earnings: z.number().default(0),
diff --git a/apps/web/scripts/download-top-links.ts b/apps/web/scripts/download-top-links.ts
index 31ffb6d71b..3cd1ab44bd 100644
--- a/apps/web/scripts/download-top-links.ts
+++ b/apps/web/scripts/download-top-links.ts
@@ -11,7 +11,7 @@ async function main() {
groupBy: "top_links",
workspaceId: "xxx",
interval: "30d",
- root: false,
+ root: { values: ["false"], operator: "IS", sqlOperator: "IN" },
}).then(async (data) => {
return await Promise.all(
data.map(
diff --git a/apps/web/scripts/dub-wrapped.ts b/apps/web/scripts/dub-wrapped.ts
index 395a460078..2cca0f3208 100644
--- a/apps/web/scripts/dub-wrapped.ts
+++ b/apps/web/scripts/dub-wrapped.ts
@@ -61,7 +61,7 @@ async function main() {
event: "clicks",
groupBy: "top_links",
interval: "ytd",
- root: false,
+ root: { values: ["false"], operator: "IS", sqlOperator: "IN" },
}),
getAnalytics({
workspaceId: projectId!,
diff --git a/apps/web/scripts/get-top-links-for-workspace.ts b/apps/web/scripts/get-top-links-for-workspace.ts
index fa52e738a3..8e3fe35eb8 100644
--- a/apps/web/scripts/get-top-links-for-workspace.ts
+++ b/apps/web/scripts/get-top-links-for-workspace.ts
@@ -39,7 +39,7 @@ async function main() {
groupBy: "top_links",
workspaceId: workspace.id,
interval: "30d",
- root: false,
+ root: { values: ["false"], operator: "IS", sqlOperator: "IN" },
}).then(async (data) => {
const topFive = data.slice(0, 5);
return await Promise.all(
diff --git a/apps/web/tests/analytics/advanced-filters.test.ts b/apps/web/tests/analytics/advanced-filters.test.ts
index dd6871271c..ee959111f2 100644
--- a/apps/web/tests/analytics/advanced-filters.test.ts
+++ b/apps/web/tests/analytics/advanced-filters.test.ts
@@ -9,7 +9,7 @@ describe("Advanced Filters - Unit Tests", () => {
const result = parseFilterValue("US");
expect(result).toEqual({
operator: "IS",
- sqlOperator: "=",
+ sqlOperator: "IN",
values: ["US"],
});
});
@@ -18,7 +18,7 @@ describe("Advanced Filters - Unit Tests", () => {
const result = parseFilterValue("-US");
expect(result).toEqual({
operator: "IS_NOT",
- sqlOperator: "!=",
+ sqlOperator: "NOT IN",
values: ["US"],
});
});
@@ -90,7 +90,7 @@ describe("Advanced Filters - Unit Tests", () => {
const result = parseFilterValue(["US"]);
expect(result).toEqual({
operator: "IS",
- sqlOperator: "=",
+ sqlOperator: "IN",
values: ["US"],
});
});
@@ -110,7 +110,7 @@ describe("Advanced Filters - Unit Tests", () => {
test("rebuild single positive value", () => {
const result = buildFilterValue({
operator: "IS",
- sqlOperator: "=",
+ sqlOperator: "IN",
values: ["US"],
});
expect(result).toBe("US");
@@ -128,7 +128,7 @@ describe("Advanced Filters - Unit Tests", () => {
test("rebuild single negative value", () => {
const result = buildFilterValue({
operator: "IS_NOT",
- sqlOperator: "!=",
+ sqlOperator: "NOT IN",
values: ["US"],
});
expect(result).toBe("-US");
@@ -175,18 +175,18 @@ describe("Advanced Filters - Unit Tests", () => {
});
describe("buildAdvancedFilters", () => {
- test("single field with equals operator", () => {
+ test("single field with IN operator (single value)", () => {
const result = buildAdvancedFilters({
country: {
operator: "IS",
- sqlOperator: "=",
+ sqlOperator: "IN",
values: ["US"],
},
});
expect(result).toEqual([
{
field: "country",
- operator: "=",
+ operator: "IN",
values: ["US"],
},
]);
@@ -235,7 +235,7 @@ describe("Advanced Filters - Unit Tests", () => {
},
device: {
operator: "IS",
- sqlOperator: "=",
+ sqlOperator: "IN",
values: ["Desktop"],
},
});
@@ -247,7 +247,7 @@ describe("Advanced Filters - Unit Tests", () => {
});
expect(result).toContainEqual({
field: "device",
- operator: "=",
+ operator: "IN",
values: ["Desktop"],
});
});
@@ -261,7 +261,7 @@ describe("Advanced Filters - Unit Tests", () => {
const result = buildAdvancedFilters({
country: {
operator: "IS",
- sqlOperator: "=",
+ sqlOperator: "IN",
values: ["US"],
},
city: undefined,
@@ -273,11 +273,11 @@ describe("Advanced Filters - Unit Tests", () => {
test("handles all supported fields", () => {
const result = buildAdvancedFilters({
- country: { operator: "IS", sqlOperator: "=", values: ["US"] },
- city: { operator: "IS", sqlOperator: "=", values: ["NYC"] },
- device: { operator: "IS", sqlOperator: "=", values: ["Mobile"] },
- browser: { operator: "IS", sqlOperator: "=", values: ["Chrome"] },
- os: { operator: "IS", sqlOperator: "=", values: ["Mac"] },
+ country: { operator: "IS", sqlOperator: "IN", values: ["US"] },
+ city: { operator: "IS", sqlOperator: "IN", values: ["NYC"] },
+ device: { operator: "IS", sqlOperator: "IN", values: ["Mobile"] },
+ browser: { operator: "IS", sqlOperator: "IN", values: ["Chrome"] },
+ os: { operator: "IS", sqlOperator: "IN", values: ["Mac"] },
});
expect(result).toHaveLength(5);
expect(result.map((f) => f.field)).toEqual([
@@ -291,9 +291,9 @@ describe("Advanced Filters - Unit Tests", () => {
test("maintains insertion order", () => {
const result = buildAdvancedFilters({
- device: { operator: "IS", sqlOperator: "=", values: ["Mobile"] },
- country: { operator: "IS", sqlOperator: "=", values: ["US"] },
- browser: { operator: "IS", sqlOperator: "=", values: ["Chrome"] },
+ device: { operator: "IS", sqlOperator: "IN", values: ["Mobile"] },
+ country: { operator: "IS", sqlOperator: "IN", values: ["US"] },
+ browser: { operator: "IS", sqlOperator: "IN", values: ["Chrome"] },
});
// Should maintain order from SUPPORTED_FIELDS, not insertion order
expect(result[0].field).toBe("country");
diff --git a/apps/web/tests/analytics/normalize-filter.test.ts b/apps/web/tests/analytics/normalize-filter.test.ts
new file mode 100644
index 0000000000..408b5ffeee
--- /dev/null
+++ b/apps/web/tests/analytics/normalize-filter.test.ts
@@ -0,0 +1,200 @@
+import { normalizeActiveFilter } from "@dub/ui";
+import { describe, expect, test } from "vitest";
+
+describe("normalizeActiveFilter", () => {
+ describe("New format (already normalized)", () => {
+ test("returns unchanged if already has operator and values array", () => {
+ const input = {
+ key: "country",
+ operator: "IS_ONE_OF" as const,
+ values: ["US", "BR"],
+ };
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual(input);
+ });
+
+ test("handles IS_NOT operator", () => {
+ const input = {
+ key: "device",
+ operator: "IS_NOT" as const,
+ values: ["Mobile"],
+ };
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual(input);
+ });
+
+ test("handles IS_NOT_ONE_OF operator", () => {
+ const input = {
+ key: "country",
+ operator: "IS_NOT_ONE_OF" as const,
+ values: ["US", "BR", "FR"],
+ };
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual(input);
+ });
+ });
+
+ describe("Legacy singular format { key, value }", () => {
+ test("converts single value to IS operator with values array", () => {
+ const input = {
+ key: "country",
+ value: "US",
+ };
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual({
+ key: "country",
+ operator: "IS",
+ values: ["US"],
+ });
+ });
+
+ test("handles string values", () => {
+ const input = {
+ key: "domain",
+ value: "dub.sh",
+ };
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual({
+ key: "domain",
+ operator: "IS",
+ values: ["dub.sh"],
+ });
+ });
+
+ test("handles non-string values", () => {
+ const input = {
+ key: "userId",
+ value: 123,
+ };
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual({
+ key: "userId",
+ operator: "IS",
+ values: [123],
+ });
+ });
+ });
+
+ describe("Legacy plural format { key, values }", () => {
+ test("single value becomes IS operator", () => {
+ const input = {
+ key: "tagIds",
+ values: ["tag_123"],
+ };
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual({
+ key: "tagIds",
+ operator: "IS",
+ values: ["tag_123"],
+ });
+ });
+
+ test("multiple values becomes IS_ONE_OF operator", () => {
+ const input = {
+ key: "tagIds",
+ values: ["tag_123", "tag_456", "tag_789"],
+ };
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual({
+ key: "tagIds",
+ operator: "IS_ONE_OF",
+ values: ["tag_123", "tag_456", "tag_789"],
+ });
+ });
+
+ test("two values becomes IS_ONE_OF operator", () => {
+ const input = {
+ key: "country",
+ values: ["US", "BR"],
+ };
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual({
+ key: "country",
+ operator: "IS_ONE_OF",
+ values: ["US", "BR"],
+ });
+ });
+
+ test("empty values array becomes IS with empty array", () => {
+ const input = {
+ key: "tagIds",
+ values: [],
+ };
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual({
+ key: "tagIds",
+ operator: "IS",
+ values: [],
+ });
+ });
+ });
+
+ describe("Edge cases", () => {
+ test("handles filter without operator or values", () => {
+ const input = {
+ key: "country",
+ } as any;
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual({
+ key: "country",
+ operator: "IS",
+ values: [],
+ });
+ });
+
+ test("preserves other properties not in the spec", () => {
+ const input = {
+ key: "country",
+ value: "US",
+ // @ts-expect-error - testing extra properties
+ extraProp: "should be ignored",
+ };
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual({
+ key: "country",
+ operator: "IS",
+ values: ["US"],
+ });
+ // Extra properties are not preserved
+ expect(result).not.toHaveProperty("extraProp");
+ });
+ });
+
+ describe("Real-world scenarios", () => {
+ test("Links page tags filter (multiple: true, hideOperator: true)", () => {
+ const input = {
+ key: "tagIds",
+ values: ["tag_abc", "tag_def"],
+ };
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual({
+ key: "tagIds",
+ operator: "IS_ONE_OF",
+ values: ["tag_abc", "tag_def"],
+ });
+ });
+
+ test("Analytics page with advanced filters", () => {
+ const input = {
+ key: "country",
+ operator: "IS_NOT_ONE_OF" as const,
+ values: ["US", "GB"],
+ };
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual(input);
+ });
+
+ test("Single domain filter (legacy format)", () => {
+ const input = {
+ key: "domain",
+ value: "dub.sh",
+ };
+ const result = normalizeActiveFilter(input);
+ expect(result).toEqual({
+ key: "domain",
+ operator: "IS",
+ values: ["dub.sh"],
+ });
+ });
+ });
+});