- 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)
12 KiB
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_logmigration is created withpnpm db:generate, committed todrizzle/, and applied bypnpm db:migratein themigratecontainer.
Review Focus
- 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
assignHardConflictstest in Task 2 and the rollback E2E in Task 4.) - 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.)
- An unauthenticated or volunteer request to assign must get 401/403, not 200. (Pinned by the auth E2E in Task 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.)
- 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>; pureauditRow({ 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, assertauditRow()returns a row with a uuidv7id, the passedaction/entityType/entityId,createdAt= the injectednow, andbeforeJson/afterJson=JSON.stringifyof 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 /auditRownot defined). -
Step 3: Implement — add the
auditLogtable tosrc/db/schema.ts(id, actorId, actorIpHash, action, entityType, entityId, beforeJson, afterJson, createdAtper ARCHITECTURE §638; append-only, no app update/delete); addsrc/db/audit.tswith pureauditRow()(id viauuidv7(),createdAtfrom an injectablenowfor testing) andwriteAudit(db, input)that inserts it; importauditLoginto theschemaexport. -
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(createsdrizzle/000X_*.sql),git addthe 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 Conflictfromsrc/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, assertassignHardConflicts({ alreadyAssignedInInstance: false })returns[], andassignHardConflicts({ alreadyAssignedInInstance: true })returns one hard conflict withcode === "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 (assignHardConflictsnot defined). -
Step 3: Implement — in
src/domain/assign.ts, implementassignHardConflicts()returning aConflict[]that hard-blocks onalreadyAssignedInInstance(rule 1) using the D5duplicate_in_instancecode 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), schemaassignments/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, implementactiveAssignmentInInstance(db, { userId, instanceStart, instanceEnd }): queryassignmentsjoined toserviceInstanceswhereuserId,status IN (proposed,confirmed,completed), andstarts_atwithin the instance's local-day range; return the row ornull. (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 withauth()+requirePermission(..., "schedule.publish")(coordinator+); zod-validate{ action, slotId, userId? }; forassign, resolve the slot's instance start, callactiveAssignmentInInstancethenassignHardConflicts, reject with 409 + the conflict message when hard conflicts exist, else insert anassignmentsrow (id=uuidv7(),status="proposed",source="manual",assignedBy=actor.id,assignedAt=now) and write anassignment.createdaudit row, return{ ok, id, status }; forclear, delete the active assignment forslotIdand write anassignment.clearedaudit row, return{ ok }. Mirror theadmin/route.tserror 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: atoast(message, kind)helper + a fixed-bottom container;kindis"error"(rollback) or"success". -
Step 3: Implement the editor — in
src/components/app/schedule-grid-editor.tsx, a"use client"component: rendersScheduleGrid; 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, callauth(), 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 --noEmitandpnpm 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_SECRETset; 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, thennpx 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.