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
+70
View File
@@ -0,0 +1,70 @@
export interface MonthlyBucket {
month: string // YYYY-MM
label: string // e.g. "Jul"
total: number
leading: number // hazard + near_miss
lagging: number // injury
}
const LEADING_TYPES = ['hazard', 'near_miss']
export function bucketIncidentsByMonth(
incidents: Array<{ reported_at: string; incident_type: string }>,
months = 12,
now = new Date(),
): MonthlyBucket[] {
const buckets: MonthlyBucket[] = []
const index = new Map<string, MonthlyBucket>()
for (let i = months - 1; i >= 0; i--) {
const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - i, 1))
const month = `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`
const bucket: MonthlyBucket = {
month,
label: d.toLocaleString('en', { month: 'short', timeZone: 'UTC' }),
total: 0,
leading: 0,
lagging: 0,
}
buckets.push(bucket)
index.set(month, bucket)
}
for (const inc of incidents) {
const month = inc.reported_at.slice(0, 7)
const bucket = index.get(month)
if (!bucket) continue
bucket.total++
if (LEADING_TYPES.includes(inc.incident_type)) bucket.leading++
if (inc.incident_type === 'injury') bucket.lagging++
}
return buckets
}
export interface RootCauseCount {
cause: string
count: number
}
// Root causes are free text (investigations.root_cause_summary); group on a
// normalized form so trivially different phrasings still collapse together.
export function topRootCauses(
investigations: Array<{ root_cause_summary: string | null }>,
top = 5,
): RootCauseCount[] {
const counts = new Map<string, { cause: string; count: number }>()
for (const inv of investigations) {
const raw = (inv.root_cause_summary ?? '').trim()
if (!raw) continue
const key = raw.toLowerCase().replace(/\s+/g, ' ').replace(/[.。]$/, '')
const entry = counts.get(key)
if (entry) entry.count++
else counts.set(key, { cause: raw, count: 1 })
}
return [...counts.values()]
.sort((a, b) => b.count - a.count)
.slice(0, top)
}
+55
View File
@@ -11,6 +11,61 @@ export interface IncidentInput {
injury_involved: boolean
medical_status?: MedicalStatus
asset_involved: boolean
type_details?: Record<string, unknown>
}
// Whitelisted type-specific intake fields per incident type (PRD §3).
// 's' = free text, 'b' = boolean. Near miss / hazard / injury stay minimal by design.
export const TYPE_DETAIL_FIELDS: Partial<Record<IncidentType, Record<string, 's' | 'b'>>> = {
environmental: { substance: 's', estimated_volume: 's', containment_deployed: 'b' },
asset_damage: { equipment_id: 's', loto_applied: 'b' },
security: { persons_involved: 's', police_reported: 'b' },
fire: { alarm_raised: 'b', fire_brigade_called: 'b' },
}
export function validateTypeDetails(
incidentType: IncidentType,
details: Record<string, unknown> | undefined,
): { ok: boolean; errors: string[]; sanitized: Record<string, unknown> | null } {
if (details == null || Object.keys(details).length === 0) {
return { ok: true, errors: [], sanitized: null }
}
const allowed = TYPE_DETAIL_FIELDS[incidentType]
if (!allowed) {
return { ok: false, errors: [`type_details not allowed for incident_type ${incidentType}`], sanitized: null }
}
const errors: string[] = []
const sanitized: Record<string, unknown> = {}
for (const [key, value] of Object.entries(details)) {
const kind = allowed[key]
if (!kind) {
errors.push(`unknown type_details field: ${key}`)
continue
}
if (kind === 's') {
if (typeof value !== 'string') {
errors.push(`${key} must be a string`)
continue
}
const trimmed = value.trim()
if (trimmed) sanitized[key] = trimmed.slice(0, 500)
} else {
if (typeof value !== 'boolean') {
errors.push(`${key} must be a boolean`)
continue
}
sanitized[key] = value
}
}
return {
ok: errors.length === 0,
errors,
sanitized: Object.keys(sanitized).length > 0 ? sanitized : null,
}
}
export function validateIncidentInput(input: IncidentInput): { ok: boolean; errors: string[] } {
+13 -1
View File
@@ -1,6 +1,7 @@
import { Resend } from 'resend'
import type { SupabaseClient } from '@supabase/supabase-js'
import { sendWhatsAppMessage } from '@/lib/notifications/whatsapp'
import { createInAppNotifications } from '@/lib/notifications/in-app'
import { getApiKey } from '@/lib/settings'
export type EscalationThreshold = 'warning_3d' | 'due_today' | 'overdue_3d' | 'overdue_7d'
@@ -32,7 +33,7 @@ export async function escalateOverdueCapa(
const { data: capas } = await supabase
.from('capa_actions')
.select(`
id, description, due_date, incident_id,
id, description, due_date, incident_id, owner_user_id,
incidents (reference_no, site_id),
owner:users!owner_user_id (email, name, phone)
`)
@@ -121,6 +122,17 @@ export async function escalateOverdueCapa(
status: threshold,
})
const ownerUserId = (capa as { owner_user_id: string | null }).owner_user_id
if (ownerUserId) {
await createInAppNotifications(supabase, [{
userId: ownerUserId,
title: `${THRESHOLD_SUBJECT[threshold].replace('[IMS] ', '')}${incidentRef}`,
link: `/hse/capa/${capa.id}`,
incidentId: capa.incident_id as string,
capaId: capa.id as string,
}])
}
notified++
}
+42
View File
@@ -0,0 +1,42 @@
import type { SupabaseClient } from '@supabase/supabase-js'
export interface InAppNotification {
userId: string
title: string
link?: string
incidentId?: string
capaId?: string
}
// Inserts go through the create_in_app_notification SECURITY DEFINER RPC:
// notifications_log INSERT is RLS-restricted to elevated roles, but reporters
// must still be able to trigger alerts to supervisors/HSE.
export async function createInAppNotifications(
supabase: SupabaseClient,
notifications: InAppNotification[],
): Promise<{ created: number }> {
const seen = new Set<string>()
let created = 0
for (const n of notifications) {
if (!n.userId || !n.title) continue
const key = `${n.userId}|${n.title}|${n.incidentId ?? ''}|${n.capaId ?? ''}`
if (seen.has(key)) continue
seen.add(key)
const { error } = await supabase.rpc('create_in_app_notification', {
p_recipient: n.userId,
p_title: n.title,
p_link: n.link ?? null,
p_incident_id: n.incidentId ?? null,
p_capa_id: n.capaId ?? null,
})
if (error) {
console.error('in-app notification error:', error)
continue
}
created++
}
return { created }
}
+1
View File
@@ -8,6 +8,7 @@ export interface PendingReport {
injury_involved: boolean
asset_involved: boolean
medical_status?: string
type_details?: Record<string, string | boolean>
created_at: string
}
+96
View File
@@ -0,0 +1,96 @@
import { computeDoshObligation } from '@/lib/incidents/dosh'
export interface Jkkp8Incident {
reference_no: string | null
incident_type: string
description: string
reported_at: string
medical_status: string | null
lost_days: number | null
is_fatality: boolean
is_serious_bodily_injury: boolean
is_dangerous_occurrence: boolean
is_occupational_disease: boolean
sites: { name: string } | null
zones: { name: string } | null
reporter: { name: string } | null
dosh_reports: Array<{ form_type: string; status: string; submitted_at: string | null }>
}
export interface Jkkp8Row {
reference: string
date: string
site: string
zone: string
incident_type: string
reported_by: string
description: string
medical_status: string
lost_days: string
obligation: string
filing_status: string
}
// JKKP 8 annual register: every incident with any NADOPOD obligation for the
// year (PRD §9 — "Any of the above → also logged in the JKKP 8 annual register").
export function buildJkkp8Rows(incidents: Jkkp8Incident[]): Jkkp8Row[] {
const rows: Jkkp8Row[] = []
for (const inc of incidents) {
const obligation = computeDoshObligation(inc)
const reportable =
obligation.requires_jkkp6 || obligation.requires_jkkp7 || obligation.requires_jkkp8
if (!reportable) continue
const filings = inc.dosh_reports ?? []
const filingStatus =
filings.length === 0
? 'pending'
: filings
.map(f => `${f.form_type.toUpperCase()}: ${f.status}${f.submitted_at ? ` (${f.submitted_at.split('T')[0]})` : ''}`)
.join('; ')
rows.push({
reference: inc.reference_no ?? '',
date: inc.reported_at.split('T')[0],
site: inc.sites?.name ?? '',
zone: inc.zones?.name ?? '',
incident_type: inc.incident_type,
reported_by: inc.reporter?.name ?? '',
description: inc.description,
medical_status: inc.medical_status ?? '',
lost_days: String(inc.lost_days ?? ''),
obligation: obligation.reasons.join('; '),
filing_status: filingStatus,
})
}
return rows
}
export const JKKP8_HEADERS = [
'Reference', 'Date', 'Site', 'Zone', 'Incident Type', 'Reported By',
'Description', 'Medical Status', 'Lost Days', 'NADOPOD Obligation', 'DOSH Filing Status',
]
export function escapeCsv(value: string | number | null | undefined): string {
if (value === null || value === undefined) return ''
const str = String(value)
if (str.includes(',') || str.includes('"') || str.includes('\n')) {
return `"${str.replace(/"/g, '""')}"`
}
return str
}
export function jkkp8Csv(rows: Jkkp8Row[]): string {
const lines = [JKKP8_HEADERS.map(escapeCsv).join(',')]
for (const r of rows) {
lines.push(
[
r.reference, r.date, r.site, r.zone, r.incident_type, r.reported_by,
r.description, r.medical_status, r.lost_days, r.obligation, r.filing_status,
].map(escapeCsv).join(','),
)
}
return lines.join('\r\n')
}
+14
View File
@@ -0,0 +1,14 @@
import { createClient as createSupabaseClient, type SupabaseClient } from '@supabase/supabase-js'
// Service-role client — bypasses RLS. Server-side only, and only for operations
// the anon client cannot perform (auth admin user invites). Never import in client code.
export function createAdminClient(): SupabaseClient {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL
const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!url || !serviceRoleKey) {
throw new Error('SUPABASE_SERVICE_ROLE_KEY not configured')
}
return createSupabaseClient(url, serviceRoleKey, {
auth: { autoRefreshToken: false, persistSession: false },
})
}