The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
backend changes
Steven Teya23748d06081
diff --git a/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.tsindex c915f460a2..44adb7a191 100644--- a/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts+++ b/apps/web/app/(ee)/api/cron/payouts/process/process-payouts.ts@@ -1,13 +1,6 @@-import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";-import { getEffectivePayoutMode } from "@/lib/api/payouts/get-effective-payout-mode";import { getPayoutEligibilityFilter } from "@/lib/api/payouts/payout-eligibility-filter";-import {- DIRECT_DEBIT_PAYMENT_METHOD_TYPES,- FAST_ACH_FEE_CENTS,- FOREX_MARKUP_RATE,-} from "@/lib/constants/payouts";-import { queueBatchEmail } from "@/lib/email/queue-batch-email";-import { exceededLimitError } from "@/lib/exceeded-limit-error";+import { FAST_ACH_FEE_CENTS, FOREX_MARKUP_RATE } from "@/lib/constants/payouts";+import { qstash } from "@/lib/cron";import {CUTOFF_PERIOD,CUTOFF_PERIOD_TYPES,@@ -15,17 +8,15 @@ import {import { stripe } from "@/lib/stripe";import { createFxQuote } from "@/lib/stripe/create-fx-quote";import { calculatePayoutFeeForMethod } from "@/lib/stripe/payment-methods";-import { PlanProps } from "@/lib/types";-import type PartnerPayoutConfirmed from "@dub/email/templates/partner-payout-confirmed";import { prisma } from "@dub/prisma";-import { currencyFormatter, log } from "@dub/utils";import {Partner,Payout,Program,ProgramPayoutMode,Project,-} from "@prisma/client";+} from "@dub/prisma/client";+import { APP_DOMAIN_WITH_NGROK, currencyFormatter, log } from "@dub/utils";const paymentMethodToCurrency = {sepa_debit: "eur",@@ -77,7 +68,13 @@ export async function processPayouts({(c) => c.id === cutoffPeriod,)?.value;- const payouts = await prisma.payout.findMany({+ const invoice = await prisma.invoice.findUniqueOrThrow({+ where: {+ id: invoiceId,+ },+ });++ const res = await prisma.payout.updateMany({where: {...(selectedPayoutId? { id: selectedPayoutId }@@ -99,89 +96,57 @@ export async function processPayouts({],}),},- select: {- id: true,- amount: true,- periodStart: true,- periodEnd: true,- mode: true,- partner: {- select: {- email: true,- payoutsEnabledAt: true,- },- },+ data: {+ invoiceId,+ status: "processing",+ userId,+ initiatedAt: new Date(),+ // if the program is in external mode, set the mode to external+ // otherwise set it to internal (we'll update to "external" later if it's hybrid mode)+ mode: program.payoutMode === "external" ? "external" : "internal",},});- if (payouts.length === 0) {+ if (res.count === 0) {+ console.log(`No payouts found for invoice ${invoiceId}. Skipping...`);return;}- let invoice = await prisma.invoice.findUniqueOrThrow({- where: {- id: invoiceId,- },- });-- let externalPayouts: ExtendedPayout[] = [];- let internalPayouts: ExtendedPayout[] = [];-- if (invoice.payoutMode === "internal") {- internalPayouts = payouts;- } else if (invoice.payoutMode === "external") {- externalPayouts = payouts;- } else if (invoice.payoutMode === "hybrid") {- payouts.forEach((payout) => {- const payoutMode = getEffectivePayoutMode({- payoutMode: invoice.payoutMode,- payoutsEnabledAt: payout.partner.payoutsEnabledAt,- });+ console.log(+ `Updated ${res.count} payouts to invoice ${invoiceId} and "processing" status`,+ );- if (payoutMode === "external") {- externalPayouts.push(payout);- } else {- internalPayouts.push(payout);- }+ //+ if (program.payoutMode === "hybrid") {+ await prisma.payout.updateMany({+ where: {+ invoiceId,+ partner: {+ payoutsEnabledAt: null,+ },+ },+ data: {+ mode: "external",+ },});}- // This is the total amount of payouts that will be processed (included external and internal payouts)- const totalPayoutAmount = payouts.reduce(- (total, payout) => total + payout.amount,- 0,- );-- const externalPayoutAmount = externalPayouts.reduce(- (total, payout) => total + payout.amount,- 0,- );-- console.log({- internalPayouts: internalPayouts.map((p) => {- return {- id: p.id,- amount: p.amount,- };- }),-- externalPayouts: externalPayouts.map((p) => {- return {- id: p.id,- amount: p.amount,- };- }),+ const payoutsByMode = await prisma.payout.groupBy({+ by: ["mode"],+ where: {+ invoiceId,+ },+ _sum: {+ amount: true,+ },});- if (workspace.payoutsUsage + totalPayoutAmount > workspace.payoutsLimit) {- throw new Error(- exceededLimitError({- plan: workspace.plan as PlanProps,- limit: workspace.payoutsLimit,- type: "payouts",- }),- );- }+ const totalInternalPayoutAmount =+ payoutsByMode.find((p) => p.mode === "internal")?._sum.amount ?? 0;+ const totalExternalPayoutAmount =+ payoutsByMode.find((p) => p.mode === "external")?._sum.amount ?? 0;+ const totalPayoutAmount =+ totalInternalPayoutAmount + totalExternalPayoutAmount;const paymentMethod = await stripe.paymentMethods.retrieve(paymentMethodId);@@ -201,9 +166,22 @@ export async function processPayouts({const fastAchFee =invoice.paymentMethod === "ach_fast" ? FAST_ACH_FEE_CENTS : 0;const currency = paymentMethodToCurrency[paymentMethod.type] || "usd";- const totalFee = Math.round(totalPayoutAmount * payoutFee) + fastAchFee;- const total = totalPayoutAmount + totalFee;- let totalToSend = total - externalPayoutAmount;+ const invoiceFee = Math.round(totalPayoutAmount * payoutFee) + fastAchFee;+ const invoiceTotal = totalPayoutAmount + invoiceFee;++ await prisma.invoice.update({+ where: {+ id: invoiceId,+ },+ data: {+ amount: totalPayoutAmount,+ externalAmount: totalExternalPayoutAmount,+ fee: invoiceFee,+ total: invoiceTotal,+ },+ });++ let totalToCharge = invoiceTotal - totalExternalPayoutAmount;// convert the amount to EUR/CAD if the payment method is sepa_debit or acss_debitif (["sepa_debit", "acss_debit"].includes(paymentMethod.type)) {@@ -222,32 +200,19 @@ export async function processPayouts({}const convertedTotal = Math.round(- (totalToSend / exchangeRate) * (1 + FOREX_MARKUP_RATE),+ (totalToCharge / exchangeRate) * (1 + FOREX_MARKUP_RATE),);console.log(- `Currency conversion: ${totalToSend} usd -> ${convertedTotal} ${currency} using exchange rate ${exchangeRate}.`,+ `Currency conversion: ${totalToCharge} usd -> ${convertedTotal} ${currency} using exchange rate ${exchangeRate}.`,);- totalToSend = convertedTotal;+ totalToCharge = convertedTotal;}- // Update the invoice with the finalized payout amount, fee, and total- invoice = await prisma.invoice.update({- where: {- id: invoiceId,- },- data: {- amount: totalPayoutAmount,- externalAmount: externalPayoutAmount,- fee: totalFee,- total,- },- });-await stripe.paymentIntents.create({- amount: totalToSend,+ amount: totalToCharge,customer: workspace.stripeId!,payment_method_types: [paymentMethod.type],payment_method: paymentMethod.id,@@ -271,42 +236,6 @@ export async function processPayouts({},);- // Mark internal payouts as processing- if (internalPayouts.length > 0) {- await prisma.payout.updateMany({- where: {- id: {- in: internalPayouts.map((p) => p.id),- },- },- data: {- invoiceId: invoice.id,- status: "processing",- userId,- initiatedAt: new Date(),- mode: "internal",- },- });- }-- // Mark external payouts as processing- if (externalPayouts.length > 0) {- await prisma.payout.updateMany({- where: {- id: {- in: externalPayouts.map((p) => p.id),- },- },- data: {- invoiceId: invoice.id,- status: "processing",- userId,- initiatedAt: new Date(),- mode: "external",- },- });- }-await prisma.project.update({where: {id: workspace.id,@@ -319,85 +248,20 @@ export async function processPayouts({});await log({- message: `*${program.name}* just sent a payout of *${currencyFormatter(totalPayoutAmount)}* :money_with_wings: \n\n Fees earned: *${currencyFormatter(totalFee)} (${payoutFee * 100}%)* :money_mouth_face:`,+ message: `*${program.name}* just sent a payout of *${currencyFormatter(totalPayoutAmount)}* :money_with_wings: \n\n Fees earned: *${currencyFormatter(invoiceFee)} (${payoutFee * 100}%)* :money_mouth_face:`,type: "payouts",});- const userWhoInitiatedPayout = await prisma.user.findUnique({- where: {- id: userId,- },- select: {- id: true,- name: true,+ const qstashResponse = await qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/process/updates`,+ body: {+ invoiceId,},});- const externalPayoutsMap = new Map(externalPayouts.map((p) => [p.id, p]));-- await recordAuditLog(- payouts.map((payout) => ({- workspaceId: workspace.id,- programId: program.id,- action: "payout.confirmed",- description: `Payout ${payout.id} confirmed`,- actor: userWhoInitiatedPayout ?? {- id: userId,- name: "Unknown user", // should never happen but just in case- },- targets: [- {- type: "payout",- id: payout.id,- metadata: {- ...payout,- invoiceId: invoice.id,- status: "processing",- userId,- initiatedAt: new Date(),- mode: externalPayoutsMap.has(payout.id) ? "external" : "internal",- },- },- ],- })),- );-- // Send emails to all the partners involved in the payouts if the payout method is Direct Debit- // This is because Direct Debit takes 4 business days to process, so we want to give partners a heads up- if (- invoice &&- internalPayouts.length > 0 &&- DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(paymentMethod.type)- ) {- await queueBatchEmail<typeof PartnerPayoutConfirmed>(- internalPayouts- .filter((payout) => payout.partner.email)- .map((payout) => ({- to: payout.partner.email!,- subject: `Your ${currencyFormatter(payout.amount)} payout for ${program.name} is on the way`,- variant: "notifications",- replyTo: program.supportEmail || "noreply",- templateName: "PartnerPayoutConfirmed",- templateProps: {- email: payout.partner.email!,- program: {- id: program.id,- name: program.name,- logo: program.logo,- },- payout: {- id: payout.id,- amount: payout.amount,- startDate: payout.periodStart,- endDate: payout.periodEnd,- mode: "internal",- paymentMethod: invoice.paymentMethod ?? "ach",- },- },- })),- {- idempotencyKey: `payout-confirmed-internal/${invoice.id}`,- },- );+ if (qstashResponse.messageId) {+ console.log(`Message sent to Qstash with id ${qstashResponse.messageId}`);+ } else {+ console.error("Error sending message to Qstash", qstashResponse);}}diff --git a/apps/web/app/(ee)/api/cron/payouts/process/updates/route.ts b/apps/web/app/(ee)/api/cron/payouts/process/updates/route.tsnew file mode 100644index 0000000000..82ae87de51--- /dev/null+++ b/apps/web/app/(ee)/api/cron/payouts/process/updates/route.ts@@ -0,0 +1,148 @@+import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { qstash } from "@/lib/cron";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { sendBatchEmail } from "@dub/email";+import { prisma } from "@dub/prisma";+import { APP_DOMAIN_WITH_NGROK, currencyFormatter, log } from "@dub/utils";+import { z } from "zod";+import { logAndRespond } from "../../../utils";++export const dynamic = "force-dynamic";++const payloadSchema = z.object({+ invoiceId: z.string(),+ startingAfter: z.string().optional(),+});++const BATCH_SIZE = 100;++// POST /api/cron/payouts/process/updates+// Recursive cron job to handle side effects of the `cron/payouts/process` job (recordAuditLog, sendBatchEmails)+export async function POST(req: Request) {+ try {+ const rawBody = await req.text();++ await verifyQstashSignature({+ req,+ rawBody,+ });++ const { invoiceId, startingAfter } = payloadSchema.parse(+ JSON.parse(rawBody),+ );++ const payouts = await prisma.payout.findMany({+ where: {+ invoiceId,+ },+ include: {+ program: true,+ partner: true,+ invoice: true,+ },+ take: BATCH_SIZE,+ skip: startingAfter ? 1 : 0,+ ...(startingAfter && {+ cursor: {+ id: startingAfter,+ },+ }),+ });++ if (payouts.length === 0) {+ return logAndRespond(+ `No more payouts to process for invoice ${invoiceId}. Skipping...`,+ );+ }++ const auditLogResponse = await recordAuditLog(+ payouts.map((payout) => ({+ workspaceId: payout.program.workspaceId,+ programId: payout.program.id,+ action: "payout.confirmed",+ description: `Payout ${payout.id} confirmed`,+ actor: {+ id: payout.userId!,+ },+ targets: [+ {+ type: "payout",+ id: payout.id,+ metadata: payout,+ },+ ],+ })),+ );++ console.log({ auditLogResponse });++ const invoice = payouts[0].invoice;+ const internalPayouts = payouts.filter(+ (payout) => payout.mode === "internal",+ );+ if (+ invoice &&+ invoice.paymentMethod !== "card" &&+ internalPayouts.length > 0+ ) {+ const batchEmailResponse = await sendBatchEmail(+ internalPayouts.map((payout) => ({+ to: payout.partner.email!,+ subject: `Your ${currencyFormatter(payout.amount)} payout for ${payout.program.name} is on the way`,+ variant: "notifications",+ replyTo: payout.program.supportEmail || "noreply",+ templateName: "PartnerPayoutConfirmed",+ templateProps: {+ email: payout.partner.email!,+ program: {+ id: payout.program.id,+ name: payout.program.name,+ logo: payout.program.logo,+ },+ payout: {+ id: payout.id,+ amount: payout.amount,+ startDate: payout.periodStart,+ endDate: payout.periodEnd,+ mode: payout.mode,+ paymentMethod: payout.invoice?.paymentMethod ?? "ach",+ },+ },+ })),+ );+ console.log({ batchEmailResponse });+ }++ if (payouts.length === BATCH_SIZE) {+ const nextStartingAfter = payouts[payouts.length - 1].id;++ await qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/process/updates`,+ method: "POST",+ body: {+ invoiceId,+ startingAfter: nextStartingAfter,+ },+ });++ return logAndRespond(+ `Enqueued next batch for invoice ${invoiceId} (startingAfter: ${nextStartingAfter}).`,+ );+ }++ return logAndRespond(+ `Finished processing updates for ${payouts.length} payouts for invoice ${invoiceId}`,+ );+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);++ await log({+ message: `Error sending Stripe payout: ${errorMessage}`,+ type: "errors",+ mention: true,+ });++ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/app/(ee)/api/programs/[programId]/payouts/eligible/count/route.ts b/apps/web/app/(ee)/api/programs/[programId]/payouts/eligible/count/route.tsindex e249cbab50..bb0718b4f7 100644--- a/apps/web/app/(ee)/api/programs/[programId]/payouts/eligible/count/route.ts+++ b/apps/web/app/(ee)/api/programs/[programId]/payouts/eligible/count/route.ts@@ -1,8 +1,11 @@-import { getEligiblePayoutsCount } from "@/lib/api/payouts/get-eligible-payouts";+import { getEligiblePayouts } from "@/lib/api/payouts/get-eligible-payouts";+import { getPayoutEligibilityFilter } from "@/lib/api/payouts/payout-eligibility-filter";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";import { withWorkspace } from "@/lib/auth";+import { CUTOFF_PERIOD } from "@/lib/partners/cutoff-period";import { eligiblePayoutsCountQuerySchema } from "@/lib/zod/schemas/payouts";+import { prisma } from "@dub/prisma";import { NextResponse } from "next/server";/*@@ -11,17 +14,51 @@ import { NextResponse } from "next/server";export const GET = withWorkspace(async ({ workspace, searchParams }) => {const programId = getDefaultProgramIdOrThrow(workspace);- const query = eligiblePayoutsCountQuerySchema.parse(searchParams);+ const { cutoffPeriod, selectedPayoutId, excludedPayoutIds } =+ eligiblePayoutsCountQuerySchema.parse(searchParams);const program = await getProgramOrThrow({workspaceId: workspace.id,programId,});- return NextResponse.json(- await getEligiblePayoutsCount({+ const cutoffPeriodValue = CUTOFF_PERIOD.find(+ (c) => c.id === cutoffPeriod,+ )?.value;++ // Requires special re-computing and filtering of payouts, so we just have to fetch all of them+ if (cutoffPeriodValue) {+ const eligiblePayouts = await getEligiblePayouts({program,- ...query,- }),- );+ cutoffPeriod,+ selectedPayoutId,+ excludedPayoutIds,+ pageSize: Infinity,+ page: 1,+ });+ return NextResponse.json({+ count: eligiblePayouts.length ?? 0,+ amount: eligiblePayouts.reduce((acc, payout) => acc + payout.amount, 0),+ });+ }++ const data = await prisma.payout.aggregate({+ where: {+ ...(selectedPayoutId+ ? { id: selectedPayoutId }+ : excludedPayoutIds && excludedPayoutIds.length > 0+ ? { id: { notIn: excludedPayoutIds } }+ : {}),+ ...getPayoutEligibilityFilter(program),+ },+ _count: true,+ _sum: {+ amount: true,+ },+ });++ return NextResponse.json({+ count: data._count ?? 0,+ amount: data._sum?.amount ?? 0,+ });});diff --git a/apps/web/lib/api/payouts/get-eligible-payouts.ts b/apps/web/lib/api/payouts/get-eligible-payouts.tsindex 63bee340c8..a13457ee03 100644--- a/apps/web/lib/api/payouts/get-eligible-payouts.ts+++ b/apps/web/lib/api/payouts/get-eligible-payouts.ts@@ -10,47 +10,14 @@ import { getEffectivePayoutMode } from "./get-effective-payout-mode";import { getPayoutEligibilityFilter } from "./payout-eligibility-filter";interface GetEligiblePayoutsProps- extends z.infer<typeof eligiblePayoutsQuerySchema> {+ extends Omit<+ z.infer<typeof eligiblePayoutsQuerySchema>,+ "excludedPayoutIds"+ > {excludedPayoutIds?: string[];program: Pick<Program, "id" | "name" | "minPayoutAmount" | "payoutMode">;}-const getEligiblePayoutsWhere = ({- program,- cutoffPeriod,- selectedPayoutId,- excludedPayoutIds,-}: Pick<- GetEligiblePayoutsProps,- "program" | "cutoffPeriod" | "selectedPayoutId" | "excludedPayoutIds"->) => {- const cutoffPeriodValue = CUTOFF_PERIOD.find(- (c) => c.id === cutoffPeriod,- )?.value;-- return {- ...(selectedPayoutId- ? { id: selectedPayoutId }- : excludedPayoutIds && excludedPayoutIds.length > 0- ? { id: { notIn: excludedPayoutIds } }- : {}),- ...getPayoutEligibilityFilter(program),- ...(cutoffPeriodValue && {- OR: [- {- periodStart: null,- periodEnd: null,- },- {- periodEnd: {- lte: cutoffPeriodValue,- },- },- ],- }),- };-};-export async function getEligiblePayouts({program,cutoffPeriod,@@ -64,12 +31,27 @@ export async function getEligiblePayouts({)?.value;let payouts = await prisma.payout.findMany({- where: getEligiblePayoutsWhere({- program,- cutoffPeriod,- selectedPayoutId,- excludedPayoutIds,- }),+ where: {+ ...(selectedPayoutId+ ? { id: selectedPayoutId }+ : excludedPayoutIds && excludedPayoutIds.length > 0+ ? { id: { notIn: excludedPayoutIds } }+ : {}),+ ...getPayoutEligibilityFilter(program),+ ...(cutoffPeriodValue && {+ OR: [+ {+ periodStart: null,+ periodEnd: null,+ },+ {+ periodEnd: {+ lte: cutoffPeriodValue,+ },+ },+ ],+ }),+ },include: {partner: {include: {@@ -136,37 +118,3 @@ export async function getEligiblePayouts({return z.array(PayoutResponseSchema).parse(eligiblePayouts);}--export async function getEligiblePayoutsCount({- program,- cutoffPeriod,- selectedPayoutId,- excludedPayoutIds,-}: Omit<GetEligiblePayoutsProps, "pageSize" | "page">) {- const cutoffPeriodValue = CUTOFF_PERIOD.find(- (c) => c.id === cutoffPeriod,- )?.value;-- // Requires special re-computing and filtering of payouts, so we just have to fetch all of them- if (cutoffPeriodValue)- return (- await getEligiblePayouts({- program,- cutoffPeriod,- selectedPayoutId,- excludedPayoutIds,- pageSize: Infinity,- page: 1,- })- ).length;-- // Simple count- return await prisma.payout.count({- where: getEligiblePayoutsWhere({- program,- cutoffPeriod,- selectedPayoutId,- excludedPayoutIds,- }),- });-}diff --git a/apps/web/lib/constants/payouts.ts b/apps/web/lib/constants/payouts.tsindex 28a13568d7..4fb5876174 100644--- a/apps/web/lib/constants/payouts.ts+++ b/apps/web/lib/constants/payouts.ts@@ -11,6 +11,8 @@ export const ALLOWED_MIN_PAYOUT_AMOUNTS = [0, 1000, 2000, 5000, 10000];export const MIN_WITHDRAWAL_AMOUNT_CENTS = 1000; // $10export const BELOW_MIN_WITHDRAWAL_FEE_CENTS = 50; // $0.50+export const ELIGIBLE_PAYOUTS_MAX_PAGE_SIZE = 500;+// Direct debit payment types for Partner payoutexport const DIRECT_DEBIT_PAYMENT_TYPES_INFO: {type: Stripe.PaymentMethod.Type;diff --git a/apps/web/lib/zod/schemas/payouts.ts b/apps/web/lib/zod/schemas/payouts.tsindex 5455c3c796..cebd2af77d 100644--- a/apps/web/lib/zod/schemas/payouts.ts+++ b/apps/web/lib/zod/schemas/payouts.ts@@ -1,3 +1,4 @@+import { ELIGIBLE_PAYOUTS_MAX_PAGE_SIZE } from "@/lib/constants/payouts";import { CUTOFF_PERIOD_ENUM } from "@/lib/partners/cutoff-period";import { PayoutMode, PayoutStatus } from "@dub/prisma/client";import { z } from "zod";@@ -112,8 +113,6 @@ export const payoutWebhookEventSchema = PayoutSchema.omit({}),});-export const ELIGIBLE_PAYOUTS_MAX_PAGE_SIZE = 500;-export const eligiblePayoutsQuerySchema = z.object({cutoffPeriod: CUTOFF_PERIOD_ENUM,@@ -123,7 +122,13 @@ export const eligiblePayoutsQuerySchema = zgetPaginationQuerySchema({ pageSize: ELIGIBLE_PAYOUTS_MAX_PAGE_SIZE }),);-export const eligiblePayoutsCountQuerySchema = eligiblePayoutsQuerySchema.omit({- page: true,- pageSize: true,-});+export const eligiblePayoutsCountQuerySchema = eligiblePayoutsQuerySchema+ .extend({+ excludedPayoutIds: z+ .union([z.string(), z.array(z.string())])+ .transform((v) => (Array.isArray(v) ? v : v.split(","))),+ })+ .omit({+ page: true,+ pageSize: true,+ });diff --git a/apps/web/ui/partners/confirm-payouts-sheet.tsx b/apps/web/ui/partners/confirm-payouts-sheet.tsxindex 3eb5fb5a6f..e69580c1e2 100644--- a/apps/web/ui/partners/confirm-payouts-sheet.tsx+++ b/apps/web/ui/partners/confirm-payouts-sheet.tsx@@ -2,6 +2,7 @@ import { confirmPayoutsAction } from "@/lib/actions/partners/confirm-payouts";import { clientAccessCheck } from "@/lib/client-access-check";import {DIRECT_DEBIT_PAYMENT_METHOD_TYPES,+ ELIGIBLE_PAYOUTS_MAX_PAGE_SIZE,FAST_ACH_FEE_CENTS,} from "@/lib/constants/payouts";import { exceededLimitError } from "@/lib/exceeded-limit-error";@@ -17,7 +18,6 @@ import usePaymentMethods from "@/lib/swr/use-payment-methods";import useProgram from "@/lib/swr/use-program";import useWorkspace from "@/lib/swr/use-workspace";import { PayoutResponse, PlanProps } from "@/lib/types";-import { ELIGIBLE_PAYOUTS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/payouts";import { X } from "@/ui/shared/icons";import {Button,@@ -89,16 +89,27 @@ function ConfirmPayoutsSheetContent() {const { queryParams, searchParamsObj } = useRouterStuff();const selectedPayoutId = searchParamsObj.selectedPayoutId || undefined;+ const excludedPayoutIds =+ searchParamsObj.excludedPayoutIds?.split(",").filter(Boolean) || [];const commonQuery = {workspaceId,cutoffPeriod,...(selectedPayoutId && { selectedPayoutId }),+ ...(excludedPayoutIds.length > 0 && {+ excludedPayoutIds: excludedPayoutIds.join(","),+ }),} as Record<string, any>;- const { data: eligiblePayoutsCount } = useSWR<number>(+ const { data: eligiblePayoutsCount } = useSWR<{+ count: number;+ amount: number;+ }>(`/api/programs/${defaultProgramId}/payouts/eligible/count?${new URLSearchParams(commonQuery).toString()}`,fetcher,+ {+ keepPreviousData: true,+ },);const [page, setPage] = useState(1);@@ -118,11 +129,11 @@ function ConfirmPayoutsSheetContent() {page: pagination.pageIndex.toString(),}).toString()}`,fetcher,+ {+ keepPreviousData: true,+ },);- const excludedPayoutIds =- searchParamsObj.excludedPayoutIds?.split(",").filter(Boolean) || [];-const finalEligiblePayouts = useMemo(() => {// if there's a selected payout id, return the payout directlyif (selectedPayoutId) return eligiblePayouts;@@ -287,9 +298,7 @@ function ConfirmPayoutsSheetContent() {};const { amount, fee, total, fastAchFee, externalAmount } = useMemo(() => {- const amount = finalEligiblePayouts?.reduce((acc, payout) => {- return acc + payout.amount;- }, 0);+ const amount = eligiblePayoutsCount?.amount ?? 0;if (amount === undefined ||@@ -395,39 +404,44 @@ function ConfirmPayoutsSheetContent() {</div>),},- {- key: "Cutoff Period",- value: (- <div className="w-full">- <Combobox- options={cutoffPeriodOptions}- selected={selectedCutoffPeriodOption}- setSelected={(option: ComboboxOption) => {- if (!option) {- return;- }-- setCutoffPeriod(option.value as CUTOFF_PERIOD_TYPES);- }}- placeholder="Select cutoff period"- buttonProps={{- className:- "h-auto border border-neutral-200 px-3 py-1.5 text-xs focus:border-neutral-600 focus:ring-neutral-600",- }}- matchTriggerWidth- hideSearch- caret- />- </div>- ),- tooltipContent:- "Cutoff period in UTC. If set, only commissions accrued up to the cutoff period will be included in the payout invoice.",- },+ // only show cutoff period if there are less than 1,000 payouts+ ...(eligiblePayoutsCount && eligiblePayoutsCount.count <= 1000+ ? [+ {+ key: "Cutoff Period",+ value: (+ <div className="w-full">+ <Combobox+ options={cutoffPeriodOptions}+ selected={selectedCutoffPeriodOption}+ setSelected={(option: ComboboxOption) => {+ if (!option) {+ return;+ }++ setCutoffPeriod(option.value as CUTOFF_PERIOD_TYPES);+ }}+ placeholder="Select cutoff period"+ buttonProps={{+ className:+ "h-auto border border-neutral-200 px-3 py-1.5 text-xs focus:border-neutral-600 focus:ring-neutral-600",+ }}+ matchTriggerWidth+ hideSearch+ caret+ />+ </div>+ ),+ tooltipContent:+ "Cutoff period in UTC. If set, only commissions accrued up to the cutoff period will be included in the payout invoice.",+ },+ ]+ : []),{key: "Partners",value:eligiblePayoutsCount !== undefined ? (- nFormatter(eligiblePayoutsCount, { full: true })+ nFormatter(eligiblePayoutsCount.count, { full: true })) : (<div className="h-4 w-24 animate-pulse rounded-md bg-neutral-200" />),@@ -535,7 +549,13 @@ function ConfirmPayoutsSheetContent() {</span>{!selectedPayoutId && (- <div className="pointer-events-none absolute right-[calc(14px+0.375rem)] top-1/2 -translate-y-1/2 opacity-0 group-hover/row:pointer-events-auto group-hover/row:opacity-100">+ <div+ className={cn(+ "pointer-events-none absolute top-1/2 -translate-y-1/2 opacity-0 group-hover/row:pointer-events-auto group-hover/row:opacity-100",+ isExternalPayout(row.original) &&+ "right-[calc(14px+0.375rem)]",+ )}+ ><Buttonvariant="secondary"text={@@ -544,21 +564,29 @@ function ConfirmPayoutsSheetContent() {: "Exclude"}className="h-6 w-fit px-2"- onClick={() =>- // Toggle excluded- queryParams({- set: {- excludedPayoutIds: excludedPayoutIds.includes(- row.original.id,+ onClick={() => {+ const newExcludedPayoutIds = excludedPayoutIds.includes(+ row.original.id,+ )+ ? excludedPayoutIds.filter(+ (id) => id !== row.original.id,)- ? excludedPayoutIds.filter(- (id) => id !== row.original.id,- )- : [...excludedPayoutIds, row.original.id],- },+ : [...excludedPayoutIds, row.original.id];++ queryParams({+ ...(newExcludedPayoutIds.length > 0+ ? {+ set: {+ excludedPayoutIds:+ newExcludedPayoutIds.join(","),+ },+ }+ : {+ del: "excludedPayoutIds",+ }),replace: true,- })- }+ });+ }}/></div>)}@@ -588,7 +616,7 @@ function ConfirmPayoutsSheetContent() {resourceName: (p) => `eligible payout${p ? "s" : ""}`,pagination,onPaginationChange: setPagination,- rowCount: eligiblePayoutsCount ?? 0,+ rowCount: eligiblePayoutsCount?.count ?? 0,loading: eligiblePayoutsLoading,error: eligiblePayoutsError? "Failed to load payouts for this invoice."