Files
ims/docs/superpowers/plans/2026-10-01-ims-admin-refresh-slice-2-capa.md
T

75 KiB
Raw Blame History

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):
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<CapaViewKey, number>
export function sortCapas(rows: CapaRow[], sort: CapaSort): CapaRow[]
export function paginate<T>(rows: T[], page: number, size: number): { items: T[]; from: number; to: number; total: number; page: number; pageCount: number }
export function distinct(values: Array<string | null | undefined>): 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).

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:

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>): 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
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<CapaViewKey, number> {
  const scoped = rows.filter(r => matchesOthers(r, f))
  const counts = {} as Record<CapaViewKey, number>
  for (const v of VIEWS) counts[v.key] = scoped.filter(r => inView(r, v.key)).length
  return counts
}

const PRIORITY_RANK: Record<CapaPriority, number> = { 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<T>(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 | null | undefined>): 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
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
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 <noreply@anthropic.com>"

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[] }).

  • Step 1: Write the failing test

Create tests/components/capa/capa-workspace.test.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>): 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(<CapaWorkspace capas={capas} today={today} />)
    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(<CapaWorkspace capas={capas} today={today} />)
    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(<CapaWorkspace capas={capas} today={today} />)
    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(<CapaWorkspace capas={capas} today={today} />)
    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(<CapaWorkspace capas={capas} today={today} />)
    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(<CapaWorkspace capas={capas} today={today} />)
    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(<CapaWorkspace capas={capas} today={today} />)
    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(<CapaWorkspace capas={capas} today={today} />)
    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(<CapaWorkspace capas={capas} today={today} />)
    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
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[] }) {
  return (
    <div className="flex gap-3 overflow-x-auto pb-2">
      {STATUS_ORDER.map(status => {
        const items = capas.filter(c => c.status === status)
        return (
          <section
            key={status}
            aria-label={`${status.replace(/_/g, ' ')} column`}
            className="w-72 shrink-0 rounded-xl bg-surface-2 p-2"
          >
            <header className="flex items-center gap-2 px-1.5 pb-2">
              <StatusTag status={status} />
              <span className="text-xs text-faint">{items.length}</span>
            </header>
            <div className="space-y-2 max-h-[70vh] overflow-y-auto">
              {items.map(c => (
                <Link
                  key={c.id}
                  href={`/hse/capa/${c.id}`}
                  className="block rounded-md bg-surface p-3 shadow-card transition-shadow hover:shadow-float"
                >
                  <p className="text-[13px] font-medium line-clamp-2">{c.description}</p>
                  <p className="mt-1 font-mono text-[12px] text-accent">{c.incident_ref ?? '—'}</p>
                  <div className="mt-2 flex items-center justify-between gap-2">
                    <span className="flex min-w-0 items-center gap-1.5 text-xs text-muted">
                      {c.owner_name && <Avatar name={c.owner_name} />}
                      <span className="truncate">{c.owner_name ?? '—'}</span>
                    </span>
                    <PriorityTag priority={c.priority} />
                  </div>
                  <p className="mt-1.5 text-xs text-faint">Due {c.due_date}</p>
                </Link>
              ))}
              {items.length === 0 && <p className="px-1.5 py-3 text-xs text-faint">Empty</p>}
            </div>
          </section>
        )
      })}
    </div>
  )
}

(The board takes only capas; it does not need today.)

  • Step 4: Write components/capa/capa-workspace.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 <span className="text-faint">—</span>
  return (
    <span className="inline-flex items-center gap-2">
      <Avatar name={name} />
      {name}
    </span>
  )
}

function Due({ row, today }: { row: CapaRow; today: string }) {
  const late = row.status === 'overdue' ? daysLate(row.due_date, today) : 0
  return (
    <span className="whitespace-nowrap">
      {row.due_date}
      {late > 0 && <span className="ml-1.5 text-xs text-danger">{`${late} day${late === 1 ? '' : 's'} late`}</span>}
    </span>
  )
}

