The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Apply the invoice minimum to the chargeable payout total
Kiran K1fcc30d5703a
diff --git a/apps/web/lib/actions/partners/confirm-payouts.ts b/apps/web/lib/actions/partners/confirm-payouts.tsindex c45e717a4e..1d5a7f2fa5 100644--- a/apps/web/lib/actions/partners/confirm-payouts.ts+++ b/apps/web/lib/actions/partners/confirm-payouts.ts@@ -16,15 +16,18 @@ import {import { qstash } from "@/lib/cron";import { exceededLimitError } from "@/lib/exceeded-limit-error";import { createTremendousCampaignJob } from "@/lib/jobs/handlers/create-tremendous-campaign-job";+import { calculatePayoutFeeWithWaiver } from "@/lib/partners/calculate-payout-fee-with-waiver";import { CUTOFF_PERIOD_ENUM } from "@/lib/partners/cutoff-period";import { prisma } from "@/lib/prisma";import { isProductionEnvironment } from "@/lib/sandbox/environment";import { mockPaymentProvider } from "@/lib/sandbox/mock-payment-provider";import { stripe } from "@/lib/stripe";import { checkPaymentMethodMandate } from "@/lib/stripe/check-payment-method-mandate";+import { calculatePayoutFeeForMethod } from "@/lib/stripe/payment-methods";import { EXTERNAL_PAYOUT_CONFIRMED_WEBHOOK_TRIGGER } from "@/lib/webhook/constants";import { getWebhooks } from "@/lib/webhook/get-webhooks";-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";+import { APP_DOMAIN_WITH_NGROK, currencyFormatter } from "@dub/utils";+import { PayoutMode, ProgramPayoutMode } from "@prisma/client";import { waitUntil } from "@vercel/functions";import * as z from "zod/v4";import { authActionClient } from "../safe-action";@@ -106,12 +109,6 @@ export const confirmPayoutsAction = authActionClient);}- if (amount < INVOICE_MIN_PAYOUT_AMOUNT_CENTS) {- throw new Error(- "Your payout total is less than the minimum invoice amount of $10.",- );- }-// TODO: Remove this once we can support cutoff periods for invoices with > 1,000 payoutsif (cutoffPeriod) {const totalEligiblePayouts = await prisma.payout.aggregate({@@ -129,28 +126,30 @@ export const confirmPayoutsAction = authActionClient}}- if (program.payoutMode !== "internal") {- const [eligiblePayouts, payoutWebhooks] = await Promise.all([- getEligiblePayouts({- program,- cutoffPeriod,- selectedPayoutIds,- excludedPayoutIds,- page: 1,- pageSize: Infinity,- }),+ const [eligiblePayouts, payoutWebhooks] = await Promise.all([+ getEligiblePayouts({+ program,+ cutoffPeriod,+ selectedPayoutIds,+ excludedPayoutIds,+ page: 1,+ pageSize: Infinity,+ }),- getWebhooks({- workspaceId: workspace.id,- triggers: [EXTERNAL_PAYOUT_CONFIRMED_WEBHOOK_TRIGGER],- disabled: false,- installationId: null,- }),- ]);+ program.payoutMode === ProgramPayoutMode.internal+ ? Promise.resolve([])+ : getWebhooks({+ workspaceId: workspace.id,+ triggers: [EXTERNAL_PAYOUT_CONFIRMED_WEBHOOK_TRIGGER],+ disabled: false,+ installationId: null,+ }),+ ]);+ if (program.payoutMode !== ProgramPayoutMode.internal) {// Check if the invoice includes any external payoutsconst hasExternalPayouts = eligiblePayouts.find(- (payout) => payout.mode === "external",+ (payout) => payout.mode === PayoutMode.external,);if (hasExternalPayouts && payoutWebhooks.length === 0) {@@ -183,6 +182,45 @@ export const confirmPayoutsAction = authActionClientthrow new Error("Fast settlement is only supported for ACH payment.");}+ const payoutAmount = eligiblePayouts.reduce(+ (sum, payout) => sum + payout.amount,+ 0,+ );++ const externalPayoutAmount = eligiblePayouts.reduce(+ (sum, payout) =>+ payout.mode === PayoutMode.external ? sum + payout.amount : sum,+ 0,+ );++ const payoutFee = calculatePayoutFeeForMethod({+ paymentMethod: paymentMethod.type,+ payoutFee: workspace.payoutFee,+ });++ if (payoutFee == null) {+ throw new Error("Failed to calculate payout fee.");+ }++ const { fee: chargeFee } = calculatePayoutFeeWithWaiver({+ payoutAmount,+ payoutFee,+ payoutFeeWaiverLimit: workspace.payoutFeeWaiverLimit,+ payoutFeeWaiverUsage: workspace.payoutFeeWaiverUsage,+ paymentMethod: fastSettlement+ ? "ach_fast"+ : STRIPE_PAYMENT_METHOD_NORMALIZATION[paymentMethod.type],+ });++ // External payouts are paid outside Dub, so Stripe is only charged the internal amount plus the fee.+ const chargeableTotal = payoutAmount - externalPayoutAmount + chargeFee;++ if (chargeableTotal < INVOICE_MIN_PAYOUT_AMOUNT_CENTS) {+ throw new Error(+ `Your payout total is less than the minimum invoice amount of ${currencyFormatter(INVOICE_MIN_PAYOUT_AMOUNT_CENTS, { trailingZeroDisplay: "stripIfInteger" })}.`,+ );+ }+// if it's a direct debit payment method, we need to check to make sure mandate is validif (isProductionWorkspace &&diff --git a/apps/web/ui/partners/confirm-payouts-sheet.tsx b/apps/web/ui/partners/confirm-payouts-sheet.tsxindex de2168d9c8..d000a025d1 100644--- a/apps/web/ui/partners/confirm-payouts-sheet.tsx+++ b/apps/web/ui/partners/confirm-payouts-sheet.tsx@@ -417,54 +417,58 @@ function ConfirmPayoutsSheetContent() {}};- const { amount, fee, total, fastAchFee, externalAmount } = useMemo(() => {- const amount = eligiblePayoutsSummaryCount?.amount;-- if (- amount === undefined ||- selectedPaymentMethod === null ||- program?.payoutMode === undefined- ) {- return {- amount: undefined,- externalAmount: undefined,- fee: undefined,- total: undefined,- fastAchFee: undefined,- };- }-- const externalAmount = payoutsIncludedInInvoice.reduce(- (acc, payout) =>- isExternalPayout(payout) ? acc + payout.amount : acc + 0,- 0,- );-- const invoicePaymentMethod = selectedPaymentMethod.fastSettlement- ? "ach_fast"- : STRIPE_PAYMENT_METHOD_NORMALIZATION[selectedPaymentMethod.type];-- const fastAchFee =- invoicePaymentMethod === "ach_fast" ? FAST_ACH_FEE_CENTS : 0;+ const { amount, fee, total, chargeableTotal, fastAchFee, externalAmount } =+ useMemo(() => {+ const amount = eligiblePayoutsSummaryCount?.amount;++ if (+ amount === undefined ||+ selectedPaymentMethod === null ||+ program?.payoutMode === undefined+ ) {+ return {+ amount: undefined,+ externalAmount: undefined,+ fee: undefined,+ total: undefined,+ chargeableTotal: undefined,+ fastAchFee: undefined,+ };+ }- const { fee } = calculatePayoutFeeWithWaiver({- payoutAmount: amount,- payoutFeeWaiverLimit: payoutFeeWaiverLimit ?? 0,- payoutFeeWaiverUsage: payoutFeeWaiverUsage ?? 0,- payoutFee: selectedPaymentMethod.fee,- paymentMethod: invoicePaymentMethod,- });+ const externalAmount = payoutsIncludedInInvoice.reduce(+ (acc, payout) =>+ isExternalPayout(payout) ? acc + payout.amount : acc + 0,+ 0,+ );++ const invoicePaymentMethod = selectedPaymentMethod.fastSettlement+ ? "ach_fast"+ : STRIPE_PAYMENT_METHOD_NORMALIZATION[selectedPaymentMethod.type];++ const fastAchFee =+ invoicePaymentMethod === "ach_fast" ? FAST_ACH_FEE_CENTS : 0;++ const { fee } = calculatePayoutFeeWithWaiver({+ payoutAmount: amount,+ payoutFeeWaiverLimit: payoutFeeWaiverLimit ?? 0,+ payoutFeeWaiverUsage: payoutFeeWaiverUsage ?? 0,+ payoutFee: selectedPaymentMethod.fee,+ paymentMethod: invoicePaymentMethod,+ });- const total = amount + fee;+ const total = amount + fee;+ const chargeableTotal = amount - externalAmount + fee;- return {- amount,- externalAmount,- fee,- total,- fastAchFee,- };- }, [+ return {+ amount,+ externalAmount,+ fee,+ total,+ chargeableTotal,+ fastAchFee,+ };+ }, [eligiblePayoutsSummaryCount,payoutsIncludedInInvoice,selectedPaymentMethod,@@ -638,15 +642,16 @@ function ConfirmPayoutsSheetContent() {{key: "Total",value:- total === undefined ? (+ chargeableTotal === undefined ? (<div className="h-4 w-24 animate-pulse rounded-md bg-neutral-200" />) : (- currencyFormatter(total)+ currencyFormatter(chargeableTotal)),},];}, [amount,+ chargeableTotal,externalAmount,eligiblePayoutsSummaryCount,payoutsIncludedInInvoice,@@ -946,8 +951,9 @@ function ConfirmPayoutsSheetContent() {? { onClick: () => openTrialLimitModal("payouts") }: { href: `/${slug}/upgrade` })}/>- ) : amount && amount < INVOICE_MIN_PAYOUT_AMOUNT_CENTS ? (- "Your payout total is less than the minimum invoice amount of $10."+ ) : typeof chargeableTotal === "number" &&+ chargeableTotal < INVOICE_MIN_PAYOUT_AMOUNT_CENTS ? (+ `Your payout total is less than the minimum invoice amount of ${currencyFormatter(INVOICE_MIN_PAYOUT_AMOUNT_CENTS, { trailingZeroDisplay: "stripIfInteger" })}.`) : (permissionsError || undefined)