1120 lines
44 KiB
Markdown
1120 lines
44 KiB
Markdown
# 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 <noreply@anthropic.com>`.
|
|
- Tests: `npx vitest run <path>`. 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<string, SiteOption>()
|
|
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 ? (...) : (<p ...>No zone detected…</p>)` block with only the QR case:
|
|
```tsx
|
|
{zoneName && (
|
|
<p className="text-sm text-gray-600 mt-1">
|
|
{siteName ?? 'Unknown Site'} — {zoneName}
|
|
</p>
|
|
)}
|
|
```
|
|
4. Update the `<ReportForm …/>` props:
|
|
```tsx
|
|
<ReportForm
|
|
zoneToken={zoneName ? (zone ?? null) : null}
|
|
zoneName={zoneName}
|
|
siteName={siteName}
|
|
sites={siteOptions}
|
|
defaultSiteId={defaultSiteId}
|
|
trucks={truckList}
|
|
initialTruckId={truck_id ?? null}
|
|
/>
|
|
```
|
|
(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" `<div>` (after the `{error && …}` block), insert:
|
|
```tsx
|
|
{!zoneToken && (
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<div>
|
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
{t.siteLabel} <span className="text-red-500">*</span>
|
|
</label>
|
|
<select
|
|
required
|
|
className="w-full border border-divider px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-accent"
|
|
value={siteId}
|
|
onChange={e => { setSiteId(e.target.value); setZoneId('') }}
|
|
>
|
|
<option value="">{t.sitePlaceholder}</option>
|
|
{sites.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
|
|
</select>
|
|
</div>
|
|
<div>
|
|
<label className="block text-sm font-medium text-gray-700 mb-1">
|
|
{t.zoneLabel} <span className="text-red-500">*</span>
|
|
</label>
|
|
<select
|
|
required
|
|
disabled={!siteId}
|
|
className="w-full border border-divider px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-accent disabled:opacity-50"
|
|
value={zoneId}
|
|
onChange={e => setZoneId(e.target.value)}
|
|
>
|
|
<option value="">{t.zonePlaceholder}</option>
|
|
{zonesForSite(sites, siteId).map(z => <option key={z.id} value={z.id}>{z.name}</option>)}
|
|
</select>
|
|
</div>
|
|
</div>
|
|
)}
|
|
```
|
|
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=<valid token>` → 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 <noreply@anthropic.com>"
|
|
```
|
|
|
|
---
|
|
|
|
### 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 <noreply@anthropic.com>"
|
|
```
|
|
|
|
---
|
|
|
|
### 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(<SubmitVerificationForm capaId="abc" />)
|
|
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<File[]>([])
|
|
const [loading, setLoading] = useState(false)
|
|
const [error, setError] = useState<string | null>(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 (
|
|
<form onSubmit={handleSubmit} className="space-y-3 rounded-xl bg-surface p-5 shadow-card">
|
|
<div>
|
|
<h2 className="text-sm font-semibold">Proof of completion</h2>
|
|
<p className="text-xs text-muted">Describe what was done and attach 1 to {MAX_CAPA_PHOTOS} photos as evidence.</p>
|
|
</div>
|
|
|
|
<Field label="Completion note" htmlFor={`note-${capaId}`}>
|
|
<Textarea
|
|
id={`note-${capaId}`}
|
|
value={note}
|
|
onChange={e => setNote(e.target.value)}
|
|
rows={3}
|
|
placeholder="What action was carried out?"
|
|
disabled={loading}
|
|
/>
|
|
</Field>
|
|
|
|
<Field label="Photos" htmlFor={`photos-${capaId}`}>
|
|
<input
|
|
id={`photos-${capaId}`}
|
|
type="file"
|
|
accept="image/*"
|
|
multiple
|
|
disabled={loading || files.length >= MAX_CAPA_PHOTOS}
|
|
onChange={e => { addFiles(e.target.files); e.target.value = '' }}
|
|
className="block w-full text-[13px] text-ink"
|
|
/>
|
|
</Field>
|
|
|
|
{files.length > 0 && (
|
|
<ul className="space-y-1">
|
|
{files.map((f, i) => (
|
|
<li key={`${f.name}-${i}`} className="flex items-center justify-between gap-2 text-[13px]">
|
|
<span className="truncate">{f.name}</span>
|
|
<button
|
|
type="button"
|
|
aria-label={`Remove ${f.name}`}
|
|
onClick={() => setFiles(prev => prev.filter((_, j) => j !== i))}
|
|
disabled={loading}
|
|
className="text-muted hover:text-ink"
|
|
>
|
|
<X size={14} strokeWidth={2} aria-hidden />
|
|
</button>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
)}
|
|
|
|
{error && <p role="alert" className="text-xs text-danger">{error}</p>}
|
|
|
|
<Button type="submit" disabled={!check.ok || loading}>
|
|
{loading ? 'Submitting…' : 'Submit for Verification'}
|
|
</Button>
|
|
</form>
|
|
)
|
|
}
|
|
```
|
|
|
|
- [ ] **Step 4: Run to verify it passes**
|
|
|
|
Run: `npx vitest run tests/components/capa/submit-verification-form.test.tsx`
|
|
Expected: PASS.
|
|
|
|
- [ ] **Step 5: Use the form in `CapaOwnerActions`**
|
|
|
|
`components/capa/capa-owner-actions.tsx`: add import `import { SubmitVerificationForm } from '@/components/capa/submit-verification-form'` and replace the `if (currentStatus === 'in_progress') { … }` block with:
|
|
|
|
```tsx
|
|
if (currentStatus === 'in_progress') {
|
|
return <SubmitVerificationForm capaId={capaId} />
|
|
}
|
|
```
|
|
`updateStatus` still serves the `Mark In Progress` branch; keep it.
|
|
|
|
Run: `npx vitest run tests/components/capa`
|
|
Expected: PASS (existing `capa-owner-actions` test still finds the "Submit for Verification" text; if its `useRouter` mock lacks what the form needs, the mock already returns `{ refresh }`).
|
|
|
|
- [ ] **Step 6: Photo gallery on the CAPA detail page**
|
|
|
|
`app/(protected)/hse/capa/[id]/page.tsx` edits:
|
|
|
|
1. Imports: change schema import to `import { capaActions, evidenceFiles, incidents, users } from '@/lib/db/schema'` and drizzle import to `import { eq, and, asc } from 'drizzle-orm'`.
|
|
2. After `if (!capa) notFound()` add:
|
|
```ts
|
|
const photos = await asAdmin(db =>
|
|
db.select({ id: evidenceFiles.id, fileUrl: evidenceFiles.fileUrl, fileType: evidenceFiles.fileType })
|
|
.from(evidenceFiles)
|
|
.where(and(eq(evidenceFiles.capaId, id), eq(evidenceFiles.deleted, false)))
|
|
.orderBy(asc(evidenceFiles.uploadedAt))
|
|
)
|
|
```
|
|
3. Change the report section condition and body:
|
|
```tsx
|
|
{(capa.ownerNotes || capa.completedAt || photos.length > 0) && (
|
|
<section className="space-y-2 rounded-xl bg-surface p-5 shadow-card">
|
|
<h2 className="text-sm font-semibold">Completion report</h2>
|
|
{capa.completedAt && (
|
|
<p className="text-xs text-muted">
|
|
Completed {new Date(capa.completedAt).toLocaleString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })}
|
|
</p>
|
|
)}
|
|
{capa.ownerNotes && (
|
|
<p className="whitespace-pre-wrap text-[13px] text-ink-3">{capa.ownerNotes}</p>
|
|
)}
|
|
{photos.length > 0 && (
|
|
<ul className="grid grid-cols-2 gap-2 sm:grid-cols-3">
|
|
{photos.map(p => (
|
|
<li key={p.id}>
|
|
<a href={p.fileUrl} target="_blank" rel="noreferrer" className="block overflow-hidden rounded-md shadow-card">
|
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
|
<img src={p.fileUrl} alt="CAPA completion evidence" className="aspect-square w-full object-cover" />
|
|
</a>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
)}
|
|
</section>
|
|
)}
|
|
```
|
|
(Evidence photos stay full colour; `fileUrl` is already the signed `/api/evidence/...?token=` URL.)
|
|
|
|
- [ ] **Step 7: Verify**
|
|
|
|
Run: `npx tsc --noEmit` — Expected: no errors.
|
|
Run: `npx vitest run` — Expected: all PASS.
|
|
Run: `npm run check:design` — Expected: `design gates: clean`.
|
|
Manual (after the schema SQL is applied to a dev DB): as a PIC with an `in_progress` CAPA, the button is disabled until note + photo; submit moves it to Pending Verification and the photo shows under Completion report; as HSE the Verify form appears under it. Calling `PATCH` with `{status:'pending_verification'}` returns 403.
|
|
|
|
- [ ] **Step 8: Commit**
|
|
|
|
```bash
|
|
git add components/capa tests/components/capa "app/(protected)/hse/capa"
|
|
git commit -m "feat(capa): proof form for owners and photo gallery for HSE
|
|
|
|
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>"
|
|
```
|
|
|
|
---
|
|
|
|
### Task 4: Test-data cleanup script and runbook
|
|
|
|
**Files:**
|
|
- Create: `db/ops/cleanup-test-data.sql`, `docs/runbooks/cleanup-test-data.md`
|
|
- Modify: `docs/superpowers/specs/2026-10-14-zone-capa-proof-cleanup-design.md`
|
|
|
|
**Interfaces:** none (ops only). Nothing here runs against production without the explicit confirmation step in the runbook.
|
|
|
|
- [ ] **Step 1: Write the script**
|
|
|
|
`db/ops/cleanup-test-data.sql` (run as the DB owner, which is allowed to disable triggers; `app_user` is not):
|
|
|
|
```sql
|
|
-- One-off: delete ALL incidents (and children) and every user with role <> 'admin'.
|
|
-- Usage: psql -p 5433 -d ims -v mode=dryrun -f cleanup-test-data.sql (counts only)
|
|
-- psql -p 5433 -d ims -v mode=run -f cleanup-test-data.sql (deletes, one transaction)
|
|
-- Evidence files on disk are NOT touched (5-year retention).
|
|
|
|
\if :{?mode}
|
|
\else
|
|
\echo 'Set -v mode=dryrun or -v mode=run'
|
|
\quit
|
|
\endif
|
|
|
|
BEGIN;
|
|
|
|
\echo '--- admins kept ---'
|
|
SELECT id, name, email FROM users WHERE role = 'admin' ORDER BY email;
|
|
|
|
\echo '--- row counts to delete ---'
|
|
SELECT 'incidents' AS tbl, count(*) FROM incidents
|
|
UNION ALL SELECT 'evidence_files', count(*) FROM evidence_files
|
|
UNION ALL SELECT 'investigations', count(*) FROM investigations
|
|
UNION ALL SELECT 'capa_actions', count(*) FROM capa_actions
|
|
UNION ALL SELECT 'dosh_reports', count(*) FROM dosh_reports
|
|
UNION ALL SELECT 'incident_addenda', count(*) FROM incident_addenda
|
|
UNION ALL SELECT 'notifications_log', count(*) FROM notifications_log
|
|
UNION ALL SELECT 'audit_log (all)', count(*) FROM audit_log
|
|
UNION ALL SELECT 'users (non-admin)', count(*) FROM users WHERE role <> 'admin';
|
|
|
|
SELECT (:'mode' = 'run') AS do_delete \gset
|
|
\if :do_delete
|
|
-- Closed incidents are locked by triggers; disable them for this transaction only.
|
|
ALTER TABLE incidents DISABLE TRIGGER incidents_closed_lock_delete;
|
|
ALTER TABLE incidents DISABLE TRIGGER incidents_closed_lock_update;
|
|
|
|
DELETE FROM notifications_log;
|
|
DELETE FROM incident_addenda;
|
|
DELETE FROM dosh_reports;
|
|
DELETE FROM evidence_files;
|
|
DELETE FROM capa_actions;
|
|
DELETE FROM investigations;
|
|
DELETE FROM incidents;
|
|
|
|
-- audit_log: remove rows about deleted incident-side tables and about non-admin users.
|
|
DELETE FROM audit_log
|
|
WHERE table_name IN ('incidents','evidence_files','investigations','capa_actions','dosh_reports','incident_addenda')
|
|
OR changed_by IN (SELECT id FROM users WHERE role <> 'admin')
|
|
OR (table_name = 'users' AND record_id IN (SELECT id FROM users WHERE role <> 'admin'));
|
|
|
|
UPDATE app_settings SET updated_by = NULL
|
|
WHERE updated_by IN (SELECT id FROM users WHERE role <> 'admin');
|
|
|
|
DELETE FROM password_reset_tokens WHERE user_id IN (SELECT id FROM users WHERE role <> 'admin');
|
|
DELETE FROM users WHERE role <> 'admin';
|
|
|
|
ALTER TABLE incidents ENABLE TRIGGER incidents_closed_lock_delete;
|
|
ALTER TABLE incidents ENABLE TRIGGER incidents_closed_lock_update;
|
|
|
|
\echo '--- after ---'
|
|
SELECT 'incidents' AS tbl, count(*) FROM incidents
|
|
UNION ALL SELECT 'users', count(*) FROM users
|
|
UNION ALL SELECT 'admins', count(*) FROM users WHERE role = 'admin';
|
|
COMMIT;
|
|
\else
|
|
ROLLBACK;
|
|
\echo 'dry run: nothing changed'
|
|
\endif
|
|
```
|
|
|
|
Note: `evidence_files` has no DELETE grant for `app_user` (by design); the owner role used here is not subject to that. `sites`, `zones`, `trucks` are kept.
|
|
|
|
- [ ] **Step 2: Syntax-check on a scratch database**
|
|
|
|
Run (local scratch DB restored from a dump, never prod):
|
|
```bash
|
|
createdb ims_scratch && psql -d ims_scratch -f db/schema.sql
|
|
psql -d ims_scratch -v mode=dryrun -f db/ops/cleanup-test-data.sql
|
|
psql -d ims_scratch -v mode=run -f db/ops/cleanup-test-data.sql
|
|
dropdb ims_scratch
|
|
```
|
|
Expected: dry run prints counts and `dry run: nothing changed`; run prints `--- after ---` with `incidents 0` and no errors. Fix any FK error by adding the offending table's delete before its parent, then rerun.
|
|
|
|
- [ ] **Step 3: Write the runbook**
|
|
|
|
`docs/runbooks/cleanup-test-data.md`:
|
|
|
|
````markdown
|
|
# Cleanup: delete test incidents and non-admin users
|
|
|
|
Owner go-ahead required before step 4. Never run during business hours without telling HSE.
|
|
|
|
1. **Backup** (on the server, `ssh -p 9321 setia@175.136.239.121`):
|
|
```bash
|
|
D=$(date +%Y%m%d-%H%M)
|
|
pg_dump -p 5433 -Fc ims > /srv/apps/ims/backups/ims-pre-cleanup-$D.dump
|
|
tar -czf /srv/apps/ims/backups/evidence-pre-cleanup-$D.tgz /var/lib/ims-evidence
|
|
ls -lh /srv/apps/ims/backups/*pre-cleanup-$D*
|
|
```
|
|
Create `/srv/apps/ims/backups` first if missing. Both files must be non-empty.
|
|
2. **Upload** `db/ops/cleanup-test-data.sql` to `/srv/apps/ims/backups/` (not into `app/`).
|
|
3. **Dry run** as the DB owner:
|
|
```bash
|
|
psql -p 5433 -d ims -v mode=dryrun -f /srv/apps/ims/backups/cleanup-test-data.sql
|
|
```
|
|
Send the admins list and the row counts to the owner. Stop here until they confirm.
|
|
4. **Run** after explicit confirmation:
|
|
```bash
|
|
psql -p 5433 -d ims -v ON_ERROR_STOP=1 -v mode=run -f /srv/apps/ims/backups/cleanup-test-data.sql
|
|
```
|
|
5. **Verify**: `systemctl is-active ims` is `active`; log in as an admin at https://ims.setia.com.my/login; Incidents page is empty; Users page lists only admins.
|
|
6. **Rollback** (only if wrong): `pg_restore -p 5433 -d ims --clean --if-exists <dump>`; evidence files were never touched.
|
|
````
|
|
|
|
- [ ] **Step 4: Fix the spec claim about notifications**
|
|
|
|
In `docs/superpowers/specs/2026-10-14-zone-capa-proof-cleanup-design.md`, section 2, delete the bullet:
|
|
` - Existing in-app notification to HSE on submission is kept.`
|
|
(There is no HSE notification on submit today; adding one is out of scope.) Also in the Schema change block replace the SQL with the `ADD COLUMN … ON DELETE RESTRICT` + index form used in `db/ops/2026-10-14-evidence-capa-id.sql`, and replace "check the `evidence_*` RLS policies … add a read policy for the CAPA owner if missing" with "no RLS change: the PIC is the uploader and already reads own rows".
|
|
|
|
- [ ] **Step 5: Commit**
|
|
|
|
```bash
|
|
git add db/ops/cleanup-test-data.sql docs/runbooks docs/superpowers/specs
|
|
git commit -m "chore(ops): test-data cleanup script and runbook
|
|
|
|
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>"
|
|
```
|
|
|
|
---
|
|
|
|
## Rollout order
|
|
|
|
1. Merge Tasks 1 to 4 locally; `npx vitest run`, `npx tsc --noEmit`, `npm run check:design` all clean; `graphify update .`.
|
|
2. With the owner's go-ahead, apply `db/ops/2026-10-14-evidence-capa-id.sql` on the server **before** deploying (the submit route inserts `capa_id`).
|
|
3. Deploy per CLAUDE.md (local build, upload standalone output without `.env*`, check `BUILD_ID`, rollback tar, restart, verify `/login` is 200 and `ims` is `active`).
|
|
4. Run the cleanup runbook last, only after the owner confirms the dry-run counts.
|
|
|
|
## Self-review notes
|
|
|
|
- Spec coverage: section 1 → Task 1; section 2 → Tasks 2 and 3 (schema, endpoint, PATCH guard, form, gallery); section 3 → Task 4. Spec's "existing notification kept" claim was wrong and is corrected in Task 4 step 4.
|
|
- The closed-incident delete trigger (`incidents_closed_lock_delete`) would break the cleanup; Task 4 disables and re-enables it inside the transaction.
|
|
- Known limitation: if a photo upload fails midway, files already written to disk are orphaned (no DB row). Acceptable for now; files are never auto-deleted by policy.
|