export function CapaWorkspace({ capas, today }: { capas: CapaRow[]; today: string }) {
  const router = useRouter()
  const [mode, setMode] = useState<'list' | 'board'>('list')
  const [filters, setFilters] = useState<CapaFilters>(EMPTY_FILTERS)
  const [sort, setSort] = useState<CapaSort>({ key: 'due_date', dir: 'asc' })
  const [page, setPage] = useState(1)

  const patch = (next: Partial<CapaFilters>) => {
    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<CapaRow>[] = [
    { key: 'action', header: 'Action', cell: r => <span className="line-clamp-2 font-medium">{r.description}</span> },
    { key: 'incident', header: 'Incident', cell: r => <span className="font-mono text-[12.5px] text-accent">{r.incident_ref ?? '—'}</span> },
    { key: 'owner', header: 'Owner', cell: r => <Owner name={r.owner_name} /> },
    { key: 'department', header: 'Department', cell: r => r.department },
    { key: 'priority', header: 'Priority', sortKey: 'priority', cell: r => <PriorityTag priority={r.priority} /> },
    { key: 'due', header: 'Due', sortKey: 'due_date', cell: r => <Due row={r} today={today} /> },
    { key: 'status', header: 'Status', sortKey: 'status', cell: r => <StatusTag status={r.status} /> },
  ]

  const toolbar = (
    <>
      <label className="flex h-8 min-w-[260px] items-center gap-2 rounded-md bg-surface px-2.5 text-[13px] shadow-input">
        <Search size={16} strokeWidth={2} className="text-muted" aria-hidden />
        <input
          type="search"
          aria-label="Search actions"
          placeholder="Search action, incident or owner"
          value={filters.q}
          onChange={e => patch({ q: e.target.value })}
          className="flex-1 bg-transparent outline-none placeholder:text-faint"
        />
      </label>
      <FilterChip label="Owner" value={filters.owner} options={toOptions(owners)} onChange={v => patch({ owner: v })} />
      <FilterChip label="Department" value={filters.department} options={toOptions(departments)} onChange={v => patch({ department: v })} />
      <FilterChip label="Priority" value={filters.priority} options={PRIORITY_OPTIONS} onChange={v => patch({ priority: v })} />
      {clearable && (
        <button
          type="button"
          onClick={() => patch({ q: '', owner: '', department: '', priority: '' })}
          className="cursor-pointer text-[12.5px] text-muted hover:text-ink"
        >
          Clear filters
        </button>
      )}
    </>
  )

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-[22px] font-[650] md:text-xl">CAPA</h1>
        <Segmented
          value={mode}
          onChange={v => setMode(v as 'list' | 'board')}
          options={[
            { value: 'list', label: <><List size={14} strokeWidth={2} aria-hidden />List</> },
            { value: 'board', label: <><Columns3 size={14} strokeWidth={2} aria-hidden />Board</> },
          ]}
        />
      </div>

      {mode === 'list' ? (
        <TableCard
          columns={columns}
          rows={pageData.items}
          rowKey={r => 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 => (
            <div className="flex items-start gap-3">
              <div className="min-w-0 flex-1 space-y-1">
                <p className="line-clamp-2 text-[13px] font-medium">{r.description}</p>
                <div className="flex items-center gap-2">
                  <StatusTag status={r.status} />
                  <PriorityTag priority={r.priority} />
                </div>
                <p className="text-xs text-faint">
                  {[r.incident_ref, r.owner_name, `Due ${r.due_date}`].filter(Boolean).join(' · ')}
                </p>
              </div>
              <ChevronRight size={16} strokeWidth={2} className="mt-1 text-faint" aria-hidden />
            </div>
          )}
        />
      ) : (
        <div className="space-y-3">
          <div className="flex flex-wrap items-center gap-2">{toolbar}</div>
          <CapaBoardView capas={boardRows} />
        </div>
      )}
    </div>
  )
}
  • Step 5: Rewrite the list page

Read app/(protected)/hse/capa/page.tsx first (the harness requires it), then replace it entirely:

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 (
    <div className="px-4 py-5 md:px-8 md:py-6">
      <CapaWorkspace capas={capas} today={today} />
    </div>
  )
}

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
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
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 <noreply@anthropic.com>"

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:

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(<VerifyForm capaId="c1" />)
    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(<VerifyForm capaId="c1" />)
    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(<VerifyForm capaId="c1" />)
    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(<VerifyForm capaId="c1" />)
    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(<VerifyForm capaId="c1" />)
    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(<VerifyForm capaId="c1" />)
    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:

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(<CapaOwnerNotesForm capaId="c9" initialNotes="Ramp ground back" />)
    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(<CapaOwnerNotesForm capaId="c9" initialNotes={null} />)
    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:

'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 (
    <button
      type="button"
      role="radio"
      aria-checked={selected}
      onClick={onSelect}
      className={cx(
        'cursor-pointer rounded-xl p-3 text-left transition-colors',
        selected ? 'bg-accent-tint shadow-chip-set' : 'bg-surface shadow-chip hover:bg-surface-2',
      )}
    >
      <span className="block text-[13px] font-semibold">{title}</span>
      <span className="mt-0.5 block text-xs text-muted">{hint}</span>
    </button>
  )
}

