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 CSV export for partner program customers

Pedro Ladeiraa4803c09102e
diff --git a/apps/web/app/(ee)/api/cron/export/customers/partner/route.ts b/apps/web/app/(ee)/api/cron/export/customers/partner/route.ts
new file mode 100644
index 0000000000..9a7d30e070
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/export/customers/partner/route.ts
@@ -0,0 +1,157 @@
+import { convertToCSV } from "@/lib/analytics/utils/convert-to-csv";
+import { createDownloadableExport } from "@/lib/api/create-downloadable-export";
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { generateExportFilename } from "@/lib/api/utils/generate-export-filename";
+import { generateRandomString } from "@/lib/api/utils/generate-random-string";
+import { CUSTOMER_LTV_EXCLUDED_PROGRAM_IDS } from "@/lib/constants/partner-profile";
+import { withCron } from "@/lib/cron/with-cron";
+import { formatPartnerCustomersForExport } from "@/lib/customers/api/format-partner-customers-export";
+import { prisma, sanitizeFullTextSearch } from "@/lib/prisma";
+import { partnerCustomersExportCronInputSchema } from "@/lib/zod/schemas/partner-profile";
+import { sendEmail } from "@dub/email";
+import ExportReady from "@dub/email/templates/export-ready";
+import { CommissionType } from "@prisma/client";
+import { logAndRespond } from "../../../utils";
+
+const MAX_CUSTOMERS_EXPORT_LIMIT = 100_000;
+const PAGE_SIZE = 1000;
+
+export const dynamic = "force-dynamic";
+
+// POST /api/cron/export/customers/partner - QStash worker for processing large partner customer exports
+export const POST = withCron(async ({ rawBody }) => {
+ const parsedFilters = partnerCustomersExportCronInputSchema.parse(
+ JSON.parse(rawBody),
+ );
+
+ const {
+ partnerId,
+ programId,
+ userId,
+ columns,
+ search,
+ country,
+ linkId,
+ sortBy,
+ sortOrder,
+ } = parsedFilters;
+
+ const user = await prisma.user.findUnique({
+ where: {
+ id: userId,
+ },
+ select: {
+ email: true,
+ },
+ });
+
+ if (!user) {
+ return logAndRespond(`User ${userId} not found.`);
+ }
+
+ if (!user.email) {
+ return logAndRespond(`User ${userId} has no email.`);
+ }
+
+ const { program, customerDataSharingEnabledAt } =
+ await getProgramEnrollmentOrThrow({
+ partnerId,
+ programId,
+ include: {
+ program: true,
+ },
+ });
+
+ const ltvExcluded = CUSTOMER_LTV_EXCLUDED_PROGRAM_IDS.includes(program.id);
+
+ const where = {
+ partnerId,
+ programId: program.id,
+ projectId: program.workspaceId,
+ ...(country && { country }),
+ ...(linkId && { linkId }),
+ ...(search && customerDataSharingEnabledAt
+ ? search.includes("@")
+ ? { email: search }
+ : {
+ email: { search: sanitizeFullTextSearch(search) },
+ name: { search: sanitizeFullTextSearch(search) },
+ }
+ : {}),
+ };
+
+ const allRows: Record<string, string | number>[] = [];
+ let page = 1;
+
+ while (allRows.length < MAX_CUSTOMERS_EXPORT_LIMIT) {
+ const customers = await prisma.customer.findMany({
+ where,
+ include: {
+ link: true,
+ commissions: {
+ where: {
+ partnerId,
+ type: CommissionType.sale,
+ },
+ take: 1,
+ orderBy: {
+ createdAt: "asc",
+ },
+ },
+ },
+ orderBy: {
+ [sortBy]: sortOrder,
+ },
+ skip: (page - 1) * PAGE_SIZE,
+ take: PAGE_SIZE,
+ });
+
+ if (customers.length === 0) {
+ break;
+ }
+
+ const formatted = formatPartnerCustomersForExport(customers, columns, {
+ customerDataSharingEnabledAt,
+ ltvExcluded,
+ });
+ const remaining = MAX_CUSTOMERS_EXPORT_LIMIT - allRows.length;
+ allRows.push(...formatted.slice(0, remaining));
+
+ if (customers.length < PAGE_SIZE) {
+ break;
+ }
+
+ page++;
+ }
+
+ const csvData = convertToCSV(allRows);
+
+ const { downloadUrl } = await createDownloadableExport({
+ fileKey: `exports/customers/partner/${generateRandomString(16)}.csv`,
+ fileName: generateExportFilename("customers"),
+ body: csvData,
+ contentType: "text/csv",
+ });
+
+ await sendEmail({
+ to: user.email,
+ subject: "Your customers export is ready",
+ react: ExportReady({
+ email: user.email,
+ exportType: "customers",
+ downloadUrl,
+ program: {
+ name: program.name,
+ },
+ }),
+ });
+
+ const capped =
+ allRows.length >= MAX_CUSTOMERS_EXPORT_LIMIT
+ ? ` (capped at ${MAX_CUSTOMERS_EXPORT_LIMIT})`
+ : "";
+
+ return logAndRespond(
+ `Export (${allRows.length} customers${capped}) generated and email sent to user.`,
+ );
+});
diff --git a/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/export/route.ts b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/export/route.ts
new file mode 100644
index 0000000000..6519dbff5f
--- /dev/null
+++ b/apps/web/app/(ee)/api/partner-profile/programs/[programId]/customers/export/route.ts
@@ -0,0 +1,121 @@
+import { convertToCSV } from "@/lib/analytics/utils";
+import { DubApiError } from "@/lib/api/errors";
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { withPartnerProfile } from "@/lib/auth/partner";
+import {
+ CUSTOMER_LTV_EXCLUDED_PROGRAM_IDS,
+ LARGE_PROGRAM_IDS,
+ LARGE_PROGRAM_MIN_TOTAL_COMMISSIONS_CENTS,
+} from "@/lib/constants/partner-profile";
+import { qstash } from "@/lib/cron";
+import { formatPartnerCustomersForExport } from "@/lib/customers/api/format-partner-customers-export";
+import { prisma, sanitizeFullTextSearch } from "@/lib/prisma";
+import { partnerCustomersExportQuerySchema } from "@/lib/zod/schemas/partner-profile";
+import { APP_DOMAIN_WITH_NGROK, toCentsNumber } from "@dub/utils";
+import { CommissionType } from "@prisma/client";
+import { NextResponse } from "next/server";
+
+const MAX_CUSTOMERS_TO_EXPORT = 1000;
+
+// GET /api/partner-profile/programs/[programId]/customers/export – export partner customers to CSV
+export const GET = withPartnerProfile(
+ async ({ partner, params, searchParams, session }) => {
+ const filters = partnerCustomersExportQuerySchema.parse(searchParams);
+ const { search, country, linkId, sortBy, sortOrder, columns } = filters;
+
+ const { program, totalCommissions, customerDataSharingEnabledAt } =
+ await getProgramEnrollmentOrThrow({
+ partnerId: partner.id,
+ programId: params.programId,
+ include: {
+ program: true,
+ },
+ });
+
+ if (
+ LARGE_PROGRAM_IDS.includes(program.id) &&
+ toCentsNumber(totalCommissions) <
+ LARGE_PROGRAM_MIN_TOTAL_COMMISSIONS_CENTS
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "This feature is not available for your program.",
+ });
+ }
+
+ const ltvExcluded = CUSTOMER_LTV_EXCLUDED_PROGRAM_IDS.includes(program.id);
+
+ if (sortBy === "saleAmount" && ltvExcluded) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This feature is not available for your program.",
+ });
+ }
+
+ const where = {
+ partnerId: partner.id,
+ programId: program.id,
+ projectId: program.workspaceId,
+ ...(country && { country }),
+ ...(linkId && { linkId }),
+ ...(search && customerDataSharingEnabledAt
+ ? search.includes("@")
+ ? { email: search }
+ : {
+ email: { search: sanitizeFullTextSearch(search) },
+ name: { search: sanitizeFullTextSearch(search) },
+ }
+ : {}),
+ };
+
+ const count = await prisma.customer.count({ where });
+
+ if (count > MAX_CUSTOMERS_TO_EXPORT) {
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/export/customers/partner`,
+ body: {
+ ...filters,
+ partnerId: partner.id,
+ programId: program.id,
+ userId: session.user.id,
+ columns: columns.join(","),
+ },
+ });
+
+ return NextResponse.json({}, { status: 202 });
+ }
+
+ const customers = await prisma.customer.findMany({
+ where,
+ include: {
+ link: true,
+ commissions: {
+ where: {
+ partnerId: partner.id,
+ type: CommissionType.sale,
+ },
+ take: 1,
+ orderBy: {
+ createdAt: "asc",
+ },
+ },
+ },
+ orderBy: {
+ [sortBy]: sortOrder,
+ },
+ take: MAX_CUSTOMERS_TO_EXPORT,
+ });
+
+ const rows = formatPartnerCustomersForExport(customers, columns, {
+ customerDataSharingEnabledAt,
+ ltvExcluded,
+ });
+
+ return new Response(convertToCSV(rows), {
+ headers: {
+ "Content-Type": "text/csv",
+ "Content-Disposition": "attachment",
+ },
+ });
+ },
+);
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/layout.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/layout.tsx
index 1e0edb18e7..cf080f70a0 100644
--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/layout.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/[programSlug]/(enrolled)/customers/(index)/layout.tsx
@@ -5,6 +5,7 @@ import usePartnerCustomersCount from "@/lib/swr/use-partner-customers-count";
import { usePartnerSubmittedLeadsCount } from "@/lib/swr/use-partner-submitted-leads-count";
import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
import { submittedLeadFormSchema } from "@/lib/zod/schemas/submitted-lead-form";
+import { PartnerCustomersMenuPopover } from "@/ui/customers/partner-customers-menu-popover";
import { PageContent } from "@/ui/layout/page-content";
import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import { SubmitLeadSheet } from "@/ui/submitted-leads/submit-lead-sheet";
@@ -94,6 +95,7 @@ export default function PartnerProgramCustomersLayout({
}}
/>
)}
+ <PartnerCustomersMenuPopover />
</>
}
>
diff --git a/apps/web/lib/customers/api/format-partner-customers-export.ts b/apps/web/lib/customers/api/format-partner-customers-export.ts
new file mode 100644
index 0000000000..dc3cb2fb6b
--- /dev/null
+++ b/apps/web/lib/customers/api/format-partner-customers-export.ts
@@ -0,0 +1,89 @@
+import { obfuscateCustomerEmail } from "@/lib/api/partner-profile/obfuscate-customer-email";
+import { formatMoneyCentsForExport } from "@/lib/api/utils/format-money-cents-for-export";
+import { generateRandomName } from "@/lib/names";
+import {
+ PARTNER_CUSTOMER_EXPORT_COLUMNS,
+ PARTNER_CUSTOMER_EXPORT_DEFAULT_COLUMNS,
+} from "@/lib/zod/schemas/partner-profile";
+import { toCentsNumber } from "@dub/utils";
+
+export type PartnerCustomerForExport = {
+ id: string;
+ name: string | null;
+ email: string | null;
+ country: string | null;
+ saleAmount: number | bigint | null;
+ createdAt: Date;
+ subscriptionCanceledAt: Date | null;
+ link?: { shortLink: string; url: string } | null;
+ commissions?: { createdAt: Date }[];
+};
+
+const dateToIso = (d: Date | null | undefined) => (d ? d.toISOString() : "");
+
+const columnOrderById = new Map<string, number>(
+ PARTNER_CUSTOMER_EXPORT_COLUMNS.map((col) => [col.id, col.order]),
+);
+
+export function formatPartnerCustomersForExport(
+ customers: PartnerCustomerForExport[],
+ columns: string[] = PARTNER_CUSTOMER_EXPORT_DEFAULT_COLUMNS,
+ {
+ customerDataSharingEnabledAt,
+ ltvExcluded = false,
+ }: {
+ customerDataSharingEnabledAt: Date | null | undefined;
+ ltvExcluded?: boolean;
+ },
+) {
+ const allowedColumns = columns.filter((key) => {
+ if (key === "name" && !customerDataSharingEnabledAt) {
+ return false;
+ }
+ if (key === "saleAmount" && ltvExcluded) {
+ return false;
+ }
+ return true;
+ });
+
+ const sortedColumns = [...allowedColumns].sort(
+ (a, b) => (columnOrderById.get(a) ?? 999) - (columnOrderById.get(b) ?? 999),
+ );
+
+ return customers.map((c) => {
+ const email = c.email
+ ? customerDataSharingEnabledAt
+ ? c.email
+ : obfuscateCustomerEmail(c.email)
+ : customerDataSharingEnabledAt
+ ? c.name || generateRandomName()
+ : generateRandomName();
+
+ const full: Record<string, string | number> = {
+ id: c.id,
+ email,
+ ...(customerDataSharingEnabledAt
+ ? { name: c.name || c.email || "" }
+ : {}),
+ country: c.country ?? "",
+ link: c.link?.shortLink ?? c.link?.url ?? "",
+ createdAt: dateToIso(c.createdAt),
+ firstSaleAt: dateToIso(c.commissions?.[0]?.createdAt),
+ subscriptionCanceledAt: dateToIso(c.subscriptionCanceledAt),
+ ...(!ltvExcluded
+ ? {
+ saleAmount: formatMoneyCentsForExport(
+ toCentsNumber(c.saleAmount ?? 0),
+ "USD",
+ `customer ${c.id}`,
+ ),
+ }
+ : {}),
+ };
+
+ return sortedColumns.reduce<Record<string, string | number>>((acc, key) => {
+ if (key in full) acc[key] = full[key];
+ return acc;
+ }, {});
+ });
+}
diff --git a/apps/web/lib/zod/schemas/partner-profile.ts b/apps/web/lib/zod/schemas/partner-profile.ts
index a2c7401ade..dc70a50ee7 100644
--- a/apps/web/lib/zod/schemas/partner-profile.ts
+++ b/apps/web/lib/zod/schemas/partner-profile.ts
@@ -300,6 +300,71 @@ export const getPartnerCustomersCountQuerySchema =
groupBy: z.enum(["country", "linkId"]).optional(),
});
+export const PARTNER_CUSTOMER_EXPORT_COLUMNS = [
+ { id: "id", label: "ID", default: true, order: 1 },
+ { id: "email", label: "Email", default: true, order: 2 },
+ { id: "name", label: "Name", default: true, order: 3 },
+ { id: "country", label: "Country", default: true, order: 4 },
+ { id: "link", label: "Link", default: true, order: 5 },
+ { id: "createdAt", label: "Created at", default: true, order: 6 },
+ { id: "saleAmount", label: "Sale amount", default: true, order: 7 },
+ { id: "firstSaleAt", label: "First sale at", default: true, order: 8 },
+ {
+ id: "subscriptionCanceledAt",
+ label: "Subscription canceled",
+ default: true,
+ order: 9,
+ },
+] as const;
+
+type PartnerCustomerExportColumnId =
+ (typeof PARTNER_CUSTOMER_EXPORT_COLUMNS)[number]["id"];
+
+export const PARTNER_CUSTOMER_EXPORT_DEFAULT_COLUMNS =
+ PARTNER_CUSTOMER_EXPORT_COLUMNS.filter((column) => column.default).map(
+ (column) => column.id,
+ );
+
+export const partnerCustomersExportQuerySchema = getPartnerCustomersQuerySchema
+ .omit({
+ page: true,
+ pageSize: true,
+ })
+ .extend({
+ columns: z
+ .string()
+ .optional()
+ .default(PARTNER_CUSTOMER_EXPORT_DEFAULT_COLUMNS.join(","))
+ .transform((v) =>
+ v
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean),
+ )
+ .refine(
+ (columns) => {
+ const validColumnIds = PARTNER_CUSTOMER_EXPORT_COLUMNS.map(
+ (col) => col.id,
+ );
+
+ return columns.every((column: PartnerCustomerExportColumnId) =>
+ validColumnIds.includes(column),
+ );
+ },
+ {
+ message:
+ "Invalid column IDs provided. Please check the available columns.",
+ },
+ ),
+ });
+
+export const partnerCustomersExportCronInputSchema =
+ partnerCustomersExportQuerySchema.extend({
+ partnerId: z.string(),
+ programId: z.string(),
+ userId: z.string(),
+ });
+
export const partnerProfileSubmittedLeadSchema = z.object({
id: z.string(),
name: z.string(),
diff --git a/apps/web/tests/customers/format-customers-export.test.ts b/apps/web/tests/customers/format-customers-export.test.ts
new file mode 100644
index 0000000000..4e3a8303dd
--- /dev/null
+++ b/apps/web/tests/customers/format-customers-export.test.ts
@@ -0,0 +1,80 @@
+import { obfuscateCustomerEmail } from "@/lib/api/partner-profile/obfuscate-customer-email";
+import { formatPartnerCustomersForExport } from "@/lib/customers/api/format-partner-customers-export";
+import { describe, expect, test, vi } from "vitest";
+
+vi.mock("@/lib/names", () => ({
+ generateRandomName: () => "Random Placeholder",
+}));
+
+const createdAt = new Date("2026-01-01T00:00:00.000Z");
+const firstSaleAt = new Date("2026-01-02T00:00:00.000Z");
+
+const partnerCustomer = {
+ id: "cus_123",
+ name: "Ada Lovelace",
+ email: "[email protected]",
+ country: "US",
+ saleAmount: 12000,
+ createdAt,
+ subscriptionCanceledAt: null,
+ link: { shortLink: "https://dub.sh/ada", url: "https://example.com" },
+ commissions: [{ createdAt: firstSaleAt }],
+};
+
+describe("formatPartnerCustomersForExport", () => {
+ test("obfuscates email and omits name when sharing is off", () => {
+ const [row] = formatPartnerCustomersForExport(
+ [partnerCustomer],
+ ["id", "email", "name", "saleAmount"],
+ { customerDataSharingEnabledAt: null },
+ );
+
+ expect(row.email).toBe(obfuscateCustomerEmail("[email protected]"));
+ expect(row).not.toHaveProperty("name");
+ expect(row.saleAmount).toBe("$120.00");
+ });
+
+ test("includes name and real email when sharing is enabled", () => {
+ const [row] = formatPartnerCustomersForExport(
+ [partnerCustomer],
+ ["id", "email", "name", "saleAmount"],
+ { customerDataSharingEnabledAt: new Date("2026-01-01") },
+ );
+
+ expect(row).toEqual({
+ id: "cus_123",
+ email: "[email protected]",
+ name: "Ada Lovelace",
+ saleAmount: "$120.00",
+ });
+ });
+
+ test("does not leak the customer name into email when sharing is off and email is missing", () => {
+ const [row] = formatPartnerCustomersForExport(
+ [{ ...partnerCustomer, email: null }],
+ ["id", "email", "name"],
+ { customerDataSharingEnabledAt: null },
+ );
+
+ expect(row.email).toBe("Random Placeholder");
+ expect(row.email).not.toBe("Ada Lovelace");
+ expect(row).not.toHaveProperty("name");
+ });
+
+ test("omits saleAmount when the program excludes LTV", () => {
+ const [row] = formatPartnerCustomersForExport(
+ [partnerCustomer],
+ ["id", "email", "saleAmount"],
+ {
+ customerDataSharingEnabledAt: new Date("2026-01-01"),
+ ltvExcluded: true,
+ },
+ );
+
+ expect(row).toEqual({
+ id: "cus_123",
+ email: "[email protected]",
+ });
+ expect(row).not.toHaveProperty("saleAmount");
+ });
+});
diff --git a/apps/web/ui/customers/partner-customers-menu-popover.tsx b/apps/web/ui/customers/partner-customers-menu-popover.tsx
new file mode 100644
index 0000000000..5376c07d58
--- /dev/null
+++ b/apps/web/ui/customers/partner-customers-menu-popover.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { useExportPartnerCustomersModal } from "@/ui/modals/export-partner-customers-modal";
+import { ThreeDots } from "@/ui/shared/icons";
+import { Button, Download, IconMenu, Popover } from "@dub/ui";
+import { useState } from "react";
+
+export function PartnerCustomersMenuPopover() {
+ const [openPopover, setOpenPopover] = useState(false);
+
+ const { ExportPartnerCustomersModal, setShowExportPartnerCustomersModal } =
+ useExportPartnerCustomersModal();
+
+ return (
+ <>
+ <ExportPartnerCustomersModal />
+ <Popover
+ content={
+ <div className="w-full md:w-52">
+ <div className="grid gap-px p-2">
+ <p className="mb-1.5 mt-1 flex items-center gap-2 px-1 text-xs font-medium text-neutral-500">
+ Export Customers
+ </p>
+ <button
+ onClick={() => {
+ setOpenPopover(false);
+ setShowExportPartnerCustomersModal(true);
+ }}
+ className="w-full rounded-md p-2 hover:bg-neutral-100 active:bg-neutral-200"
+ >
+ <IconMenu
+ text="Export as CSV"
+ icon={<Download className="h-4 w-4" />}
+ />
+ </button>
+ </div>
+ </div>
+ }
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ align="end"
+ >
+ <Button
+ onClick={() => setOpenPopover(!openPopover)}
+ variant="secondary"
+ className="h-8 w-auto px-1.5 sm:h-9"
+ icon={<ThreeDots className="h-5 w-5 text-neutral-500" />}
+ />
+ </Popover>
+ </>
+ );
+}
diff --git a/apps/web/ui/modals/export-partner-customers-modal.tsx b/apps/web/ui/modals/export-partner-customers-modal.tsx
new file mode 100644
index 0000000000..5a6f11c7f3
--- /dev/null
+++ b/apps/web/ui/modals/export-partner-customers-modal.tsx
@@ -0,0 +1,248 @@
+"use client";
+
+import { generateExportFilename } from "@/lib/api/utils/generate-export-filename";
+import { CUSTOMER_LTV_EXCLUDED_PROGRAM_IDS } from "@/lib/constants/partner-profile";
+import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
+import {
+ PARTNER_CUSTOMER_EXPORT_COLUMNS,
+ PARTNER_CUSTOMER_EXPORT_DEFAULT_COLUMNS,
+} from "@/lib/zod/schemas/partner-profile";
+import {
+ Button,
+ Checkbox,
+ InfoTooltip,
+ Modal,
+ Switch,
+ useRouterStuff,
+} from "@dub/ui";
+import { useSession } from "next-auth/react";
+import { useParams } from "next/navigation";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useId,
+ useMemo,
+ useState,
+} from "react";
+import { Controller, useForm } from "react-hook-form";
+import { toast } from "sonner";
+
+interface FormData {
+ columns: string[];
+ useFilters: boolean;
+}
+
+function ExportPartnerCustomersModal({
+ showExportPartnerCustomersModal,
+ setShowExportPartnerCustomersModal,
+}: {
+ showExportPartnerCustomersModal: boolean;
+ setShowExportPartnerCustomersModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const { programSlug } = useParams<{ programSlug: string }>();
+ const { data: session } = useSession();
+ const { programEnrollment } = useProgramEnrollment();
+ const { getQueryString } = useRouterStuff();
+
+ const columnCheckboxId = useId();
+
+ const ltvExcluded = CUSTOMER_LTV_EXCLUDED_PROGRAM_IDS.includes(
+ programEnrollment?.programId ?? "",
+ );
+ const sharingEnabled = Boolean(
+ programEnrollment?.customerDataSharingEnabledAt,
+ );
+
+ const {
+ control,
+ handleSubmit,
+ formState: { isSubmitting },
+ } = useForm<FormData>({
+ defaultValues: {
+ columns: PARTNER_CUSTOMER_EXPORT_DEFAULT_COLUMNS,
+ useFilters: true,
+ },
+ });
+
+ const visibleColumns = useMemo(() => {
+ return PARTNER_CUSTOMER_EXPORT_COLUMNS.filter((col) => {
+ if (col.id === "name" && !sharingEnabled) {
+ return false;
+ }
+ if (col.id === "saleAmount" && ltvExcluded) {
+ return false;
+ }
+ return true;
+ }).sort((a, b) => a.order - b.order);
+ }, [sharingEnabled, ltvExcluded]);
+
+ const onSubmit = handleSubmit(async (data) => {
+ if (!programSlug) {
+ return;
+ }
+
+ const lid = toast.loading("Exporting customers...");
+
+ try {
+ const visibleIds = new Set<string>(visibleColumns.map((col) => col.id));
+ const columns = data.columns.filter((column) => visibleIds.has(column));
+
+ const baseParams: Record<string, string> = {
+ ...(columns.length ? { columns: columns.join(",") } : {}),
+ };
+
+ const queryString = data.useFilters
+ ? getQueryString(baseParams)
+ : `?${new URLSearchParams(baseParams).toString()}`;
+
+ const response = await fetch(
+ `/api/partner-profile/programs/${programSlug}/customers/export${queryString}`,
+ {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ },
+ );
+
+ if (!response.ok) {
+ const body = await response.json();
+ throw new Error(body.error?.message ?? "Customer export failed");
+ }
+
+ if (response.status === 202) {
+ toast.success(
+ `Your export is being processed and we'll send you an email (${session?.user?.email}) when it's ready to download.`,
+ );
+ setShowExportPartnerCustomersModal(false);
+ return;
+ }
+
+ const blob = await response.blob();
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+
+ a.download = generateExportFilename("customers");
+ a.click();
+ window.URL.revokeObjectURL(url);
+
+ toast.success("Customers exported successfully");
+ setShowExportPartnerCustomersModal(false);
+ } catch (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Customer export failed",
+ );
+ } finally {
+ toast.dismiss(lid);
+ }
+ });
+
+ return (
+ <Modal
+ showModal={showExportPartnerCustomersModal}
+ setShowModal={setShowExportPartnerCustomersModal}
+ >
+ <div className="border-b border-neutral-200 p-4 sm:p-6">
+ <h3 className="text-lg font-medium leading-none">Export customers</h3>
+ </div>
+
+ <form onSubmit={onSubmit}>
+ <div className="bg-neutral-50 p-4 sm:p-6">
+ <div className="space-y-4">
+ <div>
+ <p className="mb-2 block text-sm font-medium text-neutral-700">
+ Columns
+ </p>
+ <Controller
+ name="columns"
+ control={control}
+ render={({ field }) => (
+ <div className="xs:grid-cols-2 grid grid-cols-1 gap-x-4 gap-y-2">
+ {visibleColumns.map(({ id, label }) => (
+ <div key={id} className="group flex gap-2">
+ <Checkbox
+ value={id}
+ id={`${columnCheckboxId}-${id}`}
+ checked={field.value.includes(id)}
+ onCheckedChange={(checked) => {
+ field.onChange(
+ checked
+ ? [...field.value, id]
+ : field.value.filter((value) => value !== id),
+ );
+ }}
+ />
+ <label
+ htmlFor={`${columnCheckboxId}-${id}`}
+ className="select-none text-sm font-medium text-neutral-600 group-hover:text-neutral-800"
+ >
+ {label}
+ </label>
+ </div>
+ ))}
+ </div>
+ )}
+ />
+ </div>
+ </div>
+ </div>
+
+ <div className="border-t border-neutral-200 bg-neutral-50 px-4 py-4 sm:px-6">
+ <Controller
+ name="useFilters"
+ control={control}
+ render={({ field }) => (
+ <div className="flex items-center justify-between gap-2">
+ <span className="flex select-none items-center gap-2 text-sm font-medium text-neutral-600 group-hover:text-neutral-800">
+ Apply current filters
+ <InfoTooltip content="Filter exported customers by your currently selected filters" />
+ </span>
+ <Switch checked={field.value} fn={field.onChange} />
+ </div>
+ )}
+ />
+ </div>
+
+ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 bg-neutral-50 px-4 py-5 sm:px-6">
+ <Button
+ onClick={() => setShowExportPartnerCustomersModal(false)}
+ variant="secondary"
+ text="Cancel"
+ className="h-8 w-fit px-3"
+ type="button"
+ />
+ <Button
+ type="submit"
+ loading={isSubmitting}
+ text="Export customers"
+ className="h-8 w-fit px-3"
+ />
+ </div>
+ </form>
+ </Modal>
+ );
+}
+
+export function useExportPartnerCustomersModal() {
+ const [showExportPartnerCustomersModal, setShowExportPartnerCustomersModal] =
+ useState(false);
+
+ const ExportPartnerCustomersModalCallback = useCallback(() => {
+ return (
+ <ExportPartnerCustomersModal
+ showExportPartnerCustomersModal={showExportPartnerCustomersModal}
+ setShowExportPartnerCustomersModal={setShowExportPartnerCustomersModal}
+ />
+ );
+ }, [showExportPartnerCustomersModal, setShowExportPartnerCustomersModal]);
+
+ return useMemo(
+ () => ({
+ setShowExportPartnerCustomersModal,
+ ExportPartnerCustomersModal: ExportPartnerCustomersModalCallback,
+ }),
+ [setShowExportPartnerCustomersModal, ExportPartnerCustomersModalCallback],
+ );
+}