import { test, expect, type Page } from "@playwright/test"; import { signInAs, resetDb, BASE } from "./dev"; /** * Phase E acceptance — E1 outbox → E2 dispatcher → E3 email → E4 respond. * * The BUILD-SPEC acceptance test: publish a week → exactly one email per * assignment arrives → running the cron again sends nothing → a confirm link * works, is single-use, and a GET on it never mutates. * * The seed's Audio seat is already confirmed, so the test auto-fills the two * open seats first; those are `proposed` and give us a confirmable assignment. */ interface NotificationRow { id: string; channel: string; templateKey: string; status: string; attempts: number; scheduledFor: string; assignmentStatus: string | null; payload: { subject?: string; html?: string; confirmUrl?: string; declineUrl?: string; }; } async function draftInstanceId(page: Page): Promise { const res = await page.request.get(`${BASE}/api/dev/schedule/instances`); expect(res.ok(), "instances route should succeed").toBe(true); const body = (await res.json()) as { instances: { id: string; status: string }[]; }; const draft = body.instances.find((i) => i.status === "draft"); expect(draft, "the seed should include a draft instance").toBeTruthy(); return draft!.id; } async function notifications(page: Page): Promise { const res = await page.request.get(`${BASE}/api/dev/notifications`); expect(res.ok(), "notification log should be readable by a coordinator").toBe( true, ); const body = (await res.json()) as { notifications: NotificationRow[] }; return body.notifications; } let instanceId: string; test.beforeAll(async ({ browser }) => { const context = await browser.newContext(); const page = await context.newPage(); await resetDb(page); instanceId = await draftInstanceId(page); await context.close(); }); test.describe("notifications", () => { test("publish enqueues one email per assignment, cron sends once, the confirm link works once", async ({ page, }) => { const errors: string[] = []; page.on("console", (msg) => { if (msg.type() === "error") errors.push(msg.text()); }); page.on("pageerror", (err) => errors.push(`page error: ${err.message}`)); await page.setViewportSize({ width: 1024, height: 768 }); await signInAs(page, "coordinator@glenloch.local"); // Fill the two open seats (proposed assignments) so the week has a // confirmable volunteer, then publish it. const filled = await ( await page.request.post( `${BASE}/api/dev/schedule/${instanceId}/auto-fill`, { data: JSON.stringify({}) }, ) ).json() as { written: number }; expect(filled.written, "auto-fill should seat the open positions").toBe(2); const published = await page.request.post( `${BASE}/api/dev/schedule/${instanceId}/publish`, { data: JSON.stringify({ allowGaps: true }) }, ); expect(published.ok(), "publish should succeed").toBe(true); // E1: one queued email per active assignment, rendered at enqueue time. // E7 additionally enqueues the future rule-based reminders (t_7 + friday), // which are scheduled ahead and must not send on this tick. const allRows = await notifications(page); const queued = allRows.filter( (row) => row.templateKey === "assignment.published", ); expect(queued, "publish enqueues one email per assignment").toHaveLength(3); const reminders = allRows.filter((row) => row.templateKey.startsWith("reminder."), ); expect(reminders, "reminders are scheduled ahead, two per assignment").toHaveLength(6); expect( reminders.every( (row) => row.status === "queued" && new Date(row.scheduledFor) > new Date(), ), "reminders are queued for the future, not sent now", ).toBe(true); for (const row of queued) { expect(row.channel).toBe("email"); expect(row.templateKey).toBe("assignment.published"); expect(row.status).toBe("queued"); // Each mail names its own role/date, with a call time and a confirm link. expect(row.payload.subject).toMatch(/^You're on .+ — Sunday, Nov 29$/); expect(row.payload.html).toMatch(/Call time: \d{1,2}:\d{2} (AM|PM)/); expect(row.payload.confirmUrl).toContain("/respond?t="); } // Pick the proposed (auto-filled) assignment — the one we can confirm. const target = queued.find((row) => row.assignmentStatus === "proposed"); expect(target, "an auto-filled proposal should be queued").toBeTruthy(); const roleName = /You're on (.+?) —/.exec(target!.payload.subject ?? "")![1]; // E2/E3: the first cron tick sends all three; the second sends nothing. const firstTick = await ( await page.request.get(`${BASE}/api/dev/cron/notifications`) ).json() as { sent: number; failed: number }; expect(firstTick.sent, "the first tick sends every queued email").toBe(3); expect(firstTick.failed).toBe(0); const secondTick = await ( await page.request.get(`${BASE}/api/dev/cron/notifications`) ).json() as { sent: number }; expect(secondTick.sent, "running the cron again sends nothing").toBe(0); const sentRows = await notifications(page); expect(sentRows.find((r) => r.id === target!.id)!.status).toBe("sent"); expect( sentRows .filter((r) => r.templateKey.startsWith("reminder.")) .every((r) => r.status === "queued"), "future reminders are untouched by the tick", ).toBe(true); // E4: GET renders the page and never mutates. const token = new URL(target!.payload.confirmUrl!).searchParams.get("t")!; await page.goto(target!.payload.confirmUrl!); await expect(page.getByRole("heading")).toContainText(roleName); const stillProposed = await notifications(page); expect( stillProposed.find((r) => r.id === target!.id)!.assignmentStatus, "GET /respond must not change state", ).toBe("proposed"); // POST confirms; the same token cannot be used twice. const confirmed = await page.request.post(`${BASE}/api/respond`, { data: JSON.stringify({ token, action: "confirm" }), }); expect(confirmed.ok(), "the confirm POST should succeed").toBe(true); expect((await confirmed.json()) as { status: string }).toMatchObject({ status: "confirmed", }); const reuse = await page.request.post(`${BASE}/api/respond`, { data: JSON.stringify({ token, action: "confirm" }), }); expect(reuse.status(), "a second POST with the same token is rejected").toBe( 409, ); const finalRows = await notifications(page); expect( finalRows.find((r) => r.id === target!.id)!.assignmentStatus, "the assignment is confirmed in the DB", ).toBe("confirmed"); expect(errors, `unexpected console/page errors: ${errors.join("; ")}`).toEqual( [], ); }); test("volunteer cannot read the admin notification log", async ({ page }) => { await page.setViewportSize({ width: 1024, height: 768 }); await signInAs(page, "avery@glenloch.local"); const res = await page.request.get(`${BASE}/api/dev/notifications`); expect(res.status()).toBe(403); }); });