export function VerifyForm({ capaId }: Props) {
  const router = useRouter()
  const [verdict, setVerdict] = useState<Verdict | null>(null)
  const [reopenReason, setReopenReason] = useState('')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(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 (
    <form onSubmit={handleSubmit} className="space-y-4 rounded-xl bg-surface p-5 shadow-card">
      <div>
        <h3 className="text-sm font-semibold">Verify this action</h3>
        <p className="mt-0.5 text-xs text-muted">Confirm the corrective action fixed the root cause, or send it back.</p>
      </div>

      <div role="radiogroup" aria-label="Verification verdict" className="grid gap-3 sm:grid-cols-2">
        <Choice
          selected={verdict === 'verified'}
          onSelect={() => setVerdict('verified')}
          title="Verified, effective"
          hint="Root cause addressed. The action is marked verified."
        />
        <Choice
          selected={verdict === 'reopened'}
          onSelect={() => setVerdict('reopened')}
          title="Reopen, ineffective"
          hint="Returns to the owner with a required reason."
        />
      </div>

      {verdict === 'reopened' && (
        <Field label="Why is the action ineffective? *" htmlFor="reopen-reason">
          <Textarea
            id="reopen-reason"
            value={reopenReason}
            onChange={e => setReopenReason(e.target.value)}
            rows={2}
            required
            placeholder="Describe why the corrective action did not resolve the root cause…"
          />
        </Field>
      )}

      {error && (
        <p role="alert" className="rounded-md bg-st-red-bg px-3 py-2 text-[13px] text-st-red-fg">
          {error}
        </p>
      )}

      {verdict && (
        <Button type="submit" disabled={saving}>
          {saving ? 'Saving…' : verdict === 'verified' ? 'Confirm verification' : 'Reopen action'}
        </Button>
      )}
    </form>
  )
}
  • Step 4: Rewrite the other three components

components/capa/close-capa-button.tsx (read it first, then replace; behaviour including the confirm dialog is unchanged):

'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'

interface Props {
  capaId: string
}

export function CloseCapaButton({ capaId }: Props) {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleClose() {
    if (!confirm('Close this CAPA? This marks it as fully resolved.')) return
    setLoading(true)
    setError(null)
    const res = await fetch(`/api/capa/${capaId}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ status: 'closed' }),
    })
    if (!res.ok) {
      setError('Failed to close CAPA. Please try again.')
      setLoading(false)
      return
    }
    router.push('/hse/capa')
    router.refresh()
  }

  return (
    <div className="space-y-3 rounded-xl bg-surface p-5 shadow-card">
      <div>
        <h3 className="text-sm font-semibold">Close CAPA</h3>
        <p className="mt-0.5 text-xs text-muted">
          This CAPA has been verified as effective. Close it to mark it fully resolved.
        </p>
      </div>
      {error && (
        <p role="alert" className="rounded-md bg-st-red-bg px-3 py-2 text-[13px] text-st-red-fg">
          {error}
        </p>
      )}
      <Button onClick={handleClose} disabled={loading}>
        {loading ? 'Closing…' : 'Close CAPA'}
      </Button>
    </div>
  )
}

components/capa/capa-owner-actions.tsx (read it first, then replace; the existing six tests keep passing because the button texts and the null renders are unchanged):

'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'

interface Props {
  capaId: string
  currentStatus: string
}

export function CapaOwnerActions({ capaId, currentStatus }: Props) {
  const router = useRouter()
  const [loading, setLoading] = useState(false)

  async function updateStatus(status: string) {
    setLoading(true)
    try {
      const res = await fetch(`/api/capa/${capaId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status }),
      })
      if (!res.ok) {
        alert('Update failed. Please try again.')
        return
      }
      router.refresh()
      setTimeout(() => window.location.reload(), 300)
    } finally {
      setLoading(false)
    }
  }

  if (currentStatus === 'open' || currentStatus === 'reopened' || currentStatus === 'overdue') {
    return (
      <Button variant="secondary" onClick={() => updateStatus('in_progress')} disabled={loading}>
        {loading ? '…' : 'Mark In Progress'}
      </Button>
    )
  }

  if (currentStatus === 'in_progress') {
    return (
      <Button onClick={() => updateStatus('pending_verification')} disabled={loading}>
        {loading ? '…' : 'Submit for Verification'}
      </Button>
    )
  }

  return null
}

components/capa/capa-owner-notes-form.tsx (read it first, then replace):

'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Field, Textarea } from '@/components/ui/field'

interface Props {
  capaId: string
  initialNotes: string | null
}

