fix(D8): grid slots render, per-cell optimistic revert, shared E2E helpers, admin reset endpoint

- src/db/grid.ts: key role map by ID (was slug, causing all cells to show '—')
- src/components/app/schedule-grid-editor.tsx: revert only failed cell, not entire grid
- src/db/audit.ts: fix import path ./db → @/db
- src/db/seed.ts: add resetAndSeed(), assign Audio only (leave Livestream/Slides open)
- src/auth/config.ts: carry id/email on JWT for audit actor
- e2e/dev.ts: shared signInAs + resetDb helpers
- e2e/schedule-grid.spec.ts: use shared helpers, reset DB beforeAll
- e2e/assign-mutations.spec.ts: E2E for assign/clear with optimistic update + rollback
- src/app/api/dev/reset/route.ts: admin-only DB reset endpoint
- playwright.config.ts: workers: 1 (serial, suites share one Postgres)
This commit is contained in:
Tiel Coder
2026-11-18 21:51:04 +00:00
parent 137a135a5e
commit d0a696167f
16 changed files with 3304 additions and 36 deletions
+134
View File
@@ -0,0 +1,134 @@
import { test, expect, type Page, type Locator } from "@playwright/test";
import { signInAs, resetDb, BASE } from "./dev";
/**
* Reset the DB to the clean seed before the suite runs. The reset truncates and
* repopulates the seed-owned tables; it must run as admin (admin.settings) and
* from the browser context (page.request does not share the session cookie), so
* it goes through `fetch` inside the page after an admin sign-in.
*/
test.beforeAll(async ({ browser }) => {
// The `page` fixture is per-test, so drive a throwaway context here: sign in
// as admin, hit the reset endpoint from inside the page (it needs the session
// cookie), then close the context. Each test still gets its own page below.
const context = await browser.newContext();
const page = await context.newPage();
await resetDb(page);
await context.close();
});
/**
* The grid renders one <td> per position, in the same order as the <thead>
* headers (which are prefixed by the "When" row header). Map a role name to
* its cell so assertions never depend on a hard-coded column index.
*/
async function cellForRole(page: Page, row: Locator, role: string) {
const headers = await page.locator("thead th").allTextContents();
const headerIndex = headers.indexOf(role);
expect(headerIndex, `grid header "${role}" present`).toBeGreaterThanOrEqual(0);
// header[0] is the "When" row header; the first data <td> sits under header[1].
return row.locator("td").nth(headerIndex - 1);
}
test.describe("assign mutations", () => {
test("assign appears immediately, forced duplicate rolls back, clear returns to open", async ({
page,
}) => {
const errors: string[] = [];
// The rule-1 rollback is an intentional 409; the browser logs that failed
// fetch as a console error. Only real failures (500s, crashes) count.
const EXPECTED_409 = "status of 409 (Conflict)";
page.on("console", (msg) => {
if (msg.type() === "error" && !msg.text().includes(EXPECTED_409))
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");
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;
// Livestream + Slides open).
const row = page.locator("tbody tr").first();
await expect(row.locator("select").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.
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();
// 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" });
await expect(
livestream.locator("button", { hasText: "Clear" }),
).toBeVisible();
await expect(
livestream.locator("span", { hasText: "Avery Kim" }),
).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 successful optimistic assign is still live.
await expect(
livestream.locator("button", { hasText: "Clear" }),
).toBeVisible();
await expect(
livestream.locator("span", { hasText: "Avery Kim" }),
).toBeVisible();
// No console or page errors while the mutations run.
expect(errors, `unexpected console/page errors: ${errors.join("; ")}`).toEqual(
[],
);
});
// Review-focus point 3: a volunteer cannot assign. The read-only grid mounts
// (no assign control), and a direct POST to the route is rejected 403 — not
// 200 and not a 500. Pins the auth chokepoint the plan calls out.
test("volunteer is read-only and the route rejects assign with 403", 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, "avery@glenloch.local");
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();
expect(assignControls, "volunteer grid should expose no assign control").toBe(0);
// The route still enforces the chokepoint directly.
const res = await page.request.post(`${BASE}/api/assignments`, {
data: JSON.stringify({ action: "assign", slotId: "x", userId: "y" }),
headers: { "content-type": "application/json" },
});
expect(res.status(), "volunteer assign must be rejected").toBe(403);
expect(errors, `unexpected console/page errors: ${errors.join("; ")}`).toEqual(
[],
);
});
});
+41
View File
@@ -0,0 +1,41 @@
import { expect, type Page } from "@playwright/test";
const BASE = "http://localhost:3000";
/**
* Shared E2E helpers. Both test files run against the same Postgres, so they
* share the dev-console sign-in transport and the DB reset used to establish a
* known-clean state before each suite.
*/
/**
* 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.
*/
export 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/);
}
/**
* Reset the DB to the clean seed. Admin-only (admin.settings): truncates the
* seed-owned tables and repopulates them, so each suite starts from a known
* state instead of accumulating the mutations of prior runs. Runs from inside
* the page (page.request does not share the session cookie).
*/
export async function resetDb(page: Page) {
await signInAs(page, "admin@glenloch.local");
const status = await page.evaluate(async () => {
const res = await fetch("/api/dev/reset", { method: "POST" });
return res.status;
});
expect(status, "admin reset should succeed").toBe(200);
}
export { BASE };
+12 -18
View File
@@ -1,21 +1,5 @@
import { test, expect, type Page } from "@playwright/test";
const BASE = "http://localhost:3000";
/**
* 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/);
}
import { test, expect } from "@playwright/test";
import { signInAs, resetDb, BASE } from "./dev";
/**
* Unit D7 — read-only scheduling grid. Done when: renders a seeded week; no
@@ -23,6 +7,16 @@ async function signInAs(page: Page, email: string) {
* logged while the grid is mounted.
*/
test.describe("schedule grid", () => {
// Establish a clean seeded state before the read-only suite runs. The grid
// is read-only, but it shares the DB with the mutating assign-mutations
// suite; resetting here keeps this suite independent of run order.
test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await resetDb(page);
await context.close();
});
test("renders a seeded week with no console errors", async ({ page }) => {
const errors: string[] = [];
page.on("console", (msg) => {