The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add batch email processing functionality (#3011)
Kiran K58baf3255d91
diff --git a/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts b/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.tsindex 08815b0ccd..5af27764f9 100644--- a/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts+++ b/apps/web/app/(ee)/api/cron/payouts/aggregate-due-commissions/route.ts@@ -259,4 +259,5 @@ async function handler(req: Request) {}}+// GET/POST /api/cron/payouts/aggregate-due-commissionsexport { handler as GET, handler as POST };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 688e2416ee..a102037c5e 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,5 +1,6 @@import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";import { exceededLimitError } from "@/lib/api/errors";+import { queueBatchEmail } from "@/lib/email/queue-batch-email";import {DIRECT_DEBIT_PAYMENT_METHOD_TYPES,FAST_ACH_FEE_CENTS,@@ -13,11 +14,9 @@ import { stripe } from "@/lib/stripe";import { createFxQuote } from "@/lib/stripe/create-fx-quote";import { calculatePayoutFeeForMethod } from "@/lib/stripe/payment-methods";import { PlanProps } from "@/lib/types";-import { sendBatchEmail } from "@dub/email";-import { resend } from "@dub/email/resend";-import PartnerPayoutConfirmed from "@dub/email/templates/partner-payout-confirmed";+import type PartnerPayoutConfirmed from "@dub/email/templates/partner-payout-confirmed";import { prisma } from "@dub/prisma";-import { chunk, currencyFormatter, log } from "@dub/utils";+import { currencyFormatter, log } from "@dub/utils";import { Program, Project } from "@prisma/client";const paymentMethodToCurrency = {@@ -280,36 +279,22 @@ export async function processPayouts({invoice &&DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(paymentMethod.type)) {- if (!resend) {- // this should never happen, but just in case- await log({- message: "Resend is not configured, skipping email sending.",- type: "errors",- });- console.log("Resend is not configured, skipping email sending.");- return;- }-- const payoutChunks = chunk(- payouts.filter(- (payout) =>- // TODO: right now we're only sending notifications for payouts above $100- // but once we have a queue for sending emails, we can remove this check- payout.partner.email && payout.amount > 100_00, // $100- ),- 100,- );-- for (const payoutChunk of payoutChunks) {- await sendBatchEmail(- payoutChunk.map((payout) => ({- variant: "notifications",+ await queueBatchEmail<typeof PartnerPayoutConfirmed>(+ payouts+ .filter((payout) => payout.partner.email)+ .map((payout) => ({to: payout.partner.email!,subject: "You've got money coming your way!",+ variant: "notifications",replyTo: program.supportEmail || "noreply",- react: PartnerPayoutConfirmed({+ templateName: "PartnerPayoutConfirmed",+ templateProps: {email: payout.partner.email!,- program,+ program: {+ id: program.id,+ name: program.name,+ logo: program.logo,+ },payout: {id: payout.id,amount: payout.amount,@@ -317,9 +302,11 @@ export async function processPayouts({endDate: payout.periodEnd,paymentMethod: invoice.paymentMethod ?? "ach",},- }),+ },})),- );- }+ {+ deduplicationId: invoice.id,+ },+ );}}diff --git a/apps/web/app/(ee)/api/cron/send-batch-email/route.ts b/apps/web/app/(ee)/api/cron/send-batch-email/route.tsnew file mode 100644index 0000000000..b89174a283--- /dev/null+++ b/apps/web/app/(ee)/api/cron/send-batch-email/route.ts@@ -0,0 +1,192 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { EMAIL_TEMPLATES_MAP } from "@/lib/email/email-templates-map";+import { sendBatchEmail } from "@dub/email";+import { ResendEmailOptions } from "@dub/email/resend/types";+import { log } from "@dub/utils";+import { NextResponse } from "next/server";+import React from "react";+import { z } from "zod";++export const dynamic = "force-dynamic";++const batchEmailPayloadSchema = z.array(+ z.object({+ templateName: z.enum(+ Object.keys(EMAIL_TEMPLATES_MAP) as [string, ...string[]],+ ),+ templateProps: z.record(z.any()),+ to: z.string().email(),+ from: z.string().optional(),+ subject: z.string(),+ bcc: z.union([z.string(), z.array(z.string())]).optional(),+ replyTo: z.string().optional(),+ variant: z.enum(["primary", "notifications", "marketing"]).optional(),+ headers: z.record(z.string()).optional(),+ tags: z.array(z.object({ name: z.string(), value: z.string() })).optional(),+ scheduledAt: z.string().optional(),+ }),+);++interface BatchError {+ email: string;+ templateName: string;+ error: string;+}++// POST /api/cron/send-batch-email+export async function POST(req: Request) {+ try {+ const rawBody = await req.text();++ await verifyQstashSignature({+ req,+ rawBody,+ });++ const payload = batchEmailPayloadSchema.parse(JSON.parse(rawBody));++ console.log(`Processing batch of ${payload.length} email(s)`);++ // Process all emails in parallel and build Resend payload+ const results = await Promise.allSettled(+ payload.map(async (emailItem) => {+ const TemplateComponent = EMAIL_TEMPLATES_MAP[emailItem.templateName];++ if (!TemplateComponent) {+ throw new Error(+ `Template "${emailItem.templateName}" not found in TEMPLATE_MAP`,+ );+ }++ const react = React.createElement(+ TemplateComponent,+ emailItem.templateProps,+ );++ return {+ emailItem,+ emailPayload: {+ react,+ from: emailItem.from,+ to: emailItem.to,+ subject: emailItem.subject,+ variant: emailItem.variant,+ ...(emailItem.bcc && { bcc: emailItem.bcc }),+ ...(emailItem.replyTo && { replyTo: emailItem.replyTo }),+ ...(emailItem.headers && { headers: emailItem.headers }),+ ...(emailItem.tags && { tags: emailItem.tags }),+ ...(emailItem.scheduledAt && {+ scheduledAt: emailItem.scheduledAt,+ }),+ },+ };+ }),+ );++ // Separate successes and failures+ const emailsToSend: ResendEmailOptions[] = [];+ const errors: BatchError[] = [];++ for (let i = 0; i < results.length; i++) {+ const result = results[i];+ const emailItem = payload[i];++ if (result.status === "fulfilled") {+ emailsToSend.push(result.value.emailPayload);+ } else {+ const errorMessage =+ result.reason instanceof Error+ ? result.reason.message+ : String(result.reason);++ console.error(+ `Failed to process email template ${emailItem.templateName} for ${emailItem.to}:`,+ errorMessage,+ );++ errors.push({+ email: emailItem.to,+ templateName: emailItem.templateName,+ error: errorMessage,+ });++ await log({+ message: `Failed to import/render email template "${emailItem.templateName}" for ${emailItem.to}: ${errorMessage}`,+ type: "errors",+ });+ }+ }++ if (emailsToSend.length === 0) {+ console.error("No emails were successfully processed.");++ await log({+ message: `Batch email processing failed: All ${payload.length} email(s) failed to process`,+ type: "errors",+ mention: true,+ });++ return NextResponse.json(+ {+ success: false,+ processed: 0,+ failed: payload.length,+ errors,+ },+ { status: 500 },+ );+ }++ console.log(`Sending ${emailsToSend.length} email(s) via Resend.`);++ const { data, error } = await sendBatchEmail(emailsToSend);++ if (error) {+ console.error("Resend API error:", error);++ await log({+ message: `Resend batch send failed: ${JSON.stringify(error)}`,+ type: "errors",+ mention: true,+ });++ return NextResponse.json(+ {+ success: false,+ processed: 0,+ failed: emailsToSend.length,+ errors: [+ ...errors,+ {+ error: "Resend API error",+ details: error,+ },+ ],+ },+ { status: 500 },+ );+ }++ if (data) {+ console.log(`Successfully sent ${emailsToSend.length} email(s).`, data);+ }++ return NextResponse.json({+ success: true,+ sent: emailsToSend.length,+ failed: errors.length,+ ...(errors.length > 0 && { processingErrors: errors }),+ });+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : String(error);++ await log({+ message: `Error processing batch email queue: ${errorMessage}`,+ type: "errors",+ mention: true,+ });++ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/lib/email/email-templates-map.ts b/apps/web/lib/email/email-templates-map.tsnew file mode 100644index 0000000000..61931425f9--- /dev/null+++ b/apps/web/lib/email/email-templates-map.ts@@ -0,0 +1,5 @@+import PartnerPayoutConfirmed from "@dub/email/templates/partner-payout-confirmed";++export const EMAIL_TEMPLATES_MAP = {+ PartnerPayoutConfirmed,+} as const;diff --git a/apps/web/lib/email/queue-batch-email.ts b/apps/web/lib/email/queue-batch-email.tsnew file mode 100644index 0000000000..bbf0b3c1fc--- /dev/null+++ b/apps/web/lib/email/queue-batch-email.ts@@ -0,0 +1,72 @@+import { qstash } from "@/lib/cron";+import { ResendEmailOptions } from "@dub/email/resend/types";+import { APP_DOMAIN_WITH_NGROK, chunk, log } from "@dub/utils";+import { EMAIL_TEMPLATES_MAP } from "./email-templates-map";++type QueueBatchProps<TTemplate extends (props: any) => any> =+ ResendEmailOptions & {+ templateName: keyof typeof EMAIL_TEMPLATES_MAP;+ templateProps: Parameters<TTemplate>[0];+ };++const BATCH_SIZE = 100;++const queue = qstash.queue({+ queueName: "batch-email",+});++export async function queueBatchEmail<TTemplate extends (props: any) => any>(+ emails: QueueBatchProps<TTemplate>[],+ options?: {+ deduplicationId?: string;+ },+): Promise<string[]> {+ if (emails.length === 0) {+ console.log("No emails to queue. Skipping...");+ return [];+ }++ try {+ await queue.upsert({+ parallelism: 10,+ });++ // Chunk emails into batches of BATCH_SIZE+ const batches = chunk(emails, BATCH_SIZE);+ const messageIds: string[] = [];++ // Enqueue each batch+ for (let i = 0; i < batches.length; i++) {+ const batch = batches[i];++ const response = await queue.enqueueJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/send-batch-email`,+ method: "POST",+ body: batch,+ ...(options?.deduplicationId && {+ deduplicationId: `${options.deduplicationId}-batch-${i}`,+ }),+ });++ messageIds.push(response.messageId);++ console.log(+ `Enqueued batch ${i + 1}/${batches.length} with ${batch.length} email(s): ${response.messageId}`,+ );+ }++ console.log(+ `Queued ${emails.length} email(s) in ${batches.length} batch(es)`,+ );++ return messageIds;+ } catch (error) {+ await log({+ message: `Failed to queue batch emails: ${error.message}`,+ type: "errors",+ mention: true,+ });++ throw error;+ }+}diff --git a/apps/web/scripts/send-batch-emails.tsx b/apps/web/scripts/send-batch-emails.tsxnew file mode 100644index 0000000000..31faaabfd1--- /dev/null+++ b/apps/web/scripts/send-batch-emails.tsx@@ -0,0 +1,58 @@+import { prisma } from "@dub/prisma";+import { ACME_PROGRAM_ID } from "@dub/utils";+import "dotenv-flow/config";+import { queueBatchEmail } from "../lib/email/queue-batch-email";++async function main() {+ const program = await prisma.program.findUniqueOrThrow({+ where: {+ id: ACME_PROGRAM_ID,+ },+ });++ const res = await queueBatchEmail(+ [+ {+ partner: { email: "[email protected]" },+ id: "po_1234567890",+ amount: 10000,+ periodStart: new Date("2025-10-01"),+ periodEnd: new Date("2025-10-31"),+ paymentMethod: "ach",+ },+ {+ partner: { email: "[email protected]" },+ id: "po_1234567890",+ amount: 25000,+ periodStart: new Date("2025-10-01"),+ periodEnd: new Date("2025-10-31"),+ paymentMethod: "ach",+ },+ ].map((payout) => ({+ to: payout.partner.email!,+ subject: "You've got money coming your way!",+ variant: "notifications",+ replyTo: program.supportEmail || "noreply",+ templateName: "PartnerPayoutConfirmed",+ templateProps: {+ email: payout.partner.email!,+ program: {+ id: program.id,+ name: program.name,+ logo: program.logo,+ },+ payout: {+ id: payout.id,+ amount: payout.amount,+ startDate: payout.periodStart,+ endDate: payout.periodEnd,+ paymentMethod: "ach",+ },+ },+ })),+ );++ console.log({ res });+}++main();diff --git a/apps/web/scripts/send-emails.tsx b/apps/web/scripts/send-emails.tsxdeleted file mode 100644index 23e279512c..0000000000--- a/apps/web/scripts/send-emails.tsx+++ /dev/null@@ -1,40 +0,0 @@-import { sendEmail } from "@dub/email";-import FailedPayment from "@dub/email/templates/failed-payment";-import "dotenv-flow/config";--const attemptCount = 2;-const amountDue = 2400;-const user = {- name: "Steven",- email: "[email protected]",-};-const workspace = {- name: "Dub",- slug: "dub",-};--async function main() {- const res = await sendEmail({- to: user.email as string,- from: "[email protected]",- subject: `${- attemptCount == 2- ? "2nd notice: "- : attemptCount == 3- ? "3rd notice: "- : ""- }Your payment for Dub.co failed`,- react: (- <FailedPayment- attemptCount={attemptCount}- amountDue={amountDue}- user={user}- workspace={workspace}- />- ),- });-- console.log({ res });-}--main();