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.

Refactor `selectedPayoutId` → `selectedPayoutIds` to support multi-payout selection/payment (#3732)

Steven Tey22891775e59a
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.ts
index bfdb88c8f0..ea16b427ca 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,4 +1,5 @@
import { getPayoutEligibilityFilter } from "@/lib/api/payouts/payout-eligibility-filter";
+import { payoutIdSelectionWhere } from "@/lib/api/payouts/payout-id-selection-where";
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";
@@ -56,7 +57,7 @@ interface ProcessPayoutsProps {
userId: string;
paymentMethodId: string;
cutoffPeriod?: CUTOFF_PERIOD_TYPES;
- selectedPayoutId?: string;
+ selectedPayoutIds?: string[];
excludedPayoutIds?: string[];
}
@@ -67,7 +68,7 @@ export async function processPayouts({
userId,
paymentMethodId,
cutoffPeriod,
- selectedPayoutId,
+ selectedPayoutIds,
excludedPayoutIds,
}: ProcessPayoutsProps) {
const cutoffPeriodValue = CUTOFF_PERIOD.find(
@@ -76,11 +77,7 @@ export async function processPayouts({
const res = await prisma.payout.updateMany({
where: {
- ...(selectedPayoutId
- ? { id: selectedPayoutId }
- : excludedPayoutIds && excludedPayoutIds.length > 0
- ? { id: { notIn: excludedPayoutIds } }
- : {}),
+ ...payoutIdSelectionWhere({ selectedPayoutIds, excludedPayoutIds }),
...getPayoutEligibilityFilter({ program, workspace }),
...(cutoffPeriodValue && {
periodEnd: {
diff --git a/apps/web/app/(ee)/api/cron/payouts/process/route.ts b/apps/web/app/(ee)/api/cron/payouts/process/route.ts
index 99a4306605..ee8ef5fc56 100644
--- a/apps/web/app/(ee)/api/cron/payouts/process/route.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/process/route.ts
@@ -11,15 +11,34 @@ import { splitPayouts } from "./split-payouts";
export const dynamic = "force-dynamic";
export const maxDuration = 600; // This function can run for a maximum of 10 minutes
-const processPayoutsCronSchema = z.object({
- workspaceId: z.string(),
- userId: z.string(),
- invoiceId: z.string(),
- paymentMethodId: z.string(),
- cutoffPeriod: CUTOFF_PERIOD_ENUM,
- selectedPayoutId: z.string().optional(),
- excludedPayoutIds: z.array(z.string()).optional(),
-});
+const processPayoutsCronSchema = z.preprocess(
+ (raw: unknown) => {
+ if (!raw || typeof raw !== "object" || raw === null) {
+ return raw;
+ }
+ const d = raw as Record<string, unknown>;
+ if (
+ typeof d.selectedPayoutId === "string" &&
+ d.selectedPayoutId &&
+ (!Array.isArray(d.selectedPayoutIds) || d.selectedPayoutIds.length === 0)
+ ) {
+ return {
+ ...d,
+ selectedPayoutIds: [d.selectedPayoutId],
+ };
+ }
+ return raw;
+ },
+ z.object({
+ workspaceId: z.string(),
+ userId: z.string(),
+ invoiceId: z.string(),
+ paymentMethodId: z.string(),
+ cutoffPeriod: CUTOFF_PERIOD_ENUM,
+ selectedPayoutIds: z.array(z.string()).optional(),
+ excludedPayoutIds: z.array(z.string()).optional(),
+ }),
+);
// POST /api/cron/payouts/process
// This route is used to process payouts for a given invoice
@@ -36,7 +55,7 @@ export async function POST(req: Request) {
invoiceId,
paymentMethodId,
cutoffPeriod,
- selectedPayoutId,
+ selectedPayoutIds,
excludedPayoutIds,
} = processPayoutsCronSchema.parse(JSON.parse(rawBody));
@@ -84,7 +103,7 @@ export async function POST(req: Request) {
program,
workspace,
cutoffPeriod,
- selectedPayoutId,
+ selectedPayoutIds,
excludedPayoutIds,
});
}
@@ -96,7 +115,7 @@ export async function POST(req: Request) {
userId,
paymentMethodId,
cutoffPeriod,
- selectedPayoutId,
+ selectedPayoutIds,
excludedPayoutIds,
});
diff --git a/apps/web/app/(ee)/api/cron/payouts/process/split-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/process/split-payouts.ts
index b967c59ed4..21b182d9f4 100644
--- a/apps/web/app/(ee)/api/cron/payouts/process/split-payouts.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/process/split-payouts.ts
@@ -1,5 +1,6 @@
import { createId } from "@/lib/api/create-id";
import { getPayoutEligibilityFilter } from "@/lib/api/payouts/payout-eligibility-filter";
+import { payoutIdSelectionWhere } from "@/lib/api/payouts/payout-id-selection-where";
import {
CUTOFF_PERIOD,
CUTOFF_PERIOD_TYPES,
@@ -12,22 +13,18 @@ export async function splitPayouts({
program,
workspace,
cutoffPeriod,
- selectedPayoutId,
+ selectedPayoutIds,
excludedPayoutIds,
}: {
program: Pick<Program, "id" | "name" | "minPayoutAmount" | "payoutMode">;
workspace: Pick<Project, "plan">;
cutoffPeriod: CUTOFF_PERIOD_TYPES;
- selectedPayoutId?: string;
+ selectedPayoutIds?: string[];
excludedPayoutIds?: string[];
}) {
const payouts = await prisma.payout.findMany({
where: {
- ...(selectedPayoutId
- ? { id: selectedPayoutId }
- : excludedPayoutIds && excludedPayoutIds.length > 0
- ? { id: { notIn: excludedPayoutIds } }
- : {}),
+ ...payoutIdSelectionWhere({ selectedPayoutIds, excludedPayoutIds }),
...getPayoutEligibilityFilter({ program, workspace }),
},
include: {
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.ts
index 0d2bf2d07c..835fd84c7a 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,5 +1,6 @@
import { getEligiblePayouts } from "@/lib/api/payouts/get-eligible-payouts";
import { getPayoutEligibilityFilter } from "@/lib/api/payouts/payout-eligibility-filter";
+import { payoutIdSelectionWhere } from "@/lib/api/payouts/payout-id-selection-where";
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";
@@ -14,7 +15,7 @@ import { NextResponse } from "next/server";
export const GET = withWorkspace(async ({ workspace, searchParams }) => {
const programId = getDefaultProgramIdOrThrow(workspace);
- const { cutoffPeriod, selectedPayoutId, excludedPayoutIds } =
+ const { cutoffPeriod, selectedPayoutIds, excludedPayoutIds } =
eligiblePayoutsCountQuerySchema.parse(searchParams);
const program = await getProgramOrThrow({
@@ -32,7 +33,7 @@ export const GET = withWorkspace(async ({ workspace, searchParams }) => {
program,
workspace,
cutoffPeriod,
- selectedPayoutId,
+ selectedPayoutIds,
excludedPayoutIds,
pageSize: Infinity,
page: 1,
@@ -46,11 +47,7 @@ export const GET = withWorkspace(async ({ workspace, searchParams }) => {
const data = await prisma.payout.aggregate({
where: {
- ...(selectedPayoutId
- ? { id: selectedPayoutId }
- : excludedPayoutIds && excludedPayoutIds.length > 0
- ? { id: { notIn: excludedPayoutIds } }
- : {}),
+ ...payoutIdSelectionWhere({ selectedPayoutIds, excludedPayoutIds }),
...getPayoutEligibilityFilter({ program, workspace }),
},
_count: true,
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/payout-stats.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/payout-stats.tsx
index 502e626b1f..0ba7304a1d 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/payout-stats.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/payout-stats.tsx
@@ -83,7 +83,7 @@ export function PayoutStats() {
<div className="text-sm text-neutral-500">Pending payouts</div>
</div>
<Button
- text="Confirm payouts"
+ text="Confirm all payouts"
shortcut="C"
shortcutClassName="px-1 py-px"
className="h-7 w-fit px-2"
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/payout-table.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/payout-table.tsx
index 650d203f00..e6dc966ceb 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/payout-table.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/payout-table.tsx
@@ -10,9 +10,10 @@ import { ExternalPayoutsIndicator } from "@/ui/partners/external-payouts-indicat
import { PartnerRowItem } from "@/ui/partners/partner-row-item";
import { PayoutStatusBadges } from "@/ui/partners/payout-status-badges";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
-import { PayoutStatus } from "@dub/prisma/client";
+import { PayoutStatus, ProgramPayoutMode } from "@dub/prisma/client";
import {
AnimatedSizeContainer,
+ Button,
DynamicTooltipWrapper,
Filter,
StatusBadge,
@@ -28,11 +29,59 @@ import { cn, currencyFormatter } from "@dub/utils";
import { formatPeriod } from "@dub/utils/src/functions/datetime";
import { fetcher } from "@dub/utils/src/functions/fetcher";
import { PayoutPaidCell } from "app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/payout-paid-cell";
+import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useMemo } from "react";
+import { toast } from "sonner";
import useSWR from "swr";
import { usePayoutFilters } from "./use-payout-filters";
+/** Matches server `getPayoutEligibilityFilter` and in-table warnings in `AmountRowItem`. */
+function isPayoutEligibleForBatchConfirm(
+ payout: PayoutResponse,
+ {
+ minPayoutAmount,
+ programPayoutMode,
+ canManageFraudEvents,
+ partnersWithPendingFraud,
+ }: {
+ minPayoutAmount: number;
+ programPayoutMode: ProgramPayoutMode;
+ canManageFraudEvents: boolean;
+ partnersWithPendingFraud: Set<string>;
+ },
+) {
+ if (payout.status !== PayoutStatus.pending) {
+ return false;
+ }
+
+ if (payout.amount < minPayoutAmount) {
+ return false;
+ }
+
+ // Derive effective mode the same way server does
+ const effectiveMode = payout.partner.payoutsEnabledAt
+ ? "internal"
+ : programPayoutMode === "hybrid" || programPayoutMode === "external"
+ ? "external"
+ : programPayoutMode;
+
+ if (effectiveMode === "external" && !payout.partner?.tenantId) {
+ return false;
+ }
+ if (effectiveMode === "internal" && !payout.partner?.payoutsEnabledAt) {
+ return false;
+ }
+
+ if (canManageFraudEvents && partnersWithPendingFraud.has(payout.partner.id)) {
+ return false;
+ }
+
+ return true;
+}
+
+const PAYOUTS_MAX_PAGE_SIZE = 50;
+
export function PayoutTable() {
const router = useRouter();
const { queryParams, searchParams, searchParamsObj, getQueryString } =
@@ -45,6 +94,9 @@ export function PayoutTable() {
defaultProgramId,
} = useWorkspace();
+ const { program } = useProgram();
+ const minPayoutAmount = program?.minPayoutAmount ?? 0;
+
const sortBy = searchParams.get("sortBy") || "amount";
const sortOrder = searchParams.get("sortOrder") === "asc" ? "asc" : "desc";
@@ -57,9 +109,14 @@ export function PayoutTable() {
} = useSWR<PayoutResponse[]>(
defaultProgramId
? `/api/payouts${getQueryString(
- { workspaceId },
+ { workspaceId, pageSize: PAYOUTS_MAX_PAGE_SIZE },
{
- exclude: ["payoutId", "selectedPayoutId", "excludedPayoutIds"],
+ exclude: [
+ "payoutId",
+ "selectedPayoutId",
+ "selectedPayoutIds",
+ "excludedPayoutIds",
+ ],
},
)}`
: undefined,
@@ -69,7 +126,7 @@ export function PayoutTable() {
},
);
- const { pagination, setPagination } = usePagination();
+ const { pagination, setPagination } = usePagination(PAYOUTS_MAX_PAGE_SIZE);
const { canManageFraudEvents } = getPlanCapabilities(plan);
@@ -94,7 +151,7 @@ export function PayoutTable() {
(key) => !["sortBy", "sortOrder", "page"].includes(key),
);
- const table = useTable({
+ const { table, ...tableProps } = useTable({
data: payouts || [],
loading: isLoading,
error: error || countError ? "Failed to load payouts" : undefined,
@@ -196,7 +253,89 @@ export function PayoutTable() {
onPointerEnter: () =>
router.prefetch(`/${workspaceSlug}/program/payouts/${row.original.id}`),
}),
- columnPinning: { right: ["menu"] },
+ getRowId: (row) => row.id,
+ selectionControls: (table) => {
+ const selectedPayouts = table
+ .getSelectedRowModel()
+ .rows.map((r) => r.original);
+
+ const eligibilityCtx = {
+ minPayoutAmount,
+ programPayoutMode: program?.payoutMode ?? "internal",
+ canManageFraudEvents,
+ partnersWithPendingFraud: fraudGroupCountMap,
+ };
+
+ const hasIneligibleAmongSelection =
+ selectedPayouts.length > 0 &&
+ selectedPayouts.some(
+ (payout) => !isPayoutEligibleForBatchConfirm(payout, eligibilityCtx),
+ );
+
+ return (
+ <Button
+ variant="primary"
+ text="Confirm selected"
+ className="h-7 w-fit rounded-lg px-2.5"
+ disabled={hasIneligibleAmongSelection}
+ disabledTooltip={
+ hasIneligibleAmongSelection ? (
+ <div className="max-w-xs space-y-2 px-4 py-3 text-left text-sm">
+ <p>
+ Your selection includes payouts that are ineligible for
+ payment:
+ </p>
+ <ul className="list-disc space-y-1 pl-4 marker:text-neutral-500">
+ <li>
+ Below the{" "}
+ <a
+ href="https://dub.co/help/article/partner-payouts#minimum-payout-amount"
+ target="_blank"
+ className="cursor-help underline decoration-dotted underline-offset-2"
+ >
+ minimum payout amount
+ </a>
+ </li>
+ <li>Partner has not connected payouts</li>
+ <li>
+ On hold due to{" "}
+ <Link
+ href={`/${workspaceSlug}/program/payouts?status=hold`}
+ className="cursor-alias underline decoration-dotted underline-offset-2"
+ >
+ unresolved fraud events
+ </Link>
+ </li>
+ </ul>
+ </div>
+ ) : undefined
+ }
+ onClick={() => {
+ const current = table
+ .getSelectedRowModel()
+ .rows.map((r) => r.original);
+ const pendingEligible = current.filter((p) =>
+ isPayoutEligibleForBatchConfirm(p, eligibilityCtx),
+ );
+
+ if (pendingEligible.length === 0) {
+ toast.error("Select at least one eligible pending payout.");
+ return;
+ }
+
+ queryParams({
+ set: {
+ confirmPayouts: "true",
+ selectedPayoutIds: pendingEligible.map((p) => p.id).join(","),
+ },
+ del: ["selectedPayoutId", "excludedPayoutIds"],
+ scroll: false,
+ });
+ }}
+ />
+ );
+ },
+ columnPinning: { left: ["select"], right: ["menu"] },
thClassName: "border-l-0",
tdClassName: "border-l-0",
resourceName: (p) => `payout${p ? "s" : ""}`,
@@ -207,7 +346,7 @@ export function PayoutTable() {
<div className="flex flex-col gap-3">
<PayoutFilters />
{payouts?.length !== 0 ? (
- <Table {...table} />
+ <Table {...tableProps} table={table} />
) : (
<AnimatedEmptyState
title="No payouts found"
diff --git a/apps/web/lib/actions/partners/confirm-payouts.ts b/apps/web/lib/actions/partners/confirm-payouts.ts
index f636e94c92..ee03605a4e 100644
--- a/apps/web/lib/actions/partners/confirm-payouts.ts
+++ b/apps/web/lib/actions/partners/confirm-payouts.ts
@@ -3,6 +3,7 @@
import { createId } from "@/lib/api/create-id";
import { getEligiblePayouts } from "@/lib/api/payouts/get-eligible-payouts";
import { getPayoutEligibilityFilter } from "@/lib/api/payouts/payout-eligibility-filter";
+import { payoutIdSelectionWhere } from "@/lib/api/payouts/payout-id-selection-where";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
import {
@@ -24,19 +25,28 @@ import * as z from "zod/v4";
import { authActionClient } from "../safe-action";
import { throwIfNoPermission } from "../throw-if-no-permission";
-const confirmPayoutsSchema = z.object({
- workspaceId: z.string(),
- paymentMethodId: z.string(),
- cutoffPeriod: CUTOFF_PERIOD_ENUM,
- selectedPayoutId: z.string().optional(),
- excludedPayoutIds: z.array(z.string()).optional(),
- fastSettlement: z.boolean().optional().default(false),
- amount: z.number(),
- fee: z.number(),
- total: z.number(),
-});
-
-// Confirm payouts
+const confirmPayoutsSchema = z
+ .object({
+ workspaceId: z.string(),
+ paymentMethodId: z.string(),
+ cutoffPeriod: CUTOFF_PERIOD_ENUM,
+ selectedPayoutIds: z.array(z.string()).optional(),
+ excludedPayoutIds: z.array(z.string()).optional(),
+ fastSettlement: z.boolean().optional().default(false),
+ amount: z.number(),
+ fee: z.number(),
+ total: z.number(),
+ })
+ .superRefine((data, ctx) => {
+ if (data.selectedPayoutIds?.length && data.excludedPayoutIds?.length) {
+ ctx.addIssue({
+ code: "custom",
+ message:
+ "Cannot combine selectedPayoutIds with excludedPayoutIds in the same request.",
+ });
+ }
+ });
+
export const confirmPayoutsAction = authActionClient
.inputSchema(confirmPayoutsSchema)
.action(async ({ parsedInput, ctx }) => {
@@ -44,7 +54,7 @@ export const confirmPayoutsAction = authActionClient
const {
paymentMethodId,
cutoffPeriod,
- selectedPayoutId,
+ selectedPayoutIds,
excludedPayoutIds,
fastSettlement,
amount,
@@ -96,11 +106,7 @@ export const confirmPayoutsAction = authActionClient
if (cutoffPeriod) {
const totalEligiblePayouts = await prisma.payout.aggregate({
where: {
- ...(selectedPayoutId
- ? { id: selectedPayoutId }
- : excludedPayoutIds && excludedPayoutIds.length > 0
- ? { id: { notIn: excludedPayoutIds } }
- : {}),
+ ...payoutIdSelectionWhere({ selectedPayoutIds, excludedPayoutIds }),
...getPayoutEligibilityFilter({ program, workspace }),
},
_count: true,
@@ -119,7 +125,7 @@ export const confirmPayoutsAction = authActionClient
program,
workspace,
cutoffPeriod,
- selectedPayoutId,
+ selectedPayoutIds,
excludedPayoutIds,
page: 1,
pageSize: Infinity,
@@ -218,7 +224,7 @@ export const confirmPayoutsAction = authActionClient
invoiceId: invoice.id,
paymentMethodId,
cutoffPeriod,
- selectedPayoutId,
+ selectedPayoutIds,
excludedPayoutIds,
},
deduplicationId: `process-payouts-${invoice.id}`,
diff --git a/apps/web/lib/api/payouts/get-eligible-payouts.ts b/apps/web/lib/api/payouts/get-eligible-payouts.ts
index 038e252259..c49109211f 100644
--- a/apps/web/lib/api/payouts/get-eligible-payouts.ts
+++ b/apps/web/lib/api/payouts/get-eligible-payouts.ts
@@ -8,13 +8,11 @@ import { Program, Project } from "@dub/prisma/client";
import * as z from "zod/v4";
import { getEffectivePayoutMode } from "./get-effective-payout-mode";
import { getPayoutEligibilityFilter } from "./payout-eligibility-filter";
+import { payoutIdSelectionWhere } from "./payout-id-selection-where";
-interface GetEligiblePayoutsProps
- extends Omit<
- z.infer<typeof eligiblePayoutsQuerySchema>,
- "excludedPayoutIds"
- > {
- excludedPayoutIds?: string[];
+interface GetEligiblePayoutsProps extends z.output<
+ typeof eligiblePayoutsQuerySchema
+> {
program: Pick<Program, "id" | "name" | "minPayoutAmount" | "payoutMode">;
workspace: Pick<Project, "plan">;
}
@@ -23,7 +21,7 @@ export async function getEligiblePayouts({
program,
workspace,
cutoffPeriod,
- selectedPayoutId,
+ selectedPayoutIds,
excludedPayoutIds,
pageSize,
page = 1,
@@ -34,11 +32,7 @@ export async function getEligiblePayouts({
let payouts = await prisma.payout.findMany({
where: {
- ...(selectedPayoutId
- ? { id: selectedPayoutId }
- : excludedPayoutIds && excludedPayoutIds.length > 0
- ? { id: { notIn: excludedPayoutIds } }
- : {}),
+ ...payoutIdSelectionWhere({ selectedPayoutIds, excludedPayoutIds }),
...getPayoutEligibilityFilter({ program, workspace }),
},
include: {
diff --git a/apps/web/lib/api/payouts/payout-id-selection-where.ts b/apps/web/lib/api/payouts/payout-id-selection-where.ts
new file mode 100644
index 0000000000..026e637f6f
--- /dev/null
+++ b/apps/web/lib/api/payouts/payout-id-selection-where.ts
@@ -0,0 +1,18 @@
+import { Prisma } from "@dub/prisma/client";
+
+/** Narrow payouts by explicit selection or by exclusions (mutually exclusive). */
+export function payoutIdSelectionWhere({
+ selectedPayoutIds,
+ excludedPayoutIds,
+}: {
+ selectedPayoutIds?: string[] | undefined;
+ excludedPayoutIds?: string[] | undefined;
+}): Prisma.PayoutWhereInput {
+ if (selectedPayoutIds && selectedPayoutIds.length > 0) {
+ return { id: { in: selectedPayoutIds } };
+ }
+ if (excludedPayoutIds && excludedPayoutIds.length > 0) {
+ return { id: { notIn: excludedPayoutIds } };
+ }
+ return {};
+}
diff --git a/apps/web/lib/zod/schemas/payouts.ts b/apps/web/lib/zod/schemas/payouts.ts
index eefd128b01..14be896572 100644
--- a/apps/web/lib/zod/schemas/payouts.ts
+++ b/apps/web/lib/zod/schemas/payouts.ts
@@ -136,23 +136,72 @@ export const payoutWebhookEventSchema = PayoutSchema.omit({
}),
});
-export const eligiblePayoutsQuerySchema = z
+const commaSeparatedIdsSchema = z
+ .union([z.string(), z.array(z.string())])
+ .transform((v) => (Array.isArray(v) ? v : v.split(",").filter(Boolean)));
+
+const eligiblePayoutsInputSchema = z
.object({
cutoffPeriod: CUTOFF_PERIOD_ENUM,
+ /** @deprecated Use `selectedPayoutIds`; kept for URL backwards compatibility. */
selectedPayoutId: z.string().optional(),
+ selectedPayoutIds: commaSeparatedIdsSchema.optional(),
+ excludedPayoutIds: commaSeparatedIdsSchema.optional(),
})
.extend(
getPaginationQuerySchema({ pageSize: ELIGIBLE_PAYOUTS_MAX_PAGE_SIZE }),
);
-export const eligiblePayoutsCountQuerySchema = eligiblePayoutsQuerySchema
- .extend({
- excludedPayoutIds: z
- .union([z.string(), z.array(z.string())])
- .transform((v) => (Array.isArray(v) ? v : v.split(",")))
- .optional(),
- })
- .omit({
- page: true,
- pageSize: true,
+function transformEligiblePayoutsSelection<
+ T extends {
+ selectedPayoutId?: string | undefined;
+ selectedPayoutIds?: string[] | undefined;
+ excludedPayoutIds?: string[] | undefined;
+ },
+>(data: T) {
+ const {
+ selectedPayoutId,
+ selectedPayoutIds: rawSelected,
+ excludedPayoutIds: rawExcluded,
+ ...rest
+ } = data;
+
+ const merged = [
+ ...new Set([
+ ...(rawSelected ?? []),
+ ...(selectedPayoutId ? [selectedPayoutId] : []),
+ ]),
+ ];
+
+ return {
+ ...rest,
+ selectedPayoutIds: merged.length > 0 ? merged : undefined,
+ excludedPayoutIds:
+ rawExcluded && rawExcluded.length > 0 ? rawExcluded : undefined,
+ };
+}
+
+export const eligiblePayoutsQuerySchema = eligiblePayoutsInputSchema
+ .transform(transformEligiblePayoutsSelection)
+ .superRefine((data, ctx) => {
+ if (data.selectedPayoutIds?.length && data.excludedPayoutIds?.length) {
+ ctx.addIssue({
+ code: "custom",
+ message:
+ "Cannot combine selectedPayoutIds with excludedPayoutIds in the same request.",
+ });
+ }
+ });
+
+export const eligiblePayoutsCountQuerySchema = eligiblePayoutsInputSchema
+ .omit({ page: true, pageSize: true })
+ .transform(transformEligiblePayoutsSelection)
+ .superRefine((data, ctx) => {
+ if (data.selectedPayoutIds?.length && data.excludedPayoutIds?.length) {
+ ctx.addIssue({
+ code: "custom",
+ message:
+ "Cannot combine selectedPayoutIds with excludedPayoutIds in the same request.",
+ });
+ }
});
diff --git a/apps/web/ui/partners/confirm-payouts-sheet.tsx b/apps/web/ui/partners/confirm-payouts-sheet.tsx
index 015ee82be8..a2f062390d 100644
--- a/apps/web/ui/partners/confirm-payouts-sheet.tsx
+++ b/apps/web/ui/partners/confirm-payouts-sheet.tsx
@@ -101,30 +101,93 @@ function ConfirmPayoutsSheetContent() {
const { queryParams, searchParamsObj } = useRouterStuff();
- const selectedPayoutId = searchParamsObj.selectedPayoutId || undefined;
+ const resolvedSelectedPayoutIds = useMemo(() => {
+ const fromMulti =
+ searchParamsObj.selectedPayoutIds?.split(",").filter(Boolean) ?? [];
+ const fromLegacy = searchParamsObj.selectedPayoutId
+ ? [searchParamsObj.selectedPayoutId]
+ : [];
+ return [...new Set([...fromMulti, ...fromLegacy])];
+ }, [searchParamsObj.selectedPayoutIds, searchParamsObj.selectedPayoutId]);
+
+ const isExplicitSelectionMode = resolvedSelectedPayoutIds.length > 0;
+
const excludedPayoutIds =
searchParamsObj.excludedPayoutIds?.split(",").filter(Boolean) || [];
- const commonQuery = {
- workspaceId,
- cutoffPeriod,
- ...(selectedPayoutId && { selectedPayoutId }),
- ...(excludedPayoutIds.length > 0 && {
- excludedPayoutIds: excludedPayoutIds.join(","),
- }),
- } as Record<string, any>;
+ /** Matches the invoice (respects excludedPayoutIds in bulk mode, selectedPayoutIds when explicit). */
+ const summaryQuery = useMemo(
+ () =>
+ ({
+ workspaceId,
+ cutoffPeriod,
+ ...(isExplicitSelectionMode
+ ? { selectedPayoutIds: resolvedSelectedPayoutIds.join(",") }
+ : excludedPayoutIds.length > 0
+ ? { excludedPayoutIds: excludedPayoutIds.join(",") }
+ : {}),
+ }) as Record<string, string>,
+ [
+ workspaceId,
+ cutoffPeriod,
+ isExplicitSelectionMode,
+ resolvedSelectedPayoutIds.join(","),
+ excludedPayoutIds.join(","),
+ ],
+ );
+
+ /** Full eligible list for the table — never applies excludedPayoutIds so excluded rows stay visible. */
+ const tableQuery = useMemo(
+ () =>
+ ({
+ workspaceId,
+ cutoffPeriod,
+ ...(isExplicitSelectionMode
+ ? { selectedPayoutIds: resolvedSelectedPayoutIds.join(",") }
+ : {}),
+ }) as Record<string, string>,
+ [
+ workspaceId,
+ cutoffPeriod,
+ isExplicitSelectionMode,
+ resolvedSelectedPayoutIds.join(","),
+ ],
+ );
+
+ const {
+ data: eligiblePayoutsSummaryCount,
+ isLoading: eligiblePayoutsSummaryLoading,
+ } = useSWR<{
+ count: number;
+ amount: number;
+ }>(
+ defaultProgramId
+ ? `/api/programs/${defaultProgramId}/payouts/eligible/count?${new URLSearchParams(summaryQuery).toString()}`
+ : null,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
- const { data: eligiblePayoutsCount } = useSWR<{
+ /** Total eligible rows for table pagination (no excludedPayoutIds). Same URL as summary when bulk + no exclusions → SWR dedupes. */
+ const { data: eligiblePayoutsTableTotalCount } = useSWR<{
count: number;
amount: number;
}>(
- `/api/programs/${defaultProgramId}/payouts/eligible/count?${new URLSearchParams(commonQuery).toString()}`,
+ defaultProgramId && !isExplicitSelectionMode
+ ? `/api/programs/${defaultProgramId}/payouts/eligible/count?${new URLSearchParams(tableQuery).toString()}`
+ : null,
fetcher,
{
keepPreviousData: true,
},
);
+ const eligiblePayoutsTableRowCount = isExplicitSelectionMode
+ ? (eligiblePayoutsSummaryCount?.count ?? 0)
+ : (eligiblePayoutsTableTotalCount?.count ?? 0);
+
const { data: payoutsCount } = useSWR<
{
status: string;
@@ -169,25 +232,41 @@ function ConfirmPayoutsSheetContent() {
error: eligiblePayoutsError,
isLoading: eligiblePayoutsLoading,
} = useSWR<PayoutResponse[]>(
- `/api/programs/${defaultProgramId}/payouts/eligible?${new URLSearchParams({
- ...commonQuery,
- page: pagination.pageIndex.toString(),
- }).toString()}`,
+ defaultProgramId
+ ? `/api/programs/${defaultProgramId}/payouts/eligible?${new URLSearchParams({
+ ...tableQuery,
+ page: pagination.pageIndex.toString(),
+ }).toString()}`
+ : null,
fetcher,
{
keepPreviousData: true,
},
);
- const finalEligiblePayouts = useMemo(() => {
- // if there's a selected payout id, return the payout directly
- if (selectedPayoutId) return eligiblePayouts;
+ /** All rows returned for the table (including bulk-mode exclusions, for strikethrough + Include). */
+ const finalEligiblePayouts = useMemo(
+ () => eligiblePayouts ?? [],
+ [eligiblePayouts],
+ );
- // else, we need to filter out the excluded payout ids (if specified)
- return eligiblePayouts?.filter(
+ /** Subset actually on the invoice (for fees / external amount / external row in summary). */
+ const payoutsIncludedInInvoice = useMemo(() => {
+ if (!eligiblePayouts) {
+ return [];
+ }
+ if (isExplicitSelectionMode) {
+ return eligiblePayouts;
+ }
+ return eligiblePayouts.filter(
(payout) => !excludedPayoutIds.includes(payout.id),
);
- }, [eligiblePayouts, selectedPayoutId, excludedPayoutIds]);
+ }, [eligiblePayouts, isExplicitSelectionMode, excludedPayoutIds]);
+
+ const showPerRowIncludeExclude = useMemo(
+ () => !isExplicitSelectionMode || resolvedSelectedPayoutIds.length > 1,
+ [isExplicitSelectionMode, resolvedSelectedPayoutIds.length],
+ );
const { executeAsync: confirmPayouts } = useAction(confirmPayoutsAction, {
onError: ({ error }) => {
@@ -343,7 +422,7 @@ function ConfirmPayoutsSheetContent() {
};
const { amount, fee, total, fastAchFee, externalAmount } = useMemo(() => {
- const amount = eligiblePayoutsCount?.amount;
+ const amount = eligiblePayoutsSummaryCount?.amount;
if (
amount === undefined ||
@@ -359,8 +438,7 @@ function ConfirmPayoutsSheetContent() {
};
}
- // Calculate the total external amount
- const externalAmount = finalEligiblePayouts?.reduce(
+ const externalAmount = payoutsIncludedInInvoice.reduce(
(acc, payout) =>
isExternalPayout(payout) ? acc + payout.amount : acc + 0,
0,
@@ -388,8 +466,8 @@ function ConfirmPayoutsSheetContent() {
fastAchFee,
};
}, [
- eligiblePayoutsCount,
- finalEligiblePayouts,
+ eligiblePayoutsSummaryCount,
+ payoutsIncludedInInvoice,
selectedPaymentMethod,
program?.payoutMode,
payoutFeeWaiverLimit,
@@ -464,8 +542,8 @@ function ConfirmPayoutsSheetContent() {
),
},
// only show cutoff period if there are less than 1,000 payouts
- ...(eligiblePayoutsCount &&
- eligiblePayoutsCount.count <= CUTOFF_PERIOD_MAX_PAYOUTS
+ ...(eligiblePayoutsSummaryCount &&
+ eligiblePayoutsSummaryCount.count <= CUTOFF_PERIOD_MAX_PAYOUTS
? [
{
key: "Cutoff Period",
@@ -500,8 +578,8 @@ function ConfirmPayoutsSheetContent() {
{
key: "Partners",
value:
- eligiblePayoutsCount !== undefined ? (
- nFormatter(eligiblePayoutsCount.count, { full: true })
+ eligiblePayoutsSummaryCount !== undefined ? (
+ nFormatter(eligiblePayoutsSummaryCount.count, { full: true })
) : (
<div className="h-4 w-24 animate-pulse rounded-md bg-neutral-200" />
),
@@ -515,7 +593,8 @@ function ConfirmPayoutsSheetContent() {
currencyFormatter(amount)
),
},
- ...(finalEligiblePayouts && finalEligiblePayouts.some(isExternalPayout)
+ ...(payoutsIncludedInInvoice.length > 0 &&
+ payoutsIncludedInInvoice.some(isExternalPayout)
? [
{
key: "External Amount",
@@ -570,8 +649,16 @@ function ConfirmPayoutsSheetContent() {
}, [
amount,
externalAmount,
+ eligiblePayoutsSummaryCount,
+ payoutsIncludedInInvoice,
paymentMethods,
+ paymentMethodsLoading,
+ paymentMethodOptions,
selectedPaymentMethod,
+ selectedPaymentMethodOption,
+ finalPaymentMethods,
+ slug,
+ program?.payoutMode,
cutoffPeriod,
cutoffPeriodOptions,
selectedCutoffPeriodOption,
@@ -598,7 +685,7 @@ function ConfirmPayoutsSheetContent() {
);
const table = useTable({
- data: eligiblePayouts || [],
+ data: finalEligiblePayouts || [],
columns: [
partnerColumn,
{
@@ -609,14 +696,16 @@ function ConfirmPayoutsSheetContent() {
<div className="relative flex items-center justify-end gap-1.5">
<span
className={cn(
- !selectedPayoutId && "group-hover/row:opacity-0",
- excludedPayoutIds.includes(row.original.id) && "line-through",
+ showPerRowIncludeExclude && "group-hover/row:opacity-0",
+ !isExplicitSelectionMode &&
+ excludedPayoutIds.includes(row.original.id) &&
+ "line-through",
)}
>
{currencyFormatter(row.original.amount)}
</span>
- {!selectedPayoutId && (
+ {showPerRowIncludeExclude && (
<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",
@@ -627,12 +716,39 @@ function ConfirmPayoutsSheetContent() {
<Button
variant="secondary"
text={
- excludedPayoutIds.includes(row.original.id)
- ? "Include"
- : "Exclude"
+ isExplicitSelectionMode
+ ? "Remove"
+ : excludedPayoutIds.includes(row.original.id)
+ ? "Include"
+ : "Exclude"
}
className="h-6 w-fit px-2"
onClick={() => {
+ if (isExplicitSelectionMode) {
+ const next = resolvedSelectedPayoutIds.filter(
+ (id) => id !== row.original.id,
+ );
+
+ queryParams({
+ ...(next.length > 0
+ ? {
+ set: {
+ selectedPayoutIds: next.join(","),
+ },
+ del: ["selectedPayoutId", "excludedPayoutIds"],
+ }
+ : {
+ del: [
+ "selectedPayoutIds",
+ "selectedPayoutId",
+ "excludedPayoutIds",
+ ],
+ }),
+ replace: true,
+ });
+ return;
+ }
+
const newExcludedPayoutIds = excludedPayoutIds.includes(
row.original.id,
)
@@ -648,9 +764,14 @@ function ConfirmPayoutsSheetContent() {
excludedPayoutIds:
newExcludedPayoutIds.join(","),
},
+ del: ["selectedPayoutIds", "selectedPayoutId"],
}
: {
- del: "excludedPayoutIds",
+ del: [
+ "excludedPayoutIds",
+ "selectedPayoutIds",
+ "selectedPayoutId",
+ ],
}),
replace: true,
});
@@ -672,10 +793,11 @@ function ConfirmPayoutsSheetContent() {
tdClassName: (id, row) =>
cn(
"transition-opacity",
- excludedPayoutIds.includes(row.original.id) && [
- "[&>div]:opacity-50",
- id === "total" && "group-hover/row:[&>div]:opacity-100",
- ], // Excluded payout
+ !isExplicitSelectionMode &&
+ excludedPayoutIds.includes(row.original.id) && [
+ "[&>div]:opacity-50",
+ id === "total" && "group-hover/row:[&>div]:opacity-100",
+ ],
id === "total" && "text-right",
"border-l-0",
),
@@ -684,7 +806,7 @@ function ConfirmPayoutsSheetContent() {
resourceName: (p) => `payout${p ? "s" : ""}`,
pagination,
onPaginationChange: setPagination,
- rowCount: eligiblePayoutsCount?.count ?? 0,
+ rowCount: eligiblePayoutsTableRowCount,
loading: eligiblePayoutsLoading,
error: eligiblePayoutsError
? "Failed to load payouts for this invoice."
@@ -772,8 +894,11 @@ function ConfirmPayoutsSheetContent() {
paymentMethodId: selectedPaymentMethod.id.replace("-fast", ""),
fastSettlement: selectedPaymentMethod.fastSettlement,
cutoffPeriod,
- selectedPayoutId,
- excludedPayoutIds,
+ ...(isExplicitSelectionMode
+ ? { selectedPayoutIds: resolvedSelectedPayoutIds }
+ : excludedPayoutIds.length > 0
+ ? { excludedPayoutIds }
+ : {}),
amount: amount ?? 0,
fee: fee ?? 0,
total: total ?? 0,
@@ -798,7 +923,10 @@ function ConfirmPayoutsSheetContent() {
: `${isTouchDevice ? "Press" : "Click"} and hold to confirm payout`
}
disabled={
- eligiblePayoutsLoading || !selectedPaymentMethod || amount === 0
+ eligiblePayoutsLoading ||
+ eligiblePayoutsSummaryLoading ||
+ !selectedPaymentMethod ||
+ amount === 0
}
disabledTooltip={
payoutsUsage &&
@@ -821,7 +949,7 @@ function ConfirmPayoutsSheetContent() {
)
}
/>
- {holdPayoutsCount > 0 && (
+ {!isExplicitSelectionMode && holdPayoutsCount > 0 && (
<div className="flex items-center justify-center gap-2 text-sm text-neutral-600">
<span>
Excluding{" "}
@@ -872,7 +1000,12 @@ export function ConfirmPayoutsSheet() {
onOpenChange={setIsOpen}
onClose={() => {
queryParams({
- del: ["confirmPayouts", "selectedPayoutId", "excludedPayoutIds"],
+ del: [
+ "confirmPayouts",
+ "selectedPayoutId",
+ "selectedPayoutIds",
+ "excludedPayoutIds",
+ ],
});
}}
>