Files
ims/components/incidents/closure-panel.tsx
T
adminandClaude Fable 5 576557181a 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
2026-07-12 10:25:08 +08:00

133 lines
4.2 KiB
TypeScript

'use client'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
type Addendum = {
id: string
body: string
created_at: string
author: { name: string } | null
}
interface Props {
incidentId: string
status: string
canClose: boolean
canAddAddenda: boolean
}
export function ClosurePanel({ incidentId, status, canClose, canAddAddenda }: Props) {
const router = useRouter()
const [addenda, setAddenda] = useState<Addendum[]>([])
const [draft, setDraft] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const isClosed = status === 'closed'
useEffect(() => {
if (!isClosed) return
fetch(`/ims/api/incidents/${incidentId}/addenda`)
.then(r => (r.ok ? r.json() : Promise.reject()))
.then((data: Addendum[]) => setAddenda(Array.isArray(data) ? data : []))
.catch(() => {})
}, [incidentId, isClosed])
const closeIncident = async () => {
if (!confirm('Close this incident? The record will be locked — only addenda can be added afterwards.')) return
setBusy(true)
setError(null)
const res = await fetch(`/ims/api/incidents/${incidentId}/close`, { method: 'POST' })
setBusy(false)
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setError(data.error ?? 'Failed to close incident')
return
}
router.refresh()
}
const addAddendum = async () => {
const text = draft.trim()
if (!text) return
setBusy(true)
setError(null)
const res = await fetch(`/ims/api/incidents/${incidentId}/addenda`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: text }),
})
setBusy(false)
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setError(data.error ?? 'Failed to add addendum')
return
}
setDraft('')
const list = await fetch(`/ims/api/incidents/${incidentId}/addenda`).then(r => r.json()).catch(() => [])
setAddenda(Array.isArray(list) ? list : [])
}
if (!isClosed && !canClose) return null
if (!isClosed) {
return (
<div className="mt-6">
{status === 'verification' ? (
<button
onClick={closeIncident}
disabled={busy}
className="bg-green-700 text-white rounded-lg px-4 py-2 text-sm font-semibold hover:bg-green-800 disabled:opacity-50"
>
{busy ? 'Closing…' : 'Close Incident'}
</button>
) : null}
{error && <p className="text-sm text-red-600 mt-2">{error}</p>}
</div>
)
}
return (
<div className="mt-6 bg-white rounded-xl shadow-sm p-5">
<h2 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-1">Addenda</h2>
<p className="text-xs text-gray-400 mb-3">
This incident is closed and locked. New information is recorded as addenda.
</p>
{addenda.length === 0 ? (
<p className="text-sm text-gray-400">No addenda.</p>
) : (
<ul className="space-y-3">
{addenda.map(a => (
<li key={a.id} className="border border-gray-100 rounded-lg p-3">
<p className="text-sm text-gray-800 whitespace-pre-wrap">{a.body}</p>
<p className="text-xs text-gray-400 mt-1">
{a.author?.name ?? 'Unknown'} · {new Date(a.created_at).toLocaleString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })}
</p>
</li>
))}
</ul>
)}
{canAddAddenda && (
<div className="mt-4">
<textarea
value={draft}
onChange={e => setDraft(e.target.value)}
rows={3}
placeholder="Add an addendum…"
className="w-full border border-gray-200 rounded-lg p-2 text-sm"
/>
<button
onClick={addAddendum}
disabled={busy || !draft.trim()}
className="mt-2 bg-gray-800 text-white rounded-lg px-4 py-2 text-sm font-semibold hover:bg-gray-900 disabled:opacity-50"
>
{busy ? 'Saving…' : 'Add Addendum'}
</button>
{error && <p className="text-sm text-red-600 mt-2">{error}</p>}
</div>
)}
</div>
)
}