The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add cron routes that email new submitted lead comments
Rafib676c92d37bc
diff --git a/apps/web/app/(ee)/api/cron/submitted-leads/comments/notify-partner/route.ts b/apps/web/app/(ee)/api/cron/submitted-leads/comments/notify-partner/route.tsnew file mode 100644index 0000000000..12c1f0c824--- /dev/null+++ b/apps/web/app/(ee)/api/cron/submitted-leads/comments/notify-partner/route.ts@@ -0,0 +1,147 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { prisma } from "@/lib/prisma";+import { getSubmittedLeadCommentNotificationBatch } from "@/lib/submitted-leads/submitted-lead-comment-notifications";+import { getCompanyLogoUrl } from "@/ui/submitted-leads/submitted-lead-utils";+import { sendBatchEmail } from "@dub/email";+import NewSubmittedLeadCommentsFromProgram from "@dub/email/templates/new-submitted-lead-comments-from-program";+import { log } from "@dub/utils";+import { subDays } from "date-fns";+import * as z from "zod/v4";+import { logAndRespond } from "../../../utils";++export const dynamic = "force-dynamic";++const schema = z.object({+ leadId: z.string(),+ lastCommentId: z.string(),+});++// POST /api/cron/submitted-leads/comments/notify-partner+// Notify a partner about new comments from the program on their submitted lead+export async function POST(req: Request) {+ try {+ const rawBody = await req.text();++ await verifyQstashSignature({+ req,+ rawBody,+ });++ const { leadId, lastCommentId } = schema.parse(JSON.parse(rawBody));++ const lead = await prisma.submittedLead.findUniqueOrThrow({+ where: {+ id: leadId,+ },+ include: {+ program: true,+ partner: {+ include: {+ users: {+ where: {+ notificationPreferences: {+ newMessageFromProgram: true,+ },+ },+ include: {+ user: true,+ },+ },+ },+ },+ comments: {+ where: {+ partnerId: null, // not written by the partner+ partnerVisible: true,+ createdAt: {+ gt: subDays(new Date(), 3),+ },+ },+ orderBy: {+ createdAt: "desc",+ },+ take: 50,+ include: {+ user: true,+ },+ },+ },+ });++ if (lead.comments.length === 0)+ return logAndRespond(+ `No comments found for the partner on lead ${leadId}. Skipping...`,+ );++ if (lead.comments[0].id !== lastCommentId)+ return logAndRespond(+ `There is a more recent comment than ${lastCommentId}. Skipping...`,+ );++ const partnerUsersToNotify = lead.partner.users+ .map(({ user }) => user)+ .filter(({ email }) => Boolean(email)) as { email: string }[];++ if (partnerUsersToNotify.length === 0)+ return logAndRespond(+ `No partner emails to notify for partner ${lead.partnerId}. Skipping...`,+ );++ const comments = getSubmittedLeadCommentNotificationBatch(lead.comments);+ const { program } = lead;++ const { error } = await sendBatchEmail(+ partnerUsersToNotify.map(({ email }) => ({+ subject: `${program.name} sent ${comments.length === 1 ? "a comment" : `${comments.length} comments`} for your submitted lead`,+ variant: "notifications",+ to: email,+ replyTo: program.supportEmail || "noreply",+ react: NewSubmittedLeadCommentsFromProgram({+ program: {+ name: program.name,+ slug: program.slug,+ logo: program.logo,+ },+ lead: {+ id: lead.id,+ name: lead.name,+ email: lead.email,+ image: getCompanyLogoUrl(lead.email),+ },+ comments: comments.map((comment) => ({+ text: comment.text,+ createdAt: comment.createdAt,+ user: comment.user.name+ ? {+ name: comment.user.name,+ image: comment.user.image,+ }+ : {+ name: program.name,+ image: program.logo,+ },+ })),+ email,+ }),+ tags: [{ name: "type", value: "notification-email" }],+ })),+ );++ if (error)+ throw new Error(+ `Error sending comment emails to partner ${lead.partnerId}: ${error.message}`,+ );++ return logAndRespond(+ `Emails sent for comments on lead ${leadId} to partner ${lead.partnerId}.`,+ );+ } catch (error) {+ await log({+ message: `Error notifying partner of new submitted lead comments: ${error.message}`,+ type: "errors",+ });++ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/app/(ee)/api/cron/submitted-leads/comments/notify-program/route.ts b/apps/web/app/(ee)/api/cron/submitted-leads/comments/notify-program/route.tsnew file mode 100644index 0000000000..2d070a9e0c--- /dev/null+++ b/apps/web/app/(ee)/api/cron/submitted-leads/comments/notify-program/route.ts@@ -0,0 +1,152 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { prisma } from "@/lib/prisma";+import { getSubmittedLeadCommentNotificationBatch } from "@/lib/submitted-leads/submitted-lead-comment-notifications";+import { getCompanyLogoUrl } from "@/ui/submitted-leads/submitted-lead-utils";+import { sendBatchEmail } from "@dub/email";+import NewSubmittedLeadCommentsFromPartner from "@dub/email/templates/new-submitted-lead-comments-from-partner";+import { log } from "@dub/utils";+import { subDays } from "date-fns";+import * as z from "zod/v4";+import { logAndRespond } from "../../../utils";++export const dynamic = "force-dynamic";++const schema = z.object({+ leadId: z.string(),+ lastCommentId: z.string(),+});++// POST /api/cron/submitted-leads/comments/notify-program+// Notify the program's workspace about new comments from the partner on a submitted lead+export async function POST(req: Request) {+ try {+ const rawBody = await req.text();++ await verifyQstashSignature({+ req,+ rawBody,+ });++ const { leadId, lastCommentId } = schema.parse(JSON.parse(rawBody));++ const lead = await prisma.submittedLead.findUniqueOrThrow({+ where: {+ id: leadId,+ },+ include: {+ partner: true,+ program: {+ include: {+ workspace: {+ include: {+ users: {+ where: {+ notificationPreference: {+ newMessageFromPartner: true,+ },+ },+ include: {+ user: true,+ },+ },+ },+ },+ },+ },+ comments: {+ where: {+ partnerId: {+ not: null, // written by the partner+ },+ createdAt: {+ gt: subDays(new Date(), 3),+ },+ },+ orderBy: {+ createdAt: "desc",+ },+ take: 50,+ include: {+ user: true,+ },+ },+ },+ });++ if (lead.comments.length === 0)+ return logAndRespond(+ `No comments from the partner found on lead ${leadId}. Skipping...`,+ );++ if (lead.comments[0].id !== lastCommentId)+ return logAndRespond(+ `There is a more recent comment than ${lastCommentId}. Skipping...`,+ );++ const { workspace } = lead.program;++ const usersToNotify = workspace.users+ .map(({ user }) => user)+ .filter(({ email, isMachine }) => email && !isMachine) as {+ email: string;+ }[];++ if (usersToNotify.length === 0)+ return logAndRespond(+ `No workspace emails to notify for lead ${leadId}. Skipping...`,+ );++ const comments = getSubmittedLeadCommentNotificationBatch(lead.comments);+ const { partner } = lead;++ const { error } = await sendBatchEmail(+ usersToNotify.map(({ email }) => ({+ subject: `${comments.length} submitted lead ${comments.length === 1 ? "comment" : "comments"} from ${partner.name}`,+ variant: "notifications",+ to: email,+ react: NewSubmittedLeadCommentsFromPartner({+ workspace: {+ slug: workspace.slug,+ },+ partner: {+ id: partner.id,+ name: partner.name,+ },+ lead: {+ id: lead.id,+ name: lead.name,+ email: lead.email,+ image: getCompanyLogoUrl(lead.email),+ },+ comments: comments.map((comment) => ({+ text: comment.text,+ createdAt: comment.createdAt,+ user: {+ name: comment.user.name || partner.name,+ image: comment.user.image || partner.image,+ },+ })),+ email,+ }),+ tags: [{ name: "type", value: "notification-email" }],+ })),+ );++ if (error)+ throw new Error(+ `Error sending comment emails for lead ${leadId}: ${error.message}`,+ );++ return logAndRespond(+ `Emails sent for comments from partner ${partner.id} on lead ${leadId}.`,+ );+ } catch (error) {+ await log({+ message: `Error notifying program of new submitted lead comments: ${error.message}`,+ type: "errors",+ });++ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/lib/submitted-leads/submitted-lead-comment-notifications.ts b/apps/web/lib/submitted-leads/submitted-lead-comment-notifications.tsnew file mode 100644index 0000000000..4a1d37aa06--- /dev/null+++ b/apps/web/lib/submitted-leads/submitted-lead-comment-notifications.ts@@ -0,0 +1,49 @@+import { qstash } from "@/lib/cron";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";++// Wait before we notify, so that comments posted close together go out in one email+const NOTIFICATION_DELAY_SECONDS = 60 * 3;++export async function enqueueSubmittedLeadCommentNotification({+ recipient,+ leadId,+ commentId,+}: {+ recipient: "partner" | "program";+ leadId: string;+ commentId: string;+}) {+ return qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/submitted-leads/comments/notify-${recipient}`,+ body: {+ leadId,+ lastCommentId: commentId,+ },+ delay: NOTIFICATION_DELAY_SECONDS,+ });+}++// Get the comments to include in one email, oldest first. Each notification+// job skips when a newer comment exists, so a comment that was posted less than+// the delay before the next one has not been sent yet.+export function getSubmittedLeadCommentNotificationBatch<+ T extends { createdAt: Date },+>(commentsNewestFirst: T[]) {+ const batch: T[] = [];++ for (const comment of commentsNewestFirst) {+ const newer = batch[batch.length - 1];++ if (+ newer &&+ newer.createdAt.getTime() - comment.createdAt.getTime() >=+ NOTIFICATION_DELAY_SECONDS * 1000+ ) {+ break;+ }++ batch.push(comment);+ }++ return batch.reverse();+}diff --git a/apps/web/tests/misc/submitted-lead-comment-notification-batch.test.ts b/apps/web/tests/misc/submitted-lead-comment-notification-batch.test.tsnew file mode 100644index 0000000000..7cbd26330f--- /dev/null+++ b/apps/web/tests/misc/submitted-lead-comment-notification-batch.test.ts@@ -0,0 +1,38 @@+import { getSubmittedLeadCommentNotificationBatch } from "@/lib/submitted-leads/submitted-lead-comment-notifications";+import { describe, expect, it } from "vitest";++const minutesAgo = (minutes: number) => ({+ id: `${minutes}m`,+ createdAt: new Date(Date.UTC(2026, 9, 2, 12) - minutes * 60 * 1000),+});++describe("getSubmittedLeadCommentNotificationBatch", () => {+ it("returns the comments that were posted less than 3 minutes apart, oldest first", () => {+ const comments = [minutesAgo(0), minutesAgo(2), minutesAgo(4)];++ expect(+ getSubmittedLeadCommentNotificationBatch(comments).map(({ id }) => id),+ ).toEqual(["4m", "2m", "0m"]);+ });++ it("stops at the first gap of 3 minutes or more", () => {+ const comments = [+ minutesAgo(0),+ minutesAgo(1),+ minutesAgo(4),+ minutesAgo(5),+ ];++ expect(+ getSubmittedLeadCommentNotificationBatch(comments).map(({ id }) => id),+ ).toEqual(["1m", "0m"]);+ });++ it("returns only the latest comment when it is alone", () => {+ const comments = [minutesAgo(0), minutesAgo(60)];++ expect(+ getSubmittedLeadCommentNotificationBatch(comments).map(({ id }) => id),+ ).toEqual(["0m"]);+ });+});