The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Customers pages updates (#3235)
Tim Wilsonfe0965f4c69c
diff --git a/apps/web/app/(ee)/api/cron/merge-partner-accounts/route.ts b/apps/web/app/(ee)/api/cron/merge-partner-accounts/route.tsindex e078e04ced..3442514735 100644--- a/apps/web/app/(ee)/api/cron/merge-partner-accounts/route.ts+++ b/apps/web/app/(ee)/api/cron/merge-partner-accounts/route.ts@@ -149,14 +149,19 @@ export async function POST(req: Request) {// update links, commissions, bounty submissions, and payoutsif (programIdsToTransfer.length > 0) {- const [updatedLinksRes, updatedCommissionsRes, updatedPayoutsRes] =- await Promise.all([- prisma.link.updateMany(updateManyPayload),- prisma.commission.updateMany(updateManyPayload),- prisma.payout.updateMany(updateManyPayload),- ]);+ const [+ updatedLinksRes,+ updatedCustomersRes,+ updatedCommissionsRes,+ updatedPayoutsRes,+ ] = await Promise.all([+ prisma.link.updateMany(updateManyPayload),+ prisma.customer.updateMany(updateManyPayload),+ prisma.commission.updateMany(updateManyPayload),+ prisma.payout.updateMany(updateManyPayload),+ ]);console.log(- `Updated ${updatedLinksRes.count} links, ${updatedCommissionsRes.count} commissions, and ${updatedPayoutsRes.count} payouts`,+ `Updated ${updatedLinksRes.count} links, ${updatedCustomersRes.count} customers, ${updatedCommissionsRes.count} commissions, and ${updatedPayoutsRes.count} payouts`,);// update notification emails, messages, and partner commentsdiff --git a/apps/web/app/(ee)/api/customers/count/route.ts b/apps/web/app/(ee)/api/customers/count/route.tsindex 63157e9bec..ebd3a8c5e3 100644--- a/apps/web/app/(ee)/api/customers/count/route.ts+++ b/apps/web/app/(ee)/api/customers/count/route.ts@@ -1,3 +1,4 @@+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { withWorkspace } from "@/lib/auth";import { getCustomersCountQuerySchema } from "@/lib/zod/schemas/customers";import { prisma, sanitizeFullTextSearch } from "@dub/prisma";@@ -6,10 +7,28 @@ import { NextResponse } from "next/server";// GET /api/customers/countexport const GET = withWorkspace(async ({ workspace, searchParams }) => {- const { email, externalId, search, country, linkId, groupBy } =- getCustomersCountQuerySchema.parse(searchParams);+ let {+ email,+ externalId,+ search,+ country,+ linkId,+ programId,+ partnerId,+ groupBy,+ } = getCustomersCountQuerySchema.parse(searchParams);++ if (programId || partnerId) {+ programId = getDefaultProgramIdOrThrow(workspace);+ }const commonWhere: Prisma.CustomerWhereInput = {+ ...(programId && {+ programId,+ }),+ ...(partnerId && {+ partnerId,+ }),projectId: workspace.id,? { email }diff --git a/apps/web/app/(ee)/api/customers/route.ts b/apps/web/app/(ee)/api/customers/route.tsindex f3cd31deaa..ded60a7d50 100644--- a/apps/web/app/(ee)/api/customers/route.ts+++ b/apps/web/app/(ee)/api/customers/route.ts@@ -1,6 +1,7 @@import { createId } from "@/lib/api/create-id";import { transformCustomer } from "@/lib/api/customers/transform-customer";import { DubApiError } from "@/lib/api/errors";+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";import { generateRandomName } from "@/lib/names";@@ -39,12 +40,14 @@ interface CustomerResponse extends Customer {// GET /api/customers – Get all customersexport const GET = withWorkspace(async ({ workspace, searchParams }) => {- const {+ let {email,externalId,search,country,linkId,+ programId,+ partnerId,includeExpandedFields,page,pageSize,@@ -53,13 +56,23 @@ export const GET = withWorkspace(sortOrder,} = getCustomersQuerySchemaExtended.parse(searchParams);- const customers = (await prisma.customer.findMany({+ if (programId || partnerId) {+ programId = getDefaultProgramIdOrThrow(workspace);+ }++ const customers = await prisma.customer.findMany({where: {...(customerIds? {id: { in: customerIds },}: {}),+ ...(programId && {+ programId,+ }),+ ...(partnerId && {+ partnerId,+ }),projectId: workspace.id,? { email }@@ -108,7 +121,7 @@ export const GET = withWorkspace(},}: {}),- })) as CustomerResponse[];+ });const responseSchema = includeExpandedFields? CustomerEnrichedSchema.merge(diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.tsindex 7b615ae202..27b83f044d 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts@@ -409,12 +409,18 @@ export async function checkoutSessionCompleted(},}),- // update customer stats+ // update customer stats + program/partner associationsprisma.customer.update({where: {id: customer.id,},data: {+ ...(link?.programId && {+ programId: link.programId,+ }),+ ...(link?.partnerId && {+ partnerId: link.partnerId,+ }),sales: {increment: 1,},diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.tsindex 21ab3938aa..890e9e3b3c 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts@@ -55,6 +55,8 @@ export async function createNewCustomer(event: Stripe.Event) {projectConnectId: stripeAccountId,externalId: dubCustomerExternalId,projectId: link.projectId,+ programId: link.programId,+ partnerId: link.partnerId,linkId,clickId,clickedAt: new Date(clickData.timestamp + "Z"),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 33b6122370..e2d2aabdeb 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@@ -7,13 +7,13 @@ import { PartnerEarningsResponse } from "@/lib/types";import { CustomerActivityList } from "@/ui/customers/customer-activity-list";import { CustomerDetailsColumn } from "@/ui/customers/customer-details-column";import { CustomerSalesTable } from "@/ui/customers/customer-sales-table";+import { PageContent } from "@/ui/layout/page-content";+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";import { ProgramRewardList } from "@/ui/partners/program-reward-list";-import { BackLink } from "@/ui/shared/back-link";-import { Button, MoneyBill2, Tooltip } from "@dub/ui";-import { fetcher, formatDate, OG_AVATAR_URL } from "@dub/utils";+import { ChevronRight, MoneyBill2, Tooltip, UserCheck } from "@dub/ui";+import { cn, fetcher, formatDate } from "@dub/utils";import { addMonths, isBefore } from "date-fns";import { AlertCircle } from "lucide-react";-import Link from "next/link";import { redirect, useParams } from "next/navigation";import { memo, useMemo } from "react";import useSWR from "swr";@@ -50,109 +50,97 @@ export function ProgramCustomerPageClient() {}return (- <div className="mb-10 mt-2">- <BackLink href={`/programs/${programSlug}/earnings`}>Earnings</BackLink>- <div className="mt-5 flex items-center gap-4">- {customer ? (- <img- src={`${OG_AVATAR_URL}${customer.id}`}- alt={customer.email ?? customer.id}- className="size-8 rounded-full"- />- ) : (- <div className="size-8 animate-pulse rounded-full bg-neutral-200" />- )}-- <div className="flex flex-col gap-1">- {customer ? (- <>- {customer["name"] && (- <h1 className="text-base font-semibold leading-tight text-neutral-900">- {customer["name"]}- </h1>- )}- {customer.email && (- <span className="text-sm font-medium text-neutral-500">- {customer.email}- </span>- )}- </>- ) : (- <div className="h-5 w-24 animate-pulse rounded-md bg-neutral-200" />- )}+ <PageContent+ title={+ <div className="flex items-center gap-1.5">+ <div+ // href={`/programs/${programSlug}/customers`}+ // aria-label="Back to customers"+ // title="Back to customers"+ className={cn(+ "bg-bg-subtle flex size-8 shrink-0 items-center justify-center rounded-lg",+ // "hover:bg-bg-emphasis transition-[transform,background-color] duration-150 active:scale-95",+ )}+ >+ <UserCheck className="size-4" />+ </div>+ <ChevronRight className="text-content-muted size-2.5 shrink-0 [&_*]:stroke-2" />+ <div>+ {customer ? (+ customer.name || customer.email+ ) : (+ <div className="h-6 w-32 animate-pulse rounded-md bg-neutral-200" />+ )}+ </div></div>- </div>- <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">- <div className="flex items-center justify-between">- <h2 className="text-lg font-semibold text-neutral-900">- Earnings- </h2>- {programEnrollment?.rewards && (- <Tooltip- content={- <ProgramRewardList- rewards={programEnrollment?.rewards}- className="gap-2 border-none p-3"- showModifiersTooltip={false}- />- }- >- <div className="border-border-subtle flex cursor-default items-center justify-center gap-1.5 rounded-md border px-2 py-1 transition-all hover:bg-neutral-50">- <MoneyBill2 className="size-4" />- <span className="text-sm">Eligible rewards</span>- </div>- </Tooltip>- )}- </div>- {rewardPeriodEndDate &&- isBefore(rewardPeriodEndDate, new Date()) && (- <div className="flex items-center gap-2 rounded-lg border border-amber-100 bg-amber-50 px-3 py-2">- <AlertCircle className="size-4 shrink-0 text-amber-600" />- <p className="text-sm text-amber-900">- The earning period for this customer has ended as of{" "}- {formatDate(rewardPeriodEndDate)}. No future conversions- will be rewarded.- </p>+ }+ >+ <PageWidthWrapper className="flex flex-col gap-6 pb-10">+ <div className="@3xl/page:grid-cols-[minmax(440px,1fr)_minmax(0,360px)] grid grid-cols-1 gap-6">+ <div className="@3xl/page:order-2">+ <CustomerDetailsColumn+ customer={customer}+ customerActivity={customer?.activity}+ isCustomerActivityLoading={!customer}+ />+ </div>+ <div className="@3xl/page:order-1">+ <div className="border-border-subtle overflow-hidden rounded-xl border p-4">+ <section className="flex flex-col gap-4">+ <div className="flex items-center justify-between">+ <h2 className="text-lg font-semibold text-neutral-900">+ Earnings+ </h2>+ {programEnrollment?.rewards && (+ <Tooltip+ content={+ <ProgramRewardList+ rewards={programEnrollment?.rewards}+ className="gap-2 border-none p-3"+ showModifiersTooltip={false}+ />+ }+ >+ <div className="border-border-subtle flex cursor-default items-center justify-center gap-1.5 rounded-md border px-2 py-1 transition-all hover:bg-neutral-50">+ <MoneyBill2 className="size-4" />+ <span className="text-sm">Eligible rewards</span>+ </div>+ </Tooltip>+ )}</div>- )}- <EarningsTable customerId={customerId} />- </section>+ {rewardPeriodEndDate &&+ isBefore(rewardPeriodEndDate, new Date()) && (+ <div className="flex items-center gap-2 rounded-lg border border-amber-100 bg-amber-50 px-3 py-2">+ <AlertCircle className="size-4 shrink-0 text-amber-600" />+ <p className="text-sm text-amber-900">+ The earning period for this customer has ended as of{" "}+ {formatDate(rewardPeriodEndDate)}. No future conversions+ will be rewarded.+ </p>+ </div>+ )}- <section className="flex flex-col">- <div className="flex items-center justify-between">- <h2 className="py-3 text-lg font-semibold text-neutral-900">- Activity- </h2>- <Link- href={`/programs/${programSlug}/events?interval=all&customerId=${customerId}`}- >- <Button- variant="secondary"- text="View all"- className="h-7 px-2"- />- </Link>+ <div className="border-border-subtle overflow-hidden rounded-lg border">+ <EarningsTable customerId={customerId} />+ </div>+ </section></div>- <CustomerActivityList- activity={customer?.activity}- isLoading={!customer}- />- </section>- </div>- {/* Right side details */}- <div className="-order-1 lg:order-1">- <CustomerDetailsColumn- customer={customer}- customerActivity={customer?.activity}- isCustomerActivityLoading={!customer}- />+ <section className="mt-3 flex flex-col px-4">+ <div className="flex items-center justify-between">+ <h2 className="py-3 text-lg font-semibold text-neutral-900">+ Activity+ </h2>+ </div>+ <CustomerActivityList+ activity={customer?.activity}+ isLoading={!customer}+ />+ </section>+ </div></div>- </div>- </div>+ </PageWidthWrapper>+ </PageContent>);}diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page.tsxindex 9dce0c1492..b3a2bd6518 100644--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/[customerId]/page.tsx@@ -1,13 +1,5 @@-import { PageContent } from "@/ui/layout/page-content";-import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";import { ProgramCustomerPageClient } from "./page-client";export default function ProgramCustomer() {- return (- <PageContent>- <PageWidthWrapper className="flex flex-col gap-6 pb-10">- <ProgramCustomerPageClient />- </PageWidthWrapper>- </PageContent>- );+ return <ProgramCustomerPageClient />;}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/earnings/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/earnings/page-client.tsxnew file mode 100644index 0000000000..77631c424f--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/earnings/page-client.tsx@@ -0,0 +1,107 @@+"use client";++import { CUSTOMER_PAGE_EVENTS_LIMIT } from "@/lib/constants/misc";+import useCustomer from "@/lib/swr/use-customer";+import useWorkspace from "@/lib/swr/use-workspace";+import { CommissionResponse, CustomerEnriched } from "@/lib/types";+import { CustomerPartnerEarningsTable } from "@/ui/customers/customer-partner-earnings-table";+import { ArrowUpRight } from "@dub/ui";+import { OG_AVATAR_URL, fetcher } from "@dub/utils";+import Link from "next/link";+import { redirect, useParams } from "next/navigation";+import { memo } from "react";+import useSWR from "swr";++export function CustomerEarningsPageClient() {+ const { customerId } = useParams<{ customerId: string }>();++ const { slug } = useWorkspace();+ const { data: customer, isLoading } = useCustomer<CustomerEnriched>({+ customerId,+ query: { includeExpandedFields: true },+ });++ if (!customer && !isLoading) redirect(`/${slug}/customers`);++ return !customer || (customer.partner && customer.programId) ? (+ <section className="flex flex-col gap-4">+ <h2 className="text-lg font-semibold text-neutral-900">+ Partner earnings+ </h2>+ <div className="border-border-subtle flex flex-col overflow-hidden rounded-lg border">+ <Link+ href={`/${slug}/program/partners/${customer?.partner?.id}`}+ target="_blank"+ className="group flex items-center justify-between overflow-hidden bg-neutral-100 px-3 py-2.5"+ >+ <div className="flex min-w-0 items-center gap-3">+ {customer?.partner ? (+ <>+ <img+ src={+ customer?.partner?.image ||+ `${OG_AVATAR_URL}${customer?.partner?.name}`+ }+ alt={customer.partner.name}+ className="size-5 rounded-full"+ />+ <span className="block min-w-0 truncate text-sm font-medium text-neutral-900">+ {customer.partner.name}+ </span>+ </>+ ) : (+ <>+ <div className="size-5 animate-pulse rounded-full bg-neutral-200" />+ <div className="h-5 w-24 animate-pulse rounded bg-neutral-200" />+ </>+ )}+ </div>+ <ArrowUpRight className="size-3 shrink-0 -translate-x-0.5 translate-y-0.5 opacity-0 transition-[transform,opacity] group-hover:translate-x-0 group-hover:translate-y-0 group-hover:opacity-100" />+ </Link>++ <div className="border-border-subtle border-t">+ <PartnerEarningsTable customerId={customerId} />+ </div>+ </div>+ </section>+ ) : null;+}++const PartnerEarningsTable = memo(({ customerId }: { customerId: string }) => {+ const { id: workspaceId, slug } = useWorkspace();++ const { data: commissions, isLoading: isComissionsLoading } = useSWR<+ CommissionResponse[]+ >(+ `/api/commissions?${new URLSearchParams({+ customerId,+ workspaceId: workspaceId!,+ pageSize: CUSTOMER_PAGE_EVENTS_LIMIT.toString(),+ })}`,+ fetcher,+ );++ const { data: totalCommissions, isLoading: isTotalCommissionsLoading } =+ useSWR<{ all: { count: number } }>(+ // Only fetch total earnings count if the earnings data is equal to the limit+ commissions?.length === CUSTOMER_PAGE_EVENTS_LIMIT &&+ `/api/commissions/count?${new URLSearchParams({+ customerId,+ workspaceId: workspaceId!,+ })}`,+ fetcher,+ );++ return (+ <CustomerPartnerEarningsTable+ commissions={commissions}+ totalCommissions={+ isTotalCommissionsLoading+ ? undefined+ : totalCommissions?.all?.count ?? commissions?.length+ }+ viewAllHref={`/${slug}/program/commissions?customerId=${customerId}`}+ isLoading={isComissionsLoading}+ />+ );+});diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/earnings/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/earnings/page.tsxnew file mode 100644index 0000000000..effdf5c3a7--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/earnings/page.tsx@@ -0,0 +1,5 @@+import { CustomerEarningsPageClient } from "./page-client";++export default function CustomerEarningsPage() {+ return <CustomerEarningsPageClient />;+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/layout.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/layout.tsxnew file mode 100644index 0000000000..903d08c1bc--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/layout.tsx@@ -0,0 +1,108 @@+"use client";++import useCustomer from "@/lib/swr/use-customer";+import useWorkspace from "@/lib/swr/use-workspace";+import { CustomerActivityResponse, CustomerEnriched } from "@/lib/types";+import { CustomerActivityList } from "@/ui/customers/customer-activity-list";+import { CustomerDetailsColumn } from "@/ui/customers/customer-details-column";+import { CustomerStats } from "@/ui/customers/customer-stats";+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, Users } from "@dub/ui/icons";+import { fetcher } from "@dub/utils";+import Link from "next/link";+import { redirect, useParams } from "next/navigation";+import { ReactNode } from "react";+import useSWR from "swr";++export default function CustomerLayout({ children }: { children: ReactNode }) {+ const { id: workspaceId, slug: workspaceSlug } = useWorkspace();+ const { customerId } = useParams<{ customerId: string }>();++ const { data: customer, error: customerError } =+ useCustomer<CustomerEnriched>({+ customerId,+ query: { includeExpandedFields: true },+ });++ const { data: customerActivity, isLoading: isCustomerActivityLoading } =+ useSWR<CustomerActivityResponse>(+ customer &&+ `/api/customers/${customer.id}/activity?workspaceId=${workspaceId}`,+ fetcher,+ );++ if (customerError && customerError.status === 404)+ redirect(`/${workspaceSlug}/customers`);++ return (+ <PageContent+ title={+ <div className="flex items-center gap-1.5">+ <Link+ href={`/${workspaceSlug}/customers`}+ aria-label="Back to customers"+ 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"+ >+ <Users className="size-4" />+ </Link>+ <ChevronRight className="text-content-muted size-2.5 shrink-0 [&_*]:stroke-2" />+ <div>+ {customer ? (+ customer.name+ ) : (+ <div className="h-6 w-32 animate-pulse rounded-md bg-neutral-200" />+ )}+ </div>+ </div>+ }+ >+ <PageWidthWrapper className="pb-10">+ <CustomerStats customer={customer} />++ <div className="@3xl/page:grid-cols-[minmax(440px,1fr)_minmax(0,360px)] mt-6 grid grid-cols-1 gap-6">+ <div className="@3xl/page:order-2">+ <CustomerDetailsColumn+ customer={customer}+ customerActivity={customerActivity}+ isCustomerActivityLoading={!customer || isCustomerActivityLoading}+ workspaceSlug={workspaceSlug}+ />+ </div>+ <div className="@3xl/page:order-1">+ <div className="border-border-subtle overflow-hidden rounded-xl border bg-neutral-100">+ <CustomerTabs customer={customer} />+ <div className="border-border-subtle -mx-px -mb-px rounded-xl border bg-white p-4">+ {children}+ </div>+ </div>++ <section className="mt-3 flex flex-col px-4">+ <div className="flex items-center justify-between">+ <h2 className="py-3 text-lg font-semibold text-neutral-900">+ Activity+ </h2>+ <Link+ href={`/${workspaceSlug}/events?interval=all&customerId=${customerId}`}+ >+ <Button+ variant="secondary"+ text="View all"+ className="h-7 px-2"+ />+ </Link>+ </div>+ <CustomerActivityList+ activity={customerActivity}+ isLoading={!customer || isCustomerActivityLoading}+ />+ </section>+ </div>+ </div>+ </PageWidthWrapper>+ </PageContent>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/page-client.tsxdeleted file mode 100644index a128b26e03..0000000000--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/page-client.tsx+++ /dev/null@@ -1,246 +0,0 @@-"use client";--import { CUSTOMER_PAGE_EVENTS_LIMIT } from "@/lib/constants/misc";-import useCustomer from "@/lib/swr/use-customer";-import useWorkspace from "@/lib/swr/use-workspace";-import {- CommissionResponse,- CustomerActivityResponse,- CustomerEnriched,- SaleEvent,-} from "@/lib/types";-import { CustomerActivityList } from "@/ui/customers/customer-activity-list";-import { CustomerDetailsColumn } from "@/ui/customers/customer-details-column";-import { CustomerPartnerEarningsTable } from "@/ui/customers/customer-partner-earnings-table";-import { CustomerSalesTable } from "@/ui/customers/customer-sales-table";-import { BackLink } from "@/ui/shared/back-link";-import { ArrowUpRight, Button, CopyButton } from "@dub/ui";-import { OG_AVATAR_URL, fetcher } from "@dub/utils";-import Link from "next/link";-import { redirect, useParams } from "next/navigation";-import { memo } from "react";-import useSWR from "swr";--export function CustomerPageClient() {- const { customerId } = useParams<{ customerId: string }>();-- const { id: workspaceId, slug } = useWorkspace();- const { data: customer, isLoading } = useCustomer<CustomerEnriched>({- customerId,- query: { includeExpandedFields: true },- });-- const { data: customerActivity, isLoading: isCustomerActivityLoading } =- useSWR<CustomerActivityResponse>(- customer &&- `/api/customers/${customer.id}/activity?workspaceId=${workspaceId}`,- fetcher,- );-- if (!customer && !isLoading) redirect("/customers");-- return (- <div className="mb-10 mt-2">- <BackLink href={`/${slug}/customers`}>Customers</BackLink>- <div className="mt-5 flex items-center gap-4">- {customer ? (- <img- src={customer.avatar || `${OG_AVATAR_URL}${customer.name}`}- alt={customer.name}- className="size-12 rounded-full"- />- ) : (- <div className="size-12 animate-pulse rounded-full bg-neutral-200" />- )}- <div className="flex flex-col gap-1">- {customer ? (- <h1 className="text-base font-semibold leading-tight text-neutral-900">- {customer.name}- </h1>- ) : (- <div className="h-5 w-32 animate-pulse rounded-md bg-neutral-200" />- )}-- {customer ? (- customer.email && (- <div className="flex items-center gap-1">- <span className="text-sm font-medium text-neutral-500">- {customer.email}- </span>- <CopyButton- value={customer.email}- variant="neutral"- className="p-1 [&>*]:h-3 [&>*]:w-3"- successMessage="Copied email to clipboard!"- />- </div>- )- ) : (- <div className="h-5 w-24 animate-pulse rounded-md bg-neutral-200" />- )}- </div>- </div>- <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">- <h2 className="py-3 text-lg font-semibold text-neutral-900">- Sales- </h2>- <SalesTable customerId={customerId} />- </section>-- {customer?.programId && customer.partner && (- <section className="flex flex-col">- <h2 className="py-3 text-lg font-semibold text-neutral-900">- Partner Earnings- </h2>- <div className="flex flex-col gap-4">- <Link- href={`/${slug}/program/partners/${customer.partner.id}`}- target="_blank"- className="border-border-subtle group flex items-center justify-between overflow-hidden rounded-lg border bg-neutral-100 px-4 py-3"- >- <div className="flex min-w-0 items-center gap-3">- {- <img- src={- customer.partner.image ||- `${OG_AVATAR_URL}${customer.partner.name}`- }- alt={customer.partner.name}- className="size-8 rounded-full"- />- }- <div className="min-w-0">- <span className="block truncate text-xs font-semibold leading-tight text-neutral-900">- {customer.partner.name}- </span>-- {customer?.partner.email && (- <span className="block min-w-0 truncate text-xs font-medium leading-tight text-neutral-500">- {customer.partner.email}- </span>- )}- </div>- </div>- <ArrowUpRight className="size-3 shrink-0 -translate-x-0.5 translate-y-0.5 opacity-0 transition-[transform,opacity] group-hover:translate-x-0 group-hover:translate-y-0 group-hover:opacity-100" />- </Link>- <PartnerEarningsTable- programId={customer.programId}- customerId={customerId}- />- </div>- </section>- )}-- <section className="flex flex-col">- <div className="flex items-center justify-between">- <h2 className="py-3 text-lg font-semibold text-neutral-900">- Activity- </h2>- <Link- href={`/${slug}/events?interval=all&customerId=${customerId}`}- >- <Button- variant="secondary"- text="View all"- className="h-7 px-2"- />- </Link>- </div>- <CustomerActivityList- activity={customerActivity}- isLoading={!customer || isCustomerActivityLoading}- />- </section>- </div>-- {/* Right side details */}- <div className="-order-1 lg:order-1">- <CustomerDetailsColumn- customer={customer}- customerActivity={customerActivity}- isCustomerActivityLoading={!customer || isCustomerActivityLoading}- />- </div>- </div>- </div>- );-}--const SalesTable = memo(({ customerId }: { customerId: string }) => {- const { id: workspaceId, slug } = useWorkspace();-- const { data: salesData, isLoading: isSalesLoading } = useSWR<SaleEvent[]>(- `/api/events?event=sales&interval=all&limit=${CUSTOMER_PAGE_EVENTS_LIMIT}&customerId=${customerId}&workspaceId=${workspaceId}`,- fetcher,- {- keepPreviousData: true,- },- );-- const { data: totalSales, isLoading: isTotalSalesLoading } = useSWR<{- sales: number;- }>(- // Only fetch total sales count if the sales data is equal to the limit- salesData?.length === CUSTOMER_PAGE_EVENTS_LIMIT &&- `/api/analytics?event=sales&interval=all&groupBy=count&customerId=${customerId}&workspaceId=${workspaceId}`,- fetcher,- {- keepPreviousData: true,- },- );-- return (- <CustomerSalesTable- sales={salesData}- totalSales={- isTotalSalesLoading ? undefined : totalSales?.sales ?? salesData?.length- }- viewAllHref={`/${slug}/events?event=sales&interval=all&customerId=${customerId}`}- isLoading={isSalesLoading}- />- );-});--const PartnerEarningsTable = memo(- ({ programId, customerId }: { programId: string; customerId: string }) => {- const { id: workspaceId, slug } = useWorkspace();-- const { data: commissions, isLoading: isComissionsLoading } = useSWR<- CommissionResponse[]- >(- `/api/commissions?${new URLSearchParams({- customerId,- workspaceId: workspaceId!,- pageSize: CUSTOMER_PAGE_EVENTS_LIMIT.toString(),- })}`,- fetcher,- );-- const { data: totalCommissions, isLoading: isTotalCommissionsLoading } =- useSWR<{ all: { count: number } }>(- // Only fetch total earnings count if the earnings data is equal to the limit- commissions?.length === CUSTOMER_PAGE_EVENTS_LIMIT &&- `/api/commissions/count?${new URLSearchParams({- customerId,- workspaceId: workspaceId!,- })}`,- fetcher,- );-- return (- <CustomerPartnerEarningsTable- commissions={commissions}- totalCommissions={- isTotalCommissionsLoading- ? undefined- : totalCommissions?.all?.count ?? commissions?.length- }- viewAllHref={`/${slug}/program/commissions?customerId=${customerId}`}- isLoading={isComissionsLoading}- />- );- },-);diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/page.tsxdeleted file mode 100644index 7651946ec2..0000000000--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/page.tsx+++ /dev/null@@ -1,13 +0,0 @@-import { PageContentOld } from "@/ui/layout/page-content";-import { MaxWidthWrapper } from "@dub/ui";-import { CustomerPageClient } from "./page-client";--export default function CustomerPage() {- return (- <PageContentOld>- <MaxWidthWrapper>- <CustomerPageClient />- </MaxWidthWrapper>- </PageContentOld>- );-}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/sales/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/sales/page-client.tsxnew file mode 100644index 0000000000..4566e658de--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/sales/page-client.tsx@@ -0,0 +1,67 @@+"use client";++import { CUSTOMER_PAGE_EVENTS_LIMIT } from "@/lib/constants/misc";+import useCustomer from "@/lib/swr/use-customer";+import useWorkspace from "@/lib/swr/use-workspace";+import { CustomerEnriched, SaleEvent } from "@/lib/types";+import { CustomerSalesTable } from "@/ui/customers/customer-sales-table";+import { fetcher } from "@dub/utils";+import { redirect, useParams } from "next/navigation";+import { memo } from "react";+import useSWR from "swr";++export function CustomerSalesPageClient() {+ const { customerId } = useParams<{ customerId: string }>();++ const { slug } = useWorkspace();+ const { data: customer, isLoading } = useCustomer<CustomerEnriched>({+ customerId,+ query: { includeExpandedFields: true },+ });++ if (!customer && !isLoading) redirect(`/${slug}/customers`);++ return (+ <section className="flex flex-col gap-4">+ <h2 className="text-lg font-semibold text-neutral-900">Sales</h2>+ <div className="border-border-subtle overflow-hidden rounded-lg border">+ <SalesTable customerId={customerId} />+ </div>+ </section>+ );+}++const SalesTable = memo(({ customerId }: { customerId: string }) => {+ const { id: workspaceId, slug } = useWorkspace();++ const { data: salesData, isLoading: isSalesLoading } = useSWR<SaleEvent[]>(+ `/api/events?event=sales&interval=all&limit=${CUSTOMER_PAGE_EVENTS_LIMIT}&customerId=${customerId}&workspaceId=${workspaceId}`,+ fetcher,+ {+ keepPreviousData: true,+ },+ );++ const { data: totalSales, isLoading: isTotalSalesLoading } = useSWR<{+ sales: number;+ }>(+ // Only fetch total sales count if the sales data is equal to the limit+ salesData?.length === CUSTOMER_PAGE_EVENTS_LIMIT &&+ `/api/analytics?event=sales&interval=all&groupBy=count&customerId=${customerId}&workspaceId=${workspaceId}`,+ fetcher,+ {+ keepPreviousData: true,+ },+ );++ return (+ <CustomerSalesTable+ sales={salesData}+ totalSales={+ isTotalSalesLoading ? undefined : totalSales?.sales ?? salesData?.length+ }+ viewAllHref={`/${slug}/events?event=sales&interval=all&customerId=${customerId}`}+ isLoading={isSalesLoading}+ />+ );+});diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/sales/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/sales/page.tsxnew file mode 100644index 0000000000..ac5fddcb5c--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/[customerId]/sales/page.tsx@@ -0,0 +1,5 @@+import { CustomerSalesPageClient } from "./page-client";++export default function CustomerSalesPage() {+ return <CustomerSalesPageClient />;+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/commission-table.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/commission-table.tsxindex 08c20e365e..5f890ce3bc 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/commission-table.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/commission-table.tsx@@ -159,7 +159,7 @@ export function CommissionTable() {row.original.customer ? (<CustomerRowItemcustomer={row.original.customer}- href={`/${slug}/customers/${row.original.customer.id}`}+ href={`/${slug}/program/customers/${row.original.customer.id}`}/>) : ("-"diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/earnings/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/earnings/page-client.tsxnew file mode 100644index 0000000000..77631c424f--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/earnings/page-client.tsx@@ -0,0 +1,107 @@+"use client";++import { CUSTOMER_PAGE_EVENTS_LIMIT } from "@/lib/constants/misc";+import useCustomer from "@/lib/swr/use-customer";+import useWorkspace from "@/lib/swr/use-workspace";+import { CommissionResponse, CustomerEnriched } from "@/lib/types";+import { CustomerPartnerEarningsTable } from "@/ui/customers/customer-partner-earnings-table";+import { ArrowUpRight } from "@dub/ui";+import { OG_AVATAR_URL, fetcher } from "@dub/utils";+import Link from "next/link";+import { redirect, useParams } from "next/navigation";+import { memo } from "react";+import useSWR from "swr";++export function CustomerEarningsPageClient() {+ const { customerId } = useParams<{ customerId: string }>();++ const { slug } = useWorkspace();+ const { data: customer, isLoading } = useCustomer<CustomerEnriched>({+ customerId,+ query: { includeExpandedFields: true },+ });++ if (!customer && !isLoading) redirect(`/${slug}/customers`);++ return !customer || (customer.partner && customer.programId) ? (+ <section className="flex flex-col gap-4">+ <h2 className="text-lg font-semibold text-neutral-900">+ Partner earnings+ </h2>+ <div className="border-border-subtle flex flex-col overflow-hidden rounded-lg border">+ <Link+ href={`/${slug}/program/partners/${customer?.partner?.id}`}+ target="_blank"+ className="group flex items-center justify-between overflow-hidden bg-neutral-100 px-3 py-2.5"+ >+ <div className="flex min-w-0 items-center gap-3">+ {customer?.partner ? (+ <>+ <img+ src={+ customer?.partner?.image ||+ `${OG_AVATAR_URL}${customer?.partner?.name}`+ }+ alt={customer.partner.name}+ className="size-5 rounded-full"+ />+ <span className="block min-w-0 truncate text-sm font-medium text-neutral-900">+ {customer.partner.name}+ </span>+ </>+ ) : (+ <>+ <div className="size-5 animate-pulse rounded-full bg-neutral-200" />+ <div className="h-5 w-24 animate-pulse rounded bg-neutral-200" />+ </>+ )}+ </div>+ <ArrowUpRight className="size-3 shrink-0 -translate-x-0.5 translate-y-0.5 opacity-0 transition-[transform,opacity] group-hover:translate-x-0 group-hover:translate-y-0 group-hover:opacity-100" />+ </Link>++ <div className="border-border-subtle border-t">+ <PartnerEarningsTable customerId={customerId} />+ </div>+ </div>+ </section>+ ) : null;+}++const PartnerEarningsTable = memo(({ customerId }: { customerId: string }) => {+ const { id: workspaceId, slug } = useWorkspace();++ const { data: commissions, isLoading: isComissionsLoading } = useSWR<+ CommissionResponse[]+ >(+ `/api/commissions?${new URLSearchParams({+ customerId,+ workspaceId: workspaceId!,+ pageSize: CUSTOMER_PAGE_EVENTS_LIMIT.toString(),+ })}`,+ fetcher,+ );++ const { data: totalCommissions, isLoading: isTotalCommissionsLoading } =+ useSWR<{ all: { count: number } }>(+ // Only fetch total earnings count if the earnings data is equal to the limit+ commissions?.length === CUSTOMER_PAGE_EVENTS_LIMIT &&+ `/api/commissions/count?${new URLSearchParams({+ customerId,+ workspaceId: workspaceId!,+ })}`,+ fetcher,+ );++ return (+ <CustomerPartnerEarningsTable+ commissions={commissions}+ totalCommissions={+ isTotalCommissionsLoading+ ? undefined+ : totalCommissions?.all?.count ?? commissions?.length+ }+ viewAllHref={`/${slug}/program/commissions?customerId=${customerId}`}+ isLoading={isComissionsLoading}+ />+ );+});diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/earnings/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/earnings/page.tsxnew file mode 100644index 0000000000..effdf5c3a7--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/earnings/page.tsx@@ -0,0 +1,5 @@+import { CustomerEarningsPageClient } from "./page-client";++export default function CustomerEarningsPage() {+ return <CustomerEarningsPageClient />;+}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.tsxnew file mode 100644index 0000000000..f03c70eca5--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/layout.tsx@@ -0,0 +1,105 @@+"use client";++import useCustomer from "@/lib/swr/use-customer";+import useCustomerActivity from "@/lib/swr/use-customer-activity";+import useWorkspace from "@/lib/swr/use-workspace";+import { CustomerEnriched } from "@/lib/types";+import { CustomerActivityList } from "@/ui/customers/customer-activity-list";+import { CustomerDetailsColumn } from "@/ui/customers/customer-details-column";+import { CustomerStats } from "@/ui/customers/customer-stats";+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 Link from "next/link";+import { redirect, useParams } from "next/navigation";+import { ReactNode } from "react";++export default function CustomerLayout({ children }: { children: ReactNode }) {+ const { slug: workspaceSlug } = useWorkspace();+ const { customerId } = useParams<{ customerId: string }>();++ const { data: customer, error: customerError } =+ useCustomer<CustomerEnriched>({+ customerId,+ query: { includeExpandedFields: true },+ });++ const { customerActivity, isCustomerActivityLoading } = useCustomerActivity({+ customerId,+ });++ if (customerError && customerError.status === 404)+ redirect(`/${workspaceSlug}/program/customers`);++ return (+ <PageContent+ title={+ <div className="flex items-center gap-1.5">+ <Link+ href={`/${workspaceSlug}/program/customers`}+ aria-label="Back to customers"+ 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" />+ </Link>+ <ChevronRight className="text-content-muted size-2.5 shrink-0 [&_*]:stroke-2" />+ <div>+ {customer ? (+ customer.name+ ) : (+ <div className="h-6 w-32 animate-pulse rounded-md bg-neutral-200" />+ )}+ </div>+ </div>+ }+ >+ <PageWidthWrapper className="pb-10">+ <CustomerStats customer={customer} />++ <div className="@3xl/page:grid-cols-[minmax(440px,1fr)_minmax(0,360px)] mt-6 grid grid-cols-1 gap-6">+ <div className="@3xl/page:order-2">+ <CustomerDetailsColumn+ customer={customer}+ customerActivity={customerActivity}+ isCustomerActivityLoading={!customer || isCustomerActivityLoading}+ workspaceSlug={workspaceSlug}+ isProgramPage+ />+ </div>+ <div className="@3xl/page:order-1">+ <div className="border-border-subtle overflow-hidden rounded-xl border bg-neutral-100">+ <CustomerTabs customer={customer} isProgramPage />+ <div className="border-border-subtle -mx-px -mb-px rounded-xl border bg-white p-4">+ {children}+ </div>+ </div>++ <section className="mt-3 flex flex-col px-4">+ <div className="flex items-center justify-between">+ <h2 className="py-3 text-lg font-semibold text-neutral-900">+ Activity+ </h2>+ <Link+ href={`/${workspaceSlug}/events?interval=all&customerId=${customerId}`}+ >+ <Button+ variant="secondary"+ text="View all"+ className="h-7 px-2"+ />+ </Link>+ </div>+ <CustomerActivityList+ activity={customerActivity}+ isLoading={!customer || isCustomerActivityLoading}+ />+ </section>+ </div>+ </div>+ </PageWidthWrapper>+ </PageContent>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/sales/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/sales/page-client.tsxnew file mode 100644index 0000000000..4566e658de--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/sales/page-client.tsx@@ -0,0 +1,67 @@+"use client";++import { CUSTOMER_PAGE_EVENTS_LIMIT } from "@/lib/constants/misc";+import useCustomer from "@/lib/swr/use-customer";+import useWorkspace from "@/lib/swr/use-workspace";+import { CustomerEnriched, SaleEvent } from "@/lib/types";+import { CustomerSalesTable } from "@/ui/customers/customer-sales-table";+import { fetcher } from "@dub/utils";+import { redirect, useParams } from "next/navigation";+import { memo } from "react";+import useSWR from "swr";++export function CustomerSalesPageClient() {+ const { customerId } = useParams<{ customerId: string }>();++ const { slug } = useWorkspace();+ const { data: customer, isLoading } = useCustomer<CustomerEnriched>({+ customerId,+ query: { includeExpandedFields: true },+ });++ if (!customer && !isLoading) redirect(`/${slug}/customers`);++ return (+ <section className="flex flex-col gap-4">+ <h2 className="text-lg font-semibold text-neutral-900">Sales</h2>+ <div className="border-border-subtle overflow-hidden rounded-lg border">+ <SalesTable customerId={customerId} />+ </div>+ </section>+ );+}++const SalesTable = memo(({ customerId }: { customerId: string }) => {+ const { id: workspaceId, slug } = useWorkspace();++ const { data: salesData, isLoading: isSalesLoading } = useSWR<SaleEvent[]>(+ `/api/events?event=sales&interval=all&limit=${CUSTOMER_PAGE_EVENTS_LIMIT}&customerId=${customerId}&workspaceId=${workspaceId}`,+ fetcher,+ {+ keepPreviousData: true,+ },+ );++ const { data: totalSales, isLoading: isTotalSalesLoading } = useSWR<{+ sales: number;+ }>(+ // Only fetch total sales count if the sales data is equal to the limit+ salesData?.length === CUSTOMER_PAGE_EVENTS_LIMIT &&+ `/api/analytics?event=sales&interval=all&groupBy=count&customerId=${customerId}&workspaceId=${workspaceId}`,+ fetcher,+ {+ keepPreviousData: true,+ },+ );++ return (+ <CustomerSalesTable+ sales={salesData}+ totalSales={+ isTotalSalesLoading ? undefined : totalSales?.sales ?? salesData?.length+ }+ viewAllHref={`/${slug}/events?event=sales&interval=all&customerId=${customerId}`}+ isLoading={isSalesLoading}+ />+ );+});diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/sales/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/sales/page.tsxnew file mode 100644index 0000000000..ac5fddcb5c--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/[customerId]/sales/page.tsx@@ -0,0 +1,5 @@+import { CustomerSalesPageClient } from "./page-client";++export default function CustomerSalesPage() {+ return <CustomerSalesPageClient />;+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/page-client.tsxnew file mode 100644index 0000000000..7fd142e825--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/page-client.tsx@@ -0,0 +1,14 @@+"use client";++import useWorkspace from "@/lib/swr/use-workspace";+import { CustomerTable } from "@/ui/customers/customer-table/customer-table";++export function CustomersPageClient() {+ const { defaultProgramId } = useWorkspace();+ return (+ <CustomerTable+ query={{ programId: defaultProgramId || undefined }}+ isProgramPage+ />+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/page.tsxnew file mode 100644index 0000000000..5f94bfd9d1--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/page.tsx@@ -0,0 +1,20 @@+import { PageContent } from "@/ui/layout/page-content";+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";+import { CustomersPageClient } from "./page-client";++export default function CustomersPage() {+ return (+ <PageContent+ title="Customers"+ titleInfo={{+ title:+ "Get deeper, real-time insights about your referred customers' demographics, purchasing behavior, and lifetime value (LTV).",+ href: "https://dub.co/help/article/customer-insights",+ }}+ >+ <PageWidthWrapper>+ <CustomersPageClient />+ </PageWidthWrapper>+ </PageContent>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/layout.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/layout.tsxindex f2d95a3a5b..4e94591d46 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/layout.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/layout.tsx@@ -61,11 +61,7 @@ export default function ProgramPartnerLayout({const searchParams = useSearchParams();const params = useParams() as { slug: string; partnerId: string };- const {- partner,- loading: isPartnerLoading,- error: partnerError,- } = usePartner({+ const { partner, error: partnerError } = usePartner({partnerId: params.partnerId,});diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/partner-nav.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/partner-nav.tsxindex ff6170bf47..85397a8b0f 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/partner-nav.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/partner-nav.tsx@@ -2,21 +2,17 @@import { usePartnerCommentsCount } from "@/lib/swr/use-partner-comments-count";import useWorkspace from "@/lib/swr/use-workspace";+import { PageNavTabs } from "@/ui/layout/page-nav-tabs";import {- ArrowUpRight2,Hyperlink,InvoiceDollar,LinesY,MoneyBills2,Msg,User,- useScrollProgress,} from "@dub/ui";-import { cn } from "@dub/utils";-import { LayoutGroup, motion } from "motion/react";-import Link from "next/link";import { useParams, usePathname } from "next/navigation";-import { useEffect, useId, useMemo, useRef } from "react";+import { useMemo } from "react";export function PartnerNav() {const pathname = usePathname();@@ -32,33 +28,6 @@ export function PartnerNav() {},);- const containerRef = useRef<HTMLDivElement>(null);- const layoutGroupId = useId();-- useEffect(() => {- if (!containerRef.current) return;-- const handleWheel = (event: WheelEvent) => {- if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) return;- event.preventDefault();-- containerRef.current?.scrollBy({- left: event.deltaY,- behavior: "smooth",- });- };-- containerRef.current.addEventListener("wheel", handleWheel);-- return () =>- containerRef.current?.removeEventListener("wheel", handleWheel);- }, []);-- const { scrollProgress, updateScrollProgress } = useScrollProgress(- containerRef,- { direction: "horizontal" },- );-const tabs = useMemo(() => [{@@ -90,7 +59,7 @@ export function PartnerNav() {[commentsCount],);- const quicklinks = useMemo(+ const quickLinks = useMemo(() => [{id: "analytics",@@ -109,78 +78,10 @@ export function PartnerNav() {);return (- <div className="relative z-0">- <div- ref={containerRef}- onScroll={updateScrollProgress}- className="scrollbar-hide relative z-0 flex items-center justify-between gap-1 overflow-x-auto p-2"- >- <LayoutGroup id={`${layoutGroupId}-tabs`}>- <motion.div- layout- className={cn("relative z-0 inline-flex items-center gap-1")}- >- {tabs.map(({ id, label, icon: Icon, badge }) => {- const isSelected = pathname.endsWith(`/${id}`);- return (- <Link- key={id}- href={`/${workspaceSlug}/program/partners/${partnerId}/${id}`}- data-selected={isSelected}- className={cn(- "text-content-emphasis relative z-10 flex items-center gap-2 px-2.5 py-1 text-sm font-medium",- !isSelected &&- "hover:text-content-subtle z-[11] transition-colors",- badge && "pr-1",- )}- >- <Icon className="size-4" />- <span>{label}</span>- {badge && (- <span className="rounded-md bg-blue-600 px-2 py-0.5 text-xs font-semibold text-white">- {badge}- </span>- )}- {isSelected && (- <motion.div- layoutId={layoutGroupId}- className={cn(- "border-border-subtle bg-bg-default absolute left-0 top-0 -z-[1] size-full rounded-lg border shadow-sm",- )}- transition={{ duration: 0.25 }}- />- )}- </Link>- );- })}- </motion.div>- </LayoutGroup>- <LayoutGroup id={`${layoutGroupId}-quicklinks`}>- <motion.div layout className="relative z-10 flex items-center gap-1">- {quicklinks.map(({ id, label, icon: Icon, href }) => {- return (- <Link- key={id}- href={href}- target="_blank"- className={cn(- "text-content-emphasis relative z-10 flex items-center gap-2 px-2.5 py-1 text-sm font-medium",- "hover:text-content-subtle z-[11] transition-colors",- )}- >- <Icon className="size-4" />- <span>{label}</span>- <ArrowUpRight2 className="text-content-subtle size-3.5" />- </Link>- );- })}- </motion.div>- </LayoutGroup>- </div>- <div- className="pointer-events-none absolute inset-y-0 -right-px w-16 bg-gradient-to-l from-neutral-100"- style={{ opacity: 1 - Math.pow(scrollProgress, 2) }}- />- </div>+ <PageNavTabs+ basePath={`/${workspaceSlug}/program/partners/${partnerId}`}+ tabs={tabs}+ quickLinks={quickLinks}+ />);}diff --git a/apps/web/lib/actions/partners/create-manual-commission.ts b/apps/web/lib/actions/partners/create-manual-commission.tsindex 1033f0bde9..c8e1d099b7 100644--- a/apps/web/lib/actions/partners/create-manual-commission.ts+++ b/apps/web/lib/actions/partners/create-manual-commission.ts@@ -326,6 +326,8 @@ export const createManualCommissionAction = authActionClient...customer,id: duplicateCustomerId,linkId: link.id,+ programId: link.programId,+ partnerId: link.partnerId,clickId: clickEventData.click_id,clickedAt: new Date(clickEventData.timestamp),country:diff --git a/apps/web/lib/api/conversions/track-lead.ts b/apps/web/lib/api/conversions/track-lead.tsindex 5872324a2e..ccede49092 100644--- a/apps/web/lib/api/conversions/track-lead.ts+++ b/apps/web/lib/api/conversions/track-lead.ts@@ -334,6 +334,17 @@ export const trackLead = async ({eventType: "lead",}),+ // update customer's program/partner associations+ prisma.customer.update({+ where: {+ id: customer.id,+ },+ data: {+ programId: link.programId,+ partnerId: link.partnerId,+ },+ }),+webhookPartner &&detectAndRecordFraudEvent({program: { id: link.programId },diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.tsindex d053845532..6b76d84b68 100644--- a/apps/web/lib/api/conversions/track-sale.ts+++ b/apps/web/lib/api/conversions/track-sale.ts@@ -521,21 +521,6 @@ const _trackSale = async ({},}),- // Update customer sales count- prisma.customer.update({- where: {- id: customer.id,- },- data: {- sales: {- increment: 1,- },- saleAmount: {- increment: amount,- },- },- }),-// Log conversion eventlogConversionEvent({workspace_id: workspace.id,@@ -622,6 +607,27 @@ const _trackSale = async ({data: webhookPayload,workspace,});++ // Update customer stats + program/partner associations+ await prisma.customer.update({+ where: {+ id: customer.id,+ },+ data: {+ ...(link.programId && {+ programId: link.programId,+ }),+ ...(link.partnerId && {+ partnerId: link.partnerId,+ }),+ sales: {+ increment: 1,+ },+ saleAmount: {+ increment: amount,+ },+ },+ });})(),);diff --git a/apps/web/lib/firstpromoter/import-customers.ts b/apps/web/lib/firstpromoter/import-customers.tsindex dedafe75d9..542ac6896f 100644--- a/apps/web/lib/firstpromoter/import-customers.ts+++ b/apps/web/lib/firstpromoter/import-customers.ts@@ -256,6 +256,8 @@ async function createCustomer({projectConnectId: workspace.stripeConnectId,clickId: clickEvent.click_id,linkId: link.id,+ programId: link.programId,+ partnerId: link.partnerId,country: clickEvent.country,clickedAt: new Date(customer.created_at),createdAt: new Date(customer.created_at),diff --git a/apps/web/lib/integrations/shopify/create-lead.ts b/apps/web/lib/integrations/shopify/create-lead.tsindex b12ca86a11..de652f464d 100644--- a/apps/web/lib/integrations/shopify/create-lead.ts+++ b/apps/web/lib/integrations/shopify/create-lead.ts@@ -1,6 +1,7 @@import { createId } from "@/lib/api/create-id";import { DubApiError } from "@/lib/api/errors";import { includeTags } from "@/lib/api/links/include-tags";+import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";import { generateRandomName } from "@/lib/names";import { getClickEvent, recordLead } from "@/lib/tinybird";import { sendWorkspaceWebhook } from "@/lib/webhook/publish";@@ -103,17 +104,37 @@ export async function createShopifyLead({]);waitUntil(- sendWorkspaceWebhook({- trigger: "lead.created",- workspace,- data: transformLeadEventData({- ...clickData,- eventName,- link,- customer,- metadata: null,+ Promise.allSettled([+ sendWorkspaceWebhook({+ trigger: "lead.created",+ workspace,+ data: transformLeadEventData({+ ...clickData,+ eventName,+ link,+ customer,+ metadata: null,+ }),}),- }),+ ...(link.programId && link.partnerId+ ? [+ syncPartnerLinksStats({+ partnerId: link.partnerId,+ programId: link.programId,+ eventType: "lead",+ }),+ prisma.customer.update({+ where: {+ id: customer.id,+ },+ data: {+ programId: link.programId,+ partnerId: link.partnerId,+ },+ }),+ ]+ : []),+ ]),);return leadData;diff --git a/apps/web/lib/middleware/utils/app-redirect.ts b/apps/web/lib/middleware/utils/app-redirect.tsindex 116d00f15b..6c6cefd605 100644--- a/apps/web/lib/middleware/utils/app-redirect.ts+++ b/apps/web/lib/middleware/utils/app-redirect.ts@@ -81,6 +81,20 @@ export const appRedirect = async (path: string) => {if (partnerPageRegex.test(path))return path.replace(partnerPageRegex, "/$1/program/partners/$2/links");+ // Redirect "/[slug]/customers/:customerId" to "/[slug]/customers/:customerId/sales"+ const customersPageRegex = /^\/([^\/]+)\/customers\/([^\/]+)$/;+ if (customersPageRegex.test(path))+ return path.replace(customersPageRegex, "/$1/customers/$2/sales");++ // Redirect "/[slug]/program/customers/:customerId" to "/[slug]/program/customers/:customerId/sales"+ const programCustomersPageRegex =+ /^\/([^\/]+)\/program\/customers\/([^\/]+)$/;+ if (programCustomersPageRegex.test(path))+ return path.replace(+ programCustomersPageRegex,+ "/$1/program/customers/$2/sales",+ );+// Handle additional simpler program redirectsconst programRedirect = Object.keys(PROGRAM_REDIRECTS).find((redirect) =>path.endsWith(redirect),diff --git a/apps/web/lib/partnerstack/import-customers.ts b/apps/web/lib/partnerstack/import-customers.tsindex 4721c81bed..9a9c706d50 100644--- a/apps/web/lib/partnerstack/import-customers.ts+++ b/apps/web/lib/partnerstack/import-customers.ts@@ -261,6 +261,8 @@ async function createCustomer({projectConnectId: workspace.stripeConnectId,clickId: clickEvent.click_id,linkId: link.id,+ programId: link.programId,+ partnerId: link.partnerId,country: clickEvent.country,clickedAt: new Date(customer.created_at),createdAt: new Date(customer.created_at),diff --git a/apps/web/lib/rewardful/import-customers.ts b/apps/web/lib/rewardful/import-customers.tsindex 3525946abd..d9c80fb920 100644--- a/apps/web/lib/rewardful/import-customers.ts+++ b/apps/web/lib/rewardful/import-customers.ts@@ -220,6 +220,8 @@ async function createCustomer({projectConnectId: workspace.stripeConnectId,clickId: clickEvent.click_id,linkId: link.id,+ programId: link.programId,+ partnerId: link.partnerId,country: clickEvent.country,clickedAt: new Date(referral.created_at),createdAt: new Date(referral.became_lead_at),diff --git a/apps/web/lib/swr/use-customer-activity.ts b/apps/web/lib/swr/use-customer-activity.tsnew file mode 100644index 0000000000..7105ea3255--- /dev/null+++ b/apps/web/lib/swr/use-customer-activity.ts@@ -0,0 +1,24 @@+import { fetcher } from "@dub/utils";+import useSWR from "swr";+import { CustomerActivityResponse } from "../types";+import useWorkspace from "./use-workspace";++export default function useCustomerActivity({+ customerId,+}: {+ customerId: string;+}) {+ const { id: workspaceId } = useWorkspace();+ const { data: customerActivity, isLoading: isCustomerActivityLoading } =+ useSWR<CustomerActivityResponse>(+ customerId &&+ workspaceId &&+ `/api/customers/${customerId}/activity?workspaceId=${workspaceId}`,+ fetcher,+ );++ return {+ customerActivity,+ isCustomerActivityLoading,+ };+}diff --git a/apps/web/lib/swr/use-customers-count.ts b/apps/web/lib/swr/use-customers-count.tsindex 5e42705b54..1661064abc 100644--- a/apps/web/lib/swr/use-customers-count.ts+++ b/apps/web/lib/swr/use-customers-count.ts@@ -21,7 +21,7 @@ export default function useCustomersCount<T = number>({`/api/customers/count${getQueryString({ workspaceId, ...query },{- include: ["linkId", "country", "search", "externalId"],+ include: ["country", "partnerId", "linkId", "externalId", "search"],},)}`,fetcher,diff --git a/apps/web/lib/swr/use-partner-customer.ts b/apps/web/lib/swr/use-partner-customer.tsindex a0bf0d4158..f7e7701dab 100644--- a/apps/web/lib/swr/use-partner-customer.ts+++ b/apps/web/lib/swr/use-partner-customer.ts@@ -10,7 +10,9 @@ export default function usePartnerCustomer({}) {const { programSlug } = useParams<{ programSlug: string }>();- const { data, isLoading } = useSWR<PartnerProfileCustomerProps>(+ const { data, isLoading } = useSWR<+ PartnerProfileCustomerProps & { name?: string | null }+ >(programSlug &&customerId &&`/api/partner-profile/programs/${programSlug}/customers/${customerId}`,diff --git a/apps/web/lib/tolt/import-customers.ts b/apps/web/lib/tolt/import-customers.tsindex ff15298d2e..f728f2371e 100644--- a/apps/web/lib/tolt/import-customers.ts+++ b/apps/web/lib/tolt/import-customers.ts@@ -234,6 +234,8 @@ async function createReferral({projectConnectId: workspace.stripeConnectId,clickId: clickEvent.click_id,linkId: link.id,+ programId: link.programId,+ partnerId: link.partnerId,country: clickEvent.country,clickedAt: new Date(customer.created_at),createdAt: new Date(customer.created_at),diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.tsindex a32190af12..824841d6d0 100644--- a/apps/web/lib/zod/schemas/customers.ts+++ b/apps/web/lib/zod/schemas/customers.ts@@ -38,6 +38,8 @@ export const getCustomersQuerySchema = z.describe("A filter on the list based on the customer's `linkId` field (the referral link ID).",),+ programId: z.string().optional().describe("Program ID to filter by."),+ partnerId: z.string().optional().describe("Partner ID to filter by."),includeExpandedFields: booleanQuerySchema.optional().describe(@@ -76,7 +78,7 @@ export const getCustomersCountQuerySchema = getCustomersQuerySchemasortBy: true,sortOrder: true,})- .extend({ groupBy: z.enum(["country", "linkId"]).optional() });+ .extend({ groupBy: z.enum(["country", "linkId", "partnerId"]).optional() });export const createCustomerBodySchema = z.object({email: z.string().email().nullish().describe("The customer's email address."),diff --git a/apps/web/scripts/migrations/backfill-customer-partner-ids.ts b/apps/web/scripts/migrations/backfill-customer-partner-ids.tsnew file mode 100644index 0000000000..485f2570b4--- /dev/null+++ b/apps/web/scripts/migrations/backfill-customer-partner-ids.ts@@ -0,0 +1,53 @@+import { prisma } from "@dub/prisma";+import { chunk } from "@dub/utils";+import "dotenv-flow/config";++async function main() {+ while (true) {+ const customers = await prisma.customer.findMany({+ where: {+ programId: null,+ link: {+ programId: {+ not: null,+ },+ },+ },+ select: {+ id: true,+ link: {+ select: {+ programId: true,+ partnerId: true,+ },+ },+ },+ take: 1000,+ });+ if (customers.length === 0) {+ console.log("No customers left to backfill");+ break;+ }++ console.log(`Found ${customers.length} customers to backfill`);++ const chunks = chunk(customers, 100);+ for (let i = 0; i < chunks.length; i++) {+ const chunk = chunks[i];+ console.log(`Backfilling chunk ${i + 1} of ${chunks.length}`);+ await Promise.all(+ chunk.map((customer) =>+ prisma.customer.update({+ where: { id: customer.id },+ data: {+ programId: customer.link?.programId,+ partnerId: customer.link?.partnerId,+ },+ }),+ ),+ );+ }+ }+}++main();diff --git a/apps/web/ui/analytics/events/metadata-viewer.tsx b/apps/web/ui/analytics/events/metadata-viewer.tsxindex 9077061745..541147abf4 100644--- a/apps/web/ui/analytics/events/metadata-viewer.tsx+++ b/apps/web/ui/analytics/events/metadata-viewer.tsx@@ -6,7 +6,7 @@ import { Fragment } from "react";// Display the event metadataexport function MetadataViewer({metadata,- previewItems = 3,+ previewItems = 2,}: {metadata: Record<string, any>;previewItems?: number;diff --git a/apps/web/ui/analytics/use-analytics-filters.tsx b/apps/web/ui/analytics/use-analytics-filters.tsxindex fae4b69d97..1870e0809a 100644--- a/apps/web/ui/analytics/use-analytics-filters.tsx+++ b/apps/web/ui/analytics/use-analytics-filters.tsx@@ -763,8 +763,8 @@ export function useAnalyticsFilters({) : null;},getOptionPermalink: () => {- return programSlug- ? `/programs/${programSlug}/customers/${selectedCustomerId}`+ return programPage+ ? `/${slug}/program/customers/${selectedCustomerId}`: slug? `/${slug}/customers/${selectedCustomerId}`: null;diff --git a/apps/web/ui/customers/customer-activity-list.tsx b/apps/web/ui/customers/customer-activity-list.tsxindex 5fdf629cb8..17ef1c5245 100644--- a/apps/web/ui/customers/customer-activity-list.tsx+++ b/apps/web/ui/customers/customer-activity-list.tsx@@ -117,7 +117,7 @@ export function CustomerActivityList({return isLoading ? (<div className="flex h-32 w-full animate-pulse rounded-lg border border-transparent bg-neutral-100" />) : !activity?.events?.length ? (- <div className="flex h-32 w-full items-center justify-center border border-neutral-200 text-xs text-neutral-500">+ <div className="flex h-32 w-full items-center justify-center rounded-lg border border-neutral-200 text-xs text-neutral-500">{activity?.events ? "No activity yet" : "Failed to load activity"}</div>) : (diff --git a/apps/web/ui/customers/customer-details-column.tsx b/apps/web/ui/customers/customer-details-column.tsxindex e6bf4e8fdd..177329b9bd 100644--- a/apps/web/ui/customers/customer-details-column.tsx+++ b/apps/web/ui/customers/customer-details-column.tsx@@ -1,7 +1,9 @@-import { CustomerActivityResponse, CustomerProps } from "@/lib/types";+import { CustomerActivityResponse, CustomerEnriched } from "@/lib/types";import {- CopyButton,CopyText,+ Envelope,+ Globe,+ Hyperlink,TimestampTooltip,UTM_PARAMETERS,} from "@dub/ui";@@ -9,9 +11,9 @@ import {capitalize,cn,COUNTRIES,- currencyFormatter,getParamsFromURL,getPrettyUrl,+ OG_AVATAR_URL,} from "@dub/utils";import { useParams } from "next/navigation";import { Fragment, HTMLProps, useMemo } from "react";@@ -22,19 +24,49 @@ export function CustomerDetailsColumn({customer,customerActivity,isCustomerActivityLoading,+ isProgramPage = false,+ workspaceSlug,}: {customer?: Omit<- CustomerProps,+ CustomerEnriched,"name" | "externalId" | "sales" | "saleAmount"> & {- name?: string;+ name?: string | null;externalId?: string;};customerActivity?: CustomerActivityResponse;isCustomerActivityLoading: boolean;+ isProgramPage?: boolean;+ workspaceSlug?: string;}) {- const { slug, programSlug } = useParams();+ const { programSlug } = useParams<{ programSlug: string }>();+ const basicFields = [+ ...(!customer || customer?.email+ ? [+ {+ id: "email",+ icon: <Envelope className="size-3.5 shrink-0" />,+ text: customer?.email,+ },+ ]+ : []),+ {+ id: "country",+ icon: customer?.country ? (+ <img+ alt={`Flag of ${COUNTRIES[customer.country]}`}+ src={`https://flag.vercel.app/m/${customer.country}.svg`}+ className="size-3.5 rounded-full"+ />+ ) : (+ <Globe className="size-3.5 shrink-0" />+ ),+ text: customer?.country ? COUNTRIES[customer.country] : "Planet Earth",+ },+ ];++ const partner = customer?.partner;const link = customerActivity?.link;const click = customerActivity?.events.find((e) => e.event === "click");@@ -49,178 +81,239 @@ export function CustomerDetailsColumn({}, [click?.url]);return (- <div className="grid grid-cols-1 gap-6 overflow-hidden whitespace-nowrap text-sm text-neutral-900 min-[320px]:grid-cols-2 lg:grid-cols-1">- <div className="flex flex-col gap-2">- <DetailHeading>Details</DetailHeading>- {customer ? (- customer.country && (- <ConditionalLink- href={`/${programSlug ? `programs/${programSlug}` : slug}/analytics?country=${encodeURIComponent(customer.country)}`}- target="_blank"- >- <div className="flex items-center gap-2">+ <div className="grid grid-cols-1 gap-6 overflow-hidden whitespace-nowrap text-sm text-neutral-900">+ <div className="border-border-subtle flex flex-col divide-y divide-neutral-200 rounded-xl border bg-white">+ <div className="p-4">+ <div className="flex items-start justify-between gap-2">+ <div className="relative w-fit">+ {customer ? (<img- src={`https://hatscripts.github.io/circle-flags/flags/${customer.country.toLowerCase()}.svg`}- alt=""- className="size-3.5 shrink-0"+ src={customer.avatar || `${OG_AVATAR_URL}${customer.id}`}+ alt={customer.id}+ className="size-10 rounded-full border border-neutral-100"/>- <span className="truncate">{COUNTRIES[customer.country]}</span>- </div>- </ConditionalLink>- )- ) : (- <div className="h-5 w-24 animate-pulse rounded-md bg-neutral-100" />- )}- {click- ? [- {- key: "device",- icon: (- <DeviceIcon- display={capitalize(click.device)!}- tab="devices"- className="size-3.5 shrink-0"- />- ),- value: click.device,- },- {- key: "browser",- icon: (- <DeviceIcon- display={capitalize(click.browser)!}- tab="browsers"- className="size-3.5 shrink-0"- />- ),- value: click.browser,- },- {- key: "os",- icon: (- <DeviceIcon- display={capitalize(click.os)!}- tab="os"- className="size-3.5 shrink-0"- />- ),- value: click.os,- },- ]- .filter(({ value }) => value)- .map(({ key, icon, value }) => (- <ConditionalLink- key={key}- href={- value === "Unknown"- ? undefined- : `/${programSlug ? `programs/${programSlug}` : slug}/analytics?${key}=${encodeURIComponent(value)}`- }- target="_blank"+ ) : (+ <div className="size-10 animate-pulse rounded-full bg-neutral-200" />+ )}+ </div>++ {customer ? (+ <div className="text-content-default bg-bg-emphasis rounded-md px-1 text-xs font-medium">+ Since{" "}+ <TimestampTooltip+ timestamp={customer.createdAt}+ rows={["local", "utc", "unix"]}+ side="left">- <span className="flex items-center gap-2">- {icon}- <span className="truncate">{value}</span>+ <span>+ {new Date(customer.createdAt).toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ })}</span>- </ConditionalLink>- ))- : (isCustomerActivityLoading || !customer) && (- <div className="h-5 w-12 animate-pulse rounded-md bg-neutral-100" />+ </TimestampTooltip>+ </div>+ ) : (+ <div className="h-5 w-24 animate-pulse rounded-md bg-neutral-100" />)}- </div>+ </div>- <div className="flex flex-col gap-2">- <DetailHeading>Customer since</DetailHeading>- {customer ? (- <TimestampTooltip- timestamp={customer.createdAt}- rows={["local"]}- side="left"- >- <span>- {new Date(customer.createdAt).toLocaleDateString("en-US", {- month: "short",- day: "numeric",- year: "numeric",- })}- </span>- </TimestampTooltip>- ) : (- <div className="h-5 w-12 animate-pulse rounded-md bg-neutral-100" />- )}- </div>+ <div className="mt-3">+ {customer ? (+ <div className="flex items-center gap-2">+ <span className="text-content-emphasis text-base font-semibold">+ {customer.name || customer.email}+ </span>+ </div>+ ) : (+ <div className="h-7 w-24 animate-pulse rounded bg-neutral-200" />+ )}+ </div>+ </div>- {customer?.externalId && (- <div className="flex flex-col gap-2">- <DetailHeading>External ID</DetailHeading>- {- <div className="flex items-center gap-1">- <CopyText value={customer.externalId} className="truncate">- {customer.externalId}- </CopyText>- <CopyButton- value={customer.externalId}- variant="neutral"- className="p-1 [&>*]:h-3 [&>*]:w-3"- successMessage="Copied external ID to clipboard!"- />- </div>- }+ <div className="flex flex-col gap-2 p-4">+ {basicFields+ .filter(({ text }) => text !== null)+ .map(({ id, icon, text }) => (+ <div key={id}>+ <div className="text-content-default flex items-center gap-1.5">+ {text !== undefined ? (+ <>+ {icon}+ <span className="min-w-0 truncate text-xs font-medium">+ {text}+ </span>+ </>+ ) : (+ <div className="h-4 w-24 animate-pulse rounded bg-neutral-200" />+ )}+ </div>+ </div>+ ))}</div>- )}- <div className="flex flex-col gap-2">- <DetailHeading>Lifetime value</DetailHeading>- {!customer || isCustomerActivityLoading ? (- <div className="h-5 w-12 animate-pulse rounded-md bg-neutral-100" />- ) : (- <span>- {customerActivity?.ltv !== undefined- ? currencyFormatter(customerActivity.ltv, {- trailingZeroDisplay: "stripIfInteger",- })- : "-"}- </span>- )}- </div>+ <div className="@md/page:grid-cols-2 @3xl/page:grid-cols-1 grid grid-cols-1 gap-5 p-4 text-xs">+ <div>+ <h2 className="text-content-emphasis text-sm font-semibold">+ Details+ </h2>++ <div className="mt-2.5 flex flex-col gap-5 text-xs">+ <div className="flex flex-col gap-2">+ {click+ ? [+ {+ key: "device",+ icon: (+ <DeviceIcon+ display={capitalize(click.device)!}+ tab="devices"+ className="size-3.5 shrink-0"+ />+ ),+ value: click.device,+ },+ {+ key: "browser",+ icon: (+ <DeviceIcon+ display={capitalize(click.browser)!}+ tab="browsers"+ className="size-3.5 shrink-0"+ />+ ),+ value: click.browser,+ },+ {+ key: "os",+ icon: (+ <DeviceIcon+ display={capitalize(click.os)!}+ tab="os"+ className="size-3.5 shrink-0"+ />+ ),+ value: click.os,+ },+ ]+ .filter(({ value }) => value)+ .map(({ key, icon, value }) => (+ <ConditionalLink+ key={key}+ href={+ value === "Unknown"+ ? undefined+ : `/${workspaceSlug || `programs/${programSlug}`}/${isProgramPage ? "program/" : ""}analytics?${key}=${encodeURIComponent(value)}`+ }+ target="_blank"+ >+ <span className="flex items-center gap-2">+ {icon}+ <span className="truncate">{value}</span>+ </span>+ </ConditionalLink>+ ))+ : (isCustomerActivityLoading || !customer) && (+ <div className="h-5 w-12 animate-pulse rounded-md bg-neutral-100" />+ )}+ </div>++ {customer?.externalId && (+ <div className="flex flex-col gap-2.5">+ <DetailHeading>External ID</DetailHeading>+ <div>+ <CopyText+ value={customer.externalId}+ className="truncate text-xs"+ >+ {customer.externalId}+ </CopyText>+ </div>+ </div>+ )}+ </div>+ </div>- <div className="flex flex-col gap-2">- <DetailHeading>Referral link</DetailHeading>- {!customer || isCustomerActivityLoading ? (- <div className="h-5 w-12 animate-pulse rounded-md bg-neutral-100" />- ) : link ? (- <ConditionalLink- href={- programSlug- ? `/programs/${programSlug}/analytics?domain=${link.domain}&key=${link.key}`- : `/${slug}/links/${link.domain}/${link.key}`- }- target="_blank"- className="min-w-0 overflow-hidden truncate"- >- {getPrettyUrl(link.shortLink)}- </ConditionalLink>- ) : (- <span>-</span>- )}+ {utmParams && Boolean(utmParams.length) && (+ <div className="flex flex-col gap-5 text-xs">+ <div className="flex flex-col gap-2.5">+ <DetailHeading>UTM</DetailHeading>+ <div className="grid w-full grid-cols-[min-content,minmax(0,1fr)] gap-x-4 gap-y-2 overflow-hidden">+ {utmParams.map(({ key, label, value }) => (+ <Fragment key={key}>+ <span className="truncate">{label}</span>+ <ConditionalLink+ href={+ workspaceSlug+ ? `/${workspaceSlug}/${isProgramPage ? "program/" : ""}analytics?${key}=${encodeURIComponent(value)}`+ : undefined+ }+ target="_blank"+ className="truncate text-neutral-500"+ >+ {value}+ </ConditionalLink>+ </Fragment>+ ))}+ </div>+ </div>+ </div>+ )}+ </div></div>- {utmParams && Boolean(utmParams.length) && (- <div className="flex flex-col gap-2">- <DetailHeading>UTM</DetailHeading>- <div className="grid w-full grid-cols-[min-content,minmax(0,1fr)] gap-x-4 gap-y-2 overflow-hidden">- {utmParams.map(({ key, label, value }) => (- <Fragment key={key}>- <span className="truncate">{label}</span>+ {(link || !customer) && (+ <div className="border-border-subtle rounded-lg border p-4">+ <h2 className="text-content-emphasis mb-2.5 text-sm font-semibold">+ Referral {partner ? "partner" : "link"}+ </h2>++ {partner && (+ <div className="mb-4 flex items-center gap-2">+ <img+ src={partner.image || `${OG_AVATAR_URL}${partner.id}`}+ alt=""+ className="size-5 rounded-full"+ />+ <ConditionalLink+ href={+ workspaceSlug+ ? `/${workspaceSlug}/program/partners/${partner.id}`+ : undefined+ }+ target="_blank"+ className="min-w-0 overflow-hidden truncate text-xs font-semibold"+ >+ {partner.name}+ </ConditionalLink>+ </div>+ )}++ <div className="flex flex-col gap-2 text-xs">+ {partner && <DetailHeading>Referral link</DetailHeading>}+ {!customer || isCustomerActivityLoading ? (+ <div className="h-5 w-12 animate-pulse rounded-md bg-neutral-100" />+ ) : link ? (+ <div className="flex items-center gap-1.5">+ <Hyperlink className="size-3.5 shrink-0" /><ConditionalLink- href={`/${programSlug ? `programs/${programSlug}` : slug}/analytics?${key}=${encodeURIComponent(value)}`}+ href={+ workspaceSlug+ ? `/${workspaceSlug}/links/${link.domain}/${link.key}`+ : programSlug+ ? `/programs/${programSlug}/analytics?domain=${encodeURIComponent(link.domain)}&key=${encodeURIComponent(link.key)}`+ : undefined+ }target="_blank"- className="truncate text-neutral-500"+ className="min-w-0 overflow-hidden truncate">- {value}+ {getPrettyUrl(link.shortLink)}</ConditionalLink>- </Fragment>- ))}+ </div>+ ) : (+ <span>-</span>+ )}</div></div>)}@@ -232,8 +325,8 @@ const DetailHeading = ({className,...rest}: HTMLProps<HTMLHeadingElement>) => (- <h2- className={cn("font-semibold text-neutral-900", className)}+ <h3+ className={cn("text-content-emphasis text-xs font-semibold", className)}{...rest}- ></h2>+ />);diff --git a/apps/web/ui/customers/customer-partner-earnings-table.tsx b/apps/web/ui/customers/customer-partner-earnings-table.tsxindex 550faf82ac..3f217e427a 100644--- a/apps/web/ui/customers/customer-partner-earnings-table.tsx+++ b/apps/web/ui/customers/customer-partner-earnings-table.tsx@@ -33,16 +33,12 @@ export function CustomerPartnerEarningsTable({{header: "Sale Amount",accessorKey: "amount",- cell: ({ getValue }) => (- <span>{currencyFormatter(getValue())}</span>- ),+ cell: ({ getValue }) => <span>{currencyFormatter(getValue())}</span>,},{header: "Commission",accessorKey: "earnings",- cell: ({ getValue }) => (- <span>{currencyFormatter(getValue())}</span>- ),+ cell: ({ getValue }) => <span>{currencyFormatter(getValue())}</span>,},{header: "Status",@@ -64,7 +60,7 @@ export function CustomerPartnerEarningsTable({return (<div className="overflow-x-auto">{isLoading ? (- <div className="flex h-32 w-full animate-pulse rounded-lg border border-transparent bg-neutral-100" />+ <div className="flex h-32 w-full animate-pulse border border-transparent bg-neutral-100" />) : !commissions?.length ? (<div className="border-border-subtle flex h-32 w-full items-center justify-center rounded-lg border text-xs text-neutral-500">{commissions?.length === 0@@ -80,7 +76,7 @@ export function CustomerPartnerEarningsTable({{headerGroup.headers.map((header) => (<thkey={header.id}- className="p-2 font-semibold text-neutral-900"+ className="px-4 py-3 font-semibold text-neutral-900">{header.isPlaceholder? null@@ -97,7 +93,7 @@ export function CustomerPartnerEarningsTable({{table.getRowModel().rows.map((row) => (<tr key={row.id}>{row.getVisibleCells().map((cell) => (- <td key={cell.id} className="truncate p-2">+ <td key={cell.id} className="truncate px-4 py-3">{flexRender(cell.column.columnDef.cell,cell.getContext(),@@ -108,7 +104,7 @@ export function CustomerPartnerEarningsTable({))}</tbody></table>- <div className="mt-2 flex items-center gap-1 px-2 text-sm text-neutral-600">+ <div className="flex items-center gap-1 px-4 py-3 text-sm text-neutral-600">{commissions.length} of<Ashref={viewAllHref ?? "#"}diff --git a/apps/web/ui/customers/customer-sales-table.tsx b/apps/web/ui/customers/customer-sales-table.tsxindex b6b4a658ff..6be0f54e9e 100644--- a/apps/web/ui/customers/customer-sales-table.tsx+++ b/apps/web/ui/customers/customer-sales-table.tsx@@ -58,9 +58,7 @@ export function CustomerSalesTable({{header: "Amount",accessorFn: (d) => ("saleAmount" in d ? d.saleAmount : d.amount),- cell: ({ getValue }) => (- <span>{currencyFormatter(getValue())}</span>- ),+ cell: ({ getValue }) => <span>{currencyFormatter(getValue())}</span>,},...(sales?.length && "earnings" in sales?.[0]? [@@ -95,7 +93,7 @@ export function CustomerSalesTable({{isLoading ? (<div className="flex h-32 w-full animate-pulse rounded-lg border border-transparent bg-neutral-100" />) : !sales?.length ? (- <div className="border-border-subtle flex h-32 w-full items-center justify-center rounded-lg border text-xs text-neutral-500">+ <div className="flex h-32 w-full items-center justify-center rounded-lg border border-transparent text-xs text-neutral-500">{sales?.length === 0 ? "No sales yet" : "Failed to load sales"}</div>) : (@@ -107,7 +105,7 @@ export function CustomerSalesTable({{headerGroup.headers.map((header) => (<thkey={header.id}- className="p-2 font-semibold text-neutral-900"+ className="px-4 py-3 font-semibold text-neutral-900">{header.isPlaceholder? null@@ -124,7 +122,7 @@ export function CustomerSalesTable({{table.getRowModel().rows.map((row) => (<tr key={row.id}>{row.getVisibleCells().map((cell) => (- <td key={cell.id} className="truncate p-2">+ <td key={cell.id} className="truncate px-4 py-3">{flexRender(cell.column.columnDef.cell,cell.getContext(),@@ -135,7 +133,7 @@ export function CustomerSalesTable({))}</tbody></table>- <div className="mt-2 flex items-center gap-1 px-2 text-sm text-neutral-600">+ <div className="flex items-center gap-1 px-4 py-3 text-sm text-neutral-600">{sales.length} of<Ashref={viewAllHref ?? "#"}diff --git a/apps/web/ui/customers/customer-stats.tsx b/apps/web/ui/customers/customer-stats.tsxnew file mode 100644index 0000000000..6143ebef72--- /dev/null+++ b/apps/web/ui/customers/customer-stats.tsx@@ -0,0 +1,119 @@+import useCustomerActivity from "@/lib/swr/use-customer-activity";+import { CustomerEnriched } from "@/lib/types";+import { TimestampTooltip } from "@dub/ui";+import { ArrowUpRight2 } from "@dub/ui/icons";+import {+ cn,+ currencyFormatter,+ formatDateTimeSmart,+ nFormatter,+} from "@dub/utils";+import { formatDistance } from "date-fns";+import Link from "next/link";+import { useParams } from "next/navigation";+import { CSSProperties, useMemo } from "react";++export function CustomerStats({+ customer,+}: {+ customer?: Pick<CustomerEnriched, "sales" | "saleAmount" | "createdAt">;+}) {+ const { customerId } = useParams<{ customerId: string }>();+ const { customerActivity, isCustomerActivityLoading } = useCustomerActivity({+ customerId,+ });++ const stats: {+ label: string;+ value?: string | React.ReactNode;+ href?: string;+ }[] = useMemo(+ () => [+ {+ label: "Time to sale",+ value:+ !customer || isCustomerActivityLoading+ ? undefined+ : customerActivity?.firstSaleDate+ ? formatDistance(+ customerActivity.firstSaleDate,+ customer.createdAt,+ )+ : "-",+ },+ {+ label: "First sale date",+ value:+ isCustomerActivityLoading ? undefined : customerActivity?.firstSaleDate ? (+ <TimestampTooltip+ timestamp={customerActivity.firstSaleDate}+ side="right"+ rows={["local", "utc"]}+ >+ <span className="hover:text-content-emphasis underline decoration-dotted underline-offset-2">+ {formatDateTimeSmart(customerActivity.firstSaleDate)}+ </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],+ );++ return (+ <div className="@container/stats">+ <div+ className={cn(+ "@xs/stats:grid-cols-[repeat(var(--cols),1fr)] grid grid-cols-1 ring-4 ring-black/5",+ "gap-px overflow-hidden rounded-xl border border-neutral-200 bg-neutral-200",+ )}+ style={+ {+ "--cols": stats.length,+ } as CSSProperties+ }+ >+ {stats.map(({ label, value, href }) => {+ const As = href ? Link : "div";+ return (+ <As+ key={label}+ href={href ?? "#"}+ target="_blank"+ className={cn(+ "group relative flex flex-col bg-white p-3",+ href && "transition-colors duration-150 hover:bg-neutral-50",+ )}+ >+ {href && (+ <ArrowUpRight2 className="text-content-subtle absolute right-3 top-3 size-3.5 opacity-50 transition-opacity duration-150 group-hover:opacity-100" />+ )}+ <span className="text-xs text-neutral-500">{label}</span>+ {value === undefined ? (+ <div className="h-5 w-16 animate-pulse rounded-md bg-neutral-200" />+ ) : (+ <span className="text-content-emphasis text-sm font-medium">+ {value}+ </span>+ )}+ </As>+ );+ })}+ </div>+ </div>+ );+}diff --git a/apps/web/ui/customers/customer-table/customer-table.tsx b/apps/web/ui/customers/customer-table/customer-table.tsxindex 054d32dc82..6a4049ec3b 100644--- a/apps/web/ui/customers/customer-table/customer-table.tsx+++ b/apps/web/ui/customers/customer-table/customer-table.tsx@@ -4,7 +4,9 @@ import { getPlanCapabilities } from "@/lib/plan-capabilities";import useCustomersCount from "@/lib/swr/use-customers-count";import useWorkspace from "@/lib/swr/use-workspace";import { CustomerProps } from "@/lib/types";+import { getCustomersQuerySchema } from "@/lib/zod/schemas/customers";import { CustomerRowItem } from "@/ui/customers/customer-row-item";+import { PartnerRowItem } from "@/ui/partners/partner-row-item";import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";import { FilterButtonTableRow } from "@/ui/shared/filter-button-table-row";import { SearchBoxPersisted } from "@/ui/shared/search-box";@@ -43,21 +45,23 @@ import Link from "next/link";import { useMemo, useState } from "react";import { toast } from "sonner";import useSWR from "swr";+import { z } from "zod";import { EXAMPLE_CUSTOMER_DATA } from "./example-data";import { useCustomerFilters } from "./use-customer-filters";-const customersColumns = {- all: ["customer", "country", "saleAmount", "createdAt", "link", "externalId"],- defaultVisible: ["customer", "country", "saleAmount", "createdAt", "link"],-};-type ColumnMeta = {filterParams?: (args: Pick<Cell<CustomerProps, any>, "getValue">,) => Record<string, any>;};-export function CustomerTable() {+export function CustomerTable({+ query,+ isProgramPage = false,+}: {+ query?: Partial<z.infer<typeof getCustomersQuerySchema>>;+ isProgramPage?: boolean;+}) {const { id: workspaceId, slug: workspaceSlug, plan } = useWorkspace();const { canManageCustomers } = getPlanCapabilities(plan);@@ -81,6 +85,7 @@ export function CustomerTable() {const { data: customersCount, error: countError } = useCustomersCount({enabled: canManageCustomers,+ query,});const {@@ -92,6 +97,7 @@ export function CustomerTable() {`/api/customers${getQueryString({workspaceId,includeExpandedFields: "true",+ ...query,})}`,fetcher,{@@ -99,8 +105,29 @@ export function CustomerTable() {},);+ const customersColumns = {+ all: [+ "customer",+ "country",+ ...(isProgramPage ? ["partner"] : []),+ "link",+ "saleAmount",+ "createdAt",+ "externalId",+ ],+ defaultVisible: [+ "customer",+ "country",+ ...(isProgramPage ? ["partner"] : ["link"]),+ "saleAmount",+ "createdAt",+ ],+ };+const { columnVisibility, setColumnVisibility } = useColumnVisibility(- "customers-table-columns",+ isProgramPage+ ? "program-customers-table-columns"+ : "customers-table-columns",customersColumns,);@@ -120,7 +147,11 @@ export function CustomerTable() {return (<CustomerRowItemcustomer={row.original}- href={`/${workspaceSlug}/customers/${row.original.id}`}+ href={+ isProgramPage+ ? `/${workspaceSlug}/program/customers/${row.original.id}`+ : `/${workspaceSlug}/customers/${row.original.id}`+ }chartActivityIconMode="visible"/>);@@ -157,6 +188,50 @@ export function CustomerTable() {);},},+ {+ id: "partner",+ header: "Partner",+ meta: {+ filterParams: ({ row }) => ({+ partnerId: row.original.partner.id,+ }),+ },+ cell: ({ row }) =>+ row.original.partner ? (+ <PartnerRowItem partner={row.original.partner} />+ ) : (+ "-"+ ),+ size: 200,+ },+ {+ id: "link",+ header: "Link",+ accessorKey: "link",+ meta: {+ filterParams: ({ getValue }) =>+ getValue() ? { linkId: getValue().id } : undefined,+ },+ cell: ({ row }) =>+ row.original.link ? (+ <Link+ href={`/${workspaceSlug}/links/${row.original.link.domain}/${row.original.link.key}`}+ target="_blank"+ className="flex cursor-alias items-center gap-3 decoration-dotted underline-offset-2 hover:underline"+ >+ <LinkLogo+ apexDomain={getApexDomain(row.original.link.url)}+ className="size-4 shrink-0 sm:size-4"+ />+ <span className="truncate" title={row.original.link.shortLink}>+ {getPrettyUrl(row.original.link.shortLink)}+ </span>+ </Link>+ ) : (+ "-"+ ),+ size: 250,+ },{id: "saleAmount",header: "Lifetime value",@@ -188,34 +263,6 @@ export function CustomerTable() {</TimestampTooltip>),},- {- id: "link",- header: "Link",- accessorKey: "link",- meta: {- filterParams: ({ getValue }) =>- getValue() ? { linkId: getValue().id } : undefined,- },- cell: ({ row }) =>- row.original.link ? (- <Link- href={`/${workspaceSlug}/links/${row.original.link.domain}/${row.original.link.key}`}- target="_blank"- className="flex cursor-alias items-center gap-3 decoration-dotted underline-offset-2 hover:underline"- >- <LinkLogo- apexDomain={getApexDomain(row.original.link.url)}- className="size-4 shrink-0 sm:size-4"- />- <span className="truncate" title={row.original.link.shortLink}>- {getPrettyUrl(row.original.link.shortLink)}- </span>- </Link>- ) : (- "-"- ),- size: 250,- },{id: "externalId",header: "External ID",@@ -244,7 +291,7 @@ export function CustomerTable() {cell: ({ row }) => <RowMenuButton row={row} />,},].filter((c) => c.id === "menu" || customersColumns.all.includes(c.id)),- [],+ [isProgramPage, workspaceSlug],);const { table, ...tableProps } = useTable({diff --git a/apps/web/ui/customers/customer-table/use-customer-filters.tsx b/apps/web/ui/customers/customer-table/use-customer-filters.tsxindex 31f9085e10..2bd3584899 100644--- a/apps/web/ui/customers/customer-table/use-customer-filters.tsx+++ b/apps/web/ui/customers/customer-table/use-customer-filters.tsx@@ -1,9 +1,18 @@import useCustomersCount from "@/lib/swr/use-customers-count";+import usePartners from "@/lib/swr/use-partners";import useWorkspace from "@/lib/swr/use-workspace";+import { EnrolledPartnerProps } from "@/lib/types";import { LinkLogo, useRouterStuff } from "@dub/ui";-import { FlagWavy, Hyperlink, SquareUserSparkle2 } from "@dub/ui/icons";-import { COUNTRIES, getApexDomain, getPrettyUrl, nFormatter } from "@dub/utils";-import { useCallback, useMemo } from "react";+import { FlagWavy, Hyperlink, SquareUserSparkle2, Users } from "@dub/ui/icons";+import {+ COUNTRIES,+ getApexDomain,+ getPrettyUrl,+ nFormatter,+ OG_AVATAR_URL,+} from "@dub/utils";+import { useCallback, useMemo, useState } from "react";+import { useDebounce } from "use-debounce";export function useCustomerFilters(extraSearchParams: Record<string, string>,@@ -12,6 +21,14 @@ export function useCustomerFilters(const { searchParamsObj, queryParams } = useRouterStuff();const { id: workspaceId, slug } = useWorkspace();+ const [selectedFilter, setSelectedFilter] = useState<string | null>(null);+ const [search, setSearch] = useState("");+ const [debouncedSearch] = useDebounce(search, 500);++ const { partners } = usePartnerFilterOptions(+ selectedFilter === "partnerId" ? debouncedSearch : "",+ );+const { data: countriesCount } = useCustomersCount<| {country: string;@@ -69,6 +86,26 @@ export function useCustomerFilters(}),},},+ {+ key: "partnerId",+ icon: Users,+ label: "Partner",+ shouldFilter: false,+ options:+ partners?.map(({ id, name, image }) => {+ return {+ value: id,+ label: name,+ icon: (+ <img+ src={image || `${OG_AVATAR_URL}${id}`}+ alt={`${name} image`}+ className="size-4 rounded-full"+ />+ ),+ };+ }) ?? null,+ },{key: "linkId",icon: Hyperlink,@@ -105,13 +142,14 @@ export function useCustomerFilters(},},],- [countriesCount, linksCount, slug],+ [partners, countriesCount, linksCount, slug],);const activeFilters = useMemo(() => {- const { country, linkId, externalId } = searchParamsObj;+ const { country, linkId, externalId, partnerId } = searchParamsObj;return [+ ...(partnerId ? [{ key: "partnerId", value: partnerId }] : []),...(country ? [{ key: "country", value: country }] : []),...(linkId ? [{ key: "linkId", value: linkId }] : []),...(externalId ? [{ key: "externalId", value: externalId }] : []),@@ -140,7 +178,7 @@ export function useCustomerFilters(const onRemoveAll = useCallback(() =>queryParams({- del: ["country", "linkId", "externalId", "search"],+ del: ["partnerId", "country", "linkId", "externalId", "search"],}),[queryParams],);@@ -171,5 +209,42 @@ export function useCustomerFilters(onRemoveAll,searchQuery,isFiltered,+ setSearch,+ setSelectedFilter,};}++function usePartnerFilterOptions(search: string) {+ const { searchParamsObj } = useRouterStuff();++ const { partners, loading: partnersLoading } = usePartners({+ query: { search },+ });++ const { partners: selectedPartners } = usePartners({+ query: {+ partnerIds: searchParamsObj.partnerId+ ? [searchParamsObj.partnerId]+ : undefined,+ },+ });++ const result = useMemo(() => {+ return partnersLoading ||+ // Consider partners loading if we can't find the currently filtered partner+ (searchParamsObj.partnerId &&+ ![...(selectedPartners ?? []), ...(partners ?? [])].some(+ (p) => p.id === searchParamsObj.partnerId,+ ))+ ? null+ : ([+ ...(partners ?? []),+ // Add selected partner to list if not already in partners+ ...(selectedPartners+ ?.filter((st) => !partners?.some((t) => t.id === st.id))+ ?.map((st) => ({ ...st, hideDuringSearch: true })) ?? []),+ ] as (EnrolledPartnerProps & { hideDuringSearch?: boolean })[]);+ }, [partnersLoading, partners, selectedPartners, searchParamsObj.partnerId]);++ return { partners: result };+}diff --git a/apps/web/ui/customers/customer-tabs.tsx b/apps/web/ui/customers/customer-tabs.tsxnew file mode 100644index 0000000000..dff1e99fbb--- /dev/null+++ b/apps/web/ui/customers/customer-tabs.tsx@@ -0,0 +1,48 @@+import useWorkspace from "@/lib/swr/use-workspace";+import { CustomerEnriched } from "@/lib/types";+import { MoneyBills2, Receipt2 } from "@dub/ui";+import { useParams } from "next/navigation";+import { useMemo } from "react";+import { PageNavTabs } from "../layout/page-nav-tabs";++export function CustomerTabs({+ customer,+ isProgramPage = false,+}: {+ customer?: Pick<CustomerEnriched, "programId" | "partner">;+ isProgramPage?: boolean;+}) {+ const { customerId } = useParams<{ customerId: string }>();+ const { slug: workspaceSlug } = useWorkspace();++ const tabs = useMemo(+ () => [+ {+ id: "sales",+ label: "Sales",+ icon: Receipt2,+ },+ ...(customer?.programId && customer.partner+ ? [+ {+ id: "earnings",+ label: "Partner earnings",+ icon: MoneyBills2,+ },+ ]+ : []),+ ],+ [customer?.programId, customer?.partner],+ );++ return (+ <PageNavTabs+ basePath={+ isProgramPage+ ? `/${workspaceSlug}/program/customers/${customerId}`+ : `/${workspaceSlug}/customers/${customerId}`+ }+ tabs={tabs}+ />+ );+}diff --git a/apps/web/ui/layout/page-nav-tabs.tsx b/apps/web/ui/layout/page-nav-tabs.tsxnew file mode 100644index 0000000000..d7fcd250ee--- /dev/null+++ b/apps/web/ui/layout/page-nav-tabs.tsx@@ -0,0 +1,141 @@+"use client";++import { ArrowUpRight2, Icon, useScrollProgress } from "@dub/ui";+import { cn } from "@dub/utils";+import { LayoutGroup, motion } from "motion/react";+import Link from "next/link";+import { usePathname } from "next/navigation";+import { useEffect, useId, useRef } from "react";++export type PageNavTabsTab = {+ id: string;+ label: string;+ icon: Icon;+ badge?: string | number;+};++export type PageNavTabsQuicklink = {+ id: string;+ label: string;+ icon: Icon;+ href: string;+};++export type PageNavTabsProps = {+ basePath: string;+ tabs: PageNavTabsTab[];+ quickLinks?: PageNavTabsQuicklink[];+};++export function PageNavTabs({ basePath, tabs, quickLinks }: PageNavTabsProps) {+ const pathname = usePathname();++ const containerRef = useRef<HTMLDivElement>(null);+ const layoutGroupId = useId();++ useEffect(() => {+ if (!containerRef.current) return;++ const handleWheel = (event: WheelEvent) => {+ if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) return;+ event.preventDefault();++ containerRef.current?.scrollBy({+ left: event.deltaY,+ behavior: "smooth",+ });+ };++ containerRef.current.addEventListener("wheel", handleWheel);++ return () =>+ containerRef.current?.removeEventListener("wheel", handleWheel);+ }, []);++ const { scrollProgress, updateScrollProgress } = useScrollProgress(+ containerRef,+ { direction: "horizontal" },+ );++ return (+ <div className="relative z-0">+ <div+ ref={containerRef}+ onScroll={updateScrollProgress}+ className="scrollbar-hide relative z-0 flex items-center justify-between gap-1 overflow-x-auto p-2"+ >+ <LayoutGroup id={`${layoutGroupId}-tabs`}>+ <motion.div+ layout+ className={cn("relative z-0 inline-flex items-center gap-1")}+ >+ {tabs.map(({ id, label, icon: Icon, badge }) => {+ const isSelected = pathname.endsWith(`/${id}`);+ return (+ <Link+ key={id}+ href={`${basePath}/${id}`}+ data-selected={isSelected}+ className={cn(+ "text-content-emphasis relative z-10 flex items-center gap-2 px-2.5 py-1 text-sm font-medium",+ !isSelected &&+ "hover:text-content-subtle z-[11] transition-colors",+ badge && "pr-1",+ )}+ >+ <Icon className="size-4" />+ <span>{label}</span>+ {badge && (+ <span className="rounded-md bg-blue-600 px-2 py-0.5 text-xs font-semibold text-white">+ {badge}+ </span>+ )}+ {isSelected && (+ <motion.div+ layoutId={layoutGroupId}+ className={cn(+ "border-border-subtle bg-bg-default absolute left-0 top-0 -z-[1] size-full rounded-lg border shadow-sm",+ )}+ transition={{ duration: 0.25 }}+ />+ )}+ </Link>+ );+ })}+ </motion.div>+ </LayoutGroup>++ {Boolean(quickLinks?.length) && (+ <LayoutGroup id={`${layoutGroupId}-quicklinks`}>+ <motion.div+ layout+ className="relative z-10 flex items-center gap-1"+ >+ {quickLinks!.map(({ id, label, icon: Icon, href }) => {+ return (+ <Link+ key={id}+ href={href}+ target="_blank"+ className={cn(+ "text-content-emphasis relative z-10 flex items-center gap-2 px-2.5 py-1 text-sm font-medium",+ "hover:text-content-subtle z-[11] transition-colors",+ )}+ >+ <Icon className="size-4" />+ <span>{label}</span>+ <ArrowUpRight2 className="text-content-subtle size-3.5" />+ </Link>+ );+ })}+ </motion.div>+ </LayoutGroup>+ )}+ </div>+ <div+ className="pointer-events-none absolute inset-y-0 -right-px w-16 bg-gradient-to-l from-neutral-100"+ style={{ opacity: 1 - Math.pow(scrollProgress, 2) }}+ />+ </div>+ );+}diff --git a/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx b/apps/web/ui/layout/sidebar/app-sidebar-nav.tsxindex 28090912b5..5b8e6bc57e 100644--- a/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx+++ b/apps/web/ui/layout/sidebar/app-sidebar-nav.tsx@@ -287,6 +287,11 @@ const NAV_AREAS: SidebarNavAreas<SidebarNavData> = {icon: LinesYStatic,href: `/${slug}/program/analytics`,},+ {+ name: "Customers",+ icon: UserCheck,+ href: `/${slug}/program/customers`,+ },{name: "Commissions",icon: InvoiceDollar,diff --git a/apps/web/ui/partners/fraud-risks/commissions-on-hold-table.tsx b/apps/web/ui/partners/fraud-risks/commissions-on-hold-table.tsxindex f6712996e5..3d1cda3077 100644--- a/apps/web/ui/partners/fraud-risks/commissions-on-hold-table.tsx+++ b/apps/web/ui/partners/fraud-risks/commissions-on-hold-table.tsx@@ -87,7 +87,7 @@ export function CommissionsOnHoldTable({row.original.customer ? (<CustomerRowItemcustomer={row.original.customer}- href={`/${slug}/customers/${row.original.customer.id}`}+ href={`/${slug}/program/customers/${row.original.customer.id}`}/>) : ("-"diff --git a/apps/web/ui/partners/fraud-risks/fraud-events-tables/fraud-matching-customer-email-table.tsx b/apps/web/ui/partners/fraud-risks/fraud-events-tables/fraud-matching-customer-email-table.tsxindex 9984497b17..86b6c9a1dd 100644--- a/apps/web/ui/partners/fraud-risks/fraud-events-tables/fraud-matching-customer-email-table.tsx+++ b/apps/web/ui/partners/fraud-risks/fraud-events-tables/fraud-matching-customer-email-table.tsx@@ -72,7 +72,7 @@ export function FraudMatchingCustomerEmailTable() {return (<Link- href={`/${workspaceSlug}/customers/${row.original.customer.id}`}+ href={`/${workspaceSlug}/program/customers/${row.original.customer.id}`}target="_blank"><Buttondiff --git a/apps/web/ui/partners/fraud-risks/fraud-events-tables/fraud-paid-traffic-detected-table.tsx b/apps/web/ui/partners/fraud-risks/fraud-events-tables/fraud-paid-traffic-detected-table.tsxindex beafaff241..8ba367345f 100644--- a/apps/web/ui/partners/fraud-risks/fraud-events-tables/fraud-paid-traffic-detected-table.tsx+++ b/apps/web/ui/partners/fraud-risks/fraud-events-tables/fraud-paid-traffic-detected-table.tsx@@ -84,7 +84,7 @@ export function FraudPaidTrafficDetectedTable() {row.original.customer ? (<CustomerRowItemcustomer={row.original.customer}- href={`/${workspaceSlug}/customers/${row.original.customer.id}`}+ href={`/${workspaceSlug}/program/customers/${row.original.customer.id}`}chartActivityIconMode="hidden"/>) : (diff --git a/packages/prisma/schema/customer.prisma b/packages/prisma/schema/customer.prismaindex 28fff85124..9de38e5754 100644--- a/packages/prisma/schema/customer.prisma+++ b/packages/prisma/schema/customer.prisma@@ -16,20 +16,27 @@ model Customer {projectId StringprojectConnectId String?- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)- link Link? @relation(fields: [linkId], references: [id])- commissions Commission[]- fraudEvents FraudEvent[]+ programId String?+ partnerId String?++ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ link Link? @relation(fields: [linkId], references: [id])+ program Program? @relation(fields: [programId], references: [id])+ partner Partner? @relation(fields: [partnerId], references: [id])+ programEnrollment ProgramEnrollment? @relation(fields: [programId, partnerId], references: [programId, partnerId])+ commissions Commission[]+ fraudEvents FraudEvent[]@@unique([projectId, externalId])@@unique([projectConnectId, externalId])@@index([projectId, email])@@index([projectId, createdAt])@@index([projectId, saleAmount])- @@index(externalId)+ @@index([programId, partnerId])@@index(linkId)@@index(country)@@fulltext([email, name]) // For full-text searchdiff --git a/packages/prisma/schema/partner.prisma b/packages/prisma/schema/partner.prismaindex ede7ccbb61..e0140cf8e4 100644--- a/packages/prisma/schema/partner.prisma+++ b/packages/prisma/schema/partner.prisma@@ -65,6 +65,7 @@ model Partner {programs ProgramEnrollment[]users PartnerUser[]invites PartnerInvite[]+ customers Customer[]payouts Payout[]commissions Commission[]bountySubmissions BountySubmission[]diff --git a/packages/prisma/schema/program.prisma b/packages/prisma/schema/program.prismaindex 59378f2ce1..af20e95698 100644--- a/packages/prisma/schema/program.prisma+++ b/packages/prisma/schema/program.prisma@@ -63,6 +63,7 @@ model Program {invoices Invoice[]applications ProgramApplication[]links Link[]+ customers Customer[]commissions Commission[]rewards Reward[]discounts Discount[] @relation("ProgramDiscounts")@@ -129,6 +130,7 @@ model ProgramEnrollment {partner Partner @relation(fields: [partnerId], references: [id], onUpdate: Cascade, onDelete: Cascade)program Program @relation(fields: [programId], references: [id], onUpdate: Cascade, onDelete: Cascade)links Link[]+ customers Customer[]partnerGroup PartnerGroup? @relation(fields: [groupId], references: [id])application ProgramApplication? @relation(fields: [applicationId], references: [id])clickReward Reward? @relation("ClickRewardEnrollments", fields: [clickRewardId], references: [id])diff --git a/packages/ui/src/timestamp-tooltip.tsx b/packages/ui/src/timestamp-tooltip.tsxindex e526945c2a..5d4250337a 100644--- a/packages/ui/src/timestamp-tooltip.tsx+++ b/packages/ui/src/timestamp-tooltip.tsx@@ -148,56 +148,58 @@ function TimestampTooltipContent({<span className="text-content-subtle cursor-default">{relative}</span>)}<table>- {items.map((row, idx) => (- <tr- key={idx}- className={cn(- interactive &&- "before:bg-bg-emphasis relative select-none before:absolute before:-inset-x-1 before:inset-y-0 before:rounded before:opacity-0 before:content-[''] hover:cursor-copy hover:before:opacity-60 active:before:opacity-100",- )}- onClick={- interactive- ? async () => {- try {- await navigator.clipboard.writeText(row.value);- toast.success(- `Copied ${row.successMessageLabel} to clipboard`,- );- } catch (e) {- toast.error(- `Failed to copy ${row.successMessageLabel} to clipboard`,- );- console.error(- `Failed to copy ${row.successMessageLabel} to clipboard`,- e,- );+ <tbody>+ {items.map((row, idx) => (+ <tr+ key={idx}+ className={cn(+ interactive &&+ "before:bg-bg-emphasis relative select-none before:absolute before:-inset-x-1 before:inset-y-0 before:rounded before:opacity-0 before:content-[''] hover:cursor-copy hover:before:opacity-60 active:before:opacity-100",+ )}+ onClick={+ interactive+ ? async () => {+ try {+ await navigator.clipboard.writeText(row.value);+ toast.success(+ `Copied ${row.successMessageLabel} to clipboard`,+ );+ } catch (e) {+ toast.error(+ `Failed to copy ${row.successMessageLabel} to clipboard`,+ );+ console.error(+ `Failed to copy ${row.successMessageLabel} to clipboard`,+ e,+ );+ }}- }- : undefined- }- >- <td className="relative py-0.5">- <span+ : undefined+ }+ >+ <td className="relative py-0.5">+ <span+ className={cn(+ "text-content-subtle truncate",+ shortLabels && "bg-bg-inverted/10 rounded px-1 font-mono",+ )}+ title={shortLabels ? row.label : undefined}+ >+ {shortLabels ? row.shortLabel : row.label}+ </span>+ </td>+ <tdclassName={cn(- "text-content-subtle truncate",- shortLabels && "bg-bg-inverted/10 rounded px-1 font-mono",+ "text-content-default relative whitespace-nowrap py-0.5 pl-3",+ shortLabels && "pl-2",+ row.valueMono && "font-mono",)}- title={shortLabels ? row.label : undefined}>- {shortLabels ? row.shortLabel : row.label}- </span>- </td>- <td- className={cn(- "text-content-default relative whitespace-nowrap py-0.5 pl-3",- shortLabels && "pl-2",- row.valueMono && "font-mono",- )}- >- {row.value}- </td>- </tr>- ))}+ {row.value}+ </td>+ </tr>+ ))}+ </tbody></table></div>);