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.

Partners Customers Page (#3302)

Tim Wilsondbc430a5ba35
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/count/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/count/route.ts
new file mode 100644
index 0000000000..8b4d3e8440
--- /dev/null
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/count/route.ts
@@ -0,0 +1,131 @@
+import { DubApiError } from "@/lib/api/errors";
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { withPartnerProfile } from "@/lib/auth/partner";
+import {
+ LARGE_PROGRAM_IDS,
+ LARGE_PROGRAM_MIN_TOTAL_COMMISSIONS_CENTS,
+} from "@/lib/constants/partner-profile";
+import { getPartnerCustomersCountQuerySchema } from "@/lib/zod/schemas/partner-profile";
+import { prisma, sanitizeFullTextSearch } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import { NextResponse } from "next/server";
+
+// GET /api/partner-profile/programs/:programId/customers/count – Get customer counts grouped by a field
+export const GET = withPartnerProfile(
+ async ({ partner, params, searchParams }) => {
+ const { programId } = params;
+ const { search, country, linkId, groupBy } =
+ getPartnerCustomersCountQuerySchema.parse(searchParams);
+
+ const { program, totalCommissions, customerDataSharingEnabledAt } =
+ await getProgramEnrollmentOrThrow({
+ partnerId: partner.id,
+ programId: programId,
+ include: {
+ program: true,
+ },
+ });
+
+ if (
+ LARGE_PROGRAM_IDS.includes(program.id) &&
+ totalCommissions < LARGE_PROGRAM_MIN_TOTAL_COMMISSIONS_CENTS
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "This feature is not available for your program.",
+ });
+ }
+
+ const commonWhere: Prisma.CustomerWhereInput = {
+ partnerId: partner.id,
+ programId: program.id,
+ projectId: program.workspaceId,
+ // Only filter by country if not grouping by country
+ ...(country &&
+ groupBy !== "country" && {
+ country,
+ }),
+ // Only filter by linkId if not grouping by linkId
+ ...(linkId &&
+ groupBy !== "linkId" && {
+ linkId,
+ }),
+ // Only allow search if customer data sharing is enabled
+ ...(search && customerDataSharingEnabledAt
+ ? search.includes("@")
+ ? { email: search }
+ : {
+ email: { search: sanitizeFullTextSearch(search) },
+ name: { search: sanitizeFullTextSearch(search) },
+ }
+ : {}),
+ };
+
+ // Get customer count by country
+ if (groupBy === "country") {
+ const data = await prisma.customer.groupBy({
+ by: ["country"],
+ where: { ...commonWhere, country: { not: null } },
+ _count: true,
+ orderBy: {
+ _count: {
+ country: "desc",
+ },
+ },
+ });
+
+ return NextResponse.json(data);
+ }
+
+ // Get customer count by linkId
+ if (groupBy === "linkId") {
+ const data = await prisma.customer.groupBy({
+ by: ["linkId"],
+ where: { ...commonWhere, linkId: { not: null } },
+ _count: true,
+ orderBy: {
+ _count: {
+ linkId: "desc",
+ },
+ },
+ take: 10000,
+ });
+
+ const links = await prisma.link.findMany({
+ where: {
+ id: { in: data.map(({ linkId }) => linkId!) },
+ },
+ select: {
+ id: true,
+ domain: true,
+ key: true,
+ shortLink: true,
+ url: true,
+ },
+ });
+
+ const enrichedData = data
+ .map((d) => {
+ const link = links.find(({ id }) => id === d.linkId);
+ if (!link) return null;
+ return {
+ ...d,
+ domain: link.domain,
+ key: link.key,
+ shortLink: link.shortLink,
+ url: link.url,
+ };
+ })
+ .filter(Boolean);
+
+ return NextResponse.json(enrichedData);
+ }
+
+ // If no groupBy, return total count
+ const count = await prisma.customer.count({
+ where: commonWhere,
+ });
+
+ return NextResponse.json(count);
+ },
+);
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/route.ts
new file mode 100644
index 0000000000..224c74a98d
--- /dev/null
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/route.ts
@@ -0,0 +1,115 @@
+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 { withPartnerProfile } from "@/lib/auth/partner";
+import {
+ LARGE_PROGRAM_IDS,
+ LARGE_PROGRAM_MIN_TOTAL_COMMISSIONS_CENTS,
+} from "@/lib/constants/partner-profile";
+import { generateRandomName } from "@/lib/names";
+import {
+ PartnerProfileCustomerSchema,
+ getPartnerCustomersQuerySchema,
+} from "@/lib/zod/schemas/partner-profile";
+import { prisma, sanitizeFullTextSearch } from "@dub/prisma";
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+// GET /api/partner-profile/programs/:programId/customers – Get all customers for a partner program
+export const GET = withPartnerProfile(
+ async ({ partner, params, searchParams }) => {
+ const { programId } = params;
+ const { search, country, linkId, sortBy, sortOrder, page, pageSize } =
+ getPartnerCustomersQuerySchema.parse(searchParams);
+
+ const { program, totalCommissions, customerDataSharingEnabledAt } =
+ await getProgramEnrollmentOrThrow({
+ partnerId: partner.id,
+ programId: programId,
+ include: {
+ program: true,
+ },
+ });
+
+ if (
+ LARGE_PROGRAM_IDS.includes(program.id) &&
+ totalCommissions < LARGE_PROGRAM_MIN_TOTAL_COMMISSIONS_CENTS
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "This feature is not available for your program.",
+ });
+ }
+
+ // Get all customers with their first commission date in a single optimized query
+ const customers = await prisma.customer.findMany({
+ where: {
+ partnerId: partner.id,
+ programId: program.id,
+ projectId: program.workspaceId,
+ ...(country && { country }),
+ ...(linkId && { linkId }),
+ // Only allow search if customer data sharing is enabled
+ ...(search && customerDataSharingEnabledAt
+ ? search.includes("@")
+ ? { email: search }
+ : {
+ email: { search: sanitizeFullTextSearch(search) },
+ name: { search: sanitizeFullTextSearch(search) },
+ }
+ : {}),
+ },
+ include: {
+ link: true,
+ commissions: {
+ where: {
+ partnerId: partner.id,
+ },
+ take: 1,
+ orderBy: {
+ createdAt: "asc",
+ },
+ select: {
+ createdAt: true,
+ },
+ },
+ },
+ orderBy: {
+ [sortBy]: sortOrder,
+ },
+ skip: (page - 1) * pageSize,
+ take: pageSize,
+ });
+
+ // Map customers with their data
+ const customersWithData = customers.map((customer) => {
+ const timeToLead =
+ customer.clickedAt && customer.createdAt
+ ? customer.createdAt.getTime() - customer.clickedAt.getTime()
+ : null;
+
+ return PartnerProfileCustomerSchema.extend({
+ ...(customerDataSharingEnabledAt && { name: z.string().nullish() }),
+ }).parse({
+ ...transformCustomer({
+ ...customer,
+ email: customer.email
+ ? customerDataSharingEnabledAt
+ ? customer.email
+ : customer.email.replace(/(?<=^.).+(?=.@)/, "****")
+ : customer.name || generateRandomName(),
+ }),
+ activity: {
+ ltv: customer.saleAmount,
+ timeToLead,
+ timeToSale: null,
+ firstSaleDate: customer.commissions[0]?.createdAt ?? null,
+ events: [],
+ link: customer.link,
+ },
+ });
+ });
+
+ return NextResponse.json(customersWithData);
+ },
+);
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/page-client.tsx
new file mode 100644
index 0000000000..684cc0d109
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/page-client.tsx
@@ -0,0 +1,260 @@
+"use client";
+
+import { PARTNER_CUSTOMERS_MAX_PAGE_SIZE } from "@/lib/constants/partner-profile";
+import usePartnerCustomers from "@/lib/swr/use-partner-customers";
+import usePartnerCustomersCount from "@/lib/swr/use-partner-customers-count";
+import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
+import { CustomerRowItem } from "@/ui/customers/customer-row-item";
+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
+import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
+import { SearchBoxPersisted } from "@/ui/shared/search-box";
+import {
+ AnimatedSizeContainer,
+ Filter,
+ LinkLogo,
+ Table,
+ TimestampTooltip,
+ useColumnVisibility,
+ usePagination,
+ useRouterStuff,
+ useTable,
+} from "@dub/ui";
+import { User } from "@dub/ui/icons";
+import {
+ COUNTRIES,
+ currencyFormatter,
+ formatDate,
+ getApexDomain,
+ getPrettyUrl,
+} from "@dub/utils";
+import Link from "next/link";
+import { useParams } from "next/navigation";
+import { useMemo } from "react";
+import { usePartnerCustomerFilters } from "./use-partner-customer-filters";
+
+export function ProgramCustomersPageClient() {
+ const { searchParams, queryParams } = useRouterStuff();
+
+ const { programSlug } = useParams<{ programSlug: string }>();
+ const { programEnrollment } = useProgramEnrollment();
+
+ const { data: customersCount, error: countError } =
+ usePartnerCustomersCount();
+ const { data: customers, isLoading, error } = usePartnerCustomers();
+
+ const { pagination, setPagination } = usePagination(
+ PARTNER_CUSTOMERS_MAX_PAGE_SIZE,
+ );
+
+ const sortBy = searchParams.get("sortBy") || "createdAt";
+ const sortOrder = searchParams.get("sortOrder") === "asc" ? "asc" : "desc";
+
+ const {
+ filters,
+ activeFilters,
+ onSelect,
+ onRemove,
+ onRemoveAll,
+ isFiltered,
+ setSelectedFilter,
+ } = usePartnerCustomerFilters();
+
+ const customersColumns = {
+ all: ["customer", "country", "link", "saleAmount", "createdAt"],
+ defaultVisible: ["customer", "country", "link", "saleAmount", "createdAt"],
+ };
+
+ const { columnVisibility, setColumnVisibility } = useColumnVisibility(
+ "partner-customers-table-columns",
+ customersColumns,
+ );
+
+ const columns = useMemo(
+ () => [
+ {
+ id: "customer",
+ header: "Customer",
+ enableHiding: false,
+ minSize: 250,
+ cell: ({ row }) => {
+ return (
+ <CustomerRowItem
+ customer={row.original}
+ href={`/programs/${programSlug}/customers/${row.original.id}`}
+ chartActivityIconMode="visible"
+ />
+ );
+ },
+ },
+ {
+ id: "country",
+ header: "Country",
+ accessorKey: "country",
+ minSize: 150,
+ cell: ({ row }) => {
+ const country = row.original.country;
+ return (
+ <div className="flex items-center gap-2">
+ {country && (
+ <img
+ alt={`${country} flag`}
+ src={`https://hatscripts.github.io/circle-flags/flags/${country.toLowerCase()}.svg`}
+ className="size-4 shrink-0"
+ />
+ )}
+ <span className="min-w-0 truncate">
+ {(country ? COUNTRIES[country] : null) ?? "-"}
+ </span>
+ </div>
+ );
+ },
+ },
+ {
+ id: "link",
+ header: "Link",
+ accessorKey: "activity.link",
+ cell: ({ row }) =>
+ row.original.activity.link ? (
+ <Link
+ href={`/programs/${programSlug}/links?domain=${row.original.activity.link.domain}&key=${row.original.activity.link.key}`}
+ className="flex cursor-alias items-center gap-3 decoration-dotted underline-offset-2 hover:underline"
+ >
+ <LinkLogo
+ apexDomain={getApexDomain(row.original.activity.link.shortLink)}
+ className="size-4 shrink-0 sm:size-4"
+ />
+ <span
+ className="truncate"
+ title={row.original.activity.link.shortLink}
+ >
+ {getPrettyUrl(row.original.activity.link.shortLink)}
+ </span>
+ </Link>
+ ) : (
+ "-"
+ ),
+ size: 250,
+ },
+ {
+ id: "saleAmount",
+ header: "Lifetime value",
+ accessorKey: "activity.ltv",
+ cell: ({ getValue }) => (
+ <div className="flex items-center gap-2">
+ <span>
+ {currencyFormatter(getValue() ?? 0, {
+ trailingZeroDisplay: "stripIfInteger",
+ })}
+ </span>
+ <span className="text-neutral-400">USD</span>
+ </div>
+ ),
+ },
+ {
+ id: "createdAt",
+ header: "Created",
+ cell: ({ row }) => (
+ <TimestampTooltip
+ timestamp={row.original.createdAt}
+ rows={["local"]}
+ side="left"
+ delayDuration={150}
+ >
+ <span>
+ {formatDate(row.original.createdAt, { month: "short" })}
+ </span>
+ </TimestampTooltip>
+ ),
+ },
+ ],
+ [programSlug],
+ );
+
+ const { table, ...tableProps } = useTable({
+ data: customers || [],
+ columns,
+ pagination,
+ onPaginationChange: setPagination,
+ columnVisibility,
+ onColumnVisibilityChange: setColumnVisibility,
+ sortableColumns: ["saleAmount", "createdAt"],
+ sortBy,
+ sortOrder,
+ onSortChange: ({ sortBy, sortOrder }) =>
+ queryParams({
+ set: {
+ ...(sortBy && { sortBy }),
+ ...(sortOrder && { sortOrder }),
+ },
+ del: "page",
+ scroll: false,
+ }),
+ thClassName: "border-l-0",
+ tdClassName: "border-l-0",
+ resourceName: (p) => `customer${p ? "s" : ""}`,
+ rowCount: customersCount || 0,
+ loading: isLoading,
+ error: error || countError ? "Failed to load customers" : undefined,
+ });
+
+ console.log({ customersCount });
+
+ return (
+ <PageWidthWrapper className="pb-10">
+ <div className="flex flex-col gap-3">
+ <div>
+ <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
+ <Filter.Select
+ className="w-full md:w-fit"
+ filters={filters}
+ activeFilters={activeFilters}
+ onSelect={onSelect}
+ onRemove={onRemove}
+ onSelectedFilterChange={setSelectedFilter}
+ />
+ {Boolean(programEnrollment?.customerDataSharingEnabledAt) && (
+ <SearchBoxPersisted
+ placeholder="Search by email or name"
+ inputClassName="md:w-[16rem]"
+ />
+ )}
+ </div>
+ <AnimatedSizeContainer height>
+ <div>
+ {activeFilters.length > 0 && (
+ <div className="pt-3">
+ <Filter.List
+ filters={filters}
+ activeFilters={activeFilters}
+ onSelect={onSelect}
+ onRemove={onRemove}
+ onRemoveAll={onRemoveAll}
+ />
+ </div>
+ )}
+ </div>
+ </AnimatedSizeContainer>
+ </div>
+
+ {customers?.length !== 0 ? (
+ <Table {...tableProps} table={table} />
+ ) : (
+ <AnimatedEmptyState
+ title={isFiltered ? "No customers found" : "No customers yet"}
+ description={
+ isFiltered
+ ? "No customers found for the selected filters. Adjust your filters to refine your search results."
+ : "No customers have been recorded for this program yet. Once customers start converting through your links, they'll appear here."
+ }
+ cardContent={() => (
+ <>
+ <User className="size-4 text-neutral-700" />
+ <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
+ </>
+ )}
+ />
+ )}
+ </div>
+ </PageWidthWrapper>
+ );
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/page.tsx
new file mode 100644
index 0000000000..111bd173cc
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/page.tsx
@@ -0,0 +1,10 @@
+import { PageContent } from "@/ui/layout/page-content";
+import { ProgramCustomersPageClient } from "./page-client";
+
+export default function ProgramCustomers() {
+ return (
+ <PageContent title="Customers">
+ <ProgramCustomersPageClient />
+ </PageContent>
+ );
+}
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/use-partner-customer-filters.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/use-partner-customer-filters.tsx
new file mode 100644
index 0000000000..957cf3c8f9
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/use-partner-customer-filters.tsx
@@ -0,0 +1,126 @@
+import usePartnerCustomersCount from "@/lib/swr/use-partner-customers-count";
+import { useRouterStuff } from "@dub/ui";
+import { Globe, Hyperlink } from "@dub/ui/icons";
+import { COUNTRIES, linkConstructor, nFormatter } from "@dub/utils";
+import { useCallback, useMemo, useState } from "react";
+
+export function usePartnerCustomerFilters() {
+ const { searchParamsObj, queryParams } = useRouterStuff();
+ const [selectedFilter, setSelectedFilter] = useState<string | null>(null);
+
+ const { data: countriesCount } = usePartnerCustomersCount<
+ | {
+ country: string;
+ _count: number;
+ }[]
+ | undefined
+ >({
+ query: {
+ groupBy: "country",
+ },
+ enabled: selectedFilter === "country" || !!searchParamsObj.country,
+ });
+
+ const { data: linksCount } = usePartnerCustomersCount<
+ | {
+ linkId: string;
+ domain: string;
+ key: string;
+ shortLink: string;
+ _count: number;
+ }[]
+ | undefined
+ >({
+ query: { groupBy: "linkId" },
+ enabled: selectedFilter === "linkId" || !!searchParamsObj.linkId,
+ });
+
+ const filters = useMemo(
+ () => [
+ {
+ key: "country",
+ icon: Globe,
+ label: "Country",
+ options:
+ countriesCount?.map(({ country, _count }) => ({
+ value: country,
+ label: COUNTRIES[country] || country,
+ icon: (
+ <img
+ alt={`${country} flag`}
+ src={`https://hatscripts.github.io/circle-flags/flags/${country.toLowerCase()}.svg`}
+ className="size-4"
+ />
+ ),
+ right: nFormatter(_count, { full: true }),
+ })) ?? null,
+ },
+ {
+ key: "linkId",
+ icon: Hyperlink,
+ label: "Link",
+ options:
+ linksCount?.map(({ linkId, domain, key, shortLink, _count }) => ({
+ value: linkId,
+ label: linkConstructor({ domain, key, pretty: true }),
+ data: { shortLink },
+ right: nFormatter(_count, { full: true }),
+ })) ?? null,
+ },
+ ],
+ [countriesCount, linksCount],
+ );
+
+ const activeFilters = useMemo(() => {
+ const { country, linkId } = searchParamsObj;
+ return [
+ ...(country ? [{ key: "country", value: country }] : []),
+ ...(linkId ? [{ key: "linkId", value: linkId }] : []),
+ ];
+ }, [searchParamsObj]);
+
+ const onSelect = useCallback(
+ (key: string, value: any) =>
+ queryParams({
+ set: {
+ [key]: value,
+ },
+ del: "page",
+ scroll: false,
+ }),
+ [queryParams],
+ );
+
+ const onRemove = useCallback(
+ (key: string) =>
+ queryParams({
+ del: [key, "page"],
+ scroll: false,
+ }),
+ [queryParams],
+ );
+
+ const onRemoveAll = useCallback(
+ () =>
+ queryParams({
+ del: ["country", "linkId", "search", "page"],
+ scroll: false,
+ }),
+ [queryParams],
+ );
+
+ const isFiltered = useMemo(
+ () => activeFilters.length > 0 || !!searchParamsObj.search,
+ [activeFilters, searchParamsObj.search],
+ );
+
+ return {
+ filters,
+ activeFilters,
+ onSelect,
+ onRemove,
+ onRemoveAll,
+ isFiltered,
+ setSelectedFilter,
+ };
+}
diff --git a/apps/web/lib/constants/partner-profile.ts b/apps/web/lib/constants/partner-profile.ts
index 51405e516b..9c6eaf49d8 100644
--- a/apps/web/lib/constants/partner-profile.ts
+++ b/apps/web/lib/constants/partner-profile.ts
@@ -13,3 +13,5 @@ export const EXCLUDED_PROGRAM_IDS = [
"prog_1JWVR53QX1NM7NDEK62E3J19H",
];
export const PARTNER_NETWORK_MIN_COMMISSIONS_CENTS = 10_00; // $10
+
+export const PARTNER_CUSTOMERS_MAX_PAGE_SIZE = 100;
diff --git a/apps/web/lib/swr/use-partner-customers-count.ts b/apps/web/lib/swr/use-partner-customers-count.ts
new file mode 100644
index 0000000000..f504cc6123
--- /dev/null
+++ b/apps/web/lib/swr/use-partner-customers-count.ts
@@ -0,0 +1,36 @@
+import { useRouterStuff } from "@dub/ui";
+import { fetcher } from "@dub/utils";
+import { useParams } from "next/navigation";
+import useSWR from "swr";
+import z from "../zod";
+import { getPartnerCustomersCountQuerySchema } from "../zod/schemas/partner-profile";
+
+export default function usePartnerCustomersCount<T = number>({
+ query,
+ enabled = true,
+}: {
+ query?: z.infer<typeof getPartnerCustomersCountQuerySchema>;
+ enabled?: boolean;
+} = {}) {
+ const { programSlug } = useParams<{ programSlug: string }>();
+ const { getQueryString } = useRouterStuff();
+
+ const { data, error } = useSWR<T>(
+ enabled &&
+ `/api/partner-profile/programs/${programSlug}/customers/count${getQueryString(
+ query,
+ {
+ include: ["country", "linkId", "search"],
+ },
+ )}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ data,
+ error,
+ };
+}
diff --git a/apps/web/lib/swr/use-partner-customers.ts b/apps/web/lib/swr/use-partner-customers.ts
new file mode 100644
index 0000000000..13b9e05813
--- /dev/null
+++ b/apps/web/lib/swr/use-partner-customers.ts
@@ -0,0 +1,27 @@
+import { useRouterStuff } from "@dub/ui";
+import { fetcher } from "@dub/utils";
+import { useParams } from "next/navigation";
+import useSWR from "swr";
+import { PartnerProfileCustomerProps } from "../types";
+
+export default function usePartnerCustomers() {
+ const { programSlug } = useParams<{ programSlug: string }>();
+ const { getQueryString } = useRouterStuff();
+
+ const { data, isLoading, error } = useSWR<
+ (PartnerProfileCustomerProps & { name?: string | null })[]
+ >(
+ programSlug &&
+ `/api/partner-profile/programs/${programSlug}/customers${getQueryString()}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ return {
+ data,
+ isLoading,
+ error,
+ };
+}
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index 4b4c441d05..2cebe26a0f 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -2,6 +2,7 @@ import {
DATE_RANGE_INTERVAL_PRESETS,
DUB_PARTNERS_ANALYTICS_INTERVAL,
} from "@/lib/analytics/constants";
+import { PARTNER_CUSTOMERS_MAX_PAGE_SIZE } from "@/lib/constants/partner-profile";
import {
CommissionType,
PartnerProfileType,
@@ -19,6 +20,7 @@ import {
import { customerActivityResponseSchema } from "./customer-activity";
import { CustomerEnrichedSchema } from "./customers";
import { LinkSchema } from "./links";
+import { getPaginationQuerySchema } from "./misc";
import { payoutsQuerySchema } from "./payouts";
import { workflowConditionSchema } from "./workflows";
@@ -198,3 +200,52 @@ export const partnerProfileChangeHistoryLogSchema = z.array(
export const partnerProfilePayoutsQuerySchema = payoutsQuerySchema.extend({
sortBy: payoutsQuerySchema.shape.sortBy.default("initiatedAt"),
});
+
+export const getPartnerCustomersQuerySchema = z
+ .object({
+ search: z
+ .string()
+ .optional()
+ .describe(
+ "A search query to filter customers by email or name. Only available if customer data sharing is enabled.",
+ ),
+ country: z
+ .string()
+ .optional()
+ .describe(
+ "A filter on the list based on the customer's `country` field.",
+ ),
+ linkId: z
+ .string()
+ .optional()
+ .describe(
+ "A filter on the list based on the customer's `linkId` field (the referral link ID).",
+ ),
+ sortBy: z
+ .enum(["createdAt", "saleAmount"])
+ .optional()
+ .default("createdAt")
+ .describe(
+ "The field to sort the customers by. The default is `createdAt`.",
+ ),
+ sortOrder: z
+ .enum(["asc", "desc"])
+ .optional()
+ .default("desc")
+ .describe("The sort order. The default is `desc`."),
+ })
+ .merge(
+ getPaginationQuerySchema({ pageSize: PARTNER_CUSTOMERS_MAX_PAGE_SIZE }),
+ );
+
+export const getPartnerCustomersCountQuerySchema =
+ getPartnerCustomersQuerySchema
+ .omit({
+ sortBy: true,
+ sortOrder: true,
+ page: true,
+ pageSize: true,
+ })
+ .extend({
+ groupBy: z.enum(["country", "linkId"]).optional(),
+ });
diff --git a/apps/web/lib/zod/schemas/partners.ts b/apps/web/lib/zod/schemas/partners.ts
index 218b99e43c..6177031614 100644
--- a/apps/web/lib/zod/schemas/partners.ts
+++ b/apps/web/lib/zod/schemas/partners.ts
@@ -378,6 +378,7 @@ export const EnrolledPartnerSchema = PartnerSchema.pick({
rewards: true,
discount: true,
group: true,
+ customerDataSharingEnabledAt: true,
}),
)
.extend({
@@ -500,12 +501,6 @@ export const LeaderboardPartnerSchema = z.object({
totalCommissions: z.number().default(0),
});
-export const getPartnerCustomersQuerySchema = z
- .object({
- search: z.string().optional(),
- })
- .merge(getPaginationQuerySchema({ pageSize: 100 }));
-
export const createPartnerSchema = z.object({
name: z
.string()
diff --git a/apps/web/lib/zod/schemas/programs.ts b/apps/web/lib/zod/schemas/programs.ts
index 5b85e1e5fb..3d2a9b928b 100644
--- a/apps/web/lib/zod/schemas/programs.ts
+++ b/apps/web/lib/zod/schemas/programs.ts
@@ -143,6 +143,7 @@ export const ProgramEnrollmentSchema = z.object({
maxPartnerLinks: true,
linkStructure: true,
}).nullish(),
+ customerDataSharingEnabledAt: z.date().nullable(),
});
export const ProgramInviteSchema = z.object({
diff --git a/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx b/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
index 6fa0e3b36e..feb49a23c3 100644
--- a/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
+++ b/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx
@@ -220,6 +220,12 @@ const NAV_AREAS: SidebarNavAreas<SidebarNavData> = {
href: `/programs/${programSlug}/events` as `/${string}`,
locked: isUnapproved,
},
+ {
+ name: "Customers",
+ icon: UserCheck,
+ href: `/programs/${programSlug}/customers` as `/${string}`,
+ locked: isUnapproved,
+ },
]
: []),
],