Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add partner customer page

Tim Wilson34affc90b995
diff --git a/apps/web/app/api/customers/[id]/activity/route.ts b/apps/web/app/api/customers/[id]/activity/route.ts
index 64fdb7f565..95645768b9 100644
--- a/apps/web/app/api/customers/[id]/activity/route.ts
+++ b/apps/web/app/api/customers/[id]/activity/route.ts
@@ -1,6 +1,5 @@
import { getCustomerEvents } from "@/lib/analytics/get-customer-events";
import { getCustomerOrThrow } from "@/lib/api/customers/get-customer-or-throw";
-import { transformCustomer } from "@/lib/api/customers/transform-customer";
import { decodeLinkIfCaseSensitive } from "@/lib/api/links/case-sensitivity";
import { withWorkspace } from "@/lib/auth";
import { verifyFolderAccess } from "@/lib/folder/permissions";
@@ -94,7 +93,6 @@ export const GET = withWorkspace(async ({ workspace, params, session }) => {
ltv,
timeToLead,
timeToSale,
- customer: transformCustomer(customer),
events,
link,
}),
diff --git a/apps/web/app/api/partner-profile/programs/[programId]/customers/[customerId]/activity/route.ts b/apps/web/app/api/partner-profile/programs/[programId]/customers/[customerId]/activity/route.ts
new file mode 100644
index 0000000000..07a3116fa7
--- /dev/null
+++ b/apps/web/app/api/partner-profile/programs/[programId]/customers/[customerId]/activity/route.ts
@@ -0,0 +1,274 @@
+import { getCustomerEvents } from "@/lib/analytics/get-customer-events";
+import { determineCustomerDiscount } from "@/lib/api/customers/determine-customer-discount";
+import { getCustomerOrThrow } from "@/lib/api/customers/get-customer-or-throw";
+import { transformCustomer } from "@/lib/api/customers/transform-customer";
+import { DubApiError } from "@/lib/api/errors";
+import { decodeLinkIfCaseSensitive } from "@/lib/api/links/case-sensitivity";
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import { withPartnerProfile } from "@/lib/auth/partner";
+import { customerActivityResponseSchema } from "@/lib/zod/schemas/customer-activity";
+import {
+ CustomerEnrichedSchema,
+ CustomerSchema,
+ getCustomersQuerySchema,
+ updateCustomerBodySchema,
+} from "@/lib/zod/schemas/customers";
+import { prisma } from "@dub/prisma";
+import { Discount } from "@prisma/client";
+import { NextResponse } from "next/server";
+
+// GET /api/partner-profile/programs/:programId/customers/:customerId/activity – Get a customer's activity by ID
+export const GET = withPartnerProfile(
+ async ({ partner, params }) => {
+ const { customerId, programId } = params;
+
+ const { program } = await getProgramEnrollmentOrThrow({
+ partnerId: partner.id,
+ programId: programId,
+ });
+
+ const customer = await prisma.customer.findUnique({
+ where: {
+ id: customerId,
+ },
+ include: {
+ link: {
+ include: {
+ programEnrollment: {
+ include: {
+ partner: true,
+ program: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (
+ !customer ||
+ ![
+ customer?.link?.programEnrollment?.programId,
+ customer?.link?.programEnrollment?.program.slug,
+ ].includes(program.id)
+ ) {
+ throw new DubApiError({
+ code: "not_found",
+ message:
+ "Customer not found. Make sure you're using the correct customer ID (e.g. `cus_3TagGjzRzmsFJdH8od2BNCsc`).",
+ });
+ }
+
+ if (!customer.linkId) {
+ return NextResponse.json(
+ customerActivityResponseSchema.parse({
+ customer,
+ events: [],
+ ltv: 0,
+ timeToLead: null,
+ timeToSale: null,
+ link: null,
+ }),
+ );
+ }
+
+ let [events, link] = await Promise.all([
+ getCustomerEvents(
+ { customerId: customer.id, clickId: customer.clickId },
+ {
+ sortOrder: "desc",
+ interval: "1y",
+ },
+ ),
+
+ prisma.link.findUniqueOrThrow({
+ where: {
+ id: customer.linkId!,
+ },
+ select: {
+ id: true,
+ domain: true,
+ key: true,
+ shortLink: true,
+ folderId: true,
+ },
+ }),
+ ]);
+
+ link = decodeLinkIfCaseSensitive(link);
+
+ // Find the LTV of the customer
+ // TODO: Calculate this from all events, not limited
+ const ltv = events.reduce((acc, event) => {
+ if (event.event === "sale" && event.saleAmount) {
+ acc += Number(event.saleAmount);
+ }
+
+ return acc;
+ }, 0);
+
+ // Find the time to lead of the customer
+ const timeToLead =
+ customer.clickedAt && customer.createdAt
+ ? customer.createdAt.getTime() - customer.clickedAt.getTime()
+ : null;
+
+ // Find the time to first sale of the customer
+ // TODO: Calculate this from all events, not limited
+ const firstSale = events.filter(({ event }) => event === "sale").pop();
+
+ const timeToSale =
+ firstSale && customer.createdAt
+ ? new Date(firstSale.timestamp).getTime() - customer.createdAt.getTime()
+ : null;
+
+ return NextResponse.json(
+ customerActivityResponseSchema.parse({
+ ltv,
+ timeToLead,
+ timeToSale,
+ events,
+ link,
+ }),
+ );
+ },
+ {
+ requiredPlan: [
+ "business",
+ "business plus",
+ "business extra",
+ "business max",
+ "advanced",
+ "enterprise",
+ ],
+ },
+);
+
+// PATCH /api/customers/:id – Update a customer by ID
+export const PATCH = withWorkspace(
+ async ({ workspace, params, req, searchParams }) => {
+ const { id } = params;
+ const { includeExpandedFields } =
+ getCustomersQuerySchema.parse(searchParams);
+
+ const { name, email, avatar, externalId } = updateCustomerBodySchema.parse(
+ await parseRequestBody(req),
+ );
+
+ const customer = await getCustomerOrThrow(
+ {
+ id,
+ workspaceId: workspace.id,
+ },
+ {
+ includeExpandedFields,
+ },
+ );
+
+ try {
+ const updatedCustomer = await prisma.customer.update({
+ where: {
+ id: customer.id,
+ },
+ data: {
+ name,
+ email,
+ avatar,
+ externalId,
+ },
+ });
+
+ let discount: Discount | null = null;
+
+ if (includeExpandedFields) {
+ const firstPurchase = await prisma.commission.findFirst({
+ where: {
+ customerId: customer.id,
+ type: "sale",
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ select: {
+ createdAt: true,
+ },
+ });
+
+ discount = determineCustomerDiscount({
+ customerLink: customer.link,
+ firstPurchase,
+ });
+ }
+
+ const responseSchema = includeExpandedFields
+ ? CustomerEnrichedSchema
+ : CustomerSchema;
+
+ return NextResponse.json(
+ responseSchema.parse(
+ transformCustomer({
+ ...customer,
+ ...updatedCustomer,
+ ...(includeExpandedFields ? { discount } : {}),
+ }),
+ ),
+ );
+ } catch (error) {
+ if (error.code === "P2002") {
+ throw new DubApiError({
+ code: "conflict",
+ message: "A customer with this external ID already exists.",
+ });
+ }
+
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: error.message,
+ });
+ }
+ },
+ {
+ requiredPlan: [
+ "business",
+ "business plus",
+ "business extra",
+ "business max",
+ "advanced",
+ "enterprise",
+ ],
+ },
+);
+
+// DELETE /api/customers/:id – Delete a customer by ID
+export const DELETE = withWorkspace(
+ async ({ workspace, params }) => {
+ const { id } = params;
+
+ const customer = await getCustomerOrThrow({
+ id,
+ workspaceId: workspace.id,
+ });
+
+ await prisma.customer.delete({
+ where: {
+ id: customer.id,
+ },
+ });
+
+ return NextResponse.json({
+ id: customer.id,
+ });
+ },
+ {
+ requiredPlan: [
+ "business",
+ "business plus",
+ "business extra",
+ "business max",
+ "advanced",
+ "enterprise",
+ ],
+ },
+);
diff --git a/apps/web/app/api/partner-profile/programs/[programId]/customers/[customerId]/route.ts b/apps/web/app/api/partner-profile/programs/[programId]/customers/[customerId]/route.ts
new file mode 100644
index 0000000000..6c60023700
--- /dev/null
+++ b/apps/web/app/api/partner-profile/programs/[programId]/customers/[customerId]/route.ts
@@ -0,0 +1,218 @@
+import { determineCustomerDiscount } from "@/lib/api/customers/determine-customer-discount";
+import { getCustomerOrThrow } from "@/lib/api/customers/get-customer-or-throw";
+import { transformCustomer } from "@/lib/api/customers/transform-customer";
+import { DubApiError } from "@/lib/api/errors";
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import { withPartnerProfile } from "@/lib/auth/partner";
+import {
+ CustomerEnrichedSchema,
+ CustomerSchema,
+ getCustomersQuerySchema,
+ updateCustomerBodySchema,
+} from "@/lib/zod/schemas/customers";
+import { PartnerProfileCustomerSchema } from "@/lib/zod/schemas/partner-profile";
+import { prisma } from "@dub/prisma";
+import { Discount } from "@prisma/client";
+import { NextResponse } from "next/server";
+
+// GET /api/partner-profile/programs/:programId/customers/:customerId – Get a customer by ID
+export const GET = withPartnerProfile(
+ async ({ partner, params }) => {
+ const { customerId, programId } = params;
+
+ const { program } = await getProgramEnrollmentOrThrow({
+ partnerId: partner.id,
+ programId: programId,
+ });
+
+ const customer = await prisma.customer.findUnique({
+ where: {
+ id: customerId,
+ },
+ include: {
+ link: {
+ include: {
+ programEnrollment: {
+ include: {
+ partner: true,
+ program: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (
+ !customer ||
+ ![
+ customer?.link?.programEnrollment?.programId,
+ customer?.link?.programEnrollment?.program.slug,
+ ].includes(program.id)
+ ) {
+ throw new DubApiError({
+ code: "not_found",
+ message:
+ "Customer not found. Make sure you're using the correct customer ID (e.g. `cus_3TagGjzRzmsFJdH8od2BNCsc`).",
+ });
+ }
+
+ customer.avatar = null;
+ customer.email;
+
+ return NextResponse.json(
+ PartnerProfileCustomerSchema.parse(
+ transformCustomer({
+ ...customer,
+ link: customer.link
+ ? {
+ ...customer.link,
+ programEnrollment: customer.link.programEnrollment
+ ? { ...customer.link.programEnrollment, program: undefined }
+ : null,
+ }
+ : null,
+ }),
+ ),
+ );
+ },
+ {
+ requiredPlan: [
+ "business",
+ "business plus",
+ "business extra",
+ "business max",
+ "advanced",
+ "enterprise",
+ ],
+ },
+);
+
+// PATCH /api/customers/:id – Update a customer by ID
+export const PATCH = withWorkspace(
+ async ({ workspace, params, req, searchParams }) => {
+ const { id } = params;
+ const { includeExpandedFields } =
+ getCustomersQuerySchema.parse(searchParams);
+
+ const { name, email, avatar, externalId } = updateCustomerBodySchema.parse(
+ await parseRequestBody(req),
+ );
+
+ const customer = await getCustomerOrThrow(
+ {
+ id,
+ workspaceId: workspace.id,
+ },
+ {
+ includeExpandedFields,
+ },
+ );
+
+ try {
+ const updatedCustomer = await prisma.customer.update({
+ where: {
+ id: customer.id,
+ },
+ data: {
+ name,
+ email,
+ avatar,
+ externalId,
+ },
+ });
+
+ let discount: Discount | null = null;
+
+ if (includeExpandedFields) {
+ const firstPurchase = await prisma.commission.findFirst({
+ where: {
+ customerId: customer.id,
+ type: "sale",
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ select: {
+ createdAt: true,
+ },
+ });
+
+ discount = determineCustomerDiscount({
+ customerLink: customer.link,
+ firstPurchase,
+ });
+ }
+
+ const responseSchema = includeExpandedFields
+ ? CustomerEnrichedSchema
+ : CustomerSchema;
+
+ return NextResponse.json(
+ responseSchema.parse(
+ transformCustomer({
+ ...customer,
+ ...updatedCustomer,
+ ...(includeExpandedFields ? { discount } : {}),
+ }),
+ ),
+ );
+ } catch (error) {
+ if (error.code === "P2002") {
+ throw new DubApiError({
+ code: "conflict",
+ message: "A customer with this external ID already exists.",
+ });
+ }
+
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: error.message,
+ });
+ }
+ },
+ {
+ requiredPlan: [
+ "business",
+ "business plus",
+ "business extra",
+ "business max",
+ "advanced",
+ "enterprise",
+ ],
+ },
+);
+
+// DELETE /api/customers/:id – Delete a customer by ID
+export const DELETE = withWorkspace(
+ async ({ workspace, params }) => {
+ const { id } = params;
+
+ const customer = await getCustomerOrThrow({
+ id,
+ workspaceId: workspace.id,
+ });
+
+ await prisma.customer.delete({
+ where: {
+ id: customer.id,
+ },
+ });
+
+ return NextResponse.json({
+ id: customer.id,
+ });
+ },
+ {
+ requiredPlan: [
+ "business",
+ "business plus",
+ "business extra",
+ "business max",
+ "advanced",
+ "enterprise",
+ ],
+ },
+);
diff --git a/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/customers/[customerId]/page-client.tsx b/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/customers/[customerId]/page-client.tsx
new file mode 100644
index 0000000000..2b75b8ca4c
--- /dev/null
+++ b/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/customers/[customerId]/page-client.tsx
@@ -0,0 +1,127 @@
+"use client";
+
+import {
+ CustomerActivityResponse,
+ CustomerEnriched,
+ 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 { BackLink } from "@/ui/shared/back-link";
+import { User } from "@dub/ui";
+import { fetcher } from "@dub/utils";
+import { notFound, useParams } from "next/navigation";
+import { memo } from "react";
+import useSWR from "swr";
+
+export function ProgramCustomerPageClient() {
+ const { programSlug, customerId } = useParams<{
+ programSlug: string;
+ customerId: string;
+ }>();
+
+ const {
+ data: customer,
+ isLoading,
+ error,
+ } = useSWR<CustomerEnriched>(
+ `/api/partner-profile/programs/${programSlug}/customers/${customerId}`,
+ fetcher,
+ );
+
+ const { data: customerActivity, isLoading: isCustomerActivityLoading } =
+ useSWR<CustomerActivityResponse>(
+ customer &&
+ `/api/partner-profile/programs/${programSlug}/customers/${customer.id}/activity`,
+ fetcher,
+ );
+
+ if (!customer && !isLoading && !error) notFound();
+
+ return (
+ <div className="mb-10 mt-2">
+ <BackLink href={`/${programSlug}/earnings`}>Earnings</BackLink>
+ <div className="mt-5 flex items-center gap-4">
+ <div className="border-border-subtle flex size-12 items-center justify-center rounded-full border bg-gradient-to-t from-neutral-50">
+ <User className="size-4 text-neutral-700" />
+ </div>
+
+ <div className="flex flex-col gap-1">
+ {customer ? (
+ 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" />
+ )}
+ </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">
+ Earnings
+ </h2>
+ <EarningsTable customerId={customerId} />
+ </section>
+
+ <section className="flex flex-col">
+ <h2 className="py-3 text-lg font-semibold text-neutral-900">
+ Activity
+ </h2>
+ <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 EarningsTable = memo(({ customerId }: { customerId: string }) => {
+ const { programSlug } = useParams();
+
+ const { data: earningsData, isLoading: isEarningsLoading } = useSWR<
+ PartnerEarningsResponse[]
+ >(
+ `/api/partner-profile/programs/${programSlug}/earnings?interval=all&pageSize=8&customerId=${customerId}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ const { data: totalEarnings, isLoading: isTotalEarningsLoading } = useSWR<{
+ count: number;
+ }>(
+ `/api/partner-profile/programs/${programSlug}/earnings/count?interval=all&customerId=${customerId}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ return (
+ <CustomerSalesTable
+ sales={earningsData}
+ totalSales={totalEarnings?.count}
+ viewAllHref={`/programs/${programSlug}/earnings?interval=all&customerId=${customerId}`}
+ isLoading={isEarningsLoading || isTotalEarningsLoading}
+ />
+ );
+});
diff --git a/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/customers/[customerId]/page.tsx b/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/customers/[customerId]/page.tsx
new file mode 100644
index 0000000000..4982498f9d
--- /dev/null
+++ b/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/customers/[customerId]/page.tsx
@@ -0,0 +1,13 @@
+import { PageContent } from "@/ui/layout/page-content";
+import { MaxWidthWrapper } from "@dub/ui";
+import { ProgramCustomerPageClient } from "./page-client";
+
+export default function ProgramCustomer() {
+ return (
+ <PageContent hideReferButton>
+ <MaxWidthWrapper className="flex flex-col gap-6">
+ <ProgramCustomerPageClient />
+ </MaxWidthWrapper>
+ </PageContent>
+ );
+}
diff --git a/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/earnings/earnings-table.tsx b/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/earnings/earnings-table.tsx
index 14e903b37f..a67d6f3d57 100644
--- a/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/earnings/earnings-table.tsx
+++ b/apps/web/app/partners.dub.co/(dashboard)/programs/[programSlug]/earnings/earnings-table.tsx
@@ -26,6 +26,8 @@ import {
getPrettyUrl,
} from "@dub/utils";
import { Cell } from "@tanstack/react-table";
+import Link from "next/link";
+import { useParams } from "next/navigation";
import useSWR from "swr";
type ColumnMeta = {
@@ -35,6 +37,7 @@ type ColumnMeta = {
};
export function EarningsTablePartner({ limit }: { limit?: number }) {
+ const { programSlug } = useParams();
const { programEnrollment } = useProgramEnrollment();
const { queryParams, searchParamsObj, getQueryString } = useRouterStuff();
@@ -120,16 +123,18 @@ export function EarningsTablePartner({ limit }: { limit?: number }) {
id: "customer",
header: "Customer",
accessorKey: "customer",
- meta: {
- filterParams: ({ getValue }) =>
- getValue()
- ? {
- customerId: getValue().id,
- }
- : {},
- },
cell: ({ row }) =>
- row.original.customer ? row.original.customer.email : "-",
+ row.original.customer ? (
+ <Link
+ href={`/programs/${programSlug}/customers/${row.original.customer.id}`}
+ scroll={false}
+ className="flex w-full items-center justify-between gap-2 px-4 py-2.5 transition-colors hover:bg-stone-100"
+ >
+ {row.original.customer.email}
+ </Link>
+ ) : (
+ "-"
+ ),
size: 250,
},
{
@@ -202,6 +207,7 @@ export function EarningsTablePartner({ limit }: { limit?: number }) {
enableColumnResizing: true,
}),
rowCount: earningsCount?.count || 0,
+ tdClassName: (columnId) => (columnId === "customer" ? "p-0" : ""),
emptyState: (
<AnimatedEmptyState
title="No earnings found"
diff --git a/apps/web/lib/api/customers/transform-customer.ts b/apps/web/lib/api/customers/transform-customer.ts
index dcd291b301..e57414e768 100644
--- a/apps/web/lib/api/customers/transform-customer.ts
+++ b/apps/web/lib/api/customers/transform-customer.ts
@@ -13,8 +13,8 @@ export interface CustomerWithLink extends Customer {
programEnrollment?:
| (ProgramEnrollment & {
partner: Partner;
- discount: Discount | null;
- program: {
+ discount?: Discount | null;
+ program?: {
defaultDiscount: Discount;
};
})
diff --git a/apps/web/lib/zod/schemas/customer-activity.ts b/apps/web/lib/zod/schemas/customer-activity.ts
index 5a5500293a..9bceb6862e 100644
--- a/apps/web/lib/zod/schemas/customer-activity.ts
+++ b/apps/web/lib/zod/schemas/customer-activity.ts
@@ -1,6 +1,5 @@
import { z } from "zod";
import { clickEventResponseSchema } from "./clicks";
-import { CustomerSchema } from "./customers";
import { leadEventResponseSchema } from "./leads";
import { LinkSchema } from "./links";
import { saleEventResponseSchema } from "./sales";
@@ -16,11 +15,6 @@ export const customerActivityResponseSchema = z.object({
timeToLead: z.number().nullable(),
timeToSale: z.number().nullable(),
events: z.array(customerActivityEventSchema),
- customer: CustomerSchema.merge(
- z.object({
- country: z.string().nullish(),
- }),
- ),
link: LinkSchema.pick({
id: true,
domain: true,
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index 733d3ab54a..7b4b6d60b7 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -8,6 +8,7 @@ import {
getCommissionsCountQuerySchema,
getCommissionsQuerySchema,
} from "./commissions";
+import { CustomerEnrichedSchema } from "./customers";
import { LinkSchema } from "./links";
export const PartnerEarningsSchema = CommissionResponseSchema.omit({
@@ -79,3 +80,14 @@ export const PartnerProfileLinkSchema = LinkSchema.pick({
}).extend({
createdAt: z.string().or(z.date()),
});
+
+export const PartnerProfileCustomerSchema = CustomerEnrichedSchema.pick({
+ id: true,
+ createdAt: true,
+ country: true,
+ link: true,
+}).extend({
+ email: z
+ .string()
+ .transform((email) => email.replace(/(?<=^.).+(?=.@)/, "********")),
+});
diff --git a/apps/web/ui/customers/customer-details-column.tsx b/apps/web/ui/customers/customer-details-column.tsx
index ae672c156b..abdc5cdaa3 100644
--- a/apps/web/ui/customers/customer-details-column.tsx
+++ b/apps/web/ui/customers/customer-details-column.tsx
@@ -26,11 +26,6 @@ export function CustomerDetailsColumn({
const link = customerActivity?.link;
const click = customerActivity?.events.find((e) => e.event === "click");
- // TODO: Remove
- if (click)
- click.url =
- "https://dub.co/brand?utm_source=dub&utm_medium=referral&utm_campaign=brand";
-
const utmParams = useMemo(() => {
if (!click?.url) return null;
const allParams = getParamsFromURL(click.url);
diff --git a/apps/web/ui/customers/customer-sales-table.tsx b/apps/web/ui/customers/customer-sales-table.tsx
index 4701455f41..dfaf84061b 100644
--- a/apps/web/ui/customers/customer-sales-table.tsx
+++ b/apps/web/ui/customers/customer-sales-table.tsx
@@ -1,4 +1,5 @@
-import { SaleEvent } from "@/lib/types";
+import { PartnerEarningsResponse, SaleEvent } from "@/lib/types";
+import { StatusBadge } from "@dub/ui";
import { currencyFormatter } from "@dub/utils";
import {
flexRender,
@@ -6,6 +7,7 @@ import {
useReactTable,
} from "@tanstack/react-table";
import Link from "next/link";
+import { CommissionStatusBadges } from "../partners/commission-status-badges";
export function CustomerSalesTable({
sales,
@@ -13,17 +15,29 @@ export function CustomerSalesTable({
isLoading,
viewAllHref,
}: {
- sales?: Pick<SaleEvent, "timestamp" | "eventName" | "saleAmount">[];
+ sales?:
+ | Pick<SaleEvent, "timestamp" | "eventName" | "saleAmount">[]
+ | Pick<
+ PartnerEarningsResponse,
+ "createdAt" | "amount" | "earnings" | "status"
+ >[];
totalSales?: number;
isLoading?: boolean;
viewAllHref?: string;
}) {
- const table = useReactTable({
+ const table = useReactTable<
+ | Pick<SaleEvent, "timestamp" | "eventName" | "saleAmount">
+ | Pick<
+ PartnerEarningsResponse,
+ "createdAt" | "amount" | "earnings" | "status"
+ >
+ >({
data: sales || [],
columns: [
{
header: "Date",
- accessorFn: (d) => new Date(d.timestamp),
+ accessorFn: (d) =>
+ new Date("timestamp" in d ? d.timestamp : d.createdAt),
enableHiding: false,
minSize: 100,
cell: ({ getValue }) => (
@@ -38,13 +52,17 @@ export function CustomerSalesTable({
</span>
),
},
- {
- header: "Event",
- accessorKey: "eventName",
- },
+ ...(sales?.length && "eventName" in sales?.[0]
+ ? [
+ {
+ header: "Event",
+ accessorKey: "eventName",
+ },
+ ]
+ : []),
{
header: "Amount",
- accessorKey: "saleAmount",
+ accessorFn: (d) => ("saleAmount" in d ? d.saleAmount : d.amount),
cell: ({ getValue }) => (
<span>
{currencyFormatter(getValue() / 100, {
@@ -54,6 +72,34 @@ export function CustomerSalesTable({
</span>
),
},
+ ...(sales?.length && "earnings" in sales?.[0]
+ ? [
+ {
+ header: "Earnings",
+ 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(),
});