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
+56
View File
@@ -0,0 +1,56 @@
import { describe, it, expect } from 'vitest'
import { bucketIncidentsByMonth, topRootCauses } from '@/lib/dashboard/trends'
describe('bucketIncidentsByMonth', () => {
const now = new Date('2026-07-15T12:00:00Z')
it('returns one bucket per month, oldest first', () => {
const buckets = bucketIncidentsByMonth([], 3, now)
expect(buckets.map(b => b.month)).toEqual(['2026-05', '2026-06', '2026-07'])
})
it('counts leading and lagging types into the right month', () => {
const buckets = bucketIncidentsByMonth(
[
{ reported_at: '2026-07-01T08:00:00Z', incident_type: 'near_miss' },
{ reported_at: '2026-07-02T08:00:00Z', incident_type: 'hazard' },
{ reported_at: '2026-07-03T08:00:00Z', incident_type: 'injury' },
{ reported_at: '2026-06-03T08:00:00Z', incident_type: 'fire' },
],
3,
now,
)
const july = buckets.find(b => b.month === '2026-07')!
expect(july).toMatchObject({ total: 3, leading: 2, lagging: 1 })
expect(buckets.find(b => b.month === '2026-06')).toMatchObject({ total: 1, leading: 0, lagging: 0 })
})
it('ignores incidents outside the window', () => {
const buckets = bucketIncidentsByMonth(
[{ reported_at: '2025-01-01T08:00:00Z', incident_type: 'injury' }],
3,
now,
)
expect(buckets.every(b => b.total === 0)).toBe(true)
})
})
describe('topRootCauses', () => {
it('groups normalized duplicates and sorts by count', () => {
const result = topRootCauses([
{ root_cause_summary: 'Inadequate forklift training.' },
{ root_cause_summary: 'inadequate forklift training' },
{ root_cause_summary: 'Blocked walkway' },
{ root_cause_summary: null },
{ root_cause_summary: '' },
])
expect(result).toHaveLength(2)
expect(result[0]).toMatchObject({ count: 2 })
expect(result[0].cause.toLowerCase()).toContain('forklift')
})
it('limits to top N', () => {
const invs = ['a', 'b', 'c', 'd', 'e', 'f'].map(c => ({ root_cause_summary: c }))
expect(topRootCauses(invs, 5)).toHaveLength(5)
})
})
+40 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { validateIncidentInput, type IncidentInput } from '@/lib/incidents/validate'
import { validateIncidentInput, validateTypeDetails, type IncidentInput } from '@/lib/incidents/validate'
const valid: IncidentInput = {
zone_token: 'scw1-dock-a-qr-2026',
@@ -43,3 +43,42 @@ describe('validateIncidentInput', () => {
expect(result.errors).toContain('incident_type is invalid')
})
})
describe('validateTypeDetails', () => {
it('accepts valid environmental fields and trims strings', () => {
const r = validateTypeDetails('environmental', {
substance: ' diesel ',
containment_deployed: true,
})
expect(r.ok).toBe(true)
expect(r.sanitized).toEqual({ substance: 'diesel', containment_deployed: true })
})
it('returns null sanitized when details empty or undefined', () => {
expect(validateTypeDetails('fire', undefined).sanitized).toBeNull()
expect(validateTypeDetails('fire', {}).sanitized).toBeNull()
})
it('rejects unknown fields', () => {
const r = validateTypeDetails('asset_damage', { equipment_id: 'FLT-3', bogus: 'x' })
expect(r.ok).toBe(false)
expect(r.errors[0]).toContain('bogus')
})
it('rejects wrong value types', () => {
const r = validateTypeDetails('security', { police_reported: 'yes' })
expect(r.ok).toBe(false)
expect(r.errors[0]).toContain('boolean')
})
it('rejects details for types without extra fields', () => {
const r = validateTypeDetails('near_miss', { substance: 'oil' })
expect(r.ok).toBe(false)
})
it('drops empty strings from sanitized output', () => {
const r = validateTypeDetails('asset_damage', { equipment_id: ' ', loto_applied: false })
expect(r.ok).toBe(true)
expect(r.sanitized).toEqual({ loto_applied: false })
})
})
+60
View File
@@ -0,0 +1,60 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createInAppNotifications } from '@/lib/notifications/in-app'
import type { SupabaseClient } from '@supabase/supabase-js'
function makeSupabaseMock(rpcResult: { error: unknown } = { error: null }) {
return {
rpc: vi.fn().mockResolvedValue(rpcResult),
} as unknown as SupabaseClient
}
describe('createInAppNotifications', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('calls create_in_app_notification RPC once per recipient', async () => {
const supabase = makeSupabaseMock()
const { created } = await createInAppNotifications(supabase, [
{ userId: 'u1', title: 'New incident', link: '/hse/incidents/i1', incidentId: 'i1' },
{ userId: 'u2', title: 'New incident', link: '/hse/incidents/i1', incidentId: 'i1' },
])
expect(created).toBe(2)
expect(supabase.rpc).toHaveBeenCalledTimes(2)
expect(supabase.rpc).toHaveBeenCalledWith('create_in_app_notification', {
p_recipient: 'u1',
p_title: 'New incident',
p_link: '/hse/incidents/i1',
p_incident_id: 'i1',
p_capa_id: null,
})
})
it('skips entries missing userId or title', async () => {
const supabase = makeSupabaseMock()
const { created } = await createInAppNotifications(supabase, [
{ userId: '', title: 'x' },
{ userId: 'u1', title: '' },
])
expect(created).toBe(0)
expect(supabase.rpc).not.toHaveBeenCalled()
})
it('counts only successful inserts when RPC errors', async () => {
const supabase = makeSupabaseMock({ error: { message: 'boom' } })
const { created } = await createInAppNotifications(supabase, [
{ userId: 'u1', title: 'x' },
])
expect(created).toBe(0)
})
it('deduplicates recipients for the same notification', async () => {
const supabase = makeSupabaseMock()
const { created } = await createInAppNotifications(supabase, [
{ userId: 'u1', title: 'same', incidentId: 'i1' },
{ userId: 'u1', title: 'same', incidentId: 'i1' },
])
expect(created).toBe(1)
expect(supabase.rpc).toHaveBeenCalledTimes(1)
})
})
+68
View File
@@ -0,0 +1,68 @@
import { describe, it, expect } from 'vitest'
import { buildJkkp8Rows, jkkp8Csv, type Jkkp8Incident } from '@/lib/reports/jkkp8'
function makeIncident(overrides: Partial<Jkkp8Incident> = {}): Jkkp8Incident {
return {
reference_no: 'SETIA-202607-0001',
incident_type: 'injury',
description: 'Fell from ladder',
reported_at: '2026-07-01T08:00:00Z',
medical_status: 'lti',
lost_days: 5,
is_fatality: false,
is_serious_bodily_injury: false,
is_dangerous_occurrence: false,
is_occupational_disease: false,
sites: { name: 'Setia Alam' },
zones: { name: 'Dock 3' },
reporter: { name: 'Ali' },
dosh_reports: [],
...overrides,
}
}
describe('buildJkkp8Rows', () => {
it('includes incidents with lost_days >= 4', () => {
const rows = buildJkkp8Rows([makeIncident()])
expect(rows).toHaveLength(1)
expect(rows[0].obligation).toContain('Lost-time injury')
expect(rows[0].filing_status).toBe('pending')
})
it('excludes non-reportable incidents', () => {
const rows = buildJkkp8Rows([
makeIncident({ lost_days: 1, medical_status: 'first_aid' }),
])
expect(rows).toHaveLength(0)
})
it('includes occupational disease (JKKP 7/8 path)', () => {
const rows = buildJkkp8Rows([
makeIncident({ lost_days: 0, is_occupational_disease: true }),
])
expect(rows).toHaveLength(1)
expect(rows[0].obligation).toContain('Occupational disease')
})
it('summarises dosh filing status when reports exist', () => {
const rows = buildJkkp8Rows([
makeIncident({
dosh_reports: [
{ form_type: 'jkkp6', status: 'submitted', submitted_at: '2026-07-03T10:00:00Z' },
],
}),
])
expect(rows[0].filing_status).toBe('JKKP6: submitted (2026-07-03)')
})
})
describe('jkkp8Csv', () => {
it('escapes commas and quotes in descriptions', () => {
const rows = buildJkkp8Rows([
makeIncident({ description: 'Slip, near "dock" area' }),
])
const csv = jkkp8Csv(rows)
expect(csv).toContain('"Slip, near ""dock"" area"')
expect(csv.split('\r\n')).toHaveLength(2)
})
})