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
+144
View File
@@ -0,0 +1,144 @@
# D8 Continuation — assign/unassign/clear mutations (E2E now green)
**Status: D8 is functionally complete. The E2E suite passes 3× in a row. The
only remaining step is committing.** This doc records the blocker that was
stuck the prior session, what I found and fixed, the full change set, and the
exact commit steps.
> Read `.pi/DEAD_ENDS.md` and `D8-HANDOFF.md` first. This doc supersedes the
> "D7 E2E cannot be completed" and "grid never rendered" conclusions — those
> were environmental (DB pollution + a missing migration), not code defects.
---
## 1. The blocker that stuck the prior session (now resolved)
The E2E `e2e/assign-mutations.spec.ts` was failing with **HTTP 500 on every
assign/clear**, which looked like a rule/logic bug but was an **auth/session
bug**:
- The `/api/assignments` route writes an `audit_log` row on every assign/clear,
using `actorId = session.user.id`.
- The Auth.js JWT callbacks only copied `systemRole` onto the token/session —
`id`/`email` were never carried across the JWT boundary. So `session.user.id`
was `undefined`.
- The audit insert therefore sent `actor_id = NULL`, violating the
`audit_log.actor_id NOT NULL` constraint → the route's catch returned 500 →
the editor reverted the optimistic change → the grid never showed the
mutation. The test timed out clicking a "Clear" that never took effect.
**Root cause was NOT the grid or the rules.** Once the audit insert stopped
500ing, assign/clear worked immediately.
### Fix — `src/auth/config.ts`
Carry `id` + `email` onto the JWT (in `jwt`) and back onto `session.user` (in
`session`), alongside `systemRole`. This is the documented Auth.js v5 pattern
(the session callback only receives `user` on the first callback, so identity
must be rehydrated from the token).
---
## 2. Second blocker: E2E test isolation (shared DB race)
After the 500 fix, the assign-mutations suite passed, but running the **full
suite** failed intermittently: `schedule-grid` (read-only) would sometimes see
an empty grid.
- Both suites share one Postgres. `assign-mutations` resets the DB in
`beforeAll` (truncate + seed); `schedule-grid` did not.
- With parallel workers, `schedule-grid` could read the DB **while
`assign-mutations` was mid-truncate** → no instances → "Sunday 9:00 AM" not
rendered.
### Fixes
- **`e2e/dev.ts`** (new): shared `signInAs` + `resetDb` helpers (dev-console
magic-link transport + admin `/api/dev/reset` reset). Both suites import it.
- **`e2e/schedule-grid.spec.ts`**: added a `beforeAll` reset (read-only suite
now establishes its own clean state, independent of run order).
- **`playwright.config.ts`**: `workers: 1` (serial). Both suites reset the same
DB in `beforeAll`; parallel workers would truncate mid-read. The suite is
tiny (~3.5s), so serial is fine. Documented why.
- **`e2e/assign-mutations.spec.ts`**: rewritten to locate cells by role header
(not hard-coded column indices), assert optimistic assign via the Clear
button + name span, assert the rule-1 rollback (Slides keeps its picker +
error toast), and filter the **expected** 409 from the "no console errors"
check (the browser logs the intentional conflict fetch as a console error).
---
## 3. Full change set
### Bug fixes (app code)
- `src/auth/config.ts` — propagate `id`/`email` through JWT → session (fixes the
audit 500). **This is the critical fix.**
- `src/db/audit.ts` — import path `./db` → `@/db` (handoff item; typecheck).
- `src/db/grid.ts` — `roleBySlug` (keyed by slug) → `roleById` (keyed by
`roleId`); grid slots were looked up by UUID, so roles never resolved and
cells never rendered.
- `src/components/app/schedule-grid-editor.tsx` — on a failed mutation, revert
**only that cell** (not the whole optimistic batch).
### E2E support
- `src/app/api/dev/reset/route.ts` (new) — admin-only (`admin.settings`)
`POST` that truncates the seed-owned tables and re-seeds. Guarded; not wired
into any UI. Used by the suites' `beforeAll`.
- `src/db/seed.ts` — exported `seed()` (idempotent populate) and
`resetAndSeed()` (truncate + seed). CLI runs only when it's the entry point
(`isMain` guard via `import.meta.url`) so importing it from the reset route
doesn't execute/exit the server.
- `e2e/dev.ts` (new) — shared helpers.
- `e2e/assign-mutations.spec.ts`, `e2e/schedule-grid.spec.ts` — rewritten above.
- `playwright.config.ts` — `workers: 1`.
### Migrations (must be committed)
- `drizzle/0009_last_wallop.sql` + `drizzle/meta/0009_snapshot.json` +
`drizzle/meta/_journal.json` — **creates the `audit_log` table** (index on
`created_at`). This migration is essential to D8: without it the audit insert
fails with "relation audit_log does not exist". `pnpm db:migrate` applies it
cleanly (verified).
---
## 4. Verification (all green, repeatable)
```
pnpm test # 23 files, 182 tests passed
pnpm tsc --noEmit # clean
npx eslint <changed files> # clean
npx playwright test # 8 passed — run 3× consecutively, all green
pnpm db:migrate # applied successfully
```
The app is running on `:3000` (built with all fixes). Env used for E2E:
`DATABASE_URL=postgres://media:media@localhost:5433/media`,
`NEXTAUTH_SECRET=e2e-secret-for-shell-tests`, `AUTO_ACTIVATE_NEW_USERS=true`.
---
## 5. Remaining steps (for the next agent / commit)
1. **Decide on `e2e/_debug.spec.ts`** — a leftover debug probe (prints grid
counts). It passes but is a scratch artifact; **remove it before commit**
unless you want to keep it as a manual debug aid.
2. **Commit everything.** Suggested scope:
- app fixes: `src/auth/config.ts`, `src/db/audit.ts`, `src/db/grid.ts`,
`src/components/app/schedule-grid-editor.tsx`
- D8 E2E infra: `src/app/api/dev/reset/`, `src/db/seed.ts`, `e2e/dev.ts`,
`e2e/assign-mutations.spec.ts`, `e2e/schedule-grid.spec.ts`,
`playwright.config.ts`
- migrations: `drizzle/0009_last_wallop.sql`, `drizzle/meta/0009_snapshot.json`,
`drizzle/meta/_journal.json`
- **exclude** `e2e/_debug.spec.ts` (or commit it separately if kept).
3. **Re-run the full E2E once more after commit** (`npx playwright test`) to
confirm nothing in the commit broke it.
### If the E2E 500s again
Check the server log (`/tmp/app.log`) for `[assignments] ERROR` or a
`23502`/`23503` SQLSTATE. `actor_id` NULL ⇒ the auth JWT fix regressed;
`relation ... does not exist` ⇒ the `0009` audit_log migration wasn't applied.
### If `pnpm start` exits 137 ("Killed")
Not OOM — the box has ~29 GiB free and no cgroup/ulimit memory cap. It was the
`pkill -f "next-start"` matching its **own** shell command line. Kill by PID
instead:
`PID=$(ss -ltnp | grep ':3000' | grep -oP 'pid=\K[0-9]+' | head -1); kill -9 $PID`.
+134
View File
@@ -0,0 +1,134 @@
# D8 Assign Mutations — Session Handoff
## Goal
Complete D8: assign/unassign/clear with optimistic update + rollback toast. Per plan `docs/superpowers/plans/2026-11-18-d8-assign-mutations-plan.md` (5 TDD tasks).
## Current State
- **Tasks 1–4: COMPLETED & committed**
- Task 1 (audit_log): `b664de6` — audit_log table + migration + auditRow()/writeAudit()
- Task 2 (assign conflict gate): `e189507` — pure assignHardConflicts() in src/domain/assign.ts
- Task 3 (route + data layer): `71b993e` — POST /api/assignments + activeAssignmentInInstance()
- Task 4 (optimistic editor + toast): `137a135` — ScheduleGridEditor, Toast, activeVolunteers()
- **Task 5 (Playwright E2E): IN PROGRESS** — writing E2E, hitting bugs
## Committed Hashes
```
D7: 6982a80
D8 Task 1: b664de6
D8 Task 2: e189507
D8 uuid fix: e47ef83
D8 Task 3: 71b993e
D8 Task 4: 137a135
```
## Pre-existing Bugs Found (D7)
1. **Grid slots never rendered** — `src/db/grid.ts` keyed `roleBySlug` map by slug but looked up by `slot.roleId` (UUID). Fixed: changed to `roleById` keyed by ID. **NOT YET COMMITTED.**
2. **Editor revert wiped ALL optimistic changes** — `src/components/app/schedule-grid-editor.tsx` line `setDisplay(committed.current)` on failure reverted the entire grid, not just the failed cell. Fixed: revert only the failed cell. **NOT YET COMMITTED.**
## Uncommitted Changes (working tree)
- `src/db/grid.ts` — roleById fix
- `src/components/app/schedule-grid-editor.tsx` — per-cell revert fix
- `e2e/assign-mutations.spec.ts` — E2E test (needs final verification)
- `e2e/_debug.spec.ts` — temporary debug test (can delete)
- `test-results/debug-grid.png` — screenshot (can delete)
## DB State
- 4 service instances (2 Sundays × 2 services)
- 12 slots (3 per instance: Audio, Livestream, Slides)
- 6 users (coordinator, admin, 4 volunteers: Avery Kim, Jordan Reyes, Sam Patel, Taylor Nguyen)
- 3 roles (audio, livestream, slides)
- **Assignments: 4 (Audio only, round-robin)** — seed modified so Livestream + Slides are open for E2E exercise
- Church TZ: America/New_York
- Today: 2026-11-18 (Wed)
## Environment
```
DATABASE_URL=postgres://media:media@localhost:5433/media
NEXTAUTH_SECRET=e2e-secret-for-shell-tests
PORT=3000
```
## Playwright Config
- webServer: `pnpm db:migrate && pnpm build && PORT=3000 pnpm start`
- reuseExistingServer: true
- Single chromium project, retries: 0
## E2E Test (`e2e/assign-mutations.spec.ts`)
Sign in as coordinator → /schedule → clear Audio → assign Avery to Livestream (optimistic) → assign Avery to Slides (rule-1 duplicate → rollback + toast) → verify no console errors.
## Steps for Next Session
### 1. Commit the two bug fixes
```bash
cd /home/bhursey/code/glenlochmedia
git add src/db/grid.ts src/components/app/schedule-grid-editor.tsx
git commit -m "fix(D8): grid slots render + per-cell optimistic revert"
```
### 2. Rebuild + restart app
```bash
# Kill any running server
echo "Linux1981" | sudo -S pkill -9 -f "next-server" 2>/dev/null
echo "Linux1981" | sudo -S pkill -9 -f "next start" 2>/dev/null
sleep 2
# Rebuild
pnpm build 2>&1 | tail -3
# Start
DATABASE_URL="postgres://media:media@localhost:5433/media" \
NEXTAUTH_SECRET="e2e-secret-for-shell-tests" \
PORT=3000 nohup pnpm start > /tmp/app.log 2>&1 &
disown
sleep 9
curl -s http://localhost:3000/api/health
```
### 3. Re-seed DB (if needed)
```bash
DATABASE_URL="postgres://media:media@localhost:5433/media" pnpm db:seed
```
### 4. Run E2E
```bash
cd /home/bhursey/code/glenlochmedia
npx playwright test e2e/assign-mutations.spec.ts 2>&1 | tail -20
```
### 5. If E2E passes — commit + clean up
```bash
git add e2e/assign-mutations.spec.ts
git commit -m "test(D8): Playwright E2E for assign/clear mutations"
rm -f e2e/_debug.spec.ts test-results/debug-grid.png
git add -u
git commit -m "chore: clean up debug files"
```
### 6. Run full suite to confirm nothing broken
```bash
pnpm vitest run # unit tests
pnpm next build # build check
npx playwright test # all E2E (shell + assign-mutations)
```
### 7. Final reviewer check
Branch is master (D3–D7 convention). All commits on master. Ready for review.
## Known Issues / Gotchas
- **`page.request` does NOT share browser cookies** — use `page.evaluate(() => fetch(...))` for session checks, or just rely on the grid rendering as proof of sign-in.
- **`document.cookie` is empty for httpOnly cookies** — can't read session via JS.
- **`pnpm start` uses production build** — source edits require `pnpm build` to take effect.
- **`pnpm build` can hang** — kill with `echo "Linux1981" | sudo -S pkill -9 -f "next-server"`.
- **Grid was always showing "—" for cells** — pre-existing D7 bug (roleBySlug → roleById). Fixed but not committed.
- **Editor revert wiped all optimistic changes** — pre-existing D8 bug. Fixed: per-cell revert.
## Key Files
- `src/db/grid.ts` — grid query (roleById fix)
- `src/components/app/schedule-grid-editor.tsx` — optimistic editor (per-cell revert fix)
- `src/components/app/schedule-grid.tsx` — grid component (client, "use client")
- `src/app/api/assignments/route.ts` — POST /api/assignments (assign/clear)
- `src/db/assignments.ts` — activeAssignmentInInstance()
- `src/domain/assign.ts` — assignHardConflicts() (pure domain)
- `src/db/audit.ts` — auditRow(), writeAudit()
- `src/db/seed.ts` — seed (modified: Audio only)
- `e2e/assign-mutations.spec.ts` — E2E test
@@ -0,0 +1,120 @@
# D8 — Assign / unassign / clear with optimistic update + rollback toast
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Let coordinators assign, unassign, and clear who fills each slot on the D7 schedule grid, with an instant optimistic cell update and a rollback toast when the write is rejected.
**Architecture:** A thin client wrapper around the D7 read-only grid holds optimistic per-cell state, calls a `POST /api/assignments` REST route, and rolls back on non-2xx with a toast. The route guards to coordinators+, enforces the hard conflict rules via the existing D5 conflict engine, writes the assignment (or clears it), and records an audit row.
**Tech Stack:** Next.js App Router (server + client components), postgres.js + Drizzle, vitest (pure domain tests), Playwright (E2E), uuidv7 (client-safe ids).
**Spec:** `docs/superpowers/specs/2026-11-18-d8-assign-mutations-design.md`
## Global Constraints
- BUILD-SPEC §7 rule 1: "A volunteer cannot hold two active assignments in the same service instance."
- BUILD-SPEC §7 rule 2: "One active assignment per slot (DB-enforced)."
- BUILD-SPEC §7 rule 12: "Every admin mutation writes an audit row."
- BUILD-SPEC §7 rule 4 (anti-goal): "Confirmed assignments block deletion — they must be unassigned or swapped"; never a silent delete.
- BUILD-PLAN D8 done-when: "assign → appears immediately; forced failure rolls back with a message."
- D8 sends nothing: notifications belong to E1/D10 — an assignment is `status="proposed"` awaiting the volunteer confirm flow.
- Domain logic lives in `src/domain/**` and never touches the DB; routes/components call it.
- Container: the API route ships in the Next build; the `audit_log` migration is created with `pnpm db:generate`, committed to `drizzle/`, and applied by `pnpm db:migrate` in the `migrate` container.
## Review Focus
1. Assigning a volunteer who already holds an active assignment in the same instance (rule 1) must reject with a clear message and roll back — not silently fail. *(Pinned by `assignHardConflicts` test in Task 2 and the rollback E2E in Task 4.)*
2. Assigning to a slot that already has an active assignment (rule 2, DB unique) must return a clean error, not a 500 or a raw DB dump. *(Pinned by the forced-failure E2E in Task 4.)*
3. An unauthenticated or volunteer request to assign must get 401/403, not 200. *(Pinned by the auth E2E in Task 4.)*
4. A rolled-back assign must revert BOTH the optimistic cell AND leave no half-written row; the toast must show the rejection reason. *(Pinned by the rollback E2E in Task 4.)*
5. Clearing an assignment returns the slot to "Open" and writes an audit row (rule 12). *(Pinned by the clear E2E in Task 4.)*
---
### Task 1: audit_log table + migration + audit-row builder
**Files:**
- Modify: `src/db/schema.ts`
- Create: `drizzle/000X_*.sql` (generated)
- Create: `src/db/audit.ts`
- Test: `src/db/audit.test.ts`
**Interfaces:**
- Consumes: nothing.
- Produces: `writeAudit(db, { actorId, action, entityType, entityId, before?, after? }) -> Promise<audit row>`; pure `auditRow({ actorId, action, entityType, entityId, before?, after?, now? }) -> { id, actorId, action, entityType, entityId, beforeJson, afterJson, createdAt }`.
- [ ] **Step 1: Write the failing test** — in `src/db/audit.test.ts`, assert `auditRow()` returns a row with a uuidv7 `id`, the passed `action`/`entityType`/`entityId`, `createdAt` = the injected `now`, and `beforeJson`/`afterJson` = `JSON.stringify` of the inputs (empty string when omitted).
- [ ] **Step 2: Run test to verify it fails** — run `pnpm vitest run src/db/audit.test.ts`. Expected: FAIL (module / `auditRow` not defined).
- [ ] **Step 3: Implement** — add the `auditLog` table to `src/db/schema.ts` (`id, actorId, actorIpHash, action, entityType, entityId, beforeJson, afterJson, createdAt` per ARCHITECTURE §638; append-only, no app update/delete); add `src/db/audit.ts` with pure `auditRow()` (id via `uuidv7()`, `createdAt` from an injectable `now` for testing) and `writeAudit(db, input)` that inserts it; import `auditLog` into the `schema` export.
- [ ] **Step 4: Run test to verify it passes** — run `pnpm vitest run src/db/audit.test.ts`. Expected: PASS.
- [ ] **Step 5: Generate + commit** — run `pnpm db:generate` (creates `drizzle/000X_*.sql`), `git add` the new SQL + `schema.ts` + `audit.ts` + test, commit.
### Task 2: assign conflict gate (pure, reuse D5)
**Files:**
- Create: `src/domain/assign.ts`
- Test: `src/domain/assign.test.ts`
**Interfaces:**
- Consumes: `type Conflict` from `src/domain/conflicts` (D5).
- Produces: `assignHardConflicts(facts: { alreadyAssignedInInstance: boolean }): Conflict[]` — returns the hard conflicts that block an assign; empty when the assign is allowed.
- [ ] **Step 1: Write the failing test** — in `src/domain/assign.test.ts`, assert `assignHardConflicts({ alreadyAssignedInInstance: false })` returns `[]`, and `assignHardConflicts({ alreadyAssignedInInstance: true })` returns one hard conflict with `code === "duplicate_in_instance"` (the D5 code for §7 rule 1).
- [ ] **Step 2: Run test to verify it fails** — run `pnpm vitest run src/domain/assign.test.ts`. Expected: FAIL (`assignHardConflicts` not defined).
- [ ] **Step 3: Implement** — in `src/domain/assign.ts`, implement `assignHardConflicts()` returning a `Conflict[]` that hard-blocks on `alreadyAssignedInInstance` (rule 1) using the D5 `duplicate_in_instance` code and message; skill gating (rules 6/13) is intentionally out of scope for D8 and stays on the picker.
- [ ] **Step 4: Run test to verify it passes** — run `pnpm vitest run src/domain/assign.test.ts`. Expected: PASS.
- [ ] **Step 5: Commit** — `git add src/domain/assign.ts src/domain/assign.test.ts && git commit -m "domain: assign conflict gate (rule 1 duplicate-in-instance)"`.
### Task 3: assign/clear API route
**Files:**
- Create: `src/db/assignments.ts`
- Create: `src/app/api/assignments/route.ts`
**Interfaces:**
- Consumes: `writeAudit` (Task 1), `assignHardConflicts` (Task 2), `auth`/`requirePermission`/`AuthError` (`src/auth`), `uuidv7` (`src/lib/uuid`), schema `assignments`/`slots`/`serviceInstances`.
- Produces: `POST /api/assignments { action: "assign"|"clear", slotId, userId? }` → `{ ok, id?, status? }` on success, `{ error, code }` on 400/401/403/409/500.
- [ ] **Step 1: Implement the data layer** — in `src/db/assignments.ts`, implement `activeAssignmentInInstance(db, { userId, instanceStart, instanceEnd })`: query `assignments` joined to `serviceInstances` where `userId`, `status IN (proposed,confirmed,completed)`, and `starts_at` within the instance's local-day range; return the row or `null`. (Validated by the Task 5 E2E — the project tests DB/route logic via Playwright, not vitest.)
- [ ] **Step 2: Implement the route** — in `src/app/api/assignments/route.ts`, `POST`: guard with `auth()` + `requirePermission(..., "schedule.publish")` (coordinator+); zod-validate `{ action, slotId, userId? }`; for `assign`, resolve the slot's instance start, call `activeAssignmentInInstance` then `assignHardConflicts`, reject with 409 + the conflict message when hard conflicts exist, else insert an `assignments` row (`id=uuidv7()`, `status="proposed"`, `source="manual"`, `assignedBy=actor.id`, `assignedAt=now`) and write an `assignment.created` audit row, return `{ ok, id, status }`; for `clear`, delete the active assignment for `slotId` and write an `assignment.cleared` audit row, return `{ ok }`. Mirror the `admin/route.ts` error shape (`AuthError` → 401/403).
- [ ] **Step 3: Typecheck** — run `pnpm tsc --noEmit`. Expected: no errors.
- [ ] **Step 4: Commit** — `git add src/db/assignments.ts src/app/api/assignments/route.ts && git commit -m "api: assign/clear route with rule-1 gate + audit"`.
### Task 4: optimistic grid editor + toast
**Files:**
- Create: `src/components/app/toast.tsx`
- Create: `src/components/app/schedule-grid-editor.tsx`
- Modify: `src/app/(app)/schedule/page.tsx`
**Interfaces:**
- Consumes: `ScheduleGrid` + `GridWeek` (`src/components/app/schedule-grid.tsx`, `src/db/grid`), `writeAudit`-free (client only calls the route).
- Produces: `<ScheduleGridEditor week={week} role={systemRole} />` — renders the read-only grid for non-coordinators, or the interactive grid (assign controls + optimistic update + toast) for coordinators/admins.
- [ ] **Step 1: Write the failing test** — (E2E-verified in Task 5; no unit test for client optimistic state.) Skip to Step 2.
- [ ] **Step 2: Implement the toast** — in `src/components/app/toast.tsx`, a `"use client"` minimal toast: a `toast(message, kind)` helper + a fixed-bottom container; `kind` is `"error"` (rollback) or `"success"`.
- [ ] **Step 3: Implement the editor** — in `src/components/app/schedule-grid-editor.tsx`, a `"use client"` component: renders `ScheduleGrid`; each open non-trainee cell gets an "Assign" control listing eligible volunteers; on selection, optimistically render the cell as filled (pending), `POST /api/assignments { action:"assign", slotId, userId }`, on success keep the optimistic cell, on non-2xx revert the cell and show an error toast with the message; an assigned cell gets a "Clear" control that optimistically reverts to "Open", `POST { action:"clear", slotId }`, and rolls back on failure.
- [ ] **Step 4: Wire the page** — in `src/app/(app)/schedule/page.tsx`, call `auth()`, and render `<ScheduleGridEditor>` when the user is coordinator/admin, else the read-only `<ScheduleGrid>` (so the D7 volunteer view is unchanged).
- [ ] **Step 5: Typecheck + lint** — run `pnpm tsc --noEmit` and `pnpm eslint .`. Expected: clean.
- [ ] **Step 6: Commit** — `git add src/components/app/toast.tsx src/components/app/schedule-grid-editor.tsx "src/app/(app)/schedule/page.tsx" && git commit -m "ui: optimistic grid editor with assign/clear + rollback toast"`.
### Task 5: E2E (done-when)
**Files:**
- Create: `e2e/assign-mutations.spec.ts`
**Interfaces:**
- Consumes: the running app (E2E webServer sets `NEXTAUTH_SECRET`); a seeded week with at least one open slot and two active volunteers.
- [ ] **Step 1: Write the failing test** — in `e2e/assign-mutations.spec.ts`: sign in as a coordinator; assert an open slot shows "Open"; click Assign → pick a volunteer; assert the cell shows that volunteer WITHOUT a full page reload (optimistic); assign the same volunteer to the same instance again → assert the cell reverts to "Open" and a toast shows the rule-1 message; clear the first assignment → assert the cell returns to "Open". Capture console + page errors and fail on any.
- [ ] **Step 2: Run test to verify it fails** — run `npx playwright test e2e/assign-mutations.spec.ts`. Expected: FAIL (file / assertions not met).
- [ ] **Step 3: Ensure the app is up** — start with `DATABASE_URL` + `NEXTAUTH_SECRET` set; seed a week with an open slot and two active volunteers if not already seeded.
- [ ] **Step 4: Run test to verify it passes** — run `npx playwright test e2e/assign-mutations.spec.ts`. Expected: PASS, no console errors.
- [ ] **Step 5: Full gate** — run `pnpm tsc --noEmit`, `pnpm eslint .`, `pnpm vitest run`, `pnpm build`, then `npx playwright test e2e/schedule-grid.spec.ts e2e/shell.spec.ts e2e/assign-mutations.spec.ts`. Expected: all green.
- [ ] **Step 6: Commit** — `git add e2e/assign-mutations.spec.ts && git commit -m "e2e: assign/clear optimistic + rollback (D8 done-when)"`.
## Self-Review Notes
- Spec coverage: rule 1 → Task 2 + Task 5; rule 2 → Task 3 (route) + Task 5; rule 12 → Task 1 + Task 3; optimistic + rollback → Task 4 + Task 5; no-notifications → assign defaults to `proposed`/`manual`.
- The D7 read-only E2E (`schedule-grid.spec.ts`) still passes: the editor renders the grid as a subset plus assign controls.
- Skill gating (rules 6/13) is deliberately deferred to the picker; the plan marks it as out of scope for D8's route.
@@ -0,0 +1,56 @@
# D8 — Assign / unassign / clear with optimistic update + rollback toast
**Date:** 2026-11-18
**Phase:** D (Scheduling). Depends on D6 (ranking) + D7 (grid). Feeds D9 (auto-fill) + D10 (publish).
**Size:** M. **Done-when (BUILD-PLAN):** E2E — assign appears immediately; forced failure rolls back with a message; no console errors.
## Intent and why
D7 made the schedule grid **read-only**. D8 turns it into a working scheduling surface: coordinators assign, unassign, and clear who fills each slot, with instant optimistic feedback and a clear rollback when the write is rejected. The data layer already provides the pieces — D6 ranks who can fill a slot, D7 renders the week. D8 writes the `assignments`.
## Goals
- **Assign** a volunteer to a slot: the cell updates instantly (optimistic), the write goes through a REST route, an audit row is written.
- **Unassign / clear**: remove an assignment; the slot returns to `open`.
- **Rollback**: if the write is rejected (a conflict), the cell reverts and a toast shows the reason.
- **Done-when E2E**: assign appears without a full reload; a forced failure (a duplicate-instance assignment) rolls back with a message; no console/page errors.
## Non-goals
- No ranking/picker changes — D6 owns who ranks high.
- No notifications — D10/E1 own that. D8 assigns; it does not tell anyone.
- No bulk-assign UI polish beyond what the done-when needs (the route supports it, the UI can stay single-cell for D8).
## Anti-goals (what would make this a failure even if it "works")
- A **silent delete** when an assignment conflicts (BUILD-SPEC rule 4: never silently drop).
- A full page reload on assign (defeats "optimistic").
- A hard-rule violation slipping through because the toast hid it.
## Constraints
- **Rule 12** — every mutation writes an `audit_log` row. Build the audit table first.
- **Rule 2** — one active assignment per slot is DB-enforced (`uq_active_assignment` on `slot_id` where status IN proposed/confirmed/completed). Already present.
- **Rule 1** — a volunteer cannot hold two active assignments in the same service instance. App-layer check before insert.
- Domain logic lives in `src/domain/**` and never touches the DB from routes/components (ARCHITECTURE §5).
- REST convention: `POST /api/...` with zod validation; routes return JSON.
- **Container**: the API route ships in the Next build; the `audit_log` migration is created with `pnpm db:generate`, committed to `drizzle/`, and applied by `pnpm db:migrate` in the `migrate` container. No extra infra.
## Approaches
- **Client component + REST route + optimistic state** — *chosen*. A thin client wrapper calls `POST /api/assignments`, updates the cell locally before the response, and rolls back on error with a toast. Matches the project's REST convention and makes the done-when directly testable in Playwright.
- Server actions + `useOptimistic` — rejected: diverges from the `/api/...` convention the E2E targets.
- Pure server re-render on mutation — rejected: not truly optimistic (full round-trip flash).
## Decided (their calls)
- REST API approach for the optimistic layer.
## Calls made by the builder (override if you disagree)
- **`audit_log` first**: new table + migration + a small `writeAudit(db, {actor, action, entityType, entityId, before, after})` helper. Append-only; no app update/delete.
- **One route, one action field**: `POST /api/assignments` with `{ action: "assign" | "clear", slotId, userId? }`. Assign creates `status="proposed", source="manual"` (awaiting the volunteer confirm flow); clear deletes the active row (history preserved).
- **API enforces rule 1 + rule 2 + audit.** Skill gating (rules 6/13 — trainee can't fill a `qualified` slot, core-skill-below-required blocks solo) stays on the picker/ranking surface, not the assign API — the coordinator picks from the D6-ranked list. *(See open question below.)*
- **Toast**: a minimal inline toast (no new library).
- **Actor**: the authenticated user's id (coordinator/admin) is the audit `actor_id`; the route guards to coordinator+ roles.
## What's left to the builder
- Optimistic state wiring on the grid cell + rollback on non-2xx.
- The toast.
- The E2E (assign appears; forced duplicate rolls back; no console errors).
- `audit_log` table + migration + helper.
## Open question (needs a yes/no)
Should the **assign API itself** enforce skill gating (rules 6/13), or only the duplicate rules (1/2)? Keeping it to 1/2 keeps D8 focused and puts gating in the picker; enforcing 6/13 in the API makes a manual mis-assign hard-fail. This changes how much domain logic the route carries.
File diff suppressed because it is too large Load Diff
+7
View File
@@ -64,6 +64,13 @@
"when": 1794979809192, "when": 1794979809192,
"tag": "0008_needy_stryfe", "tag": "0008_needy_stryfe",
"breakpoints": true "breakpoints": true
},
{
"idx": 9,
"version": "7",
"when": 1795026324840,
"tag": "0009_last_wallop",
"breakpoints": true
} }
] ]
} }
+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"; import { test, expect } from "@playwright/test";
import { signInAs, resetDb, BASE } from "./dev";
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/);
}
/** /**
* Unit D7 — read-only scheduling grid. Done when: renders a seeded week; no * 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. * logged while the grid is mounted.
*/ */
test.describe("schedule grid", () => { 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 }) => { test("renders a seeded week with no console errors", async ({ page }) => {
const errors: string[] = []; const errors: string[] = [];
page.on("console", (msg) => { page.on("console", (msg) => {
+4 -1
View File
@@ -9,7 +9,10 @@ export default defineConfig({
testDir: "./e2e", testDir: "./e2e",
fullyParallel: true, fullyParallel: true,
retries: process.env.CI ? 2 : 0, retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined, // Serial: both suites share one Postgres and reset it in beforeAll. Parallel
// workers would truncate mid-read (one suite resets while another reads an
// empty grid), so run one file at a time. The suite is tiny (~2s).
workers: 1,
reporter: "list", reporter: "list",
use: { use: {
baseURL: "http://localhost:3000", baseURL: "http://localhost:3000",
+35
View File
@@ -0,0 +1,35 @@
import { auth } from "@/auth/config";
import { AuthError, requirePermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { resetAndSeed } from "@/db/seed";
const JSON_HEADERS = { "content-type": "application/json" };
/**
* Dev console reset. Admin-only (admin.settings): truncates the seed-owned
* tables and repopulates them, so E2E tests start from a known-clean state on
* every run instead of accumulating the mutations of prior runs. Not wired into
* any UI — it exists only for test harnesses.
*/
export const POST = async () => {
try {
const session = await auth();
requirePermission(
(session?.user as { systemRole: SystemRole } | null | undefined),
"admin.settings",
);
await resetAndSeed();
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status: e.status,
headers: JSON_HEADERS,
});
}
throw e;
}
};
+14 -2
View File
@@ -48,13 +48,25 @@ export const authConfig = {
callbacks: { callbacks: {
async jwt({ token, user }) { async jwt({ token, user }) {
if (user) { if (user) {
(token as { systemRole?: SystemRole }).systemRole = // Carry the stable identity + role onto the JWT so the session (which
// only receives `user` on the first callback) can expose `id`/`email`
// for the audit actor. Without this, `session.user.id` is undefined and
// every assign/clear 500s on the audit_log actor_id NOT NULL constraint.
(token as { id?: string; email?: string; systemRole?: SystemRole }).id =
(user as { id?: string }).id;
(token as { id?: string; email?: string; systemRole?: SystemRole }).email =
(user as { email?: string }).email;
(token as { id?: string; email?: string; systemRole?: SystemRole }).systemRole =
(user as { systemRole?: SystemRole }).systemRole ?? "volunteer"; (user as { systemRole?: SystemRole }).systemRole ?? "volunteer";
} }
return token; return token;
}, },
async session({ session, token }) { async session({ session, token }) {
(session.user as { systemRole?: SystemRole }).systemRole = (session.user as { id?: string; email?: string; systemRole?: SystemRole }).id =
(token as { id?: string }).id;
(session.user as { id?: string; email?: string; systemRole?: SystemRole }).email =
(token as { email?: string }).email;
(session.user as { id?: string; email?: string; systemRole?: SystemRole }).systemRole =
(token as { systemRole?: SystemRole }).systemRole ?? "volunteer"; (token as { systemRole?: SystemRole }).systemRole ?? "volunteer";
return session; return session;
}, },
+7 -1
View File
@@ -61,7 +61,13 @@ export function ScheduleGridEditor({
// non-JSON body — fall through to the default message // non-JSON body — fall through to the default message
} }
if (!res.ok) { if (!res.ok) {
setDisplay(committed.current); // Revert only the cell that failed, leaving other optimistic changes intact
const committedSlot = committed.current.instances
.flatMap((i) => i.slots)
.find((s) => s.id === payload.slotId);
setDisplay((prev) =>
withSlotAssignments(prev, payload.slotId, committedSlot?.assignments ?? []),
);
setToast({ message: error ?? "Could not save. Please try again.", kind: "error" }); setToast({ message: error ?? "Could not save. Please try again.", kind: "error" });
} else { } else {
committed.current = display; committed.current = display;
+1 -1
View File
@@ -52,7 +52,7 @@ export function auditRow(input: AuditInput): AuditRow {
/** Insert an audit row via the injected Drizzle client. */ /** Insert an audit row via the injected Drizzle client. */
export async function writeAudit( export async function writeAudit(
db: typeof import("./db").db, db: typeof import("@/db").db,
input: AuditInput, input: AuditInput,
): Promise<AuditRow> { ): Promise<AuditRow> {
const row = auditRow(input); const row = auditRow(input);
+2 -2
View File
@@ -108,7 +108,7 @@ export async function gridForWeek(weekStart: string): Promise<GridWeek> {
name: r.name, name: r.name,
colorHex: r.colorHex, colorHex: r.colorHex,
})); }));
const roleBySlug = new Map(positions.map((p) => [p.slug, p])); const roleById = new Map(roleRows.map((r) => [r.id, r]));
const serviceById = new Map( const serviceById = new Map(
(await db.select().from(services)).map((s) => [s.id, s.name]), (await db.select().from(services)).map((s) => [s.id, s.name]),
@@ -124,7 +124,7 @@ export async function gridForWeek(weekStart: string): Promise<GridWeek> {
const slotsOut: GridSlot[] = []; const slotsOut: GridSlot[] = [];
for (const slot of slotRows) { for (const slot of slotRows) {
const role = roleBySlug.get(slot.roleId); const role = roleById.get(slot.roleId);
const assignRows = await db const assignRows = await db
.select() .select()
.from(assignments) .from(assignments)
+50 -11
View File
@@ -10,6 +10,7 @@
*/ */
import { eq, sql } from "drizzle-orm"; import { eq, sql } from "drizzle-orm";
import { db } from "./index"; import { db } from "./index";
import { fileURLToPath } from "node:url";
import { import {
users, users,
notificationPreferences, notificationPreferences,
@@ -24,7 +25,20 @@ import { localToUtc, nextSundaysInTz } from "../lib/tz";
const CHURCH_TZ = "America/New_York"; const CHURCH_TZ = "America/New_York";
async function main() { // Tables the seed owns. Truncating these (and cascading) gives a clean slate
// for E2E resets without touching schema/migration tables.
const RESET_TABLES = [
"users",
"roles",
"services",
"service_instances",
"slots",
"assignments",
"notification_preferences",
] as const;
/** Populate the core scheduling tables (idempotent: ON CONFLICT DO NOTHING). */
export async function seed() {
/* 1. Roles — production positions (audio, livestream, slides) */ /* 1. Roles — production positions (audio, livestream, slides) */
const roleRows: (typeof roles.$inferInsert)[] = [ const roleRows: (typeof roles.$inferInsert)[] = [
{ {
@@ -173,14 +187,20 @@ async function main() {
console.log(`notification_preferences: ${prefRows.length} seeded`); console.log(`notification_preferences: ${prefRows.length} seeded`);
/* 6. Assignments — one confirmed volunteer per slot (round-robin) */ /* 6. Assignments — one confirmed volunteer per instance (Audio only),
* round-robin across instances. Livestream + Slides are left OPEN so the
* assign picker (unit D8) has open cells and free volunteers to exercise; a
* real published schedule also has open positions. */
const volunteers = userRows2.filter((u) => u.systemRole === "volunteer"); const volunteers = userRows2.filter((u) => u.systemRole === "volunteer");
const assignedRows: (typeof assignments.$inferInsert)[] = []; const assignedRows: (typeof assignments.$inferInsert)[] = [];
for (let i = 0; i < slotRows2.length; i++) { let volIndex = 0;
const vol = volunteers[i % volunteers.length]; for (const slot of slotRows2) {
if (slot.slotIndex !== 1) continue; // Audio only — leave the rest open
const vol = volunteers[volIndex % volunteers.length];
volIndex++;
assignedRows.push({ assignedRows.push({
id: uuidv7(), id: uuidv7(),
slotId: slotRows2[i].id, slotId: slot.id,
userId: vol.id, userId: vol.id,
status: "confirmed", status: "confirmed",
source: "manual", source: "manual",
@@ -209,9 +229,28 @@ async function main() {
console.log("seed complete"); console.log("seed complete");
} }
main() /** Truncate the seed-owned tables, then populate them from scratch. */
.then(() => process.exit(0)) export async function resetAndSeed(): Promise<void> {
.catch((err) => { // The postgres.js driver exposes no typed `.truncate()`, and `sql.ident`
console.error("seed failed:", err); // isn't available on its sql builder, so run TRUNCATE as raw SQL. The table
process.exit(1); // names are a hardcoded safe list, so string interpolation is fine. RESTART
}); // IDENTITY resets sequences; CASCADE drops dependent rows.
const list = RESET_TABLES.join(", ");
await db.execute(sql`TRUNCATE TABLE ${sql.raw(list)} RESTART IDENTITY CASCADE`);
await seed();
}
// Only run the CLI when this file is the entry point (e.g. `pnpm db:seed`),
// not when imported by the app (the /api/dev/reset route). Without this guard
// importing the module would execute the seed and exit the server process.
const isMain =
process.argv[1] !== undefined &&
process.argv[1] === fileURLToPath(import.meta.url);
if (isMain) {
void seed()
.then(() => process.exit(0))
.catch((err) => {
console.error("seed failed:", err);
process.exit(1);
});
}