push to maple-street

This commit is contained in:
Tiel Coder
2026-11-20 04:07:02 +00:00
parent 2cec220a24
commit 5adf1cef1f
345 changed files with 86105 additions and 1079 deletions
+309
View File
@@ -0,0 +1,309 @@
import { test, expect, type Page } from "@playwright/test";
import { signInAs, resetDb, BASE } from "./dev";
/**
* Admin surface: people lifecycle, reminder rules, notification log, and the
* publish controls on the schedule. These are the actions that previously had
* data/API support but no UI.
*/
/** The seed's draft week (its second Sunday). */
async function draftWeek(page: Page): Promise<string> {
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; occursOn: string; status: string }[];
};
const draft = body.instances.find((i) => i.status === "draft");
expect(draft, "the seed should include a draft instance").toBeTruthy();
return draft!.occursOn.slice(0, 10);
}
test.describe("admin", () => {
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await resetDb(page);
await context.close();
});
test("admin adds, edits, approves, and removes a person", async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 1000 });
await signInAs(page, "admin@glenloch.local");
await page.goto(`${BASE}/admin`);
await expect(page.getByRole("heading", { name: "Admin", level: 1 })).toBeVisible();
await expect(page.getByText("People", { exact: true })).toBeVisible();
await expect(page.getByText("Reminder rules", { exact: true })).toBeVisible();
await expect(page.getByText("Notifications", { exact: true })).toBeVisible();
// --- add an account that needs approval
const email = `e2e-admin-${Date.now()}@example.com`;
await page.getByLabel("First name").fill("E2E");
await page.getByLabel("Last name").fill("Volunteer");
await page.getByLabel("Email").fill(email);
await page.getByLabel("Role").selectOption("volunteer");
await page.getByLabel("Needs approval before signing in").check();
await page.getByRole("button", { name: "Add user" }).click();
// The admin gets a sign-in link to hand over.
await expect(page.getByText(/api\/dev\/complete/).first()).toBeVisible();
const row = page.getByRole("row", { name: new RegExp(email) });
await expect(row).toBeVisible();
await expect(row.getByText("pending approval")).toBeVisible();
await row.getByRole("button", { name: "Approve" }).click();
await expect(row.getByText("active", { exact: true })).toBeVisible();
await expect(row.getByRole("button", { name: "Approve" })).toHaveCount(0);
// --- edit every editable field through the row editor
await row.getByRole("button", { name: "Edit" }).click();
const editor = page.getByRole("form", { name: `Edit ${email}` });
await expect(editor).toBeVisible();
await editor.getByLabel("First name").fill("Edited");
await editor.getByLabel("Display name").fill("Edited Volunteer");
await editor.getByLabel("Role").selectOption("coordinator");
await editor.getByLabel("Phone").fill("+15551234567");
await editor.getByLabel("Emergency contact").fill("Sam — +15550000000");
await editor.getByLabel("Notes").fill("E2E edit");
await editor.getByRole("button", { name: "Save changes" }).click();
await expect(page.getByText("Changes saved.")).toBeVisible();
const edited = page.getByRole("row", { name: new RegExp(email) });
await expect(edited.getByText("Edited Volunteer")).toBeVisible();
await expect(edited.getByText("coordinator")).toBeVisible();
await expect(edited.getByText("+15551234567")).toBeVisible();
const list = (await (await page.request.get(`${BASE}/api/dev/users`)).json()) as {
users: {
id: string;
email: string;
firstName: string;
systemRole: string;
phoneE164: string | null;
}[];
};
const saved = list.users.find((user) => user.email === email);
expect(saved?.firstName, "the edit should persist").toBe("Edited");
expect(saved?.systemRole).toBe("coordinator");
expect(saved?.phoneE164).toBe("+15551234567");
// --- skill levels: add (default none), raise, then delete a row
await edited.getByRole("button", { name: "Edit" }).click();
const skillEditor = page.getByRole("form", { name: `Edit ${email}` });
await expect(skillEditor.getByText("No skills recorded yet.")).toBeVisible();
const addSkill = skillEditor.getByLabel("Add skill");
const firstSkill = await addSkill
.locator('option:not([disabled])')
.nth(1)
.getAttribute("value");
await addSkill.selectOption(firstSkill!);
await skillEditor.getByRole("button", { name: "Add skill" }).click();
await expect(page.getByText("Skill added at level none.")).toBeVisible();
const levelSelect = skillEditor.getByLabel(/Skill level for/).first();
await expect(levelSelect, "a new entry starts at none").toHaveValue("none");
await levelSelect.selectOption("qualified");
await expect(page.getByText("Skill level updated.")).toBeVisible();
await expect(skillEditor.getByLabel(/Skill level for/).first()).toHaveValue(
"qualified",
);
// A second entry, then delete the first row outright.
const secondSkill = await addSkill
.locator('option:not([disabled])')
.nth(1)
.getAttribute("value");
await addSkill.selectOption(secondSkill!);
await skillEditor.getByRole("button", { name: "Add skill" }).click();
await expect(skillEditor.getByLabel(/Skill level for/)).toHaveCount(2);
await skillEditor.getByRole("button", { name: "Remove" }).first().click();
await expect(page.getByText("Skill entry removed.")).toBeVisible();
await expect(skillEditor.getByLabel(/Skill level for/)).toHaveCount(1);
await page
.getByRole("row", { name: new RegExp(email) })
.getByRole("button", { name: "Cancel" })
.click();
// --- deactivate, then remove
await edited.getByRole("button", { name: "Deactivate" }).click();
await expect(
page.getByRole("row", { name: new RegExp(email) }).getByText("deactivated"),
).toBeVisible();
page.once("dialog", (dialog) => dialog.accept());
await page
.getByRole("row", { name: new RegExp(email) })
.getByRole("button", { name: "Delete" })
.click();
await expect(page.getByRole("row", { name: new RegExp(email) })).toHaveCount(0);
// Removing the person removes their skill-level entries too.
const remaining = (await (
await page.request.get(`${BASE}/api/dev/user-skills?userId=${saved!.id}`)
).json()) as { rows: unknown[] };
expect(
remaining.rows,
"deleting a user should delete their competency rows",
).toHaveLength(0);
});
test("admin can send a test email and toggle a reminder rule", async ({ page }) => {
await page.setViewportSize({ width: 1024, height: 900 });
await signInAs(page, "admin@glenloch.local");
await page.goto(`${BASE}/admin`);
await page.getByRole("button", { name: "Send test email" }).click();
await expect(page.getByText(/Test message sent via/)).toBeVisible();
const disable = page.getByRole("button", { name: "Disable" }).first();
await expect(disable).toBeVisible();
await disable.click();
await expect(page.getByRole("button", { name: "Enable" }).first()).toBeVisible();
});
test("admin can publish a draft week from the schedule", async ({ page }) => {
await page.setViewportSize({ width: 1024, height: 900 });
await signInAs(page, "admin@glenloch.local");
const week = await draftWeek(page);
await page.goto(`${BASE}/schedule?week=${week}`);
await page.getByRole("button", { name: "Publish", exact: true }).first().click();
// Open seats are a deliberate override, not a silent publish.
const publishAnyway = page.getByRole("button", { name: "Publish anyway" }).first();
await expect(publishAnyway).toBeVisible();
await publishAnyway.click();
await expect(page.getByText(/Published\. Assignment emails/)).toBeVisible();
await expect(page.getByRole("button", { name: "Unpublish" }).first()).toBeVisible();
});
test("admin verifies a skill level and edits position requirements", async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 1000 });
await signInAs(page, "admin@glenloch.local");
await page.goto(`${BASE}/admin`);
const matrixRes = await page.request.get(`${BASE}/api/dev/skills/matrix`);
expect(matrixRes.ok(), "matrix route should require and accept the admin").toBe(true);
const matrix = (await matrixRes.json()) as {
rows: {
userId: string;
userName: string;
skillId: string;
skillName: string;
verifiedLevel: string;
}[];
};
const target = matrix.rows.find((row) => row.verifiedLevel !== "expert");
expect(target, "the seed should include a promotable competency").toBeTruthy();
const levels = ["none", "observer", "assisted", "qualified", "expert"];
const newLevel = levels[levels.indexOf(target!.verifiedLevel) + 1];
const targetRow = page
.getByRole("row", { name: new RegExp(target!.skillName) })
.filter({ hasText: target!.userName })
.first();
await targetRow.getByRole("button", { name: "Verify" }).click();
const form = page.getByRole("form", {
name: `Verify ${target!.skillName} for ${target!.userName}`,
});
await expect(form).toBeVisible();
await form.getByLabel("Level").selectOption(newLevel);
await form.getByLabel("Notes (optional)").fill("E2E verification");
await form.getByRole("button", { name: "Save assessment" }).click();
await expect(
page.getByText(`${target!.skillName}: ${target!.userName} is now ${newLevel}`),
).toBeVisible();
const afterRes = await page.request.get(
`${BASE}/api/dev/skills/matrix?userId=${target!.userId}&skillId=${target!.skillId}`,
);
const after = (await afterRes.json()) as { rows: { verifiedLevel: string }[] };
expect(after.rows[0]?.verifiedLevel, "the level should persist").toBe(newLevel);
// Requirements editor: the B4 gate refuses a publishable position with no
// core skill, and the same set saves when it is not publishable.
const positionRow = page.getByRole("row", { name: /^Audio/ }).first();
await positionRow.getByRole("button", { name: "Edit requirements" }).click();
const editor = page.getByRole("form", { name: "Requirements for Audio" });
await expect(editor).toBeVisible();
await editor.getByLabel("Core").first().uncheck();
await editor.getByRole("button", { name: "Save requirements" }).click();
await expect(editor.getByRole("alert")).toContainText("at least one core skill");
await editor.getByLabel(/Publishable/).uncheck();
await editor.getByLabel("Core").first().check();
await editor.getByRole("button", { name: "Save requirements" }).click();
await expect(page.getByText("Requirements saved for Audio.")).toBeVisible();
});
test("admin connects Gmail with an app password and disconnects it", async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 1000 });
await signInAs(page, "admin@glenloch.local");
await page.goto(`${BASE}/admin`);
await expect(page.getByText("Email delivery", { exact: true })).toBeVisible();
await expect(page.getByText(/Not connected/)).toBeVisible();
await page.getByLabel("Gmail address").fill("media.team.test@gmail.com");
await page.getByLabel("App password").fill("abcd efgh ijkl mnop");
await page.getByRole("button", { name: "Save Gmail" }).click();
await expect(
page.getByText(/Connected as media\.team\.test@gmail\.com/),
).toBeVisible();
// The app password is write-only: the API reports that it exists and never
// returns the secret itself.
const saved = (await (
await page.request.get(`${BASE}/api/dev/settings`)
).json()) as { settings: Record<string, unknown> };
expect(saved.settings.smtpConfigured).toBe(true);
expect(saved.settings.smtpUser).toBe("media.team.test@gmail.com");
expect(JSON.stringify(saved)).not.toContain("abcdefghijklmnop");
// Persisted in the database, not just in component state.
await page.reload();
await expect(
page.getByText(/Connected as media\.team\.test@gmail\.com/),
).toBeVisible();
page.once("dialog", (dialog) => dialog.accept());
await page.getByRole("button", { name: "Remove Gmail" }).click();
await expect(page.getByText(/Not connected/)).toBeVisible();
const cleared = (await (
await page.request.get(`${BASE}/api/dev/settings`)
).json()) as { settings: { smtpConfigured: boolean; smtpUser: string } };
expect(cleared.settings.smtpConfigured).toBe(false);
expect(cleared.settings.smtpUser).toBe("");
});
// Never leave fake Gmail credentials behind: the notification tests send
// through the fallback transport and must not try to authenticate as Gmail.
test.afterAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await signInAs(page, "admin@glenloch.local");
const current = (await (
await page.request.get(`${BASE}/api/dev/settings`)
).json()) as { settings: { emailFrom: string; notificationEmail: string } };
await page.request.put(`${BASE}/api/dev/settings`, {
data: {
emailFrom: current.settings.emailFrom,
notificationEmail: current.settings.notificationEmail,
smtpUser: "",
},
});
await context.close();
});
});
+60
View File
@@ -0,0 +1,60 @@
import { test, expect } from "@playwright/test";
import { signInAs, resetDb, BASE } from "./dev";
/**
* Announcements: an admin posts a published update; a volunteer sees it but no
* authoring controls; unpublishing hides it from the volunteer feed.
*/
const title = `E2E announcement ${Date.now()}`;
test.describe("announcements", () => {
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await resetDb(page);
await context.close();
});
test("an admin creates and publishes an announcement", async ({ page }) => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "admin@glenloch.local");
await page.goto(`${BASE}/announcements`);
await page.getByLabel("Title").fill(title);
await page
.getByLabel("Message")
.fill("Doors open 30 minutes early this Sunday.");
await page.getByRole("button", { name: "Create announcement" }).click();
await expect(page.getByRole("heading", { name: title })).toBeVisible();
await expect(page.getByText("Published")).toBeVisible();
});
test("a volunteer sees the post but no authoring controls", async ({
page,
}) => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "avery@glenloch.local");
await page.goto(`${BASE}/announcements`);
await expect(page.getByRole("heading", { name: title })).toBeVisible();
await expect(
page.getByRole("button", { name: "Create announcement" }),
).toHaveCount(0);
await expect(page.getByRole("button", { name: "Unpublish" })).toHaveCount(0);
});
test("unpublishing hides the post from volunteers", async ({ page }) => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "admin@glenloch.local");
await page.goto(`${BASE}/announcements`);
await page.getByRole("button", { name: "Unpublish" }).first().click();
await expect(page.getByText("Draft")).toBeVisible();
await signInAs(page, "avery@glenloch.local");
await page.goto(`${BASE}/announcements`);
await expect(page.getByRole("heading", { name: title })).toHaveCount(0);
});
});
+38 -22
View File
@@ -49,48 +49,61 @@ test.describe("assign mutations", () => {
await page.goto(`${BASE}/schedule`);
await expect(page).toHaveURL(`${BASE}/schedule`);
// The interactive editor mounts for coordinators: each open cell has an
// assign <select>. Take the first instance row (Audio pre-assigned;
// The interactive editor mounts for coordinators: each open cell opens the
// ranked picker. Take the first instance row (Audio pre-assigned;
// Livestream + Slides open).
const row = page.locator("tbody tr").first();
await expect(row.locator("select").first()).toBeVisible();
await expect(row.getByRole("button", { name: /Choose volunteer/ }).first()).toBeVisible();
const audio = await cellForRole(page, row, "Audio");
const livestream = await cellForRole(page, row, "Livestream");
const slides = await cellForRole(page, row, "Slides");
// Clear the pre-assigned Audio seat so every seat in the row is open and a
// free volunteer (Avery) can be assigned twice — the second trips rule 1.
// free volunteer can be assigned twice — the second trips rule 1.
await audio.locator("button", { hasText: "Clear" }).click();
// Optimistic revert: the cell is open again and shows the assign picker.
await expect(audio.locator("select")).toBeVisible();
// Optimistic revert: the cell is open again and shows the ranked picker.
await expect(
audio.getByRole("button", { name: /Choose volunteer/ }),
).toBeVisible();
// Assign Avery Kim to Livestream — the cell updates at once (optimistic):
// the picker is replaced by the name + a Clear control, no full reload.
await livestream.locator("select").selectOption({ label: "Avery Kim" });
// Assign Sam Okafor to Livestream. Sam is verified qualified on both the
// Livestream and Slides skills.
await livestream
.getByRole("button", { name: /Choose volunteer/ })
.click();
const livestreamDialog = page.getByRole("dialog");
await expect(livestreamDialog).toBeVisible();
await livestreamDialog
.locator("li")
.filter({ hasText: "Sam Okafor" })
.getByRole("button", { name: "Assign" })
.click();
await expect(
livestream.locator("button", { hasText: "Clear" }),
).toBeVisible();
await expect(
livestream.locator("span", { hasText: "Avery Kim" }),
livestream.locator("span", { hasText: "Sam Okafor" }),
).toBeVisible();
// Force a rule-1 duplicate: Avery already has Livestream, so assigning
// Avery to Slides must roll back — the cell keeps its picker (stays open)
// and an error toast shows the server's message.
await slides.locator("select").selectOption({ label: "Avery Kim" });
await expect(slides.locator("select")).toBeVisible();
const toast = page
.getByRole("status")
.filter({ hasText: "Already assigned in this instance" });
await expect(toast).toBeVisible();
// The picker refuses the rule-1 duplicate in the UI: Sam is already serving
// in this instance, so the excluded list explains why there is no Assign.
await slides.getByRole("button", { name: /Choose volunteer/ }).click();
const slidesDialog = page.getByRole("dialog");
await slidesDialog
.getByRole("button", { name: /unavailable \/ not eligible/i })
.click();
const samRow = slidesDialog.locator("li").filter({ hasText: "Sam Okafor" });
await expect(samRow).toContainText("Already serving in this service");
await expect(samRow.getByRole("button", { name: "Assign" })).toHaveCount(0);
await page.getByRole("button", { name: "Close ranked picker" }).click();
// The successful optimistic assign is still live.
await expect(
livestream.locator("button", { hasText: "Clear" }),
).toBeVisible();
await expect(
livestream.locator("span", { hasText: "Avery Kim" }),
livestream.locator("span", { hasText: "Sam Okafor" }),
).toBeVisible();
// No console or page errors while the mutations run.
@@ -116,8 +129,11 @@ test.describe("assign mutations", () => {
await page.goto(`${BASE}/schedule`);
await expect(page).toHaveURL(`${BASE}/schedule`);
// Read-only grid: no per-cell assign <select> mounts for a volunteer.
const assignControls = await page.locator("tbody tr").locator("select").count();
// Read-only grid: no per-cell picker trigger mounts for a volunteer.
const assignControls = await page
.locator("tbody tr")
.getByRole("button", { name: /Choose volunteer/ })
.count();
expect(assignControls, "volunteer grid should expose no assign control").toBe(0);
// The route still enforces the chokepoint directly.
+96
View File
@@ -0,0 +1,96 @@
import { test, expect } from "@playwright/test";
import { signInAs, resetDb, firstInstanceId, BASE } from "./dev";
/**
* Auto-fill — unit D9.
*
* The route computes proposals (GET) and applies them (POST). The two
* properties pinned here:
* - proposals are deterministic for a fixed seed (GET twice, same result),
* - apply is idempotent (POST twice: the second writes 0 rows).
*
* The DB is reset to the clean seed (which now includes the skill taxonomy and
* volunteer verified levels) before the suite, so the proposals are stable.
*/
/**
* The first instance id, resolved once while the admin session (which holds
* `schedule.publish`) is live. The instances helper route is coordinator-gated,
* so a volunteer session cannot read it — fetching it up front keeps the
* volunteer test focused on the 403 it actually pins.
*/
let instanceId: string;
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await resetDb(page);
instanceId = await firstInstanceId(page);
await context.close();
});
test.describe("auto-fill", () => {
test("proposals are deterministic and apply is a no-op on the second run", 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");
expect(instanceId, "a first instance should exist").toBeTruthy();
const url = `${BASE}/api/dev/schedule/${instanceId}/auto-fill`;
// GET twice — deterministic for a fixed seed.
const first = await (await page.request.get(url)).json();
const second = await (await page.request.get(url)).json();
expect(first).toEqual(second);
// The seed pre-assigns only each instance's Audio seat, so Livestream and
// Slides are the open seats — the Audio seat must never be re-proposed.
expect(first.proposals.length, "proposals should be non-empty").toBeGreaterThan(0);
expect(
new Set(first.proposals.map((p: { roleName: string }) => p.roleName)),
"an already-filled seat is not an open seat",
).not.toContain("Audio");
// Apply once — writes one assignment per still-free proposal.
const applied = await (
await page.request.post(url, { data: JSON.stringify({}) })
).json() as { written: number; proposals: { slotId: string }[] };
expect(applied.written).toBe(applied.proposals.length);
expect(applied.written).toBeGreaterThan(0);
// Apply again — every seat is now filled, so it is a no-op.
const again = await (
await page.request.post(url, { data: JSON.stringify({}) })
).json() as { written: number };
expect(again.written, "second apply should write 0 rows").toBe(0);
expect(errors, `unexpected console/page errors: ${errors.join("; ")}`).toEqual(
[],
);
});
// Review-focus point: a volunteer cannot auto-fill. The route enforces the
// chokepoint directly — a volunteer POST is rejected 403, not 200 and not a
// 500.
test("volunteer is rejected by the auto-fill route with 403", async ({ page }) => {
await page.setViewportSize({ width: 1024, height: 768 });
await signInAs(page, "avery@glenloch.local");
await page.goto(`${BASE}/schedule`);
await expect(page).toHaveURL(`${BASE}/schedule`);
expect(instanceId).toBeTruthy();
const res = await page.request.post(
`${BASE}/api/dev/schedule/${instanceId}/auto-fill`,
{ data: JSON.stringify({}) },
);
expect(res.status(), "volunteer auto-fill must be rejected").toBe(403);
});
});
+87
View File
@@ -0,0 +1,87 @@
import { test, expect } from "@playwright/test";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { signInAs, resetDb, BASE } from "./dev";
/**
* A backup must restore both sides of the system: the Postgres records and the
* bytes on the uploads volume. This test creates a marker in each, downloads a
* backup, deletes both markers, restores the ZIP, and verifies they are back.
*/
test.describe("backup and restore", () => {
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await resetDb(page);
await context.close();
});
test("admin can download a complete backup and restore it", async ({ page }) => {
await signInAs(page, "admin@glenloch.local");
const email = `e2e-backup-${Date.now()}@example.com`;
const createdRes = await page.request.post(`${BASE}/api/dev/users`, {
data: {
email,
firstName: "Backup",
lastName: "Marker",
systemRole: "volunteer",
status: "active",
},
});
expect(createdRes.status()).toBe(201);
const uploadDir = process.env.UPLOAD_DIR ?? "/tmp/uploads";
const markerName = `e2e-restore-marker-${Date.now()}.txt`;
const markerPath = path.join(uploadDir, markerName);
await mkdir(uploadDir, { recursive: true });
await writeFile(markerPath, "restored from backup\n", "utf8");
const backupRes = await page.request.get(`${BASE}/api/dev/backup`);
expect(backupRes.status()).toBe(200);
expect(backupRes.headers()["content-type"]).toContain("application/zip");
expect(backupRes.headers()["content-disposition"]).toContain(
"glenloch-media-backup-",
);
const backup = await backupRes.body();
expect(backup.length, "the ZIP should contain real data").toBeGreaterThan(
1000,
);
// Remove both markers: the user row through the app, the file from disk.
const created = (await createdRes.json()) as { user: { id: string } };
const deleteRes = await page.request.delete(
`${BASE}/api/dev/users?id=${encodeURIComponent(created.user.id)}`,
);
expect(deleteRes.ok()).toBe(true);
await rm(markerPath, { force: true });
const beforeRestore = (await (
await page.request.get(`${BASE}/api/dev/users`)
).json()) as { users: { email: string }[] };
expect(beforeRestore.users.some((user) => user.email === email)).toBe(false);
const restoreRes = await page.request.post(`${BASE}/api/dev/backup/restore`, {
headers: {
"content-type": "application/zip",
"x-restore-confirm": "RESTORE",
},
data: backup,
});
expect(restoreRes.status(), await restoreRes.text()).toBe(200);
let listRes = await page.request.get(`${BASE}/api/dev/users`);
if (listRes.status() === 401) {
// A backup from another deployment can carry a different admin id.
await signInAs(page, "admin@glenloch.local");
listRes = await page.request.get(`${BASE}/api/dev/users`);
}
expect(listRes.ok()).toBe(true);
const afterRestore = (await listRes.json()) as {
users: { email: string }[];
};
expect(afterRestore.users.some((user) => user.email === email)).toBe(true);
expect(await readFile(markerPath, "utf8")).toBe("restored from backup\n");
});
});
+29
View File
@@ -0,0 +1,29 @@
import { test, expect } from "@playwright/test";
import { signInAs, BASE } from "./dev";
/** Week / month / year lenses over the same schedule. */
test.describe("calendar views", () => {
test("switches between week, month, and year", async ({ page }) => {
await page.setViewportSize({ width: 1024, height: 900 });
await signInAs(page, "admin@glenloch.local");
await page.goto(`${BASE}/schedule`);
await expect(page.getByRole("link", { name: "Week" })).toHaveAttribute(
"aria-current",
"page",
);
await page.getByRole("link", { name: "Month" }).click();
await expect(page).toHaveURL(/view=month/);
await expect(page.getByRole("link", { name: "Month" })).toHaveAttribute(
"aria-current",
"page",
);
await expect(page.getByText(/Every service this month/)).toBeVisible();
await page.getByRole("link", { name: "Year" }).click();
await expect(page).toHaveURL(/view=year/);
await expect(page.getByText(/A year at a glance/)).toBeVisible();
await expect(page.getByTestId("year-calendar").locator("a")).toHaveCount(12);
});
});
+34 -1
View File
@@ -1,6 +1,7 @@
import { expect, type Page } from "@playwright/test";
const BASE = "http://localhost:3000";
const E2E_PASSWORD = "e2e-password-123";
/**
* Shared E2E helpers. Both test files run against the same Postgres, so they
@@ -20,7 +21,19 @@ export async function signInAs(page: Page, email: string) {
const body = (await res.json()) as { url?: string };
expect(body.url, "magic-link should return a sign-in url").toBeTruthy();
await page.goto(body.url!);
await expect(page).toHaveURL(/complete/);
// New accounts are prompted to choose credentials after their first magic
// link. Set the deterministic test password, then continue into the shell.
if (new URL(page.url()).pathname === "/welcome") {
await expect(
page.getByRole("heading", { name: "Set your login" }),
).toBeVisible();
await page.getByLabel("Username").fill(email);
await page.getByLabel("Password", { exact: true }).fill(E2E_PASSWORD);
await page.getByLabel("Confirm password").fill(E2E_PASSWORD);
await page.getByRole("button", { name: "Save and continue" }).click();
}
// The completion route redirects into the shell, which requires a session.
await expect(page).toHaveURL(`${BASE}/schedule`);
}
/**
@@ -36,6 +49,26 @@ export async function resetDb(page: Page) {
return res.status;
});
expect(status, "admin reset should succeed").toBe(200);
// The reset recreates every user with a new id, so the session obtained
// before the reset now points at a deleted row. Re-authenticate so helper
// routes called in the same context see a live account (the guard returns 401
// for stale ids).
await signInAs(page, "admin@glenloch.local");
}
/**
* The first service instance's id, read from the instances helper route. Needs
* a `schedule.publish` session (coordinator or admin).
*/
export async function firstInstanceId(page: Page): Promise<string> {
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 }[] };
expect(
body.instances.length,
"at least one instance should exist",
).toBeGreaterThan(0);
return body.instances[0].id;
}
export { BASE };
+197
View File
@@ -0,0 +1,197 @@
import { test, expect } from "@playwright/test";
import { readFile } from "node:fs/promises";
import { signInAs, resetDb, BASE } from "./dev";
/**
* Event photography (J/K slice): a coordinator creates an event and assigns two
* photographers; the first creates a folder and uploads an edited JPEG plus a
* RAW original; the second — not the uploader — downloads the untouched bytes.
* An unassigned volunteer cannot open the event at all.
*/
// A real 32×24 JPEG, so the editor path sees a normal browser image.
const PHOTO = Buffer.from(
"/9j/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAAYACADASIAAhEBAxEB/8QAFwABAQEBAAAAAAAAAAAAAAAAAAcICf/EABgQAQADAQAAAAAAAAAAAAAAAAAXZaTi/8QAFQEBAQAAAAAAAAAAAAAAAAAACAf/xAAbEQEAAQUBAAAAAAAAAAAAAAAAAQMEFFKh0f/aAAwDAQACEQMRAD8AuYAvrq5kinQtc5eyFrnL2XmDca9j0ccyhtyW6ABDI5mQA6BNf//Z",
"base64",
);
const PHOTO_NAME = "photo.jpg";
const RAW = Buffer.from("II*\u0000fake-cr3-bytes-for-download-verification");
let eventUrl = "";
test.describe("event photo sharing", () => {
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await resetDb(page);
await context.close();
});
test("a coordinator creates an event and assigns two photographers", async ({
page,
}) => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "admin@glenloch.local");
await page.goto(`${BASE}/events`);
await page.getByLabel("Title").fill("E2E photo day");
await page.getByLabel("Location").fill("Main campus");
await page.getByRole("button", { name: "Create event" }).click();
await expect(page).toHaveURL(/\/events\/[^/]+$/);
eventUrl = page.url().replace(/\/$/, "");
await expect(
page.getByRole("heading", { name: "E2E photo day" }),
).toBeVisible();
const teamMember = page.getByLabel("Team member");
await teamMember.selectOption({
label: "Avery Kim (avery@glenloch.local)",
});
await page.getByRole("button", { name: "Assign" }).click();
await expect(page.getByText("Avery Kim").first()).toBeVisible();
await teamMember.selectOption({ label: "Sam Okafor (sam@glenloch.local)" });
await page.getByRole("button", { name: "Assign" }).click();
await expect(page.getByText("Sam Okafor").first()).toBeVisible();
});
test("an assigned photographer creates a folder and uploads files", async ({
page,
}) => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "avery@glenloch.local");
await page.goto(eventUrl);
await page.getByLabel("New folder").fill("Originals");
await page.getByRole("button", { name: "Create folder" }).click();
await page.getByRole("link", { name: /Originals/ }).click();
await page.getByLabel("Choose photos to upload").setInputFiles([
{ name: PHOTO_NAME, mimeType: "image/jpeg", buffer: PHOTO },
{ name: "raw.CR3", mimeType: "application/octet-stream", buffer: RAW },
]);
await page.getByRole("button", { name: "Upload 2" }).click();
await expect(page.getByText("2 uploaded")).toBeVisible({ timeout: 30_000 });
await expect(page.getByText(PHOTO_NAME)).toBeVisible();
await expect(page.getByText("raw.CR3")).toBeVisible();
});
test("another assigned photographer downloads the original bytes", async ({
page,
}) => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "sam@glenloch.local");
await page.goto(eventUrl);
await page.getByRole("link", { name: /Originals/ }).click();
const [download] = await Promise.all([
page.waitForEvent("download"),
page.getByRole("link", { name: "Download" }).first().click(),
]);
const downloadPath = await download.path();
expect(downloadPath).toBeTruthy();
const bytes = await readFile(downloadPath!);
expect(bytes.equals(PHOTO)).toBe(true);
});
test("a photographer downloads every photo as one ZIP", async ({ page }) => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "sam@glenloch.local");
await page.goto(eventUrl);
const [download] = await Promise.all([
page.waitForEvent("download"),
page.getByRole("link", { name: /Download all \(2\)/ }).click(),
]);
expect(download.suggestedFilename()).toBe("E2E photo day photos.zip");
const downloadPath = await download.path();
expect(downloadPath).toBeTruthy();
const zip = await readFile(downloadPath!);
expect(zip.subarray(0, 4).toString("binary")).toBe("PK\x03\x04");
// Store-only entries keep the original bytes and folder paths in the ZIP.
expect(zip.includes(PHOTO)).toBe(true);
expect(zip.includes(RAW)).toBe(true);
expect(zip.includes(Buffer.from(`Originals/${PHOTO_NAME}`))).toBe(true);
expect(zip.includes(Buffer.from("Originals/raw.CR3"))).toBe(true);
});
test("a photographer views a photo and saves a full-resolution edited JPEG", async ({
page,
}) => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "sam@glenloch.local");
await page.goto(eventUrl);
await page.getByRole("link", { name: /Originals/ }).click();
await page
.getByRole("button", { name: `View and edit ${PHOTO_NAME}` })
.click();
await expect(page.getByRole("dialog")).toBeVisible();
await expect(page.getByRole("heading", { name: "Edit photo" })).toBeVisible();
await page.getByLabel("Exposure").focus();
await page.getByLabel("Exposure").press("ArrowRight");
await page.getByRole("button", { name: "Save edited JPEG" }).click();
await expect(page.getByText("Full-resolution JPEG saved.")).toBeVisible({
timeout: 30_000,
});
const [download] = await Promise.all([
page.waitForEvent("download"),
page.getByRole("link", { name: "Download edited JPEG" }).click(),
]);
expect(download.suggestedFilename()).toBe("photo-edited.jpg");
const edited = await readFile((await download.path())!);
expect(edited.subarray(0, 3).toString("hex")).toBe("ffd8ff");
expect(edited.equals(PHOTO)).toBe(false);
await page.getByRole("button", { name: "Close photo editor" }).click();
await expect(page.getByText("Edited", { exact: true })).toBeVisible();
await expect(page.locator(`img[alt="${PHOTO_NAME}"]`)).toHaveAttribute(
"src",
/variant=edited/,
);
// The event-wide ZIP now carries the generated JPEG beside its original.
await page.goto(eventUrl);
const [zipDownload] = await Promise.all([
page.waitForEvent("download"),
page.getByRole("link", { name: /Download all \(2\)/ }).click(),
]);
const zip = await readFile((await zipDownload.path())!);
expect(zip.includes(edited)).toBe(true);
expect(zip.includes(Buffer.from("Originals/photo-edited.jpg"))).toBe(true);
});
test("an unassigned volunteer cannot open the event", async ({ page }) => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "jordan@glenloch.local");
const response = await page.goto(eventUrl);
expect(response?.status()).toBe(404);
});
test("a manager deletes the event and its photos", async ({ page }) => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "admin@glenloch.local");
await page.goto(eventUrl);
await page.getByRole("link", { name: /Originals/ }).click();
const photoHref = await page
.getByRole("link", { name: "Download" })
.first()
.getAttribute("href");
expect(photoHref).toBeTruthy();
await page.goto(eventUrl);
page.once("dialog", (dialog) => dialog.accept());
await page.getByRole("button", { name: "Delete event" }).click();
await expect(page).toHaveURL(`${BASE}/events`);
const gone = await page.goto(eventUrl);
expect(gone?.status()).toBe(404);
const photoGone = await page.request.get(`${BASE}${photoHref}`);
expect(photoGone.status()).toBe(404);
});
});
+330
View File
@@ -0,0 +1,330 @@
import { test, expect } from "@playwright/test";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { access, mkdir, readFile, rm, stat } from "node:fs/promises";
import path from "node:path";
import { signInAs, resetDb, BASE } from "./dev";
/**
* Video library workflow: a generated MP4 is uploaded to an event, the camera
* original lands on the NFS mount, FFmpeg builds a playable derivative, the
* original survives a trim, and the public watch/embed/oEmbed endpoints work
* anonymously. Deleting the event removes both the NFS original and derivatives.
*/
const execFileAsync = promisify(execFile);
const ARCHIVE_ROOT = process.env.ARCHIVE_DIR ?? "/tmp/glenloch-e2e-archive";
const ARCHIVE_FOLDER = "E2E Video Archive";
const UPLOAD_DIR = process.env.UPLOAD_DIR ?? "/tmp/glenloch-e2e-uploads";
const SAMPLE = "/tmp/glenloch-e2e-media-sample.mp4";
// A real 32×24 JPEG, so the media page renders a normal browser image.
const PHOTO = Buffer.from(
"/9j/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAAYACADASIAAhEBAxEB/8QAFwABAQEBAAAAAAAAAAAAAAAAAAcICf/EABgQAQADAQAAAAAAAAAAAAAAAAAXZaTi/8QAFQEBAQAAAAAAAAAAAAAAAAAACAf/xAAbEQEAAQUBAAAAAAAAAAAAAAAAAQMEFFKh0f/aAAwDAQACEQMRAD8AuYAvrq5kinQtc5eyFrnL2XmDca9j0ccyhtyW6ABDI5mQA6BNf//Z",
"base64",
);
let sampleBytes: Buffer;
type VideoPayload = {
video: {
id: string;
status: "processing" | "ready" | "failed";
durationMs: number | null;
trimStartMs: number;
trimEndMs: number | null;
canPlay: boolean;
isShareable: boolean;
embedCode: string | null;
};
};
test.describe("media library and video sharing", () => {
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await resetDb(page);
await context.close();
await mkdir(ARCHIVE_ROOT, { recursive: true });
await rm(path.join(ARCHIVE_ROOT, ARCHIVE_FOLDER), {
recursive: true,
force: true,
});
await execFileAsync("ffmpeg", [
"-hide_banner",
"-loglevel",
"error",
"-y",
"-f",
"lavfi",
"-i",
"color=c=0x204060:s=1280x720:d=3:r=24",
"-f",
"lavfi",
"-i",
"sine=frequency=440:duration=3",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-c:a",
"aac",
"-shortest",
SAMPLE,
]);
sampleBytes = await readFile(SAMPLE);
});
test("uploads, trims, publishes, and cleans up a video", async ({ page }) => {
test.setTimeout(240_000);
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "admin@glenloch.local");
const configured = await page.request.put(`${BASE}/api/dev/storage`, {
data: {
nfsShare: "e2e-nas:/export/church",
archivePath: ARCHIVE_ROOT,
archiveFolder: ARCHIVE_FOLDER,
},
});
expect(configured.ok()).toBe(true);
const eventResponse = await page.request.post(`${BASE}/api/events`, {
data: {
title: "E2E media event",
eventType: "photoshoot",
startsAtLocal: "2026-11-21T10:00",
location: "Main campus",
},
});
expect(eventResponse.ok()).toBe(true);
const event = (await eventResponse.json()) as { event: { id: string } };
const eventId = event.event.id;
const folderResponse = await page.request.post(
`${BASE}/api/events/${eventId}/folders`,
{ data: { name: "Originals", kind: "originals" } },
);
expect(folderResponse.ok()).toBe(true);
const folder = (await folderResponse.json()) as {
folder: { id: string };
};
const photoUpload = await page.request.post(
`${BASE}/api/events/${eventId}/folders/${folder.folder.id}/photos?name=media-test.jpg`,
{
headers: { "content-type": "image/jpeg" },
data: PHOTO,
},
);
expect(photoUpload.ok()).toBe(true);
const upload = await page.request.post(
`${BASE}/api/events/${eventId}/videos?name=recap.mp4&title=E2E%20video&visibility=team`,
{
headers: { "content-type": "video/mp4" },
data: sampleBytes,
},
);
expect(upload.status()).toBe(201);
const created = (await upload.json()) as VideoPayload;
const videoId = created.video.id;
expect(created.video.status).toBe("processing");
const readVideo = async (): Promise<VideoPayload> => {
const response = await page.request.get(
`${BASE}/api/events/${eventId}/videos/${videoId}`,
);
expect(response.ok()).toBe(true);
return (await response.json()) as VideoPayload;
};
await expect
.poll(async () => (await readVideo()).video.status, {
timeout: 120_000,
intervals: [500, 1000, 2000],
})
.toBe("ready");
const ready = await readVideo();
expect(ready.video.durationMs).toBeGreaterThan(2500);
expect(ready.video.canPlay).toBe(true);
expect(ready.video.isShareable).toBe(false);
const nfsOriginal = path.join(
ARCHIVE_ROOT,
ARCHIVE_FOLDER,
"videos",
eventId,
videoId,
"original.mp4",
);
expect((await stat(nfsOriginal)).size).toBe(sampleBytes.length);
expect((await readFile(nfsOriginal)).equals(sampleBytes)).toBe(true);
const sidecar = JSON.parse(
await readFile(path.join(path.dirname(nfsOriginal), "video.json"), "utf8"),
) as { checksumSha256: string; eventId: string };
expect(sidecar.eventId).toBe(eventId);
expect(sidecar.checksumSha256).toMatch(/^[a-f0-9]{64}$/);
const original = await page.request.get(
`${BASE}/api/events/${eventId}/videos/${videoId}/original`,
);
expect(original.ok()).toBe(true);
expect((await original.body()).equals(sampleBytes)).toBe(true);
const poster = await page.request.get(
`${BASE}/api/media/${videoId}/poster`,
);
expect(poster.ok()).toBe(true);
expect(poster.headers()["content-type"]).toContain("image/jpeg");
const edit = await page.request.post(
`${BASE}/api/events/${eventId}/videos/${videoId}/edit`,
{
data: {
title: "E2E video public",
visibility: "public",
trimStartMs: 500,
trimEndMs: 2000,
},
},
);
expect(edit.ok()).toBe(true);
const edited = (await edit.json()) as VideoPayload;
expect(edited.video.status).toBe("processing");
await expect
.poll(async () => (await readVideo()).video.status, {
timeout: 120_000,
intervals: [500, 1000, 2000],
})
.toBe("ready");
const trimmed = await readVideo();
expect(trimmed.video.trimStartMs).toBe(500);
expect(trimmed.video.trimEndMs).toBe(2000);
expect(trimmed.video.isShareable).toBe(true);
expect(trimmed.video.embedCode).toContain(`/embed/${videoId}`);
const webPath = path.join(
UPLOAD_DIR,
"videos",
eventId,
videoId,
"web.mp4",
);
const probe = await execFileAsync(
"ffprobe",
[
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=nw=1:nk=1",
webPath,
],
{ encoding: "utf8" },
);
const trimmedSeconds = Number(String(probe.stdout).trim());
expect(trimmedSeconds).toBeGreaterThan(1.2);
expect(trimmedSeconds).toBeLessThan(1.9);
// A 720p upload gets a smaller 480p sibling for slow connections.
const lowPath = path.join(
UPLOAD_DIR,
"videos",
eventId,
videoId,
"web-480.mp4",
);
expect((await stat(lowPath)).size).toBeGreaterThan(0);
const lowStream = await fetch(
`${BASE}/api/media/${videoId}/stream?quality=480`,
{ headers: { range: "bytes=0-255" } },
);
expect(lowStream.status).toBe(206);
expect(lowStream.headers.get("content-range")).toContain("bytes 0-255/");
expect((await lowStream.arrayBuffer()).byteLength).toBe(256);
// The non-destructive trim must never touch the NFS camera original.
expect((await readFile(nfsOriginal)).equals(sampleBytes)).toBe(true);
const stream = await fetch(`${BASE}/api/media/${videoId}/stream`, {
headers: { range: "bytes=0-255" },
});
expect(stream.status).toBe(206);
expect(stream.headers.get("content-range")).toContain("bytes 0-255/");
expect((await stream.arrayBuffer()).byteLength).toBe(256);
const watch = await fetch(`${BASE}/watch/${videoId}`);
expect(watch.status).toBe(200);
const watchHtml = await watch.text();
expect(watchHtml).toContain("E2E video public");
expect(watchHtml).toContain("Glenloch Baptist Church");
expect(watchHtml).not.toContain("Media Team Hub");
expect(watchHtml).toContain('property="og:video"');
expect(watchHtml).toContain('name="twitter:player"');
expect(watchHtml).toContain("application/json+oembed");
const embed = await fetch(`${BASE}/embed/${videoId}`);
expect(embed.status).toBe(200);
expect(embed.headers.get("x-frame-options")).toBeNull();
expect(await embed.text()).toContain("<video");
const oembed = await fetch(
`${BASE}/api/oembed?url=${encodeURIComponent(`${BASE}/watch/${videoId}`)}&format=json`,
);
expect(oembed.status).toBe(200);
expect(oembed.headers.get("access-control-allow-origin")).toBe("*");
const payload = (await oembed.json()) as {
type: string;
width: number;
height: number;
html: string;
thumbnail_url: string;
};
expect(payload.type).toBe("video");
expect(payload.width).toBe(1280);
expect(payload.height).toBe(720);
expect(payload.html).toContain(`/embed/${videoId}`);
expect(payload.thumbnail_url).toContain(`/api/media/${videoId}/poster`);
await page.goto(`${BASE}/media`);
await expect(
page.getByRole("heading", { name: "Media", exact: true }),
).toBeVisible();
await expect(page.getByText("media-test.jpg").first()).toBeVisible();
await expect(page.getByText("E2E video public").first()).toBeVisible();
await page.getByRole("link", { name: /E2E video public/ }).click();
await expect(page).toHaveURL(new RegExp(`/media/${videoId}$`));
await expect(
page.getByRole("heading", { name: "Edit video" }),
).toBeVisible();
await expect(page.getByLabel("Visibility")).toHaveValue("public");
await expect(page.getByLabel("Embed code")).toHaveValue(/<iframe/);
await page.goto(`${BASE}/events/${eventId}`);
await expect(
page.getByRole("heading", { name: "E2E media event" }),
).toBeVisible();
await expect(page.getByText("E2E video public").first()).toBeVisible();
await expect(page.getByLabel("Video file")).toBeVisible();
page.once("dialog", (dialog) => dialog.accept());
await page.getByRole("button", { name: "Delete event" }).click();
await expect(page).toHaveURL(`${BASE}/events`);
await expect(access(nfsOriginal)).rejects.toThrow();
await expect(
access(path.join(UPLOAD_DIR, "videos", eventId)),
).rejects.toThrow();
const gone = await fetch(`${BASE}/watch/${videoId}`);
expect(gone.status).toBe(404);
});
});
+186
View File
@@ -0,0 +1,186 @@
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<string> {
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<NotificationRow[]> {
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);
});
});
+177
View File
@@ -0,0 +1,177 @@
import { test, expect } from "@playwright/test";
import { resetDb, signInAs, BASE } from "./dev";
const PASSWORD = "first-password-123";
const NEW_PASSWORD = "second-password-456";
test.describe("username and password accounts", () => {
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await resetDb(page);
await context.close();
});
test("first magic link sets credentials; the user can change their password", async ({
page,
}) => {
const email = `e2e-password-${Date.now()}@example.com`;
const username = `pwuser${Date.now()}`;
const linkRes = await page.request.post(`${BASE}/api/dev/magic-link`, {
data: { email },
});
expect(linkRes.ok()).toBe(true);
const link = (await linkRes.json()) as { url?: string };
await page.goto(link.url!);
await expect(page).toHaveURL(`${BASE}/welcome`);
await expect(
page.getByRole("heading", { name: "Set your login" }),
).toBeVisible();
await expect(page.getByLabel("Username")).toHaveValue(email);
await page.getByLabel("Username").fill(username);
await page.getByLabel("Password", { exact: true }).fill(PASSWORD);
await page.getByLabel("Confirm password").fill(PASSWORD);
await page.getByRole("button", { name: "Save and continue" }).click();
await expect(page.getByRole("heading", { name: "Schedule", level: 1 })).toBeVisible();
await page.context().clearCookies();
await page.goto(`${BASE}/login`);
await page.getByLabel("Username or email").fill(username);
await page.getByLabel("Password", { exact: true }).fill(PASSWORD);
await page.getByRole("button", { name: "Sign in", exact: true }).click();
await expect(page.getByRole("heading", { name: "Schedule", level: 1 })).toBeVisible();
await page.goto(`${BASE}/settings`);
await page.getByLabel("Current password", { exact: true }).fill(PASSWORD);
await page.getByLabel("New password", { exact: true }).fill(NEW_PASSWORD);
await page.getByLabel("Confirm new password", { exact: true }).fill(NEW_PASSWORD);
await page.getByRole("button", { name: "Change password" }).click();
await expect(page.getByText("Your login has been updated.")).toBeVisible();
await page.context().clearCookies();
await page.goto(`${BASE}/login`);
await page.getByLabel("Username or email").fill(username);
await page.getByLabel("Password", { exact: true }).fill(PASSWORD);
await page.getByRole("button", { name: "Sign in", exact: true }).click();
await expect(
page.getByText("That username or password did not match an active account."),
).toBeVisible();
await page.getByLabel("Password", { exact: true }).fill(NEW_PASSWORD);
await page.getByRole("button", { name: "Sign in", exact: true }).click();
await expect(page.getByRole("heading", { name: "Schedule", level: 1 })).toBeVisible();
});
test("admin can set a password and issue a reset link", async ({ page, browser }) => {
await signInAs(page, "admin@glenloch.local");
const email = `e2e-reset-${Date.now()}@example.com`;
const createdRes = await page.request.post(`${BASE}/api/dev/users`, {
data: {
email,
firstName: "Reset",
lastName: "Test",
systemRole: "volunteer",
status: "active",
},
});
expect(createdRes.status()).toBe(201);
const created = (await createdRes.json()) as { user: { id: string } };
await page.goto(`${BASE}/admin`);
const row = page.getByRole("row", { name: new RegExp(email) });
await row.getByRole("button", { name: "Edit" }).click();
const editor = page.getByRole("form", { name: `Edit ${email}` });
await editor.getByLabel("New password").fill("admin-direct-123");
await editor.getByRole("button", { name: "Set password" }).click();
await expect(page.getByText("Password updated for this person.")).toBeVisible();
const directContext = await browser.newContext();
const directPage = await directContext.newPage();
await directPage.goto(`${BASE}/login`);
await directPage.getByLabel("Username or email").fill(email);
await directPage.getByLabel("Password", { exact: true }).fill("admin-direct-123");
await directPage.getByRole("button", { name: "Sign in", exact: true }).click();
await expect(
directPage.getByRole("heading", { name: "Schedule", level: 1 }),
).toBeVisible();
await directContext.close();
await editor.getByRole("button", { name: "Create reset link" }).click();
const resetNotice = page.getByText(/Reset link \(valid for 1 hour\)/);
await expect(resetNotice).toBeVisible();
const noticeText = (await resetNotice.textContent()) ?? "";
const resetUrl = noticeText.match(/https?:\/\/\S+/)?.[0];
expect(resetUrl, "the admin should receive a reset URL").toBeTruthy();
const resetContext = await browser.newContext();
const resetPage = await resetContext.newPage();
await resetPage.goto(resetUrl!);
await resetPage.getByLabel("New password").fill("reset-password-789");
await resetPage.getByLabel("Confirm password").fill("reset-password-789");
await resetPage.getByRole("button", { name: "Reset password" }).click();
await expect(
resetPage.getByText(/Your password has been updated/),
).toBeVisible();
await resetPage.goto(`${BASE}/login`);
await resetPage.getByLabel("Username or email").fill(email);
await resetPage.getByLabel("Password", { exact: true }).fill("reset-password-789");
await resetPage.getByRole("button", { name: "Sign in", exact: true }).click();
await expect(
resetPage.getByRole("heading", { name: "Schedule", level: 1 }),
).toBeVisible();
await resetContext.close();
expect(created.user.id).toBeTruthy();
});
test("admin can reveal and resend an emergency magic link", async ({
page,
browser,
}) => {
await signInAs(page, "admin@glenloch.local");
const email = `e2e-magic-${Date.now()}@example.com`;
const createdRes = await page.request.post(`${BASE}/api/dev/users`, {
data: {
email,
firstName: "Magic",
lastName: "Test",
systemRole: "volunteer",
status: "active",
},
});
expect(createdRes.status()).toBe(201);
await page.goto(`${BASE}/admin`);
const row = page.getByRole("row", { name: new RegExp(email) });
await row.getByRole("button", { name: "Edit" }).click();
const editor = page.getByRole("form", { name: `Edit ${email}` });
await editor.getByRole("button", { name: "Show magic link" }).click();
const linkNotice = page.getByText(/Magic link \(valid for 10 minutes\)/);
await expect(linkNotice).toBeVisible();
const linkText = (await linkNotice.textContent()) ?? "";
const magicUrl = linkText.match(/https?:\/\/\S+/)?.[0];
expect(magicUrl, "the admin should receive a magic URL").toBeTruthy();
// The revealed link signs the person in; a first-time account lands on the
// credential setup page.
const magicContext = await browser.newContext();
const magicPage = await magicContext.newPage();
await magicPage.goto(magicUrl!);
await expect(magicPage).toHaveURL(`${BASE}/welcome`);
await expect(
magicPage.getByRole("heading", { name: "Set your login" }),
).toBeVisible();
await magicContext.close();
await editor.getByRole("button", { name: "Resend magic link" }).click();
await expect(page.getByText(/Magic link sent via/)).toBeVisible();
});
});
+149
View File
@@ -0,0 +1,149 @@
import { test, expect } from "@playwright/test";
import { access, mkdir, readFile, readdir, rm } from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";
import { signInAs, resetDb, BASE } from "./dev";
/**
* The finish-workflow APIs: save an edit, export a delivery size, archive the
* event to the mounted destination, and remove the live event only after the
* archive is complete. Runs against the isolated `media_e2e` database.
*/
const ARCHIVE_ROOT = process.env.ARCHIVE_DIR ?? "/tmp/glenloch-e2e-archive";
const ARCHIVE_FOLDER = "E2E Archive";
const UPLOAD_DIR = process.env.UPLOAD_DIR ?? "/tmp/glenloch-e2e-uploads";
let photoBytes: Buffer;
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await resetDb(page);
await context.close();
photoBytes = await sharp({
create: {
width: 1200,
height: 800,
channels: 3,
background: { r: 80, g: 120, b: 160 },
},
})
.jpeg({ quality: 95 })
.toBuffer();
await mkdir(ARCHIVE_ROOT, { recursive: true });
await rm(path.join(ARCHIVE_ROOT, ARCHIVE_FOLDER), {
recursive: true,
force: true,
});
});
test("exports a delivery size, then archives and removes the event", async ({
page,
}) => {
await page.setViewportSize({ width: 1200, height: 900 });
await signInAs(page, "admin@glenloch.local");
const configured = await page.request.put(`${BASE}/api/dev/storage`, {
data: {
nfsShare: "e2e-nas:/export/church",
archivePath: ARCHIVE_ROOT,
archiveFolder: ARCHIVE_FOLDER,
},
});
expect(configured.ok()).toBe(true);
const storage = (await configured.json()) as { status?: { ready: boolean } };
expect(storage.status?.ready).toBe(true);
const eventResponse = await page.request.post(`${BASE}/api/events`, {
data: {
title: "E2E archive workflow",
eventType: "photoshoot",
startsAtLocal: "2026-11-20T10:00",
location: "Main campus",
},
});
expect(eventResponse.ok()).toBe(true);
const event = (await eventResponse.json()) as { event: { id: string } };
const folderResponse = await page.request.post(
`${BASE}/api/events/${event.event.id}/folders`,
{ data: { name: "Originals", kind: "originals" } },
);
expect(folderResponse.ok()).toBe(true);
const folder = (await folderResponse.json()) as { folder: { id: string } };
const upload = await page.request.post(
`${BASE}/api/events/${event.event.id}/folders/${folder.folder.id}/photos?name=archive-test.jpg`,
{
headers: { "content-type": "image/jpeg" },
data: photoBytes,
},
);
expect(upload.ok()).toBe(true);
const uploaded = (await upload.json()) as { photo: { id: string } };
const edit = await page.request.post(
`${BASE}/api/events/${event.event.id}/folders/${folder.folder.id}/photos/${uploaded.photo.id}/edit`,
{
data: {
adjustments: {
exposure: 0.4,
contrast: 8,
blackPoint: 0,
brightness: 0,
curves: [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
],
},
},
},
);
expect(edit.ok()).toBe(true);
const exported = await page.request.get(
`${BASE}/api/events/${event.event.id}/folders/${folder.folder.id}/photos/${uploaded.photo.id}/export?size=640`,
);
expect(exported.ok()).toBe(true);
expect(exported.headers()["content-disposition"]).toContain(
"archive-test-640.jpg",
);
const exportMeta = await sharp(await exported.body()).metadata();
expect(exportMeta.width).toBe(640);
expect(exportMeta.height).toBe(427);
const archived = await page.request.post(
`${BASE}/api/events/${event.event.id}/archive`,
);
expect(archived.ok()).toBe(true);
const archive = (await archived.json()) as {
archivePath: string;
files: number;
};
expect(archive.files).toBe(3);
const manifest = JSON.parse(
await readFile(path.join(archive.archivePath, "manifest.json"), "utf8"),
) as {
photos: { original: string; edited: string | null; editJson: string | null }[];
};
expect(manifest.photos).toHaveLength(1);
expect(manifest.photos[0].original).toContain("archive-test.jpg");
expect(manifest.photos[0].edited).toContain("archive-test-edited.jpg");
expect(manifest.photos[0].editJson).toContain('"exposure":0.4');
const entries = await readdir(archive.archivePath, { recursive: true });
expect(entries.some((entry) => entry.endsWith("archive-test.jpg"))).toBe(true);
expect(
entries.some((entry) => entry.endsWith("archive-test-edited.jpg")),
).toBe(true);
const gone = await page.goto(`${BASE}/events/${event.event.id}`);
expect(gone?.status()).toBe(404);
await expect(
access(path.join(UPLOAD_DIR, "events", event.event.id)),
).rejects.toThrow();
});
+121
View File
@@ -0,0 +1,121 @@
import { test, expect, type Page } from "@playwright/test";
import { signInAs, resetDb, BASE } from "./dev";
/**
* Publish / unpublish — unit D10 (ARCHITECTURE §5.5).
*
* The seed leaves the second Sunday's instances in draft, so this suite has a
* week it can actually publish. The properties pinned here:
* - publishing a week with empty covering seats is blocked (409) with the
* empty seats listed, unless the admin passes `allowGaps`,
* - re-publishing the same week is an idempotent no-op,
* - unpublishing is refused while a volunteer has confirmed,
* - a volunteer cannot publish or unpublish at all (403).
*
* D10 sends nothing: no notifications exist yet, by design.
*/
/** The seed's draft instance (second Sunday). */
async function draftInstanceId(page: Page): Promise<string> {
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;
}
let instanceId: string;
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await resetDb(page);
// Resolve the draft instance while the admin session (which holds
// `schedule.publish`) is live; the volunteer test cannot read this route.
instanceId = await draftInstanceId(page);
await context.close();
});
test.describe("publish", () => {
test("open seats block publish, allowGaps publishes, re-publish is a no-op", 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");
const url = `${BASE}/api/dev/schedule/${instanceId}/publish`;
// Blocked: the seed fills only Audio, so Livestream and Slides are empty.
const blocked = await page.request.post(url, { data: JSON.stringify({}) });
expect(blocked.status(), "publish with empty seats is refused").toBe(409);
const blockedBody = (await blocked.json()) as {
code: string;
gaps: { slotId: string }[];
};
expect(blockedBody.code).toBe("open_slots");
expect(blockedBody.gaps.length, "both empty seats are listed").toBe(2);
// The explicit override publishes the week with those gaps.
const published = await (
await page.request.post(url, {
data: JSON.stringify({ allowGaps: true }),
})
).json() as {
published: boolean;
alreadyPublished: boolean;
gaps: unknown[];
publishedAt: string;
};
expect(published.published).toBe(true);
expect(published.alreadyPublished).toBe(false);
expect(published.gaps).toHaveLength(2);
// Re-publish is idempotent: nothing changes, including the publish instant.
const again = await (
await page.request.post(url, {
data: JSON.stringify({ allowGaps: true }),
})
).json() as {
published: boolean;
alreadyPublished: boolean;
publishedAt: string;
};
expect(again.published).toBe(false);
expect(again.alreadyPublished).toBe(true);
expect(again.publishedAt).toBe(published.publishedAt);
// A volunteer confirmed the Audio seat, so the week cannot revert to draft.
const unpublish = await page.request.delete(url);
expect(unpublish.status(), "confirmed volunteer blocks unpublish").toBe(409);
const unpublishBody = (await unpublish.json()) as { code: string };
expect(unpublishBody.code).toBe("unpublish_blocked");
expect(errors, `unexpected console/page errors: ${errors.join("; ")}`).toEqual(
[],
);
});
test("volunteer is rejected by publish and unpublish with 403", async ({
page,
}) => {
await page.setViewportSize({ width: 1024, height: 768 });
await signInAs(page, "avery@glenloch.local");
await page.goto(`${BASE}/schedule`);
await expect(page).toHaveURL(`${BASE}/schedule`);
const url = `${BASE}/api/dev/schedule/${instanceId}/publish`;
const post = await page.request.post(url, { data: JSON.stringify({}) });
expect(post.status(), "volunteer publish must be rejected").toBe(403);
const del = await page.request.delete(url);
expect(del.status(), "volunteer unpublish must be rejected").toBe(403);
});
});
+34
View File
@@ -0,0 +1,34 @@
import { test, expect } from "@playwright/test";
import { signInAs, resetDb, BASE } from "./dev";
/** Building the schedule out: add a service template, then generate instances. */
test.describe("services", () => {
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await resetDb(page);
await context.close();
});
test("admin can add a service and generate upcoming instances", async ({
page,
}) => {
await page.setViewportSize({ width: 1024, height: 900 });
await signInAs(page, "admin@glenloch.local");
await page.goto(`${BASE}/admin`);
const name = `E2E Service ${Date.now()}`;
await page.getByLabel("Name", { exact: true }).fill(name);
await page.getByLabel("Start time").fill("17:00");
await page.getByLabel("Minutes").fill("60");
await page.getByLabel("Location").fill("Chapel");
await page.getByRole("button", { name: "Add service" }).click();
await expect(page.getByRole("cell", { name: new RegExp(name) })).toBeVisible();
await page.getByRole("button", { name: "Generate upcoming Sundays" }).click();
await expect(
page.getByText(/Generated \d+ new service instance\(s\)/),
).toBeVisible();
});
});
+34
View File
@@ -0,0 +1,34 @@
import { test, expect } from "@playwright/test";
import { signInAs, resetDb, BASE } from "./dev";
/** Admin email identity settings persist in the database, not env files. */
test.describe("email settings", () => {
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await resetDb(page);
await context.close();
});
test("admin can edit the sender and notification inbox", async ({ page }) => {
await page.setViewportSize({ width: 1024, height: 900 });
await signInAs(page, "admin@glenloch.local");
await page.goto(`${BASE}/settings`);
await page.getByLabel("From address").fill("notifications@glenloch.local");
await page
.getByLabel("Admin notifications (optional)")
.fill("ops@glenloch.local");
await page.getByRole("button", { name: "Save email settings" }).click();
await expect(page.getByText(/Saved\. New notifications/)).toBeVisible();
await page.reload();
await expect(page.getByLabel("From address")).toHaveValue(
"notifications@glenloch.local",
);
await expect(page.getByLabel("Admin notifications (optional)")).toHaveValue(
"ops@glenloch.local",
);
});
});
+14 -20
View File
@@ -1,25 +1,19 @@
import { test, expect, type Page } from "@playwright/test";
import { test, expect } from "@playwright/test";
import { signInAs, BASE } from "./dev";
const BASE = "http://localhost:3000";
const TAB_LABELS = ["Schedule", "Roster", "Training", "Announcements", "Settings"];
/**
* Dev console transport: request a magic link, then complete it in the browser
* context so the Auth.js session cookie is set for the navigation under test.
*/
async function signInAs(page: Page, email: string) {
const res = await page.request.post(`${BASE}/api/dev/magic-link`, {
data: { email },
});
expect(res.ok(), "magic-link request should succeed").toBe(true);
const body = (await res.json()) as { url?: string };
expect(body.url, "magic-link should return a sign-in url").toBeTruthy();
await page.goto(body.url!);
await expect(page).toHaveURL(/complete/);
}
const TAB_LABELS = [
"Home",
"Schedule",
"Events",
"Media",
"Roster",
"Training",
"Announcements",
"Settings",
];
test.describe("app shell", () => {
test("renders the shell with 5 nav tabs at a 360px viewport", async ({ page }) => {
test("renders the shell with 8 nav tabs at a 360px viewport", async ({ page }) => {
await page.setViewportSize({ width: 360, height: 780 });
await signInAs(page, `e2e-mobile-${Date.now()}@example.com`);
@@ -29,7 +23,7 @@ test.describe("app shell", () => {
// Header + page title.
await expect(page.getByRole("heading", { name: "Schedule", level: 1 })).toBeVisible();
// Five nav tabs, one per label.
// One tab per primary destination.
for (const label of TAB_LABELS) {
await expect(page.getByRole("link", { name: label, exact: true })).toBeVisible();
}
+77
View File
@@ -0,0 +1,77 @@
import { test, expect } from "@playwright/test";
import { signInAs, resetDb, BASE } from "./dev";
/**
* Training authoring (F2): create a lesson, publish it, upload an attachment,
* and confirm a volunteer sees the content without authoring controls.
*/
let lessonTitle: string;
let lessonId: string;
test.describe("training", () => {
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await resetDb(page);
await context.close();
});
test("admin authors a lesson and uploads an attachment", async ({ page }) => {
await page.setViewportSize({ width: 1024, height: 900 });
await signInAs(page, "admin@glenloch.local");
await page.goto(`${BASE}/training`);
// Seeded starter content is visible.
await expect(page.getByRole("heading", { name: "Audio team basics" })).toBeVisible();
lessonTitle = `E2E lesson ${Date.now()}`;
await page.getByLabel("Title").fill(lessonTitle);
await page.getByLabel("Summary").fill("Created from the admin UI");
await page.getByLabel("Content").fill("Step one\nStep two");
await page.getByRole("button", { name: "Create lesson" }).click();
await expect(
page.getByRole("heading", { name: lessonTitle }),
).toBeVisible();
const list = (await (
await page.request.get(`${BASE}/api/dev/training/lessons`)
).json()) as { lessons: { id: string; title: string }[] };
lessonId = list.lessons.find((lesson) => lesson.title === lessonTitle)!.id;
const upload = await page.request.post(
`${BASE}/api/dev/training/resources`,
{
multipart: {
lessonId,
file: {
name: "guide.txt",
mimeType: "text/plain",
buffer: Buffer.from("hello from the upload test"),
},
},
},
);
expect(upload.status(), "upload should be accepted").toBe(201);
await page.reload();
await expect(page.getByRole("link", { name: "guide.txt" })).toBeVisible();
});
test("volunteer sees published lessons but no authoring controls", async ({
page,
}) => {
await page.setViewportSize({ width: 1024, height: 900 });
await signInAs(page, "avery@glenloch.local");
await page.goto(`${BASE}/training`);
await expect(
page.getByRole("heading", { name: lessonTitle }),
).toBeVisible();
await expect(
page.getByRole("button", { name: "Create lesson" }),
).toHaveCount(0);
await expect(page.getByRole("link", { name: "guide.txt" })).toBeVisible();
});
});