Files
ims/app/(protected)/management/page.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

151 lines
6.7 KiB
TypeScript

export const dynamic = 'force-dynamic'
import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import { StatCard } from '@/components/dashboard/stat-card'
import { RiskFlagsPanel } from '@/components/dashboard/risk-flags-panel'
export default async function ManagementPage() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) redirect('/login')
const { data: profile } = await supabase.from('users').select('role').eq('id', user.id).single()
if (!profile || !['management', 'admin'].includes(profile.role)) redirect('/')
const now = new Date()
const thisMonthStart = new Date(now.getFullYear(), now.getMonth(), 1).toISOString()
const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1).toISOString()
const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000).toISOString()
const [
{ data: allIncidents },
{ data: thisMonthIncidents },
{ data: lastMonthIncidents },
{ data: recentIncidents },
{ data: overdueCapas },
] = await Promise.all([
supabase.from('incidents').select('id, severity, status, incident_type, medical_status, sites (name)'),
supabase.from('incidents').select('id').gte('reported_at', thisMonthStart),
supabase.from('incidents').select('id').gte('reported_at', lastMonthStart).lt('reported_at', thisMonthStart),
supabase.from('incidents').select('incident_type').gte('reported_at', thirtyDaysAgo),
supabase.from('capa_actions').select('id').eq('status', 'overdue'),
])
const rows = allIncidents ?? []
const totalThisMonth = thisMonthIncidents?.length ?? 0
const totalLastMonth = lastMonthIncidents?.length ?? 0
const monthDelta = totalThisMonth - totalLastMonth
const ltiCount = rows.filter(r => r.medical_status === 'lti').length
const overdueCount = overdueCapas?.length ?? 0
// Severity distribution
const severityDist: Record<number, number> = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 }
for (const r of rows) {
if (r.severity && r.severity >= 1 && r.severity <= 5) {
severityDist[r.severity] = (severityDist[r.severity] ?? 0) + 1
}
}
const severityMax = Math.max(...Object.values(severityDist), 1)
// Leading vs lagging (last 30 days)
const recent = recentIncidents ?? []
const leadingCount = recent.filter(r => ['hazard', 'near_miss'].includes(r.incident_type)).length
const laggingCount = recent.filter(r => r.incident_type === 'injury').length
// Site comparison
const siteMap: Record<string, number> = {}
for (const r of rows) {
const name = (r.sites as unknown as { name: string } | null)?.name ?? 'Unknown'
siteMap[name] = (siteMap[name] ?? 0) + 1
}
const by_site = Object.entries(siteMap).map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count)
const SEVERITY_LABELS: Record<number, string> = { 1: 'Minor', 2: 'Low', 3: 'Moderate', 4: 'Serious', 5: 'Critical' }
const SEVERITY_COLORS: Record<number, string> = {
1: 'bg-green-400', 2: 'bg-yellow-400', 3: 'bg-orange-400', 4: 'bg-red-500', 5: 'bg-red-700',
}
return (
<main className="max-w-4xl mx-auto px-4 py-6">
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-bold text-gray-900">Management Dashboard</h1>
<a
href="/ims/api/dashboard/export?role=management"
className="text-sm text-gray-500 hover:text-gray-700 border border-gray-200 rounded-lg px-3 py-1.5"
>
Export CSV
</a>
</div>
<RiskFlagsPanel />
{/* Summary stats */}
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4 mb-6">
<StatCard
label="This Month"
value={totalThisMonth}
sub={monthDelta >= 0 ? `+${monthDelta} vs last month` : `${monthDelta} vs last month`}
accent={monthDelta > 0 ? 'yellow' : 'green'}
/>
<StatCard label="LTI Count" value={ltiCount} accent={ltiCount > 0 ? 'red' : 'green'} sub="lost-time injuries" />
<StatCard label="CAPA Overdue" value={overdueCount} accent={overdueCount > 0 ? 'red' : 'green'} sub="past due date" />
<StatCard label="Total (All Time)" value={rows.length} />
</div>
{/* Leading vs lagging */}
<div className="bg-white rounded-xl shadow-sm p-5 mb-4">
<h2 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-1">Leading vs Lagging Last 30 Days</h2>
<p className="text-xs text-gray-400 mb-4">Leading: hazard + near-miss · Lagging: injuries</p>
<div className="flex gap-6">
<div className="flex-1 text-center bg-blue-50 rounded-lg p-4">
<p className="text-3xl font-bold text-blue-600">{leadingCount}</p>
<p className="text-xs text-blue-700 mt-1">Leading (Hazards + Near Misses)</p>
</div>
<div className="flex-1 text-center bg-red-50 rounded-lg p-4">
<p className="text-3xl font-bold text-red-600">{laggingCount}</p>
<p className="text-xs text-red-700 mt-1">Lagging (Injuries)</p>
</div>
</div>
</div>
{/* Severity distribution */}
<div className="bg-white rounded-xl shadow-sm p-5 mb-4">
<h2 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-4">Severity Distribution (All Time)</h2>
<div className="space-y-2">
{([5, 4, 3, 2, 1] as const).map(sev => (
<div key={sev} className="flex items-center gap-3">
<span className="text-sm text-gray-600 w-24 shrink-0">{SEVERITY_LABELS[sev]}</span>
<div className="flex-1 bg-gray-100 rounded-full h-3">
<div
className={`h-3 rounded-full ${SEVERITY_COLORS[sev]}`}
style={{ width: severityMax > 0 ? `${(severityDist[sev] / severityMax) * 100}%` : '0%' }}
/>
</div>
<span className="text-sm font-semibold text-gray-900 w-6 text-right">{severityDist[sev]}</span>
</div>
))}
</div>
</div>
{/* Site comparison */}
<div className="bg-white rounded-xl shadow-sm p-5">
<h2 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-4">Incidents by Site</h2>
{by_site.length === 0 ? (
<p className="text-sm text-gray-400">No data</p>
) : (
<div className="space-y-2">
{by_site.map(({ name, count }) => (
<div key={name} className="flex items-center justify-between py-1 border-b border-gray-50 last:border-0">
<span className="text-sm text-gray-700">{name}</span>
<span className="text-sm font-semibold text-gray-900">{count}</span>
</div>
))}
</div>
)}
</div>
</main>
)
}