diff --git a/docs/superpowers/plans/2026-10-01-ims-admin-refresh-slice-2-capa.md b/docs/superpowers/plans/2026-10-01-ims-admin-refresh-slice-2-capa.md new file mode 100644 index 0000000..4306531 --- /dev/null +++ b/docs/superpowers/plans/2026-10-01-ims-admin-refresh-slice-2-capa.md @@ -0,0 +1,1805 @@ +# IMS Admin Refresh, Slice 2: CAPA 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:** Migrate the CAPA screens (list 04, board 04b, detail and verification 04c, plus the create form) to the IMS Admin design, reusing the slice 1 primitives. + +**Architecture:** One client component, `CapaWorkspace`, owns search, filters, saved views, sort and paging for both a `TableCard` list and a board of status columns, switched by `Segmented`. Filtering, sorting and paging live in a pure helper module (`lib/capa/list.ts`) so they are unit tested; the CAPA table is small, so everything stays client-side as it is today. The detail page, verification form, owner actions and create form are restyled with the existing primitives. No API, database or routing changes. + +**Tech Stack:** Next.js 16.3.7 (App Router), React 19, Tailwind CSS v4 tokens from `app/globals.css`, `lucide-react`, vitest 4 + jsdom + `@testing-library/react`. + +**Spec:** `design-system/design.md` (§4 components, §5 screens 04, 04b, 04c). Reference artboards: `design-system/IMS Admin.dc.html` (04 CAPA list, 04b CAPA board, 04c CAPA detail verification). + +## Global Constraints + +- Source of truth is `design-system/design.md`. Colours, type, radius and shadows come from the tokens: ink `#1f1f1f`, ground `#f1f1f1`, surface `#ffffff`, surface-2 `#f7f7f7`, one teal accent `#0f766e`, danger `#b3261e`. +- Rules are 1px. Never `border-2` or `border-{t,b,l,r}-2`. Radius scale: `rounded-md` = 8 (buttons, chips, inputs, pills), `rounded-xl` = 12 (cards), `rounded-[6px]` avatar. +- Status and priority colours only through `StatusTag` and `PriorityTag` (design.md §4.2). Banners: error `bg-st-red-bg text-st-red-fg`, warning `bg-st-amber-bg text-st-amber-fg`, info `bg-accent-tint`. +- Every list is a `TableCard`. Use the primitives in `components/ui/` (`Button`, `Field`/`Input`/`Select`/`Textarea`, `FilterChip`, `Segmented`, `Avatar`, `Card`, `TableCard`, `StatusTag`, `PriorityTag`); do not hand-build tables, buttons or inputs. +- Never write `*/` inside a CSS comment in `app/globals.css`. Do not run `next dev` while verifying a production build in the same `.next`; verify with `rm -rf .next && npm run build`. +- Baseline: exactly 7 tests fail before this work (missing `DEEPSEEK_API_KEY`, `BREVO_API_KEY`, a `cookies()` scope error): `lib/incidents/bulk-import.test.ts` (2), `tests/api/incidents/quality-check.test.ts` (2), `rca-draft.test.ts` (1), `triage-suggest.test.ts` (1), `tests/lib/notifications/email.test.ts` (1). "No new failures" means exactly these 7 and no others. After slice 1 the full suite is `7 failed | 294 passed`. +- No database, API, auth or routing changes. Keep every existing `fetch` call, URL, payload and redirect exactly as it is. Do not deploy and do not push `main` without the owner's go-ahead. +- Work on branch `feat/admin-refresh-slice-2-capa`, created from `feat/admin-refresh-slice-1` (it contains the primitives). Stage only named paths; never `git add -A`. Leave the untracked `*.zip` files, `.superpowers/` and the deleted `design-system/ims-admin/MASTER.md` alone. + +## Out of scope (in the mockup, not backed by the app today) + +Export, bulk actions on a selection (send reminder, reassign, escalate), "Group by", Department and Due-date range filters beyond a Department chip, the activity and comments feed, cost, evidence files on a CAPA, the verification note field, "Ask owner a question", "Edit", and the recheck-date sentence. Do not build or fake them. Note them for a later slice that adds the backend. + +## File Structure + +**Create** +- `lib/capa/list.ts` (pure helpers and types), `tests/lib/capa/list.test.ts` +- `components/capa/capa-workspace.tsx`, `components/capa/capa-board-view.tsx`, `tests/components/capa/capa-workspace.test.tsx` +- `tests/components/capa/verify-form.test.tsx`, `tests/components/capa/capa-form.test.tsx` + +**Modify** +- `app/(protected)/hse/capa/page.tsx`, `app/(protected)/hse/capa/[id]/page.tsx`, `app/(protected)/hse/incidents/[id]/capa/new/page.tsx` +- `components/capa/verify-form.tsx`, `close-capa-button.tsx`, `capa-owner-actions.tsx`, `capa-owner-notes-form.tsx`, `capa-form.tsx` +- `design-system/design.md`, memory `ims-design-system.md` + +**Delete** +- `components/capa/capa-board.tsx` (replaced by the workspace and board view) + +--- + +### Task 1: CAPA list helpers + +**Files:** +- Create: `lib/capa/list.ts` +- Test: `tests/lib/capa/list.test.ts` + +**Interfaces:** +- Consumes: nothing. +- Produces (later tasks import exactly these from `@/lib/capa/list`): + +```ts +export type CapaStatus = 'open' | 'in_progress' | 'overdue' | 'pending_verification' | 'verified' | 'reopened' | 'closed' +export type CapaPriority = 'low' | 'med' | 'high' +export interface CapaRow { + id: string; incident_id: string; description: string; department: string; due_date: string + priority: CapaPriority; status: CapaStatus; incident_ref: string | null; owner_name: string | null +} +export const PAGE_SIZE = 25 +export const STATUS_ORDER: CapaStatus[] // open, in_progress, overdue, reopened, pending_verification, verified, closed +export type CapaViewKey = 'all' | 'active' | 'overdue' | 'verification' | 'done' +export const VIEWS: Array<{ key: CapaViewKey; label: string; statuses: CapaStatus[] | null }> +export interface CapaFilters { q: string; owner: string; department: string; priority: string; view: CapaViewKey } +export const EMPTY_FILTERS: CapaFilters +export type CapaSortKey = 'due_date' | 'priority' | 'status' +export type CapaSort = { key: CapaSortKey; dir: 'asc' | 'desc' } +export function filterCapas(rows: CapaRow[], f: CapaFilters): CapaRow[] +export function viewCounts(rows: CapaRow[], f: CapaFilters): Record +export function sortCapas(rows: CapaRow[], sort: CapaSort): CapaRow[] +export function paginate(rows: T[], page: number, size: number): { items: T[]; from: number; to: number; total: number; page: number; pageCount: number } +export function distinct(values: Array): string[] +export function daysLate(due: string, today: string): number +export function nextSort(current: CapaSort, key: CapaSortKey): CapaSort +``` + +- [ ] **Step 1: Confirm the branch and the baseline** + +The branch `feat/admin-refresh-slice-2-capa` already exists (created from `feat/admin-refresh-slice-1`, which holds the primitives). + +```bash +cd /Users/yapweeihan/Projects/IMS.nosync +git branch --show-current +npx vitest run 2>&1 | grep -E "Test Files|Tests " +``` + +Expected: `feat/admin-refresh-slice-2-capa`, then `Tests 7 failed | 294 passed` (the 7 baseline failures). If either differs, stop and report. + +- [ ] **Step 2: Write the failing test** + +Create `tests/lib/capa/list.test.ts`: + +```ts +import { describe, it, expect } from 'vitest' +import { + EMPTY_FILTERS, PAGE_SIZE, STATUS_ORDER, VIEWS, + daysLate, distinct, filterCapas, nextSort, paginate, sortCapas, viewCounts, + type CapaRow, +} from '@/lib/capa/list' + +const row = (over: Partial): CapaRow => ({ + id: 'x', incident_id: 'i', description: 'Fit guard rail', department: 'Facilities', due_date: '2026-10-10', + priority: 'med', status: 'open', incident_ref: 'SC1-202607-0001', owner_name: 'Tan Mei Ling', ...over, +}) + +const rows: CapaRow[] = [ + row({ id: '1', description: 'Anti-slip coating', due_date: '2026-09-12', priority: 'high', status: 'overdue', owner_name: 'Tan Mei Ling', department: 'Facilities' }), + row({ id: '2', description: 'Forklift refresher', due_date: '2026-10-20', priority: 'low', status: 'in_progress', owner_name: 'Ravi Kumar', department: 'Operations', incident_ref: 'SC3-202607-0002' }), + row({ id: '3', description: 'Guard rail repair', due_date: '2026-10-01', priority: 'med', status: 'pending_verification', owner_name: 'Tan Mei Ling', department: 'Facilities' }), + row({ id: '4', description: 'Signage', due_date: '2026-08-30', priority: 'low', status: 'closed', owner_name: null, department: 'Operations' }), +] + +describe('constants', () => { + it('orders statuses for the board and defines the saved views', () => { + expect(STATUS_ORDER).toEqual(['open', 'in_progress', 'overdue', 'reopened', 'pending_verification', 'verified', 'closed']) + expect(VIEWS.map(v => v.key)).toEqual(['all', 'active', 'overdue', 'verification', 'done']) + expect(PAGE_SIZE).toBe(25) + }) +}) + +describe('filterCapas', () => { + it('returns everything for the empty filters', () => { + expect(filterCapas(rows, EMPTY_FILTERS)).toHaveLength(4) + }) + + it('searches description, incident reference and owner, case-insensitively', () => { + expect(filterCapas(rows, { ...EMPTY_FILTERS, q: 'GUARD' }).map(r => r.id)).toEqual(['3']) + expect(filterCapas(rows, { ...EMPTY_FILTERS, q: 'sc3-' }).map(r => r.id)).toEqual(['2']) + expect(filterCapas(rows, { ...EMPTY_FILTERS, q: 'ravi' }).map(r => r.id)).toEqual(['2']) + }) + + it('filters by owner, department and priority', () => { + expect(filterCapas(rows, { ...EMPTY_FILTERS, owner: 'Tan Mei Ling' }).map(r => r.id)).toEqual(['1', '3']) + expect(filterCapas(rows, { ...EMPTY_FILTERS, department: 'Operations' }).map(r => r.id)).toEqual(['2', '4']) + expect(filterCapas(rows, { ...EMPTY_FILTERS, priority: 'low' }).map(r => r.id)).toEqual(['2', '4']) + }) + + it('filters by saved view', () => { + expect(filterCapas(rows, { ...EMPTY_FILTERS, view: 'overdue' }).map(r => r.id)).toEqual(['1']) + expect(filterCapas(rows, { ...EMPTY_FILTERS, view: 'active' }).map(r => r.id)).toEqual(['2']) + expect(filterCapas(rows, { ...EMPTY_FILTERS, view: 'verification' }).map(r => r.id)).toEqual(['3']) + expect(filterCapas(rows, { ...EMPTY_FILTERS, view: 'done' }).map(r => r.id)).toEqual(['4']) + }) + + it('combines filters', () => { + expect(filterCapas(rows, { ...EMPTY_FILTERS, owner: 'Tan Mei Ling', view: 'overdue' }).map(r => r.id)).toEqual(['1']) + }) +}) + +describe('viewCounts', () => { + it('counts each view with the other filters applied', () => { + expect(viewCounts(rows, EMPTY_FILTERS)).toEqual({ all: 4, active: 1, overdue: 1, verification: 1, done: 1 }) + expect(viewCounts(rows, { ...EMPTY_FILTERS, owner: 'Tan Mei Ling', view: 'done' })).toEqual({ all: 2, active: 0, overdue: 1, verification: 1, done: 0 }) + }) +}) + +describe('sortCapas', () => { + it('sorts by due date both ways without mutating the input', () => { + const copy = [...rows] + expect(sortCapas(rows, { key: 'due_date', dir: 'asc' }).map(r => r.id)).toEqual(['4', '1', '3', '2']) + expect(sortCapas(rows, { key: 'due_date', dir: 'desc' }).map(r => r.id)).toEqual(['2', '3', '1', '4']) + expect(rows).toEqual(copy) + }) + + it('sorts priority high first and status in board order', () => { + expect(sortCapas(rows, { key: 'priority', dir: 'asc' }).map(r => r.id)).toEqual(['1', '3', '2', '4']) + expect(sortCapas(rows, { key: 'status', dir: 'asc' }).map(r => r.id)).toEqual(['2', '1', '3', '4']) + }) +}) + +describe('nextSort', () => { + it('flips the direction on the same column and starts a new one ascending', () => { + expect(nextSort({ key: 'due_date', dir: 'asc' }, 'due_date')).toEqual({ key: 'due_date', dir: 'desc' }) + expect(nextSort({ key: 'due_date', dir: 'desc' }, 'priority')).toEqual({ key: 'priority', dir: 'asc' }) + }) +}) + +describe('paginate', () => { + const many = Array.from({ length: 27 }, (_, i) => i + 1) + + it('slices a page and reports the range', () => { + expect(paginate(many, 1, 25)).toMatchObject({ from: 1, to: 25, total: 27, page: 1, pageCount: 2 }) + expect(paginate(many, 2, 25)).toMatchObject({ from: 26, to: 27, items: [26, 27], page: 2 }) + }) + + it('clamps an out-of-range page and handles empty input', () => { + expect(paginate(many, 9, 25).page).toBe(2) + expect(paginate(many, 0, 25).page).toBe(1) + expect(paginate([], 1, 25)).toMatchObject({ from: 0, to: 0, total: 0, page: 1, pageCount: 1, items: [] }) + }) +}) + +describe('distinct and daysLate', () => { + it('returns sorted unique non-empty values', () => { + expect(distinct(['b', 'a', 'b', null, undefined, ''])).toEqual(['a', 'b']) + }) + + it('counts whole days past the due date, never negative', () => { + expect(daysLate('2026-09-12', '2026-09-27')).toBe(15) + expect(daysLate('2026-10-10', '2026-09-27')).toBe(0) + }) +}) +``` + +- [ ] **Step 3: Run it to verify it fails** + +Run: `npx vitest run tests/lib/capa/list.test.ts 2>&1 | grep -E "Test Files|Failed to resolve"` +Expected: FAIL (`Failed to resolve import "@/lib/capa/list"`). + +- [ ] **Step 4: Write `lib/capa/list.ts`** + +```ts +export type CapaStatus = + | 'open' | 'in_progress' | 'overdue' | 'pending_verification' | 'verified' | 'reopened' | 'closed' +export type CapaPriority = 'low' | 'med' | 'high' + +export interface CapaRow { + id: string + incident_id: string + description: string + department: string + due_date: string + priority: CapaPriority + status: CapaStatus + incident_ref: string | null + owner_name: string | null +} + +export const PAGE_SIZE = 25 + +export const STATUS_ORDER: CapaStatus[] = [ + 'open', 'in_progress', 'overdue', 'reopened', 'pending_verification', 'verified', 'closed', +] + +export type CapaViewKey = 'all' | 'active' | 'overdue' | 'verification' | 'done' + +export const VIEWS: Array<{ key: CapaViewKey; label: string; statuses: CapaStatus[] | null }> = [ + { key: 'all', label: 'All', statuses: null }, + { key: 'active', label: 'Active', statuses: ['open', 'in_progress', 'reopened'] }, + { key: 'overdue', label: 'Overdue', statuses: ['overdue'] }, + { key: 'verification', label: 'Verification', statuses: ['pending_verification'] }, + { key: 'done', label: 'Done', statuses: ['verified', 'closed'] }, +] + +export interface CapaFilters { + q: string + owner: string + department: string + priority: string + view: CapaViewKey +} + +export const EMPTY_FILTERS: CapaFilters = { q: '', owner: '', department: '', priority: '', view: 'all' } + +export type CapaSortKey = 'due_date' | 'priority' | 'status' +export type CapaSort = { key: CapaSortKey; dir: 'asc' | 'desc' } + +function matchesOthers(r: CapaRow, f: CapaFilters): boolean { + if (f.owner && r.owner_name !== f.owner) return false + if (f.department && r.department !== f.department) return false + if (f.priority && r.priority !== f.priority) return false + if (f.q) { + const q = f.q.toLowerCase() + const hay = `${r.description} ${r.incident_ref ?? ''} ${r.owner_name ?? ''}`.toLowerCase() + if (!hay.includes(q)) return false + } + return true +} + +function inView(r: CapaRow, view: CapaViewKey): boolean { + const statuses = VIEWS.find(v => v.key === view)?.statuses ?? null + return statuses === null || statuses.includes(r.status) +} + +export function filterCapas(rows: CapaRow[], f: CapaFilters): CapaRow[] { + return rows.filter(r => matchesOthers(r, f) && inView(r, f.view)) +} + +export function viewCounts(rows: CapaRow[], f: CapaFilters): Record { + const scoped = rows.filter(r => matchesOthers(r, f)) + const counts = {} as Record + for (const v of VIEWS) counts[v.key] = scoped.filter(r => inView(r, v.key)).length + return counts +} + +const PRIORITY_RANK: Record = { high: 0, med: 1, low: 2 } + +export function sortCapas(rows: CapaRow[], sort: CapaSort): CapaRow[] { + const sign = sort.dir === 'asc' ? 1 : -1 + const key = (r: CapaRow): number | string => + sort.key === 'priority' ? PRIORITY_RANK[r.priority] + : sort.key === 'status' ? STATUS_ORDER.indexOf(r.status) + : r.due_date + return [...rows].sort((a, b) => { + const ka = key(a) + const kb = key(b) + return ka < kb ? -sign : ka > kb ? sign : 0 + }) +} + +export function nextSort(current: CapaSort, key: CapaSortKey): CapaSort { + if (current.key === key) return { key, dir: current.dir === 'asc' ? 'desc' : 'asc' } + return { key, dir: 'asc' } +} + +export function paginate(rows: T[], page: number, size: number) { + const total = rows.length + const pageCount = Math.max(1, Math.ceil(total / size)) + const p = Math.min(Math.max(1, page), pageCount) + const items = rows.slice((p - 1) * size, p * size) + const from = items.length === 0 ? 0 : (p - 1) * size + 1 + const to = items.length === 0 ? 0 : from + items.length - 1 + return { items, from, to, total, page: p, pageCount } +} + +export function distinct(values: Array): string[] { + return [...new Set(values.filter((v): v is string => Boolean(v)))].sort() +} + +export function daysLate(due: string, today: string): number { + const diff = Math.round((Date.parse(today) - Date.parse(due)) / 86_400_000) + return Math.max(0, diff) +} +``` + +- [ ] **Step 5: Run the test, tsc and the gate** + +```bash +npx vitest run tests/lib/capa/list.test.ts 2>&1 | grep -E "Test Files|Tests |×" +npx tsc --noEmit 2>&1 | head -5; echo "tsc done" +npm run check:design 2>&1 | tail -2 +``` + +Expected: all pass (14 tests), `tsc` prints nothing, `design gates: clean`. If the status-sort expectation fails, remember `STATUS_ORDER` puts `in_progress` (index 1) before `overdue` (2) and `pending_verification` (4) before `closed` (6), so `['2','1','3','4']` is correct. + +- [ ] **Step 6: Commit** + +```bash +git add lib/capa/list.ts tests/lib/capa/list.test.ts +git commit -m "feat(capa): add pure list helpers for filtering, saved views, sorting and paging + +Co-Authored-By: Claude Haiku 4.5 " +``` + +--- + +### Task 2: CAPA workspace (list and board) and the list page + +**Files:** +- Create: `components/capa/capa-workspace.tsx`, `components/capa/capa-board-view.tsx` +- Modify: `app/(protected)/hse/capa/page.tsx` (full rewrite) +- Delete: `components/capa/capa-board.tsx` +- Test: `tests/components/capa/capa-workspace.test.tsx` + +**Interfaces:** +- Consumes: everything exported by `@/lib/capa/list` (Task 1); `TableCard`, `Column`, `Segmented`, `FilterChip`, `Avatar`, `StatusTag`, `PriorityTag` from `@/components/ui/*`. +- Produces: `CapaWorkspace({ capas: CapaRow[]; today: string })` and `CapaBoardView({ capas: CapaRow[]; today: string })`. + +- [ ] **Step 1: Write the failing test** + +Create `tests/components/capa/capa-workspace.test.tsx`: + +```tsx +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, fireEvent, within } from '@testing-library/react' + +const push = vi.fn() +vi.mock('next/navigation', () => ({ useRouter: () => ({ push }) })) + +import { CapaWorkspace } from '@/components/capa/capa-workspace' +import type { CapaRow } from '@/lib/capa/list' + +const row = (over: Partial): CapaRow => ({ + id: 'x', incident_id: 'i', description: 'Fit guard rail', department: 'Facilities', due_date: '2026-10-10', + priority: 'med', status: 'open', incident_ref: 'SC1-202607-0001', owner_name: 'Tan Mei Ling', ...over, +}) + +const capas: CapaRow[] = [ + row({ id: '1', description: 'Anti-slip coating', due_date: '2026-09-12', priority: 'high', status: 'overdue', owner_name: 'Tan Mei Ling', department: 'Facilities' }), + row({ id: '2', description: 'Forklift refresher', due_date: '2026-10-20', priority: 'low', status: 'in_progress', owner_name: 'Ravi Kumar', department: 'Operations', incident_ref: 'SC3-202607-0002' }), + row({ id: '3', description: 'Guard rail repair', due_date: '2026-10-01', priority: 'med', status: 'pending_verification', owner_name: 'Tan Mei Ling', department: 'Facilities' }), + row({ id: '4', description: 'Signage', due_date: '2026-08-30', priority: 'low', status: 'closed', owner_name: null, department: 'Operations' }), +] +const today = '2026-09-27' + +const desktopRows = () => screen.getAllByRole('row').slice(1) + +beforeEach(() => push.mockClear()) + +describe('CapaWorkspace list', () => { + it('renders a TableCard with the action, incident, owner, tags and a late indicator', () => { + render() + expect(screen.getAllByText('Anti-slip coating').length).toBeGreaterThan(0) + expect(screen.getAllByText('SC1-202607-0001').length).toBeGreaterThan(0) + expect(screen.getAllByText('Ravi Kumar').length).toBeGreaterThan(0) + expect(screen.getAllByText('Overdue').some(el => el.className.includes('bg-st-red-bg'))).toBe(true) + expect(screen.getAllByText('High').some(el => el.className.includes('bg-st-orange-bg'))).toBe(true) + expect(screen.getByText('15 days late')).toBeTruthy() + expect(screen.getByText('Showing 1–4 of 4')).toBeTruthy() + }) + + it('shows saved views with counts and filters by view', () => { + render() + expect(screen.getByRole('button', { name: /All/ }).className).toContain('bg-rule-2') + fireEvent.click(screen.getByRole('button', { name: /Overdue/ })) + expect(screen.queryAllByText('Forklift refresher')).toHaveLength(0) + expect(screen.getAllByText('Anti-slip coating').length).toBeGreaterThan(0) + expect(screen.getByText('Showing 1–1 of 1')).toBeTruthy() + }) + + it('searches across action, incident and owner', () => { + render() + fireEvent.change(screen.getByRole('searchbox', { name: 'Search actions' }), { target: { value: 'guard' } }) + expect(screen.getAllByText('Guard rail repair').length).toBeGreaterThan(0) + expect(screen.queryAllByText('Signage')).toHaveLength(0) + }) + + it('filters by owner chip and clears the filters', () => { + render() + fireEvent.change(screen.getByLabelText('Owner'), { target: { value: 'Ravi Kumar' } }) + expect(screen.queryAllByText('Anti-slip coating')).toHaveLength(0) + expect(screen.getAllByText('Forklift refresher').length).toBeGreaterThan(0) + fireEvent.click(screen.getByRole('button', { name: 'Clear filters' })) + expect(screen.getAllByText('Anti-slip coating').length).toBeGreaterThan(0) + }) + + it('sorts by due date ascending by default and flips on the header', () => { + render() + expect(desktopRows()[0].textContent).toContain('Signage') + fireEvent.click(screen.getByRole('button', { name: /Due/ })) + expect(desktopRows()[0].textContent).toContain('Forklift refresher') + }) + + it('opens a CAPA from its row', () => { + render() + fireEvent.click(desktopRows().find(r => r.textContent?.includes('Anti-slip coating'))!) + expect(push).toHaveBeenCalledWith('/hse/capa/1') + }) + + it('shows an empty state when nothing matches', () => { + render() + fireEvent.change(screen.getByRole('searchbox', { name: 'Search actions' }), { target: { value: 'zzzz' } }) + expect(screen.getByText('No CAPA actions match')).toBeTruthy() + expect(screen.queryByText(/Showing/)).toBeNull() + }) +}) + +describe('CapaWorkspace board', () => { + it('switches to a board of status columns with counts and card links', () => { + render() + fireEvent.click(screen.getByRole('button', { name: 'Board' })) + expect(screen.queryByRole('table')).toBeNull() + const col = screen.getByRole('region', { name: 'in progress column' }) + expect(within(col).getByText('1')).toBeTruthy() + expect(within(col).getByRole('link', { name: /Forklift refresher/ }).getAttribute('href')).toBe('/hse/capa/2') + expect(screen.getByRole('region', { name: 'reopened column' })).toBeTruthy() + expect(within(screen.getByRole('region', { name: 'reopened column' })).getByText('Empty')).toBeTruthy() + }) + + it('keeps the search and chip filters on the board', () => { + render() + fireEvent.click(screen.getByRole('button', { name: 'Board' })) + fireEvent.change(screen.getByLabelText('Owner'), { target: { value: 'Ravi Kumar' } }) + expect(screen.queryByRole('link', { name: /Anti-slip coating/ })).toBeNull() + expect(screen.getByRole('link', { name: /Forklift refresher/ })).toBeTruthy() + }) +}) +``` + +- [ ] **Step 2: Run it to verify it fails** + +Run: `npx vitest run tests/components/capa/capa-workspace.test.tsx 2>&1 | grep -E "Test Files|Failed to resolve"` +Expected: FAIL (`Failed to resolve import "@/components/capa/capa-workspace"`). + +- [ ] **Step 3: Write `components/capa/capa-board-view.tsx`** + +```tsx +import Link from 'next/link' +import { Avatar } from '@/components/ui/avatar' +import { PriorityTag, StatusTag } from '@/components/ui/status-tag' +import { STATUS_ORDER, type CapaRow } from '@/lib/capa/list' + +export function CapaBoardView({ capas }: { capas: CapaRow[]; today: string }) { + return ( +
+ {STATUS_ORDER.map(status => { + const items = capas.filter(c => c.status === status) + return ( +
+
+ + {items.length} +
+
+ {items.map(c => ( + +

{c.description}

+

{c.incident_ref ?? '—'}

+
+ + {c.owner_name && } + {c.owner_name ?? '—'} + + +
+

Due {c.due_date}

+ + ))} + {items.length === 0 &&

Empty

} +
+
+ ) + })} +
+ ) +} +``` + +(`today` stays in the props type so the workspace passes one shape to both views; the board does not use it yet. If `tsc` or lint flags it, drop it from both places.) + +- [ ] **Step 4: Write `components/capa/capa-workspace.tsx`** + +```tsx +'use client' + +import { useMemo, useState } from 'react' +import { useRouter } from 'next/navigation' +import { ChevronRight, Columns3, List, Search } from 'lucide-react' +import { Avatar } from '@/components/ui/avatar' +import { FilterChip } from '@/components/ui/filter-chip' +import { Segmented } from '@/components/ui/segmented' +import { PriorityTag, StatusTag } from '@/components/ui/status-tag' +import { TableCard, type Column } from '@/components/ui/table-card' +import { + EMPTY_FILTERS, PAGE_SIZE, VIEWS, daysLate, distinct, filterCapas, nextSort, paginate, sortCapas, viewCounts, + type CapaFilters, type CapaRow, type CapaSort, type CapaSortKey, type CapaViewKey, +} from '@/lib/capa/list' +import { CapaBoardView } from './capa-board-view' + +const PRIORITY_OPTIONS = [ + { value: 'high', label: 'High' }, + { value: 'med', label: 'Medium' }, + { value: 'low', label: 'Low' }, +] + +const toOptions = (values: string[]) => values.map(v => ({ value: v, label: v })) + +function Owner({ name }: { name: string | null }) { + if (!name) return — + return ( + + + {name} + + ) +} + +function Due({ row, today }: { row: CapaRow; today: string }) { + const late = row.status === 'overdue' ? daysLate(row.due_date, today) : 0 + return ( + + {row.due_date} + {late > 0 && {`${late} day${late === 1 ? '' : 's'} late`}} + + ) +} + +export function CapaWorkspace({ capas, today }: { capas: CapaRow[]; today: string }) { + const router = useRouter() + const [mode, setMode] = useState<'list' | 'board'>('list') + const [filters, setFilters] = useState(EMPTY_FILTERS) + const [sort, setSort] = useState({ key: 'due_date', dir: 'asc' }) + const [page, setPage] = useState(1) + + const patch = (next: Partial) => { + setFilters(f => ({ ...f, ...next })) + setPage(1) + } + + const owners = useMemo(() => distinct(capas.map(c => c.owner_name)), [capas]) + const departments = useMemo(() => distinct(capas.map(c => c.department)), [capas]) + const counts = useMemo(() => viewCounts(capas, filters), [capas, filters]) + const sorted = useMemo(() => sortCapas(filterCapas(capas, filters), sort), [capas, filters, sort]) + const boardRows = useMemo( + () => sortCapas(filterCapas(capas, { ...filters, view: 'all' }), { key: 'due_date', dir: 'asc' }), + [capas, filters], + ) + const pageData = paginate(sorted, page, PAGE_SIZE) + const clearable = Boolean(filters.q || filters.owner || filters.department || filters.priority) + + const columns: Column[] = [ + { key: 'action', header: 'Action', cell: r => {r.description} }, + { key: 'incident', header: 'Incident', cell: r => {r.incident_ref ?? '—'} }, + { key: 'owner', header: 'Owner', cell: r => }, + { key: 'department', header: 'Department', cell: r => r.department }, + { key: 'priority', header: 'Priority', sortKey: 'priority', cell: r => }, + { key: 'due', header: 'Due', sortKey: 'due_date', cell: r => }, + { key: 'status', header: 'Status', sortKey: 'status', cell: r => }, + ] + + const toolbar = ( + <> + + patch({ owner: v })} /> + patch({ department: v })} /> + patch({ priority: v })} /> + {clearable && ( + + )} + + ) + + return ( +
+
+

CAPA

+ setMode(v as 'list' | 'board')} + options={[ + { value: 'list', label: <>List }, + { value: 'board', label: <>Board }, + ]} + /> +
+ + {mode === 'list' ? ( + r.id} + onRowOpen={r => router.push(`/hse/capa/${r.id}`)} + views={{ + items: VIEWS.map(v => ({ key: v.key, label: v.label, count: counts[v.key] })), + active: filters.view, + onChange: key => patch({ view: key as CapaViewKey }), + }} + toolbar={toolbar} + sort={sort} + onSortChange={key => { + setSort(nextSort(sort, key as CapaSortKey)) + setPage(1) + }} + footer={ + pageData.total > 0 + ? { from: pageData.from, to: pageData.to, total: pageData.total, page: pageData.page, pageCount: pageData.pageCount, onPage: setPage } + : undefined + } + empty={{ title: 'No CAPA actions match' }} + mobileRow={r => ( +
+
+

{r.description}

+
+ + +
+

+ {[r.incident_ref, r.owner_name, `Due ${r.due_date}`].filter(Boolean).join(' · ')} +

+
+ +
+ )} + /> + ) : ( +
+
{toolbar}
+ +
+ )} +
+ ) +} +``` + +- [ ] **Step 5: Rewrite the list page** + +Read `app/(protected)/hse/capa/page.tsx` first (the harness requires it), then replace it entirely: + +```tsx +export const dynamic = 'force-dynamic' + +import { redirect } from 'next/navigation' +import { asAdmin } from '@/lib/db/with-user' +import { getSession } from '@/lib/auth/get-session' +import { capaActions, incidents, users } from '@/lib/db/schema' +import { eq, asc } from 'drizzle-orm' +import { aliasedTable } from 'drizzle-orm' +import { CapaWorkspace } from '@/components/capa/capa-workspace' +import type { CapaRow, CapaStatus } from '@/lib/capa/list' + +export default async function CapaListPage() { + const session = await getSession() + if (!session) redirect('/login?redirect=/hse/capa') + + const ownerAlias = aliasedTable(users, 'owner') + + const rows = await asAdmin(db => + db.select({ + id: capaActions.id, + incidentId: capaActions.incidentId, + description: capaActions.description, + department: capaActions.department, + dueDate: capaActions.dueDate, + priority: capaActions.priority, + status: capaActions.status, + incidentRefNo: incidents.referenceNo, + ownerName: ownerAlias.name, + }) + .from(capaActions) + .leftJoin(incidents, eq(capaActions.incidentId, incidents.id)) + .leftJoin(ownerAlias, eq(capaActions.ownerUserId, ownerAlias.id)) + .orderBy(asc(capaActions.dueDate)) + ) + + const today = new Date().toISOString().slice(0, 10) + const capas: CapaRow[] = rows.map(r => ({ + id: r.id, + incident_id: r.incidentId, + description: r.description, + department: r.department, + due_date: r.dueDate, + priority: r.priority, + status: ((r.status === 'open' || r.status === 'in_progress') && r.dueDate && r.dueDate < today + ? 'overdue' + : r.status) as CapaStatus, + incident_ref: r.incidentRefNo ?? null, + owner_name: r.ownerName ?? null, + })) + + return ( +
+ +
+ ) +} +``` + +Behaviour changes from the old board, both intentional: the old board hid `reopened` actions (it had no column for them), the new board has a Reopened column; and the page no longer renders its own "CAPA Board" heading and back link, because the workspace renders the heading and the shell provides navigation. + +- [ ] **Step 6: Delete the old board and run everything** + +```bash +git rm -q components/capa/capa-board.tsx +grep -rn "capa-board'" app components tests | head -3; echo "(nothing above = no dangling imports)" +npx vitest run tests/components/capa tests/lib/capa 2>&1 | grep -E "Test Files|Tests |×" +npm run check:design 2>&1 | tail -2 +npx tsc --noEmit 2>&1 | head -8; echo "tsc done" +npx vitest run 2>&1 | grep -E "Test Files|Tests " +``` + +Expected: capa tests pass (the 14 helper tests, the 9 workspace tests and the 6 existing owner-action tests), `design gates: clean`, `tsc` prints nothing, and the full suite shows exactly the 7 baseline failures. If `getByText('1')` in the board test matches more than one element, scope it as written (`within(col)`); the column's count is the only bare `1` inside that column. + +- [ ] **Step 7: Commit** + +```bash +git add components/capa "app/(protected)/hse/capa/page.tsx" tests/components/capa +git commit -m "feat(capa): replace the CAPA board with a workspace (TableCard list and status board) with search, filters and saved views + +Co-Authored-By: Claude Haiku 4.5 " +``` + +--- + +### Task 3: CAPA detail page, verification, close, owner actions and notes + +**Files:** +- Modify: `app/(protected)/hse/capa/[id]/page.tsx` (full rewrite), `components/capa/verify-form.tsx` (full rewrite), `components/capa/close-capa-button.tsx` (full rewrite), `components/capa/capa-owner-actions.tsx` (full rewrite), `components/capa/capa-owner-notes-form.tsx` (full rewrite) +- Test: `tests/components/capa/verify-form.test.tsx`, `tests/components/capa/capa-owner-notes-form.test.tsx`, existing `tests/components/capa/capa-owner-actions.test.tsx` must keep passing unchanged + +**Interfaces:** +- Consumes: `Button`, `Field`, `Textarea`, `Card`, `Avatar`, `StatusTag`, `PriorityTag` (slice 1); `daysLate` from `@/lib/capa/list` (Task 1). +- Produces: unchanged component APIs: `VerifyForm({ capaId })`, `CloseCapaButton({ capaId })`, `CapaOwnerActions({ capaId, currentStatus })`, `CapaOwnerNotesForm({ capaId, initialNotes })`. Every `fetch` URL, method, body and redirect stays exactly as it is today (`POST /api/capa/:id/verify` with `{ verdict, reopen_reason }` then `router.push('/hse/capa')`; `PATCH /api/capa/:id` with `{ status: 'closed' }` or `{ owner_notes }`). + +- [ ] **Step 1: Write the failing tests** + +Create `tests/components/capa/verify-form.test.tsx`: + +```tsx +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' + +const push = vi.fn() +const refresh = vi.fn() +vi.mock('next/navigation', () => ({ useRouter: () => ({ push, refresh }) })) + +import { VerifyForm } from '@/components/capa/verify-form' + +const ok = () => vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }) + +beforeEach(() => { + push.mockClear() + refresh.mockClear() + vi.stubGlobal('fetch', ok()) +}) + +describe('VerifyForm', () => { + it('offers two verdict cards and no submit button until one is chosen', () => { + render() + expect(screen.getByRole('radio', { name: /Verified, effective/ })).toBeTruthy() + expect(screen.getByRole('radio', { name: /Reopen, ineffective/ })).toBeTruthy() + expect(screen.queryByRole('button', { name: /Confirm verification|Reopen action/ })).toBeNull() + }) + + it('marks the chosen card and shows the matching submit label', () => { + render() + fireEvent.click(screen.getByRole('radio', { name: /Verified, effective/ })) + expect(screen.getByRole('radio', { name: /Verified, effective/ }).getAttribute('aria-checked')).toBe('true') + expect(screen.getByRole('radio', { name: /Reopen, ineffective/ }).getAttribute('aria-checked')).toBe('false') + expect(screen.getByRole('button', { name: 'Confirm verification' })).toBeTruthy() + fireEvent.click(screen.getByRole('radio', { name: /Reopen, ineffective/ })) + expect(screen.getByRole('button', { name: 'Reopen action' })).toBeTruthy() + }) + + it('posts a verified verdict and returns to the CAPA list', async () => { + render() + fireEvent.click(screen.getByRole('radio', { name: /Verified, effective/ })) + fireEvent.click(screen.getByRole('button', { name: 'Confirm verification' })) + await waitFor(() => expect(push).toHaveBeenCalledWith('/hse/capa')) + expect(fetch).toHaveBeenCalledWith('/api/capa/c1/verify', expect.objectContaining({ + method: 'POST', + body: JSON.stringify({ verdict: 'verified', reopen_reason: null }), + })) + }) + + it('requires a reason to reopen and does not call the API without one', () => { + const { container } = render() + fireEvent.click(screen.getByRole('radio', { name: /Reopen, ineffective/ })) + fireEvent.submit(container.querySelector('form')!) + expect(screen.getByRole('alert').textContent).toBe('Reopen reason is required') + expect(fetch).not.toHaveBeenCalled() + }) + + it('posts the reason when reopening', async () => { + const { container } = render() + fireEvent.click(screen.getByRole('radio', { name: /Reopen, ineffective/ })) + fireEvent.change(screen.getByLabelText(/Why is the action ineffective/), { target: { value: 'Coating peeled' } }) + fireEvent.submit(container.querySelector('form')!) + await waitFor(() => expect(push).toHaveBeenCalledWith('/hse/capa')) + expect(fetch).toHaveBeenCalledWith('/api/capa/c1/verify', expect.objectContaining({ + body: JSON.stringify({ verdict: 'reopened', reopen_reason: 'Coating peeled' }), + })) + }) + + it('shows the API error in a red banner and stays on the page', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, json: async () => ({ error: 'Not allowed' }) })) + render() + fireEvent.click(screen.getByRole('radio', { name: /Verified, effective/ })) + fireEvent.click(screen.getByRole('button', { name: 'Confirm verification' })) + const alert = await screen.findByRole('alert') + expect(alert.textContent).toBe('Not allowed') + expect(alert.className).toContain('bg-st-red-bg') + expect(push).not.toHaveBeenCalled() + }) +}) +``` + +Create `tests/components/capa/capa-owner-notes-form.test.tsx`: + +```tsx +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import { CapaOwnerNotesForm } from '@/components/capa/capa-owner-notes-form' + +beforeEach(() => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) })) +}) + +describe('CapaOwnerNotesForm', () => { + it('shows the saved notes and saves edits with PATCH', async () => { + render() + const box = screen.getByLabelText('Remarks / Notes') as HTMLTextAreaElement + expect(box.value).toBe('Ramp ground back') + fireEvent.change(box, { target: { value: 'Ramp ground back and coated' } }) + fireEvent.click(screen.getByRole('button', { name: 'Save Notes' })) + await waitFor(() => expect(screen.getByText('Saved')).toBeTruthy()) + expect(fetch).toHaveBeenCalledWith('/api/capa/c9', expect.objectContaining({ + method: 'PATCH', + body: JSON.stringify({ owner_notes: 'Ramp ground back and coated' }), + })) + }) + + it('shows an error when the save fails', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, json: async () => ({}) })) + render() + fireEvent.click(screen.getByRole('button', { name: 'Save Notes' })) + expect((await screen.findByRole('alert')).textContent).toBe('Failed to save. Please try again.') + }) +}) +``` + +- [ ] **Step 2: Run them to verify they fail** + +Run: `npx vitest run tests/components/capa/verify-form.test.tsx tests/components/capa/capa-owner-notes-form.test.tsx 2>&1 | grep -E "Test Files|Tests |×" | head -8` +Expected: FAIL (the verify form has no radios and no `role="alert"`; the notes form's textarea has no accessible label). + +- [ ] **Step 3: Rewrite `components/capa/verify-form.tsx`** + +Read the file first (the harness requires it), then replace it entirely: + +```tsx +'use client' + +import { useState } from 'react' +import { useRouter } from 'next/navigation' +import { Button } from '@/components/ui/button' +import { Field, Textarea } from '@/components/ui/field' +import { cx } from '@/components/ui/cx' + +interface Props { + capaId: string +} + +type Verdict = 'verified' | 'reopened' + +function Choice({ + selected, + onSelect, + title, + hint, +}: { + selected: boolean + onSelect: () => void + title: string + hint: string +}) { + return ( + + ) +} + +export function VerifyForm({ capaId }: Props) { + const router = useRouter() + const [verdict, setVerdict] = useState(null) + const [reopenReason, setReopenReason] = useState('') + const [saving, setSaving] = useState(false) + const [error, setError] = useState(null) + + async function handleSubmit(e: React.FormEvent) { + e.preventDefault() + if (!verdict) return + if (verdict === 'reopened' && !reopenReason.trim()) { + setError('Reopen reason is required') + return + } + setSaving(true) + setError(null) + const res = await fetch(`/api/capa/${capaId}/verify`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ verdict, reopen_reason: reopenReason || null }), + }) + if (!res.ok) { + const data = await res.json() + setError(data.error ?? 'Verification failed') + setSaving(false) + return + } + router.push('/hse/capa') + router.refresh() + } + + return ( +
+
+

Verify this action

+

Confirm the corrective action fixed the root cause, or send it back.

+
+ +
+ setVerdict('verified')} + title="Verified, effective" + hint="Root cause addressed. The action is marked verified." + /> + setVerdict('reopened')} + title="Reopen, ineffective" + hint="Returns to the owner with a required reason." + /> +
+ + {verdict === 'reopened' && ( + +