From 98cc7c4ac9454cfc8c1ab1501caef1cf60342d52 Mon Sep 17 00:00:00 2001 From: weeihan Date: Wed, 14 Oct 2026 11:05:57 +0800 Subject: [PATCH] docs: implementation plan for zone picker, CAPA proof, cleanup Co-Authored-By: Claude Sonnet 5.5 --- .../2026-10-14-zone-capa-proof-cleanup.md | 1119 +++++++++++++++++ 1 file changed, 1119 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-14-zone-capa-proof-cleanup.md diff --git a/docs/superpowers/plans/2026-10-14-zone-capa-proof-cleanup.md b/docs/superpowers/plans/2026-10-14-zone-capa-proof-cleanup.md new file mode 100644 index 0000000..cbe413f --- /dev/null +++ b/docs/superpowers/plans/2026-10-14-zone-capa-proof-cleanup.md @@ -0,0 +1,1119 @@ +# Zone Picker, CAPA Completion Proof, Test-Data Cleanup Implementation Plan + +> **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 users report an incident without a QR scan by picking site and zone, force PICs to attach photo proof and a note when submitting a CAPA for verification, and give ops a safe script to wipe test data. + +**Architecture:** Zone picker is client-side only: `/report` passes site/zone options to `ReportForm`, which resolves a `zone_token` for the unchanged `POST /api/incidents`. CAPA proof adds one multipart endpoint `POST /api/capa/[id]/submit` as the only way to reach `pending_verification` (PATCH blocks it), storing photos as `evidence_files` rows linked by a new `capa_id` column. Cleanup is a one-off SQL script with a dry-run and a manual confirm step. + +**Tech Stack:** Next.js 16 App Router, Drizzle ORM + `pg`, PostgreSQL with RLS, vitest (+ Testing Library), Tailwind tokens, `components/ui/*`. + +## Global Constraints + +Spec: `docs/superpowers/specs/2026-10-14-zone-capa-proof-cleanup-design.md`. + +- Never run `next build`, `pnpm build` or `npm ci` on the server. Never overwrite, delete or ship `.env*`. +- Schema changes: edit `db/schema.sql` / `db/rls.sql` and `lib/db/schema.ts`, apply by hand to the server DB only with the owner's go-ahead. A deploy never runs migrations. +- Every DB mutation writes `audit_log` in the same transaction (`withUser` + `writeAuditLog`). +- Evidence files are never hard-deleted (5-year retention). Cleanup leaves files on disk. +- Use `components/ui/*` and design tokens (`text-muted`, `text-danger`, `bg-surface`, …); no hard-coded hex, no 2px borders. `npm run check:design` must print `design gates: clean`. +- Run `graphify update .` after code changes. +- Commit message trailer: `Co-Authored-By: Claude Sonnet 5.5 `. +- Tests: `npx vitest run `. Route tests that build `Request` with `FormData` need `// @vitest-environment node` on the first line. + +## File Structure + +| File | Action | Responsibility | +|---|---|---| +| `lib/report/zones.ts` | Create | Pure helpers: group zone rows into sites, filter zones by site, resolve the `zone_token` to send | +| `tests/lib/report/zones.test.ts` | Create | Tests for the helpers | +| `app/report/page.tsx` | Modify | Load sites/zones and user's default site, drop "No zone detected" banner | +| `components/incidents/report-form.tsx` | Modify | Site/Zone selects, use resolved token, gate submit | +| `messages/en.json`, `ms.json`, `zh.json` | Modify | `siteLabel`, `sitePlaceholder`, `zoneLabel`, `zonePlaceholder` in `ReportForm` | +| `db/ops/2026-10-14-evidence-capa-id.sql` | Create | Hand-applied migration for `evidence_files.capa_id` | +| `db/schema.sql`, `lib/db/schema.ts` | Modify | Add `capa_id` column + index | +| `lib/capa/submit-validation.ts` | Create | Pure validation of note + photos, shared by client and server | +| `tests/lib/capa/submit-validation.test.ts` | Create | Tests for validation | +| `app/api/capa/[id]/submit/route.ts` | Create | Multipart submit endpoint | +| `tests/api/capa-submit.test.ts` | Create | Route tests | +| `app/api/capa/[id]/route.ts` | Modify | PATCH rejects `pending_verification` | +| `tests/api/capa-patch.test.ts` | Create | PATCH bypass test | +| `components/capa/submit-verification-form.tsx` | Create | Note + photo form for the PIC | +| `components/capa/capa-owner-actions.tsx` | Modify | Render the form for `in_progress` | +| `tests/components/capa/submit-verification-form.test.tsx` | Create | Form gating test | +| `app/(protected)/hse/capa/[id]/page.tsx` | Modify | Photo gallery in "Completion report" | +| `db/ops/cleanup-test-data.sql` | Create | Dry-run + delete script | +| `docs/runbooks/cleanup-test-data.md` | Create | Backup/dry-run/confirm/run steps | +| `docs/superpowers/specs/2026-10-14-zone-capa-proof-cleanup-design.md` | Modify | Remove wrong "notification kept" claim | + +--- + +### Task 1: Zone picker on `/report` + +**Files:** +- Create: `lib/report/zones.ts`, `tests/lib/report/zones.test.ts` +- Modify: `app/report/page.tsx`, `components/incidents/report-form.tsx`, `messages/en.json`, `messages/ms.json`, `messages/zh.json` + +**Interfaces:** +- Produces (`lib/report/zones.ts`): + - `type ZoneOption = { id: string; name: string; qr_code_token: string }` + - `type SiteOption = { id: string; name: string; zones: ZoneOption[] }` + - `type ZoneRow = { siteId: string; siteName: string; zoneId: string; zoneName: string; token: string }` + - `groupSites(rows: ZoneRow[]): SiteOption[]` (keeps row order, sites with no rows are absent) + - `zonesForSite(sites: SiteOption[], siteId: string): ZoneOption[]` + - `resolveZoneToken(args: { zoneToken: string | null; sites: SiteOption[]; zoneId: string }): string | null` (QR token wins; else token of the chosen zone; else `null`) + +- [ ] **Step 1: Write the failing tests** + +`tests/lib/report/zones.test.ts`: + +```ts +import { describe, it, expect } from 'vitest' +import { groupSites, zonesForSite, resolveZoneToken, type ZoneRow } from '@/lib/report/zones' + +const rows: ZoneRow[] = [ + { siteId: 's1', siteName: 'SC1', zoneId: 'z1', zoneName: 'Dock A', token: 'tok-a' }, + { siteId: 's1', siteName: 'SC1', zoneId: 'z2', zoneName: 'Dock B', token: 'tok-b' }, + { siteId: 's2', siteName: 'SC2', zoneId: 'z3', zoneName: 'Cold Room', token: 'tok-c' }, +] + +describe('groupSites', () => { + it('groups zone rows under their site, keeping order', () => { + const sites = groupSites(rows) + expect(sites.map(s => s.name)).toEqual(['SC1', 'SC2']) + expect(sites[0].zones.map(z => z.name)).toEqual(['Dock A', 'Dock B']) + expect(sites[1].zones[0]).toEqual({ id: 'z3', name: 'Cold Room', qr_code_token: 'tok-c' }) + }) + + it('returns [] for no rows', () => { + expect(groupSites([])).toEqual([]) + }) +}) + +describe('zonesForSite', () => { + const sites = groupSites(rows) + it('returns the zones of the given site', () => { + expect(zonesForSite(sites, 's2').map(z => z.id)).toEqual(['z3']) + }) + it('returns [] for an unknown or empty site id', () => { + expect(zonesForSite(sites, 'nope')).toEqual([]) + expect(zonesForSite(sites, '')).toEqual([]) + }) +}) + +describe('resolveZoneToken', () => { + const sites = groupSites(rows) + it('prefers the QR token', () => { + expect(resolveZoneToken({ zoneToken: 'qr-1', sites, zoneId: 'z1' })).toBe('qr-1') + }) + it('falls back to the selected zone token', () => { + expect(resolveZoneToken({ zoneToken: null, sites, zoneId: 'z2' })).toBe('tok-b') + }) + it('returns null when nothing is chosen or the zone is unknown', () => { + expect(resolveZoneToken({ zoneToken: null, sites, zoneId: '' })).toBeNull() + expect(resolveZoneToken({ zoneToken: null, sites, zoneId: 'zz' })).toBeNull() + }) +}) +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `npx vitest run tests/lib/report/zones.test.ts` +Expected: FAIL, cannot resolve `@/lib/report/zones`. + +- [ ] **Step 3: Implement the helpers** + +`lib/report/zones.ts`: + +```ts +export type ZoneOption = { id: string; name: string; qr_code_token: string } +export type SiteOption = { id: string; name: string; zones: ZoneOption[] } +export type ZoneRow = { siteId: string; siteName: string; zoneId: string; zoneName: string; token: string } + +export function groupSites(rows: ZoneRow[]): SiteOption[] { + const bySite = new Map() + for (const r of rows) { + let site = bySite.get(r.siteId) + if (!site) { + site = { id: r.siteId, name: r.siteName, zones: [] } + bySite.set(r.siteId, site) + } + site.zones.push({ id: r.zoneId, name: r.zoneName, qr_code_token: r.token }) + } + return [...bySite.values()] +} + +export function zonesForSite(sites: SiteOption[], siteId: string): ZoneOption[] { + return sites.find(s => s.id === siteId)?.zones ?? [] +} + +export function resolveZoneToken(args: { + zoneToken: string | null + sites: SiteOption[] + zoneId: string +}): string | null { + if (args.zoneToken) return args.zoneToken + for (const site of args.sites) { + const zone = site.zones.find(z => z.id === args.zoneId) + if (zone) return zone.qr_code_token + } + return null +} +``` + +- [ ] **Step 4: Run to verify it passes** + +Run: `npx vitest run tests/lib/report/zones.test.ts` +Expected: PASS (7 tests). + +- [ ] **Step 5: Add i18n keys** + +In each of `messages/en.json`, `messages/ms.json`, `messages/zh.json`, inside `"ReportForm"` after `"truckPlaceholder"` (add a comma to that line): + +en: +```json + "truckPlaceholder": "Select truck…", + "siteLabel": "Site", + "sitePlaceholder": "Select site…", + "zoneLabel": "Zone", + "zonePlaceholder": "Select zone…" +``` +ms: +```json + "truckPlaceholder": "Pilih trak…", + "siteLabel": "Tapak", + "sitePlaceholder": "Pilih tapak…", + "zoneLabel": "Zon", + "zonePlaceholder": "Pilih zon…" +``` +zh: +```json + "truckPlaceholder": "选择货车…", + "siteLabel": "场地", + "sitePlaceholder": "选择场地…", + "zoneLabel": "区域", + "zonePlaceholder": "选择区域…" +``` + +Run: `npx vitest run tests/lib/i18n/translations.test.ts` +Expected: PASS (key parity). + +- [ ] **Step 6: Load sites/zones in the page and drop the banner** + +`app/report/page.tsx` edits: + +1. Imports: change to +```ts +import { zones, sites, trucks, users } from '@/lib/db/schema' +import { eq, asc, and } from 'drizzle-orm' +import { groupSites } from '@/lib/report/zones' +``` +2. After the `truckList` block, add: +```ts + const zoneRows = await asAdmin(db => + db.select({ + siteId: sites.id, + siteName: sites.name, + zoneId: zones.id, + zoneName: zones.name, + token: zones.qrCodeToken, + }) + .from(zones) + .innerJoin(sites, eq(zones.siteId, sites.id)) + .where(and(eq(zones.active, true), eq(sites.active, true))) + .orderBy(asc(sites.name), asc(zones.name)) + ) + const siteOptions = groupSites(zoneRows) + + const [me] = await asAdmin(db => + db.select({ siteId: users.siteId }).from(users).where(eq(users.id, session.sub)).limit(1) + ) + const defaultSiteId = me?.siteId ?? '' +``` +3. Replace the `zoneName ? (...) : (

