The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Handle payouts in batches of 100 (#3002)
Steven Teyc7e0bc5091b2
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.tsindex fe0847f123..fdfaa4c8ee 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@@ -1,8 +1,10 @@import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { qstash } from "@/lib/cron";import { verifyQstashSignature } from "@/lib/cron/verify-qstash";import { prisma } from "@dub/prisma";-import { log } from "@dub/utils";+import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";import { z } from "zod";+import { logAndRespond } from "../../utils";import { sendPaypalPayouts } from "./send-paypal-payouts";import { sendStripePayouts } from "./send-stripe-payouts";@@ -17,9 +19,9 @@ const stripeChargeMetadataSchema = z.object({});// POST /api/cron/payouts/charge-succeeded-// This route is used to process the charge-succeeded event from Stripe-// we're intentionally offloading this to a cron job to avoid blocking the main thread-// so that we can return a 200 to Stripe immediately+// This route is used to process the charge-succeeded event from Stripe.+// We're intentionally offloading this to a cron job so we can return a 200 to Stripe immediately.+// We'll also be calling this route recursively to process payouts in batches of 100.export async function POST(req: Request) {try {const rawBody = await req.text();@@ -36,9 +38,7 @@ export async function POST(req: Request) {select: {payouts: {where: {- status: {- not: "completed",- },+ status: "processing",},},},@@ -47,14 +47,12 @@ export async function POST(req: Request) {});if (!invoice) {- console.log(`Invoice with id ${invoiceId} not found.`);- return new Response(`Invoice with id ${invoiceId} not found.`);+ return logAndRespond(`Invoice ${invoiceId} not found.`);}if (invoice._count.payouts === 0) {- console.log("No payouts found with status not completed, skipping...");- return new Response(- `No payouts found with status not completed for invoice ${invoiceId}`,+ return logAndRespond(+ `No payouts found with status 'processing' for invoice ${invoiceId}, skipping...`,);}@@ -88,7 +86,36 @@ export async function POST(req: Request) {}),]);- return new Response(`Invoice ${invoiceId} processed.`);+ if (invoice._count.payouts > 100) {+ console.log(+ "More than 100 payouts found for invoice, scheduling next batch...",+ );+ const qstashResponse = await qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/charge-succeeded`,+ body: {+ invoiceId: invoiceId,+ },+ });+ if (qstashResponse.messageId) {+ console.log(+ `Message sent to Qstash with id ${qstashResponse.messageId}`,+ );+ } else {+ // should never happen but just in case+ await log({+ message: `Error sending message to Qstash to schedule next batch of payouts for invoice ${invoiceId}: ${JSON.stringify(qstashResponse)}`,+ type: "errors",+ });+ }++ return logAndRespond(+ `Completed processing current batch of payouts for invoice ${invoiceId}. Next batch scheduled.`,+ );+ }++ return logAndRespond(+ `Completed processing all payouts for invoice ${invoiceId}.`,+ );} catch (error) {await log({message: `Error sending payouts for invoice: ${error.message}`,diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.tsindex 670fc2f017..72ce2b3b70 100644--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-paypal-payouts.ts@@ -7,9 +7,7 @@ export async function sendPaypalPayouts({ invoiceId }: { invoiceId: string }) {const payouts = await prisma.payout.findMany({where: {invoiceId,- status: {- not: "completed",- },+ status: "processing",partner: {payoutsEnabledAt: {not: null,@@ -33,6 +31,7 @@ export async function sendPaypalPayouts({ invoiceId }: { invoiceId: string }) {},},},+ take: 100,});if (payouts.length === 0) {@@ -47,6 +46,18 @@ export async function sendPaypalPayouts({ invoiceId }: { invoiceId: string }) {console.log("PayPal batch payout created", batchPayout);+ // update the payouts to "sent" status+ const updatedPayouts = await prisma.payout.updateMany({+ where: {+ id: { in: payouts.map((p) => p.id) },+ },+ data: {+ status: "sent",+ paidAt: new Date(),+ },+ });+ console.log(`Updated ${updatedPayouts.count} payouts to "sent" status`);+const batchEmails = await sendBatchEmail(payouts.filter((payout) => payout.partner.email)diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-stripe-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-stripe-payouts.tsindex d1cbfd24e6..64340011db 100644--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-stripe-payouts.ts+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-stripe-payouts.ts@@ -42,6 +42,7 @@ export async function sendStripePayouts({},},include: commonInclude,+ take: 100,});if (currentInvoicePayouts.length === 0) {diff --git a/apps/web/app/(ee)/api/paypal/webhook/payouts-item-failed.ts b/apps/web/app/(ee)/api/paypal/webhook/payouts-item-failed.tsindex 245e0e956b..dd6a39b186 100644--- a/apps/web/app/(ee)/api/paypal/webhook/payouts-item-failed.ts+++ b/apps/web/app/(ee)/api/paypal/webhook/payouts-item-failed.ts@@ -9,10 +9,10 @@ const PAYPAL_TO_DUB_STATUS = {"PAYMENT.PAYOUTS-ITEM.CANCELED": "canceled","PAYMENT.PAYOUTS-ITEM.DENIED": "failed","PAYMENT.PAYOUTS-ITEM.FAILED": "failed",- "PAYMENT.PAYOUTS-ITEM.HELD": "processing",+ "PAYMENT.PAYOUTS-ITEM.HELD": "processed","PAYMENT.PAYOUTS-ITEM.REFUNDED": "failed","PAYMENT.PAYOUTS-ITEM.RETURNED": "failed",- "PAYMENT.PAYOUTS-ITEM.UNCLAIMED": "processing",+ "PAYMENT.PAYOUTS-ITEM.UNCLAIMED": "processed",};export async function payoutsItemFailed(event: any) {@@ -58,9 +58,9 @@ export async function payoutsItemFailed(event: any) {},});- if (payoutStatus === "processing") {+ if (payoutStatus === "processed") {await log({- message: `Paypal payout is stuck in processing for invoice ${invoiceId} and partner ${paypalEmail}. PayPal webhook status: ${body.event_type}.${+ message: `Paypal payout is stuck in processed for invoice ${invoiceId} and partner ${paypalEmail}. PayPal webhook status: ${body.event_type}.${failureReason ? ` Failure reason: ${failureReason}` : ""}`,type: "errors",diff --git a/apps/web/app/(ee)/api/paypal/webhook/payouts-item-succeeded.ts b/apps/web/app/(ee)/api/paypal/webhook/payouts-item-succeeded.tsindex 1267244f11..a00e0ddbb6 100644--- a/apps/web/app/(ee)/api/paypal/webhook/payouts-item-succeeded.ts+++ b/apps/web/app/(ee)/api/paypal/webhook/payouts-item-succeeded.ts@@ -45,7 +45,7 @@ export async function payoutsItemSucceeded(event: any) {data: {paypalTransferId: payoutItemId,status: "completed",- paidAt: new Date(),+ paidAt: payout.paidAt ?? new Date(), // preserve the paidAt if it already exists},}),