The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add customer events pipe
Tim Wilson143c2cfc0c57
diff --git a/apps/web/app/api/customers/[id]/activity/route.ts b/apps/web/app/api/customers/[id]/activity/route.tsindex 247f3f6b0a..8b3a9c6e5f 100644--- a/apps/web/app/api/customers/[id]/activity/route.ts+++ b/apps/web/app/api/customers/[id]/activity/route.ts@@ -1,14 +1,11 @@-import { getEvents } from "@/lib/analytics/get-events";+import { getCustomerEvents } from "@/lib/analytics/get-customer-events";import { getCustomerOrThrow } from "@/lib/api/customers/get-customer-or-throw";import { transformCustomer } from "@/lib/api/customers/transform-customer";import { decodeLinkIfCaseSensitive } from "@/lib/api/links/case-sensitivity";import { withWorkspace } from "@/lib/auth";import { verifyFolderAccess } from "@/lib/folder/permissions";-import { CustomerActivity, LeadEvent, SaleEvent } from "@/lib/types";import { customerActivityResponseSchema } from "@/lib/zod/schemas/customers";import { prisma } from "@dub/prisma";-import { EventType } from "@dub/prisma/client";-import { currencyFormatter, getPrettyUrl } from "@dub/utils";import { NextResponse } from "next/server";// GET /api/customers/[id]/activity - get a customer's activity@@ -33,26 +30,14 @@ export const GET = withWorkspace(async ({ workspace, params, session }) => {);}- let [leadEvents, saleEvents, link] = await Promise.all([- getEvents({- customerId: customer.id,- event: "leads",- sortOrder: "desc",- sortBy: "timestamp",- interval: "1y",- page: 1,- limit: 50,- }),-- getEvents({- customerId: customer.id,- event: "sales",- sortOrder: "desc",- sortBy: "timestamp",- interval: "1y",- page: 1,- limit: 50,- }),+ let [events, link] = await Promise.all([+ getCustomerEvents(+ { customerId: customer.id, clickId: customer.clickId! },+ {+ sortOrder: "desc",+ interval: "1y",+ },+ ),prisma.link.findUniqueOrThrow({where: {@@ -77,49 +62,49 @@ export const GET = withWorkspace(async ({ workspace, params, session }) => {});}- const leadActivity = leadEvents.map((event: LeadEvent) => {- return {- timestamp: new Date(event.timestamp),- event: EventType.lead,- eventName: event.eventName,- metadata: null,- };- });-- const saleActivity = saleEvents.map((event: SaleEvent) => {- return {- timestamp: new Date(event.timestamp),- event: EventType.sale,- eventName: event.eventName,- eventDetails: currencyFormatter(event.sale.amount / 100, {- maximumFractionDigits: 2,- }),- metadata: {- amount: event.sale.amount,- paymentProcessor: event.sale.paymentProcessor,- },- };- });-- const activity: CustomerActivity[] = [...leadActivity, ...saleActivity].sort(- (a, b) => b.timestamp.getTime() - a.timestamp.getTime(),- );+ // const leadActivity = leadEvents.map((event: LeadEvent) => {+ // return {+ // timestamp: new Date(event.timestamp),+ // event: EventType.lead,+ // eventName: event.eventName,+ // metadata: null,+ // };+ // });++ // const saleActivity = saleEvents.map((event: SaleEvent) => {+ // return {+ // timestamp: new Date(event.timestamp),+ // event: EventType.sale,+ // eventName: event.eventName,+ // eventDetails: currencyFormatter(event.sale.amount / 100, {+ // maximumFractionDigits: 2,+ // }),+ // metadata: {+ // amount: event.sale.amount,+ // paymentProcessor: event.sale.paymentProcessor,+ // },+ // };+ // });++ // const activity: CustomerActivity[] = [...leadActivity, ...saleActivity].sort(+ // (a, b) => b.timestamp.getTime() - a.timestamp.getTime(),+ // );link = decodeLinkIfCaseSensitive(link);- // Add click event to activities- activity.push({- timestamp: customer.clickedAt!,- event: "click",- eventName: "Link click",- eventDetails: link?.shortLink ? getPrettyUrl(link.shortLink) : null,- metadata: null,- });+ // // Add click event to activities+ // activity.push({+ // timestamp: customer.clickedAt!,+ // event: "click",+ // eventName: "Link click",+ // eventDetails: link?.shortLink ? getPrettyUrl(link.shortLink) : null,+ // metadata: null,+ // });// Find the LTV of the customer- const ltv = activity.reduce((acc, { event, metadata }) => {- if (event === "sale" && metadata) {- acc += Number(metadata.amount);+ const ltv = events.reduce((acc, event) => {+ if (event.event === "sale" && event.saleAmount) {+ acc += Number(event.saleAmount);}return acc;@@ -132,7 +117,7 @@ export const GET = withWorkspace(async ({ workspace, params, session }) => {: null;// Find the time to first sale of the customer- const firstSale = activity.filter(({ event }) => event === "sale").pop();+ const firstSale = events.filter(({ event }) => event === "sale").pop();const timeToSale =firstSale && customer.createdAt@@ -145,7 +130,7 @@ export const GET = withWorkspace(async ({ workspace, params, session }) => {timeToLead,timeToSale,customer: transformCustomer(customer),- activity,+ events,link,}),);diff --git a/apps/web/app/api/customers/[id]/route.ts b/apps/web/app/api/customers/[id]/route.tsindex ef98e0c4ef..25a451a942 100644--- a/apps/web/app/api/customers/[id]/route.ts+++ b/apps/web/app/api/customers/[id]/route.ts@@ -4,22 +4,27 @@ import { transformCustomer } from "@/lib/api/customers/transform-customer";import { DubApiError } from "@/lib/api/errors";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";+import { getClickEvent } from "@/lib/tinybird";+import { clickEventSchema, clickEventSchemaTB } from "@/lib/zod/schemas/clicks";import {CustomerEnrichedSchema,CustomerSchema,+ getCustomerQuerySchema,getCustomersQuerySchema,updateCustomerBodySchema,} from "@/lib/zod/schemas/customers";import { prisma } from "@dub/prisma";+import { toCamelCase } from "@dub/utils";import { Discount } from "@prisma/client";import { NextResponse } from "next/server";+import { z } from "zod";// GET /api/customers/:id – Get a customer by IDexport const GET = withWorkspace(async ({ workspace, params, searchParams }) => {const { id } = params;- const { includeExpandedFields } =- getCustomersQuerySchema.parse(searchParams);+ const { includeExpandedFields, includeClickEvent } =+ getCustomerQuerySchema.parse(searchParams);const customer = await getCustomerOrThrow({@@ -31,6 +36,12 @@ export const GET = withWorkspace(},);+ let clickEvent: z.infer<typeof clickEventSchemaTB> | undefined = undefined;+ if (includeClickEvent && customer.clickId) {+ clickEvent = (await getClickEvent({ clickId: customer.clickId }))+ ?.data[0];+ }+let discount: Discount | null = null;if (includeExpandedFields) {@@ -53,17 +64,37 @@ export const GET = withWorkspace(});}- const responseSchema = includeExpandedFields- ? CustomerEnrichedSchema- : CustomerSchema;+ console.log({ clickEvent });+ const responseSchema = (+ includeExpandedFields ? CustomerEnrichedSchema : CustomerSchema+ ).extend(+ clickEvent+ ? {+ clickEvent: clickEventSchema.nullish(),+ }+ : {},+ );return NextResponse.json(- responseSchema.parse(- transformCustomer({+ responseSchema.parse({+ ...transformCustomer({...customer,...(includeExpandedFields ? { discount } : {}),}),- ),++ ...(clickEvent && {+ clickEvent: clickEventSchema.parse({+ ...Object.fromEntries(+ Object.entries(clickEvent).map(([key, value]) => [+ toCamelCase(key),+ value,+ ]),+ ),+ timestamp: new Date(clickEvent.timestamp),+ id: clickEvent.click_id,+ }),+ }),+ }),);},{diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/[customerId]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/[customerId]/page-client.tsxindex 8506ae6939..12d5bd67cb 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/[customerId]/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/[customerId]/page-client.tsx@@ -26,7 +26,11 @@ export function CustomerPageClient() {data: customer,isLoading,error,- } = useCustomer({ customerId, query: { includeExpandedFields: true } });+ } = useCustomer({+ customerId,+ query: { includeExpandedFields: true },+ includeClickEvent: true,+ });let { data: customerActivity, isLoading: isCustomerActivityLoading } =useSWR<CustomerActivityResponse>(@@ -71,7 +75,7 @@ export function CustomerPageClient() {)}</div></div>- <div className="mt-8 grid grid-cols-1 gap-16 md:grid-cols-[minmax(0,1fr)_240px]">+ <div className="mt-8 grid grid-cols-1 items-start gap-x-16 gap-y-10 lg:grid-cols-[minmax(0,1fr)_240px]">{/* Main content */}<div className="flex flex-col gap-10"><section className="flex flex-col gap-4">@@ -86,7 +90,7 @@ export function CustomerPageClient() {</div>{/* Right side details */}- <div className="flex flex-col gap-6 text-sm text-neutral-900">+ <div className="-order-1 grid grid-cols-2 gap-6 text-sm text-neutral-900 lg:order-1 lg:grid-cols-1">{customer.country && (<div className="flex flex-col gap-2"><DetailHeading>Details</DetailHeading>diff --git a/apps/web/lib/analytics/get-customer-events.ts b/apps/web/lib/analytics/get-customer-events.tsnew file mode 100644index 0000000000..6747343c2d--- /dev/null+++ b/apps/web/lib/analytics/get-customer-events.ts@@ -0,0 +1,150 @@+import { tb } from "@/lib/tinybird";+import { prisma } from "@dub/prisma";+import { Link } from "@dub/prisma/client";+import { DICEBEAR_AVATAR_URL } from "@dub/utils";+import { transformLink } from "../api/links";+import { decodeLinkIfCaseSensitive } from "../api/links/case-sensitivity";+import { generateRandomName } from "../names";+import z from "../zod";+import { clickEventSchema } from "../zod/schemas/clicks";+import { CustomerSchema } from "../zod/schemas/customers";+import { EventsFilters } from "./types";+import { getStartEndDates } from "./utils/get-start-end-dates";++export const getCustomerEvents = async (+ { customerId, clickId }: { customerId: string; clickId: string },+ params: Pick<+ EventsFilters,+ "sortOrder" | "start" | "end" | "dataAvailableFrom" | "interval"+ >,+) => {+ let { sortOrder, start, end, dataAvailableFrom, interval } = params;++ const { startDate, endDate } = getStartEndDates({+ interval,+ start,+ end,+ dataAvailableFrom,+ });++ const pipe = tb.buildPipe({+ pipe: "v2_customer_events",+ parameters: z.any(), // TODO+ data: z.any(), // TODO+ });++ const response = await pipe({+ ...params,+ customerId,+ clickId,+ order: sortOrder,+ start: startDate.toISOString().replace("T", " ").replace("Z", ""),+ end: endDate.toISOString().replace("T", " ").replace("Z", ""),+ });++ const linksMap = await getLinksMap(response.data.map((d) => d.link_id));++ const events = response.data+ .map((evt) => {+ let link = linksMap[evt.link_id];+ if (!link) {+ return null;+ }++ link = decodeLinkIfCaseSensitive(link);++ const eventData = {+ ...evt,+ // use link domain & key from mysql instead of tinybird+ domain: link.domain,+ key: link.key,+ // timestamp is always in UTC+ timestamp: new Date(evt.timestamp + "Z"),+ click: clickEventSchema.parse({+ ...evt,+ id: evt.click_id,+ // normalize processed values+ region: evt.region_processed ?? "",+ refererUrl: evt.referer_url_processed ?? "",+ }),+ // transformLink -> add shortLink, qrCode, workspaceId, etc.+ link: transformLink(link, { skipDecodeKey: true }),+ ...(evt.event === "lead" || evt.event === "sale"+ ? {+ eventId: evt.event_id,+ eventName: evt.event_name,+ ...(evt.event === "sale"+ ? {+ sale: {+ amount: evt.saleAmount,+ invoiceId: evt.invoice_id,+ paymentProcessor: evt.payment_processor,+ },+ }+ : {}),+ }+ : {}),+ };++ // TODO+ // return z+ // .discriminatedUnion("event", [+ // clickEventResponseSchema,+ // leadEventResponseSchema,+ // saleEventResponseSchema,+ // ])+ // .parse(eventData);+ return eventData;+ })+ .filter((d) => d !== null);++ return events;+};++const getLinksMap = async (linkIds: string[]) => {+ const links = await prisma.link.findMany({+ where: {+ id: {+ in: linkIds,+ },+ },+ });++ return links.reduce(+ (acc, link) => {+ acc[link.id] = link;+ return acc;+ },+ {} as Record<string, Link>,+ );+};++const getCustomersMap = async (customerIds: string[]) => {+ if (customerIds.length === 0) {+ return {};+ }++ const customers = await prisma.customer.findMany({+ where: {+ id: {+ in: customerIds,+ },+ },+ });++ return customers.reduce(+ (acc, customer) => {+ acc[customer.id] = CustomerSchema.parse({+ id: customer.id,+ externalId: customer.externalId || "",+ name: customer.name || customer.email || generateRandomName(),+ email: customer.email || "",+ avatar: customer.avatar || `${DICEBEAR_AVATAR_URL}${customer.id}`,+ country: customer.country || "",+ createdAt: customer.createdAt,+ });+ return acc;+ },+ {} as Record<string, z.infer<typeof CustomerSchema>>,+ );+};diff --git a/apps/web/lib/swr/use-customer.ts b/apps/web/lib/swr/use-customer.tsindex 4162f6b322..2b1d9bb048 100644--- a/apps/web/lib/swr/use-customer.ts+++ b/apps/web/lib/swr/use-customer.ts@@ -2,6 +2,7 @@ import { fetcher } from "@dub/utils";import useSWR from "swr";import { z } from "zod";import { CustomerProps } from "../types";+import { clickEventSchema } from "../zod/schemas/clicks";import { getCustomersQuerySchema } from "../zod/schemas/customers";import useWorkspace from "./use-workspace";@@ -9,22 +10,29 @@ const partialQuerySchema = getCustomersQuerySchema.pick({includeExpandedFields: true,});-export default function useCustomer({+export default function useCustomer<IncludeClickEvent extends boolean = false>({customerId,query,enabled = true,+ includeClickEvent,}: {customerId: CustomerProps["id"];query?: z.infer<typeof partialQuerySchema>;enabled?: boolean;+ includeClickEvent?: IncludeClickEvent;}) {const { id: workspaceId } = useWorkspace();- const { data, error, isLoading } = useSWR<CustomerProps>(+ const { data, error, isLoading } = useSWR<+ IncludeClickEvent extends true+ ? CustomerProps & { clickEvent: z.infer<typeof clickEventSchema> }+ : CustomerProps+ >(enabled && workspaceId? `/api/customers/${customerId}?${new URLSearchParams({workspaceId: workspaceId,...query,+ includeClickEvent,} as Record<string, any>).toString()}`: undefined,fetcher,diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.tsindex 3830a7b978..7c1870e847 100644--- a/apps/web/lib/zod/schemas/customers.ts+++ b/apps/web/lib/zod/schemas/customers.ts@@ -24,6 +24,12 @@ export const getCustomersQuerySchema = z.object({),});+export const getCustomerQuerySchema = getCustomersQuerySchema.extend({+ includeClickEvent: booleanQuerySchema+ .optional()+ .describe("Whether to include the customer's click event."),+});+export const createCustomerBodySchema = z.object({email: z.string()@@ -113,7 +119,7 @@ export const customerActivityResponseSchema = z.object({ltv: z.number(),timeToLead: z.number().nullable(),timeToSale: z.number().nullable(),- activity: z.array(customerActivitySchema),+ events: z.array(z.any()),customer: CustomerSchema.merge(z.object({country: z.string().nullish(),diff --git a/packages/tinybird/pipes/v2_customer_events.pipe b/packages/tinybird/pipes/v2_customer_events.pipenew file mode 100644index 0000000000..97f4bb7e82--- /dev/null+++ b/packages/tinybird/pipes/v2_customer_events.pipe@@ -0,0 +1,131 @@+DESCRIPTION >+ Customer events+++TAGS "Dub Endpoints"++NODE click_events+SQL >++ %+ SELECT+ timestamp,+ click_id,+ link_id,+ url,+ continent,+ country,+ city,+ region,+ latitude,+ longitude,+ device,+ browser,+ os,+ engine,+ ua,+ referer,+ referer_url,+ qr,+ ip,+ CONCAT(country, '-', region) as region_processed,+ splitByString('?', referer_url)[1] as referer_url_processed,+ 'click' as event+ FROM dub_click_events_mv+ WHERE+ click_id = {{ clickId }}+ LIMIT {{ Int32(limit, 100) }}++++NODE lead_events+SQL >++ %+ SELECT+ timestamp,+ click_id,+ link_id,+ url,+ continent,+ country,+ city,+ region,+ latitude,+ longitude,+ device,+ browser,+ os,+ engine,+ ua,+ referer,+ referer_url,+ qr,+ ip,+ CONCAT(country, '-', region) as region_processed,+ splitByString('?', referer_url)[1] as referer_url_processed,+ 'lead' as event+ FROM dub_lead_events_mv+ WHERE+ customer_id = {{ String(customerId) }}+ AND timestamp >= {{ DateTime(start, '2024-06-01 00:00:00') }}+ AND timestamp < {{ DateTime(end, '2024-06-07 00:00:00') }}+ ORDER BY timestamp {% if order == 'asc' %} ASC {% else %} DESC {% end %}+ LIMIT {{ Int32(limit, 100) }}++++NODE sale_events+SQL >++ %+ SELECT+ timestamp,+ click_id,+ link_id,+ url,+ continent,+ country,+ city,+ region,+ latitude,+ longitude,+ device,+ browser,+ os,+ engine,+ ua,+ referer,+ referer_url,+ qr,+ ip,+ CONCAT(country, '-', region) as region_processed,+ splitByString('?', referer_url)[1] as referer_url_processed,+ 'sale' as event,+ amount as saleAmount+ FROM dub_sale_events_mv+ WHERE+ customer_id = {{ String(customerId) }}+ AND timestamp >= {{ DateTime(start, '2024-06-01 00:00:00') }}+ AND timestamp < {{ DateTime(end, '2024-06-07 00:00:00') }}+ LIMIT {{ Int32(limit, 100) }}++++NODE endpoint+SQL >++ %+ SELECT * FROM (+ SELECT *, NULL AS saleAmount+ FROM click_events+ UNION ALL+ SELECT *, NULL AS saleAmount+ FROM lead_events+ UNION ALL+ SELECT *+ FROM sale_events+ )+ ORDER BY timestamp {% if order == 'asc' %} ASC {% else %} DESC {% end %}++