From f10fa071f9c9dab1307b3ec212dc6c847fc0232e Mon Sep 17 00:00:00 2001 From: weeihan Date: Sat, 11 Jul 2026 16:27:29 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20AI=20triage=20suggestion=20=E2=80=94=20?= =?UTF-8?q?severity=20+=20DOSH=20flags=20pre-fill?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 4.6 Claude-Session: https://claude.ai/code/session_01FFDuBhMKvoWjrWT3ZnGmmr --- .../incidents/[id]/ai/triage-suggest/route.ts | 105 ++++++++++++++++++ components/incidents/triage-form.tsx | 61 ++++++++-- tests/api/incidents/triage-suggest.test.ts | 60 ++++++++++ 3 files changed, 219 insertions(+), 7 deletions(-) create mode 100644 app/api/incidents/[id]/ai/triage-suggest/route.ts create mode 100644 tests/api/incidents/triage-suggest.test.ts diff --git a/app/api/incidents/[id]/ai/triage-suggest/route.ts b/app/api/incidents/[id]/ai/triage-suggest/route.ts new file mode 100644 index 0000000..6b77856 --- /dev/null +++ b/app/api/incidents/[id]/ai/triage-suggest/route.ts @@ -0,0 +1,105 @@ +export const dynamic = 'force-dynamic' + +import { NextRequest, NextResponse } from 'next/server' +import { createClient } from '@/lib/supabase/server' +import { anthropic } from '@/lib/claude/client' + +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 || !['hse', 'admin'].includes(profile.role)) + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) + + const { data: incident } = await supabase + .from('incidents') + .select('id, incident_type, description, injury_involved, asset_involved, medical_status') + .eq('id', id) + .single() + if (!incident) return NextResponse.json({ error: 'Not found' }, { status: 404 }) + + const inc = incident as { + incident_type: string + description: string + injury_involved: boolean + asset_involved: boolean + medical_status: string | null + } + + const message = await anthropic.messages.create({ + model: 'claude-opus-4-8', + thinking: { type: 'adaptive' }, + max_tokens: 1024, + tools: [{ + name: 'suggest_triage', + description: 'Suggest severity rating and NADOPOD 2004 DOSH classification for a warehouse incident', + input_schema: { + type: 'object' as const, + properties: { + severity: { type: 'number', description: '1=minor, 2=low, 3=moderate, 4=serious, 5=critical/fatality' }, + is_fatality: { type: 'boolean' }, + is_serious_bodily_injury: { type: 'boolean', description: 'Fracture, amputation, blindness, serious burn, or similar' }, + is_dangerous_occurrence: { type: 'boolean', description: 'Structural collapse, explosion, fire, scaffold collapse, etc.' }, + is_occupational_disease: { type: 'boolean', description: 'Disease arising from workplace exposure' }, + rationale: { type: 'string', description: 'One-sentence rationale citing NADOPOD 2004 where applicable' }, + }, + required: [ + 'severity', 'is_fatality', 'is_serious_bodily_injury', + 'is_dangerous_occurrence', 'is_occupational_disease', 'rationale', + ], + }, + }], + tool_choice: { type: 'tool', name: 'suggest_triage' }, + messages: [{ + role: 'user', + content: `You are an HSE triage specialist for a Malaysian 3PL warehouse. Assess this incident under NADOPOD 2004. + +Incident type: ${inc.incident_type} +Description: ${inc.description} +Injury involved: ${inc.injury_involved ? 'yes' : 'no'} +Medical status: ${inc.medical_status ?? 'N/A'} +Asset/equipment involved: ${inc.asset_involved ? 'yes' : 'no'} + +Suggest severity (1–5) and tick the appropriate NADOPOD 2004 flags. Give a one-sentence rationale.`, + }], + }) + + const toolBlock = message.content.find(b => b.type === 'tool_use') + if (!toolBlock || toolBlock.type !== 'tool_use') + return NextResponse.json({ error: 'AI suggestion failed' }, { status: 500 }) + + const input = toolBlock.input as { + severity?: unknown + is_fatality?: unknown + is_serious_bodily_injury?: unknown + is_dangerous_occurrence?: unknown + is_occupational_disease?: unknown + rationale?: unknown + } + + if ( + typeof input.severity !== 'number' || + typeof input.is_fatality !== 'boolean' || + typeof input.is_serious_bodily_injury !== 'boolean' || + typeof input.is_dangerous_occurrence !== 'boolean' || + typeof input.is_occupational_disease !== 'boolean' || + typeof input.rationale !== 'string' + ) { + return NextResponse.json({ error: 'AI returned unexpected structure' }, { status: 500 }) + } + + await supabase.rpc('write_audit_log', { + p_table_name: 'incidents', + p_record_id: id, + p_action: 'ai_triage_suggest', + p_new_value: { suggestion: toolBlock.input, model: 'claude-opus-4-8' } as never, + }) + + return NextResponse.json(toolBlock.input) +} diff --git a/components/incidents/triage-form.tsx b/components/incidents/triage-form.tsx index cc3cfa1..23b0379 100644 --- a/components/incidents/triage-form.tsx +++ b/components/incidents/triage-form.tsx @@ -27,6 +27,8 @@ export function TriageForm({ incidentId, currentSeverity }: Props) { const [triageNotes, setTriageNotes] = useState('') const [saving, setSaving] = useState(false) const [error, setError] = useState(null) + const [aiLoading, setAiLoading] = useState(false) + const [aiRationale, setAiRationale] = useState(null) const dosh = computeDoshObligation({ is_fatality: isFatality, @@ -36,6 +38,33 @@ export function TriageForm({ incidentId, currentSeverity }: Props) { lost_days: null, }) + async function getAiSuggestion() { + setAiLoading(true) + setAiRationale(null) + try { + const res = await fetch(`/api/incidents/${incidentId}/ai/triage-suggest`, { method: 'POST' }) + if (!res.ok) return + const data = await res.json() as { + severity: number + is_fatality: boolean + is_serious_bodily_injury: boolean + is_dangerous_occurrence: boolean + is_occupational_disease: boolean + rationale: string + } + setSeverity(data.severity) + setIsFatality(data.is_fatality) + setIsSBI(data.is_serious_bodily_injury) + setIsDO(data.is_dangerous_occurrence) + setIsOD(data.is_occupational_disease) + setAiRationale(data.rationale) + } catch { + // Non-blocking — user can still triage manually + } finally { + setAiLoading(false) + } + } + async function handleSubmit(e: React.FormEvent) { e.preventDefault() setSaving(true) @@ -120,15 +149,33 @@ export function TriageForm({ incidentId, currentSeverity }: Props) { /> + {aiRationale && ( +
+

