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.

finalize schema changes, add deprecated fields

Steven Tey37673367636f
diff --git a/apps/web/lib/analytics/get-events.ts b/apps/web/lib/analytics/get-events.ts
index eb6abf65f1..ff9f14536b 100644
--- a/apps/web/lib/analytics/get-events.ts
+++ b/apps/web/lib/analytics/get-events.ts
@@ -1,10 +1,13 @@
import { prisma } from "@/lib/prisma";
import { tb } from "@/lib/tinybird";
import { Link } from "@prisma/client";
+import { transformLink } from "../api/links";
import { tbDemo } from "../tinybird/demo-client";
+import { clickEventSchema } from "../webhook/schemas";
import {
transformClickEventData,
transformLeadEventData,
+ transformLinkEventData,
transformSaleEventData,
} from "../webhook/transform";
import { eventsFilterTB } from "../zod/schemas/analytics";
@@ -14,15 +17,9 @@ import { saleEventEnrichedSchema } from "../zod/schemas/sales";
import { INTERVAL_DATA } from "./constants";
import { EventsFilters } from "./types";
-// Promise<
-// | z.infer<typeof clickEventEnrichedSchema>[]
-// | z.infer<typeof leadEventEnrichedSchema>[]
-// | z.infer<typeof saleEventEnrichedSchema>[]
-// >
-
// Fetch data for /api/events
export const getEvents = async (params: EventsFilters) => {
- let { event, workspaceId, interval, start, end, isDemo } = params;
+ let { event: eventType, workspaceId, interval, start, end, isDemo } = params;
if (start) {
start = new Date(start);
@@ -46,29 +43,24 @@ export const getEvents = async (params: EventsFilters) => {
clicks: clickEventEnrichedSchema,
leads: leadEventEnrichedSchema,
sales: saleEventEnrichedSchema,
- }[event] ?? clickEventEnrichedSchema,
+ }[eventType] ?? clickEventEnrichedSchema,
});
const response = await pipe({
...params,
- eventType: event,
+ eventType,
workspaceId,
offset: params.page * params.limit,
start: start.toISOString().replace("T", " ").replace("Z", ""),
end: end.toISOString().replace("T", " ").replace("Z", ""),
});
- const linkIds = response.data.map((d) => d.link_id);
-
const links = await prisma.link.findMany({
where: {
id: {
- in: linkIds,
+ in: response.data.map((d) => d.link_id),
},
},
- include: {
- tags: true,
- },
});
const linksMap = links.reduce(
@@ -86,75 +78,50 @@ export const getEvents = async (params: EventsFilters) => {
return null;
}
- return {
+ const eventData = {
...event,
- link,
+ // timestamp is always in UTC
+ timestamp: new Date(event.timestamp + "Z"),
+ click: clickEventSchema.parse({
+ ...event,
+ id: event.click_id,
+ }),
+ link: transformLinkEventData(transformLink(link)),
+ ...(eventType === "leads" || eventType === "sales"
+ ? {
+ customer: {
+ id: event.customer_id,
+ name: event.customer_name,
+ email: event.customer_email,
+ avatar:
+ event.customer_avatar ||
+ `https://api.dicebear.com/7.x/micah/svg?seed=${event.customer_id}`,
+ },
+ ...(eventType === "sales"
+ ? {
+ sale: {
+ amount: event.saleAmount,
+ invoiceId: event.invoice_id,
+ paymentProcessor: event.payment_processor,
+ metadata: event.metadata,
+ },
+ }
+ : {}),
+ }
+ : {}),
};
- })
- .filter((d) => d !== null);
-
- console.log({ events: JSON.stringify(events, null, 2) });
-
- // Click events
- if (event === "clicks") {
- return events.map((d) =>
- transformClickEventData({
- ...d,
- link: linksMap[d.link_id],
- bot: d.bot === 1,
- qr: d.qr === 1,
- }),
- );
- }
- // Lead events
- if (event === "leads") {
- return response.data.map((d) =>
- transformLeadEventData({
- ...d,
- bot: d.bot === 1,
- qr: d.qr === 1,
- link: linksMap[d.link_id],
- customerId: "d.customer_id", // TODO: fix it,
- customerName: d.customer_name,
- customerEmail: d.customer_email,
- customerAvatar: d.customer_avatar,
- }),
- );
- }
+ if (event === "clicks") {
+ return transformClickEventData(eventData);
+ } else if (event === "leads") {
+ return transformLeadEventData(eventData);
+ } else if (event === "sales") {
+ return transformSaleEventData(eventData);
+ }
- // Sale events
- if (event === "sales") {
- return response.data.map((d) =>
- transformSaleEventData({
- ...d,
- bot: d.bot === 1,
- qr: d.qr === 1,
- link: linksMap[d.link_id],
- customerId: "d.customer_id",
- customerName: d.customer_name,
- customerEmail: d.customer_email,
- customerAvatar: d.customer_avatar,
- }),
- );
- }
+ return eventData;
+ })
+ .filter((d) => d !== null);
- return response.data.map((d) => ({
- ...d,
- // timestamp is always in UTC
- timestamp: new Date(d.timestamp + "Z"),
- link: {
- id: d.link_id,
- domain: d.domain,
- key: d.key,
- url: d.url,
- },
- customer: {
- name: d.customer_name,
- email: d.customer_email,
- avatar:
- d.customer_avatar ||
- `https://api.dicebear.com/7.x/micah/svg?seed=${d.customer_id}`,
- },
- }));
+ return events;
};
diff --git a/apps/web/lib/openapi/events/index.ts b/apps/web/lib/openapi/events/index.ts
index c5263d230e..4d18e5a770 100644
--- a/apps/web/lib/openapi/events/index.ts
+++ b/apps/web/lib/openapi/events/index.ts
@@ -1,9 +1,9 @@
import { openApiErrorResponses } from "@/lib/openapi/responses";
import z from "@/lib/zod";
import { eventsQuerySchema } from "@/lib/zod/schemas/analytics";
-import { clickEventEnrichedSchema } from "@/lib/zod/schemas/clicks";
-import { leadEventEnrichedSchema } from "@/lib/zod/schemas/leads";
-import { saleEventEnrichedSchema } from "@/lib/zod/schemas/sales";
+import { clickEventResponseSchema } from "@/lib/zod/schemas/clicks";
+import { leadEventResponseSchema } from "@/lib/zod/schemas/leads";
+import { saleEventResponseSchema } from "@/lib/zod/schemas/sales";
import { ZodOpenApiOperationObject, ZodOpenApiPathsObject } from "zod-openapi";
export const listEvents: ZodOpenApiOperationObject = {
@@ -21,9 +21,9 @@ export const listEvents: ZodOpenApiOperationObject = {
content: {
"application/json": {
schema: z.union([
- z.array(clickEventEnrichedSchema).openapi({ title: "ClickEvents" }),
- z.array(leadEventEnrichedSchema).openapi({ title: "LeadEvents" }),
- z.array(saleEventEnrichedSchema).openapi({ title: "SaleEvents" }),
+ z.array(clickEventResponseSchema).openapi({ title: "ClickEvents" }),
+ z.array(leadEventResponseSchema).openapi({ title: "LeadEvents" }),
+ z.array(saleEventResponseSchema).openapi({ title: "SaleEvents" }),
]),
},
},
diff --git a/apps/web/lib/webhook/schemas.ts b/apps/web/lib/webhook/schemas.ts
index 58e3bdad57..6db6903e63 100644
--- a/apps/web/lib/webhook/schemas.ts
+++ b/apps/web/lib/webhook/schemas.ts
@@ -1,5 +1,6 @@
import z from "@/lib/zod";
import { LinkSchema } from "../zod/schemas/links";
+import { parseUrlSchemaAllowEmpty } from "../zod/schemas/utils";
import { WEBHOOK_TRIGGERS } from "./constants";
const customerSchema = z.object({
@@ -17,14 +18,31 @@ const saleSchema = z.object({
});
export const linkEventSchema = LinkSchema.omit({
+ url: true,
tags: true,
tagId: true,
projectId: true,
-});
+ // boolean fields
+ archived: true,
+ doIndex: true,
+ proxy: true,
+ publicStats: true,
+ rewrite: true,
+ trackConversion: true,
+}).merge(
+ z.object({
+ url: parseUrlSchemaAllowEmpty,
+ archived: z.coerce.boolean(),
+ doIndex: z.coerce.boolean(),
+ proxy: z.coerce.boolean(),
+ publicStats: z.coerce.boolean(),
+ rewrite: z.coerce.boolean(),
+ trackConversion: z.coerce.boolean(),
+ }),
+);
export const clickEventSchema = z.object({
- timestamp: z.string(),
- clickId: z.string(),
+ id: z.string(),
url: z.string(),
ip: z.string(),
continent: z.string(),
@@ -33,21 +51,15 @@ export const clickEventSchema = z.object({
device: z.string(),
browser: z.string(),
os: z.string(),
- ua: z.string(),
- bot: z.boolean(),
- qr: z.boolean(),
+ bot: z.coerce.boolean(),
+ qr: z.coerce.boolean(),
referer: z.string(),
- link: linkEventSchema,
});
export const leadEventSchema = z.object({
eventName: z.string(),
customer: customerSchema,
- click: z
- .object({
- id: z.string(),
- })
- .and(clickEventSchema.omit({ link: true, timestamp: true, clickId: true })),
+ click: clickEventSchema,
link: linkEventSchema,
});
@@ -55,11 +67,7 @@ export const saleEventSchema = z.object({
eventName: z.string(),
customer: customerSchema,
sale: saleSchema,
- click: z
- .object({
- id: z.string(),
- })
- .and(clickEventSchema.omit({ link: true, timestamp: true, clickId: true })),
+ click: clickEventSchema,
link: linkEventSchema,
});
diff --git a/apps/web/lib/webhook/transform.ts b/apps/web/lib/webhook/transform.ts
index 49f6a9a1e1..ae74d5eee5 100644
--- a/apps/web/lib/webhook/transform.ts
+++ b/apps/web/lib/webhook/transform.ts
@@ -1,11 +1,10 @@
-import { webhookPayloadSchema } from "@/lib/webhook/schemas";
+import { linkEventSchema, webhookPayloadSchema } from "@/lib/webhook/schemas";
import { nanoid, toCamelCase } from "@dub/utils";
import type { Link, Webhook } from "@prisma/client";
import { LinkWithTags, transformLink } from "../api/links/utils/transform-link";
import { WebhookTrigger } from "../types";
import z from "../zod";
import { clickEventSchemaTB } from "../zod/schemas/clicks";
-import { LinkSchema } from "../zod/schemas/links";
import { WEBHOOK_EVENT_ID_PREFIX } from "./constants";
import { clickEventSchema, leadEventSchema, saleEventSchema } from "./schemas";
@@ -28,7 +27,7 @@ export const transformWebhook = (webhook: TransformWebhookProps) => {
// Note utm_* properties are not converted to camelCase
export const transformLinkEventData = (data: Link) => {
- return LinkSchema.parse({
+ return linkEventSchema.parse({
...data,
expiresAt: data.expiresAt?.toISOString() || null,
lastClicked: data.lastClicked?.toISOString() || null,
@@ -46,22 +45,16 @@ export const transformClickEventData = (
Object.entries(data).map(([key, value]) => [toCamelCase(key), value]),
);
- // TODO: This is a bit flaky – e.g. if we add another boolean field to link schema
- // this will still break. We should make it more robust.
- const link = {
- ...transformLink(data.link),
- archived: data.link.archived === 1,
- doIndex: data.link.doIndex === 1,
- proxy: data.link.proxy === 1,
- publicStats: data.link.publicStats === 1,
- rewrite: data.link.rewrite === 1,
- trackConversion: data.link.trackConversion === 1,
- };
-
- return clickEventSchema.parse({
- ...click,
- link,
- });
+ return clickEventSchema
+ .omit({ id: true })
+ .merge(
+ z.object({
+ timestamp: z.string(),
+ clickId: z.string(),
+ link: linkEventSchema,
+ }),
+ )
+ .parse(click);
};
export const transformLeadEventData = (data: any) => {
diff --git a/apps/web/lib/zod/schemas/clicks.ts b/apps/web/lib/zod/schemas/clicks.ts
index 50b2047496..c7e2ac279f 100644
--- a/apps/web/lib/zod/schemas/clicks.ts
+++ b/apps/web/lib/zod/schemas/clicks.ts
@@ -1,4 +1,5 @@
import z from "@/lib/zod";
+import { LinkSchema } from "./links";
export const clickEventSchemaTB = z.object({
timestamp: z.string(),
@@ -49,3 +50,17 @@ export const clickEventEnrichedSchema = z
qr: z.number().nullable(),
})
.openapi({ ref: "ClickEvent" });
+
+export const clickEventResponseSchema = clickEventEnrichedSchema
+ .omit({
+ link_id: true,
+ })
+ .merge(
+ z.object({
+ link: LinkSchema,
+ link_id: z
+ .string()
+ .describe("Deprecated. Use `link.id` instead.")
+ .openapi({ deprecated: true }),
+ }),
+ );
diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.ts
index 5538e6f0b7..e062009924 100644
--- a/apps/web/lib/zod/schemas/customers.ts
+++ b/apps/web/lib/zod/schemas/customers.ts
@@ -51,3 +51,10 @@ export const customersMetadataSchema = z.object({
avatar: z.string().default(""),
deleted: z.number().default(0),
});
+
+// simple schema returned by /events API
+export const customerSchema = z.object({
+ name: z.string(),
+ email: z.string(),
+ avatar: z.string(),
+});
diff --git a/apps/web/lib/zod/schemas/leads.ts b/apps/web/lib/zod/schemas/leads.ts
index 57b552d641..8b1b27b234 100644
--- a/apps/web/lib/zod/schemas/leads.ts
+++ b/apps/web/lib/zod/schemas/leads.ts
@@ -1,5 +1,8 @@
+import { clickEventSchema } from "@/lib/webhook/schemas";
import z from "@/lib/zod";
import { clickEventSchemaTB } from "./clicks";
+import { customerSchema } from "./customers";
+import { LinkSchema } from "./links";
export const trackLeadRequestSchema = z.object({
// Required
@@ -101,3 +104,41 @@ export const leadEventEnrichedSchema = z
ip: z.string().nullable(),
})
.openapi({ ref: "LeadEvent" });
+
+export const leadEventResponseSchema = leadEventEnrichedSchema
+ .omit({
+ link_id: true,
+ click_id: true,
+ customer_name: true,
+ customer_email: true,
+ customer_avatar: true,
+ })
+ .merge(
+ z.object({
+ // deprecated fields
+ link_id: z
+ .string()
+ .describe("Deprecated. Use `link.id` instead.")
+ .openapi({ deprecated: true }),
+ click_id: z
+ .string()
+ .describe("Deprecated. Use `click.id` instead.")
+ .openapi({ deprecated: true }),
+ customer_name: z
+ .string()
+ .describe("Deprecated. Use `customer.name` instead.")
+ .openapi({ deprecated: true }),
+ customer_email: z
+ .string()
+ .describe("Deprecated. Use `customer.email` instead.")
+ .openapi({ deprecated: true }),
+ customer_avatar: z
+ .string()
+ .describe("Deprecated. Use `customer.avatar` instead.")
+ .openapi({ deprecated: true }),
+ // nested objects
+ link: LinkSchema,
+ click: clickEventSchema,
+ customer: customerSchema,
+ }),
+ );
diff --git a/apps/web/lib/zod/schemas/sales.ts b/apps/web/lib/zod/schemas/sales.ts
index fc4ec83187..4d1f01cd89 100644
--- a/apps/web/lib/zod/schemas/sales.ts
+++ b/apps/web/lib/zod/schemas/sales.ts
@@ -1,5 +1,8 @@
+import { clickEventSchema } from "@/lib/webhook/schemas";
import z from "@/lib/zod";
import { clickEventSchemaTB } from "./clicks";
+import { customerSchema } from "./customers";
+import { LinkSchema } from "./links";
export const trackSaleRequestSchema = z.object({
// Required
@@ -107,3 +110,60 @@ export const saleEventEnrichedSchema = z
ip: z.string().nullable(),
})
.openapi({ ref: "SaleEvent" });
+
+export const saleEventResponseSchema = saleEventEnrichedSchema
+ .omit({
+ click_id: true,
+ link_id: true,
+ customer_name: true,
+ customer_email: true,
+ customer_avatar: true,
+ saleAmount: true,
+ invoice_id: true,
+ payment_processor: true,
+ })
+ .merge(
+ z.object({
+ // deprecated fields
+ link_id: z
+ .string()
+ .describe("Deprecated. Use `link.id` instead.")
+ .openapi({ deprecated: true }),
+ click_id: z
+ .string()
+ .describe("Deprecated. Use `click.id` instead.")
+ .openapi({ deprecated: true }),
+ customer_name: z
+ .string()
+ .describe("Deprecated. Use `customer.name` instead.")
+ .openapi({ deprecated: true }),
+ customer_email: z
+ .string()
+ .describe("Deprecated. Use `customer.email` instead.")
+ .openapi({ deprecated: true }),
+ customer_avatar: z
+ .string()
+ .describe("Deprecated. Use `customer.avatar` instead.")
+ .openapi({ deprecated: true }),
+ saleAmount: z
+ .number()
+ .describe("Deprecated. Use `sale.amount` instead.")
+ .openapi({ deprecated: true }),
+ invoice_id: z
+ .string()
+ .describe("Deprecated. Use `sale.invoiceId` instead.")
+ .openapi({ deprecated: true }),
+ payment_processor: z
+ .string()
+ .describe("Deprecated. Use `sale.paymentProcessor` instead."),
+ // nested objects
+ link: LinkSchema,
+ click: clickEventSchema,
+ customer: customerSchema,
+ sale: trackSaleRequestSchema.pick({
+ amount: true,
+ invoiceId: true,
+ paymentProcessor: true,
+ }),
+ }),
+ );
diff --git a/apps/web/ui/analytics/events/events-table.tsx b/apps/web/ui/analytics/events/events-table.tsx
index 895d2676c0..07f7648a09 100644
--- a/apps/web/ui/analytics/events/events-table.tsx
+++ b/apps/web/ui/analytics/events/events-table.tsx
@@ -187,12 +187,13 @@ export default function EventsTable() {
header: "Customer",
accessorKey: "customer",
cell: ({ getValue }) => {
- const display = getValue().name || getValue().email || "Unknown";
+ const customer = getValue();
+ const display = customer.name || customer.email || "Unknown";
return (
<div className="flex items-center gap-3" title={display}>
<img
alt={display}
- src={getValue().avatar}
+ src={customer.avatar}
className="size-4 shrink-0 rounded-full border border-gray-200"
/>
<span className="truncate">{display}</span>
@@ -353,12 +354,12 @@ export default function EventsTable() {
{
id: "saleAmount",
header: "Sale Amount",
- accessorKey: "saleAmount",
+ accessorKey: "sale",
enableHiding: false,
minSize: 120,
cell: ({ getValue }) => (
<div className="flex items-center gap-2">
- <span>${nFormatter(getValue() / 100)}</span>
+ <span>${nFormatter(getValue().amount / 100)}</span>
<span className="text-gray-400">USD</span>
</div>
),