No zone detected…

)` block with only the QR case: +```tsx + {zoneName && ( +

+ {siteName ?? 'Unknown Site'} — {zoneName} +

+ )} +``` +4. Update the `` props: +```tsx + +``` +(An unknown `?zone=` token now passes `null`, so the picker shows.) + +- [ ] **Step 7: Add the selects and token resolution to `ReportForm`** + +`components/incidents/report-form.tsx` edits: + +1. Import: `import { zonesForSite, resolveZoneToken, type SiteOption } from '@/lib/report/zones'` +2. Props interface add `sites: SiteOption[]` and `defaultSiteId: string`; signature becomes `export function ReportForm({ zoneToken, sites, defaultSiteId, trucks, initialTruckId }: Props)`. +3. After the `useState` hooks (before the `form` state), add: +```ts + const [siteId, setSiteId] = useState( + sites.some(s => s.id === defaultSiteId) ? defaultSiteId : (sites.length === 1 ? sites[0].id : '') + ) + const [zoneId, setZoneId] = useState('') + const effectiveZoneToken = resolveZoneToken({ zoneToken, sites, zoneId }) +``` +4. Offline payload: replace `zone_token: zoneToken ?? '',` with `zone_token: effectiveZoneToken ?? '',`. +5. Online FormData: replace `if (zoneToken) fd.append('zone_token', zoneToken)` with `if (effectiveZoneToken) fd.append('zone_token', effectiveZoneToken)`. +6. Just before the "Incident type" `
` (after the `{error && …}` block), insert: +```tsx + {!zoneToken && ( +
+
+ + +
+
+ + +
+
+ )} +``` +7. Submit button `disabled`: change to +```tsx + disabled={submitting || !effectiveZoneToken || !form.incident_type || (form.incident_type === 'transport' && !form.truck_id)} +``` + +- [ ] **Step 8: Verify** + +Run: `npx tsc --noEmit` — Expected: no errors. +Run: `npx vitest run tests/lib/report tests/lib/i18n` — Expected: PASS. +Run: `npm run check:design` — Expected: `design gates: clean`. +Manual (dev server `npm run dev`): open `/report` with no query → site/zone selects show, no banner, submit disabled until zone chosen; open `/report?zone=` → header "Site — Zone", no selects, submit works as before. + +- [ ] **Step 9: Commit** + +```bash +git add lib/report tests/lib/report app/report/page.tsx components/incidents/report-form.tsx messages +git commit -m "feat(report): site and zone picker when no QR zone is detected + +Co-Authored-By: Claude Sonnet 5.5 " +``` + +--- + +### Task 2: CAPA submit endpoint and schema + +**Files:** +- Create: `db/ops/2026-10-14-evidence-capa-id.sql`, `lib/capa/submit-validation.ts`, `tests/lib/capa/submit-validation.test.ts`, `app/api/capa/[id]/submit/route.ts`, `tests/api/capa-submit.test.ts`, `tests/api/capa-patch.test.ts` +- Modify: `db/schema.sql:142-154`, `lib/db/schema.ts:138-148`, `app/api/capa/[id]/route.ts` + +**Interfaces:** +- Produces (`lib/capa/submit-validation.ts`): + - `const MAX_CAPA_PHOTOS = 5` + - `validateCapaSubmission(note: string, files: ReadonlyArray<{ type: string }>): { ok: true; note: string } | { ok: false; errors: string[] }` (note is trimmed; needs non-empty note, 1 to 5 files, every file `type` starts with `image/`) +- Produces (API): `POST /api/capa/[id]/submit`, multipart fields `note` (string) and `files` (1 to 5 images). Responses: 200 `{ ok: true }`, 401, 403, 404, 409 `{ error }`, 422 `{ error, details: string[] }`. +- Consumes: `uploadEvidenceFile(file, incidentId, 'capa', userId)` from `lib/storage/evidence.ts` returning `{ path, publicUrl, hash }`; `writeAuditLog(tx, table, id, action, newValue?, oldValue?)`; `withUser(userId, fn)`. + +- [ ] **Step 1: Write the failing validation test** + +`tests/lib/capa/submit-validation.test.ts`: + +```ts +import { describe, it, expect } from 'vitest' +import { validateCapaSubmission, MAX_CAPA_PHOTOS } from '@/lib/capa/submit-validation' + +const img = { type: 'image/jpeg' } + +describe('validateCapaSubmission', () => { + it('accepts a note with 1 image and trims the note', () => { + expect(validateCapaSubmission(' done ', [img])).toEqual({ ok: true, note: 'done' }) + }) + it('rejects an empty or whitespace note', () => { + const r = validateCapaSubmission(' ', [img]) + expect(r.ok).toBe(false) + if (!r.ok) expect(r.errors).toContain('Completion note is required') + }) + it('rejects zero files', () => { + const r = validateCapaSubmission('done', []) + expect(r.ok).toBe(false) + if (!r.ok) expect(r.errors).toContain('At least 1 photo is required') + }) + it('rejects more than the max', () => { + const r = validateCapaSubmission('done', Array(MAX_CAPA_PHOTOS + 1).fill(img)) + expect(r.ok).toBe(false) + if (!r.ok) expect(r.errors).toContain(`At most ${MAX_CAPA_PHOTOS} photos are allowed`) + }) + it('rejects non-image files', () => { + const r = validateCapaSubmission('done', [{ type: 'application/pdf' }]) + expect(r.ok).toBe(false) + if (!r.ok) expect(r.errors).toContain('Only image files are allowed') + }) +}) +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `npx vitest run tests/lib/capa/submit-validation.test.ts` +Expected: FAIL, module not found. + +- [ ] **Step 3: Implement validation** + +`lib/capa/submit-validation.ts`: + +```ts +export const MAX_CAPA_PHOTOS = 5 + +export type CapaSubmissionResult = + | { ok: true; note: string } + | { ok: false; errors: string[] } + +export function validateCapaSubmission( + note: string, + files: ReadonlyArray<{ type: string }>, +): CapaSubmissionResult { + const errors: string[] = [] + const trimmed = note.trim() + if (!trimmed) errors.push('Completion note is required') + if (files.length < 1) errors.push('At least 1 photo is required') + if (files.length > MAX_CAPA_PHOTOS) errors.push(`At most ${MAX_CAPA_PHOTOS} photos are allowed`) + if (files.some(f => !f.type.startsWith('image/'))) errors.push('Only image files are allowed') + return errors.length ? { ok: false, errors } : { ok: true, note: trimmed } +} +``` + +- [ ] **Step 4: Run to verify it passes** + +Run: `npx vitest run tests/lib/capa/submit-validation.test.ts` +Expected: PASS (5 tests). + +- [ ] **Step 5: Schema change files** + +`db/ops/2026-10-14-evidence-capa-id.sql`: + +```sql +-- Apply by hand on the server DB with the owner's go-ahead. Not run by deploy. +BEGIN; +ALTER TABLE evidence_files ADD COLUMN IF NOT EXISTS capa_id UUID REFERENCES capa_actions(id) ON DELETE RESTRICT; +CREATE INDEX IF NOT EXISTS evidence_files_capa_id_idx ON evidence_files(capa_id); +COMMIT; +``` + +`db/schema.sql`: `capa_actions` is created after `evidence_files`, so do not touch `CREATE TABLE evidence_files`. Right after the `capa_actions` table definition (and its indexes, if any) add: +```sql +ALTER TABLE evidence_files ADD COLUMN capa_id UUID REFERENCES capa_actions(id) ON DELETE RESTRICT; +CREATE INDEX evidence_files_capa_id_idx ON evidence_files(capa_id); +``` + +`lib/db/schema.ts`: `capaActions` is defined after `evidenceFiles`, so reference it lazily. In `evidenceFiles` add after `deleted`: +```ts + capaId: uuid('capa_id').references((): AnyPgColumn => capaActions.id), +``` +and add `AnyPgColumn` to the `drizzle-orm/pg-core` import at the top of the file. + +Run: `npx tsc --noEmit` — Expected: no errors. + +RLS: no change. `evidence_insert` needs `uploaded_by = app_current_user_id()` (the PIC), and `evidence_read_uploader` lets the PIC read their own rows; hse/admin/management/supervisor read via `evidence_read_elevated`. + +- [ ] **Step 6: Write the failing route tests** + +`tests/api/capa-submit.test.ts`: + +```ts +// @vitest-environment node +import { describe, it, expect, vi, beforeEach } from 'vitest' + +const h = vi.hoisted(() => ({ + session: null as null | { sub: string; role: string }, + capa: null as null | { incidentId: string; ownerUserId: string; status: string }, + updates: [] as unknown[], + inserts: [] as unknown[], +})) + +vi.mock('@/lib/auth/get-session', () => ({ getSession: async () => h.session })) +vi.mock('@/lib/db/audit', () => ({ writeAuditLog: vi.fn() })) +vi.mock('@/lib/storage/evidence', () => ({ + uploadEvidenceFile: vi.fn(async () => ({ path: 'p', publicUrl: '/api/evidence/p?token=t', hash: 'h' })), +})) +vi.mock('@/lib/db/with-user', () => ({ + withUser: async (_id: string, fn: (tx: unknown) => unknown) => { + const tx = { + select: () => ({ from: () => ({ where: () => ({ limit: async () => (h.capa ? [h.capa] : []) }) }) }), + insert: () => ({ values: (v: unknown) => { h.inserts.push(v); return { returning: async () => [{ id: 'ev-1' }] } } }), + update: () => ({ set: (v: unknown) => { h.updates.push(v); return { where: async () => undefined } } }), + } + return fn(tx) + }, +})) + +import { writeAuditLog } from '@/lib/db/audit' +import { POST } from '@/app/api/capa/[id]/submit/route' + +function req(note: string | null, fileCount: number) { + const fd = new FormData() + if (note !== null) fd.append('note', note) + for (let i = 0; i < fileCount; i++) fd.append('files', new File(['x'], `p${i}.jpg`, { type: 'image/jpeg' })) + return new Request('http://localhost/api/capa/capa-1/submit', { method: 'POST', body: fd }) +} +const ctx = { params: Promise.resolve({ id: 'capa-1' }) } + +beforeEach(() => { + h.session = { sub: 'owner-1', role: 'capa_owner' } + h.capa = { incidentId: 'inc-1', ownerUserId: 'owner-1', status: 'in_progress' } + h.updates = [] + h.inserts = [] + vi.mocked(writeAuditLog).mockClear() +}) + +describe('POST /api/capa/[id]/submit', () => { + it('401 without a session', async () => { + h.session = null + expect((await POST(req('done', 1) as never, ctx)).status).toBe(401) + }) + it('404 when the CAPA does not exist', async () => { + h.capa = null + expect((await POST(req('done', 1) as never, ctx)).status).toBe(404) + }) + it('403 for a user who is neither owner nor hse/admin', async () => { + h.session = { sub: 'other', role: 'reporter' } + expect((await POST(req('done', 1) as never, ctx)).status).toBe(403) + }) + it('409 when status is not in_progress', async () => { + h.capa!.status = 'open' + expect((await POST(req('done', 1) as never, ctx)).status).toBe(409) + }) + it('422 when no photo is attached', async () => { + const res = await POST(req('done', 0) as never, ctx) + expect(res.status).toBe(422) + expect((await res.json()).details).toContain('At least 1 photo is required') + }) + it('422 when the note is empty', async () => { + expect((await POST(req(' ', 1) as never, ctx)).status).toBe(422) + }) + it('stores evidence, sets status and audits on success', async () => { + const res = await POST(req(' fixed the rack ', 2) as never, ctx) + expect(res.status).toBe(200) + expect(h.inserts[0]).toEqual([ + expect.objectContaining({ incidentId: 'inc-1', capaId: 'capa-1', stage: 'capa', uploadedBy: 'owner-1' }), + expect.objectContaining({ incidentId: 'inc-1', capaId: 'capa-1', stage: 'capa', uploadedBy: 'owner-1' }), + ]) + expect(h.updates[0]).toEqual( + expect.objectContaining({ status: 'pending_verification', ownerNotes: 'fixed the rack', completedAt: expect.any(Date) }), + ) + expect(writeAuditLog).toHaveBeenCalledWith( + expect.anything(), 'capa_actions', 'capa-1', 'submitted_for_verification', + expect.objectContaining({ status: 'pending_verification' }), + expect.objectContaining({ status: 'in_progress' }), + ) + }) +}) +``` + +- [ ] **Step 7: Run to verify it fails** + +Run: `npx vitest run tests/api/capa-submit.test.ts` +Expected: FAIL, cannot resolve `@/app/api/capa/[id]/submit/route`. + +- [ ] **Step 8: Implement the route** + +`app/api/capa/[id]/submit/route.ts`: + +```ts +export const dynamic = 'force-dynamic' + +import { NextRequest, NextResponse } from 'next/server' +import { eq } from 'drizzle-orm' +import { getSession } from '@/lib/auth/get-session' +import { withUser } from '@/lib/db/with-user' +import { writeAuditLog } from '@/lib/db/audit' +import { capaActions, evidenceFiles } from '@/lib/db/schema' +import { uploadEvidenceFile } from '@/lib/storage/evidence' +import { validateCapaSubmission } from '@/lib/capa/submit-validation' + +export async function POST( + request: NextRequest, + { params }: { params: Promise<{ id: string }> } +) { + const { id } = await params + const session = await getSession() + if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + + const [capa] = await withUser(session.sub, async tx => + tx.select({ + incidentId: capaActions.incidentId, + ownerUserId: capaActions.ownerUserId, + status: capaActions.status, + }).from(capaActions).where(eq(capaActions.id, id)).limit(1) + ) + if (!capa) return NextResponse.json({ error: 'Not found' }, { status: 404 }) + + const isElevated = ['hse', 'admin'].includes(session.role) + if (capa.ownerUserId !== session.sub && !isElevated) + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) + + if (capa.status !== 'in_progress') + return NextResponse.json({ error: 'CAPA must be in_progress' }, { status: 409 }) + + const form = await request.formData() + const files = form.getAll('files').filter((f): f is File => f instanceof File) + const check = validateCapaSubmission(String(form.get('note') ?? ''), files) + if (!check.ok) + return NextResponse.json({ error: 'Validation failed', details: check.errors }, { status: 422 }) + + const uploaded: Array<{ publicUrl: string; hash: string; type: string }> = [] + try { + for (const file of files) { + const { publicUrl, hash } = await uploadEvidenceFile(file, capa.incidentId, 'capa', session.sub) + uploaded.push({ publicUrl, hash, type: file.type }) + } + } catch (err) { + return NextResponse.json( + { error: 'Photo upload failed', details: [err instanceof Error ? err.message : 'unknown error'] }, + { status: 422 }, + ) + } + + const completedAt = new Date() + await withUser(session.sub, async tx => { + const rows = await tx.insert(evidenceFiles).values( + uploaded.map(u => ({ + incidentId: capa.incidentId, + capaId: id, + stage: 'capa' as const, + fileUrl: u.publicUrl, + fileType: u.type, + fileHash: u.hash, + uploadedBy: session.sub, + })) + ).returning({ id: evidenceFiles.id }) + + await tx.update(capaActions).set({ + status: 'pending_verification', + ownerNotes: check.note, + completedAt, + }).where(eq(capaActions.id, id)) + + await writeAuditLog( + tx, 'capa_actions', id, 'submitted_for_verification', + { + status: 'pending_verification', + owner_notes: check.note, + completed_at: completedAt.toISOString(), + evidence_file_ids: rows.map(r => r.id), + }, + { status: 'in_progress' }, + ) + }) + + return NextResponse.json({ ok: true }) +} +``` + +- [ ] **Step 9: Run to verify it passes** + +Run: `npx vitest run tests/api/capa-submit.test.ts` +Expected: PASS (7 tests). + +- [ ] **Step 10: Write the failing PATCH-bypass test** + +`tests/api/capa-patch.test.ts`: + +```ts +// @vitest-environment node +import { describe, it, expect, vi } from 'vitest' + +vi.mock('@/lib/auth/get-session', () => ({ + getSession: async () => ({ sub: 'owner-1', role: 'capa_owner' }), +})) +vi.mock('@/lib/db/audit', () => ({ writeAuditLog: vi.fn() })) +vi.mock('@/lib/db/with-user', () => ({ + withUser: async (_id: string, fn: (tx: unknown) => unknown) => + fn({ + select: () => ({ from: () => ({ where: () => ({ limit: async () => [{ ownerUserId: 'owner-1', status: 'in_progress' }] }) }) }), + update: () => ({ set: () => ({ where: async () => undefined }) }), + }), +})) + +import { PATCH } from '@/app/api/capa/[id]/route' + +const ctx = { params: Promise.resolve({ id: 'capa-1' }) } +const patch = (body: unknown) => + new Request('http://localhost/api/capa/capa-1', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }) + +describe('PATCH /api/capa/[id]', () => { + it('rejects pending_verification (must use /submit)', async () => { + const res = await PATCH(patch({ status: 'pending_verification' }) as never, ctx) + expect(res.status).toBe(403) + }) + it('still allows in_progress', async () => { + const res = await PATCH(patch({ status: 'in_progress' }) as never, ctx) + expect(res.status).toBe(200) + }) +}) +``` + +Run: `npx vitest run tests/api/capa-patch.test.ts` +Expected: FAIL on the first test (currently returns 200). + +- [ ] **Step 11: Block the bypass in PATCH** + +`app/api/capa/[id]/route.ts`: right after `const body = await request.json()` add: + +```ts + if (body.status === 'pending_verification') { + return NextResponse.json( + { error: 'Use POST /api/capa/[id]/submit to submit for verification' }, + { status: 403 }, + ) + } +``` +Then delete the two now-dead lines: +```ts + if (body.status === 'pending_verification') updateSet.completedAt = new Date() +``` +and +```ts + if (body.status === 'pending_verification') auditNew.completed_at = updateSet.completedAt?.toISOString() +``` + +- [ ] **Step 12: Run all new tests** + +Run: `npx vitest run tests/api/capa-patch.test.ts tests/api/capa-submit.test.ts tests/lib/capa` +Expected: PASS. +Run: `npx tsc --noEmit` — Expected: no errors. + +- [ ] **Step 13: Commit** + +```bash +git add db lib/capa lib/db/schema.ts app/api/capa tests/api tests/lib/capa +git commit -m "feat(capa): require note and photos via /submit, block PATCH bypass + +Co-Authored-By: Claude Sonnet 5.5 " +``` + +--- + +### Task 3: CAPA proof UI and gallery + +**Files:** +- Create: `components/capa/submit-verification-form.tsx`, `tests/components/capa/submit-verification-form.test.tsx` +- Modify: `components/capa/capa-owner-actions.tsx`, `app/(protected)/hse/capa/[id]/page.tsx` + +**Interfaces:** +- Consumes: `validateCapaSubmission`, `MAX_CAPA_PHOTOS` from `lib/capa/submit-validation.ts`; `POST /api/capa/[id]/submit` (Task 2). +- Produces: `SubmitVerificationForm({ capaId }: { capaId: string })` (client component). `CapaOwnerActions` renders it when `currentStatus === 'in_progress'`. + +- [ ] **Step 1: Write the failing component test** + +`tests/components/capa/submit-verification-form.test.tsx`: + +```tsx +import { describe, it, expect, vi } from 'vitest' +import { render, screen, fireEvent } from '@testing-library/react' +import { SubmitVerificationForm } from '@/components/capa/submit-verification-form' + +vi.mock('next/navigation', () => ({ + useRouter: () => ({ refresh: vi.fn() }), +})) + +function button() { + return screen.getByRole('button', { name: 'Submit for Verification' }) as HTMLButtonElement +} + +describe('SubmitVerificationForm', () => { + it('is disabled until a note and a photo are provided', () => { + const { container } = render() + expect(button().disabled).toBe(true) + + fireEvent.change(screen.getByLabelText('Completion note'), { target: { value: 'Rack fixed' } }) + expect(button().disabled).toBe(true) + + const input = container.querySelector('input[type="file"]') as HTMLInputElement + const file = new File(['x'], 'proof.jpg', { type: 'image/jpeg' }) + fireEvent.change(input, { target: { files: [file] } }) + expect(button().disabled).toBe(false) + expect(screen.getByText('proof.jpg')).toBeTruthy() + }) +}) +``` + +- [ ] **Step 2: Run to verify it fails** + +Run: `npx vitest run tests/components/capa/submit-verification-form.test.tsx` +Expected: FAIL, module not found. + +- [ ] **Step 3: Implement the form** + +`components/capa/submit-verification-form.tsx`: + +```tsx +'use client' + +import { useState } from 'react' +import { useRouter } from 'next/navigation' +import { X } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Field, Textarea } from '@/components/ui/field' +import { MAX_CAPA_PHOTOS, validateCapaSubmission } from '@/lib/capa/submit-validation' + +interface Props { + capaId: string +} + +export function SubmitVerificationForm({ capaId }: Props) { + const router = useRouter() + const [note, setNote] = useState('') + const [files, setFiles] = useState([]) + const [loading, setLoading] = useState(false) + const [error, setError] = useState(null) + + const check = validateCapaSubmission(note, files) + + function addFiles(list: FileList | null) { + if (!list) return + setFiles(prev => [...prev, ...Array.from(list)].slice(0, MAX_CAPA_PHOTOS)) + } + + async function handleSubmit(e: React.FormEvent) { + e.preventDefault() + if (!check.ok) return + setLoading(true) + setError(null) + try { + const fd = new FormData() + fd.append('note', check.note) + files.forEach(f => fd.append('files', f)) + const res = await fetch(`/api/capa/${capaId}/submit`, { method: 'POST', body: fd }) + if (!res.ok) { + const data = await res.json().catch(() => ({})) + setError(Array.isArray(data.details) ? data.details.join('. ') : (data.error ?? 'Submit failed. Please try again.')) + return + } + router.refresh() + } finally { + setLoading(false) + } + } + + return ( +
+
+

Proof of completion

+

Describe what was done and attach 1 to {MAX_CAPA_PHOTOS} photos as evidence.

+
+ + +