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.

Send every unsent comment in submitted lead comment emails

Rafi77bf7bcd5a2e
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.ts
index 8630082681..dd1883cd46 100644
--- 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.ts
@@ -1,7 +1,7 @@
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 { getSubmittedLeadCommentsToNotify } 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";
@@ -15,6 +15,7 @@ export const dynamic = "force-dynamic";
const schema = z.object({
leadId: z.string(),
lastCommentId: z.string(),
+ lastCommentCreatedAt: z.coerce.date(),
});
// POST /api/cron/submitted-leads/comments/notify-partner
@@ -28,7 +29,9 @@ export async function POST(req: Request) {
rawBody,
});
- const { leadId, lastCommentId } = schema.parse(JSON.parse(rawBody));
+ const { leadId, lastCommentId, lastCommentCreatedAt } = schema.parse(
+ JSON.parse(rawBody),
+ );
const lead = await prisma.submittedLead.findUniqueOrThrow({
where: {
@@ -54,6 +57,7 @@ export async function POST(req: Request) {
where: {
partnerId: null, // not written by the partner
partnerVisible: true,
+ notifiedAt: null,
createdAt: {
gt: subDays(new Date(), 3),
},
@@ -69,74 +73,89 @@ export async function POST(req: Request) {
},
});
- if (lead.comments.length === 0)
+ const comments = getSubmittedLeadCommentsToNotify({
+ unsentComments: lead.comments,
+ lastCommentCreatedAt,
+ });
+
+ if (!comments)
return logAndRespond(
- `No comments found for the partner on lead ${leadId}. Skipping...`,
+ `There is an unsent comment newer than ${lastCommentId}. Skipping...`,
);
- if (lead.comments[0].id !== lastCommentId)
+ if (comments.length === 0)
return logAndRespond(
- `There is a more recent comment than ${lastCommentId}. Skipping...`,
+ `No unsent comments found on lead ${leadId}. 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 { program } = lead;
+
+ if (partnerUsersToNotify.length > 0) {
+ 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,
+ }),
+ })),
+ {
+ idempotencyKey: `submitted-lead-comments-partner/${lastCommentId}`,
+ },
);
- const comments = getSubmittedLeadCommentNotificationBatch(lead.comments);
- const { program } = lead;
+ if (error)
+ throw new Error(
+ `Error sending comment emails to partner ${lead.partnerId}: ${error.message}`,
+ );
+ }
- 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,
- }),
- })),
- {
- idempotencyKey: `submitted-lead-comments-partner/${lastCommentId}`,
+ await prisma.submittedLeadComment.updateMany({
+ where: {
+ id: {
+ in: comments.map(({ id }) => id),
+ },
+ notifiedAt: null,
},
- );
-
- if (error)
- throw new Error(
- `Error sending comment emails to partner ${lead.partnerId}: ${error.message}`,
- );
+ data: {
+ notifiedAt: new Date(),
+ },
+ });
return logAndRespond(
- `Emails sent for comments on lead ${leadId} to partner ${lead.partnerId}.`,
+ partnerUsersToNotify.length > 0
+ ? `Emails sent for comments on lead ${leadId} to partner ${lead.partnerId}.`
+ : `No partner emails to notify for partner ${lead.partnerId}. Marked the comments as handled.`,
);
} catch (error) {
await log({
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.ts
index 63bb2a45bb..1bed5f45db 100644
--- 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.ts
@@ -1,7 +1,7 @@
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 { getSubmittedLeadCommentsToNotify } 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";
@@ -15,6 +15,7 @@ export const dynamic = "force-dynamic";
const schema = z.object({
leadId: z.string(),
lastCommentId: z.string(),
+ lastCommentCreatedAt: z.coerce.date(),
});
// POST /api/cron/submitted-leads/comments/notify-program
@@ -28,7 +29,9 @@ export async function POST(req: Request) {
rawBody,
});
- const { leadId, lastCommentId } = schema.parse(JSON.parse(rawBody));
+ const { leadId, lastCommentId, lastCommentCreatedAt } = schema.parse(
+ JSON.parse(rawBody),
+ );
const lead = await prisma.submittedLead.findUniqueOrThrow({
where: {
@@ -59,6 +62,7 @@ export async function POST(req: Request) {
partnerId: {
not: null, // written by the partner
},
+ notifiedAt: null,
createdAt: {
gt: subDays(new Date(), 3),
},
@@ -74,14 +78,19 @@ export async function POST(req: Request) {
},
});
- if (lead.comments.length === 0)
+ const comments = getSubmittedLeadCommentsToNotify({
+ unsentComments: lead.comments,
+ lastCommentCreatedAt,
+ });
+
+ if (!comments)
return logAndRespond(
- `No comments from the partner found on lead ${leadId}. Skipping...`,
+ `There is an unsent comment newer than ${lastCommentId}. Skipping...`,
);
- if (lead.comments[0].id !== lastCommentId)
+ if (comments.length === 0)
return logAndRespond(
- `There is a more recent comment than ${lastCommentId}. Skipping...`,
+ `No unsent comments found on lead ${leadId}. Skipping...`,
);
const { workspace } = lead.program;
@@ -92,56 +101,66 @@ export async function POST(req: Request) {
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,
+ if (usersToNotify.length > 0) {
+ 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,
},
- })),
- email,
- }),
- })),
- {
- idempotencyKey: `submitted-lead-comments-program/${lastCommentId}`,
- },
- );
-
- if (error)
- throw new Error(
- `Error sending comment emails for lead ${leadId}: ${error.message}`,
+ 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,
+ }),
+ })),
+ {
+ idempotencyKey: `submitted-lead-comments-program/${lastCommentId}`,
+ },
);
+ if (error)
+ throw new Error(
+ `Error sending comment emails for lead ${leadId}: ${error.message}`,
+ );
+ }
+
+ await prisma.submittedLeadComment.updateMany({
+ where: {
+ id: {
+ in: comments.map(({ id }) => id),
+ },
+ notifiedAt: null,
+ },
+ data: {
+ notifiedAt: new Date(),
+ },
+ });
+
return logAndRespond(
- `Emails sent for comments from partner ${partner.id} on lead ${leadId}.`,
+ usersToNotify.length > 0
+ ? `Emails sent for comments from partner ${partner.id} on lead ${leadId}.`
+ : `No workspace emails to notify for lead ${leadId}. Marked the comments as handled.`,
);
} catch (error) {
await log({
diff --git a/apps/web/lib/submitted-leads/create-partner-submitted-lead-comment-action.ts b/apps/web/lib/submitted-leads/create-partner-submitted-lead-comment-action.ts
index 7c7a777a4f..2aa08f5c35 100644
--- a/apps/web/lib/submitted-leads/create-partner-submitted-lead-comment-action.ts
+++ b/apps/web/lib/submitted-leads/create-partner-submitted-lead-comment-action.ts
@@ -58,7 +58,7 @@ export const createPartnerSubmittedLeadCommentAction = authPartnerActionClient
enqueueSubmittedLeadCommentNotification({
recipient: "program",
leadId: lead.id,
- commentId: comment.id,
+ comment,
}),
);
diff --git a/apps/web/lib/submitted-leads/create-submitted-lead-comment-action.ts b/apps/web/lib/submitted-leads/create-submitted-lead-comment-action.ts
index e5af464c4d..b2c927943a 100644
--- a/apps/web/lib/submitted-leads/create-submitted-lead-comment-action.ts
+++ b/apps/web/lib/submitted-leads/create-submitted-lead-comment-action.ts
@@ -48,7 +48,7 @@ export const createSubmittedLeadCommentAction = authActionClient
enqueueSubmittedLeadCommentNotification({
recipient: "partner",
leadId: lead.id,
- commentId: comment.id,
+ comment,
}),
);
}
diff --git a/apps/web/lib/submitted-leads/submitted-lead-comment-notifications.ts b/apps/web/lib/submitted-leads/submitted-lead-comment-notifications.ts
index 4a1d37aa06..fd24e5cac4 100644
--- a/apps/web/lib/submitted-leads/submitted-lead-comment-notifications.ts
+++ b/apps/web/lib/submitted-leads/submitted-lead-comment-notifications.ts
@@ -7,43 +7,44 @@ const NOTIFICATION_DELAY_SECONDS = 60 * 3;
export async function enqueueSubmittedLeadCommentNotification({
recipient,
leadId,
- commentId,
+ comment,
}: {
recipient: "partner" | "program";
leadId: string;
- commentId: string;
+ comment: { id: string; createdAt: Date };
}) {
return qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/submitted-leads/comments/notify-${recipient}`,
body: {
leadId,
- lastCommentId: commentId,
+ lastCommentId: comment.id,
+ lastCommentCreatedAt: comment.createdAt.toISOString(),
},
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<
+// Get the unsent comments for the job's email, oldest first. Returns null when
+// an unsent comment is newer than the job's comment, because the job for that
+// comment sends the email. A deleted comment has no row, so it does not block.
+export function getSubmittedLeadCommentsToNotify<
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);
+>({
+ unsentComments,
+ lastCommentCreatedAt,
+}: {
+ unsentComments: T[];
+ lastCommentCreatedAt: Date;
+}) {
+ if (
+ unsentComments.some(
+ ({ createdAt }) => createdAt.getTime() > lastCommentCreatedAt.getTime(),
+ )
+ ) {
+ return null;
}
- return batch.reverse();
+ return [...unsentComments].sort(
+ (a, b) => a.createdAt.getTime() - b.createdAt.getTime(),
+ );
}
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.ts
deleted file mode 100644
index 7cbd26330f..0000000000
--- a/apps/web/tests/misc/submitted-lead-comment-notification-batch.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-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"]);
- });
-});
diff --git a/apps/web/tests/misc/submitted-lead-comments-to-notify.test.ts b/apps/web/tests/misc/submitted-lead-comments-to-notify.test.ts
new file mode 100644
index 0000000000..8c9d4914bc
--- /dev/null
+++ b/apps/web/tests/misc/submitted-lead-comments-to-notify.test.ts
@@ -0,0 +1,33 @@
+import { getSubmittedLeadCommentsToNotify } from "@/lib/submitted-leads/submitted-lead-comment-notifications";
+import { describe, expect, it } from "vitest";
+
+const atMinute = (minute: number) => new Date(Date.UTC(2026, 9, 2, 12, minute));
+const comment = (minute: number) => ({
+ id: `${minute}m`,
+ createdAt: atMinute(minute),
+});
+
+const idsToNotify = (unsentMinutes: number[], lastCommentMinute: number) =>
+ getSubmittedLeadCommentsToNotify({
+ unsentComments: unsentMinutes.map(comment),
+ lastCommentCreatedAt: atMinute(lastCommentMinute),
+ })?.map(({ id }) => id) ?? null;
+
+describe("getSubmittedLeadCommentsToNotify", () => {
+ it("returns all unsent comments, oldest first, for the newest comment's job", () => {
+ expect(idsToNotify([2, 0], 2)).toEqual(["0m", "2m"]);
+ });
+
+ it("skips when an unsent comment is newer than the job's comment", () => {
+ expect(idsToNotify([2, 0], 0)).toBeNull();
+ });
+
+ it("sends the earlier comment when the newer comment was deleted", () => {
+ // A at minute 0, B at minute 2, B deleted before its job runs
+ expect(idsToNotify([0], 2)).toEqual(["0m"]);
+ });
+
+ it("returns no comments when every comment was already sent", () => {
+ expect(idsToNotify([], 2)).toEqual([]);
+ });
+});