The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add partner earnings table
Tim Wilsonf8fbc638ff86
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/[customerId]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/[customerId]/page-client.tsxindex 70ecb7b984..17f0880528 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/[customerId]/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/customers/[customerId]/page-client.tsx@@ -2,13 +2,20 @@import useCustomer from "@/lib/swr/use-customer";import useWorkspace from "@/lib/swr/use-workspace";-import { CustomerActivityResponse, SaleEvent } from "@/lib/types";+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 { CopyButton } from "@dub/ui";+import { ArrowUpRight, CopyButton } from "@dub/ui";import { DICEBEAR_AVATAR_URL, fetcher } from "@dub/utils";+import Link from "next/link";import { notFound, useParams } from "next/navigation";import { memo } from "react";import useSWR from "swr";@@ -21,12 +28,12 @@ export function CustomerPageClient() {data: customer,isLoading,error,- } = useCustomer({+ } = useCustomer<CustomerEnriched>({customerId,query: { includeExpandedFields: true },});- let { data: customerActivity, isLoading: isCustomerActivityLoading } =+ const { data: customerActivity, isLoading: isCustomerActivityLoading } =useSWR<CustomerActivityResponse>(customer &&`/api/customers/${customer.id}/activity?workspaceId=${workspaceId}`,@@ -79,18 +86,66 @@ export function CustomerPageClient() {<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">- <h2 className="text-lg font-semibold text-neutral-900">Sales</h2>+ <section className="flex flex-col">+ <h2 className="py-3 text-lg font-semibold text-neutral-900">+ Sales+ </h2><SalesTable customerId={customerId} /></section>- <section className="flex flex-col gap-4">- <h2 className="text-lg font-semibold text-neutral-900">Activity</h2>+ <section className="flex flex-col">+ <h2 className="py-3 text-lg font-semibold text-neutral-900">+ Activity+ </h2><CustomerActivityListactivity={customerActivity}isLoading={!customer || isCustomerActivityLoading}/></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}/programs/${customer.programId}/partners?partnerId=${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 ||+ `${DICEBEAR_AVATAR_URL}${customer.partner.name}`+ }+ alt={customer.partner.name}+ className="size-8 rounded-full"+ />+ }+ <div className="min-w-0">+ <span className="block truncate text-base 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>+ )}</div>{/* Right side details */}@@ -137,3 +192,31 @@ const SalesTable = memo(({ customerId }: { customerId: string }) => {/>);});++const PartnerEarningsTable = memo(+ ({ programId, customerId }: { programId: string; customerId: string }) => {+ const { id: workspaceId, slug } = useWorkspace();++ const { data: commissions, isLoading: isComissionsLoading } = useSWR<+ CommissionResponse[]+ >(+ `/api/programs/${programId}/commissions?customerId=${customerId}&workspaceId=${workspaceId}&pageSize=8`,+ fetcher,+ );++ const { data: totalCommissions, isLoading: isTotalCommissionsLoading } =+ useSWR<{ all: { count: number } }>(+ `/api/programs/${programId}/commissions/count?customerId=${customerId}&workspaceId=${workspaceId}`,+ fetcher,+ );++ return (+ <CustomerPartnerEarningsTable+ commissions={commissions}+ totalCommissions={totalCommissions?.all?.count}+ viewAllHref={`/${slug}/programs/${programId}/commissions?customerId=${customerId}`}+ isLoading={isComissionsLoading || isTotalCommissionsLoading}+ />+ );+ },+);diff --git a/apps/web/lib/api/customers/transform-customer.ts b/apps/web/lib/api/customers/transform-customer.tsindex 15f4705f47..dcd291b301 100644--- a/apps/web/lib/api/customers/transform-customer.ts+++ b/apps/web/lib/api/customers/transform-customer.ts@@ -31,6 +31,7 @@ export const transformCustomer = (customer: CustomerWithLink) => {...customer,name: customer.name || customer.email || generateRandomName(),link: customer.link || undefined,+ programId: programEnrollment?.programId || undefined,partner: programEnrollment?.partner || undefined,};};diff --git a/apps/web/lib/swr/use-customer.ts b/apps/web/lib/swr/use-customer.tsindex 4162f6b322..494de68a07 100644--- a/apps/web/lib/swr/use-customer.ts+++ b/apps/web/lib/swr/use-customer.ts@@ -1,7 +1,7 @@import { fetcher } from "@dub/utils";import useSWR from "swr";import { z } from "zod";-import { CustomerProps } from "../types";+import { CustomerEnriched, CustomerProps } from "../types";import { getCustomersQuerySchema } from "../zod/schemas/customers";import useWorkspace from "./use-workspace";@@ -9,18 +9,20 @@ const partialQuerySchema = getCustomersQuerySchema.pick({includeExpandedFields: true,});-export default function useCustomer({+export default function useCustomer<+ T extends CustomerProps | CustomerEnriched = CustomerProps,+>({customerId,query,enabled = true,}: {- customerId: CustomerProps["id"];+ customerId: T["id"];query?: z.infer<typeof partialQuerySchema>;enabled?: boolean;}) {const { id: workspaceId } = useWorkspace();- const { data, error, isLoading } = useSWR<CustomerProps>(+ const { data, error, isLoading } = useSWR<T>(enabled && workspaceId? `/api/customers/${customerId}?${new URLSearchParams({workspaceId: workspaceId,diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.tsindex de1ee4ee65..2d94d5d623 100644--- a/apps/web/lib/zod/schemas/customers.ts+++ b/apps/web/lib/zod/schemas/customers.ts@@ -73,6 +73,7 @@ export const CustomerEnrichedSchema = CustomerSchema.extend({shortLink: true,programId: true,}).nullish(),+ programId: z.string().nullish(),partner: PartnerSchema.pick({id: true,name: true,diff --git a/apps/web/ui/customers/customer-partner-earnings-table.tsx b/apps/web/ui/customers/customer-partner-earnings-table.tsxnew file mode 100644index 0000000000..a5c93b160c--- /dev/null+++ b/apps/web/ui/customers/customer-partner-earnings-table.tsx@@ -0,0 +1,145 @@+import { CommissionResponse } from "@/lib/types";+import { StatusBadge } from "@dub/ui";+import { currencyFormatter } from "@dub/utils";+import {+ flexRender,+ getCoreRowModel,+ useReactTable,+} from "@tanstack/react-table";+import Link from "next/link";+import { CommissionStatusBadges } from "../partners/commission-status-badges";++export function CustomerPartnerEarningsTable({+ commissions,+ totalCommissions,+ isLoading,+ viewAllHref,+}: {+ commissions?: CommissionResponse[];+ totalCommissions?: number;+ isLoading?: boolean;+ viewAllHref?: string;+}) {+ const table = useReactTable({+ data: commissions || [],+ columns: [+ {+ header: "Date",+ accessorFn: (d) => new Date(d.createdAt),+ enableHiding: false,+ minSize: 100,+ cell: ({ getValue }) => (+ <span>+ {getValue().toLocaleTimeString("en-US", {+ month: "short",+ day: "numeric",+ hour: "numeric",+ minute: "numeric",+ hour12: true,+ })}+ </span>+ ),+ },+ {+ header: "Sale Amount",+ accessorKey: "amount",+ cell: ({ getValue }) => (+ <span>+ {currencyFormatter(getValue() / 100, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}+ </span>+ ),+ },+ {+ header: "Commission",+ accessorKey: "earnings",+ cell: ({ getValue }) => (+ <span>+ {currencyFormatter(getValue() / 100, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}+ </span>+ ),+ },+ {+ header: "Status",+ cell: ({ row }) => {+ const badge = CommissionStatusBadges[row.original.status];++ return (+ <StatusBadge icon={null} variant={badge.variant}>+ {badge.label}+ </StatusBadge>+ );+ },+ },+ ],+ getCoreRowModel: getCoreRowModel(),+ });++ return (+ <div className="overflow-x-auto">+ {isLoading ? (+ <div className="flex h-32 w-full animate-pulse rounded-lg 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+ ? "No earnings yet"+ : "Failed to load earnings"}+ </div>+ ) : (+ <>+ <table className="[&_tr]:border-border-subtle w-full overflow-hidden text-left text-sm [&_tr]:border-b">+ <thead>+ {table.getHeaderGroups().map((headerGroup) => (+ <tr key={headerGroup.id}>+ {headerGroup.headers.map((header) => (+ <th+ key={header.id}+ className="p-2 font-semibold text-neutral-900"+ >+ {header.isPlaceholder+ ? null+ : flexRender(+ header.column.columnDef.header,+ header.getContext(),+ )}+ </th>+ ))}+ </tr>+ ))}+ </thead>+ <tbody className="text-neutral-600">+ {table.getRowModel().rows.map((row) => (+ <tr key={row.id}>+ {row.getVisibleCells().map((cell) => (+ <td key={cell.id} className="truncate p-2">+ {flexRender(+ cell.column.columnDef.cell,+ cell.getContext(),+ )}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ {commissions?.length && totalCommissions && viewAllHref && (+ <div className="mt-2 px-2 text-sm text-neutral-600">+ {commissions.length} of{" "}+ <Link+ href={viewAllHref}+ className="font-medium text-neutral-700 hover:text-neutral-900"+ >+ {totalCommissions} results+ </Link>+ </div>+ )}+ </>+ )}+ </div>+ );+}