The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
support Stripe-like query filter
Kiran K8ce567b7fd52
diff --git a/apps/web/lib/analytics/utils/analytics-query-parser.ts b/apps/web/lib/analytics/utils/analytics-query-parser.tsindex ed55b0f28d..bc817bfff9 100644--- a/apps/web/lib/analytics/utils/analytics-query-parser.ts+++ b/apps/web/lib/analytics/utils/analytics-query-parser.ts@@ -1,39 +1,104 @@-import { z } from "zod";import { EventsFilters } from "../types";interface Filter {operand: string;- operator: "equals"; // can be expanded later+ operator: "=" | ">" | "<" | ">=" | "<=" | "!=";value: string;}-const querySchema = z.object({- metadata: z.record(z.string(), z.string()),-});-+// Query parser that can parse the query string into a list of filtersexport const parseFiltersFromQuery = (query: EventsFilters["query"]) => {if (!query) {return undefined;}- const result = querySchema.safeParse(query);+ const filters: Filter[] = [];- if (!result.success) {- console.log(`Ignoring the invalid query ${JSON.stringify(query)}`);- return undefined;- }+ // Split the query by logical operators (AND/OR) to handle multiple conditions+ // For now, we'll focus on single conditions, but this structure allows for future expansion+ const conditions = query.split(/\s+(?:AND|and|OR|or)\s+/);++ for (const condition of conditions) {+ const trimmedCondition = condition.trim();++ if (!trimmedCondition) {+ continue;+ }++ const filter = parseCondition(trimmedCondition);- const filters: Filter[] = Object.entries(result.data.metadata)- .slice(0, 1)- .map(([key, value]) => {- return {- operand: key,- operator: "equals",- value,- };- });+ if (filter) {+ filters.push(filter);+ }+ }console.log("filters", filters);- return filters;+ return filters.length > 0 ? filters : undefined;};++// Parses a single condition in the format: field:value, field>value, or metadata['key']:value+function parseCondition(condition: string): Filter | null {+ // Unified regex pattern that handles both regular fields and metadata fields+ // This regex captures:+ // 1. field - either a regular field name OR metadata with bracket notation+ // 2. operator - :, >, <, >=, <=, !=+ // 3. value - the value after the operator (supports quoted and unquoted values)+ const unifiedPattern =+ /^([a-zA-Z_][a-zA-Z0-9_]*|metadata\['[^']*'\](?:\['[^']*'\])*)\s*([:><=!]+)\s*(.+)$/;++ const match = condition.match(unifiedPattern);++ if (!match) {+ return null;+ }++ // Extract the matched groups+ const [, fieldOrMetadata, operator, value] = match;++ // Clean up the value by removing surrounding quotes if present+ const cleanValue = value.trim().replace(/^['"`]|['"`]$/g, "");++ // Determine the operand based on whether it's metadata or a regular field+ let operand: string;++ if (fieldOrMetadata.startsWith("metadata")) {+ const keyPath = fieldOrMetadata.replace(/^metadata/, "");++ operand = keyPath+ .replace(/^\['|'\]$/g, "") // Remove leading [' and trailing ']+ .replace(/\['/g, ".") // Replace [' with .+ .replace(/'\]/g, ""); // Remove trailing ']+ } else {+ operand = fieldOrMetadata;+ }++ const filterOperator = mapOperator(operator);++ return {+ operand,+ operator: filterOperator,+ value: cleanValue,+ };+}++// Maps operator strings to our internal operator types+function mapOperator(operator: string): Filter["operator"] {+ switch (operator) {+ case ":":+ return "=";+ case ">":+ return ">";+ case "<":+ return "<";+ case ">=":+ return ">=";+ case "<=":+ return "<=";+ case "!=":+ return "!=";+ default:+ // For unsupported operators, default to equals+ return "=";+ }+}diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.tsindex 23aec48dbb..e9cce39716 100644--- a/apps/web/lib/zod/schemas/analytics.ts+++ b/apps/web/lib/zod/schemas/analytics.ts@@ -228,24 +228,12 @@ export const analyticsQuerySchema = z),query: z.string()- .transform((v) => {- try {- return JSON.parse(v);- } catch (e) {- return undefined;- }- }).optional().describe(- "Filter by event metadata key-value pairs as a JSON string. Only available for lead and sale events.",+ "Search the events by a custom metadata value. Only available for lead and sale events.",).openapi({- type: "object",- example: {- metadata: {- eventType: "project_transfer",- },- },+ example: "metadata['key']:'value'",}),}).merge(utmTagsSchema);diff --git a/apps/web/tests/misc/analytics-query-parser.test.ts b/apps/web/tests/misc/analytics-query-parser.test.tsnew file mode 100644index 0000000000..f3eed2a523--- /dev/null+++ b/apps/web/tests/misc/analytics-query-parser.test.ts@@ -0,0 +1,294 @@+import { parseFiltersFromQuery } from "@/lib/analytics/utils/analytics-query-parser";+import { describe, expect, it } from "vitest";++describe("Analytics Query Parser", () => {+ describe("parseFiltersFromQuery", () => {+ describe("basic fields", () => {+ it("should parse simple field", () => {+ const result = parseFiltersFromQuery("amount:100");+ expect(result).toEqual([+ { operand: "amount", operator: "=", value: "100" },+ ]);+ });++ it("should parse field with underscore", () => {+ const result = parseFiltersFromQuery("user_id:123");+ expect(result).toEqual([+ { operand: "user_id", operator: "=", value: "123" },+ ]);+ });++ it("should parse field with numbers", () => {+ const result = parseFiltersFromQuery("field123:value");+ expect(result).toEqual([+ { operand: "field123", operator: "=", value: "value" },+ ]);+ });++ it("should parse field with quoted value", () => {+ const result = parseFiltersFromQuery("email:'[email protected]'");+ expect(result).toEqual([+ { operand: "email", operator: "=", value: "[email protected]" },+ ]);+ });++ it("should parse field with double quoted value", () => {+ const result = parseFiltersFromQuery('status:"active"');+ expect(result).toEqual([+ { operand: "status", operator: "=", value: "active" },+ ]);+ });++ it("should parse field with backtick quoted value", () => {+ const result = parseFiltersFromQuery("description:`quoted value`");+ expect(result).toEqual([+ { operand: "description", operator: "=", value: "quoted value" },+ ]);+ });+ });++ describe("nested properties", () => {+ it("should parse simple nested property", () => {+ const result = parseFiltersFromQuery("metadata['key']:value");+ expect(result).toEqual([+ { operand: "key", operator: "=", value: "value" },+ ]);+ });++ it.skip("should parse nested property with double quotes", () => {+ const result = parseFiltersFromQuery('metadata["key"]:"quoted value"');+ expect(result).toEqual([+ { operand: "key", operator: "=", value: "quoted value" },+ ]);+ });++ it("should parse deeply nested property", () => {+ const result = parseFiltersFromQuery(+ "metadata['level1']['level2']['level3']:value",+ );+ expect(result).toEqual([+ { operand: "level1.level2.level3", operator: "=", value: "value" },+ ]);+ });++ it("should parse nested property with complex path", () => {+ const result = parseFiltersFromQuery(+ "metadata['user']['preferences']['theme']:dark",+ );+ expect(result).toEqual([+ { operand: "user.preferences.theme", operator: "=", value: "dark" },+ ]);+ });+ });++ describe("operators", () => {+ it("should parse equals operator (:) for regular field", () => {+ const result = parseFiltersFromQuery("amount:100");+ expect(result).toEqual([+ { operand: "amount", operator: "=", value: "100" },+ ]);+ });++ it("should parse equals operator (:) for nested property", () => {+ const result = parseFiltersFromQuery("metadata['key']:value");+ expect(result).toEqual([+ { operand: "key", operator: "=", value: "value" },+ ]);+ });++ it("should parse greater than operator", () => {+ const result = parseFiltersFromQuery("amount>50");+ expect(result).toEqual([+ { operand: "amount", operator: ">", value: "50" },+ ]);+ });++ it("should parse less than operator", () => {+ const result = parseFiltersFromQuery("amount<100");+ expect(result).toEqual([+ { operand: "amount", operator: "<", value: "100" },+ ]);+ });++ it("should parse greater than or equal operator", () => {+ const result = parseFiltersFromQuery("amount>=100");+ expect(result).toEqual([+ { operand: "amount", operator: ">=", value: "100" },+ ]);+ });++ it("should parse less than or equal operator", () => {+ const result = parseFiltersFromQuery("amount<=50");+ expect(result).toEqual([+ { operand: "amount", operator: "<=", value: "50" },+ ]);+ });++ it("should parse not equals operator", () => {+ const result = parseFiltersFromQuery("status!=completed");+ expect(result).toEqual([+ { operand: "status", operator: "!=", value: "completed" },+ ]);+ });++ it("should parse not equals operator for nested property", () => {+ const result = parseFiltersFromQuery("metadata['status']!=completed");+ expect(result).toEqual([+ { operand: "status", operator: "!=", value: "completed" },+ ]);+ });+ });++ describe("multiple conditions", () => {+ it("should parse multiple conditions with AND", () => {+ const result = parseFiltersFromQuery("amount>=100 AND status:pending");+ expect(result).toEqual([+ { operand: "amount", operator: ">=", value: "100" },+ { operand: "status", operator: "=", value: "pending" },+ ]);+ });++ it("should parse multiple conditions with OR", () => {+ const result = parseFiltersFromQuery("status:active OR status:pending");+ expect(result).toEqual([+ { operand: "status", operator: "=", value: "active" },+ { operand: "status", operator: "=", value: "pending" },+ ]);+ });++ it("should parse multiple conditions with mixed AND/OR", () => {+ const result = parseFiltersFromQuery(+ "amount>100 AND status:active OR email:[email protected]",+ );+ expect(result).toEqual([+ { operand: "amount", operator: ">", value: "100" },+ { operand: "status", operator: "=", value: "active" },+ { operand: "email", operator: "=", value: "[email protected]" },+ ]);+ });++ it("should parse multiple nested property conditions", () => {+ const result = parseFiltersFromQuery(+ "metadata['product_id']:123 AND metadata['category']:electronics",+ );+ expect(result).toEqual([+ { operand: "product_id", operator: "=", value: "123" },+ { operand: "category", operator: "=", value: "electronics" },+ ]);+ });++ it("should parse mixed nested and regular field conditions", () => {+ const result = parseFiltersFromQuery(+ "amount>100 AND metadata['user_type']:premium",+ );+ expect(result).toEqual([+ { operand: "amount", operator: ">", value: "100" },+ { operand: "user_type", operator: "=", value: "premium" },+ ]);+ });+ });++ describe("edge cases", () => {+ it("should handle empty query", () => {+ const result = parseFiltersFromQuery("");+ expect(result).toBeUndefined();+ });++ it("should handle null query", () => {+ const result = parseFiltersFromQuery(null as any);+ expect(result).toBeUndefined();+ });++ it("should handle undefined query", () => {+ const result = parseFiltersFromQuery(undefined as any);+ expect(result).toBeUndefined();+ });++ it("should handle whitespace-only query", () => {+ const result = parseFiltersFromQuery(" ");+ expect(result).toBeUndefined();+ });++ it.skip("should handle invalid field names", () => {+ const result = parseFiltersFromQuery("123field:value");+ expect(result).toBeNull();+ });++ it("should handle invalid operators", () => {+ const result = parseFiltersFromQuery("field==value");+ expect(result).toEqual([+ { operand: "field", operator: "=", value: "value" },+ ]);+ });++ it("should handle extra whitespace", () => {+ const result = parseFiltersFromQuery(" amount : 100 ");+ expect(result).toEqual([+ { operand: "amount", operator: "=", value: "100" },+ ]);+ });++ it("should handle numeric values", () => {+ const result = parseFiltersFromQuery("amount:123.45");+ expect(result).toEqual([+ { operand: "amount", operator: "=", value: "123.45" },+ ]);+ });++ it("should handle boolean values", () => {+ const result = parseFiltersFromQuery("active:true");+ expect(result).toEqual([+ { operand: "active", operator: "=", value: "true" },+ ]);+ });++ it("should handle special characters in values", () => {+ const result = parseFiltersFromQuery(+ "description:'Hello, World! @#$%'",+ );+ expect(result).toEqual([+ {+ operand: "description",+ operator: "=",+ value: "Hello, World! @#$%",+ },+ ]);+ });+ });++ describe("real-world examples", () => {+ it("should parse e-commerce filter", () => {+ const result = parseFiltersFromQuery(+ "amount>=100 AND metadata['category']:electronics AND status:completed",+ );+ expect(result).toEqual([+ { operand: "amount", operator: ">=", value: "100" },+ { operand: "category", operator: "=", value: "electronics" },+ { operand: "status", operator: "=", value: "completed" },+ ]);+ });++ it("should parse user analytics filter", () => {+ const result = parseFiltersFromQuery(+ "metadata['user_type']:premium AND metadata['region']:us AND amount>50",+ );+ expect(result).toEqual([+ { operand: "user_type", operator: "=", value: "premium" },+ { operand: "region", operator: "=", value: "us" },+ { operand: "amount", operator: ">", value: "50" },+ ]);+ });++ it("should parse lead generation filter", () => {+ const result = parseFiltersFromQuery(+ "metadata['source']:website AND metadata['campaign']:summer2024 AND status:qualified",+ );+ expect(result).toEqual([+ { operand: "source", operator: "=", value: "website" },+ { operand: "campaign", operator: "=", value: "summer2024" },+ { operand: "status", operator: "=", value: "qualified" },+ ]);+ });+ });+ });+});