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>
This commit is contained in:
2026-10-01 10:47:04 +08:00
co-authored by Claude Haiku 4.5
parent 9dca2a51d2
commit 04437926c2
6 changed files with 333 additions and 150 deletions
+10 -16
View File
@@ -1,13 +1,13 @@
export const dynamic = 'force-dynamic'
import { redirect } from 'next/navigation'
import Link from 'next/link'
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 { CapaBoard } from '@/components/capa/capa-board'
import { CapaWorkspace } from '@/components/capa/capa-workspace'
import type { CapaRow, CapaStatus } from '@/lib/capa/list'
export default async function CapaListPage() {
const session = await getSession()
@@ -34,29 +34,23 @@ export default async function CapaListPage() {
)
const today = new Date().toISOString().slice(0, 10)
const capas = rows.map(r => ({
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' as const
: r.status,
incidents: { reference_no: r.incidentRefNo ?? null },
owner: r.ownerName ? { name: r.ownerName } : null,
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 (
<main className="max-w-6xl mx-auto px-4 py-6">
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-bold text-gray-900">CAPA Board</h1>
<Link href="/hse/incidents" className="text-sm text-accent-700 hover:underline">
← Incidents
</Link>
<div className="px-4 py-5 md:px-8 md:py-6">
<CapaWorkspace capas={capas} today={today} />
</div>
<CapaBoard capas={capas} />
</main>
)
}
+47
View File
@@ -0,0 +1,47 @@
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>
)
}
-129
View File
@@ -1,129 +0,0 @@
'use client'
import { useState } from 'react'
import Link from 'next/link'
import { PriorityTag } from '@/components/ui/status-tag'
type CapaStatus = 'open' | 'in_progress' | 'overdue' | 'pending_verification' | 'verified' | 'reopened' | 'closed'
type CapaAction = {
id: string
incident_id: string
description: string
department: string
due_date: string
priority: 'low' | 'med' | 'high'
status: CapaStatus
incidents: { reference_no: string | null } | null
owner: { name: string } | null
}
const STATUS_ORDER: CapaStatus[] = ['open', 'in_progress', 'overdue', 'pending_verification', 'verified', 'closed']
const STATUS_LABELS: Record<CapaStatus, string> = {
open: 'Open',
in_progress: 'In Progress',
overdue: 'Overdue',
pending_verification: 'Pending Verification',
verified: 'Verified',
reopened: 'Reopened',
closed: 'Closed',
}
const COLUMN_BORDER: Record<CapaStatus, string> = {
open: 'border-divider',
in_progress: 'border-divider',
overdue: 'border-accent',
pending_verification: 'border-divider',
verified: 'border-divider',
reopened: 'border-accent',
closed: 'border-divider',
}
interface Props {
capas: CapaAction[]
}
export function CapaBoard({ capas }: Props) {
const [view, setView] = useState<'board' | 'table'>('board')
const byStatus = STATUS_ORDER.reduce<Record<CapaStatus, CapaAction[]>>((acc, s) => {
acc[s] = capas.filter(c => c.status === s)
return acc
}, {} as Record<CapaStatus, CapaAction[]>)
if (view === 'table') {
return (
<div>
<div className="flex justify-end mb-3">
<button onClick={() => setView('board')} className="text-sm text-accent-700 hover:underline">Board view</button>
</div>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-left text-xs text-gray-500 uppercase border-b">
<th className="pb-2 pr-4">Ref</th>
<th className="pb-2 pr-4">Action</th>
<th className="pb-2 pr-4">Owner</th>
<th className="pb-2 pr-4">Due</th>
<th className="pb-2 pr-4">Priority</th>
<th className="pb-2">Status</th>
</tr>
</thead>
<tbody className="divide-y divide-divider">
{capas.map(c => (
<tr key={c.id}>
<td className="py-2 pr-4 text-gray-500 text-xs">
{(c.incidents as { reference_no: string | null } | null)?.reference_no ?? '—'}
</td>
<td className="py-2 pr-4">
<Link href={`/hse/capa/${c.id}`} className="text-accent-700 hover:underline line-clamp-2">
{c.description}
</Link>
</td>
<td className="py-2 pr-4 text-gray-600">{(c.owner as { name: string } | null)?.name ?? '—'}</td>
<td className="py-2 pr-4 text-gray-600">{c.due_date}</td>
<td className="py-2 pr-4">
<PriorityTag priority={c.priority} />
</td>
<td className="py-2 text-gray-600 text-xs">{STATUS_LABELS[c.status]}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)
}
return (
<div>
<div className="flex justify-end mb-3">
<button onClick={() => setView('table')} className="text-sm text-accent-700 hover:underline">Table view</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{STATUS_ORDER.filter(s => s !== 'reopened').map(status => (
<div key={status} className={`border p-4 bg-ground ${COLUMN_BORDER[status]}`}>
<h3 className="text-xs font-extrabold uppercase tracking-wide text-ink/70 mb-3 pb-2 border-b border-divider">
{STATUS_LABELS[status]} ({byStatus[status].length})
</h3>
<div className="space-y-2 max-h-96 overflow-y-auto pr-2">
{byStatus[status].map(c => (
<Link key={c.id} href={`/hse/capa/${c.id}`}
className="block bg-surface p-3 shadow-sm hover:shadow-md transition-shadow border border-divider">
<p className="text-sm text-gray-800 line-clamp-2 mb-1">{c.description}</p>
<div className="flex items-center justify-between text-xs text-gray-500">
<span>{(c.owner as { name: string } | null)?.name ?? '—'}</span>
<PriorityTag priority={c.priority} />
</div>
<p className="text-xs text-gray-400 mt-1">Due {c.due_date}</p>
</Link>
))}
{byStatus[status].length === 0 && (
<p className="text-xs text-gray-400 text-center py-3">Empty</p>
)}
</div>
</div>
))}
</div>
</div>
)
}
+167
View File
@@ -0,0 +1,167 @@
'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>
)
}
@@ -356,7 +356,7 @@ Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
**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 })`.
- Produces: `CapaWorkspace({ capas: CapaRow[]; today: string })` and `CapaBoardView({ capas: CapaRow[] })`.
- [ ] **Step 1: Write the failing test**
@@ -482,7 +482,7 @@ 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 }) {
export function CapaBoardView({ capas }: { capas: CapaRow[] }) {
return (
<div className="flex gap-3 overflow-x-auto pb-2">
{STATUS_ORDER.map(status => {
@@ -526,7 +526,7 @@ export function CapaBoardView({ capas }: { capas: CapaRow[]; today: string }) {
}
```
(`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.)
(The board takes only `capas`; it does not need `today`.)
- [ ] **Step 4: Write `components/capa/capa-workspace.tsx`**
@@ -692,7 +692,7 @@ export function CapaWorkspace({ capas, today }: { capas: CapaRow[]; today: strin
) : (
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-2">{toolbar}</div>
<CapaBoardView capas={boardRows} today={today} />
<CapaBoardView capas={boardRows} />
</div>
)}
</div>
@@ -0,0 +1,104 @@
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()
})
})