The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add tiered payout fee pricing with waiver support (#3406)
Kiran Kf8e5b5d703e0
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 0cf2802787..c9a78c03ef 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,6 +1,7 @@import { getPayoutEligibilityFilter } from "@/lib/api/payouts/payout-eligibility-filter";import { FAST_ACH_FEE_CENTS, FOREX_MARKUP_RATE } from "@/lib/constants/payouts";import { qstash } from "@/lib/cron";+import { calculatePayoutFeeWithWaiver } from "@/lib/partners/calculate-payout-fee-with-waiver";import {CUTOFF_PERIOD,CUTOFF_PERIOD_TYPES,@@ -41,6 +42,8 @@ interface ProcessPayoutsProps {| "payoutsUsage"| "payoutsLimit"| "payoutFee"+ | "payoutFeeWaiverLimit"+ | "payoutFeeWaiverUsage"| "webhookEnabled">;program: Pick<@@ -155,9 +158,19 @@ export async function processPayouts({`Using payout fee of ${payoutFee} for payment method ${paymentMethod.type}`,);- const fastAchFee =- invoice.paymentMethod === "ach_fast" ? FAST_ACH_FEE_CENTS : 0;- const invoiceFee = Math.round(totalPayoutAmount * payoutFee) + fastAchFee;+ const {+ feeFreeAmount,+ feeChargedAmount,+ feeWaiverRemaining,+ fee: invoiceFee,+ } = calculatePayoutFeeWithWaiver({+ payoutAmount: totalPayoutAmount,+ payoutFee,+ payoutFeeWaiverLimit: workspace.payoutFeeWaiverLimit,+ payoutFeeWaiverUsage: workspace.payoutFeeWaiverUsage,+ fastAchFee: invoice.paymentMethod === "ach_fast" ? FAST_ACH_FEE_CENTS : 0,+ });+const invoiceTotal = totalPayoutAmount + invoiceFee;console.log({@@ -166,6 +179,9 @@ export async function processPayouts({totalPayoutAmount,invoiceFee,invoiceTotal,+ feeFreeAmount,+ feeChargedAmount,+ feeWaiverRemaining,});await prisma.invoice.update({@@ -244,6 +260,9 @@ export async function processPayouts({payoutsUsage: {increment: totalPayoutAmount,},+ payoutFeeWaiverUsage: {+ increment: feeFreeAmount,+ },},include: {users: {diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsxindex 9e9d1f4c00..7b36d0a4da 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx@@ -38,7 +38,7 @@ import {} from "@dub/utils";import NumberFlow from "@number-flow/react";import Link from "next/link";-import { CSSProperties, useMemo } from "react";+import { CSSProperties, ReactNode, useMemo } from "react";import { UsageChart } from "./usage-chart";export default function PlanUsage() {@@ -55,6 +55,8 @@ export default function PlanUsage() {payoutsUsage,payoutsLimit,payoutFee,+ payoutFeeWaiverLimit,+ payoutFeeWaiverUsage,domains,domainsLimit,foldersUsage,@@ -122,6 +124,33 @@ export default function PlanUsage() {return tabs;}, [usage, usageLimit, linksUsage, linksLimit, totalLinks]);+ // Display the payout fee in a readable format+ const payoutFeeDisplay = useMemo((): ReactNode => {+ if (!plan || payoutFee === undefined) return undefined;++ const hasTieredPricing = payoutFeeWaiverLimit && payoutFeeWaiverLimit > 0;+ const hasWaiverRemaining =+ payoutFeeWaiverUsage !== undefined &&+ payoutFeeWaiverUsage < payoutFeeWaiverLimit!;++ if (hasTieredPricing && hasWaiverRemaining) {+ const waiverLimitFormatted = nFormatter(payoutFeeWaiverLimit / 100, {+ full: payoutFeeWaiverLimit < 100000,+ });++ return (+ <>+ <span className="text-neutral-400 line-through">+ {payoutFee * 100}%+ </span>{" "}+ 0% for the first ${waiverLimitFormatted}+ </>+ );+ }++ return `${payoutFee * 100}%`;+ }, [plan, payoutFee, payoutFeeWaiverLimit, payoutFeeWaiverUsage]);+return (<div className="rounded-xl border border-neutral-200 bg-white"><div className="flex flex-col items-start justify-between gap-y-4 p-6 md:px-8 lg:flex-row">@@ -231,11 +260,7 @@ export default function PlanUsage() {<UsageCategorytitle="Payout fees"icon={CirclePercentage}- usage={- plan && payoutFee !== undefined- ? `${payoutFee * 100}%`- : undefined- }+ usage={payoutFeeDisplay}href="https://dub.co/help/article/partner-payouts#payout-fees-and-timing"/></div>@@ -439,7 +464,7 @@ function UsageTabCard({function UsageCategory(data: {title: string;icon: Icon;- usage?: number | string;+ usage?: number | string | ReactNode;usageLimit?: number;href?: string;unit?: string;@@ -465,9 +490,7 @@ function UsageCategory(data: {{usage || usage === 0 ? (<p>{typeof usage === "number"- ? `${unit ?? ""}${nFormatter(usage / (unit === "$" ? 100 : 1), {- full: true,- })}`+ ? `${unit ?? ""}${nFormatter(usage / (unit === "$" ? 100 : 1), { full: true })}`: usage}</p>) : (diff --git a/apps/web/lib/actions/partners/confirm-payouts.ts b/apps/web/lib/actions/partners/confirm-payouts.tsindex ca703ed397..f636e94c92 100644--- a/apps/web/lib/actions/partners/confirm-payouts.ts+++ b/apps/web/lib/actions/partners/confirm-payouts.ts@@ -168,6 +168,7 @@ export const confirmPayoutsAction = authActionClientconst mandate = await checkPaymentMethodMandate({paymentMethodId,});+if (!mandate) {// if mandate is not valid, remove the payment methodawait stripe.paymentMethods.detach(paymentMethodId);diff --git a/apps/web/lib/openapi/index.ts b/apps/web/lib/openapi/index.tsindex 42db43125e..a2e1ce8d6f 100644--- a/apps/web/lib/openapi/index.ts+++ b/apps/web/lib/openapi/index.ts@@ -4,7 +4,6 @@ import { DomainSchema } from "../zod/schemas/domains";import { FolderSchema } from "../zod/schemas/folders";import { LinkErrorSchema, LinkSchema } from "../zod/schemas/links";import { LinkTagSchema } from "../zod/schemas/tags";-import { WorkspaceSchema } from "../zod/schemas/workspaces";import { analyticsPath } from "./analytics";import { bountiesPaths } from "./bounties";import { commissionsPaths } from "./commissions";@@ -19,7 +18,6 @@ import { qrCodePaths } from "./qr";import { openApiErrorResponsesComponents } from "./responses";import { tagsPaths } from "./tags";import { trackPaths } from "./track";-import { workspacesPaths } from "./workspaces";export const document = createDocument({openapi: "3.0.3",@@ -55,7 +53,6 @@ export const document = createDocument({...customersPaths,...partnersPaths,...commissionsPaths,- ...workspacesPaths,...embedTokensPaths,...qrCodePaths,...bountiesPaths,@@ -63,7 +60,6 @@ export const document = createDocument({components: {schemas: {LinkSchema,- WorkspaceSchema,LinkTagSchema,FolderSchema,DomainSchema,diff --git a/apps/web/lib/openapi/workspaces/get-workspace-info.ts b/apps/web/lib/openapi/workspaces/get-workspace-info.tsdeleted file mode 100644index 2e55876868..0000000000--- a/apps/web/lib/openapi/workspaces/get-workspace-info.ts+++ /dev/null@@ -1,29 +0,0 @@-import { openApiErrorResponses } from "@/lib/openapi/responses";-import { WorkspaceSchema } from "@/lib/zod/schemas/workspaces";-import { ZodOpenApiOperationObject } from "zod-openapi";-import * as z from "zod/v4";--export const getWorkspaceInfo: ZodOpenApiOperationObject = {- operationId: "getWorkspace",- "x-speakeasy-name-override": "get",- summary: "Retrieve a workspace",- description: "Retrieve a workspace for the authenticated user.",- requestParams: {- path: z.object({- idOrSlug: z.string().describe("The ID or slug of the workspace."),- }),- },- responses: {- "200": {- description: "The retrieved workspace",- content: {- "application/json": {- schema: WorkspaceSchema,- },- },- },- ...openApiErrorResponses,- },- tags: ["Workspaces"],- security: [{ token: [] }],-};diff --git a/apps/web/lib/openapi/workspaces/index.ts b/apps/web/lib/openapi/workspaces/index.tsdeleted file mode 100644index b06aa781a4..0000000000--- a/apps/web/lib/openapi/workspaces/index.ts+++ /dev/null@@ -1,10 +0,0 @@-import { ZodOpenApiPathsObject } from "zod-openapi";-import { getWorkspaceInfo } from "./get-workspace-info";-import { updateWorkspace } from "./update-workspace";--export const workspacesPaths: ZodOpenApiPathsObject = {- "/workspaces/{idOrSlug}": {- get: getWorkspaceInfo,- patch: updateWorkspace,- },-};diff --git a/apps/web/lib/openapi/workspaces/update-workspace.ts b/apps/web/lib/openapi/workspaces/update-workspace.tsdeleted file mode 100644index 0f718aa7ce..0000000000--- a/apps/web/lib/openapi/workspaces/update-workspace.ts+++ /dev/null@@ -1,42 +0,0 @@-import { openApiErrorResponses } from "@/lib/openapi/responses";-import {- WorkspaceSchema,- createWorkspaceSchema,-} from "@/lib/zod/schemas/workspaces";-import { ZodOpenApiOperationObject } from "zod-openapi";-import * as z from "zod/v4";--export const updateWorkspace: ZodOpenApiOperationObject = {- operationId: "updateWorkspace",- "x-speakeasy-name-override": "update",- "x-speakeasy-max-method-params": 2,- summary: "Update a workspace",- description: "Update a workspace by ID or slug.",- requestParams: {- path: z.object({- idOrSlug: z- .string()- .describe("The ID or slug of the workspace to update."),- }),- },- requestBody: {- content: {- "application/json": {- schema: createWorkspaceSchema.partial(),- },- },- },- responses: {- "200": {- description: "The updated workspace.",- content: {- "application/json": {- schema: WorkspaceSchema,- },- },- },- ...openApiErrorResponses,- },- tags: ["Workspaces"],- security: [{ token: [] }],-};diff --git a/apps/web/lib/partners/calculate-payout-fee-with-waiver.ts b/apps/web/lib/partners/calculate-payout-fee-with-waiver.tsnew file mode 100644index 0000000000..75ba1c14cd--- /dev/null+++ b/apps/web/lib/partners/calculate-payout-fee-with-waiver.ts@@ -0,0 +1,40 @@+export interface PayoutFeeWithWaiverParams {+ payoutAmount: number;+ payoutFee: number;+ payoutFeeWaiverLimit: number;+ payoutFeeWaiverUsage: number;+ fastAchFee?: number;+}++// Calculates payout fee with tiered waiver logic+export function calculatePayoutFeeWithWaiver({+ payoutAmount,+ payoutFee,+ payoutFeeWaiverLimit,+ payoutFeeWaiverUsage,+ fastAchFee = 0,+}: PayoutFeeWithWaiverParams) {+ if (payoutFeeWaiverLimit === 0) {+ return {+ fee: Math.round(payoutAmount * payoutFee) + fastAchFee,+ feeFreeAmount: 0,+ feeChargedAmount: payoutAmount,+ feeWaiverRemaining: 0,+ };+ }++ // Split the payout amount between free tier (0% fee) and fee charged (normal rate)+ const feeWaiverRemaining = Math.max(+ 0,+ payoutFeeWaiverLimit - payoutFeeWaiverUsage,+ );+ const feeFreeAmount = Math.min(payoutAmount, feeWaiverRemaining);+ const feeChargedAmount = payoutAmount - feeFreeAmount;++ return {+ fee: Math.round(feeChargedAmount * payoutFee) + fastAchFee,+ feeFreeAmount,+ feeChargedAmount,+ feeWaiverRemaining,+ };+}diff --git a/apps/web/lib/zod/schemas/workspaces.ts b/apps/web/lib/zod/schemas/workspaces.tsindex ba17ba3854..5862510191 100644--- a/apps/web/lib/zod/schemas/workspaces.ts+++ b/apps/web/lib/zod/schemas/workspaces.ts@@ -72,6 +72,16 @@ export const WorkspaceSchema = z.describe("The processing fee (in decimals) for partner payouts. For card payments, an additional 0.03 is added to the fee. Learn more: https://d.to/payouts",),+ payoutFeeWaiverLimit: z+ .number()+ .describe(+ "The amount in cents for which the payout fee will be waived. Applicable only to custom enterprise plans.",+ ),+ payoutFeeWaiverUsage: z+ .number()+ .describe(+ "How much of `payoutFeeWaiverLimit` has been used. Applicable only to custom enterprise plans.",+ ),domainsLimit: z.number().describe("The domains limit of the workspace."),tagsLimit: z.number().describe("The tags limit of the workspace."),foldersUsage: z.number().describe("The folders usage of the workspace."),diff --git a/apps/web/tests/misc/calculate-payout-fee-with-waiver.test.ts b/apps/web/tests/misc/calculate-payout-fee-with-waiver.test.tsnew file mode 100644index 0000000000..5546a75d8e--- /dev/null+++ b/apps/web/tests/misc/calculate-payout-fee-with-waiver.test.ts@@ -0,0 +1,87 @@+import { calculatePayoutFeeWithWaiver } from "@/lib/partners/calculate-payout-fee-with-waiver";+import { describe, expect, it } from "vitest";++describe("calculatePayoutFeeWithWaiver", () => {+ const payoutFee = 0.03; // 3% fee++ it("zero waiver limit (backward compatibility)", () => {+ const result = calculatePayoutFeeWithWaiver({+ payoutAmount: 10000, // $100.00+ payoutFee,+ payoutFeeWaiverLimit: 0,+ payoutFeeWaiverUsage: 0,+ });++ expect(result).toEqual({+ feeFreeAmount: 0,+ feeChargedAmount: 10000,+ feeWaiverRemaining: 0,+ fee: 300, // 3% of $100.00+ });+ });++ it("fully within waiver", () => {+ const result = calculatePayoutFeeWithWaiver({+ payoutAmount: 10000, // $100.00+ payoutFee,+ payoutFeeWaiverLimit: 50000, // $500.00 limit+ payoutFeeWaiverUsage: 0, // nothing used yet+ });++ expect(result).toEqual({+ fee: 0, // no fee charged+ feeFreeAmount: 10000, // entire amount is free+ feeChargedAmount: 0,+ feeWaiverRemaining: 50000,+ });+ });++ it("partially within waiver", () => {+ const result = calculatePayoutFeeWithWaiver({+ payoutAmount: 10000, // $100.00+ payoutFee,+ payoutFeeWaiverLimit: 50000, // $500.00 limit+ payoutFeeWaiverUsage: 45000, // $450.00 already used+ });++ expect(result).toEqual({+ fee: 150, // 3% of $50.00+ feeFreeAmount: 5000, // $50.00 free (remaining waiver)+ feeChargedAmount: 5000, // $50.00 charged+ feeWaiverRemaining: 5000,+ });+ });++ it("waiver exhausted", () => {+ const result = calculatePayoutFeeWithWaiver({+ payoutAmount: 10000, // $100.00+ payoutFee,+ payoutFeeWaiverLimit: 50000, // $500.00 limit+ payoutFeeWaiverUsage: 50000, // fully used+ });++ expect(result).toEqual({+ fee: 300, // 3% of $100.00+ feeFreeAmount: 0,+ feeChargedAmount: 10000,+ feeWaiverRemaining: 0,+ });+ });++ it("includes fastAchFee when provided", () => {+ const result = calculatePayoutFeeWithWaiver({+ payoutAmount: 10000,+ payoutFeeWaiverLimit: 50000,+ payoutFeeWaiverUsage: 45000,+ payoutFee,+ fastAchFee: 50,+ });++ expect(result).toEqual({+ fee: 200, // 3% of $50.00 + $0.50 fast ACH fee+ feeFreeAmount: 5000,+ feeChargedAmount: 5000,+ feeWaiverRemaining: 5000,+ });+ });+});diff --git a/apps/web/ui/partners/confirm-payouts-sheet.tsx b/apps/web/ui/partners/confirm-payouts-sheet.tsxindex 7b75b80cb4..1dd94736e4 100644--- a/apps/web/ui/partners/confirm-payouts-sheet.tsx+++ b/apps/web/ui/partners/confirm-payouts-sheet.tsx@@ -8,6 +8,7 @@ import {INVOICE_MIN_PAYOUT_AMOUNT_CENTS,} from "@/lib/constants/payouts";import { exceededLimitError } from "@/lib/exceeded-limit-error";+import { calculatePayoutFeeWithWaiver } from "@/lib/partners/calculate-payout-fee-with-waiver";import {CUTOFF_PERIOD,CUTOFF_PERIOD_TYPES,@@ -59,7 +60,6 @@ import {useState,} from "react";import { toast } from "sonner";-import Stripe from "stripe";import useSWR from "swr";import { UpgradeRequiredToast } from "../shared/upgrade-required-toast";import { ExternalPayoutsIndicator } from "./external-payouts-indicator";@@ -84,6 +84,8 @@ function ConfirmPayoutsSheetContent() {payoutsUsage,payoutsLimit,payoutFee,+ payoutFeeWaiverLimit,+ payoutFeeWaiverUsage,fastDirectDebitPayouts,} = useWorkspace();@@ -335,7 +337,14 @@ function ConfirmPayoutsSheetContent() {? FAST_ACH_FEE_CENTS: 0;- const fee = Math.round(amount * selectedPaymentMethod.fee + fastAchFee);+ const { fee } = calculatePayoutFeeWithWaiver({+ payoutAmount: amount,+ payoutFeeWaiverLimit: payoutFeeWaiverLimit ?? 0,+ payoutFeeWaiverUsage: payoutFeeWaiverUsage ?? 0,+ payoutFee: selectedPaymentMethod.fee,+ fastAchFee,+ });+const total = amount + fee;return {@@ -345,7 +354,14 @@ function ConfirmPayoutsSheetContent() {total,fastAchFee,};- }, [finalEligiblePayouts, selectedPaymentMethod, program?.payoutMode]);+ }, [+ eligiblePayoutsCount,+ finalEligiblePayouts,+ selectedPaymentMethod,+ program?.payoutMode,+ payoutFeeWaiverLimit,+ payoutFeeWaiverUsage,+ ]);const invoiceData = useMemo(() => {return [@@ -492,7 +508,12 @@ function ConfirmPayoutsSheetContent() {<div className="h-4 w-24 animate-pulse rounded-md bg-neutral-200" />),tooltipContent: selectedPaymentMethod- ? `${selectedPaymentMethod.fee * 100}% processing fee${(fastAchFee ?? 0) > 0 ? ` + ${currencyFormatter(fastAchFee ?? 0)} Fast ACH fee` : ""}. ${!DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(selectedPaymentMethod.type as Stripe.PaymentMethod.Type) ? " Switch to Direct Debit for a reduced fee." : ""} [Learn more](https://d.to/payouts)`+ ? buildPayoutFeeTooltip({+ selectedPaymentMethod,+ fastAchFee: fastAchFee ?? 0,+ payoutFeeWaiverLimit: payoutFeeWaiverLimit ?? 0,+ payoutFeeWaiverUsage: payoutFeeWaiverUsage ?? 0,+ }): undefined,},{@@ -521,6 +542,9 @@ function ConfirmPayoutsSheetContent() {cutoffPeriod,cutoffPeriodOptions,selectedCutoffPeriodOption,+ fastAchFee,+ payoutFeeWaiverLimit,+ payoutFeeWaiverUsage,]);const partnerColumn = useMemo(@@ -984,3 +1008,39 @@ function ConfirmPayoutsButton({</Popover>);}++function buildPayoutFeeTooltip({+ selectedPaymentMethod,+ fastAchFee,+ payoutFeeWaiverLimit,+ payoutFeeWaiverUsage,+}: {+ selectedPaymentMethod: Pick<SelectPaymentMethod, "fee" | "type">;+ fastAchFee: number;+ payoutFeeWaiverLimit: number;+ payoutFeeWaiverUsage: number;+}): string {+ const feePercentage = selectedPaymentMethod.fee * 100;++ const isWithinWaiver =+ payoutFeeWaiverLimit > 0 && payoutFeeWaiverUsage < payoutFeeWaiverLimit;++ const fastAchFeeText =+ fastAchFee > 0 ? ` + ${currencyFormatter(fastAchFee)} Fast ACH fee` : "";++ if (isWithinWaiver) {+ const waiverLimitFormatted = nFormatter(payoutFeeWaiverLimit / 100);++ return `0% processing fee for the first $${waiverLimitFormatted} payouts, then ${feePercentage}%${fastAchFeeText}. [Learn more](https://d.to/payouts)`;+ }++ const isDirectDebit = DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(+ selectedPaymentMethod.type as any,+ );++ const directDebitSuggestion = isDirectDebit+ ? ""+ : " Switch to Direct Debit for a reduced fee.";++ return `${feePercentage}% processing fee${fastAchFeeText}. ${directDebitSuggestion} [Learn more](https://d.to/payouts)`;+}diff --git a/packages/prisma/schema/workspace.prisma b/packages/prisma/schema/workspace.prismaindex 4f76ae778d..97b347357c 100644--- a/packages/prisma/schema/workspace.prisma+++ b/packages/prisma/schema/workspace.prisma@@ -19,22 +19,25 @@ model Project {totalLinks Int @default(0) // Total number of links in the workspacetotalClicks Int @default(0) // Total number of clicks in the workspace- usage Int @default(0)- usageLimit Int @default(1000)- linksUsage Int @default(0)- linksLimit Int @default(25)- payoutsUsage Int @default(0)- payoutsLimit Int @default(0)- payoutFee Float @default(0.05) // processing fee (in decimals) for partner payouts- domainsLimit Int @default(3)- tagsLimit Int @default(5)- foldersUsage Int @default(0)- foldersLimit Int @default(0)- groupsLimit Int @default(0)- usersLimit Int @default(1)- aiUsage Int @default(0)- aiLimit Int @default(10)- networkInvitesLimit Int @default(0)+ usage Int @default(0)+ usageLimit Int @default(1000)+ linksUsage Int @default(0)+ linksLimit Int @default(25)+ payoutsUsage Int @default(0)+ payoutsLimit Int @default(0)+ payoutFee Float @default(0.05) // processing fee (in decimals) for partner payouts+ payoutFeeWaiverLimit Int @default(0) // amount in cents for which the payout fee will be waived+ payoutFeeWaiverUsage Int @default(0) // how much of payoutFeeWaiverLimit has been used++ domainsLimit Int @default(3)+ tagsLimit Int @default(5)+ foldersUsage Int @default(0)+ foldersLimit Int @default(0)+ groupsLimit Int @default(0)+ usersLimit Int @default(1)+ aiUsage Int @default(0)+ aiLimit Int @default(10)+ networkInvitesLimit Int @default(0)referralLinkId String? @uniquereferredSignups Int @default(0)