The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Update pipe + types
Tim Wilsonb11d21a28a14
diff --git a/apps/web/app/api/customers/[id]/activity/route.ts b/apps/web/app/api/customers/[id]/activity/route.tsindex 0302dec5d1..64fdb7f565 100644--- a/apps/web/app/api/customers/[id]/activity/route.ts+++ b/apps/web/app/api/customers/[id]/activity/route.ts@@ -4,7 +4,7 @@ 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 { customerActivityResponseSchema } from "@/lib/zod/schemas/customers";+import { customerActivityResponseSchema } from "@/lib/zod/schemas/customer-activity";import { prisma } from "@dub/prisma";import { NextResponse } from "next/server";@@ -21,7 +21,7 @@ export const GET = withWorkspace(async ({ workspace, params, session }) => {return NextResponse.json(customerActivityResponseSchema.parse({customer,- activity: [],+ events: [],ltv: 0,timeToLead: null,timeToSale: null,@@ -62,46 +62,10 @@ 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(),- // );-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,- // });-// Find the LTV of the customer+ // TODO: Calculate this from all events, not limitedconst ltv = events.reduce((acc, event) => {if (event.event === "sale" && event.saleAmount) {acc += Number(event.saleAmount);@@ -117,6 +81,7 @@ export const GET = withWorkspace(async ({ workspace, params, session }) => {: null;// Find the time to first sale of the customer+ // TODO: Calculate this from all events, not limitedconst firstSale = events.filter(({ event }) => event === "sale").pop();const timeToSale =diff --git a/apps/web/lib/analytics/get-customer-events.ts b/apps/web/lib/analytics/get-customer-events.tsindex e1bca37871..d51641c5a0 100644--- a/apps/web/lib/analytics/get-customer-events.ts+++ b/apps/web/lib/analytics/get-customer-events.ts@@ -6,8 +6,13 @@ 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 {+ clickEventResponseSchema,+ clickEventSchema,+} from "../zod/schemas/clicks";import { CustomerSchema } from "../zod/schemas/customers";+import { leadEventResponseSchema } from "../zod/schemas/leads";+import { saleEventResponseSchema } from "../zod/schemas/sales";import { EventsFilters } from "./types";import { getStartEndDates } from "./utils/get-start-end-dates";@@ -86,15 +91,11 @@ export const getCustomerEvents = async (: {}),};- // TODO- // return z- // .discriminatedUnion("event", [- // clickEventResponseSchema,- // leadEventResponseSchema,- // saleEventResponseSchema,- // ])- // .parse(eventData);- return eventData;+ return {+ click: clickEventResponseSchema,+ lead: leadEventResponseSchema.omit({ customer: true }),+ sale: saleEventResponseSchema.omit({ customer: true }),+ }[evt.event].parse(eventData);}).filter((d) => d !== null);diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex 2907867521..c9c8bbf7d7 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -27,9 +27,8 @@ import {CommissionResponseSchema,CommissionSchema,} from "./zod/schemas/commissions";+import { customerActivityResponseSchema } from "./zod/schemas/customer-activity";import {- customerActivityResponseSchema,- customerActivitySchema,CustomerEnrichedSchema,CustomerSchema,} from "./zod/schemas/customers";@@ -425,8 +424,6 @@ export type SegmentIntegrationCredentials = {};export type InvoiceProps = z.infer<typeof InvoiceSchema>;-export type CustomerActivity = z.infer<typeof customerActivitySchema>;-export type CustomerActivityResponse = z.infer<typeof customerActivityResponseSchema>;diff --git a/apps/web/lib/zod/schemas/customer-activity.ts b/apps/web/lib/zod/schemas/customer-activity.tsnew file mode 100644index 0000000000..5a5500293a--- /dev/null+++ b/apps/web/lib/zod/schemas/customer-activity.ts@@ -0,0 +1,30 @@+import { z } from "zod";+import { clickEventResponseSchema } from "./clicks";+import { CustomerSchema } from "./customers";+import { leadEventResponseSchema } from "./leads";+import { LinkSchema } from "./links";+import { saleEventResponseSchema } from "./sales";++export const customerActivityEventSchema = z.discriminatedUnion("event", [+ clickEventResponseSchema,+ leadEventResponseSchema.omit({ customer: true }),+ saleEventResponseSchema.omit({ customer: true }),+]);++export const customerActivityResponseSchema = z.object({+ ltv: z.number(),+ timeToLead: z.number().nullable(),+ timeToSale: z.number().nullable(),+ events: z.array(customerActivityEventSchema),+ customer: CustomerSchema.merge(+ z.object({+ country: z.string().nullish(),+ }),+ ),+ link: LinkSchema.pick({+ id: true,+ domain: true,+ key: true,+ shortLink: true,+ }).nullish(),+});diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.tsindex d4b3252dd0..de1ee4ee65 100644--- a/apps/web/lib/zod/schemas/customers.ts+++ b/apps/web/lib/zod/schemas/customers.ts@@ -94,35 +94,3 @@ export const customersQuerySchema = z.describe("IDs of customers to filter by."),}).merge(getPaginationQuerySchema({ pageSize: CUSTOMERS_MAX_PAGE_SIZE }));--export const customerActivitySchema = z.object({- timestamp: z.date(),- event: z.enum(["click", "lead", "sale"]),- eventName: z.string(),- eventDetails: z.string().nullish(),- metadata: z.union([- z.null(),- z.object({- paymentProcessor: z.string(),- amount: z.number(),- }),- ]),-});--export const customerActivityResponseSchema = z.object({- ltv: z.number(),- timeToLead: z.number().nullable(),- timeToSale: z.number().nullable(),- events: z.array(z.any()),- customer: CustomerSchema.merge(- z.object({- country: z.string().nullish(),- }),- ),- link: LinkSchema.pick({- id: true,- domain: true,- key: true,- shortLink: true,- }).nullish(),-});diff --git a/packages/tinybird/pipes/v2_customer_events.pipe b/packages/tinybird/pipes/v2_customer_events.pipeindex 25cec50319..365cb44411 100644--- a/packages/tinybird/pipes/v2_customer_events.pipe+++ b/packages/tinybird/pipes/v2_customer_events.pipe@@ -65,6 +65,7 @@ SQL >CONCAT(country, '-', region) as region_processed,splitByString('?', referer_url)[1] as referer_url_processed,'lead' as event,+ event_id,event_nameFROM dub_lead_events_mvWHERE@@ -103,8 +104,11 @@ SQL >CONCAT(country, '-', region) as region_processed,splitByString('?', referer_url)[1] as referer_url_processed,'sale' as event,+ event_id,event_name,- amount as saleAmount+ amount as saleAmount,+ invoice_id,+ payment_processorFROM dub_sale_events_mvWHEREcustomer_id = {{ String(customerId) }}@@ -118,18 +122,26 @@ NODE endpointSQL >%- SELECT * FROM (- {% if defined(clickId) %}- SELECT *, NULL AS event_name, NULL AS saleAmount- FROM click_events- UNION ALL- {% end %}- SELECT *, NULL AS saleAmount- FROM lead_events- UNION ALLSELECT *- FROM sale_events- )+ FROM+ (+ {% if defined(clickId) %}+ SELECT+ *,+ NULL AS event_id,+ NULL AS event_name,+ NULL AS saleAmount,+ NULL AS invoice_id,+ NULL AS payment_processor+ FROM click_events+ UNION ALL+ {% end %}+ SELECT *, NULL AS saleAmount, NULL AS invoice_id, NULL AS payment_processor+ FROM lead_events+ UNION ALL+ SELECT *+ FROM sale_events+ )ORDER BY timestamp {% if order == 'asc' %} ASC {% else %} DESC {% end %}