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 commissions as CSV

Kiran K67850e13dde0
diff --git a/apps/web/app/(ee)/api/commissions/export/route.ts b/apps/web/app/(ee)/api/commissions/export/route.ts
new file mode 100644
index 0000000000..130c912084
--- /dev/null
+++ b/apps/web/app/(ee)/api/commissions/export/route.ts
@@ -0,0 +1,151 @@
+import { convertToCSV } from "@/lib/analytics/utils";
+import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";
+import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
+import { withWorkspace } from "@/lib/auth";
+import {
+ COMMISSION_EXPORT_COLUMNS,
+ commissionsExportQuerySchema,
+ getCommissionsQuerySchema,
+} from "@/lib/zod/schemas/commissions";
+import { prisma } from "@dub/prisma";
+import { z } from "zod";
+
+const COLUMN_LOOKUP: Map<
+ string,
+ { label: string; type: string; order: number }
+> = new Map(
+ COMMISSION_EXPORT_COLUMNS.map((column, index) => [
+ column.id,
+ {
+ label: column.label,
+ type: column.type,
+ order: index + 1,
+ },
+ ]),
+);
+
+// Define the Zod schemas for each column type
+const COLUMN_TYPE_SCHEMAS = {
+ number: z.coerce
+ .number()
+ .nullable()
+ .default(0)
+ .transform((value) => value || 0),
+ date: z.date().transform((date) => date?.toISOString() || ""),
+ string: z
+ .string()
+ .nullable()
+ .default("")
+ .transform((value) => value || ""),
+};
+
+// GET /api/commissions/export – export commissions to CSV
+export const GET = withWorkspace(async ({ searchParams, workspace }) => {
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ let { columns, ...filters } =
+ commissionsExportQuerySchema.parse(searchParams);
+
+ // Parse the search filters
+ const {
+ status,
+ type,
+ customerId,
+ payoutId,
+ partnerId,
+ invoiceId,
+ sortBy,
+ sortOrder,
+ start,
+ end,
+ interval,
+ } = getCommissionsQuerySchema.parse(filters);
+
+ const { startDate, endDate } = getStartEndDates({
+ interval,
+ start,
+ end,
+ });
+
+ // Find commissions that match the filters
+ const commissions = await prisma.commission.findMany({
+ where: invoiceId
+ ? {
+ invoiceId,
+ programId,
+ }
+ : {
+ earnings: {
+ not: 0,
+ },
+ programId,
+ partnerId,
+ status,
+ type,
+ customerId,
+ payoutId,
+ createdAt: {
+ gte: startDate.toISOString(),
+ lte: endDate.toISOString(),
+ },
+ },
+ include: {
+ customer: {
+ select: {
+ name: true,
+ email: true,
+ },
+ },
+ partner: {
+ select: {
+ name: true,
+ email: true,
+ },
+ },
+ },
+ take: 1000,
+ orderBy: {
+ [sortBy]: sortOrder,
+ },
+ });
+
+ // Format the commissions
+ const formattedCommissions = commissions.map((commission) => ({
+ ...commission,
+ customerName: commission.customer?.name || "",
+ customerEmail: commission.customer?.email || "",
+ partnerName: commission.partner?.name || "",
+ partnerEmail: commission.partner?.email || "",
+ }));
+
+ // Sort columns by their order
+ columns = columns.sort(
+ (a, b) =>
+ (COLUMN_LOOKUP.get(a)?.order || 999) -
+ (COLUMN_LOOKUP.get(b)?.order || 999),
+ );
+
+ // Build column schemas
+ const columnSchemas: Record<string, z.ZodTypeAny> = {};
+
+ for (const column of columns) {
+ const columnInfo = COLUMN_LOOKUP.get(column);
+
+ if (!columnInfo) {
+ continue;
+ }
+
+ columnSchemas[column] = COLUMN_TYPE_SCHEMAS[columnInfo.type];
+ }
+
+ // Prepare the data for export
+ const data = z.array(z.object(columnSchemas)).parse(formattedCommissions);
+ const csvData = convertToCSV(data);
+
+ return new Response(csvData, {
+ headers: {
+ "Content-Type": "text/csv",
+ "Content-Disposition": `attachment; filename="Dub Commissions Export - ${new Date().toISOString()}.csv"`,
+ },
+ });
+});
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/commission-popover-buttons.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/commission-popover-buttons.tsx
index c8574c34cd..340bdea376 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/commission-popover-buttons.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/commission-popover-buttons.tsx
@@ -1,7 +1,8 @@
"use client";
+import { useExportCommissionsModal } from "@/ui/modals/export-commissions-modal";
import { ThreeDots } from "@/ui/shared/icons";
-import { Button, IconMenu, Popover, Refresh2 } from "@dub/ui";
+import { Button, Download, IconMenu, Popover, Refresh2 } from "@dub/ui";
import { useState } from "react";
import { useCreateClawbackSheet } from "./create-clawback-sheet";
@@ -11,9 +12,13 @@ export function CommissionPopoverButtons() {
const { createClawbackSheet, setIsOpen: setClawbackSheetOpen } =
useCreateClawbackSheet({});
+ const { ExportCommissionsModal, setShowExportCommissionsModal } =
+ useExportCommissionsModal();
+
return (
<>
{createClawbackSheet}
+ <ExportCommissionsModal />
<Popover
content={
<div className="w-full md:w-52">
@@ -31,6 +36,26 @@ export function CommissionPopoverButtons() {
/>
</button>
</div>
+
+ <div className="border-t border-neutral-200" />
+
+ <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 Commissions
+ </p>
+ <button
+ onClick={() => {
+ setOpenPopover(false);
+ setShowExportCommissionsModal(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}
diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.ts
index a50ff45edf..a9321fd91c 100644
--- a/apps/web/lib/zod/schemas/commissions.ts
+++ b/apps/web/lib/zod/schemas/commissions.ts
@@ -203,3 +203,71 @@ export const createClawbackSchema = z.object({
CLAWBACK_REASONS.map((r) => r.value) as [string, ...string[]],
),
});
+
+export const COMMISSION_EXPORT_COLUMNS = [
+ { id: "id", label: "ID", type: "string", default: true },
+ { id: "type", label: "Type", type: "string", default: true },
+ { id: "amount", label: "Amount", type: "number", default: true },
+ { id: "earnings", label: "Earnings", type: "number", default: true },
+ { id: "currency", label: "Currency", type: "string", default: true },
+ { id: "status", label: "Status", type: "string", default: true },
+ { id: "invoiceId", label: "Invoice ID", type: "string", default: true },
+ { id: "quantity", label: "Quantity", type: "number", default: true },
+ { id: "createdAt", label: "Created at", type: "date", default: true },
+ { id: "updatedAt", label: "Updated at", type: "date", default: false },
+ { id: "partnerId", label: "Partner ID", type: "string", default: false },
+ { id: "partnerName", label: "Partner name", type: "string", default: false },
+ {
+ id: "partnerEmail",
+ label: "Partner email",
+ type: "string",
+ default: false,
+ },
+ { id: "customerId", label: "Customer ID", type: "string", default: false },
+ {
+ id: "customerName",
+ label: "Customer name",
+ type: "string",
+ default: false,
+ },
+ {
+ id: "customerEmail",
+ label: "Customer email",
+ type: "string",
+ default: false,
+ },
+] as const;
+
+type CommissionExportColumnId =
+ (typeof COMMISSION_EXPORT_COLUMNS)[number]["id"];
+
+export const DEFAULT_COMMISSION_EXPORT_COLUMNS =
+ COMMISSION_EXPORT_COLUMNS.filter((column) => column.default).map(
+ (column) => column.id,
+ );
+
+export const commissionsExportQuerySchema = getCommissionsQuerySchema
+ .omit({ page: true, pageSize: true })
+ .merge(
+ z.object({
+ columns: z
+ .string()
+ .default(DEFAULT_COMMISSION_EXPORT_COLUMNS.join(","))
+ .transform((v) => v.split(","))
+ .refine(
+ (columns): columns is CommissionExportColumnId[] => {
+ const validColumnIds = COMMISSION_EXPORT_COLUMNS.map(
+ (col) => col.id,
+ );
+
+ return columns.every((column): column is CommissionExportColumnId =>
+ validColumnIds.includes(column as CommissionExportColumnId),
+ );
+ },
+ {
+ message:
+ "Invalid column IDs provided. Please check the available columns.",
+ },
+ ),
+ }),
+ );
diff --git a/apps/web/ui/modals/export-commissions-modal.tsx b/apps/web/ui/modals/export-commissions-modal.tsx
new file mode 100644
index 0000000000..dca40dbbd1
--- /dev/null
+++ b/apps/web/ui/modals/export-commissions-modal.tsx
@@ -0,0 +1,197 @@
+import useProgram from "@/lib/swr/use-program";
+import useWorkspace from "@/lib/swr/use-workspace";
+import {
+ COMMISSION_EXPORT_COLUMNS,
+ DEFAULT_COMMISSION_EXPORT_COLUMNS,
+} from "@/lib/zod/schemas/commissions";
+import {
+ Button,
+ Checkbox,
+ InfoTooltip,
+ Logo,
+ Modal,
+ Switch,
+ useRouterStuff,
+} from "@dub/ui";
+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 ExportCommissionsModal({
+ showExportCommissionsModal,
+ setShowExportCommissionsModal,
+}: {
+ showExportCommissionsModal: boolean;
+ setShowExportCommissionsModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const columnCheckboxId = useId();
+ const { program } = useProgram();
+ const { id: workspaceId } = useWorkspace();
+ const { getQueryString } = useRouterStuff();
+
+ const {
+ control,
+ handleSubmit,
+ formState: { isSubmitting },
+ } = useForm<FormData>({
+ defaultValues: {
+ columns: DEFAULT_COMMISSION_EXPORT_COLUMNS,
+ useFilters: true,
+ },
+ });
+
+ const onSubmit = handleSubmit(async (data) => {
+ if (!workspaceId || !program?.id) {
+ return;
+ }
+
+ const lid = toast.loading("Exporting commissions...");
+
+ try {
+ const params = {
+ workspaceId,
+ ...(data.columns.length
+ ? { columns: data.columns.join(",") }
+ : undefined),
+ };
+
+ const searchParams = data.useFilters
+ ? getQueryString(params)
+ : "?" + new URLSearchParams(params);
+
+ const response = await fetch(`/api/commissions/export${searchParams}`, {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+
+ if (!response.ok) {
+ const { error } = await response.json();
+ throw new Error(error.message);
+ }
+
+ const blob = await response.blob();
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement("a");
+
+ a.href = url;
+ a.download = `Dub Commissions Export - ${new Date().toISOString()}.csv`;
+ a.click();
+
+ toast.success("Exported successfully");
+ setShowExportCommissionsModal(false);
+ } catch (error) {
+ toast.error(error);
+ } finally {
+ toast.dismiss(lid);
+ }
+ });
+
+ return (
+ <Modal
+ showModal={showExportCommissionsModal}
+ setShowModal={setShowExportCommissionsModal}
+ >
+ <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>
+
+ <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>
+ <Controller
+ name="columns"
+ 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>
+ )}
+ />
+ </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" />
+ </form>
+ </Modal>
+ );
+}
+
+export function useExportCommissionsModal() {
+ const [showExportCommissionsModal, setShowExportCommissionsModal] =
+ useState(false);
+
+ const ExportCommissionsModalCallback = useCallback(() => {
+ return (
+ <ExportCommissionsModal
+ showExportCommissionsModal={showExportCommissionsModal}
+ setShowExportCommissionsModal={setShowExportCommissionsModal}
+ />
+ );
+ }, [showExportCommissionsModal, setShowExportCommissionsModal]);
+
+ return useMemo(
+ () => ({
+ setShowExportCommissionsModal,
+ ExportCommissionsModal: ExportCommissionsModalCallback,
+ }),
+ [setShowExportCommissionsModal, ExportCommissionsModalCallback],
+ );
+}