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.

Simulate sandbox payout settlement without Stripe or PayPal

Kiran Kd248b2234c04
diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts
index 3c0cda2ae3..99cb384f4b 100644
--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/route.ts
@@ -4,8 +4,10 @@ import {
STABLECOIN_PAYOUT_FIXED_FEE_CENTS,
} from "@/lib/constants/payouts";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { mockPayoutCompletion } from "@/lib/sandbox/mock-payout-completion";
import { fundFinancialAccount } from "@/lib/stripe/fund-financial-account";
import { prisma } from "@dub/prisma";
+import { WorkspaceEnvironment } from "@dub/prisma/client";
import { log } from "@dub/utils";
import * as z from "zod/v4";
import { logAndRespond } from "../../utils";
@@ -45,6 +47,15 @@ export async function POST(req: Request) {
},
},
},
+ program: {
+ select: {
+ workspace: {
+ select: {
+ environment: true,
+ },
+ },
+ },
+ },
},
});
@@ -58,6 +69,15 @@ export async function POST(req: Request) {
);
}
+ if (!invoice.program || !invoice.program.workspace) {
+ return logAndRespond(
+ `Invoice ${invoiceId} has no program or workspace, skipping...`,
+ );
+ }
+
+ const isProductionWorkspace =
+ invoice.program.workspace.environment === WorkspaceEnvironment.production;
+
// Set the method for each payout in the invoice to the corresponding partner's default payout method
await prisma.$executeRaw`
UPDATE Payout p
@@ -91,7 +111,7 @@ export async function POST(req: Request) {
(_sum.amount ?? 0) + _count.id * STABLECOIN_PAYOUT_FIXED_FEE_CENTS;
// Send money to Financial Account to handle stablecoin payouts
- if (stablecoinFundingAmount > 0) {
+ if (isProductionWorkspace && stablecoinFundingAmount > 0) {
const { nextAction } = await scheduleDelayedStablecoinPayouts(invoice);
if (nextAction === "executeNow") {
@@ -116,12 +136,28 @@ export async function POST(req: Request) {
}
await Promise.allSettled([
- // Queue Stripe payouts
- queueStripePayouts(invoice, skipStablecoinPayouts),
- // Send PayPal payouts
- sendPaypalPayouts(invoice),
+ ...(isProductionWorkspace
+ ? [
+ // Queue Stripe payouts
+ queueStripePayouts(invoice, skipStablecoinPayouts),
+
+ // Send PayPal payouts
+ sendPaypalPayouts(invoice),
+ ]
+ : []),
+
// Queue external payouts
queueExternalPayouts(invoice),
+
+ // Mock sandbox payouts
+ ...(!isProductionWorkspace
+ ? [
+ mockPayoutCompletion({
+ invoice,
+ workspace: invoice.program.workspace,
+ }),
+ ]
+ : []),
]);
return logAndRespond(
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 4b4b7b7c3e..fc612aa0b0 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
@@ -27,6 +27,7 @@ import {
nFormatter,
pluralize,
} from "@dub/utils";
+import { addMinutes } from "date-fns";
const nonUsdPaymentMethodTypes = {
sepa_debit: "eur",
@@ -307,6 +308,34 @@ export async function processPayouts({
console.error("Error sending message to Qstash", qstashResponse);
}
+ // Non-production workspaces skip the Stripe payment intent above.
+ // Simulate that flow here with a 2-minute delay so
+ // sandbox payouts behave like a settled ACH charge.
+ if (!isProductionWorkspace) {
+ await prisma.invoice.update({
+ where: {
+ id: invoice.id,
+ },
+ data: {
+ status: "completed",
+ paidAt: addMinutes(new Date(), 2),
+ },
+ });
+
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/charge-succeeded`,
+ method: "POST",
+ delay: 2 * 60,
+ flowControl: {
+ key: invoice.id,
+ rate: 1,
+ },
+ body: {
+ invoiceId: invoice.id,
+ },
+ });
+ }
+
// should never happen, but just in case
if (users.length === 0) {
console.error(
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.ts
index ee560e0900..1bb629bfd3 100644
--- a/apps/web/app/(ee)/api/cron/payouts/process/updates/route.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/process/updates/route.ts
@@ -60,7 +60,7 @@ export async function POST(req: Request) {
);
}
- const auditLogResponse = await recordAuditLog(
+ await recordAuditLog(
payouts.map(({ program, partner, invoice, ...payout }) => {
return {
workspaceId: program.workspaceId,
@@ -81,13 +81,11 @@ export async function POST(req: Request) {
}),
);
- // TODO
- // Add banner to the email
-
const invoice = payouts[0].invoice;
const internalPayouts = payouts.filter(
(payout) => payout.mode === "internal",
);
+
if (
invoice &&
invoice.paymentMethod !== "card" &&
diff --git a/apps/web/lib/sandbox/mock-payout-completion.ts b/apps/web/lib/sandbox/mock-payout-completion.ts
new file mode 100644
index 0000000000..34cc1f9205
--- /dev/null
+++ b/apps/web/lib/sandbox/mock-payout-completion.ts
@@ -0,0 +1,142 @@
+import { sendBatchEmail } from "@dub/email";
+import PartnerPayoutProcessed from "@dub/email/templates/partner-payout-processed";
+import { prisma } from "@dub/prisma";
+import { Invoice, Project, WorkspaceEnvironment } from "@dub/prisma/client";
+import { APP_DOMAIN_WITH_NGROK, currencyFormatter } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
+import { trackCommissionStatusUpdatesByProgram } from "../api/commissions/track-commission-update-activity-log";
+import { enqueueBatchJobs } from "../cron/enqueue-batch-jobs";
+
+interface MockPayoutCompletionParams {
+ invoice: Invoice;
+ workspace: Pick<Project, "environment">;
+}
+
+// Mark the all payouts and commissions in the invoice as paid
+export async function mockPayoutCompletion({
+ invoice,
+ workspace,
+}: MockPayoutCompletionParams) {
+ if (workspace.environment === WorkspaceEnvironment.production) {
+ return;
+ }
+
+ const payouts = await prisma.payout.findMany({
+ where: {
+ invoiceId: invoice.id,
+ status: "processing",
+ },
+ orderBy: {
+ id: "asc",
+ },
+ include: {
+ program: {
+ select: {
+ id: true,
+ name: true,
+ logo: true,
+ workspaceId: true,
+ },
+ },
+ partner: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ });
+
+ if (payouts.length === 0) {
+ return;
+ }
+
+ const payoutIds = payouts.map((p) => p.id);
+
+ const commissions = await prisma.commission.findMany({
+ where: {
+ payoutId: {
+ in: payoutIds,
+ },
+ },
+ select: {
+ id: true,
+ amount: true,
+ earnings: true,
+ status: true,
+ programId: true,
+ },
+ });
+
+ await prisma.$transaction([
+ prisma.payout.updateMany({
+ where: {
+ id: {
+ in: payoutIds,
+ },
+ },
+ data: {
+ status: "sent",
+ paidAt: new Date(),
+ },
+ }),
+
+ prisma.commission.updateMany({
+ where: {
+ payoutId: {
+ in: payoutIds,
+ },
+ },
+ data: {
+ status: "paid",
+ },
+ }),
+ ]);
+
+ waitUntil(
+ Promise.allSettled([
+ trackCommissionStatusUpdatesByProgram({
+ commissions,
+ payouts,
+ newStatus: "paid",
+ }),
+
+ enqueueBatchJobs(
+ payoutIds.map((payoutId) => ({
+ queueName: "create-referral-commissions",
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/commissions/referrals/queue`,
+ body: {
+ payoutId,
+ },
+ })),
+ ),
+ ]),
+ );
+
+ // Group partner -> payouts so we send only one email per partner when there are multiple payouts
+ const partnerPayouts = payouts.reduce(
+ (acc, payout) => {
+ acc[payout.partnerId] = [...(acc[payout.partnerId] || []), payout];
+ return acc;
+ },
+ {} as Record<string, typeof payouts>,
+ );
+
+ await sendBatchEmail(
+ Object.values(partnerPayouts)
+ .filter((partnerPayoutList) => partnerPayoutList[0].partner.email)
+ .map((partnerPayoutList) => {
+ const { partner, program, ...payout } = partnerPayoutList[0];
+
+ return {
+ variant: "notifications",
+ to: partner.email!,
+ subject: `You've received a ${currencyFormatter(payout.amount)} payout from ${program.name}`,
+ react: PartnerPayoutProcessed({
+ email: partner.email!,
+ program,
+ payout,
+ }),
+ };
+ }),
+ );
+}