The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add tests for submitted lead comment access and notification routes
Rafi568cce82223c
diff --git a/apps/web/tests/misc/submitted-lead-comment-access.test.ts b/apps/web/tests/misc/submitted-lead-comment-access.test.tsnew file mode 100644index 0000000000..eae4915d8e--- /dev/null+++ b/apps/web/tests/misc/submitted-lead-comment-access.test.ts@@ -0,0 +1,139 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { GET as partnerComments } from "../../app/(ee)/api/partner-profile/programs/[programId]/submitted-leads/[leadId]/comments/route";+import { GET as workspaceComments } from "../../app/(ee)/api/programs/[programId]/submitted-leads/[leadId]/comments/route";++const mocks = vi.hoisted(() => ({+ findLead: vi.fn(),+ findComments: vi.fn(),+ enrollment: vi.fn(),+}));++// Test the route's access rules. The middleware supplies authentication.+vi.mock("@/lib/auth", () => ({ withWorkspace: (handler: unknown) => handler }));+vi.mock("@/lib/auth/partner", () => ({+ withPartnerProfile: (handler: unknown) => handler,+}));+vi.mock("@/lib/prisma", () => ({+ prisma: {+ submittedLead: { findUnique: mocks.findLead },+ submittedLeadComment: { findMany: mocks.findComments },+ },+}));+vi.mock("@/lib/api/programs/get-program-enrollment-or-throw", () => ({+ getProgramEnrollmentOrThrow: mocks.enrollment,+}));+vi.mock("@/lib/api/errors", () => ({+ DubApiError: class extends Error {+ code: string;+ constructor({ code, message }: { code: string; message: string }) {+ super(message);+ this.code = code;+ }+ },+}));++const context = {+ partner: { id: "pn_1" },+ workspace: { defaultProgramId: "prog_1" },+ params: { programId: "program-slug", leadId: "lead_1" },+};+// The middleware mocks expose the wrapped callback for these tests.+const readPartnerComments = partnerComments as unknown as (+ ctx: typeof context,+) => Promise<Response>;+const readWorkspaceComments = workspaceComments as unknown as (+ ctx: typeof context,+) => Promise<Response>;++const comment = (id: string, partnerVisible: boolean) => ({+ id,+ leadId: "lead_1",+ userId: "user_1",+ partnerId: null,+ text: id,+ partnerVisible,+ createdAt: new Date(),+ updatedAt: new Date(),+ user: { id: "user_1", name: "Author", image: null },+});++describe("submitted lead comment access", () => {+ beforeEach(() => {+ vi.resetAllMocks();+ mocks.enrollment.mockResolvedValue({ programId: "prog_1" });+ mocks.findLead.mockImplementation(+ async ({+ where,+ }: {+ where: { partnerId?: string; programId?: string };+ }) => {+ if (where.partnerId && where.partnerId !== "pn_1") return null;+ if (where.programId && where.programId !== "prog_1") return null;+ return { id: "lead_1", programId: "prog_1" };+ },+ );+ mocks.findComments.mockImplementation(+ async ({ where }: { where: { partnerVisible?: boolean } }) =>+ [comment("private", false), comment("visible", true)].filter(+ (comment) =>+ where.partnerVisible === undefined ||+ comment.partnerVisible === where.partnerVisible,+ ),+ );+ });++ it("excludes private workspace comments from the partner response", async () => {+ const response = await readPartnerComments(context);++ expect((await response.json()).map(({ id }: { id: string }) => id)).toEqual(+ ["visible"],+ );+ expect(mocks.findLead).toHaveBeenCalledWith({+ where: { id: "lead_1", programId: "prog_1", partnerId: "pn_1" },+ select: { id: true },+ });+ });++ it("rejects a lead owned by another partner before loading comments", async () => {+ await expect(+ readPartnerComments({ ...context, partner: { id: "pn_other" } }),+ ).rejects.toMatchObject({ code: "not_found" });+ expect(mocks.findComments).not.toHaveBeenCalled();+ });++ it("rejects a lead in another program before loading comments", async () => {+ mocks.enrollment.mockResolvedValue({ programId: "prog_other" });++ await expect(readPartnerComments(context)).rejects.toMatchObject({+ code: "not_found",+ });+ expect(mocks.findComments).not.toHaveBeenCalled();+ });++ it("rejects a partner without an enrollment before loading the lead", async () => {+ mocks.enrollment.mockRejectedValue(new Error("Not enrolled"));++ await expect(readPartnerComments(context)).rejects.toThrow("Not enrolled");+ expect(mocks.findLead).not.toHaveBeenCalled();+ expect(mocks.findComments).not.toHaveBeenCalled();+ });++ it("returns private and visible comments to the owning workspace", async () => {+ const response = await readWorkspaceComments(context);++ expect((await response.json()).map(({ id }: { id: string }) => id)).toEqual(+ ["private", "visible"],+ );+ });++ it("rejects another workspace even when the URL names the lead's program", async () => {+ await expect(+ readWorkspaceComments({+ ...context,+ workspace: { defaultProgramId: "prog_other" },+ params: { ...context.params, programId: "prog_1" },+ }),+ ).rejects.toMatchObject({ code: "forbidden" });+ expect(mocks.findComments).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/tests/misc/submitted-lead-comment-notification-routes.test.ts b/apps/web/tests/misc/submitted-lead-comment-notification-routes.test.tsnew file mode 100644index 0000000000..b21aca74ce--- /dev/null+++ b/apps/web/tests/misc/submitted-lead-comment-notification-routes.test.ts@@ -0,0 +1,196 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { POST as notifyPartner } from "../../app/(ee)/api/cron/submitted-leads/comments/notify-partner/route";+import { POST as notifyProgram } from "../../app/(ee)/api/cron/submitted-leads/comments/notify-program/route";++const mocks = vi.hoisted(() => ({+ findLead: vi.fn(),+ updateComments: vi.fn(),+ sendEmail: vi.fn(),+ verifySignature: vi.fn(),+ template: vi.fn(),+}));++vi.mock("@/lib/prisma", () => ({+ prisma: {+ submittedLead: { findUniqueOrThrow: mocks.findLead },+ submittedLeadComment: { updateMany: mocks.updateComments },+ },+}));+vi.mock("@/lib/cron", () => ({ qstash: {} }));+vi.mock("@/lib/cron/verify-qstash", () => ({+ verifyQstashSignature: mocks.verifySignature,+}));+vi.mock("@/lib/api/errors", () => ({+ handleAndReturnErrorResponse: () => new Response("Failed", { status: 500 }),+}));+vi.mock("@/ui/submitted-leads/submitted-lead-utils", () => ({+ getCompanyLogoUrl: () => null,+}));+vi.mock("@dub/email", () => ({ sendBatchEmail: mocks.sendEmail }));+vi.mock(+ "@dub/email/templates/new-submitted-lead-comments-from-program",+ () => ({+ default: mocks.template,+ }),+);+vi.mock(+ "@dub/email/templates/new-submitted-lead-comments-from-partner",+ () => ({+ default: mocks.template,+ }),+);+vi.mock("@dub/utils", () => ({+ log: vi.fn(),+ APP_DOMAIN_WITH_NGROK: "https://app.dub.co",+}));+vi.mock("../../app/(ee)/api/cron/utils", () => ({+ logAndRespond: (message: string) => new Response(message),+}));++const atMinute = (minute: number) => new Date(Date.UTC(2026, 9, 2, 12, minute));+const comment = (id: string, minute: number) => ({+ id,+ text: id,+ createdAt: atMinute(minute),+ user: { name: "Author", image: null },+});++function lead(comments = [comment("A", 0)]) {+ return {+ id: "lead_1",+ name: "Lead",+ email: "[email protected]",+ partnerId: "pn_1",+ comments,+ partner: {+ id: "pn_1",+ name: "Partner",+ image: null,+ users: [{ user: { email: "[email protected]" } }],+ },+ program: {+ name: "Program",+ slug: "program",+ logo: null,+ supportEmail: null,+ workspace: {+ slug: "workspace",+ users: [{ user: { email: "[email protected]", isMachine: false } }],+ },+ },+ };+}++function request(lastCommentId = "A", minute = 0) {+ return new Request("https://app.dub.co/api/cron/comments", {+ method: "POST",+ body: JSON.stringify({+ leadId: "lead_1",+ lastCommentId,+ lastCommentCreatedAt: atMinute(minute).toISOString(),+ }),+ });+}++describe.each([+ { recipient: "partner", post: notifyPartner, email: "[email protected]" },+ { recipient: "program", post: notifyProgram, email: "[email protected]" },+])(+ "submitted lead notifications to $recipient",+ ({ recipient, post, email }) => {+ beforeEach(() => {+ vi.resetAllMocks();+ mocks.findLead.mockResolvedValue(lead());+ mocks.sendEmail.mockResolvedValue({ error: null });+ mocks.updateComments.mockResolvedValue({ count: 1 });+ });++ it("sends older unsent comments after the newest comment is deleted", async () => {+ const response = await post(request("deleted_B", 2));++ expect(response.status).toBe(200);+ expect(mocks.sendEmail).toHaveBeenCalledWith(+ [expect.objectContaining({ to: email })],+ { idempotencyKey: `submitted-lead-comments-${recipient}/deleted_B` },+ );+ expect(mocks.updateComments).toHaveBeenCalledWith({+ where: { id: { in: ["A"] }, notifiedAt: null },+ data: { notifiedAt: expect.any(Date) },+ });+ expect(mocks.sendEmail.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.updateComments.mock.invocationCallOrder[0],+ );+ });++ it("leaves comments unsent when the email provider returns an error", async () => {+ mocks.sendEmail.mockResolvedValue({ error: { message: "Unavailable" } });++ expect((await post(request())).status).toBe(500);+ expect(mocks.updateComments).not.toHaveBeenCalled();+ });++ it("leaves comments unsent when the email request throws", async () => {+ mocks.sendEmail.mockRejectedValue(new Error("Connection lost"));++ expect((await post(request())).status).toBe(500);+ expect(mocks.updateComments).not.toHaveBeenCalled();+ });++ it("waits for the newer comment's job without marking comments as sent", async () => {+ mocks.findLead.mockResolvedValue(+ lead([comment("B", 2), comment("A", 0)]),+ );++ expect((await post(request())).status).toBe(200);+ expect(mocks.sendEmail).not.toHaveBeenCalled();+ expect(mocks.updateComments).not.toHaveBeenCalled();+ });++ it("does not send again when no unsent comments remain", async () => {+ mocks.findLead.mockResolvedValue(lead([]));++ expect((await post(request())).status).toBe(200);+ expect(mocks.sendEmail).not.toHaveBeenCalled();+ expect(mocks.updateComments).not.toHaveBeenCalled();+ });++ it("sends the full batch in time order, including more than 50 comments", async () => {+ const comments = Array.from({ length: 51 }, (_, i) =>+ comment(`comment_${i}`, i),+ );+ mocks.findLead.mockResolvedValue(lead([...comments].reverse()));++ expect((await post(request("comment_50", 50))).status).toBe(200);+ expect(mocks.template).toHaveBeenCalledWith(+ expect.objectContaining({+ comments: comments.map(({ text, createdAt, user }) => ({+ text,+ createdAt,+ user,+ })),+ }),+ );+ expect(mocks.updateComments).toHaveBeenCalledWith({+ where: { id: { in: comments.map(({ id }) => id) }, notifiedAt: null },+ data: { notifiedAt: expect.any(Date) },+ });+ const query = mocks.findLead.mock.calls[0][0];+ expect(query.include.comments).not.toHaveProperty("take");+ expect(query.include.comments.where).toEqual({+ partnerId: recipient === "partner" ? null : { not: null },+ ...(recipient === "partner" && { partnerVisible: true }),+ notifiedAt: null,+ createdAt: { gt: expect.any(Date) },+ });+ });++ it("rejects an invalid signature before reading or sending comments", async () => {+ mocks.verifySignature.mockRejectedValue(new Error("Invalid signature"));++ expect((await post(request())).status).toBe(500);+ expect(mocks.findLead).not.toHaveBeenCalled();+ expect(mocks.sendEmail).not.toHaveBeenCalled();+ expect(mocks.updateComments).not.toHaveBeenCalled();+ });+ },+);