From 04437926c20adcb0bec4b2c7f3746fece74fa304 Mon Sep 17 00:00:00 2001 From: weeihan Date: Thu, 1 Oct 2026 10:47:04 +0800 Subject: [PATCH] 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 --- app/(protected)/hse/capa/page.tsx | 28 ++- components/capa/capa-board-view.tsx | 47 +++++ components/capa/capa-board.tsx | 129 -------------- components/capa/capa-workspace.tsx | 167 ++++++++++++++++++ ...26-10-01-ims-admin-refresh-slice-2-capa.md | 8 +- tests/components/capa/capa-workspace.test.tsx | 104 +++++++++++ 6 files changed, 333 insertions(+), 150 deletions(-) create mode 100644 components/capa/capa-board-view.tsx delete mode 100644 components/capa/capa-board.tsx create mode 100644 components/capa/capa-workspace.tsx create mode 100644 tests/components/capa/capa-workspace.test.tsx diff --git a/app/(protected)/hse/capa/page.tsx b/app/(protected)/hse/capa/page.tsx index 333dd20..5ac1a98 100644 --- a/app/(protected)/hse/capa/page.tsx +++ b/app/(protected)/hse/capa/page.tsx @@ -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 ( -
-
-

CAPA Board

- - ← Incidents - -
- -
+
+ +
) } diff --git a/components/capa/capa-board-view.tsx b/components/capa/capa-board-view.tsx new file mode 100644 index 0000000..d9dc712 --- /dev/null +++ b/components/capa/capa-board-view.tsx @@ -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 ( +
+ {STATUS_ORDER.map(status => { + const items = capas.filter(c => c.status === status) + return ( +
+
+ + {items.length} +
+
+ {items.map(c => ( + +

{c.description}

+

{c.incident_ref ?? '—'}

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

Due {c.due_date}

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

Empty

} +
+
+ ) + })} +
+ ) +} diff --git a/components/capa/capa-board.tsx b/components/capa/capa-board.tsx deleted file mode 100644 index 6c93347..0000000 --- a/components/capa/capa-board.tsx +++ /dev/null @@ -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 = { - open: 'Open', - in_progress: 'In Progress', - overdue: 'Overdue', - pending_verification: 'Pending Verification', - verified: 'Verified', - reopened: 'Reopened', - closed: 'Closed', -} -const COLUMN_BORDER: Record = { - 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>((acc, s) => { - acc[s] = capas.filter(c => c.status === s) - return acc - }, {} as Record) - - if (view === 'table') { - return ( -
-
- -
-
- - - - - - - - - - - - - {capas.map(c => ( - - - - - - - - - ))} - -
RefActionOwnerDuePriorityStatus
- {(c.incidents as { reference_no: string | null } | null)?.reference_no ?? '—'} - - - {c.description} - - {(c.owner as { name: string } | null)?.name ?? '—'}{c.due_date} - - {STATUS_LABELS[c.status]}
-
-
- ) - } - - return ( -
-
- -
-
- {STATUS_ORDER.filter(s => s !== 'reopened').map(status => ( -
-

- {STATUS_LABELS[status]} ({byStatus[status].length}) -

-
- {byStatus[status].map(c => ( - -

{c.description}

-
- {(c.owner as { name: string } | null)?.name ?? '—'} - -
-

Due {c.due_date}

- - ))} - {byStatus[status].length === 0 && ( -

Empty

- )} -
-
- ))} -
-
- ) -} diff --git a/components/capa/capa-workspace.tsx b/components/capa/capa-workspace.tsx new file mode 100644 index 0000000..c676293 --- /dev/null +++ b/components/capa/capa-workspace.tsx @@ -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 — + return ( + + + {name} + + ) +} + +function Due({ row, today }: { row: CapaRow; today: string }) { + const late = row.status === 'overdue' ? daysLate(row.due_date, today) : 0 + return ( + + {row.due_date} + {late > 0 && {`${late} day${late === 1 ? '' : 's'} late`}} + + ) +} + +export function CapaWorkspace({ capas, today }: { capas: CapaRow[]; today: string }) { + const router = useRouter() + const [mode, setMode] = useState<'list' | 'board'>('list') + const [filters, setFilters] = useState(EMPTY_FILTERS) + const [sort, setSort] = useState({ key: 'due_date', dir: 'asc' }) + const [page, setPage] = useState(1) + + const patch = (next: Partial) => { + setFilters(f => ({ ...f, ...next })) + setPage(1) + } + + const owners = useMemo(() => distinct(capas.map(c => c.owner_name)), [capas]) + const departments = useMemo(() => distinct(capas.map(c => c.department)), [capas]) + const counts = useMemo(() => viewCounts(capas, filters), [capas, filters]) + const sorted = useMemo(() => sortCapas(filterCapas(capas, filters), sort), [capas, filters, sort]) + const boardRows = useMemo( + () => sortCapas(filterCapas(capas, { ...filters, view: 'all' }), { key: 'due_date', dir: 'asc' }), + [capas, filters], + ) + const pageData = paginate(sorted, page, PAGE_SIZE) + const clearable = Boolean(filters.q || filters.owner || filters.department || filters.priority) + + const columns: Column[] = [ + { key: 'action', header: 'Action', cell: r => {r.description} }, + { key: 'incident', header: 'Incident', cell: r => {r.incident_ref ?? '—'} }, + { key: 'owner', header: 'Owner', cell: r => }, + { key: 'department', header: 'Department', cell: r => r.department }, + { key: 'priority', header: 'Priority', sortKey: 'priority', cell: r => }, + { key: 'due', header: 'Due', sortKey: 'due_date', cell: r => }, + { key: 'status', header: 'Status', sortKey: 'status', cell: r => }, + ] + + const toolbar = ( + <> + + patch({ owner: v })} /> + patch({ department: v })} /> + patch({ priority: v })} /> + {clearable && ( + + )} + + ) + + return ( +
+
+

CAPA

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

{r.description}

+
+ + +
+

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

+
+ +
+ )} + /> + ) : ( +
+
{toolbar}
+ +
+ )} +
+ ) +} diff --git a/docs/superpowers/plans/2026-10-01-ims-admin-refresh-slice-2-capa.md b/docs/superpowers/plans/2026-10-01-ims-admin-refresh-slice-2-capa.md index 4306531..7bb3f18 100644 --- a/docs/superpowers/plans/2026-10-01-ims-admin-refresh-slice-2-capa.md +++ b/docs/superpowers/plans/2026-10-01-ims-admin-refresh-slice-2-capa.md @@ -356,7 +356,7 @@ Co-Authored-By: Claude Haiku 4.5 " **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 (
{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 ) : (
{toolbar}
- +
)}
diff --git a/tests/components/capa/capa-workspace.test.tsx b/tests/components/capa/capa-workspace.test.tsx new file mode 100644 index 0000000..43f0e16 --- /dev/null +++ b/tests/components/capa/capa-workspace.test.tsx @@ -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 => ({ + id: 'x', incident_id: 'i', description: 'Fit guard rail', department: 'Facilities', due_date: '2026-10-10', + priority: 'med', status: 'open', incident_ref: 'SC1-202607-0001', owner_name: 'Tan Mei Ling', ...over, +}) + +const capas: CapaRow[] = [ + row({ id: '1', description: 'Anti-slip coating', due_date: '2026-09-12', priority: 'high', status: 'overdue', owner_name: 'Tan Mei Ling', department: 'Facilities' }), + row({ id: '2', description: 'Forklift refresher', due_date: '2026-10-20', priority: 'low', status: 'in_progress', owner_name: 'Ravi Kumar', department: 'Operations', incident_ref: 'SC3-202607-0002' }), + row({ id: '3', description: 'Guard rail repair', due_date: '2026-10-01', priority: 'med', status: 'pending_verification', owner_name: 'Tan Mei Ling', department: 'Facilities' }), + row({ id: '4', description: 'Signage', due_date: '2026-08-30', priority: 'low', status: 'closed', owner_name: null, department: 'Operations' }), +] +const today = '2026-09-27' + +const desktopRows = () => screen.getAllByRole('row').slice(1) + +beforeEach(() => push.mockClear()) + +describe('CapaWorkspace list', () => { + it('renders a TableCard with the action, incident, owner, tags and a late indicator', () => { + render() + expect(screen.getAllByText('Anti-slip coating').length).toBeGreaterThan(0) + expect(screen.getAllByText('SC1-202607-0001').length).toBeGreaterThan(0) + expect(screen.getAllByText('Ravi Kumar').length).toBeGreaterThan(0) + expect(screen.getAllByText('Overdue').some(el => el.className.includes('bg-st-red-bg'))).toBe(true) + expect(screen.getAllByText('High').some(el => el.className.includes('bg-st-orange-bg'))).toBe(true) + expect(screen.getByText('15 days late')).toBeTruthy() + expect(screen.getByText('Showing 1–4 of 4')).toBeTruthy() + }) + + it('shows saved views with counts and filters by view', () => { + render() + expect(screen.getByRole('button', { name: /All/ }).className).toContain('bg-rule-2') + fireEvent.click(screen.getByRole('button', { name: /Overdue/ })) + expect(screen.queryAllByText('Forklift refresher')).toHaveLength(0) + expect(screen.getAllByText('Anti-slip coating').length).toBeGreaterThan(0) + expect(screen.getByText('Showing 1–1 of 1')).toBeTruthy() + }) + + it('searches across action, incident and owner', () => { + render() + fireEvent.change(screen.getByRole('searchbox', { name: 'Search actions' }), { target: { value: 'guard' } }) + expect(screen.getAllByText('Guard rail repair').length).toBeGreaterThan(0) + expect(screen.queryAllByText('Signage')).toHaveLength(0) + }) + + it('filters by owner chip and clears the filters', () => { + render() + fireEvent.change(screen.getByLabelText('Owner'), { target: { value: 'Ravi Kumar' } }) + expect(screen.queryAllByText('Anti-slip coating')).toHaveLength(0) + expect(screen.getAllByText('Forklift refresher').length).toBeGreaterThan(0) + fireEvent.click(screen.getByRole('button', { name: 'Clear filters' })) + expect(screen.getAllByText('Anti-slip coating').length).toBeGreaterThan(0) + }) + + it('sorts by due date ascending by default and flips on the header', () => { + render() + expect(desktopRows()[0].textContent).toContain('Signage') + fireEvent.click(screen.getByRole('button', { name: /Due/ })) + expect(desktopRows()[0].textContent).toContain('Forklift refresher') + }) + + it('opens a CAPA from its row', () => { + render() + fireEvent.click(desktopRows().find(r => r.textContent?.includes('Anti-slip coating'))!) + expect(push).toHaveBeenCalledWith('/hse/capa/1') + }) + + it('shows an empty state when nothing matches', () => { + render() + fireEvent.change(screen.getByRole('searchbox', { name: 'Search actions' }), { target: { value: 'zzzz' } }) + expect(screen.getByText('No CAPA actions match')).toBeTruthy() + expect(screen.queryByText(/Showing/)).toBeNull() + }) +}) + +describe('CapaWorkspace board', () => { + it('switches to a board of status columns with counts and card links', () => { + render() + fireEvent.click(screen.getByRole('button', { name: 'Board' })) + expect(screen.queryByRole('table')).toBeNull() + const col = screen.getByRole('region', { name: 'in progress column' }) + expect(within(col).getByText('1')).toBeTruthy() + expect(within(col).getByRole('link', { name: /Forklift refresher/ }).getAttribute('href')).toBe('/hse/capa/2') + expect(screen.getByRole('region', { name: 'reopened column' })).toBeTruthy() + expect(within(screen.getByRole('region', { name: 'reopened column' })).getByText('Empty')).toBeTruthy() + }) + + it('keeps the search and chip filters on the board', () => { + render() + fireEvent.click(screen.getByRole('button', { name: 'Board' })) + fireEvent.change(screen.getByLabelText('Owner'), { target: { value: 'Ravi Kumar' } }) + expect(screen.queryByRole('link', { name: /Anti-slip coating/ })).toBeNull() + expect(screen.getByRole('link', { name: /Forklift refresher/ })).toBeTruthy() + }) +})