The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Refactor Stripe payouts flow to use queue setup (#3058)
Steven Tey84b9b108d95f
diff --git a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-stripe-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-stripe-payouts.tsnew file mode 100644index 0000000000..957b1ebe3a--- /dev/null+++ b/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/queue-stripe-payouts.ts@@ -0,0 +1,61 @@+import { qstash } from "@/lib/cron";+import { prisma } from "@dub/prisma";+import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";+import { Invoice } from "@prisma/client";+import { z } from "zod";++const stripeChargeMetadataSchema = z.object({+ id: z.string(), // Stripe charge id+});++export async function queueStripePayouts(+ invoice: Pick<Invoice, "id" | "stripeChargeMetadata">,+) {+ const { id: invoiceId, stripeChargeMetadata } = invoice;++ // Find the id of the charge that was used to fund the transfer+ const parsedChargeMetadata =+ stripeChargeMetadataSchema.safeParse(stripeChargeMetadata);+ const chargeId = parsedChargeMetadata?.success+ ? parsedChargeMetadata?.data.id+ : undefined;++ // this should never happen since all completed invoices should have a charge id, but just in case+ if (!chargeId) {+ await log({+ message:+ "No charge id found in stripeChargeMetadata for invoice " ++ invoiceId ++ ", continuing without source_transaction.",+ type: "errors",+ });+ }++ const partnersInCurrentInvoice = await prisma.payout.groupBy({+ by: ["partnerId"],+ where: {+ invoiceId,+ status: "processing",+ },+ });++ const queue = qstash.queue({+ queueName: "send-stripe-payout",+ });++ for (const { partnerId } of partnersInCurrentInvoice) {+ const response = await queue.enqueueJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/send-stripe-payout`,+ deduplicationId: `${invoiceId}-${partnerId}`,+ method: "POST",+ body: {+ invoiceId,+ partnerId,+ chargeId,+ },+ });+ console.log(+ `Enqueued Stripe payout for invoice ${invoiceId} and partner ${partnerId}: ${response.messageId}`,+ );+ }+}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 3707571a31..4f0c2aeea6 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,12 +1,11 @@import { handleAndReturnErrorResponse } from "@/lib/api/errors";-import { qstash } from "@/lib/cron";import { verifyQstashSignature } from "@/lib/cron/verify-qstash";import { prisma } from "@dub/prisma";-import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";+import { log } from "@dub/utils";import { z } from "zod";import { logAndRespond } from "../../utils";+import { queueStripePayouts } from "./queue-stripe-payouts";import { sendPaypalPayouts } from "./send-paypal-payouts";-import { sendStripePayouts } from "./send-stripe-payouts";export const dynamic = "force-dynamic";export const maxDuration = 600; // This function can run for a maximum of 10 minutes@@ -14,15 +13,9 @@ export const maxDuration = 600; // This function can run for a maximum of 10 minconst payloadSchema = z.object({invoiceId: z.string(),});--const stripeChargeMetadataSchema = z.object({- id: z.string(), // Stripe charge id-});-// 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 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();@@ -57,63 +50,13 @@ export async function POST(req: Request) {);}- // Find the id of the charge that was used to fund the transfer- const parsedChargeMetadata = stripeChargeMetadataSchema.safeParse(- invoice.stripeChargeMetadata,- );- const chargeId = parsedChargeMetadata.success- ? parsedChargeMetadata.data.id- : undefined;-- // this should never happen since all completed invoices should have a charge id, but just in case- if (!chargeId) {- await log({- message:- "No charge id found in stripeChargeMetadata for invoice " +- invoiceId +- ", continuing without source_transaction.",- type: "errors",- });- }-await Promise.allSettled([- sendStripePayouts({- invoiceId,- chargeId,- }),-+ queueStripePayouts(invoice),sendPaypalPayouts({invoiceId,}),]);- 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}.`,);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 72ce2b3b70..ec15f8325c 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@@ -31,7 +31,6 @@ export async function sendPaypalPayouts({ invoiceId }: { invoiceId: string }) {},},},- take: 100,});if (payouts.length === 0) {@@ -74,5 +73,5 @@ export async function sendPaypalPayouts({ invoiceId }: { invoiceId: string }) {})),);- console.log("Resend batch emails sent", batchEmails);+ console.log("Resend batch emails sent", JSON.stringify(batchEmails, null, 2));}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.tsdeleted file mode 100644index 156a833e56..0000000000--- a/apps/web/app/(ee)/api/cron/payouts/charge-succeeded/send-stripe-payouts.ts+++ /dev/null@@ -1,114 +0,0 @@-import { queueBatchEmail } from "@/lib/email/queue-batch-email";-import { createStripeTransfer } from "@/lib/partners/create-stripe-transfer";-import PartnerPayoutProcessed from "@dub/email/templates/partner-payout-processed";-import { prisma } from "@dub/prisma";-import { Prisma } from "@prisma/client";--export async function sendStripePayouts({- invoiceId,- chargeId,-}: {- invoiceId: string;- chargeId?: string;-}) {- const commonInclude = Prisma.validator<Prisma.PayoutInclude>()({- partner: {- select: {- id: true,- email: true,- stripeConnectId: true,- },- },- program: {- select: {- id: true,- name: true,- logo: true,- },- },- });-- const currentInvoicePayouts = await prisma.payout.findMany({- where: {- invoiceId,- status: "processing",- partner: {- payoutsEnabledAt: {- not: null,- },- stripeConnectId: {- not: null,- },- },- },- include: commonInclude,- take: 100,- });-- if (currentInvoicePayouts.length === 0) {- console.log("No payouts to be sent via Stripe, skipping...");- return;- }-- // get all previously processed payouts for the partners in this invoice- // but haven't been transferred to their Stripe Express account yet- const previouslyProcessedPayouts = await prisma.payout.findMany({- where: {- status: "processed",- stripeTransferId: null,- partnerId: {- in: currentInvoicePayouts.map((p) => p.partnerId),- },- },- include: commonInclude,- });-- // Group currentInvoicePayouts + previouslyProcessedPayouts by partnerId- const partnerPayoutsMap = [- ...currentInvoicePayouts,- ...previouslyProcessedPayouts,- ].reduce((map, payout) => {- const { partner } = payout;-- if (!map.has(partner.id)) {- map.set(partner.id, []);- }-- map.get(partner.id)!.push(payout);-- return map;- }, new Map<string, typeof currentInvoicePayouts>());-- // Process payouts for each partner- for (const [_, partnerPayouts] of partnerPayoutsMap) {- await createStripeTransfer({- partner: partnerPayouts[0].partner,- previouslyProcessedPayouts: partnerPayouts.filter(- (p) => p.status === "processed",- ),- // this is usually just one payout, but we're doing this- // just in case there are multiple payouts for the same partner in the same invoice- currentInvoicePayouts: partnerPayouts.filter(- (p) => p.invoiceId === invoiceId,- ),- chargeId,- });- }-- await queueBatchEmail<typeof PartnerPayoutProcessed>(- currentInvoicePayouts- .filter((p) => p.partner.email)- .map((p) => ({- variant: "notifications",- to: p.partner.email!,- subject: "You've been paid!",- templateName: "PartnerPayoutProcessed",- templateProps: {- email: p.partner.email!,- program: p.program,- payout: p,- variant: "stripe",- },- })),- );-}diff --git a/apps/web/app/(ee)/api/cron/payouts/send-stripe-payout/route.ts b/apps/web/app/(ee)/api/cron/payouts/send-stripe-payout/route.tsnew file mode 100644index 0000000000..cb454cbc11--- /dev/null+++ b/apps/web/app/(ee)/api/cron/payouts/send-stripe-payout/route.ts@@ -0,0 +1,105 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { createStripeTransfer } from "@/lib/partners/create-stripe-transfer";+import { sendEmail } from "@dub/email";+import PartnerPayoutProcessed from "@dub/email/templates/partner-payout-processed";+import { prisma } from "@dub/prisma";+import { log } from "@dub/utils";+import { z } from "zod";+import { logAndRespond } from "../../utils";++export const dynamic = "force-dynamic";++const payloadSchema = z.object({+ invoiceId: z.string(),+ partnerId: z.string(),+ chargeId: z.string().optional(),+});++// POST /api/cron/payouts/send-stripe-payout+export async function POST(req: Request) {+ try {+ const rawBody = await req.text();++ await verifyQstashSignature({+ req,+ rawBody,+ });++ const { invoiceId, partnerId, chargeId } = payloadSchema.parse(+ JSON.parse(rawBody),+ );++ // there should only be one payout per partner in a given invoice, but just in case there are multiple+ const currentInvoicePayouts = await prisma.payout.findMany({+ where: {+ invoiceId,+ partnerId,+ status: "processing",+ },+ include: {+ partner: true,+ program: true,+ },+ });++ if (currentInvoicePayouts.length === 0) {+ return logAndRespond(+ `No "processing" payouts found for partner ${partnerId} and invoice ${invoiceId}`,+ );+ }++ // get all previously processed payouts for the partners in this invoice+ // but haven't been transferred to their Stripe Express account yet+ const previouslyProcessedPayouts = await prisma.payout.findMany({+ where: {+ status: "processed",+ stripeTransferId: null,+ partnerId,+ },+ include: {+ partner: true,+ program: true,+ },+ });++ await createStripeTransfer({+ partner: currentInvoicePayouts[0].partner,+ previouslyProcessedPayouts,+ currentInvoicePayouts,+ chargeId,+ });++ // again, there should only be one payout per partner in a given invoice+ const payout = currentInvoicePayouts[0];+ if (payout.partner.email) {+ const emailRes = await sendEmail({+ variant: "notifications",+ to: payout.partner.email!,+ subject: "You've been paid!",+ react: PartnerPayoutProcessed({+ email: payout.partner.email!,+ program: payout.program,+ payout,+ variant: "stripe",+ }),+ });++ console.log(`Resend email sent: ${JSON.stringify(emailRes, null, 2)}`);+ }++ return logAndRespond(+ `Processed send-stripe-payout job for partner ${partnerId} and invoice ${invoiceId}`,+ );+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);++ await log({+ message: `Error sending Stripe payout: ${errorMessage}`,+ type: "errors",+ mention: true,+ });++ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/app/(ee)/api/stripe/connect/webhook/balance-available.ts b/apps/web/app/(ee)/api/stripe/connect/webhook/balance-available.tsindex 747d25721b..176b6033bb 100644--- a/apps/web/app/(ee)/api/stripe/connect/webhook/balance-available.ts+++ b/apps/web/app/(ee)/api/stripe/connect/webhook/balance-available.ts@@ -3,7 +3,7 @@ import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import Stripe from "stripe";const queue = qstash.queue({- queueName: "stripe-balance-available",+ queueName: "withdraw-stripe-balance",});export async function balanceAvailable(event: Stripe.Event) {@@ -13,10 +13,6 @@ export async function balanceAvailable(event: Stripe.Event) {return "No stripeConnectId found in event. Skipping...";}- await queue.upsert({- parallelism: 10,- });-const response = await queue.enqueueJSON({url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/balance-available`,deduplicationId: event.id,diff --git a/apps/web/lib/api/discounts/queue-discount-code-deletion.ts b/apps/web/lib/api/discounts/queue-discount-code-deletion.tsindex 9e2e4bc1ef..452bcfe644 100644--- a/apps/web/lib/api/discounts/queue-discount-code-deletion.ts+++ b/apps/web/lib/api/discounts/queue-discount-code-deletion.ts@@ -2,7 +2,7 @@ import { qstash } from "@/lib/cron";import { APP_DOMAIN_WITH_NGROK, chunk } from "@dub/utils";const queue = qstash.queue({- queueName: "discount-code-deletion",+ queueName: "delete-discount-code",});// Triggered in the following cases:@@ -19,10 +19,6 @@ export async function queueDiscountCodeDeletion(return;}- await queue.upsert({- parallelism: 10,- });-// TODO:// Check if we can use the batchJSON (I tried it but didn't work)diff --git a/apps/web/lib/email/queue-batch-email.ts b/apps/web/lib/email/queue-batch-email.tsindex 9c407c322a..94a097e624 100644--- a/apps/web/lib/email/queue-batch-email.ts+++ b/apps/web/lib/email/queue-batch-email.ts@@ -12,7 +12,7 @@ type QueueBatchProps<TTemplate extends (props: any) => any> =const BATCH_SIZE = 100;const queue = qstash.queue({- queueName: "batch-email",+ queueName: "send-batch-email",});export async function queueBatchEmail<TTemplate extends (props: any) => any>(@@ -27,10 +27,6 @@ export async function queueBatchEmail<TTemplate extends (props: any) => any>(}try {- await queue.upsert({- parallelism: 10,- });-// Chunk emails into batches of BATCH_SIZEconst batches = chunk(emails, BATCH_SIZE);const messageIds: string[] = [];