feat: Phase 5 & 6 — usability, compliance hardening, analytics

Phase 5 (usability + compliance):
- In-app notification bell/badge: migration 016 adds read state + per-user
  RLS + create_in_app_notification SECURITY DEFINER RPC; /api/notifications;
  wired into incident creation, CAPA assign/verify, escalation cron
- Incident closure: new POST /api/incidents/[id]/close (requires verification
  status + all CAPAs verified); migration 017 locks closed incidents at DB
  level (update/delete triggers) with append-only incident_addenda + UI panel
- Server-side pagination on HSE/supervisor incident inboxes (.range, 25/page)
- Investigation form: alcohol/urine test result + witness statement refs
  (existing schema columns, now editable)
- Type-specific intake fields: migration 018 adds incidents.type_details
  JSONB; whitelist validation; environmental/asset/security/fire field
  groups in report form; EN/MS/ZH labels; offline queue support
- JKKP 8 annual register CSV export (/api/reports/jkkp8) + dashboard button
  + January statutory deadline banner
- Admin page: user invite (service-role client), role/site/active management,
  site + zone CRUD with QR report links — replaces Phase 0 stub
- Evidence gallery thumbnails via Supabase render transform with fallback

Phase 6 (analytics):
- 12-month stacked trend chart (leading/lagging/other) + top root causes
  (lib/dashboard/trends.ts pure helpers)
- AI rising-risk zones: /api/dashboard/ai/risk-flags aggregates 90-day
  zone stats, claude-opus-4-8 forced tool_use, panel on HSE + management
  dashboards, suggestion audit-logged

Also fixes 9 pre-existing missing /ims basePath prefixes in client fetches
and download links.

132 tests passing, tsc clean, next build clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CPf5Rc8QPx6V8KLEEgfKEQ
This commit is contained in:
2026-07-12 10:25:08 +08:00
co-authored by Claude Fable 5
parent 98c38c3716
commit 576557181a
51 changed files with 2394 additions and 38 deletions
+46 -3
View File
@@ -37,6 +37,8 @@ export function InvestigationForm({ incidentId, existingInvestigationId }: Props
)
const [findingsText, setFindingsText] = useState('')
const [rootCause, setRootCause] = useState('')
const [alcoholTest, setAlcoholTest] = useState('')
const [witnessRefs, setWitnessRefs] = useState<string[]>([''])
const [complete, setComplete] = useState(false)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
@@ -61,7 +63,7 @@ export function InvestigationForm({ incidentId, existingInvestigationId }: Props
async function getAiDraft() {
setAiDraftLoading(true)
try {
const res = await fetch(`/api/incidents/${incidentId}/ai/rca-draft`, { method: 'POST' })
const res = await fetch(`/ims/api/incidents/${incidentId}/ai/rca-draft`, { method: 'POST' })
if (!res.ok) return
const draft = await res.json() as {
five_why_steps: Array<{ why: string; answer: string }>
@@ -92,6 +94,8 @@ export function InvestigationForm({ incidentId, existingInvestigationId }: Props
method,
findings_text: findingsText || null,
root_cause_summary: rootCause || null,
alcohol_test_result: alcoholTest || null,
witness_statement_refs: witnessRefs.map(w => w.trim()).filter(Boolean),
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)
@@ -100,13 +104,13 @@ export function InvestigationForm({ incidentId, existingInvestigationId }: Props
let res: Response
if (existingInvestigationId) {
res = await fetch(`/api/incidents/${incidentId}/investigation`, {
res = await fetch(`/ims/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`, {
res = await fetch(`/ims/api/incidents/${incidentId}/investigation`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
@@ -207,6 +211,45 @@ export function InvestigationForm({ incidentId, existingInvestigationId }: Props
</div>
)}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Alcohol / Urine Test Result</label>
<select
value={alcoholTest}
onChange={e => setAlcoholTest(e.target.value)}
className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm"
>
<option value="">Not applicable / not conducted</option>
<option value="negative">Negative</option>
<option value="positive">Positive</option>
<option value="refused">Refused</option>
<option value="pending">Result pending</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Witness Statements</label>
<p className="text-xs text-gray-400 mb-2">
Reference each statement (witness name, document ref). Upload scans as investigation-stage evidence.
</p>
{witnessRefs.map((ref, i) => (
<input
key={i}
type="text"
value={ref}
onChange={e => setWitnessRefs(witnessRefs.map((w, j) => (j === i ? e.target.value : w)))}
placeholder="e.g. Ali bin Ahmad — statement dated 12/07/2026"
className="w-full rounded border border-gray-300 px-2 py-1.5 text-sm mb-1.5"
/>
))}
<button
type="button"
onClick={() => setWitnessRefs([...witnessRefs, ''])}
className="text-xs text-blue-600 hover:underline"
>
+ Add witness statement
</button>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Key Findings</label>
<textarea