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.

Export customers (#3499)

Kiran K4f183df0d831
diff --git a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
index e537d8d106..db452820ef 100644
--- a/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
+++ b/apps/web/app/(ee)/api/bounties/[bountyId]/route.ts
@@ -148,8 +148,8 @@ export const PATCH = withWorkspace(
const submissionCount = bounty._count.submissions;
const currentSocialMetrics = bounty.submissionRequirements
- ? (submissionRequirementsSchema.parse(bounty.submissionRequirements)
- .socialMetrics ?? {})
+ ? submissionRequirementsSchema.parse(bounty.submissionRequirements)
+ .socialMetrics ?? {}
: {};
const incomingSocialMetrics =
diff --git a/apps/web/app/(ee)/api/cron/export/customers/route.ts b/apps/web/app/(ee)/api/cron/export/customers/route.ts
new file mode 100644
index 0000000000..f4004134cf
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/export/customers/route.ts
@@ -0,0 +1,99 @@
+import { convertToCSV } from "@/lib/analytics/utils/convert-to-csv";
+import { createDownloadableExport } from "@/lib/api/create-downloadable-export";
+import { generateExportFilename } from "@/lib/api/utils/generate-export-filename";
+import { generateRandomString } from "@/lib/api/utils/generate-random-string";
+import { withCron } from "@/lib/cron/with-cron";
+import { fetchCustomersBatch } from "@/lib/customers/api/fetch-customers-batch";
+import { formatCustomersForExport } from "@/lib/customers/api/format-customers-export";
+import { customersExportCronInputSchema } from "@/lib/zod/schemas/customers";
+import { sendEmail } from "@dub/email";
+import ExportReady from "@dub/email/templates/export-ready";
+import { prisma } from "@dub/prisma";
+import { logAndRespond } from "../../utils";
+
+const MAX_CUSTOMERS_EXPORT_LIMIT = 100_000;
+
+export const dynamic = "force-dynamic";
+
+// POST /api/cron/export/customers - QStash worker for processing large customer exports
+export const POST = withCron(async ({ rawBody }) => {
+ const parsedFilters = customersExportCronInputSchema.parse(
+ JSON.parse(rawBody),
+ );
+
+ const { workspaceId, userId, columns } = 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 workspace = await prisma.project.findUnique({
+ where: {
+ id: workspaceId,
+ },
+ select: {
+ name: true,
+ },
+ });
+
+ if (!workspace) {
+ return logAndRespond(`Workspace ${workspaceId} not found.`);
+ }
+
+ const allRows: Record<string, string | number>[] = [];
+
+ for await (const { customers } of fetchCustomersBatch(parsedFilters)) {
+ const formatted = formatCustomersForExport(customers, columns);
+ const remaining = MAX_CUSTOMERS_EXPORT_LIMIT - allRows.length;
+
+ if (remaining <= 0) {
+ break;
+ }
+
+ allRows.push(...formatted.slice(0, remaining));
+ }
+
+ const csvData = convertToCSV(allRows);
+
+ const { downloadUrl } = await createDownloadableExport({
+ fileKey: `exports/customers/${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,
+ workspace: {
+ name: workspace.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/customers/count/route.ts b/apps/web/app/(ee)/api/customers/count/route.ts
index ebd3a8c5e3..fd97809e9f 100644
--- a/apps/web/app/(ee)/api/customers/count/route.ts
+++ b/apps/web/app/(ee)/api/customers/count/route.ts
@@ -1,58 +1,25 @@
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { withWorkspace } from "@/lib/auth";
+import { buildCustomerCountWhere } from "@/lib/customers/api/customer-count-where";
import { getCustomersCountQuerySchema } from "@/lib/zod/schemas/customers";
-import { prisma, sanitizeFullTextSearch } from "@dub/prisma";
-import { Prisma } from "@dub/prisma/client";
+import { prisma } from "@dub/prisma";
import { NextResponse } from "next/server";
// GET /api/customers/count
export const GET = withWorkspace(async ({ workspace, searchParams }) => {
- let {
- email,
- externalId,
- search,
- country,
- linkId,
- programId,
- partnerId,
- groupBy,
- } = getCustomersCountQuerySchema.parse(searchParams);
+ const parsedFilters = getCustomersCountQuerySchema.parse(searchParams);
+
+ let { programId, partnerId, groupBy } = parsedFilters;
if (programId || partnerId) {
programId = getDefaultProgramIdOrThrow(workspace);
}
- const commonWhere: Prisma.CustomerWhereInput = {
- ...(programId && {
- programId,
- }),
- ...(partnerId && {
- partnerId,
- }),
- projectId: workspace.id,
- ...(email
- ? { email }
- : externalId
- ? { externalId }
- : search
- ? search.includes("@")
- ? { email: search }
- : {
- email: { search: sanitizeFullTextSearch(search) },
- name: { search: sanitizeFullTextSearch(search) },
- }
- : {}),
- // 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,
- }),
- };
+ const commonWhere = buildCustomerCountWhere({
+ ...parsedFilters,
+ workspaceId: workspace.id,
+ programId,
+ });
// Get customer count by country
if (groupBy === "country") {
diff --git a/apps/web/app/(ee)/api/customers/export/route.ts b/apps/web/app/(ee)/api/customers/export/route.ts
new file mode 100644
index 0000000000..73123bb784
--- /dev/null
+++ b/apps/web/app/(ee)/api/customers/export/route.ts
@@ -0,0 +1,79 @@
+import { convertToCSV } from "@/lib/analytics/utils";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { withWorkspace } from "@/lib/auth";
+import { qstash } from "@/lib/cron";
+import { buildCustomerCountWhere } from "@/lib/customers/api/customer-count-where";
+import { formatCustomersForExport } from "@/lib/customers/api/format-customers-export";
+import { getCustomers } from "@/lib/customers/api/get-customers";
+import { customersExportQuerySchema } from "@/lib/zod/schemas/customers";
+import { prisma } from "@dub/prisma";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+const MAX_CUSTOMERS_TO_EXPORT = 1000;
+
+// GET /api/customers/export – export customers to CSV
+export const GET = withWorkspace(
+ async ({ searchParams, workspace, session }) => {
+ const filters = customersExportQuerySchema.parse(searchParams);
+
+ let { programId, partnerId, columns } = filters;
+
+ if (programId || partnerId) {
+ programId = getDefaultProgramIdOrThrow(workspace);
+ }
+
+ const where = buildCustomerCountWhere({
+ ...filters,
+ workspaceId: workspace.id,
+ programId,
+ });
+
+ 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`,
+ body: {
+ ...filters,
+ workspaceId: workspace.id,
+ programId,
+ userId: session.user.id,
+ columns: columns.join(","),
+ },
+ });
+
+ return NextResponse.json({}, { status: 202 });
+ }
+
+ const customers = await getCustomers({
+ ...filters,
+ workspaceId: workspace.id,
+ programId,
+ page: 1,
+ pageSize: MAX_CUSTOMERS_TO_EXPORT,
+ includeExpandedFields: true,
+ });
+
+ const rows = formatCustomersForExport(customers, columns);
+
+ return new Response(convertToCSV(rows), {
+ headers: {
+ "Content-Type": "text/csv",
+ "Content-Disposition": "attachment",
+ },
+ });
+ },
+ {
+ requiredPlan: [
+ "business",
+ "business plus",
+ "business extra",
+ "business max",
+ "advanced",
+ "enterprise",
+ ],
+ },
+);
diff --git a/apps/web/app/(ee)/api/customers/route.ts b/apps/web/app/(ee)/api/customers/route.ts
index 2fc5cdf60a..b217620d7c 100644
--- a/apps/web/app/(ee)/api/customers/route.ts
+++ b/apps/web/app/(ee)/api/customers/route.ts
@@ -4,6 +4,7 @@ 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 { getCustomers } from "@/lib/customers/api/get-customers";
import { generateRandomName } from "@/lib/names";
import { isStored, storage } from "@/lib/storage";
import {
@@ -13,7 +14,7 @@ import {
getCustomersQuerySchemaExtended,
} from "@/lib/zod/schemas/customers";
import { DiscountSchemaWithDeprecatedFields } from "@/lib/zod/schemas/discount";
-import { prisma, sanitizeFullTextSearch } from "@dub/prisma";
+import { prisma } from "@dub/prisma";
import { nanoid, R2_URL } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -21,93 +22,18 @@ import { NextResponse } from "next/server";
// GET /api/customers – Get all customers
export const GET = withWorkspace(
async ({ workspace, searchParams }) => {
- let {
- email,
- externalId,
- search,
- country,
- linkId,
- programId,
- partnerId,
- includeExpandedFields,
- page,
- pageSize,
- customerIds,
- sortBy,
- sortOrder,
- } = getCustomersQuerySchemaExtended.parse(searchParams);
+ const filters = getCustomersQuerySchemaExtended.parse(searchParams);
+
+ let { programId, partnerId, includeExpandedFields } = filters;
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
- ? { email }
- : externalId
- ? { externalId }
- : search
- ? search.includes("@")
- ? { email: search }
- : {
- email: { search: sanitizeFullTextSearch(search) },
- name: { search: sanitizeFullTextSearch(search) },
- }
- : {}),
- ...(country && {
- country,
- }),
- ...(linkId && {
- linkId,
- }),
- },
- orderBy: {
- [sortBy]: sortOrder,
- },
- skip: (page - 1) * pageSize,
- take: pageSize,
- ...(includeExpandedFields
- ? {
- include: {
- link: {
- select: {
- id: true,
- domain: true,
- key: true,
- shortLink: true,
- url: true,
- programId: true,
- },
- },
- programEnrollment: {
- include: {
- partner: {
- select: {
- id: true,
- name: true,
- email: true,
- image: true,
- },
- },
- discount: true,
- },
- },
- },
- }
- : {}),
+ const customers = await getCustomers({
+ ...filters,
+ workspaceId: workspace.id,
+ programId,
});
const responseSchema = includeExpandedFields
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/page.tsx
index 5b95f1f889..d7fb02a972 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/customers/page.tsx
@@ -1,3 +1,4 @@
+import { ExportCustomersButton } from "@/ui/customers/export-customers-button";
import { PageContent } from "@/ui/layout/page-content";
import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import { CustomersPageClient } from "./page-client";
@@ -11,6 +12,7 @@ export default function CustomersPage() {
"Get deeper, real-time insights about your customers' demographics, purchasing behavior, and lifetime value (LTV).",
href: "https://dub.co/help/article/customer-insights",
}}
+ controls={<ExportCustomersButton />}
>
<PageWidthWrapper>
<CustomersPageClient />
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/(index)/layout.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/(index)/layout.tsx
index 8f0d084a53..8cd8b21dac 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/(index)/layout.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/customers/(index)/layout.tsx
@@ -4,6 +4,7 @@ import { REFERRAL_ENABLED_PROGRAM_IDS } from "@/lib/referrals/constants";
import useCustomersCount from "@/lib/swr/use-customers-count";
import { useProgramReferralsCount } from "@/lib/swr/use-program-referrals-count";
import useWorkspace from "@/lib/swr/use-workspace";
+import { ExportCustomersButton } from "@/ui/customers/export-customers-button";
import { PageContent } from "@/ui/layout/page-content";
import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import { InfoTooltip } from "@dub/ui";
@@ -64,6 +65,7 @@ export default function PartnerCustomersLayout({
"Get deeper, real-time insights about your referred customers' demographics, purchasing behavior, and lifetime value (LTV).",
href: "https://dub.co/help/article/customer-insights",
}}
+ controls={<ExportCustomersButton />}
>
<PageWidthWrapper className="flex flex-col gap-3 pb-10">
{tabs.length > 0 && (
diff --git a/apps/web/lib/customers/api/customer-count-where.ts b/apps/web/lib/customers/api/customer-count-where.ts
new file mode 100644
index 0000000000..6c8c18fcf6
--- /dev/null
+++ b/apps/web/lib/customers/api/customer-count-where.ts
@@ -0,0 +1,56 @@
+import { getCustomersCountQuerySchema } from "@/lib/zod/schemas/customers";
+import { sanitizeFullTextSearch } from "@dub/prisma";
+import { Prisma } from "@dub/prisma/client";
+import * as z from "zod/v4";
+
+type CustomerCountFilters = z.infer<typeof getCustomersCountQuerySchema> & {
+ workspaceId: string;
+};
+
+export function buildCustomerCountWhere(filters: CustomerCountFilters) {
+ const {
+ programId,
+ partnerId,
+ workspaceId,
+ email,
+ externalId,
+ search,
+ country,
+ linkId,
+ groupBy,
+ } = filters;
+
+ const customerWhereInput: Prisma.CustomerWhereInput = {
+ ...(programId && {
+ programId,
+ }),
+ ...(partnerId && {
+ partnerId,
+ }),
+ projectId: workspaceId,
+ ...(email
+ ? { email }
+ : externalId
+ ? { externalId }
+ : search
+ ? search.includes("@")
+ ? { email: search }
+ : {
+ email: { search: sanitizeFullTextSearch(search) },
+ name: { search: sanitizeFullTextSearch(search) },
+ }
+ : {}),
+ // 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,
+ }),
+ };
+
+ return customerWhereInput;
+}
diff --git a/apps/web/lib/customers/api/fetch-customers-batch.ts b/apps/web/lib/customers/api/fetch-customers-batch.ts
new file mode 100644
index 0000000000..9b48384435
--- /dev/null
+++ b/apps/web/lib/customers/api/fetch-customers-batch.ts
@@ -0,0 +1,32 @@
+import { getCustomers } from "@/lib/customers/api/get-customers";
+import { customersExportCronInputSchema } from "@/lib/zod/schemas/customers";
+import * as z from "zod/v4";
+
+type CustomersExportFilters = z.infer<typeof customersExportCronInputSchema>;
+
+export async function* fetchCustomersBatch(
+ filters: CustomersExportFilters,
+ pageSize: number = 1000,
+) {
+ const { columns: _columns, ...filtersRest } = filters;
+
+ let page = 1;
+ let hasMore = true;
+
+ while (hasMore) {
+ const customers = await getCustomers({
+ ...filtersRest,
+ page,
+ pageSize,
+ includeExpandedFields: true,
+ });
+
+ if (customers.length > 0) {
+ yield { customers };
+ page++;
+ hasMore = customers.length === pageSize;
+ } else {
+ hasMore = false;
+ }
+ }
+}
diff --git a/apps/web/lib/customers/api/format-customers-export.ts b/apps/web/lib/customers/api/format-customers-export.ts
new file mode 100644
index 0000000000..32db76dacd
--- /dev/null
+++ b/apps/web/lib/customers/api/format-customers-export.ts
@@ -0,0 +1,64 @@
+import {
+ CUSTOMER_EXPORT_COLUMNS,
+ CUSTOMER_EXPORT_DEFAULT_COLUMNS,
+} from "@/lib/zod/schemas/customers";
+import type { Customer, Link, ProgramEnrollment } from "@dub/prisma/client";
+
+type CustomerForExport = Customer & {
+ link?: Pick<Link, "shortLink" | "url"> | null;
+ programEnrollment?:
+ | (ProgramEnrollment & {
+ partner: {
+ id: string;
+ name: string | null;
+ email: string | null;
+ image: string | null;
+ };
+ })
+ | null;
+};
+
+const dateToIso = (d: Date | null) => (d ? d.toISOString() : "");
+
+const columnOrderById = new Map<string, number>(
+ CUSTOMER_EXPORT_COLUMNS.map((col) => [col.id, col.order]),
+);
+
+export function formatCustomersForExport(
+ customers: CustomerForExport[],
+ columns: string[] = CUSTOMER_EXPORT_DEFAULT_COLUMNS,
+) {
+ const sortedColumns = [...columns].sort(
+ (a, b) => (columnOrderById.get(a) ?? 999) - (columnOrderById.get(b) ?? 999),
+ );
+
+ return customers.map((c) => {
+ const partner = c.programEnrollment?.partner;
+ const link = c.link;
+
+ const full: Record<string, string | number> = {
+ id: c.id,
+ name: c.name || c.email || "",
+ email: c.email ?? "",
+ avatar: c.avatar ?? "",
+ externalId: c.externalId ?? "",
+ stripeCustomerId: c.stripeCustomerId ?? "",
+ country: c.country ?? "",
+ sales: c.sales ?? 0,
+ saleAmount: c.saleAmount ?? 0,
+ createdAt: dateToIso(c.createdAt),
+ firstSaleAt: dateToIso(c.firstSaleAt),
+ subscriptionCanceledAt: dateToIso(c.subscriptionCanceledAt),
+ link: link?.shortLink ?? link?.url ?? "",
+ partnerId: partner?.id ?? "",
+ partnerName: partner?.name ?? "",
+ partnerEmail: partner?.email ?? "",
+ partnerTenantId: c.programEnrollment?.tenantId ?? "",
+ };
+
+ 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/customers/api/get-customers.ts b/apps/web/lib/customers/api/get-customers.ts
new file mode 100644
index 0000000000..1a5650b658
--- /dev/null
+++ b/apps/web/lib/customers/api/get-customers.ts
@@ -0,0 +1,95 @@
+import { getCustomersQuerySchemaExtended } from "@/lib/zod/schemas/customers";
+import { prisma, sanitizeFullTextSearch } from "@dub/prisma";
+import * as z from "zod/v4";
+
+type GetCustomersInput = z.infer<typeof getCustomersQuerySchemaExtended> & {
+ workspaceId: string;
+};
+
+export async function getCustomers(filters: GetCustomersInput) {
+ const {
+ customerIds,
+ programId,
+ partnerId,
+ workspaceId,
+ email,
+ externalId,
+ search,
+ country,
+ linkId,
+ sortBy,
+ sortOrder,
+ page,
+ pageSize,
+ includeExpandedFields,
+ } = filters;
+
+ return await prisma.customer.findMany({
+ where: {
+ ...(customerIds
+ ? {
+ id: { in: customerIds },
+ }
+ : {}),
+ ...(programId && {
+ programId,
+ }),
+ ...(partnerId && {
+ partnerId,
+ }),
+ projectId: workspaceId,
+ ...(email
+ ? { email }
+ : externalId
+ ? { externalId }
+ : search
+ ? search.includes("@")
+ ? { email: search }
+ : {
+ email: { search: sanitizeFullTextSearch(search) },
+ name: { search: sanitizeFullTextSearch(search) },
+ }
+ : {}),
+ ...(country && {
+ country,
+ }),
+ ...(linkId && {
+ linkId,
+ }),
+ },
+ orderBy: {
+ [sortBy]: sortOrder,
+ },
+ skip: (page - 1) * pageSize,
+ take: pageSize,
+ ...(includeExpandedFields
+ ? {
+ include: {
+ link: {
+ select: {
+ id: true,
+ domain: true,
+ key: true,
+ shortLink: true,
+ url: true,
+ programId: true,
+ },
+ },
+ programEnrollment: {
+ include: {
+ partner: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+ },
+ },
+ discount: true,
+ },
+ },
+ },
+ }
+ : {}),
+ });
+}
diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.ts
index 648e3ae3a3..3980e66b11 100644
--- a/apps/web/lib/zod/schemas/customers.ts
+++ b/apps/web/lib/zod/schemas/customers.ts
@@ -202,3 +202,183 @@ export const StripeCustomerInvoiceSchema = z.object({
metadata: z.any(),
dubCommissionId: z.string().nullish(),
});
+
+export const CUSTOMER_EXPORT_COLUMNS = [
+ {
+ id: "id",
+ label: "ID",
+ type: "string",
+ default: true,
+ order: 1,
+ programOnly: false,
+ },
+ {
+ id: "name",
+ label: "Name",
+ type: "string",
+ default: true,
+ order: 2,
+ programOnly: false,
+ },
+ {
+ id: "email",
+ label: "Email",
+ type: "string",
+ default: true,
+ order: 3,
+ programOnly: false,
+ },
+ {
+ id: "avatar",
+ label: "Avatar",
+ type: "string",
+ default: true,
+ order: 4,
+ programOnly: false,
+ },
+ {
+ id: "externalId",
+ label: "External ID",
+ type: "string",
+ default: true,
+ order: 5,
+ programOnly: false,
+ },
+ {
+ id: "stripeCustomerId",
+ label: "Stripe customer ID",
+ type: "string",
+ default: true,
+ order: 6,
+ programOnly: false,
+ },
+ {
+ id: "country",
+ label: "Country",
+ type: "string",
+ default: true,
+ order: 7,
+ programOnly: false,
+ },
+ {
+ id: "sales",
+ label: "Sales",
+ type: "number",
+ default: true,
+ order: 8,
+ programOnly: false,
+ },
+ {
+ id: "saleAmount",
+ label: "Sale amount",
+ type: "number",
+ default: true,
+ order: 9,
+ programOnly: false,
+ },
+ {
+ id: "createdAt",
+ label: "Created at",
+ type: "date",
+ default: true,
+ order: 10,
+ programOnly: false,
+ },
+ {
+ id: "firstSaleAt",
+ label: "First sale at",
+ type: "date",
+ default: true,
+ order: 11,
+ programOnly: false,
+ },
+ {
+ id: "subscriptionCanceledAt",
+ label: "Subscription canceled",
+ type: "date",
+ default: true,
+ order: 12,
+ programOnly: false,
+ },
+ {
+ id: "link",
+ label: "Link",
+ type: "string",
+ default: false,
+ order: 13,
+ programOnly: false,
+ },
+ {
+ id: "partnerId",
+ label: "Partner ID",
+ type: "string",
+ default: false,
+ order: 14,
+ programOnly: true,
+ },
+ {
+ id: "partnerName",
+ label: "Partner name",
+ type: "string",
+ default: false,
+ order: 15,
+ programOnly: true,
+ },
+ {
+ id: "partnerEmail",
+ label: "Partner email",
+ type: "string",
+ default: false,
+ order: 16,
+ programOnly: true,
+ },
+ {
+ id: "partnerTenantId",
+ label: "Partner tenant ID",
+ type: "string",
+ default: false,
+ order: 17,
+ programOnly: true,
+ },
+] as const;
+
+type CustomerExportColumnId = (typeof CUSTOMER_EXPORT_COLUMNS)[number]["id"];
+
+export const CUSTOMER_EXPORT_DEFAULT_COLUMNS = CUSTOMER_EXPORT_COLUMNS.filter(
+ (column) => column.default,
+).map((column) => column.id);
+
+export const customersExportQuerySchema = getCustomersQuerySchema
+ .omit({
+ page: true,
+ pageSize: true,
+ includeExpandedFields: true,
+ })
+ .extend({
+ columns: z
+ .string()
+ .optional()
+ .default(CUSTOMER_EXPORT_DEFAULT_COLUMNS.join(","))
+ .transform((v) => v.split(","))
+ .refine(
+ (columns) => {
+ const validColumnIds = CUSTOMER_EXPORT_COLUMNS.map((col) => col.id);
+
+ return columns.every((column: CustomerExportColumnId) =>
+ validColumnIds.includes(column),
+ );
+ },
+ {
+ message:
+ "Invalid column IDs provided. Please check the available columns.",
+ },
+ ),
+ });
+
+export const customersExportCronInputSchema = customersExportQuerySchema.extend(
+ {
+ workspaceId: z.string(),
+ programId: z.string().optional(),
+ userId: z.string(),
+ },
+);
diff --git a/apps/web/ui/customers/export-customers-button.tsx b/apps/web/ui/customers/export-customers-button.tsx
new file mode 100644
index 0000000000..caccc10e2f
--- /dev/null
+++ b/apps/web/ui/customers/export-customers-button.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { useExportCustomersModal } from "@/ui/modals/export-customers-modal";
+import { ThreeDots } from "@/ui/shared/icons";
+import { Button, Download, IconMenu, Popover } from "@dub/ui";
+import { useState } from "react";
+
+export function ExportCustomersButton() {
+ const [openPopover, setOpenPopover] = useState(false);
+
+ const { ExportCustomersModal, setShowExportCustomersModal } =
+ useExportCustomersModal();
+
+ return (
+ <>
+ <ExportCustomersModal />
+ <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);
+ setShowExportCustomersModal(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-commissions-modal.tsx b/apps/web/ui/modals/export-commissions-modal.tsx
index ece566c0ca..0af58b466e 100644
--- a/apps/web/ui/modals/export-commissions-modal.tsx
+++ b/apps/web/ui/modals/export-commissions-modal.tsx
@@ -1,3 +1,5 @@
+"use client";
+
import { generateExportFilename } from "@/lib/api/utils/generate-export-filename";
import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
@@ -9,7 +11,6 @@ import {
Button,
Checkbox,
InfoTooltip,
- Logo,
Modal,
Switch,
useRouterStuff,
@@ -89,8 +90,8 @@ function ExportCommissionsModal({
});
if (!response.ok) {
- const { error } = await response.json();
- throw new Error(error.message);
+ const body = await response.json();
+ throw new Error(body.error?.message ?? "Commission export failed");
}
if (response.status === 202) {
@@ -104,15 +105,16 @@ function ExportCommissionsModal({
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
-
a.href = url;
a.download = generateExportFilename("commissions");
a.click();
- toast.success("Exported successfully");
+ toast.success("Commissions exported successfully");
setShowExportCommissionsModal(false);
} catch (error) {
- toast.error(error);
+ toast.error(
+ error instanceof Error ? error.message : "Commission export failed",
+ );
} finally {
toast.dismiss(lid);
}
@@ -122,72 +124,83 @@ function ExportCommissionsModal({
<Modal
showModal={showExportCommissionsModal}
setShowModal={setShowExportCommissionsModal}
- className="max-w-lg"
>
- <div className="flex flex-col items-center justify-center space-y-3 border-b border-neutral-200 px-4 py-4 pt-8 sm:px-16">
- <Logo />
- <div className="flex flex-col space-y-1 text-center">
- <h3 className="text-lg font-medium">Export commissions</h3>
- <p className="text-sm text-neutral-500">
- Export this program's commissions to a CSV file
- </p>
- </div>
+ <div className="border-b border-neutral-200 p-4 sm:p-6">
+ <h3 className="text-lg font-medium leading-none">Export commissions</h3>
</div>
- <form
- onSubmit={onSubmit}
- className="flex flex-col gap-6 bg-neutral-50 px-4 py-8 text-left sm:rounded-b-2xl sm:px-12"
- >
- <div>
- <p className="block text-sm font-medium text-neutral-700">Columns</p>
+ <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">
+ {COMMISSION_EXPORT_COLUMNS.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="columns"
+ name="useFilters"
control={control}
render={({ field }) => (
- <div className="xs:grid-cols-2 mt-2 grid grid-cols-1 gap-x-4 gap-y-2">
- {COMMISSION_EXPORT_COLUMNS.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 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 commissions by your currently selected filters" />
+ </span>
+ <Switch checked={field.value} fn={field.onChange} />
</div>
)}
/>
</div>
- <div className="border-t border-neutral-200" />
-
- <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 commissions by your currently selected filters" />
- </span>
- <Switch checked={field.value} fn={field.onChange} />
- </div>
- )}
- />
- <Button loading={isSubmitting} text="Export commissions" />
+ <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={() => setShowExportCommissionsModal(false)}
+ variant="secondary"
+ text="Cancel"
+ className="h-8 w-fit px-3"
+ type="button"
+ />
+ <Button
+ type="submit"
+ loading={isSubmitting}
+ text="Export commissions"
+ className="h-8 w-fit px-3"
+ />
+ </div>
</form>
</Modal>
);
diff --git a/apps/web/ui/modals/export-customers-modal.tsx b/apps/web/ui/modals/export-customers-modal.tsx
new file mode 100644
index 0000000000..92531b4305
--- /dev/null
+++ b/apps/web/ui/modals/export-customers-modal.tsx
@@ -0,0 +1,262 @@
+"use client";
+
+import { generateExportFilename } from "@/lib/api/utils/generate-export-filename";
+import useProgram from "@/lib/swr/use-program";
+import useWorkspace from "@/lib/swr/use-workspace";
+import {
+ CUSTOMER_EXPORT_COLUMNS,
+ CUSTOMER_EXPORT_DEFAULT_COLUMNS,
+} from "@/lib/zod/schemas/customers";
+import {
+ Button,
+ Checkbox,
+ InfoTooltip,
+ Modal,
+ Switch,
+ useRouterStuff,
+} from "@dub/ui";
+import { useSession } from "next-auth/react";
+import { usePathname } 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 ExportCustomersModal({
+ showExportCustomersModal,
+ setShowExportCustomersModal,
+}: {
+ showExportCustomersModal: boolean;
+ setShowExportCustomersModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const pathname = usePathname();
+
+ const { program } = useProgram();
+ const { data: session } = useSession();
+ const { id: workspaceId } = useWorkspace();
+ const { getQueryString } = useRouterStuff();
+
+ const columnCheckboxId = useId();
+
+ const {
+ control,
+ handleSubmit,
+ formState: { isSubmitting },
+ } = useForm<FormData>({
+ defaultValues: {
+ columns: CUSTOMER_EXPORT_DEFAULT_COLUMNS,
+ useFilters: true,
+ },
+ });
+
+ const scope = pathname.includes("/program") ? "program" : "workspace";
+
+ const visibleColumns = useMemo(() => {
+ const cols =
+ scope === "program"
+ ? [...CUSTOMER_EXPORT_COLUMNS]
+ : CUSTOMER_EXPORT_COLUMNS.filter((col) => !col.programOnly);
+
+ return cols.sort((a, b) => a.order - b.order);
+ }, [scope]);
+
+ const onSubmit = handleSubmit(async (data) => {
+ if (!workspaceId) {
+ return;
+ }
+
+ if (scope === "program" && !program?.id) {
+ return;
+ }
+
+ const lid = toast.loading("Exporting customers...");
+
+ try {
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+
+ const programOnlyIds = new Set<string>(
+ CUSTOMER_EXPORT_COLUMNS.filter((col) => col.programOnly).map(
+ (col) => col.id,
+ ),
+ );
+
+ const columns =
+ scope === "program"
+ ? data.columns
+ : data.columns.filter((c) => !programOnlyIds.has(c));
+
+ let baseParams: Record<string, string> = {
+ timezone,
+ workspaceId,
+ ...(columns.length ? { columns: columns.join(",") } : {}),
+ };
+
+ if (scope === "program" && program?.id) {
+ baseParams = {
+ ...baseParams,
+ programId: program?.id,
+ };
+ }
+
+ const queryString = data.useFilters
+ ? getQueryString(baseParams)
+ : `?${new URLSearchParams(baseParams).toString()}`;
+
+ const response = await fetch(`/api/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.`,
+ );
+ setShowExportCustomersModal(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");
+ setShowExportCustomersModal(false);
+ } catch (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Customer export failed",
+ );
+ } finally {
+ toast.dismiss(lid);
+ }
+ });
+
+ return (
+ <Modal
+ showModal={showExportCustomersModal}
+ setShowModal={setShowExportCustomersModal}
+ >
+ <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={() => setShowExportCustomersModal(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 useExportCustomersModal() {
+ const [showExportCustomersModal, setShowExportCustomersModal] =
+ useState(false);
+
+ const ExportCustomersModalCallback = useCallback(() => {
+ return (
+ <ExportCustomersModal
+ showExportCustomersModal={showExportCustomersModal}
+ setShowExportCustomersModal={setShowExportCustomersModal}
+ />
+ );
+ }, [showExportCustomersModal, setShowExportCustomersModal]);
+
+ return useMemo(
+ () => ({
+ setShowExportCustomersModal,
+ ExportCustomersModal: ExportCustomersModalCallback,
+ }),
+ [setShowExportCustomersModal, ExportCustomersModalCallback],
+ );
+}
diff --git a/packages/email/src/templates/export-ready.tsx b/packages/email/src/templates/export-ready.tsx
index 3c5a67b7ab..83525f6fa1 100644
--- a/packages/email/src/templates/export-ready.tsx
+++ b/packages/email/src/templates/export-ready.tsx
@@ -24,7 +24,7 @@ export default function ExportReady({
}: {
email: string;
downloadUrl: string;
- exportType: "partners" | "commissions" | "links" | "events";
+ exportType: "partners" | "commissions" | "links" | "events" | "customers";
expiresInDays?: number;
program?: {
name: string;
diff --git a/packages/ui/src/table/selection-toolbar.tsx b/packages/ui/src/table/selection-toolbar.tsx
index 382d177794..1a05505142 100644
--- a/packages/ui/src/table/selection-toolbar.tsx
+++ b/packages/ui/src/table/selection-toolbar.tsx
@@ -50,7 +50,7 @@ export function SelectionToolbar<T>({
title="Select all"
>
<Checkbox
- className="pointer-events-none border-border-default size-4 rounded data-[state=checked]:bg-black data-[state=indeterminate]:bg-black"
+ className="border-border-default pointer-events-none size-4 rounded data-[state=checked]:bg-black data-[state=indeterminate]:bg-black"
checked={
table.getIsAllRowsSelected()
? true