Files
ims/components/incidents/offline-sync.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

74 lines
2.6 KiB
TypeScript

'use client'
import { useEffect, useState, useCallback, useRef } from 'react'
export function OfflineSync() {
const [pendingCount, setPendingCount] = useState(0)
const [syncing, setSyncing] = useState(false)
const syncingRef = useRef(false)
async function checkPending() {
const { getPendingCount } = await import('@/lib/offline/db')
setPendingCount(await getPendingCount())
}
const syncNow = useCallback(async () => {
if (syncingRef.current) return
syncingRef.current = true
setSyncing(true)
try {
const { getPendingReports, removePendingReport } = await import('@/lib/offline/db')
const reports = await getPendingReports()
for (const report of reports) {
const fd = new FormData()
fd.append('zone_token', report.zone_token)
fd.append('incident_type', report.incident_type)
fd.append('description', report.description)
fd.append('injury_involved', String(report.injury_involved))
fd.append('asset_involved', String(report.asset_involved))
if (report.medical_status) fd.append('medical_status', report.medical_status)
if (report.type_details) fd.append('type_details', JSON.stringify(report.type_details))
try {
const res = await fetch('/ims/api/incidents', { method: 'POST', body: fd })
if (res.ok && report.id != null) {
await removePendingReport(report.id)
}
} catch {
// Network still unavailable — will retry on next online event
}
}
} finally {
syncingRef.current = false
await checkPending()
setSyncing(false)
}
}, [])
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
checkPending()
const handleOnline = () => { syncNow() }
window.addEventListener('online', handleOnline)
return () => window.removeEventListener('online', handleOnline)
}, [syncNow])
if (pendingCount === 0) return null
return (
<div className="fixed bottom-4 left-4 right-4 bg-yellow-50 border border-yellow-300 rounded-lg p-3 flex items-center justify-between shadow-md z-50">
<span className="text-sm text-yellow-800 font-medium">
{pendingCount} report{pendingCount > 1 ? 's' : ''} saved offline
</span>
<button
onClick={syncNow}
disabled={syncing || !navigator.onLine}
className="text-xs bg-yellow-600 text-white px-3 py-1.5 rounded font-medium
hover:bg-yellow-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{syncing ? 'Syncing…' : 'Sync now'}
</button>
</div>
)
}