The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Fix customer activity endpoint (#3401)
Steven Tey87c8cc59998a
diff --git a/apps/web/app/(ee)/api/customers/[id]/activity/route.ts b/apps/web/app/(ee)/api/customers/[id]/activity/route.tsindex c20e644ec9..84ae05fb64 100644--- a/apps/web/app/(ee)/api/customers/[id]/activity/route.ts+++ b/apps/web/app/(ee)/api/customers/[id]/activity/route.ts@@ -46,22 +46,9 @@ export const GET = withWorkspace(async ({ workspace, params }) => {link = decodeLinkIfCaseSensitive(link);}- // Find the time to lead of the customer- const timeToLead =- customer.clickedAt && customer.createdAt- ? customer.createdAt.getTime() - customer.clickedAt.getTime()- : null;-- const timeToSale =- customer.firstSaleAt && customer.createdAt- ? customer.firstSaleAt.getTime() - customer.createdAt.getTime()- : null;-return NextResponse.json(customerActivityResponseSchema.parse({...customer,- timeToLead,- timeToSale,events,link,}),diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/[customerId]/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/[customerId]/route.tsindex 2e98fa1291..b1ef667b65 100644--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/[customerId]/route.ts+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/[customerId]/route.ts@@ -82,17 +82,6 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {const firstSaleAt =customer.commissions[0]?.createdAt ?? customer.firstSaleAt;- // TODO: Calculate based on events (more accurate for multi-tenant setups where customers can interact with multiple partners)- const timeToLead =- customer.clickedAt && customer.createdAt- ? customer.createdAt.getTime() - customer.clickedAt.getTime()- : null;-- const timeToSale =- firstSaleAt && customer.createdAt- ? firstSaleAt.getTime() - customer.createdAt.getTime()- : null;-return NextResponse.json(PartnerProfileCustomerSchema.extend({...(customerDataSharingEnabledAt && { name: z.string().nullish() }),@@ -108,9 +97,6 @@ export const GET = withPartnerProfile(async ({ partner, params }) => {}),activity: {...customer,- firstSaleAt,- timeToLead,- timeToSale,events,link,},diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/route.tsindex d832b8c152..6b73219f82 100644--- a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/route.ts+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/route.ts@@ -85,12 +85,6 @@ export const GET = withPartnerProfile(const firstSaleAt =customer.commissions[0]?.createdAt ?? customer.firstSaleAt;- // TODO: Calculate based on events (more accurate for multi-tenant setups where customers can interact with multiple partners)- const timeToLead =- customer.clickedAt && customer.createdAt- ? customer.createdAt.getTime() - customer.clickedAt.getTime()- : null;-return PartnerProfileCustomerSchema.extend({...(customerDataSharingEnabledAt && { name: z.string().nullish() }),}).parse({@@ -105,9 +99,6 @@ export const GET = withPartnerProfile(}),activity: {...customer,- firstSaleAt,- timeToLead,- timeToSale: null,events: [],link: customer.link,},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 2e211e084d..b351687c27 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@@ -31,8 +31,7 @@ export function ProgramCustomerPageClient() {});const rewardPeriodEndDate = useMemo(() => {- if (!programEnrollment?.rewards || !customer?.activity?.firstSaleAt)- return null;+ if (!programEnrollment?.rewards || !customer?.firstSaleAt) return null;const saleReward = programEnrollment?.rewards.find((r) => r.event === "sale",);@@ -43,7 +42,7 @@ export function ProgramCustomerPageClient() {return null;// add the max duration to the first sale date- return addMonths(customer.activity.firstSaleAt, saleReward.maxDuration);+ return addMonths(customer.firstSaleAt, saleReward.maxDuration);}, [programEnrollment, customer]);if ((!customer && !isLoading) || !showDetailedAnalytics) {diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/layout.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/layout.tsxindex f03c70eca5..41c2eb1830 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/layout.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/layout.tsx@@ -11,7 +11,7 @@ import { CustomerTabs } from "@/ui/customers/customer-tabs";import { PageContent } from "@/ui/layout/page-content";import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";import { Button } from "@dub/ui";-import { ChevronRight, UserCheck } from "@dub/ui/icons";+import { ChevronRight, User } from "@dub/ui/icons";import Link from "next/link";import { redirect, useParams } from "next/navigation";import { ReactNode } from "react";@@ -43,7 +43,7 @@ export default function CustomerLayout({ children }: { children: ReactNode }) {title="Back to customers"className="bg-bg-subtle hover:bg-bg-emphasis flex size-8 shrink-0 items-center justify-center rounded-lg transition-[transform,background-color] duration-150 active:scale-95">- <UserCheck className="size-4" />+ <User className="size-4" /></Link><ChevronRight className="text-content-muted size-2.5 shrink-0 [&_*]:stroke-2" /><div>diff --git a/apps/web/lib/zod/schemas/customer-activity.ts b/apps/web/lib/zod/schemas/customer-activity.tsindex 0261084cbc..032833b1e9 100644--- a/apps/web/lib/zod/schemas/customer-activity.ts+++ b/apps/web/lib/zod/schemas/customer-activity.ts@@ -2,11 +2,6 @@ import * as z from "zod/v4";import { LinkSchema } from "./links";export const customerActivityResponseSchema = z.object({- saleAmount: z.number(),- timeToLead: z.number().nullable(),- timeToSale: z.number().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/tests/utils/verify-commission.ts b/apps/web/tests/utils/verify-commission.tsindex 22ae6cf6ec..0e230e300d 100644--- a/apps/web/tests/utils/verify-commission.ts+++ b/apps/web/tests/utils/verify-commission.ts@@ -19,8 +19,8 @@ export const verifyCommission = async ({}: VerifyCommissionProps) => {let customerId: string | undefined;- // Pause for 1.5 seconds for data to be fully processed- await new Promise((resolve) => setTimeout(resolve, 1500));+ // Pause for 3 seconds for data to be fully processed+ await new Promise((resolve) => setTimeout(resolve, 3000));// Optional: resolve customer ID if customerExternalId is givenif (customerExternalId) {@@ -31,9 +31,6 @@ export const verifyCommission = async ({expect(customers.length).toBeGreaterThan(0);customerId = customers[0].id;-- // Small delay if necessary for async commission processing- await new Promise((resolve) => setTimeout(resolve, 2000));}const query: Record<string, string> = {};diff --git a/apps/web/ui/customers/customer-stats.tsx b/apps/web/ui/customers/customer-stats.tsxindex 77b2606a62..7c463ed723 100644--- a/apps/web/ui/customers/customer-stats.tsx+++ b/apps/web/ui/customers/customer-stats.tsx@@ -1,4 +1,3 @@-import useCustomerActivity from "@/lib/swr/use-customer-activity";import { CustomerEnriched } from "@/lib/types";import { TimestampTooltip } from "@dub/ui";import { ArrowUpRight2 } from "@dub/ui/icons";@@ -17,17 +16,20 @@ import { CSSProperties, useMemo } from "react";export function CustomerStats({customer,}: {- customer?: Pick<CustomerEnriched, "sales" | "saleAmount" | "createdAt">;+ customer?: Pick<+ CustomerEnriched,+ | "sales"+ | "saleAmount"+ | "createdAt"+ | "firstSaleAt"+ | "subscriptionCanceledAt"+ >;}) {const { slug: workspaceSlug, customerId } = useParams<{slug: string;customerId: string;}>();- const { customerActivity, isCustomerActivityLoading } = useCustomerActivity({- customerId,- });-const stats: {label: string;value?: string | React.ReactNode;@@ -36,29 +38,27 @@ export function CustomerStats({() => [{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>- ) : (- "-"- ),+ value: !customer ? undefined : customer.firstSaleAt ? (+ <TimestampTooltip+ timestamp={customer.firstSaleAt}+ side="right"+ rows={["local", "utc"]}+ >+ <span className="hover:text-content-emphasis underline decoration-dotted underline-offset-2">+ {formatDateTimeSmart(customer.firstSaleAt)}+ </span>+ </TimestampTooltip>+ ) : (+ "-"+ ),},{label: "Time to sale",- value:- !customer || isCustomerActivityLoading- ? undefined- : customerActivity?.firstSaleAt- ? formatDistance(customerActivity.firstSaleAt, customer.createdAt)- : "-",+ value: !customer+ ? undefined+ : customer.firstSaleAt+ ? formatDistance(customer.firstSaleAt, customer.createdAt)+ : "-",},{label: "Lifetime value",@@ -75,23 +75,22 @@ export function CustomerStats({},{label: "Subscription canceled",- value:- isCustomerActivityLoading ? undefined : customerActivity?.subscriptionCanceledAt ? (- <TimestampTooltip- timestamp={customerActivity.subscriptionCanceledAt}- side="right"- rows={["local", "utc"]}- >- <span className="hover:text-content-emphasis underline decoration-dotted underline-offset-2">- {formatDateTimeSmart(customerActivity.subscriptionCanceledAt)}- </span>- </TimestampTooltip>- ) : (- "-"- ),+ value: !customer ? undefined : customer.subscriptionCanceledAt ? (+ <TimestampTooltip+ timestamp={customer.subscriptionCanceledAt}+ side="right"+ rows={["local", "utc"]}+ >+ <span className="hover:text-content-emphasis underline decoration-dotted underline-offset-2">+ {formatDateTimeSmart(customer.subscriptionCanceledAt)}+ </span>+ </TimestampTooltip>+ ) : (+ "-"+ ),},],- [workspaceSlug, customer, customerActivity, isCustomerActivityLoading],+ [workspaceSlug, customer],);return (