feat: AI triage suggestion — severity + DOSH flags pre-fill
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FFDuBhMKvoWjrWT3ZnGmmr
This commit is contained in:
@@ -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)
|
||||||
|
}
|
||||||
@@ -27,6 +27,8 @@ export function TriageForm({ incidentId, currentSeverity }: Props) {
|
|||||||
const [triageNotes, setTriageNotes] = useState('')
|
const [triageNotes, setTriageNotes] = 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)
|
||||||
|
const [aiLoading, setAiLoading] = useState(false)
|
||||||
|
const [aiRationale, setAiRationale] = useState<string | null>(null)
|
||||||
|
|
||||||
const dosh = computeDoshObligation({
|
const dosh = computeDoshObligation({
|
||||||
is_fatality: isFatality,
|
is_fatality: isFatality,
|
||||||
@@ -36,6 +38,33 @@ export function TriageForm({ incidentId, currentSeverity }: Props) {
|
|||||||
lost_days: null,
|
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) {
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
setSaving(true)
|
setSaving(true)
|
||||||
@@ -120,15 +149,33 @@ export function TriageForm({ incidentId, currentSeverity }: Props) {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{aiRationale && (
|
||||||
|
<div className="rounded-lg bg-purple-50 border border-purple-200 p-3">
|
||||||
|
<p className="text-xs font-semibold text-purple-700 mb-1">AI Suggestion Rationale</p>
|
||||||
|
<p className="text-xs text-purple-600">{aiRationale}</p>
|
||||||
|
<p className="text-xs text-purple-400 mt-1">Fields pre-filled — review before submitting.</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{error && <p className="text-sm text-red-600">{error}</p>}
|
{error && <p className="text-sm text-red-600">{error}</p>}
|
||||||
|
|
||||||
<button
|
<div className="flex gap-3">
|
||||||
type="submit"
|
<button
|
||||||
disabled={saving}
|
type="button"
|
||||||
className="w-full bg-blue-600 text-white rounded-lg py-2 text-sm font-semibold disabled:opacity-50"
|
onClick={getAiSuggestion}
|
||||||
>
|
disabled={aiLoading || saving}
|
||||||
{saving ? 'Saving…' : 'Complete Triage'}
|
className="flex-1 bg-purple-50 text-purple-700 border border-purple-300 rounded-lg py-2 text-sm font-semibold disabled:opacity-50 hover:bg-purple-100"
|
||||||
</button>
|
>
|
||||||
|
{aiLoading ? 'Getting suggestion…' : 'Get AI Suggestion'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={saving}
|
||||||
|
className="flex-1 bg-blue-600 text-white rounded-lg py-2 text-sm font-semibold disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{saving ? 'Saving…' : 'Complete Triage'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</form>
|
</form>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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()
|
||||||
|
})
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user