export function CapaOwnerNotesForm({ capaId, initialNotes }: Props) {
  const [notes, setNotes] = useState(initialNotes ?? '')
  const [saving, setSaving] = useState(false)
  const [saved, setSaved] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleSave() {
    setSaving(true)
    setSaved(false)
    setError(null)
    const res = await fetch(`/api/capa/${capaId}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ owner_notes: notes }),
    })
    setSaving(false)
    if (!res.ok) {
      setError('Failed to save. Please try again.')
      return
    }
    setSaved(true)
    setTimeout(() => setSaved(false), 2000)
  }

  return (
    <div className="mt-3 space-y-2">
      <Field label="Remarks / Notes" htmlFor={`notes-${capaId}`}>
        <Textarea
          id={`notes-${capaId}`}
          value={notes}
          onChange={e => { setNotes(e.target.value); setSaved(false) }}
          rows={2}
          placeholder="Add any notes or updates for this action…"
        />
      </Field>
      {error && <p role="alert" className="text-xs text-danger">{error}</p>}
      <div className="flex items-center gap-2">
        <Button variant="secondary" onClick={handleSave} disabled={saving}>
          {saving ? 'Saving…' : 'Save Notes'}
        </Button>
        {saved && <span className="text-xs text-st-green-fg">Saved</span>}
      </div>
    </div>
  )
}
  • Step 5: Rewrite the detail page

Read app/(protected)/hse/capa/[id]/page.tsx first, then replace it entirely. The query, session check, role gating and action conditions are unchanged; only the markup is new, and the displayed status now shows overdue for open or in-progress actions past their due date, matching the list:

export const dynamic = 'force-dynamic'

import { notFound, redirect } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { capaActions, incidents, users } from '@/lib/db/schema'
import { eq } from 'drizzle-orm'
import { aliasedTable } from 'drizzle-orm'
import { VerifyForm } from '@/components/capa/verify-form'
import { CloseCapaButton } from '@/components/capa/close-capa-button'
import { CapaOwnerActions } from '@/components/capa/capa-owner-actions'
import { Avatar } from '@/components/ui/avatar'
import { PriorityTag, StatusTag } from '@/components/ui/status-tag'
import { daysLate } from '@/lib/capa/list'

interface Props {
  params: Promise<{ id: string }>
}

function Row({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="flex items-center justify-between gap-3 border-b border-rule py-2.5 last:border-0">
      <dt className="text-xs text-muted">{label}</dt>
      <dd className="text-right text-[13px]">{children}</dd>
    </div>
  )
}

export default async function CapaDetailPage({ params }: Props) {
  const { id } = await params
  const session = await getSession()
  if (!session) redirect(`/login?redirect=/hse/capa/${id}`)

  const ownerAlias = aliasedTable(users, 'owner')

  const [capa] = await asAdmin(db =>
    db.select({
      id: capaActions.id,
      incidentId: capaActions.incidentId,
      rootCauseRef: capaActions.rootCauseRef,
      description: capaActions.description,
      department: capaActions.department,
      dueDate: capaActions.dueDate,
      priority: capaActions.priority,
      status: capaActions.status,
      completedAt: capaActions.completedAt,
      ownerNotes: capaActions.ownerNotes,
      ownerUserId: capaActions.ownerUserId,
      incidentRefNo: incidents.referenceNo,
      ownerName: ownerAlias.name,
    })
    .from(capaActions)
    .leftJoin(incidents, eq(capaActions.incidentId, incidents.id))
    .leftJoin(ownerAlias, eq(capaActions.ownerUserId, ownerAlias.id))
    .where(eq(capaActions.id, id))
    .limit(1)
  )

  if (!capa) notFound()

  const isHse = session && ['hse', 'admin'].includes(session.role)
  const status = capa.status
  const today = new Date().toISOString().slice(0, 10)
  const pastDue = (status === 'open' || status === 'in_progress') && Boolean(capa.dueDate) && capa.dueDate < today
  const shownStatus = pastDue ? 'overdue' : status
  const late = shownStatus === 'overdue' ? daysLate(capa.dueDate, today) : 0
  const canAct = ['open', 'in_progress', 'overdue', 'reopened'].includes(status) &&
    (isHse || session?.sub === capa.ownerUserId)

  return (
    <div className="space-y-4 px-4 py-5 md:px-8 md:py-6">
      <Link href="/hse/capa" className="inline-flex items-center gap-1 text-[13px] text-accent hover:underline">
        <ArrowLeft size={14} strokeWidth={2} aria-hidden />
        CAPA
      </Link>

      <div className="space-y-2">
        <h1 className="text-xl font-[650]">{capa.description}</h1>
        <div className="flex flex-wrap items-center gap-2">
          <StatusTag status={shownStatus} />
          <PriorityTag priority={capa.priority} />
          <span className="text-[13px] text-muted">
            From{' '}
            <Link href={`/hse/incidents/${capa.incidentId}`} className="font-mono text-[12.5px] text-accent hover:underline">
              {capa.incidentRefNo ?? '—'}
            </Link>
          </span>
        </div>
        {capa.rootCauseRef && <p className="text-[13px] text-muted">Root cause: {capa.rootCauseRef}</p>}
      </div>

      <div className="grid gap-4 lg:grid-cols-[1fr_320px]">
        <div className="space-y-4">
          {canAct && (
            <div>
              <CapaOwnerActions capaId={id} currentStatus={status} />
            </div>
          )}

          {isHse && status === 'pending_verification' && <VerifyForm capaId={id} />}
          {isHse && status === 'verified' && <CloseCapaButton capaId={id} />}

          {(capa.ownerNotes || capa.completedAt) && (
            <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>
              )}
            </section>
          )}
        </div>

        <aside>
          <section className="rounded-xl bg-surface p-5 shadow-card">
            <h2 className="mb-1 text-sm font-semibold">Details</h2>
            <dl>
              <Row label="Owner">
                {capa.ownerName ? (
                  <span className="inline-flex items-center gap-2">
                    <Avatar name={capa.ownerName} />
                    {capa.ownerName}
                  </span>
                ) : (
                  '—'
                )}
              </Row>
              <Row label="Department">{capa.department}</Row>
              <Row label="Priority"><PriorityTag priority={capa.priority} /></Row>
              <Row label="Due">
                {capa.dueDate}
                {late > 0 && <span className="ml-1.5 text-xs text-danger">{`${late} day${late === 1 ? '' : 's'} late`}</span>}
              </Row>
              {capa.completedAt && (
                <Row label="Completed">
                  {new Date(capa.completedAt).toLocaleDateString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })}
                </Row>
              )}
            </dl>
          </section>
        </aside>
      </div>
    </div>
  )
}
  • Step 6: Run the tests, the gate, tsc and the full suite
npx vitest run tests/components/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: all CAPA tests pass (the 6 existing owner-action tests unchanged, plus 6 verify-form and 2 notes-form tests), design gates: clean, tsc prints nothing, and the full suite shows exactly the 7 baseline failures. If tsc rejects capa.dueDate < today because dueDate is nullable, keep the explicit Boolean(capa.dueDate) guard as written and add capa.dueDate! only on the comparison.

  • Step 7: Commit
git add "app/(protected)/hse/capa/[id]/page.tsx" components/capa tests/components/capa
git commit -m "feat(capa): restyle the CAPA detail page, verification form, close card, owner actions and notes

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"

Task 4: Create CAPA form and page

Files:

  • Modify: components/capa/capa-form.tsx (full rewrite), app/(protected)/hse/incidents/[id]/capa/new/page.tsx (full rewrite)
  • Test: tests/components/capa/capa-form.test.tsx

Interfaces:

  • Consumes: Button, Field, Input, Select, Textarea (slice 1).

  • Produces: CapaForm({ incidentId }) with the same API. Same requests as today: GET /api/users, then POST /api/capa with { incident_id, description, owner_user_id, department, due_date, priority, root_cause_ref }, then router.push('/hse/incidents/<id>').

  • Step 1: Write the failing test

Create tests/components/capa/capa-form.test.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 { CapaForm } from '@/components/capa/capa-form'

const users = [{ id: 'u1', name: 'Tan Mei Ling', department: 'Facilities' }]

function stubFetch(postResponse: { ok: boolean; body?: unknown } = { ok: true }) {
  const fn = vi.fn(async (url: string, init?: RequestInit) => {
    void init
    if (url === '/api/users') return { ok: true, json: async () => users }
    return { ok: postResponse.ok, json: async () => postResponse.body ?? {} }
  })
  vi.stubGlobal('fetch', fn)
  return fn
}

const postCall = (fn: ReturnType<typeof stubFetch>) => fn.mock.calls.find(c => c[0] === '/api/capa')

beforeEach(() => {
  push.mockClear()
  refresh.mockClear()
})

describe('CapaForm', () => {
  it('uses the shared labelled fields', async () => {
    stubFetch()
    render(<CapaForm incidentId="inc1" />)
    expect(screen.getByLabelText('Action Description *').className).toContain('rounded-md')
    expect(screen.getByLabelText('Due Date *').className).toContain('shadow-input')
    expect(await screen.findByRole('option', { name: /Tan Mei Ling/ })).toBeTruthy()
  })

  it('rejects an empty submission without calling the API', async () => {
    const fn = stubFetch()
    const { container } = render(<CapaForm incidentId="inc1" />)
    await screen.findByRole('option', { name: /Tan Mei Ling/ })
    fireEvent.submit(container.querySelector('form')!)
    expect((await screen.findByRole('alert')).textContent).toBe('Description, owner, and due date are required')
    expect(postCall(fn)).toBeUndefined()
  })

  it('creates the action with the owner department and returns to the incident', async () => {
    const fn = stubFetch()
    const { container } = render(<CapaForm incidentId="inc1" />)
    await screen.findByRole('option', { name: /Tan Mei Ling/ })
    fireEvent.change(screen.getByLabelText('Action Description *'), { target: { value: 'Re-coat the ramp' } })
    fireEvent.change(screen.getByLabelText('Root Cause Reference'), { target: { value: 'Why #2' } })
    fireEvent.change(screen.getByLabelText('Assigned To *'), { target: { value: 'u1' } })
    fireEvent.change(screen.getByLabelText('Due Date *'), { target: { value: '2026-11-01' } })
    fireEvent.change(screen.getByLabelText('Priority'), { target: { value: 'high' } })
    fireEvent.submit(container.querySelector('form')!)
    await waitFor(() => expect(push).toHaveBeenCalledWith('/hse/incidents/inc1'))
    expect(JSON.parse(postCall(fn)![1]!.body as string)).toEqual({
      incident_id: 'inc1',
      description: 'Re-coat the ramp',
      owner_user_id: 'u1',
      department: 'Facilities',
      due_date: '2026-11-01',
      priority: 'high',
      root_cause_ref: 'Why #2',
    })
  })

  it('shows the API error in a red banner and stays on the page', async () => {
    stubFetch({ ok: false, body: { error: 'Owner inactive' } })
    const { container } = render(<CapaForm incidentId="inc1" />)
    await screen.findByRole('option', { name: /Tan Mei Ling/ })
    fireEvent.change(screen.getByLabelText('Action Description *'), { target: { value: 'x' } })
    fireEvent.change(screen.getByLabelText('Assigned To *'), { target: { value: 'u1' } })
    fireEvent.change(screen.getByLabelText('Due Date *'), { target: { value: '2026-11-01' } })
    fireEvent.submit(container.querySelector('form')!)
    const alert = await screen.findByRole('alert')
    expect(alert.textContent).toBe('Owner inactive')
    expect(alert.className).toContain('bg-st-red-bg')
    expect(push).not.toHaveBeenCalled()
  })
})
  • Step 2: Run it to verify it fails

Run: npx vitest run tests/components/capa/capa-form.test.tsx 2>&1 | grep -E "Test Files|Tests |×" | head -6 Expected: FAIL (the labels are not associated with their controls and there is no role="alert").

  • Step 3: Rewrite components/capa/capa-form.tsx

Read it first (the harness requires it), then replace it entirely. State, effects and requests are unchanged:

'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Field, Input, Select, Textarea } from '@/components/ui/field'

interface User {
  id: string
  name: string
  department: string
}

interface Props {
  incidentId: string
}

export function CapaForm({ incidentId }: Props) {
  const router = useRouter()
  const [users, setUsers] = useState<User[]>([])
  const [description, setDescription] = useState('')
  const [ownerId, setOwnerId] = useState('')
  const [department, setDepartment] = useState('')
  const [dueDate, setDueDate] = useState('')
  const [priority, setPriority] = useState<'low' | 'med' | 'high'>('med')
  const [rootCauseRef, setRootCauseRef] = useState('')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    fetch('/api/users')
      .then(r => r.json())
      .then(data => { if (Array.isArray(data)) setUsers(data) })
      .catch(() => {})
  }, [])

  function handleOwnerChange(id: string) {
    setOwnerId(id)
    const u = users.find(u => u.id === id)
    if (u) setDepartment(u.department)
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!ownerId || !description || !dueDate) {
      setError('Description, owner, and due date are required')
      return
    }
    setSaving(true)
    setError(null)
    const res = await fetch('/api/capa', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        incident_id: incidentId,
        description,
        owner_user_id: ownerId,
        department,
        due_date: dueDate,
        priority,
        root_cause_ref: rootCauseRef || null,
      }),
    })
    if (!res.ok) {
      const data = await res.json()
      setError(data.error ?? 'Create failed')
      setSaving(false)
      return
    }
    router.push(`/hse/incidents/${incidentId}`)
    router.refresh()
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <Field label="Action Description *" htmlFor="capa-description">
        <Textarea
          id="capa-description"
          value={description}
          onChange={e => setDescription(e.target.value)}
          rows={3}
          required
          placeholder="What corrective action will be taken?"
        />
      </Field>

      <Field label="Root Cause Reference" htmlFor="capa-root-cause">
        <Input
          id="capa-root-cause"
          type="text"
          value={rootCauseRef}
          onChange={e => setRootCauseRef(e.target.value)}
          placeholder="e.g. Why #3 — inadequate training"
        />
      </Field>

      <Field label="Assigned To *" htmlFor="capa-owner">
        <Select id="capa-owner" value={ownerId} onChange={e => handleOwnerChange(e.target.value)} required>
          <option value="">Select owner…</option>
          {users.map(u => (
            <option key={u.id} value={u.id}>{u.name} ({u.department})</option>
          ))}
        </Select>
      </Field>

      <div className="grid grid-cols-2 gap-3">
        <Field label="Due Date *" htmlFor="capa-due">
          <Input id="capa-due" type="date" value={dueDate} onChange={e => setDueDate(e.target.value)} required />
        </Field>
        <Field label="Priority" htmlFor="capa-priority">
          <Select
            id="capa-priority"
            value={priority}
            onChange={e => setPriority(e.target.value as 'low' | 'med' | 'high')}
          >
            <option value="low">Low</option>
            <option value="med">Medium</option>
            <option value="high">High</option>
          </Select>
        </Field>
      </div>

      {error && (
        <p role="alert" className="rounded-md bg-st-red-bg px-3 py-2 text-[13px] text-st-red-fg">
          {error}
        </p>
      )}

      <Button type="submit" block disabled={saving}>
        {saving ? 'Creating…' : 'Create CAPA Action'}
      </Button>
    </form>
  )
}
  • Step 4: Rewrite the new-CAPA page

Read app/(protected)/hse/incidents/[id]/capa/new/page.tsx first, then replace it entirely. The guards and the incident query are unchanged:

import { notFound, redirect } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { incidents } from '@/lib/db/schema'
import { eq } from 'drizzle-orm'
import { CapaForm } from '@/components/capa/capa-form'

interface Props {
  params: Promise<{ id: string }>
}

export default async function NewCapaPage({ params }: Props) {
  const { id } = await params
  const session = await getSession()
  if (!session) redirect(`/login?redirect=/hse/incidents/${id}/capa/new`)
  if (!['hse', 'admin'].includes(session.role)) redirect('/hse/incidents')

  const [incident] = await asAdmin(db =>
    db.select({
      id: incidents.id,
      referenceNo: incidents.referenceNo,
      status: incidents.status,
    })
    .from(incidents)
    .where(eq(incidents.id, id))
    .limit(1)
  )

  if (!incident) notFound()

  return (
    <div className="max-w-xl space-y-4 px-4 py-5 md:px-8 md:py-6">
      <Link href={`/hse/incidents/${id}`} className="inline-flex items-center gap-1 text-[13px] text-accent hover:underline">
        <ArrowLeft size={14} strokeWidth={2} aria-hidden />
        Back to incident
      </Link>
      <div>
        <h1 className="text-xl font-[650]">Add CAPA action</h1>
        <p className="mt-0.5 font-mono text-[12.5px] text-muted">{incident.referenceNo ?? id}</p>
      </div>
      <div className="rounded-xl bg-surface p-5 shadow-card">
        <CapaForm incidentId={id} />
      </div>
    </div>
  )
}
  • Step 5: Run the tests, the gate, tsc and the full suite
npx vitest run tests/components/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: all CAPA tests pass, design gates: clean, tsc prints nothing, and the full suite shows exactly the 7 baseline failures.

  • Step 6: Commit
git add components/capa/capa-form.tsx "app/(protected)/hse/incidents/[id]/capa/new/page.tsx" tests/components/capa/capa-form.test.tsx
git commit -m "feat(capa): restyle the create CAPA form and page with the shared field primitives

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"

Task 5: Docs, memory and verification

Files:

  • Modify: design-system/design.md, memory /Users/yapweeihan/.claude/projects/-Users-yapweeihan-Projects-Setia/memory/ims-design-system.md

Interfaces:

  • Consumes: everything above.

  • Produces: a verified branch, ready for the owner's go-ahead to deploy.

  • Step 1: Update design-system/design.md

Read it first. In section 8 replace the sentence "Slice 1 (gate, tokens, primitives, TableCard, shells, Incidents list) is implemented; the remaining screens follow in later plans." with: "Slice 1 (gate, tokens, primitives, TableCard, shells, Incidents list) and slice 2 (CAPA list, board, detail, verification, create form) are implemented; the remaining screens follow in later plans." Add a final subsection to section 5, directly under the screen table:

Mockup features with no backend yet (do not fake them in the UI): CAPA export, bulk actions on a selection (send reminder, reassign, escalate), group-by, department and due-date range filters, the activity and comments feed, cost, evidence files on a CAPA, the verification note, "ask owner a question", and edit. Add them in a slice that also adds the backend.
  • Step 2: Update the memory file

In /Users/yapweeihan/.claude/projects/-Users-yapweeihan-Projects-Setia/memory/ims-design-system.md replace the line starting - Slice 1 done with:

- Slice 1 done (gate, tokens, primitives, TableCard, shells, Incidents list) and slice 2 done on branch `feat/admin-refresh-slice-2-capa` (CAPA workspace with list and board, detail, verification, create form). Remaining slices, in order: incident detail and forms, admin and settings, dashboard, reporter and mobile. Mockup features without a backend (CAPA export, bulk actions, comments, cost, evidence on a CAPA) are deliberately not built.
  • Step 3: Full verification
npm run check:design 2>&1 | tail -2
npx tsc --noEmit 2>&1 | head -5; echo "tsc done"
npx vitest run 2>&1 | grep -E "Test Files|Tests "
rm -rf .next && npm run build > /tmp/ims-build.log 2>&1; echo "build exit=$?"
grep -E "hse/capa" /tmp/ims-build.log | head -4
grep -rn "capa-board'" app components tests | head -2; echo "(nothing above = old board fully removed)"

Expected: gate clean, tsc clean, the full suite shows exactly the 7 baseline failures, build exit 0, the build log lists /hse/capa and /hse/capa/[id], and no dangling capa-board import.

  • Step 4: Browser check of the pages that need no data

The local database is empty, so authenticated CAPA pages cannot be rendered here; they are verified on production after a deploy (Step 6). Confirm only that the build served by npm run dev still renders the login page, then stop the server and undo the file next dev rewrites:

(npm run dev > /tmp/ims-dev.log 2>&1 &); sleep 9; curl -s -o /dev/null -w "login http %{http_code}\n" http://localhost:3000/login
kill $(lsof -ti :3000 -sTCP:LISTEN) 2>/dev/null; git checkout -- AGENTS.md 2>/dev/null; git status --short | grep -v '^??'

Expected: login http 200, and the working tree shows only this task's changes plus the pre-existing D design-system/ims-admin/MASTER.md.

  • Step 5: Commit
git add design-system/design.md
git commit -m "docs(design): record slice 2 (CAPA) and the mockup features that need a backend

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
  • Step 6: Report, do not deploy

Report to the owner: what shipped, the test and gate results, that the CAPA pages are unverified against real data until deployed, and ask for the go-ahead to push the branch, deploy per CLAUDE.md and run the post-deploy checks below. Do not deploy and do not push without it.

Post-deploy checks (curl with a logged-in session, then delete the cookie jar): /hse/capa returns 200 and contains the "CAPA" heading; the page lists the real actions (their count matches the number of rows in capa_actions); an existing /hse/capa/<id> returns 200 with the Details card; /hse/incidents/<id>/capa/new returns 200 with the form; the server log shows 0 errors since the restart.


Self-Review Notes

Spec coverage (design.md §5, screens 04, 04b, 04c): list as TableCard with saved views, search, owner, department and priority chips, sortable priority, due and status columns, pager and a mobile list (Task 2); board with status columns, counts and cards, including a Reopened column the old board lacked (Task 2); segmented List and Board switch (Task 2); detail with header tags, "From" incident link, completion report, Details card and the two-card verification form (Task 3); create form and page (Task 4).

Deliberate gaps (mockup features without a backend, listed under "Out of scope"): export, bulk actions, group-by, date-range filter, activity feed, cost, evidence on a CAPA, verification note, ask-owner, edit, recheck sentence.

Type consistency: CapaRow, CapaFilters, CapaSort, CapaSortKey, CapaViewKey, VIEWS, STATUS_ORDER, EMPTY_FILTERS, PAGE_SIZE, filterCapas, viewCounts, sortCapas, nextSort, paginate, distinct, daysLate are defined in Task 1 and used with the same names and shapes in Tasks 2 and 3; the page maps database rows to CapaRow field by field (incident_ref, owner_name, due_date).

Risks to watch during execution: the status tag for an open or in-progress action past its due date now reads Overdue on the detail page (computed the same way the list page already did); the old board hid reopened actions, so the board may show actions that were previously invisible; Columns3 must exist in the installed lucide-react (if tsc reports it missing, use Kanban or LayoutGrid).