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>
This commit is contained in:
2026-10-01 11:38:44 +08:00
co-authored by Claude Haiku 4.5
parent 572a9c9484
commit 587b580797
7 changed files with 297 additions and 137 deletions
+86 -59
View File
@@ -2,6 +2,7 @@ export const dynamic = 'force-dynamic'
import { notFound, redirect } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { capaActions, incidents, users } from '@/lib/db/schema'
@@ -10,12 +11,23 @@ import { aliasedTable } from 'drizzle-orm'
import { VerifyForm } from '@/components/capa/verify-form'
import { CloseCapaButton } from '@/components/capa/close-capa-button'
import { CapaOwnerActions } from '@/components/capa/capa-owner-actions'
import { 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 {
params: Promise<{ id: string }>
}
function Row({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="flex items-center justify-between gap-3 border-b border-rule py-2.5 last:border-0">
<dt className="text-xs text-muted">{label}</dt>
<dd className="text-right text-[13px]">{children}</dd>
</div>
)
}
export default async function CapaDetailPage({ params }: Props) {
const { id } = await params
const session = await getSession()
@@ -50,75 +62,90 @@ export default async function CapaDetailPage({ params }: Props) {
const isHse = session && ['hse', 'admin'].includes(session.role)
const status = capa.status
const today = new Date().toISOString().slice(0, 10)
const pastDue = (status === 'open' || status === 'in_progress') && Boolean(capa.dueDate) && capa.dueDate < today
const shownStatus = pastDue ? 'overdue' : status
const late = shownStatus === 'overdue' ? daysLate(capa.dueDate, today) : 0
const canAct = ['open', 'in_progress', 'overdue', 'reopened'].includes(status) &&
(isHse || session?.sub === capa.ownerUserId)
return (
<main className="max-w-2xl mx-auto px-4 py-6">
<Link href="/hse/capa" className="text-sm text-accent-700 hover:underline mb-4 inline-block">
← CAPA Board
<div className="space-y-4 px-4 py-5 md:px-8 md:py-6">
<Link href="/hse/capa" className="inline-flex items-center gap-1 text-[13px] text-accent hover:underline">
<ArrowLeft size={14} strokeWidth={2} aria-hidden />
CAPA
</Link>
<div className="bg-surface shadow-sm p-5 mb-4 space-y-4">
<div className="flex items-start justify-between">
<div>
<p className="text-xs text-gray-500 mb-1">
Incident: {capa.incidentRefNo ?? '—'}
</p>
<p className="text-gray-900 font-medium">{capa.description}</p>
</div>
<div className="space-y-2">
<h1 className="text-xl font-[650]">{capa.description}</h1>
<div className="flex flex-wrap items-center gap-2">
<StatusTag status={shownStatus} />
<PriorityTag priority={capa.priority} />
<span className="text-[13px] text-muted">
From{' '}
<Link href={`/hse/incidents/${capa.incidentId}`} className="font-mono text-[12.5px] text-accent hover:underline">
{capa.incidentRefNo ?? '—'}
</Link>
</span>
</div>
{capa.rootCauseRef && <p className="text-[13px] text-muted">Root cause: {capa.rootCauseRef}</p>}
</div>
<div className="grid grid-cols-2 gap-3 text-sm">
<div>
<p className="text-xs text-gray-500">Owner</p>
<p className="text-gray-800">{capa.ownerName ?? '—'}</p>
</div>
<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 className="grid gap-4 lg:grid-cols-[1fr_320px]">
<div className="space-y-4">
{canAct && (
<div>
<CapaOwnerActions capaId={id} currentStatus={status} />
</div>
)}
{isHse && status === 'pending_verification' && <VerifyForm capaId={id} />}
{isHse && status === 'verified' && <CloseCapaButton capaId={id} />}
{(capa.ownerNotes || capa.completedAt) && (
<section className="space-y-2 rounded-xl bg-surface p-5 shadow-card">
<h2 className="text-sm font-semibold">Completion report</h2>
{capa.completedAt && (
<p className="text-xs text-muted">
Completed {new Date(capa.completedAt).toLocaleString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })}
</p>
)}
{capa.ownerNotes && (
<p className="whitespace-pre-wrap text-[13px] text-ink-3">{capa.ownerNotes}</p>
)}
</section>
)}
</div>
{capa.rootCauseRef && (
<div>
<p className="text-xs text-gray-500">Root Cause Reference</p>
<p className="text-sm text-gray-800">{capa.rootCauseRef}</p>
</div>
)}
{capa.completedAt && (
<p className="text-xs text-gray-500">
Completed: {new Date(capa.completedAt).toLocaleString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })}
</p>
)}
<aside>
<section className="rounded-xl bg-surface p-5 shadow-card">
<h2 className="mb-1 text-sm font-semibold">Details</h2>
<dl>
<Row label="Owner">
{capa.ownerName ? (
<span className="inline-flex items-center gap-2">
<Avatar name={capa.ownerName} />
{capa.ownerName}
</span>
) : (
'—'
)}
</Row>
<Row label="Department">{capa.department}</Row>
<Row label="Priority"><PriorityTag priority={capa.priority} /></Row>
<Row label="Due">
{capa.dueDate}
{late > 0 && <span className="ml-1.5 text-xs text-danger">{`${late} day${late === 1 ? '' : 's'} late`}</span>}
</Row>
{capa.completedAt && (
<Row label="Completed">
{new Date(capa.completedAt).toLocaleDateString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })}
</Row>
)}
</dl>
</section>
</aside>
</div>
{['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>
</div>
)
}
+5 -12
View File
@@ -2,6 +2,7 @@
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
interface Props {
capaId: string
@@ -33,25 +34,17 @@ export function CapaOwnerActions({ capaId, currentStatus }: Props) {
if (currentStatus === 'open' || currentStatus === 'reopened' || currentStatus === 'overdue') {
return (
<button
onClick={() => updateStatus('in_progress')}
disabled={loading}
className="text-sm px-3 py-1.5 border border-divider hover:bg-gray-50 disabled:opacity-50"
>
<Button variant="secondary" onClick={() => updateStatus('in_progress')} disabled={loading}>
{loading ? '…' : 'Mark In Progress'}
</button>
</Button>
)
}
if (currentStatus === 'in_progress') {
return (
<button
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"
>
<Button onClick={() => updateStatus('pending_verification')} disabled={loading}>
{loading ? '…' : 'Submit for Verification'}
</button>
</Button>
)
}
+16 -17
View File
@@ -1,6 +1,8 @@
'use client'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Field, Textarea } from '@/components/ui/field'
interface Props {
capaId: string
@@ -32,25 +34,22 @@ export function CapaOwnerNotesForm({ capaId, initialNotes }: Props) {
}
return (
<div className="mt-3 space-y-1">
<label className="text-xs text-gray-500 font-medium">Remarks / Notes</label>
<textarea
value={notes}
onChange={e => { setNotes(e.target.value); setSaved(false) }}
rows={2}
placeholder="Add any notes or updates for this action…"
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"
/>
{error && <p className="text-xs text-red-600">{error}</p>}
<div className="mt-3 space-y-2">
<Field label="Remarks / Notes" htmlFor={`notes-${capaId}`}>
<Textarea
id={`notes-${capaId}`}
value={notes}
onChange={e => { setNotes(e.target.value); setSaved(false) }}
rows={2}
placeholder="Add any notes or updates for this action…"
/>
</Field>
{error && <p role="alert" className="text-xs text-danger">{error}</p>}
<div className="flex items-center gap-2">
<button
onClick={handleSave}
disabled={saving}
className="text-xs px-3 py-1 bg-gray-800 text-white hover:bg-gray-700 disabled:opacity-50"
>
<Button variant="secondary" onClick={handleSave} disabled={saving}>
{saving ? 'Saving…' : 'Save Notes'}
</button>
{saved && <span className="text-xs text-ink">Saved</span>}
</Button>
{saved && <span className="text-xs text-st-green-fg">Saved</span>}
</div>
</div>
)
+15 -12
View File
@@ -2,6 +2,7 @@
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
interface Props {
capaId: string
@@ -31,19 +32,21 @@ export function CloseCapaButton({ capaId }: Props) {
}
return (
<div className="border border-divider p-5 space-y-3 bg-neutral-100">
<h3 className="text-sm font-semibold text-gray-800">Close CAPA</h3>
<p className="text-sm text-gray-600">
This CAPA has been verified as effective. Close it to mark it fully resolved.
</p>
{error && <p className="text-sm text-red-600">{error}</p>}
<button
onClick={handleClose}
disabled={loading}
className="w-full bg-accent text-white py-2 text-sm font-semibold hover:bg-accent-700 disabled:opacity-50"
>
<div className="space-y-3 rounded-xl bg-surface p-5 shadow-card">
<div>
<h3 className="text-sm font-semibold">Close CAPA</h3>
<p className="mt-0.5 text-xs text-muted">
This CAPA has been verified as effective. Close it to mark it fully resolved.
</p>
</div>
{error && (
<p role="alert" className="rounded-md bg-st-red-bg px-3 py-2 text-[13px] text-st-red-fg">
{error}
</p>
)}
<Button onClick={handleClose} disabled={loading}>
{loading ? 'Closing…' : 'Close CAPA'}
</button>
</Button>
</div>
)
}
+70 -37
View File
@@ -2,14 +2,47 @@
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Field, Textarea } from '@/components/ui/field'
import { cx } from '@/components/ui/cx'
interface Props {
capaId: string
}
type Verdict = 'verified' | 'reopened'
function Choice({
selected,
onSelect,
title,
hint,
}: {
selected: boolean
onSelect: () => void
title: string
hint: string
}) {
return (
<button
type="button"
role="radio"
aria-checked={selected}
onClick={onSelect}
className={cx(
'cursor-pointer rounded-xl p-3 text-left transition-colors',
selected ? 'bg-accent-tint shadow-chip-set' : 'bg-surface shadow-chip hover:bg-surface-2',
)}
>
<span className="block text-[13px] font-semibold">{title}</span>
<span className="mt-0.5 block text-xs text-muted">{hint}</span>
</button>
)
}
export function VerifyForm({ capaId }: Props) {
const router = useRouter()
const [verdict, setVerdict] = useState<'verified' | 'reopened' | null>(null)
const [verdict, setVerdict] = useState<Verdict | null>(null)
const [reopenReason, setReopenReason] = useState('')
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
@@ -39,50 +72,50 @@ export function VerifyForm({ capaId }: Props) {
}
return (
<form onSubmit={handleSubmit} className="border border-divider p-5 space-y-4 bg-accent-100">
<h3 className="text-sm font-semibold text-gray-800">HSE Verification</h3>
<div className="flex gap-3">
<button
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>
<form onSubmit={handleSubmit} className="space-y-4 rounded-xl bg-surface p-5 shadow-card">
<div>
<h3 className="text-sm font-semibold">Verify this action</h3>
<p className="mt-0.5 text-xs text-muted">Confirm the corrective action fixed the root cause, or send it back.</p>
</div>
<div role="radiogroup" aria-label="Verification verdict" className="grid gap-3 sm:grid-cols-2">
<Choice
selected={verdict === 'verified'}
onSelect={() => setVerdict('verified')}
title="Verified, effective"
hint="Root cause addressed. The action is marked verified."
/>
<Choice
selected={verdict === 'reopened'}
onSelect={() => setVerdict('reopened')}
title="Reopen, ineffective"
hint="Returns to the owner with a required reason."
/>
</div>
{verdict === 'reopened' && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Why is the action ineffective? *</label>
<textarea
<Field label="Why is the action ineffective? *" htmlFor="reopen-reason">
<Textarea
id="reopen-reason"
value={reopenReason}
onChange={e => setReopenReason(e.target.value)}
rows={2} required
className="w-full border border-divider px-3 py-2 text-sm"
rows={2}
required
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 && (
<button type="submit" disabled={saving}
className="w-full bg-gray-900 text-white py-2 text-sm font-semibold disabled:opacity-50">
{saving ? 'Saving…' : 'Submit Verification'}
</button>
<Button type="submit" disabled={saving}>
{saving ? 'Saving…' : verdict === 'verified' ? 'Confirm verification' : 'Reopen action'}
</Button>
)}
</form>
)
@@ -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,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()
})
})