feat: investigation workspace — 5-Why/fishbone RCA, transitions triaged→investigating→capa_pending

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FFDuBhMKvoWjrWT3ZnGmmr
This commit is contained in:
2026-07-11 15:14:27 +08:00
co-authored by Claude Opus 4.8
parent e55c5284a7
commit 63cb28f520
3 changed files with 378 additions and 0 deletions
@@ -0,0 +1,54 @@
export const dynamic = 'force-dynamic'
import { notFound, redirect } from 'next/navigation'
import Link from 'next/link'
import { createClient } from '@/lib/supabase/server'
import { InvestigationForm } from '@/components/incidents/investigation-form'
interface Props {
params: Promise<{ id: string }>
}
export default async function InvestigationPage({ params }: Props) {
const { id } = await params
const supabase = await createClient()
const { data, error: authError } = await supabase.auth.getUser()
if (authError || !data?.user) redirect(`/login?redirect=/hse/incidents/${id}/investigation`)
const { data: profile } = await supabase
.from('users').select('role').eq('id', data.user.id).single()
if (!profile || profile.role !== 'hse') redirect('/hse/incidents')
const { data: incident } = await supabase
.from('incidents')
.select('id, reference_no, status')
.eq('id', id)
.single()
if (!incident) notFound()
if (!['triaged', 'investigating'].includes((incident as { status: string }).status))
redirect(`/hse/incidents/${id}`)
const { data: existing } = await supabase
.from('investigations')
.select('id')
.eq('incident_id', id)
.order('created_at', { ascending: false })
.limit(1)
.maybeSingle()
return (
<main className="max-w-2xl mx-auto px-4 py-6">
<Link href={`/hse/incidents/${id}`} className="text-sm text-blue-600 hover:underline mb-4 inline-block">
Back to incident
</Link>
<h1 className="text-xl font-bold text-gray-900 mb-1">Investigation Workspace</h1>
<p className="text-sm text-gray-500 mb-6">{(incident as { reference_no: string | null }).reference_no ?? id}</p>
<InvestigationForm
incidentId={id}
existingInvestigationId={(existing as { id: string } | null)?.id ?? null}
/>
</main>
)
}
@@ -0,0 +1,112 @@
export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase
.from('users').select('role').eq('id', user.id).single()
if (!profile || profile.role !== 'hse')
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const { data: incident } = await supabase
.from('incidents').select('status').eq('id', id).single()
if (!incident) return NextResponse.json({ error: 'Not found' }, { status: 404 })
if (incident.status !== 'triaged')
return NextResponse.json({ error: 'Incident must be triaged first' }, { status: 409 })
const body = await request.json()
const method: 'five_why' | 'fishbone' | 'other' = body.method ?? 'five_why'
const { data: inv, error } = await supabase
.from('investigations')
.insert({
incident_id: id,
investigator_id: user.id,
method,
findings_text: body.findings_text ?? null,
root_cause_summary: body.root_cause_summary ?? null,
five_why_steps: method === 'five_why' ? (body.five_why_steps ?? []) : null,
fishbone_categories: method === 'fishbone' ? (body.fishbone_categories ?? []) : null,
})
.select('id')
.single()
if (error || !inv) return NextResponse.json({ error: 'Insert failed' }, { status: 500 })
await supabase
.from('incidents')
.update({ status: 'investigating' })
.eq('id', id)
await supabase.rpc('write_audit_log', {
p_table_name: 'incidents',
p_record_id: id,
p_action: 'investigation_started',
p_new_value: { status: 'investigating', investigation_id: inv.id },
})
return NextResponse.json({ id: inv.id })
}
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user }, error: authError } = await supabase.auth.getUser()
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data: profile } = await supabase
.from('users').select('role').eq('id', user.id).single()
if (!profile || profile.role !== 'hse')
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const body = await request.json()
const { investigation_id, complete, ...fields } = body
if (!investigation_id) return NextResponse.json({ error: 'investigation_id required' }, { status: 422 })
const updateData: Record<string, unknown> = {
findings_text: fields.findings_text ?? null,
root_cause_summary: fields.root_cause_summary ?? null,
five_why_steps: fields.five_why_steps ?? null,
fishbone_categories: fields.fishbone_categories ?? null,
}
if (complete) updateData.completed_at = new Date().toISOString()
const { error } = await supabase
.from('investigations')
.update(updateData)
.eq('id', investigation_id)
.eq('incident_id', id)
if (error) return NextResponse.json({ error: 'Update failed' }, { status: 500 })
if (complete) {
await supabase
.from('incidents')
.update({ status: 'capa_pending' })
.eq('id', id)
await supabase.rpc('write_audit_log', {
p_table_name: 'incidents',
p_record_id: id,
p_action: 'investigation_completed',
p_new_value: { status: 'capa_pending' },
})
}
return NextResponse.json({ ok: true })
}
+212
View File
@@ -0,0 +1,212 @@
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
type FiveWhyStep = { why: string; answer: string }
type FishboneCategory = {
category: 'man' | 'machine' | 'method' | 'material' | 'environment' | 'measurement'
causes: string[]
}
const FISHBONE_CATEGORIES: FishboneCategory['category'][] = [
'man', 'machine', 'method', 'material', 'environment', 'measurement',
]
const CATEGORY_LABELS: Record<FishboneCategory['category'], string> = {
man: 'Man (People)',
machine: 'Machine',
method: 'Method',
material: 'Material',
environment: 'Environment',
measurement: 'Measurement',
}
interface Props {
incidentId: string
existingInvestigationId: string | null
}
export function InvestigationForm({ incidentId, existingInvestigationId }: Props) {
const router = useRouter()
const [method, setMethod] = useState<'five_why' | 'fishbone' | 'other'>('five_why')
const [fiveWhy, setFiveWhy] = useState<FiveWhyStep[]>([
{ why: 'Why did the incident happen?', answer: '' },
])
const [fishbone, setFishbone] = useState<FishboneCategory[]>(
FISHBONE_CATEGORIES.map(c => ({ category: c, causes: [''] }))
)
const [findingsText, setFindingsText] = useState('')
const [rootCause, setRootCause] = useState('')
const [complete, setComplete] = useState(false)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
function addWhyStep() {
if (fiveWhy.length >= 5) return
setFiveWhy([...fiveWhy, { why: '', answer: '' }])
}
function updateWhyStep(i: number, field: keyof FiveWhyStep, value: string) {
setFiveWhy(fiveWhy.map((s, idx) => idx === i ? { ...s, [field]: value } : s))
}
function updateFishboneCause(catIdx: number, causeIdx: number, value: string) {
setFishbone(fishbone.map((c, i) =>
i === catIdx ? { ...c, causes: c.causes.map((cause, j) => j === causeIdx ? value : cause) } : c
))
}
function addFishboneCause(catIdx: number) {
setFishbone(fishbone.map((c, i) => i === catIdx ? { ...c, causes: [...c.causes, ''] } : c))
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
setSaving(true)
setError(null)
const payload = {
method,
findings_text: findingsText || null,
root_cause_summary: rootCause || null,
five_why_steps: method === 'five_why' ? fiveWhy.filter(s => s.answer) : null,
fishbone_categories: method === 'fishbone'
? fishbone.map(c => ({ ...c, causes: c.causes.filter(Boolean) })).filter(c => c.causes.length > 0)
: null,
}
let res: Response
if (existingInvestigationId) {
res = await fetch(`/api/incidents/${incidentId}/investigation`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...payload, investigation_id: existingInvestigationId, complete }),
})
} else {
res = await fetch(`/api/incidents/${incidentId}/investigation`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
}
if (!res.ok) {
const data = await res.json()
setError(data.error ?? 'Save failed')
setSaving(false)
return
}
router.push(`/hse/incidents/${incidentId}`)
router.refresh()
}
return (
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">RCA Method</label>
<div className="flex gap-3">
{(['five_why', 'fishbone', 'other'] as const).map(m => (
<button
key={m} type="button"
onClick={() => setMethod(m)}
className={`px-3 py-1.5 rounded-lg text-sm font-medium border ${
method === m
? 'bg-blue-600 text-white border-blue-600'
: 'bg-white text-gray-700 border-gray-300 hover:border-blue-400'
}`}
>
{m === 'five_why' ? '5-Why' : m === 'fishbone' ? 'Fishbone' : 'Other'}
</button>
))}
</div>
</div>
{method === 'five_why' && (
<div className="space-y-3">
<p className="text-sm font-medium text-gray-700">5-Why Analysis</p>
{fiveWhy.map((step, i) => (
<div key={i} className="border border-gray-200 rounded-lg p-3 space-y-2">
<label className="block text-xs text-gray-500">Why #{i + 1}</label>
<input
type="text" value={step.why}
onChange={e => updateWhyStep(i, 'why', e.target.value)}
placeholder="Why did this happen?"
className="w-full rounded border border-gray-300 px-2 py-1.5 text-sm"
/>
<textarea
value={step.answer}
onChange={e => updateWhyStep(i, 'answer', e.target.value)}
rows={2} placeholder="Answer / finding…"
className="w-full rounded border border-gray-300 px-2 py-1.5 text-sm"
/>
</div>
))}
{fiveWhy.length < 5 && (
<button type="button" onClick={addWhyStep}
className="text-sm text-blue-600 hover:underline">
+ Add another Why
</button>
)}
</div>
)}
{method === 'fishbone' && (
<div className="space-y-3">
<p className="text-sm font-medium text-gray-700">Fishbone (Ishikawa) Analysis</p>
{fishbone.map((cat, catIdx) => (
<div key={cat.category} className="border border-gray-200 rounded-lg p-3">
<p className="text-xs font-semibold text-gray-600 mb-2">{CATEGORY_LABELS[cat.category]}</p>
{cat.causes.map((cause, causeIdx) => (
<input
key={causeIdx}
type="text" value={cause}
onChange={e => updateFishboneCause(catIdx, causeIdx, e.target.value)}
placeholder="Contributing cause…"
className="w-full rounded border border-gray-300 px-2 py-1.5 text-sm mb-1.5"
/>
))}
<button type="button" onClick={() => addFishboneCause(catIdx)}
className="text-xs text-blue-600 hover:underline">
+ Add cause
</button>
</div>
))}
</div>
)}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Key Findings</label>
<textarea
value={findingsText}
onChange={e => setFindingsText(e.target.value)}
rows={3}
className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm"
placeholder="Describe the sequence of events and contributing factors…"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Root Cause Summary</label>
<textarea
value={rootCause}
onChange={e => setRootCause(e.target.value)}
rows={2}
className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm"
placeholder="One-sentence root cause statement…"
/>
</div>
{!existingInvestigationId && (
<label className="flex items-center gap-2 text-sm text-gray-700">
<input type="checkbox" checked={complete} onChange={e => setComplete(e.target.checked)}
className="rounded border-gray-300 text-blue-600" />
Mark investigation complete (transitions incident to CAPA Pending)
</label>
)}
{error && <p className="text-sm text-red-600">{error}</p>}
<button type="submit" disabled={saving}
className="w-full bg-indigo-600 text-white rounded-lg py-2 text-sm font-semibold disabled:opacity-50">
{saving ? 'Saving…' : existingInvestigationId ? 'Update Investigation' : 'Start Investigation'}
</button>
</form>
)
}