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.

Add filter extraction and processing for event metadata in analytics

Kiran K2d5934a0e599
diff --git a/apps/web/lib/analytics/get-events.ts b/apps/web/lib/analytics/get-events.ts
index bca1c30aac..79803cfa49 100644
--- a/apps/web/lib/analytics/get-events.ts
+++ b/apps/web/lib/analytics/get-events.ts
@@ -24,6 +24,43 @@ import {
import { EventsFilters } from "./types";
import { getStartEndDates } from "./utils/get-start-end-dates";
+interface Filter {
+ operand: string;
+ operator: "equals"; // can be expanded later
+ value: string;
+}
+
+const extractFiltersFromQuery = (query: EventsFilters["query"]) => {
+ if (!query) {
+ return undefined;
+ }
+
+ const result = z
+ .object({
+ metadata: z.record(z.string(), z.string()),
+ })
+ .safeParse(query);
+
+ if (!result.success) {
+ console.log(`Ignoring the invalid query ${JSON.stringify(query)}`);
+ return undefined;
+ }
+
+ const filters: Filter[] = Object.entries(result.data.metadata)
+ .slice(0, 1)
+ .map(([key, value]) => {
+ return {
+ operand: key,
+ operator: "equals",
+ value,
+ };
+ });
+
+ console.log("filters", filters);
+
+ return filters;
+};
+
// Fetch data for /api/events
export const getEvents = async (params: EventsFilters) => {
let {
@@ -39,6 +76,7 @@ export const getEvents = async (params: EventsFilters) => {
order,
sortOrder,
dataAvailableFrom,
+ query,
} = params;
const { startDate, endDate } = getStartEndDates({
@@ -78,6 +116,8 @@ export const getEvents = async (params: EventsFilters) => {
}[eventType] ?? clickEventSchemaTBEndpoint,
});
+ const filters = extractFiltersFromQuery(query);
+
const response = await pipe({
...params,
eventType,
@@ -89,6 +129,7 @@ export const getEvents = async (params: EventsFilters) => {
offset: (params.page - 1) * params.limit,
start: startDate.toISOString().replace("T", " ").replace("Z", ""),
end: endDate.toISOString().replace("T", " ").replace("Z", ""),
+ filters: filters ? JSON.stringify(filters) : undefined,
});
const [linksMap, customersMap] = await Promise.all([
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index 4ec793fb6a..57bb1065be 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -226,13 +226,26 @@ export const analyticsQuerySchema = z
.describe(
"Filter for root domains. If true, filter for domains only. If false, filter for links only. If undefined, return both.",
),
- metadata: z
- .record(z.string(), z.string())
+ query: z
+ .string()
+ .transform((v) => {
+ try {
+ return JSON.parse(v);
+ } catch (e) {
+ return undefined;
+ }
+ })
.optional()
.describe(
"Filter by event metadata key-value pairs. Format: key=value. Only available for lead and sale events.",
)
- .openapi({ example: { product: "premium" } }),
+ .openapi({
+ example: {
+ metadata: {
+ eventType: "project_transfer",
+ },
+ },
+ }),
})
.merge(utmTagsSchema);
@@ -299,6 +312,7 @@ export const eventsFilterTB = analyticsFilterTB
limit: z.coerce.number().default(PAGINATION_LIMIT),
order: z.enum(["asc", "desc"]).default("desc"),
sortBy: z.enum(["timestamp"]).default("timestamp"),
+ filters: z.any()
}),
);
diff --git a/packages/tinybird/pipes/v2_events.pipe b/packages/tinybird/pipes/v2_events.pipe
index 6f7eebf092..9d5ea0d03e 100644
--- a/packages/tinybird/pipes/v2_events.pipe
+++ b/packages/tinybird/pipes/v2_events.pipe
@@ -133,6 +133,15 @@ SQL >
AND url LIKE concat('%utm_content=', encodeURLFormComponent({{ String(utm_content) }}), '%')
{% end %}
{% if defined(url) %} AND url = {{ url }} {% end %}
+
+ {% if defined(filters) %}
+ {% for item in JSON(filters, '[]') %}
+ {% if item.get('operator', '') == 'equals' %}
+ AND JSONExtractString(metadata, {{ item.get('operand', '') }}) = {{ item.get('value', '') }}
+ {% end %}
+ {% end %}
+ {% end %}
+
ORDER BY timestamp {% if order == 'asc' %} ASC {% else %} DESC {% end %}
LIMIT {{ Int32(limit, 100) }}
{% if defined(offset) %} OFFSET {{ Int32(offset, 0) }} {% end %}
@@ -174,6 +183,15 @@ SQL >
{% if defined(utm_term) %} AND url LIKE concat('%utm_term=', encodeURLFormComponent({{ String(utm_term) }}), '%') {% end %}
{% if defined(utm_content) %} AND url LIKE concat('%utm_content=', encodeURLFormComponent({{ String(utm_content) }}), '%') {% end %}
{% if defined(url) %} AND url = {{ url }} {% end %}
+
+ {% if defined(filters) %}
+ {% for item in JSON(filters, '[]') %}
+ {% if item.get('operator', '') == 'equals' %}
+ AND JSONExtractString(metadata, {{ item.get('operand', '') }}) = {{ item.get('value', '') }}
+ {% end %}
+ {% end %}
+ {% end %}
+
ORDER BY timestamp {% if order == 'asc' %} ASC {% else %} DESC {% end %}
LIMIT {{ Int32(limit, 100) }}
{% if defined(offset) %} OFFSET {{ Int32(offset, 0) }} {% end %}