Author SHA1 Message Date
adminandClaude Haiku 4.5 4f9ca6e37f docs(design): record slice 2 (CAPA) and the mockup features that need a backend
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 11:37:41 +08:00
adminandClaude Haiku 4.5 48b77458dd test(capa): fix the fetch mock typing in the create form test
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 11:37:11 +08:00
adminandClaude Haiku 4.5 7e129b2781 feat(capa): restyle the create CAPA form and page with the shared field primitives
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 11:35:46 +08:00
adminandClaude Haiku 4.5 4f75dd5887 feat(ai): switch from DeepSeek to local Ollama (qwen3:14b)
- Point AI client to localhost:11434/v1 (Ollama)
- Remove DeepSeek API key dependency
- Update model name to qwen3:14b across all routes
- Update test mocks to use createLocalLLMClient
- Removes need for DEEPSEEK_API_KEY setting

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 11:34:05 +08:00
adminandClaude Haiku 4.5 69e510af74 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>
2026-10-01 11:20:57 +08:00
adminandClaude Haiku 4.5 04437926c2 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>
2026-10-01 10:47:04 +08:00
adminandClaude Haiku 4.5 9dca2a51d2 feat(capa): add pure list helpers for filtering, saved views, sorting and paging
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 10:26:34 +08:00
adminandClaude Haiku 4.5 9f0331d190 docs: add IMS Admin refresh slice 2 (CAPA) implementation plan
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 10:20:01 +08:00
27 changed files with 2812 additions and 366 deletions
+86 -59
View File
@@ -2,6 +2,7 @@ export const dynamic = 'force-dynamic'
import { notFound, redirect } from 'next/navigation' import { notFound, redirect } from 'next/navigation'
import Link from 'next/link' import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'
import { asAdmin } from '@/lib/db/with-user' import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session' import { getSession } from '@/lib/auth/get-session'
import { capaActions, incidents, users } from '@/lib/db/schema' import { capaActions, incidents, users } from '@/lib/db/schema'
@@ -10,12 +11,23 @@ import { aliasedTable } from 'drizzle-orm'
import { VerifyForm } from '@/components/capa/verify-form' import { VerifyForm } from '@/components/capa/verify-form'
import { CloseCapaButton } from '@/components/capa/close-capa-button' import { CloseCapaButton } from '@/components/capa/close-capa-button'
import { CapaOwnerActions } from '@/components/capa/capa-owner-actions' import { CapaOwnerActions } from '@/components/capa/capa-owner-actions'
import { PriorityTag } from '@/components/ui/status-tag' import { Avatar } from '@/components/ui/avatar'
import { PriorityTag, StatusTag } from '@/components/ui/status-tag'
import { daysLate } from '@/lib/capa/list'
interface Props { interface Props {
params: Promise<{ id: string }> 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) { export default async function CapaDetailPage({ params }: Props) {
const { id } = await params const { id } = await params
const session = await getSession() const session = await getSession()
@@ -50,75 +62,90 @@ export default async function CapaDetailPage({ params }: Props) {
const isHse = session && ['hse', 'admin'].includes(session.role) const isHse = session && ['hse', 'admin'].includes(session.role)
const status = capa.status 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 ( return (
<main className="max-w-2xl mx-auto px-4 py-6"> <div className="space-y-4 px-4 py-5 md:px-8 md:py-6">
<Link href="/hse/capa" className="text-sm text-accent-700 hover:underline mb-4 inline-block"> <Link href="/hse/capa" className="inline-flex items-center gap-1 text-[13px] text-accent hover:underline">
← CAPA Board <ArrowLeft size={14} strokeWidth={2} aria-hidden />
CAPA
</Link> </Link>
<div className="bg-surface shadow-sm p-5 mb-4 space-y-4"> <div className="space-y-2">
<div className="flex items-start justify-between"> <h1 className="text-xl font-[650]">{capa.description}</h1>
<div> <div className="flex flex-wrap items-center gap-2">
<p className="text-xs text-gray-500 mb-1"> <StatusTag status={shownStatus} />
Incident: {capa.incidentRefNo ?? '—'}
</p>
<p className="text-gray-900 font-medium">{capa.description}</p>
</div>
<PriorityTag priority={capa.priority} /> <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> </div>
{capa.rootCauseRef && <p className="text-[13px] text-muted">Root cause: {capa.rootCauseRef}</p>}
</div>
<div className="grid grid-cols-2 gap-3 text-sm"> <div className="grid gap-4 lg:grid-cols-[1fr_320px]">
<div> <div className="space-y-4">
<p className="text-xs text-gray-500">Owner</p> {canAct && (
<p className="text-gray-800">{capa.ownerName ?? '—'}</p> <div>
</div> <CapaOwnerActions capaId={id} currentStatus={status} />
<div>
<p className="text-xs text-gray-500">Department</p>
<p className="text-gray-800">{capa.department}</p>
</div>
<div>
<p className="text-xs text-gray-500">Due Date</p>
<p className="text-gray-800">{capa.dueDate}</p>
</div>
<div>
<p className="text-xs text-gray-500">Status</p>
<p className="text-gray-800 capitalize">{status.replace(/_/g, ' ')}</p>
</div>
{capa.ownerNotes && (
<div className="col-span-2">
<p className="text-xs text-gray-500">Owner Notes</p>
<p className="text-sm text-gray-800 whitespace-pre-wrap">{capa.ownerNotes}</p>
</div> </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> </div>
{capa.rootCauseRef && ( <aside>
<div> <section className="rounded-xl bg-surface p-5 shadow-card">
<p className="text-xs text-gray-500">Root Cause Reference</p> <h2 className="mb-1 text-sm font-semibold">Details</h2>
<p className="text-sm text-gray-800">{capa.rootCauseRef}</p> <dl>
</div> <Row label="Owner">
)} {capa.ownerName ? (
<span className="inline-flex items-center gap-2">
{capa.completedAt && ( <Avatar name={capa.ownerName} />
<p className="text-xs text-gray-500"> {capa.ownerName}
Completed: {new Date(capa.completedAt).toLocaleString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })} </span>
</p> ) : (
)} '—'
)}
</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>
</div>
{['open', 'in_progress', 'overdue', 'reopened'].includes(status) &&
(isHse || session?.sub === capa.ownerUserId) && (
<CapaOwnerActions capaId={id} currentStatus={status} />
)}
{isHse && status === 'pending_verification' && (
<VerifyForm capaId={id} />
)}
{isHse && status === 'verified' && (
<CloseCapaButton capaId={id} />
)}
</main>
) )
} }
+11 -17
View File
@@ -1,13 +1,13 @@
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
import Link from 'next/link'
import { asAdmin } from '@/lib/db/with-user' import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session' import { getSession } from '@/lib/auth/get-session'
import { capaActions, incidents, users } from '@/lib/db/schema' import { capaActions, incidents, users } from '@/lib/db/schema'
import { eq, asc } from 'drizzle-orm' import { eq, asc } from 'drizzle-orm'
import { aliasedTable } 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() { export default async function CapaListPage() {
const session = await getSession() const session = await getSession()
@@ -34,29 +34,23 @@ export default async function CapaListPage() {
) )
const today = new Date().toISOString().slice(0, 10) const today = new Date().toISOString().slice(0, 10)
const capas = rows.map(r => ({ const capas: CapaRow[] = rows.map(r => ({
id: r.id, id: r.id,
incident_id: r.incidentId, incident_id: r.incidentId,
description: r.description, description: r.description,
department: r.department, department: r.department,
due_date: r.dueDate, due_date: r.dueDate,
priority: r.priority, priority: r.priority,
status: (r.status === 'open' || r.status === 'in_progress') && r.dueDate && r.dueDate < today status: ((r.status === 'open' || r.status === 'in_progress') && r.dueDate && r.dueDate < today
? 'overdue' as const ? 'overdue'
: r.status, : r.status) as CapaStatus,
incidents: { reference_no: r.incidentRefNo ?? null }, incident_ref: r.incidentRefNo ?? null,
owner: r.ownerName ? { name: r.ownerName } : null, owner_name: r.ownerName ?? null,
})) }))
return ( return (
<main className="max-w-6xl mx-auto px-4 py-6"> <div className="px-4 py-5 md:px-8 md:py-6">
<div className="flex items-center justify-between mb-6"> <CapaWorkspace capas={capas} today={today} />
<h1 className="text-2xl font-bold text-gray-900">CAPA Board</h1> </div>
<Link href="/hse/incidents" className="text-sm text-accent-700 hover:underline">
← Incidents
</Link>
</div>
<CapaBoard capas={capas} />
</main>
) )
} }
@@ -1,5 +1,6 @@
import { notFound, redirect } from 'next/navigation' import { notFound, redirect } from 'next/navigation'
import Link from 'next/link' import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'
import { asAdmin } from '@/lib/db/with-user' import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session' import { getSession } from '@/lib/auth/get-session'
import { incidents } from '@/lib/db/schema' import { incidents } from '@/lib/db/schema'
@@ -30,15 +31,18 @@ export default async function NewCapaPage({ params }: Props) {
if (!incident) notFound() if (!incident) notFound()
return ( return (
<main className="max-w-lg mx-auto px-4 py-6"> <div className="max-w-xl space-y-4 px-4 py-5 md:px-8 md:py-6">
<Link href={`/hse/incidents/${id}`} className="text-sm text-accent-700 hover:underline mb-4 inline-block"> <Link href={`/hse/incidents/${id}`} className="inline-flex items-center gap-1 text-[13px] text-accent hover:underline">
← Back to incident <ArrowLeft size={14} strokeWidth={2} aria-hidden />
Back to incident
</Link> </Link>
<h1 className="text-xl font-bold text-gray-900 mb-1">Add CAPA Action</h1> <div>
<p className="text-sm text-gray-500 mb-6"> <h1 className="text-xl font-[650]">Add CAPA action</h1>
{incident.referenceNo ?? id} <p className="mt-0.5 font-mono text-[12.5px] text-muted">{incident.referenceNo ?? id}</p>
</p> </div>
<CapaForm incidentId={id} /> <div className="rounded-xl bg-surface p-5 shadow-card">
</main> <CapaForm incidentId={id} />
</div>
</div>
) )
} }
+4 -6
View File
@@ -6,8 +6,7 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit' import { writeAuditLog } from '@/lib/db/audit'
import { incidents, sites, zones, auditLog } from '@/lib/db/schema' import { incidents, sites, zones, auditLog } from '@/lib/db/schema'
import { eq, and, gte, desc } from 'drizzle-orm' import { eq, and, gte, desc } from 'drizzle-orm'
import { createDeepSeekClient } from '@/lib/claude/client' import { createLocalLLMClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
type ZoneAggregate = { type ZoneAggregate = {
zone: string zone: string
@@ -103,13 +102,12 @@ export async function POST() {
return NextResponse.json({ error: 'Rate limit: wait 60 seconds between AI requests' }, { status: 429 }) return NextResponse.json({ error: 'Rate limit: wait 60 seconds between AI requests' }, { status: 429 })
} }
const deepseekKey = await getApiKey('DEEPSEEK_API_KEY') const client = createLocalLLMClient()
const client = createDeepSeekClient(deepseekKey)
let res: Awaited<ReturnType<typeof client.chat.completions.create>> let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try { try {
res = await client.chat.completions.create({ res = await client.chat.completions.create({
model: 'deepseek-v4-pro', model: 'qwen3:14b',
max_tokens: 2048, max_tokens: 2048,
messages: [ messages: [
{ {
@@ -168,7 +166,7 @@ Flag only zones with rising or elevated risk (at most 5 flags; do not flag healt
await withUser(session.sub, async tx => await withUser(session.sub, async tx =>
writeAuditLog(tx, 'incidents', session.sub, 'ai_risk_flags', writeAuditLog(tx, 'incidents', session.sub, 'ai_risk_flags',
{ flags, summary: input.summary, model: 'deepseek-v4-pro' }) { flags, summary: input.summary, model: 'qwen3:14b' })
) )
return NextResponse.json({ flags, summary: input.summary }) return NextResponse.json({ flags, summary: input.summary })
+4 -6
View File
@@ -6,8 +6,7 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit' import { writeAuditLog } from '@/lib/db/audit'
import { incidents, auditLog, sites, zones } from '@/lib/db/schema' import { incidents, auditLog, sites, zones } from '@/lib/db/schema'
import { eq, and, gte, sql } from 'drizzle-orm' import { eq, and, gte, sql } from 'drizzle-orm'
import { createDeepSeekClient } from '@/lib/claude/client' import { createLocalLLMClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
export async function POST( export async function POST(
_request: NextRequest, _request: NextRequest,
@@ -32,8 +31,7 @@ export async function POST(
if (Number(rateRow?.cnt ?? 0) > 0) if (Number(rateRow?.cnt ?? 0) > 0)
return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 }) return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 })
const deepseekKey = await getApiKey('DEEPSEEK_API_KEY') const client = createLocalLLMClient()
const client = createDeepSeekClient(deepseekKey)
const [incident] = await withUser(session.sub, async tx => const [incident] = await withUser(session.sub, async tx =>
tx.select({ tx.select({
@@ -59,7 +57,7 @@ export async function POST(
let res: Awaited<ReturnType<typeof client.chat.completions.create>> let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try { try {
res = await client.chat.completions.create({ res = await client.chat.completions.create({
model: 'deepseek-v4-pro', model: 'qwen3:14b',
max_tokens: 2048, max_tokens: 2048,
messages: [ messages: [
{ {
@@ -107,7 +105,7 @@ Provide 3–5 Why steps drilling from immediate cause to root cause. Frame CAPA
await withUser(session.sub, async tx => { await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'incidents', id, 'ai_rca_draft', { await writeAuditLog(tx, 'incidents', id, 'ai_rca_draft', {
root_cause_summary: draft.root_cause_summary as string, root_cause_summary: draft.root_cause_summary as string,
model: 'deepseek-v4-pro', model: 'qwen3:14b',
}) })
}) })
@@ -6,8 +6,7 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit' import { writeAuditLog } from '@/lib/db/audit'
import { incidents, auditLog } from '@/lib/db/schema' import { incidents, auditLog } from '@/lib/db/schema'
import { eq, and, gte, sql } from 'drizzle-orm' import { eq, and, gte, sql } from 'drizzle-orm'
import { createDeepSeekClient } from '@/lib/claude/client' import { createLocalLLMClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
export async function POST( export async function POST(
_request: NextRequest, _request: NextRequest,
@@ -32,8 +31,7 @@ export async function POST(
if (Number(rateRow?.cnt ?? 0) > 0) if (Number(rateRow?.cnt ?? 0) > 0)
return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 }) return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 })
const deepseekKey = await getApiKey('DEEPSEEK_API_KEY') const client = createLocalLLMClient()
const client = createDeepSeekClient(deepseekKey)
const [incident] = await withUser(session.sub, async tx => const [incident] = await withUser(session.sub, async tx =>
tx.select({ tx.select({
@@ -50,7 +48,7 @@ export async function POST(
let res: Awaited<ReturnType<typeof client.chat.completions.create>> let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try { try {
res = await client.chat.completions.create({ res = await client.chat.completions.create({
model: 'deepseek-v4-pro', model: 'qwen3:14b',
max_tokens: 1024, max_tokens: 1024,
messages: [ messages: [
{ {
@@ -105,7 +103,7 @@ Output exactly this JSON structure:
} }
await withUser(session.sub, async tx => { await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'incidents', id, 'ai_triage_suggest', { suggestion: input, model: 'deepseek-v4-pro' }) await writeAuditLog(tx, 'incidents', id, 'ai_triage_suggest', { suggestion: input, model: 'qwen3:14b' })
}) })
return NextResponse.json(input) return NextResponse.json(input)
+4 -6
View File
@@ -6,8 +6,7 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit' import { writeAuditLog } from '@/lib/db/audit'
import { auditLog } from '@/lib/db/schema' import { auditLog } from '@/lib/db/schema'
import { eq, and, gte, sql } from 'drizzle-orm' import { eq, and, gte, sql } from 'drizzle-orm'
import { createDeepSeekClient } from '@/lib/claude/client' import { createLocalLLMClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
const session = await getSession() const session = await getSession()
@@ -26,8 +25,7 @@ export async function POST(request: NextRequest) {
if (Number(rateRow?.cnt ?? 0) > 0) if (Number(rateRow?.cnt ?? 0) > 0)
return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 }) return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 })
const deepseekKey = await getApiKey('DEEPSEEK_API_KEY') const client = createLocalLLMClient()
const client = createDeepSeekClient(deepseekKey)
let body: { description?: string; incident_type?: string } let body: { description?: string; incident_type?: string }
try { try {
@@ -42,7 +40,7 @@ export async function POST(request: NextRequest) {
let res: Awaited<ReturnType<typeof client.chat.completions.create>> let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try { try {
res = await client.chat.completions.create({ res = await client.chat.completions.create({
model: 'deepseek-v4-pro', model: 'qwen3:14b',
max_tokens: 1024, max_tokens: 1024,
messages: [ messages: [
{ {
@@ -89,7 +87,7 @@ Scoring criteria: specificity (location, time, persons involved), completeness (
await withUser(session.sub, async tx => { await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'incidents', session.sub, 'ai_quality_check', { await writeAuditLog(tx, 'incidents', session.sub, 'ai_quality_check', {
score: input.score, passes: input.passes, model: 'deepseek-v4-pro', score: input.score, passes: input.passes, model: 'qwen3:14b',
}) })
}) })
+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>
)
}
+38 -33
View File
@@ -2,6 +2,8 @@
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Field, Input, Select, Textarea } from '@/components/ui/field'
interface User { interface User {
id: string id: string
@@ -71,59 +73,62 @@ export function CapaForm({ incidentId }: Props) {
return ( return (
<form onSubmit={handleSubmit} className="space-y-4"> <form onSubmit={handleSubmit} className="space-y-4">
<div> <Field label="Action Description *" htmlFor="capa-description">
<label className="block text-sm font-medium text-gray-700 mb-1">Action Description *</label> <Textarea
<textarea id="capa-description"
value={description} value={description}
onChange={e => setDescription(e.target.value)} onChange={e => setDescription(e.target.value)}
rows={3} required rows={3}
className="w-full border border-divider px-3 py-2 text-sm" required
placeholder="What corrective action will be taken?" placeholder="What corrective action will be taken?"
/> />
</div> </Field>
<div> <Field label="Root Cause Reference" htmlFor="capa-root-cause">
<label className="block text-sm font-medium text-gray-700 mb-1">Root Cause Reference</label> <Input
<input type="text" value={rootCauseRef} id="capa-root-cause"
type="text"
value={rootCauseRef}
onChange={e => setRootCauseRef(e.target.value)} onChange={e => setRootCauseRef(e.target.value)}
className="w-full border border-divider px-3 py-2 text-sm" placeholder="e.g. Why #3 — inadequate training"
placeholder="e.g. Why #3 — inadequate training" /> />
</div> </Field>
<div> <Field label="Assigned To *" htmlFor="capa-owner">
<label className="block text-sm font-medium text-gray-700 mb-1">Assigned To *</label> <Select id="capa-owner" value={ownerId} onChange={e => handleOwnerChange(e.target.value)} required>
<select value={ownerId} onChange={e => handleOwnerChange(e.target.value)} required
className="w-full border border-divider px-3 py-2 text-sm">
<option value="">Select owner…</option> <option value="">Select owner…</option>
{users.map(u => ( {users.map(u => (
<option key={u.id} value={u.id}>{u.name} ({u.department})</option> <option key={u.id} value={u.id}>{u.name} ({u.department})</option>
))} ))}
</select> </Select>
</div> </Field>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div> <Field label="Due Date *" htmlFor="capa-due">
<label className="block text-sm font-medium text-gray-700 mb-1">Due Date *</label> <Input id="capa-due" type="date" value={dueDate} onChange={e => setDueDate(e.target.value)} required />
<input type="date" value={dueDate} onChange={e => setDueDate(e.target.value)} required </Field>
className="w-full border border-divider px-3 py-2 text-sm" /> <Field label="Priority" htmlFor="capa-priority">
</div> <Select
<div> id="capa-priority"
<label className="block text-sm font-medium text-gray-700 mb-1">Priority</label> value={priority}
<select value={priority} onChange={e => setPriority(e.target.value as 'low' | 'med' | 'high')} onChange={e => setPriority(e.target.value as 'low' | 'med' | 'high')}
className="w-full border border-divider px-3 py-2 text-sm"> >
<option value="low">Low</option> <option value="low">Low</option>
<option value="med">Medium</option> <option value="med">Medium</option>
<option value="high">High</option> <option value="high">High</option>
</select> </Select>
</div> </Field>
</div> </div>
{error && <p className="text-sm text-red-600">{error}</p>} {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" disabled={saving} <Button type="submit" block disabled={saving}>
className="w-full bg-accent text-white py-2 text-sm font-semibold disabled:opacity-50">
{saving ? 'Creating…' : 'Create CAPA Action'} {saving ? 'Creating…' : 'Create CAPA Action'}
</button> </Button>
</form> </form>
) )
} }
+5 -12
View File
@@ -2,6 +2,7 @@
import { useState } from 'react' import { useState } from 'react'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
interface Props { interface Props {
capaId: string capaId: string
@@ -33,25 +34,17 @@ export function CapaOwnerActions({ capaId, currentStatus }: Props) {
if (currentStatus === 'open' || currentStatus === 'reopened' || currentStatus === 'overdue') { if (currentStatus === 'open' || currentStatus === 'reopened' || currentStatus === 'overdue') {
return ( return (
<button <Button variant="secondary" onClick={() => updateStatus('in_progress')} disabled={loading}>
onClick={() => updateStatus('in_progress')}
disabled={loading}
className="text-sm px-3 py-1.5 border border-divider hover:bg-gray-50 disabled:opacity-50"
>
{loading ? '…' : 'Mark In Progress'} {loading ? '…' : 'Mark In Progress'}
</button> </Button>
) )
} }
if (currentStatus === 'in_progress') { if (currentStatus === 'in_progress') {
return ( return (
<button <Button onClick={() => updateStatus('pending_verification')} disabled={loading}>
onClick={() => updateStatus('pending_verification')}
disabled={loading}
className="text-sm px-3 py-1.5 bg-accent text-white hover:bg-accent-600 disabled:opacity-50"
>
{loading ? '…' : 'Submit for Verification'} {loading ? '…' : 'Submit for Verification'}
</button> </Button>
) )
} }
+16 -17
View File
@@ -1,6 +1,8 @@
'use client' 'use client'
import { useState } from 'react' import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Field, Textarea } from '@/components/ui/field'
interface Props { interface Props {
capaId: string capaId: string
@@ -32,25 +34,22 @@ export function CapaOwnerNotesForm({ capaId, initialNotes }: Props) {
} }
return ( return (
<div className="mt-3 space-y-1"> <div className="mt-3 space-y-2">
<label className="text-xs text-gray-500 font-medium">Remarks / Notes</label> <Field label="Remarks / Notes" htmlFor={`notes-${capaId}`}>
<textarea <Textarea
value={notes} id={`notes-${capaId}`}
onChange={e => { setNotes(e.target.value); setSaved(false) }} value={notes}
rows={2} onChange={e => { setNotes(e.target.value); setSaved(false) }}
placeholder="Add any notes or updates for this action…" rows={2}
className="w-full border border-divider px-3 py-2 text-sm text-gray-800 resize-none focus:outline-none focus:ring-2 focus:ring-accent" placeholder="Add any notes or updates for this action…"
/> />
{error && <p className="text-xs text-red-600">{error}</p>} </Field>
{error && <p role="alert" className="text-xs text-danger">{error}</p>}
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<button <Button variant="secondary" onClick={handleSave} disabled={saving}>
onClick={handleSave}
disabled={saving}
className="text-xs px-3 py-1 bg-gray-800 text-white hover:bg-gray-700 disabled:opacity-50"
>
{saving ? 'Saving…' : 'Save Notes'} {saving ? 'Saving…' : 'Save Notes'}
</button> </Button>
{saved && <span className="text-xs text-ink">Saved</span>} {saved && <span className="text-xs text-st-green-fg">Saved</span>}
</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>
)
}
+15 -12
View File
@@ -2,6 +2,7 @@
import { useState } from 'react' import { useState } from 'react'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
interface Props { interface Props {
capaId: string capaId: string
@@ -31,19 +32,21 @@ export function CloseCapaButton({ capaId }: Props) {
} }
return ( return (
<div className="border border-divider p-5 space-y-3 bg-neutral-100"> <div className="space-y-3 rounded-xl bg-surface p-5 shadow-card">
<h3 className="text-sm font-semibold text-gray-800">Close CAPA</h3> <div>
<p className="text-sm text-gray-600"> <h3 className="text-sm font-semibold">Close CAPA</h3>
This CAPA has been verified as effective. Close it to mark it fully resolved. <p className="mt-0.5 text-xs text-muted">
</p> This CAPA has been verified as effective. Close it to mark it fully resolved.
{error && <p className="text-sm text-red-600">{error}</p>} </p>
<button </div>
onClick={handleClose} {error && (
disabled={loading} <p role="alert" className="rounded-md bg-st-red-bg px-3 py-2 text-[13px] text-st-red-fg">
className="w-full bg-accent text-white py-2 text-sm font-semibold hover:bg-accent-700 disabled:opacity-50" {error}
> </p>
)}
<Button onClick={handleClose} disabled={loading}>
{loading ? 'Closing…' : 'Close CAPA'} {loading ? 'Closing…' : 'Close CAPA'}
</button> </Button>
</div> </div>
) )
} }
+70 -37
View File
@@ -2,14 +2,47 @@
import { useState } from 'react' import { useState } from 'react'
import { useRouter } from 'next/navigation' 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 { interface Props {
capaId: string 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) { export function VerifyForm({ capaId }: Props) {
const router = useRouter() const router = useRouter()
const [verdict, setVerdict] = useState<'verified' | 'reopened' | null>(null) const [verdict, setVerdict] = useState<Verdict | null>(null)
const [reopenReason, setReopenReason] = useState('') const [reopenReason, setReopenReason] = useState('')
const [saving, setSaving] = useState(false) const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
@@ -39,50 +72,50 @@ export function VerifyForm({ capaId }: Props) {
} }
return ( return (
<form onSubmit={handleSubmit} className="border border-divider p-5 space-y-4 bg-accent-100"> <form onSubmit={handleSubmit} className="space-y-4 rounded-xl bg-surface p-5 shadow-card">
<h3 className="text-sm font-semibold text-gray-800">HSE Verification</h3> <div>
<div className="flex gap-3"> <h3 className="text-sm font-semibold">Verify this action</h3>
<button <p className="mt-0.5 text-xs text-muted">Confirm the corrective action fixed the root cause, or send it back.</p>
type="button"
onClick={() => setVerdict('verified')}
className={`flex-1 py-2 text-sm font-medium border ${
verdict === 'verified'
? 'bg-accent text-white border-accent'
: 'bg-surface text-gray-700 border-divider hover:border-accent'
}`}
>
Verified — Effective
</button>
<button
type="button"
onClick={() => setVerdict('reopened')}
className={`flex-1 py-2 text-sm font-medium border ${
verdict === 'reopened'
? 'bg-accent text-white border-accent'
: 'bg-surface text-gray-700 border-divider hover:border-accent'
}`}
>
Reopen — Ineffective
</button>
</div> </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' && ( {verdict === 'reopened' && (
<div> <Field label="Why is the action ineffective? *" htmlFor="reopen-reason">
<label className="block text-sm font-medium text-gray-700 mb-1">Why is the action ineffective? *</label> <Textarea
<textarea id="reopen-reason"
value={reopenReason} value={reopenReason}
onChange={e => setReopenReason(e.target.value)} onChange={e => setReopenReason(e.target.value)}
rows={2} required rows={2}
className="w-full border border-divider px-3 py-2 text-sm" required
placeholder="Describe why the corrective action did not resolve the root cause…" placeholder="Describe why the corrective action did not resolve the root cause…"
/> />
</div> </Field>
)} )}
{error && <p className="text-sm text-red-600">{error}</p>}
{error && (
<p role="alert" className="rounded-md bg-st-red-bg px-3 py-2 text-[13px] text-st-red-fg">
{error}
</p>
)}
{verdict && ( {verdict && (
<button type="submit" disabled={saving} <Button type="submit" disabled={saving}>
className="w-full bg-gray-900 text-white py-2 text-sm font-semibold disabled:opacity-50"> {saving ? 'Saving…' : verdict === 'verified' ? 'Confirm verification' : 'Reopen action'}
{saving ? 'Saving…' : 'Submit Verification'} </Button>
</button>
)} )}
</form> </form>
) )
+3 -1
View File
@@ -172,6 +172,8 @@ Notifications drawer: absolute, top/right/bottom 8px, width 420px, white, radius
| 12-15 | Mobile, new incident 1/3 to saved offline | `/report` | | 12-15 | Mobile, new incident 1/3 to saved offline | `/report` |
| 16 | Mobile, CAPA owner action | `/capa-owner` | | 16 | Mobile, CAPA owner action | `/capa-owner` |
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.
New routes in the mockup that do not exist yet: audit log (05d), DOSH reporting entry (02d), and any "new tab" marked above. Treat them as separate features; do not build them as part of the restyle. New routes in the mockup that do not exist yet: audit log (05d), DOSH reporting entry (02d), and any "new tab" marked above. Treat them as separate features; do not build them as part of the restyle.
## 6. Accessibility ## 6. Accessibility
@@ -193,7 +195,7 @@ This file covers look and component structure. Routes, queries, permissions and
5. **Migrate the Incidents list** (screen 01 and 10) as the first full screen. 5. **Migrate the Incidents list** (screen 01 and 10) as the first full screen.
6. **Remaining screens**, in §5 order, one plan per group. 6. **Remaining screens**, in §5 order, one plan per group.
Slice 1 (gate, tokens, primitives, TableCard, shells, Incidents list) is implemented; the remaining screens follow in later plans. 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.
Gate first: before step 1, update `scripts/check-design-gates.mjs` to allow `rounded-*`, flag `border-b-2` and `border-2`, and flag Archivo and `#ec3013`. `npm run check:design` must pass at the end of each step. Gate first: before step 1, update `scripts/check-design-gates.mjs` to allow `rounded-*`, flag `border-b-2` and `border-2`, and flag Archivo and `#ec3013`. `npm run check:design` must pass at the end of each step.
File diff suppressed because it is too large Load Diff
+111
View File
@@ -0,0 +1,111 @@
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)
}
+4
View File
@@ -3,3 +3,7 @@ import OpenAI from 'openai'
export function createDeepSeekClient(apiKey: string): OpenAI { export function createDeepSeekClient(apiKey: string): OpenAI {
return new OpenAI({ apiKey, baseURL: 'https://api.deepseek.com' }) return new OpenAI({ apiKey, baseURL: 'https://api.deepseek.com' })
} }
export function createLocalLLMClient(): OpenAI {
return new OpenAI({ apiKey: 'local', baseURL: 'http://localhost:11434/v1' })
}
+2 -6
View File
@@ -17,7 +17,7 @@ vi.mock('@/lib/supabase/server', () => ({
})) }))
vi.mock('@/lib/claude/client', () => ({ vi.mock('@/lib/claude/client', () => ({
createDeepSeekClient: vi.fn().mockReturnValue({ createLocalLLMClient: vi.fn().mockReturnValue({
chat: { chat: {
completions: { completions: {
create: vi.fn().mockResolvedValue({ create: vi.fn().mockResolvedValue({
@@ -38,10 +38,6 @@ vi.mock('@/lib/claude/client', () => ({
}), }),
})) }))
vi.mock('@/lib/settings', () => ({
getApiKey: vi.fn().mockResolvedValue('sk-test-key'),
}))
describe('POST /api/incidents/ai/quality-check', () => { describe('POST /api/incidents/ai/quality-check', () => {
it('returns 422 when description is missing', async () => { it('returns 422 when description is missing', async () => {
const { POST } = await import('@/app/api/incidents/ai/quality-check/route') const { POST } = await import('@/app/api/incidents/ai/quality-check/route')
@@ -54,7 +50,7 @@ describe('POST /api/incidents/ai/quality-check', () => {
expect(res.status).toBe(422) expect(res.status).toBe(422)
}) })
it('returns quality assessment from DeepSeek', async () => { it('returns quality assessment from local LLM', async () => {
const { POST } = await import('@/app/api/incidents/ai/quality-check/route') const { POST } = await import('@/app/api/incidents/ai/quality-check/route')
const req = new Request('http://localhost/api/incidents/ai/quality-check', { const req = new Request('http://localhost/api/incidents/ai/quality-check', {
method: 'POST', method: 'POST',
+1 -5
View File
@@ -46,7 +46,7 @@ vi.mock('@/lib/supabase/server', () => ({
})) }))
vi.mock('@/lib/claude/client', () => ({ vi.mock('@/lib/claude/client', () => ({
createDeepSeekClient: vi.fn().mockReturnValue({ createLocalLLMClient: vi.fn().mockReturnValue({
chat: { chat: {
completions: { completions: {
create: vi.fn().mockResolvedValue({ create: vi.fn().mockResolvedValue({
@@ -67,10 +67,6 @@ vi.mock('@/lib/claude/client', () => ({
}), }),
})) }))
vi.mock('@/lib/settings', () => ({
getApiKey: vi.fn().mockResolvedValue('sk-test-key'),
}))
describe('POST /api/incidents/[id]/ai/rca-draft', () => { describe('POST /api/incidents/[id]/ai/rca-draft', () => {
it('returns five_why_steps, root_cause_summary, and capa_suggestions', async () => { it('returns five_why_steps, root_cause_summary, and capa_suggestions', async () => {
const { POST } = await import('@/app/api/incidents/[id]/ai/rca-draft/route') const { POST } = await import('@/app/api/incidents/[id]/ai/rca-draft/route')
+1 -5
View File
@@ -36,7 +36,7 @@ vi.mock('@/lib/supabase/server', () => ({
})) }))
vi.mock('@/lib/claude/client', () => ({ vi.mock('@/lib/claude/client', () => ({
createDeepSeekClient: vi.fn().mockReturnValue({ createLocalLLMClient: vi.fn().mockReturnValue({
chat: { chat: {
completions: { completions: {
create: vi.fn().mockResolvedValue({ create: vi.fn().mockResolvedValue({
@@ -57,10 +57,6 @@ vi.mock('@/lib/claude/client', () => ({
}), }),
})) }))
vi.mock('@/lib/settings', () => ({
getApiKey: vi.fn().mockResolvedValue('sk-test-key'),
}))
describe('POST /api/incidents/[id]/ai/triage-suggest', () => { describe('POST /api/incidents/[id]/ai/triage-suggest', () => {
it('returns triage suggestion with severity and DOSH flags', async () => { it('returns triage suggestion with severity and DOSH flags', async () => {
const { POST } = await import('@/app/api/incidents/[id]/ai/triage-suggest/route') const { POST } = await import('@/app/api/incidents/[id]/ai/triage-suggest/route')
+82
View File
@@ -0,0 +1,82 @@
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()
})
})
@@ -0,0 +1,29 @@
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.')
})
})
@@ -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()
})
})
@@ -0,0 +1,76 @@
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()
})
})
+109
View File
@@ -0,0 +1,109 @@
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)
})
})