The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Update customer page + add sortBy firstSaleAt/subscriptionCanceledAt (#3398)
Steven Teya8aeb02a7f50
diff --git a/apps/web/app/(ee)/api/customers/[id]/activity/route.ts b/apps/web/app/(ee)/api/customers/[id]/activity/route.tsindex 1a92a37ef5..c20e644ec9 100644--- a/apps/web/app/(ee)/api/customers/[id]/activity/route.ts+++ b/apps/web/app/(ee)/api/customers/[id]/activity/route.ts@@ -52,21 +52,16 @@ export const GET = withWorkspace(async ({ workspace, params }) => {? customer.createdAt.getTime() - customer.clickedAt.getTime(): null;- // Find the time to first sale of the customer- // TODO: Calculate this from all events, not limited- const firstSale = events.filter(({ event }) => event === "sale").pop();-const timeToSale =- firstSale && customer.createdAt- ? new Date(firstSale.timestamp).getTime() - customer.createdAt.getTime()+ customer.firstSaleAt && customer.createdAt+ ? customer.firstSaleAt.getTime() - customer.createdAt.getTime(): null;return NextResponse.json(customerActivityResponseSchema.parse({- ltv: customer.saleAmount,+ ...customer,timeToLead,timeToSale,- firstSaleDate: firstSale ? new Date(firstSale.timestamp) : null,events,link,}),diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page-client.tsxindex bf1a6de8af..852ee3c8b0 100644--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page-client.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/page-client.tsx@@ -278,7 +278,12 @@ export function ProgramCustomersPageClient() {onPaginationChange: setPagination,columnVisibility,onColumnVisibilityChange: setColumnVisibility,- sortableColumns: ["saleAmount", "createdAt"],+ sortableColumns: [+ "saleAmount",+ "createdAt",+ "firstSaleAt",+ "subscriptionCanceledAt",+ ],sortBy,sortOrder,onSortChange: ({ sortBy, sortOrder }) =>diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page-client.tsxindex 80a734e0e3..7b7755d310 100644--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page-client.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page-client.tsx@@ -30,7 +30,7 @@ export function ProgramCustomerPageClient() {});const rewardPeriodEndDate = useMemo(() => {- if (!programEnrollment?.rewards || !customer?.activity?.firstSaleDate)+ if (!programEnrollment?.rewards || !customer?.activity?.firstSaleAt)return null;const saleReward = programEnrollment?.rewards.find((r) => r.event === "sale",@@ -42,7 +42,7 @@ export function ProgramCustomerPageClient() {return null;// add the max duration to the first sale date- return addMonths(customer.activity.firstSaleDate, saleReward.maxDuration);+ return addMonths(customer.activity.firstSaleAt, saleReward.maxDuration);}, [programEnrollment, customer]);if ((!customer && !isLoading) || !showDetailedAnalytics) {diff --git a/apps/web/lib/zod/schemas/customer-activity.ts b/apps/web/lib/zod/schemas/customer-activity.tsindex f91fc0a8a7..0261084cbc 100644--- a/apps/web/lib/zod/schemas/customer-activity.ts+++ b/apps/web/lib/zod/schemas/customer-activity.ts@@ -2,10 +2,11 @@ import * as z from "zod/v4";import { LinkSchema } from "./links";export const customerActivityResponseSchema = z.object({- ltv: z.number(),+ saleAmount: z.number(),timeToLead: z.number().nullable(),timeToSale: z.number().nullable(),- firstSaleDate: z.date().nullable(),+ firstSaleAt: z.date().nullable(),+ subscriptionCanceledAt: z.date().nullable(),events: z.array(z.any()), // we've already parsed the events in get-customer-events.tslink: LinkSchema.pick({id: true,diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.tsindex 54e3c3508c..537f256645 100644--- a/apps/web/lib/zod/schemas/customers.ts+++ b/apps/web/lib/zod/schemas/customers.ts@@ -46,7 +46,12 @@ export const getCustomersQuerySchema = z"Whether to include expanded fields on the customer (`link`, `partner`, `discount`).",),sortBy: z- .enum(["createdAt", "saleAmount"])+ .enum([+ "createdAt",+ "saleAmount",+ "firstSaleAt",+ "subscriptionCanceledAt",+ ]).optional().default("createdAt").describe(diff --git a/apps/web/ui/customers/customer-stats.tsx b/apps/web/ui/customers/customer-stats.tsxindex 6143ebef72..77b2606a62 100644--- a/apps/web/ui/customers/customer-stats.tsx+++ b/apps/web/ui/customers/customer-stats.tsx@@ -7,6 +7,7 @@ import {currencyFormatter,formatDateTimeSmart,nFormatter,+ pluralize,} from "@dub/utils";import { formatDistance } from "date-fns";import Link from "next/link";@@ -18,7 +19,11 @@ export function CustomerStats({}: {customer?: Pick<CustomerEnriched, "sales" | "saleAmount" | "createdAt">;}) {- const { customerId } = useParams<{ customerId: string }>();+ const { slug: workspaceSlug, customerId } = useParams<{+ slug: string;+ customerId: string;+ }>();+const { customerActivity, isCustomerActivityLoading } = useCustomerActivity({customerId,});@@ -29,49 +34,64 @@ export function CustomerStats({href?: string;}[] = useMemo(() => [+ {+ label: "First sale date",+ value:+ isCustomerActivityLoading ? undefined : customerActivity?.firstSaleAt ? (+ <TimestampTooltip+ timestamp={customerActivity.firstSaleAt}+ side="right"+ rows={["local", "utc"]}+ >+ <span className="hover:text-content-emphasis underline decoration-dotted underline-offset-2">+ {formatDateTimeSmart(customerActivity.firstSaleAt)}+ </span>+ </TimestampTooltip>+ ) : (+ "-"+ ),+ },{label: "Time to sale",value:!customer || isCustomerActivityLoading? undefined- : customerActivity?.firstSaleDate- ? formatDistance(- customerActivity.firstSaleDate,- customer.createdAt,- )+ : customerActivity?.firstSaleAt+ ? formatDistance(customerActivity.firstSaleAt, customer.createdAt): "-",},{- label: "First sale date",+ label: "Lifetime value",+ value: customer ? (+ <div className="flex items-center gap-1">+ {currencyFormatter(customer.saleAmount ?? 0)}+ <span className="text-xs text-neutral-500">+ ({nFormatter(customer.sales ?? 0, { full: true })}{" "}+ {pluralize("sale", customer.sales ?? 0)})+ </span>+ </div>+ ) : undefined,+ href: `/${workspaceSlug}/events?event=sales&customerId=${customerId}&interval=1y`,+ },+ {+ label: "Subscription canceled",value:- isCustomerActivityLoading ? undefined : customerActivity?.firstSaleDate ? (+ isCustomerActivityLoading ? undefined : customerActivity?.subscriptionCanceledAt ? (<TimestampTooltip- timestamp={customerActivity.firstSaleDate}+ timestamp={customerActivity.subscriptionCanceledAt}side="right"rows={["local", "utc"]}><span className="hover:text-content-emphasis underline decoration-dotted underline-offset-2">- {formatDateTimeSmart(customerActivity.firstSaleDate)}+ {formatDateTimeSmart(customerActivity.subscriptionCanceledAt)}</span></TimestampTooltip>) : ("-"),},- {- label: "Sales",- value: customer- ? nFormatter(customer.sales ?? 0, { full: true })- : undefined,- },- {- label: "Lifetime value",- value: customer- ? currencyFormatter(customer.saleAmount ?? 0)- : undefined,- },],- [customer, customerActivity, isCustomerActivityLoading],+ [workspaceSlug, customer, customerActivity, isCustomerActivityLoading],);return (diff --git a/apps/web/ui/customers/customers-table/customers-table.tsx b/apps/web/ui/customers/customers-table/customers-table.tsxindex 9c71cd53d8..537935c0b4 100644--- a/apps/web/ui/customers/customers-table/customers-table.tsx+++ b/apps/web/ui/customers/customers-table/customers-table.tsx@@ -378,7 +378,12 @@ export function CustomersTable({onPaginationChange: setPagination,columnVisibility,onColumnVisibilityChange: setColumnVisibility,- sortableColumns: ["createdAt", "saleAmount"],+ sortableColumns: [+ "createdAt",+ "saleAmount",+ "firstSaleAt",+ "subscriptionCanceledAt",+ ],sortBy,sortOrder,onSortChange: ({ sortBy, sortOrder }) =>diff --git a/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx b/apps/web/ui/layout/sidebar/app-sidebar-nav.tsxindex c5df9c731d..6bc6c92c52 100644--- a/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx+++ b/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx@@ -293,7 +293,7 @@ const NAV_AREAS: SidebarNavAreas<SidebarNavData> = {},{name: "Customers",- icon: UserCheck,+ icon: User,href: `/${slug}/program/customers`,badge: pendingReferralsCount? pendingReferralsCount > 99diff --git a/packages/prisma/schema/customer.prisma b/packages/prisma/schema/customer.prismaindex 07f9f0af8b..4467554367 100644--- a/packages/prisma/schema/customer.prisma+++ b/packages/prisma/schema/customer.prisma@@ -39,6 +39,8 @@ model Customer {@@index([projectId, email])@@index([projectId, createdAt])@@index([projectId, saleAmount])+ @@index([projectId, firstSaleAt])+ @@index([projectId, subscriptionCanceledAt])@@index([programId, partnerId])@@index(partnerId)@@index(linkId)