diff --git a/docs/superpowers/D8-CONTINUATION.md b/docs/superpowers/D8-CONTINUATION.md new file mode 100644 index 0000000..ceaea8a --- /dev/null +++ b/docs/superpowers/D8-CONTINUATION.md @@ -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 # 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`. diff --git a/docs/superpowers/D8-HANDOFF.md b/docs/superpowers/D8-HANDOFF.md new file mode 100644 index 0000000..356ee04 --- /dev/null +++ b/docs/superpowers/D8-HANDOFF.md @@ -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 diff --git a/docs/superpowers/plans/2026-11-18-d8-assign-mutations-plan.md b/docs/superpowers/plans/2026-11-18-d8-assign-mutations-plan.md new file mode 100644 index 0000000..2b2428f --- /dev/null +++ b/docs/superpowers/plans/2026-11-18-d8-assign-mutations-plan.md @@ -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`; 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: `` — 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 `` when the user is coordinator/admin, else the read-only `` (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. diff --git a/docs/superpowers/specs/2026-11-18-d8-assign-mutations-design.md b/docs/superpowers/specs/2026-11-18-d8-assign-mutations-design.md new file mode 100644 index 0000000..086dc53 --- /dev/null +++ b/docs/superpowers/specs/2026-11-18-d8-assign-mutations-design.md @@ -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. diff --git a/drizzle/meta/0009_snapshot.json b/drizzle/meta/0009_snapshot.json new file mode 100644 index 0000000..0930d22 --- /dev/null +++ b/drizzle/meta/0009_snapshot.json @@ -0,0 +1,2543 @@ +{ + "id": "c471ad54-a8c3-42c8-85f5-67e98e9096a3", + "prevId": "b0bafcb2-2d8b-46c5-be51-0019fdb1ed84", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.assignments": { + "name": "assignments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slot_id": { + "name": "slot_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'proposed'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "assigned_by": { + "name": "assigned_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "responded_at": { + "name": "responded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "decline_reason": { + "name": "decline_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "confirmed_via": { + "name": "confirmed_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_count": { + "name": "reminder_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "uq_active_assignment": { + "name": "uq_active_assignment", + "columns": [ + { + "expression": "slot_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"assignments\".\"status\" IN ('proposed','confirmed','completed')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "assignments_user_idx": { + "name": "assignments_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "assignments_slot_id_slots_id_fk": { + "name": "assignments_slot_id_slots_id_fk", + "tableFrom": "assignments", + "tableTo": "slots", + "columnsFrom": [ + "slot_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assignments_user_id_users_id_fk": { + "name": "assignments_user_id_users_id_fk", + "tableFrom": "assignments", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.audit_log": { + "name": "audit_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_ip_hash": { + "name": "actor_ip_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "before_json": { + "name": "before_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "after_json": { + "name": "after_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "audit_log_created_idx": { + "name": "audit_log_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.functions": { + "name": "functions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category_id": { + "name": "category_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "functions_slug_idx": { + "name": "functions_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "functions_active_idx": { + "name": "functions_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "functions_category_idx": { + "name": "functions_category_idx", + "columns": [ + { + "expression": "category_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "functions_category_id_skill_categories_id_fk": { + "name": "functions_category_id_skill_categories_id_fk", + "tableFrom": "functions", + "tableTo": "skill_categories", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "functions_slug_unique": { + "name": "functions_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.growth_goals": { + "name": "growth_goals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_level": { + "name": "target_level", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_date": { + "name": "target_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'requested'" + }, + "mentor_user_id": { + "name": "mentor_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "shadow_count": { + "name": "shadow_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "growth_goals_user_skill_idx": { + "name": "growth_goals_user_skill_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "growth_goals_status_idx": { + "name": "growth_goals_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "growth_goals_user_id_users_id_fk": { + "name": "growth_goals_user_id_users_id_fk", + "tableFrom": "growth_goals", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "growth_goals_skill_id_skills_id_fk": { + "name": "growth_goals_skill_id_skills_id_fk", + "tableFrom": "growth_goals", + "tableTo": "skills", + "columnsFrom": [ + "skill_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "growth_goals_mentor_user_id_users_id_fk": { + "name": "growth_goals_mentor_user_id_users_id_fk", + "tableFrom": "growth_goals", + "tableTo": "users", + "columnsFrom": [ + "mentor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.notification_preferences": { + "name": "notification_preferences", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email_enabled": { + "name": "email_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "sms_enabled": { + "name": "sms_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "sms_consent_at": { + "name": "sms_consent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "sms_consent_source": { + "name": "sms_consent_source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sms_consent_ip": { + "name": "sms_consent_ip", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_lead_days": { + "name": "reminder_lead_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 7 + }, + "quiet_hours_start": { + "name": "quiet_hours_start", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'21:00'" + }, + "quiet_hours_end": { + "name": "quiet_hours_end", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'08:00'" + }, + "digest_only": { + "name": "digest_only", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": {}, + "foreignKeys": { + "notification_preferences_user_id_users_id_fk": { + "name": "notification_preferences_user_id_users_id_fk", + "tableFrom": "notification_preferences", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.position_skills": { + "name": "position_skills", + "schema": "", + "columns": { + "position_id": { + "name": "position_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "weight": { + "name": "weight", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "required_level": { + "name": "required_level", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_core": { + "name": "is_core", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": { + "position_skills_skill_idx": { + "name": "position_skills_skill_idx", + "columns": [ + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "position_skills_position_id_roles_id_fk": { + "name": "position_skills_position_id_roles_id_fk", + "tableFrom": "position_skills", + "tableTo": "roles", + "columnsFrom": [ + "position_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "position_skills_skill_id_skills_id_fk": { + "name": "position_skills_skill_id_skills_id_fk", + "tableFrom": "position_skills", + "tableTo": "skills", + "columnsFrom": [ + "skill_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "position_skills_pk": { + "name": "position_skills_pk", + "columns": [ + "position_id", + "skill_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.roles": { + "name": "roles", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "color_hex": { + "name": "color_hex", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "call_time_offset_minutes": { + "name": "call_time_offset_minutes", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "requires_certification": { + "name": "requires_certification", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "default_headcount": { + "name": "default_headcount", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "roles_slug_idx": { + "name": "roles_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "roles_active_idx": { + "name": "roles_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "roles_slug_unique": { + "name": "roles_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.service_instances": { + "name": "service_instances", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service_id": { + "name": "service_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "occurs_on": { + "name": "occurs_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "is_special": { + "name": "is_special", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "title_override": { + "name": "title_override", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "published_by": { + "name": "published_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "si_service_starts_at_idx": { + "name": "si_service_starts_at_idx", + "columns": [ + { + "expression": "service_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "si_occurs_on_idx": { + "name": "si_occurs_on_idx", + "columns": [ + { + "expression": "occurs_on", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "si_status_idx": { + "name": "si_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "service_instances_service_id_services_id_fk": { + "name": "service_instances_service_id_services_id_fk", + "tableFrom": "service_instances", + "tableTo": "services", + "columnsFrom": [ + "service_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.services": { + "name": "services", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'America/New_York'" + }, + "rrule": { + "name": "rrule", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_time_local": { + "name": "start_time_local", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "duration_minutes": { + "name": "duration_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 75 + }, + "doors_open_minutes_before": { + "name": "doors_open_minutes_before", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "services_active_idx": { + "name": "services_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "services_name_unique": { + "name": "services_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skill_assessments": { + "name": "skill_assessments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "assessor_id": { + "name": "assessor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'admin'" + }, + "level_from": { + "name": "level_from", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "level_to": { + "name": "level_to", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "comfort_at_time": { + "name": "comfort_at_time", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "skill_assessments_user_created_idx": { + "name": "skill_assessments_user_created_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skill_assessments_skill_idx": { + "name": "skill_assessments_skill_idx", + "columns": [ + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "skill_assessments_user_id_users_id_fk": { + "name": "skill_assessments_user_id_users_id_fk", + "tableFrom": "skill_assessments", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_assessments_skill_id_skills_id_fk": { + "name": "skill_assessments_skill_id_skills_id_fk", + "tableFrom": "skill_assessments", + "tableTo": "skills", + "columnsFrom": [ + "skill_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "skill_assessments_assessor_id_users_id_fk": { + "name": "skill_assessments_assessor_id_users_id_fk", + "tableFrom": "skill_assessments", + "tableTo": "users", + "columnsFrom": [ + "assessor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skill_categories": { + "name": "skill_categories", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "color_hex": { + "name": "color_hex", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "skill_categories_slug_idx": { + "name": "skill_categories_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skill_categories_active_idx": { + "name": "skill_categories_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "skill_categories_slug_unique": { + "name": "skill_categories_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.skills": { + "name": "skills", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category_id": { + "name": "category_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "technology_id": { + "name": "technology_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "function_id": { + "name": "function_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "mentor_min_level": { + "name": "mentor_min_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'expert'" + }, + "stale_after_days": { + "name": "stale_after_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 120 + }, + "recert_required": { + "name": "recert_required", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "skills_slug_idx": { + "name": "skills_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skills_active_idx": { + "name": "skills_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "skills_category_idx": { + "name": "skills_category_idx", + "columns": [ + { + "expression": "category_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "skills_category_id_skill_categories_id_fk": { + "name": "skills_category_id_skill_categories_id_fk", + "tableFrom": "skills", + "tableTo": "skill_categories", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "skills_technology_id_technologies_id_fk": { + "name": "skills_technology_id_technologies_id_fk", + "tableFrom": "skills", + "tableTo": "technologies", + "columnsFrom": [ + "technology_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "skills_function_id_functions_id_fk": { + "name": "skills_function_id_functions_id_fk", + "tableFrom": "skills", + "tableTo": "functions", + "columnsFrom": [ + "function_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "skills_slug_unique": { + "name": "skills_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "skills_dedupe_key_unique": { + "name": "skills_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slots": { + "name": "slots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service_instance_id": { + "name": "service_instance_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slot_index": { + "name": "slot_index", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "call_time": { + "name": "call_time", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "slot_note": { + "name": "slot_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_trainee_slot": { + "name": "is_trainee_slot", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "paired_with_user_id": { + "name": "paired_with_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "slots_instance_role_idx": { + "name": "slots_instance_role_idx", + "columns": [ + { + "expression": "service_instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "role_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "slot_index", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slots_status_idx": { + "name": "slots_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slots_service_instance_id_service_instances_id_fk": { + "name": "slots_service_instance_id_service_instances_id_fk", + "tableFrom": "slots", + "tableTo": "service_instances", + "columnsFrom": [ + "service_instance_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slots_role_id_roles_id_fk": { + "name": "slots_role_id_roles_id_fk", + "tableFrom": "slots", + "tableTo": "roles", + "columnsFrom": [ + "role_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "slots_paired_with_user_id_users_id_fk": { + "name": "slots_paired_with_user_id_users_id_fk", + "tableFrom": "slots", + "tableTo": "users", + "columnsFrom": [ + "paired_with_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "chk_slots_single_parent": { + "name": "chk_slots_single_parent", + "value": "(service_instance_id IS NOT NULL) <> (event_id IS NOT NULL)" + }, + "chk_shadow_paired": { + "name": "chk_shadow_paired", + "value": "not is_trainee_slot or paired_with_user_id is not null" + } + }, + "isRLSEnabled": false + }, + "public.technologies": { + "name": "technologies", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "vendor_id": { + "name": "vendor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category_id": { + "name": "category_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model_number": { + "name": "model_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "version_label": { + "name": "version_label", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "docs_url": { + "name": "docs_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "purchased_on": { + "name": "purchased_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "serial_number": { + "name": "serial_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "retired_at": { + "name": "retired_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "successor_technology_id": { + "name": "successor_technology_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "technologies_slug_idx": { + "name": "technologies_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "technologies_active_idx": { + "name": "technologies_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "technologies_vendor_idx": { + "name": "technologies_vendor_idx", + "columns": [ + { + "expression": "vendor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "technologies_category_idx": { + "name": "technologies_category_idx", + "columns": [ + { + "expression": "category_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "technologies_vendor_id_vendors_id_fk": { + "name": "technologies_vendor_id_vendors_id_fk", + "tableFrom": "technologies", + "tableTo": "vendors", + "columnsFrom": [ + "vendor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "technologies_category_id_skill_categories_id_fk": { + "name": "technologies_category_id_skill_categories_id_fk", + "tableFrom": "technologies", + "tableTo": "skill_categories", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "technologies_slug_unique": { + "name": "technologies_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.unavailability": { + "name": "unavailability", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'blackout'" + }, + "starts_on": { + "name": "starts_on", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "ends_on": { + "name": "ends_on", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "all_day": { + "name": "all_day", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rrule": { + "name": "rrule", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "uq_unavailability_range": { + "name": "uq_unavailability_range", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_on", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "ends_on", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"unavailability\".\"status\" = 'active'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "unavailability_user_idx": { + "name": "unavailability_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "unavailability_user_id_users_id_fk": { + "name": "unavailability_user_id_users_id_fk", + "tableFrom": "unavailability", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "chk_unavailability_span": { + "name": "chk_unavailability_span", + "value": "\"unavailability\".\"ends_on\" >= \"unavailability\".\"starts_on\"" + }, + "chk_unavailability_max_span": { + "name": "chk_unavailability_max_span", + "value": "\"unavailability\".\"ends_on\" - \"unavailability\".\"starts_on\" <= 365" + } + }, + "isRLSEnabled": false + }, + "public.user_skills": { + "name": "user_skills", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "skill_id": { + "name": "skill_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "self_comfort": { + "name": "self_comfort", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "self_rated_at": { + "name": "self_rated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "verified_level": { + "name": "verified_level", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "verified_by": { + "name": "verified_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "verified_at": { + "name": "verified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "mentor_opt_in": { + "name": "mentor_opt_in", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "last_served_on": { + "name": "last_served_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "user_skills_user_skill_idx": { + "name": "user_skills_user_skill_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_skills_skill_idx": { + "name": "user_skills_skill_idx", + "columns": [ + { + "expression": "skill_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_skills_user_id_users_id_fk": { + "name": "user_skills_user_id_users_id_fk", + "tableFrom": "user_skills", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_skills_skill_id_skills_id_fk": { + "name": "user_skills_skill_id_skills_id_fk", + "tableFrom": "user_skills", + "tableTo": "skills", + "columnsFrom": [ + "skill_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "phone_e164": { + "name": "phone_e164", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "first_name": { + "name": "first_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_name": { + "name": "last_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "system_role": { + "name": "system_role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'volunteer'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending_approval'" + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'America/New_York'" + }, + "emergency_contact": { + "name": "emergency_contact", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_by": { + "name": "approved_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_at": { + "name": "approved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_served_at": { + "name": "last_served_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "reliability_score": { + "name": "reliability_score", + "type": "numeric(5, 2)", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "deactivated_at": { + "name": "deactivated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "users_email_lower_idx": { + "name": "users_email_lower_idx", + "columns": [ + { + "expression": "lower(\"email\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_status_idx": { + "name": "users_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_system_role_idx": { + "name": "users_system_role_idx", + "columns": [ + { + "expression": "system_role", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_email_unique": { + "name": "users_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.vendors": { + "name": "vendors", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "support_url": { + "name": "support_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "support_phone": { + "name": "support_phone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "vendors_slug_idx": { + "name": "vendors_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "vendors_active_idx": { + "name": "vendors_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "vendors_slug_unique": { + "name": "vendors_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index e0dbd37..fd71a50 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -64,6 +64,13 @@ "when": 1794979809192, "tag": "0008_needy_stryfe", "breakpoints": true + }, + { + "idx": 9, + "version": "7", + "when": 1795026324840, + "tag": "0009_last_wallop", + "breakpoints": true } ] } \ No newline at end of file diff --git a/e2e/assign-mutations.spec.ts b/e2e/assign-mutations.spec.ts new file mode 100644 index 0000000..7ab388d --- /dev/null +++ b/e2e/assign-mutations.spec.ts @@ -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 per position, in the same order as the + * 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 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 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( + [], + ); + }); +}); diff --git a/e2e/dev.ts b/e2e/dev.ts new file mode 100644 index 0000000..12162ab --- /dev/null +++ b/e2e/dev.ts @@ -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 }; diff --git a/e2e/schedule-grid.spec.ts b/e2e/schedule-grid.spec.ts index 01a5471..fa9b76a 100644 --- a/e2e/schedule-grid.spec.ts +++ b/e2e/schedule-grid.spec.ts @@ -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) => { diff --git a/playwright.config.ts b/playwright.config.ts index 1a2c711..039e8b1 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -9,7 +9,10 @@ export default defineConfig({ testDir: "./e2e", fullyParallel: true, 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", use: { baseURL: "http://localhost:3000", diff --git a/src/app/api/dev/reset/route.ts b/src/app/api/dev/reset/route.ts new file mode 100644 index 0000000..6ddbd94 --- /dev/null +++ b/src/app/api/dev/reset/route.ts @@ -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; + } +}; diff --git a/src/auth/config.ts b/src/auth/config.ts index 50a733c..ec31118 100644 --- a/src/auth/config.ts +++ b/src/auth/config.ts @@ -48,13 +48,25 @@ export const authConfig = { callbacks: { async jwt({ token, 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"; } return 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"; return session; }, diff --git a/src/components/app/schedule-grid-editor.tsx b/src/components/app/schedule-grid-editor.tsx index 428080a..df50ac7 100644 --- a/src/components/app/schedule-grid-editor.tsx +++ b/src/components/app/schedule-grid-editor.tsx @@ -61,7 +61,13 @@ export function ScheduleGridEditor({ // non-JSON body — fall through to the default message } 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" }); } else { committed.current = display; diff --git a/src/db/audit.ts b/src/db/audit.ts index 2d10885..8574dd0 100644 --- a/src/db/audit.ts +++ b/src/db/audit.ts @@ -52,7 +52,7 @@ export function auditRow(input: AuditInput): AuditRow { /** Insert an audit row via the injected Drizzle client. */ export async function writeAudit( - db: typeof import("./db").db, + db: typeof import("@/db").db, input: AuditInput, ): Promise { const row = auditRow(input); diff --git a/src/db/grid.ts b/src/db/grid.ts index d269671..bb79111 100644 --- a/src/db/grid.ts +++ b/src/db/grid.ts @@ -108,7 +108,7 @@ export async function gridForWeek(weekStart: string): Promise { name: r.name, 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( (await db.select().from(services)).map((s) => [s.id, s.name]), @@ -124,7 +124,7 @@ export async function gridForWeek(weekStart: string): Promise { const slotsOut: GridSlot[] = []; for (const slot of slotRows) { - const role = roleBySlug.get(slot.roleId); + const role = roleById.get(slot.roleId); const assignRows = await db .select() .from(assignments) diff --git a/src/db/seed.ts b/src/db/seed.ts index 8aa56f7..c5cf4c3 100644 --- a/src/db/seed.ts +++ b/src/db/seed.ts @@ -10,6 +10,7 @@ */ import { eq, sql } from "drizzle-orm"; import { db } from "./index"; +import { fileURLToPath } from "node:url"; import { users, notificationPreferences, @@ -24,7 +25,20 @@ import { localToUtc, nextSundaysInTz } from "../lib/tz"; 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) */ const roleRows: (typeof roles.$inferInsert)[] = [ { @@ -173,14 +187,20 @@ async function main() { 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 assignedRows: (typeof assignments.$inferInsert)[] = []; - for (let i = 0; i < slotRows2.length; i++) { - const vol = volunteers[i % volunteers.length]; + let volIndex = 0; + 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({ id: uuidv7(), - slotId: slotRows2[i].id, + slotId: slot.id, userId: vol.id, status: "confirmed", source: "manual", @@ -209,9 +229,28 @@ async function main() { console.log("seed complete"); } -main() - .then(() => process.exit(0)) - .catch((err) => { - console.error("seed failed:", err); - process.exit(1); - }); +/** Truncate the seed-owned tables, then populate them from scratch. */ +export async function resetAndSeed(): Promise { + // The postgres.js driver exposes no typed `.truncate()`, and `sql.ident` + // isn't available on its sql builder, so run TRUNCATE as raw SQL. The table + // 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); + }); +}