The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add `stripeInvoicesToImport` prop to `POST /commissions`
Steven Teyf92edd01e8df
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-commission-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-commission-sheet.tsxindex 2af5aa7e81..3e4df792b5 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-commission-sheet.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-commission-sheet.tsx@@ -27,7 +27,9 @@ import {Sheet,SmartDateTimePicker,Switch,+ Table,ToggleGroup,+ useTable,} from "@dub/ui";import { cn, currencyFormatter, formatDate } from "@dub/utils";import { CommissionType } from "@prisma/client";@@ -86,6 +88,118 @@ async function fetcherStripeInvoices(url: string): Promise<{return { invoices: Array.isArray(body) ? body : [] };}+function StripeInvoicesToImportTable({+ invoices,+ selectedInvoiceIds,+ onSelectionChange,+ slug,+ partnerId,+ customerId,+}: {+ invoices: StripeInvoiceFromApi[];+ selectedInvoiceIds: string[];+ onSelectionChange: (invoiceIds: string[]) => void;+ slug?: string;+ partnerId?: string;+ customerId?: string | null;+}) {+ const selectedRows = useMemo(+ () =>+ Object.fromEntries(+ selectedInvoiceIds.map((invoiceId) => [invoiceId, true]),+ ),+ [selectedInvoiceIds],+ );++ const { table, ...tableProps } = useTable<StripeInvoiceFromApi>({+ data: invoices,+ columns: [+ {+ id: "invoice",+ header: "Invoice",+ cell: ({ row }) => (+ <div className="min-w-0">+ <a+ href={`https://dashboard.stripe.com/invoices/${row.original.id}`}+ target="_blank"+ rel="noopener noreferrer"+ className={cn(+ "cursor-alias font-mono text-sm font-medium decoration-dotted underline-offset-2 hover:underline",+ row.original.dubCommissionId+ ? "text-neutral-500"+ : "text-neutral-800",+ )}+ >+ {row.original.id}+ </a>+ {(row.original.refunded || row.original.dubCommissionId) && (+ <p className="mt-0.5 flex flex-wrap items-center gap-1.5">+ {row.original.refunded ? (+ <span className="rounded-md bg-neutral-200/80 px-1.5 py-0.5 text-xs text-neutral-500">+ Refunded+ </span>+ ) : null}+ {row.original.dubCommissionId ? (+ <a+ href={`/${slug}/program/commissions?partnerId=${partnerId}&customerId=${customerId}`}+ target="_blank"+ className="rounded bg-neutral-200/80 px-1.5 py-0.5 text-xs text-neutral-500 hover:bg-neutral-200 hover:text-neutral-900"+ >+ Already imported+ </a>+ ) : null}+ </p>+ )}+ </div>+ ),+ },+ {+ id: "date",+ header: "Date",+ cell: ({ row }) => formatDate(row.original.createdAt),+ },+ {+ id: "amount",+ header: "Amount",+ cell: ({ row }) => (+ <span+ className={cn(+ "font-medium",+ row.original.dubCommissionId+ ? "text-neutral-500"+ : "text-neutral-700",+ )}+ >+ {currencyFormatter(row.original.amount)}+ </span>+ ),+ },+ ],+ getRowId: (invoice) => invoice.id,+ enableRowSelection: (row) => !row.original.dubCommissionId,+ selectedRows,+ onRowSelectionChange: (rows) =>+ onSelectionChange(rows.map((row) => row.original.id)),+ onRowClick: (row) => {+ if (row.getCanSelect()) {+ row.toggleSelected();+ }+ },+ rowProps: (row) => ({+ className: cn(row.original.dubCommissionId && "opacity-60"),+ }),+ resourceName: (plural) => `invoice${plural ? "s" : ""}`,+ thClassName: (id) =>+ cn("border-l-0", id === "amount" && "[&>div]:justify-end"),+ tdClassName: (id) => cn("border-l-0", id === "amount" && "text-right"),+ className: "[&_tr:last-child>td]:border-b-transparent",+ containerClassName: "border-border-default",+ scrollWrapperClassName: "min-h-0 max-h-96",+ });++ return <Table {...tableProps} table={table} />;+}+function CreateCommissionSheetContent({setIsOpen,}: CreateCommissionSheetProps) {@@ -206,6 +320,21 @@ function CreateCommissionSheetContent({const unimportedStripeInvoices = stripeInvoices.filter((inv) => !inv.dubCommissionId,);+ const unimportedStripeInvoiceIdsKey = unimportedStripeInvoices+ .map((invoice) => invoice.id)+ .join(",");+ const unimportedStripeInvoiceIds = useMemo(+ () => unimportedStripeInvoiceIdsKey.split(",").filter(Boolean),+ [unimportedStripeInvoiceIdsKey],+ );+ const [selectedStripeInvoiceIds, setSelectedStripeInvoiceIds] = useState<+ string[]+ >([]);+ const [selectionInvoiceIdsKey, setSelectionInvoiceIdsKey] = useState("");+ const selectedInvoiceIdsToImport =+ selectionInvoiceIdsKey === unimportedStripeInvoiceIdsKey+ ? selectedStripeInvoiceIds+ : unimportedStripeInvoiceIds;const noStripeCustomerId = stripeInvoicesData?.noStripeCustomerId ?? false;const noStripeCustomerMessage = stripeInvoicesData?.message;@@ -277,9 +406,9 @@ function CreateCommissionSheetContent({partnerId,customerId: data.customerId,linkId: data.linkId,- importStripeInvoices,...(importStripeInvoices? {+ stripeInvoicesToImport: selectedInvoiceIdsToImport,saleAmount: null,saleEventDate: null,invoiceId: null,@@ -337,6 +466,10 @@ function CreateCommissionSheetContent({if (unimportedStripeInvoices.length === 0) {return "No unimported Stripe invoices found for this customer.";}++ if (selectedInvoiceIdsToImport.length === 0) {+ return "You need to select at least one invoice to import.";+ }} else {if (!saleAmount) {return "You need to enter a sale amount for the commission.";@@ -355,6 +488,7 @@ function CreateCommissionSheetContent({importStripeInvoices,noStripeCustomerId,unimportedStripeInvoices.length,+ selectedInvoiceIdsToImport.length,isStripeInvoicesLoading,]);@@ -699,67 +833,20 @@ function CreateCommissionSheetContent({</p></div>) : (- <div className="overflow-hidden rounded-lg border border-neutral-200 bg-white shadow-sm">- <div className="border-b border-neutral-100 bg-neutral-50/80 px-3 py-2">- <p className="text-xs font-medium text-neutral-500">- Paid invoices ({stripeInvoices.length})- </p>- </div>- <div className="max-h-96 overflow-y-auto p-1.5">- {stripeInvoices.map((inv) => (- <div- key={inv.id}- className={cn(- "flex items-center justify-between gap-3 rounded-md px-3 py-2.5",- inv.dubCommissionId &&- "bg-neutral-50/80 opacity-75",- )}- >- <div className="min-w-0 flex-1">- <a- href={`https://dashboard.stripe.com/invoices/${inv.id}`}- target="_blank"- rel="noopener noreferrer"- className={cn(- "cursor-alias font-mono text-sm font-medium decoration-dotted underline-offset-2 hover:underline",- inv.dubCommissionId- ? "text-neutral-500"- : "text-neutral-800",- )}- >- {inv.id}- </a>- <p className="mt-0.5 flex flex-wrap items-center gap-x-2 text-xs text-neutral-500">- {formatDate(inv.createdAt)}- {inv.refunded ? (- <span className="rounded-md bg-neutral-200/80 px-1.5 py-0.5 text-xs text-neutral-500">- Refunded- </span>- ) : inv.dubCommissionId ? (- <a- href={`/${slug}/program/commissions?partnerId=${partnerId}&customerId=${customerId}`}- target="_blank"- className="rounded bg-neutral-200/80 px-1.5 py-0.5 text-neutral-500 hover:bg-neutral-200 hover:text-neutral-900"- >- Already imported- </a>- ) : null}- </p>- </div>- <span- className={cn(- "shrink-0 text-sm font-medium",- inv.dubCommissionId- ? "text-neutral-500"- : "text-neutral-700",- )}- >- {currencyFormatter(inv.amount)}- </span>- </div>- ))}- </div>- </div>+ <StripeInvoicesToImportTable+ key={`${customerId}:${unimportedStripeInvoiceIdsKey}`}+ invoices={stripeInvoices}+ selectedInvoiceIds={selectedInvoiceIdsToImport}+ onSelectionChange={(invoiceIds) => {+ setSelectionInvoiceIdsKey(+ unimportedStripeInvoiceIdsKey,+ );+ setSelectedStripeInvoiceIds(invoiceIds);+ }}+ slug={slug}+ partnerId={partnerId}+ customerId={customerId}+ />)}</div>)}@@ -1064,7 +1151,7 @@ function CreateCommissionSheetContent({<Buttontype="submit"variant="primary"- text={`Create commission${unimportedStripeInvoices.length > 0 ? "s" : ""}`}+ text={`Create commission${importStripeInvoices && selectedInvoiceIdsToImport.length !== 1 ? "s" : ""}`}className="w-fit"loading={isSubmitting}disabledTooltip={submitDisabledMessage}diff --git a/apps/web/lib/api/commissions/create-manual-commissions.ts b/apps/web/lib/api/commissions/create-manual-commissions.tsindex 1b72fd2f47..34656ebf6a 100644--- a/apps/web/lib/api/commissions/create-manual-commissions.ts+++ b/apps/web/lib/api/commissions/create-manual-commissions.ts@@ -42,9 +42,6 @@ type CreateCommissionsArgs = z.infer<workspace: Pick<Project, "id" | "slug" | "stripeConnectId">;programId: string;user: Session["user"];- // Only import these Stripe invoices when `importStripeInvoices` is true.- // Not part of the API schema. Scripts use it to skip invoices that should not be attributed.- stripeInvoiceIds?: string[];};type ResolveLinkAndCustomerArgs = CreateCommissionsArgs & {@@ -81,6 +78,14 @@ const saleEventSchemaTBWithTimestamp = saleEventSchemaTB.extend({});export async function createManualCommissions(args: CreateCommissionsArgs) {+ if (+ args.type === "sale" &&+ args.importStripeInvoices &&+ args.stripeInvoicesToImport == null+ ) {+ args = { ...args, stripeInvoicesToImport: "all" };+ }+const { workspace, programId, partnerId, type, user } = args;const { partner, links } = await getProgramEnrollmentOrThrow({@@ -121,9 +126,9 @@ export async function createManualCommissions(args: CreateCommissionsArgs) {});if (type === "sale") {- const { importStripeInvoices, sale } = args;+ const { stripeInvoicesToImport, sale } = args;- if (importStripeInvoices) {+ if (stripeInvoicesToImport) {if (!workspace.stripeConnectId) {throw new DubApiError({code: "bad_request",@@ -551,23 +556,50 @@ async function recordEvents(args: RecordEventsArgs) {if (type === "lead") {finalLeadEventDate = args.date ?? args.leadEventDate ?? new Date();- } else if (args.importStripeInvoices) {+ } else if (args.stripeInvoicesToImport) {+ const { stripeInvoicesToImport } = args;+stripeCustomerInvoices = await getCustomerStripeInvoices({stripeCustomerId: targetCustomer.stripeCustomerId!,stripeConnectId: workspace.stripeConnectId!,programId,});- // Filter out invoices that are already associated with a commission on Dub- stripeCustomerInvoices = stripeCustomerInvoices.filter(- (invoice) => !invoice.dubCommissionId,- );+ if (stripeInvoicesToImport === "all") {+ // Filter out invoices that are already associated with a commission on Dub+ stripeCustomerInvoices = stripeCustomerInvoices.filter(+ (invoice) => !invoice.dubCommissionId,+ );+ } else {+ const invoicesById = new Map(+ stripeCustomerInvoices.map((invoice) => [invoice.id, invoice]),+ );+ const requestedInvoiceIds = [...new Set(stripeInvoicesToImport)];++ const notFoundInvoiceIds = requestedInvoiceIds.filter(+ (id) => !invoicesById.has(id),+ );++ if (notFoundInvoiceIds.length > 0) {+ throw new DubApiError({+ code: "bad_request",+ message: `No paid Stripe invoices found for customer with the IDs: ${notFoundInvoiceIds.join(", ")}`,+ });+ }++ const importedInvoiceIds = requestedInvoiceIds.filter(+ (id) => invoicesById.get(id)!.dubCommissionId,+ );- if (args.stripeInvoiceIds) {- const stripeInvoiceIds = new Set(args.stripeInvoiceIds);+ if (importedInvoiceIds.length > 0) {+ throw new DubApiError({+ code: "conflict",+ message: `There is already a commission for the invoices: ${importedInvoiceIds.join(", ")}`,+ });+ }- stripeCustomerInvoices = stripeCustomerInvoices.filter((invoice) =>- stripeInvoiceIds.has(invoice.id),+ stripeCustomerInvoices = requestedInvoiceIds.map(+ (id) => invoicesById.get(id)!,);}@@ -633,7 +665,7 @@ async function recordEvents(args: RecordEventsArgs) {let commissionMetadata: Record<string, unknown> | null = null;if (type === "sale") {- if (args.importStripeInvoices) {+ if (args.stripeInvoicesToImport) {saleEvents = stripeCustomerInvoices.map((invoice) =>saleEventSchemaTBWithTimestamp.parse({...clickEvent,diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.tsindex e315405a84..8466838536 100644--- a/apps/web/lib/zod/schemas/commissions.ts+++ b/apps/web/lib/zod/schemas/commissions.ts@@ -650,17 +650,16 @@ const createSaleCommissionSchema = z.describe("The partner discount code to resolve the associated link. Use this when the link ID is unknown. Cannot be provided together with `linkId`.",),- importStripeInvoices: z- .boolean()+ stripeInvoicesToImport: z+ .union([z.literal("all"), z.array(z.string().min(1)).min(1).max(100)]).nullish()- .default(false).describe(- "When `true`, import all unimported paid Stripe invoices for the customer and create a commission for each. When `false`, create a single manual sale event using `sale.amount` (or deprecated `saleAmount`).",+ "Import paid Stripe invoices for the customer and create a commission for each. Pass `all` to import every unimported paid invoice, or an array of Stripe invoice IDs to import only those invoices. When not provided, create a single manual sale event using `sale.amount`",),date: parseDateSchema.nullish().describe(- "Only used when `importStripeInvoices` is `false`. The date of the manual sale event. Defaults to the current date and time if not provided.",+ "Only used when `stripeInvoicesToImport` is not provided. The date of the manual sale event. Defaults to the current date and time if not provided.",),sale: z.object({@@ -680,6 +679,11 @@ const createSaleCommissionSchema = z.describe("The sale event object to associate the commission with."),// Deprecated fields+ importStripeInvoices: z+ .boolean()+ .nullish()+ .describe("Deprecated: Use `stripeInvoicesToImport: all` instead.")+ .meta({ deprecated: true }),saleEventDate: parseDateSchema.nullish().describe("Deprecated: Use `date` instead.")@@ -701,7 +705,17 @@ const createSaleCommissionSchema = z.meta({ deprecated: true }),}).superRefine((data, ctx) => {- if (data.importStripeInvoices) {+ if (data.stripeInvoicesToImport != null && data.importStripeInvoices) {+ ctx.addIssue({+ code: "custom",+ message:+ "`stripeInvoicesToImport` and `importStripeInvoices` cannot be provided together. Use `stripeInvoicesToImport` instead.",+ path: ["importStripeInvoices"],+ });+ return;+ }++ if (data.stripeInvoicesToImport != null || data.importStripeInvoices) {const conflicts = [data.sale != null && "sale",data.date != null && "date",@@ -714,8 +728,8 @@ const createSaleCommissionSchema = zif (conflicts.length > 0) {ctx.addIssue({- code: z.ZodIssueCode.custom,- message: `${conflicts.map((field) => `\`${field}\``).join(", ")} cannot be provided when \`importStripeInvoices\` is enabled.`,+ code: "custom",+ message: `${conflicts.map((field) => `\`${field}\``).join(", ")} cannot be provided when importing Stripe invoices.`,path: [conflicts[0]],});}@@ -726,9 +740,9 @@ const createSaleCommissionSchema = zif (saleAmount == null) {ctx.addIssue({- code: z.ZodIssueCode.custom,+ code: "custom",message:- "`sale.amount` or `saleAmount` is required when `importStripeInvoices` is false.",+ "`sale.amount` or `saleAmount` is required when not importing Stripe invoices.",path: data.sale ? ["sale", "amount"] : ["saleAmount"],});return;@@ -736,7 +750,7 @@ const createSaleCommissionSchema = zif (saleAmount === 0) {ctx.addIssue({- code: z.ZodIssueCode.custom,+ code: "custom",message: "Sale amount cannot be 0.",path: data.sale?.amount != null ? ["sale", "amount"] : ["saleAmount"],});diff --git a/apps/web/playwright/api/commissions/commissions-create.spec.ts b/apps/web/playwright/api/commissions/commissions-create.spec.tsindex 6c5838d513..d00ebc78ca 100644--- a/apps/web/playwright/api/commissions/commissions-create.spec.ts+++ b/apps/web/playwright/api/commissions/commissions-create.spec.ts@@ -975,23 +975,35 @@ test.describe("Sale commissions", () => {});});- test("imports Stripe invoices", async ({ api, program, workspace }) => {- await withCommissionPartner(api, program, async (partnerId) => {- expect(- await api.post("/api/commissions", {- type: "sale",- partnerId,- importStripeInvoices: true,- customer: customerBody(),- }),- ).toEqual(- apiError({- code: "bad_request",- message: `Your workspace isn't connected to Stripe yet. Please install the Stripe integration to continue: https://app.dub.co/${workspace.slug}/settings/integrations/stripe`,- }),- );+ const importStripeInvoicesCases = [+ { name: "all", body: { stripeInvoicesToImport: "all" } },+ { name: "invoice IDs", body: { stripeInvoicesToImport: ["in_test"] } },+ { name: "deprecated flag", body: { importStripeInvoices: true } },+ ];++ for (const { name, body } of importStripeInvoicesCases) {+ test(`imports Stripe invoices (${name})`, async ({+ api,+ program,+ workspace,+ }) => {+ await withCommissionPartner(api, program, async (partnerId) => {+ expect(+ await api.post("/api/commissions", {+ type: "sale",+ partnerId,+ ...body,+ customer: customerBody(),+ }),+ ).toEqual(+ apiError({+ code: "bad_request",+ message: `Your workspace isn't connected to Stripe yet. Please install the Stripe integration to continue: https://app.dub.co/${workspace.slug}/settings/integrations/stripe`,+ }),+ );+ });});- });+ }test.describe("validates", () => {const errorCases = [@@ -1006,7 +1018,7 @@ test.describe("Sale commissions", () => {expected: apiError({code: "unprocessable_entity",message:- "custom: saleAmount: `sale.amount` or `saleAmount` is required when `importStripeInvoices` is false.",+ "custom: saleAmount: `sale.amount` or `saleAmount` is required when not importing Stripe invoices.",}),},{@@ -1056,7 +1068,7 @@ test.describe("Sale commissions", () => {type: "sale",partnerId: "pn_test",customerId: "cus_test",- importStripeInvoices: true,+ stripeInvoicesToImport: "all",date: "2024-03-01T08:30:00.000Z",sale: {amount: 5000,@@ -1067,7 +1079,22 @@ test.describe("Sale commissions", () => {expected: apiError({code: "unprocessable_entity",message:- "custom: sale: `sale`, `date`, `invoiceId`, `productId` cannot be provided when `importStripeInvoices` is enabled.",+ "custom: sale: `sale`, `date`, `invoiceId`, `productId` cannot be provided when importing Stripe invoices.",+ }),+ },+ {+ name: "rejects stripeInvoicesToImport with importStripeInvoices",+ body: {+ type: "sale",+ partnerId: "pn_test",+ customerId: "cus_test",+ stripeInvoicesToImport: ["in_test"],+ importStripeInvoices: true,+ },+ expected: apiError({+ code: "unprocessable_entity",+ message:+ "custom: importStripeInvoices: `stripeInvoicesToImport` and `importStripeInvoices` cannot be provided together. Use `stripeInvoicesToImport` instead.",}),},{@@ -1083,7 +1110,7 @@ test.describe("Sale commissions", () => {expected: apiError({code: "unprocessable_entity",message:- "custom: invoiceId: `invoiceId`, `productId` cannot be provided when `importStripeInvoices` is enabled.",+ "custom: invoiceId: `invoiceId`, `productId` cannot be provided when importing Stripe invoices.",}),},{diff --git a/apps/web/scripts/stripe/backfill-discount-code-sales.ts b/apps/web/scripts/stripe/backfill-discount-code-sales.tsindex dd9f446122..24c546b262 100644--- a/apps/web/scripts/stripe/backfill-discount-code-sales.ts+++ b/apps/web/scripts/stripe/backfill-discount-code-sales.ts@@ -378,7 +378,7 @@ async function backfillCustomer({type: "sale",partnerId: discountCode.partnerId,discountCode: discountCode.code,- importStripeInvoices: true,+ stripeInvoicesToImport: invoicesToImport.map((invoice) => invoice.id!),customer: {externalId: dubCustomerExternalId,stripeCustomerId,@@ -396,7 +396,6 @@ async function backfillCustomer({workspace,programId,user,- stripeInvoiceIds: invoicesToImport.map((invoice) => invoice.id!),});return { ...result, status: "imported" };diff --git a/packages/ui/src/table/table.tsx b/packages/ui/src/table/table.tsxindex 8e91b29238..0c0476ecfe 100644--- a/packages/ui/src/table/table.tsx+++ b/packages/ui/src/table/table.tsx@@ -72,6 +72,7 @@ export function useTable<T extends any>(pagination,onPaginationChange,getRowId,+ enableRowSelection,enableColumnResizing = false,columnResizeMode = "onChange",} = props;@@ -212,6 +213,7 @@ export function useTable<T extends any>(const end = Math.max(lastSelectedIndex, currentIndex);const rangeIds = rows.slice(start, end + 1)+ .filter((row) => row.getCanSelect()).map((row) => getRowId?.(row.original)).filter((id): id is string => id !== undefined);@@ -238,16 +240,20 @@ export function useTable<T extends any>(}};+ const canSelect = row.getCanSelect();+return (<buttontype="button"- className="flex size-full items-center justify-center"+ className="flex size-full items-center justify-center disabled:cursor-not-allowed"onClick={onSelectRow}+ disabled={!canSelect}title="Select"><CheckboxclassName="border-border-default pointer-events-none size-4 rounded data-[state=checked]:bg-black data-[state=indeterminate]:bg-black"checked={row.getIsSelected()}+ disabled={!canSelect}/></button>);@@ -285,6 +291,7 @@ export function useTable<T extends any>(autoResetPageIndex: false,manualSorting: true,getRowId,+ enableRowSelection,enableColumnResizing,columnResizeMode,});diff --git a/packages/ui/src/table/types.ts b/packages/ui/src/table/types.tsindex ab9351c060..faee6c78f8 100644--- a/packages/ui/src/table/types.ts+++ b/packages/ui/src/table/types.ts@@ -51,6 +51,7 @@ type BaseTableProps<T> = {// Row selectiongetRowId?: (row: T) => string;+ enableRowSelection?: boolean | ((row: Row<T>) => boolean);onRowSelectionChange?: (rows: Row<T>[]) => void;selectedRows?: RowSelectionState;selectionControls?: (table: TableType<T>) => ReactNode;