feat(capa): restyle the create CAPA form and page with the shared field primitives

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 587b580797
commit 40878c126a
3 changed files with 132 additions and 42 deletions
@@ -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>
) )
} }
+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>
) )
} }
+81
View File
@@ -0,0 +1,81 @@
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) => {
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()
})
})