AI Suggestion Rationale

+

{aiRationale}

+

Fields pre-filled — review before submitting.

+
+ )} + {error &&

{error}

} - +
+ + +
) } diff --git a/tests/api/incidents/triage-suggest.test.ts b/tests/api/incidents/triage-suggest.test.ts new file mode 100644 index 0000000..1f61b52 --- /dev/null +++ b/tests/api/incidents/triage-suggest.test.ts @@ -0,0 +1,60 @@ +import { describe, it, expect, vi } from 'vitest' + +const mockIncident = { + id: 'inc-1', + incident_type: 'injury', + description: 'Worker slipped on wet floor in cold store, fractured wrist.', + injury_involved: true, + asset_involved: false, + medical_status: 'medical_treatment', +} + +vi.mock('@/lib/supabase/server', () => ({ + createClient: vi.fn().mockResolvedValue({ + auth: { + getUser: vi.fn().mockResolvedValue({ data: { user: { id: 'user-1' } }, error: null }), + }, + from: vi.fn().mockReturnValue({ + select: vi.fn().mockReturnThis(), + eq: vi.fn().mockReturnThis(), + single: vi.fn() + .mockResolvedValueOnce({ data: { role: 'hse' } }) // profile + .mockResolvedValueOnce({ data: mockIncident }), // incident + }), + rpc: vi.fn().mockResolvedValue({ error: null }), + }), +})) + +vi.mock('@/lib/claude/client', () => ({ + anthropic: { + messages: { + create: vi.fn().mockResolvedValue({ + content: [{ + type: 'tool_use', + name: 'suggest_triage', + input: { + severity: 3, + is_fatality: false, + is_serious_bodily_injury: true, + is_dangerous_occurrence: false, + is_occupational_disease: false, + rationale: 'Fracture constitutes serious bodily injury under NADOPOD 2004.', + }, + }], + }), + }, + }, +})) + +describe('POST /api/incidents/[id]/ai/triage-suggest', () => { + it('returns triage suggestion with severity and DOSH flags', async () => { + const { POST } = await import('@/app/api/incidents/[id]/ai/triage-suggest/route') + const req = new Request('http://localhost/api/incidents/inc-1/ai/triage-suggest', { method: 'POST' }) + const res = await POST(req as never, { params: Promise.resolve({ id: 'inc-1' }) }) + expect(res.status).toBe(200) + const body = await res.json() + expect(body.severity).toBe(3) + expect(body.is_serious_bodily_injury).toBe(true) + expect(body.rationale).toBeTruthy() + }) +})