feat: dashboard — leading/lagging, zone heatmap, CAPA on-time rate, DOSH filing status
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FFDuBhMKvoWjrWT3ZnGmmr
This commit is contained in:
@@ -17,10 +17,40 @@ const TYPE_LABELS: Record<string, string> = {
|
||||
export default async function HseDashboardPage() {
|
||||
const supabase = await createClient()
|
||||
|
||||
const { data: incidents } = await supabase
|
||||
.from('incidents')
|
||||
.select('id, status, incident_type, sites (name)')
|
||||
const now = new Date()
|
||||
const thirtyDaysAgo = new Date(now)
|
||||
thirtyDaysAgo.setDate(now.getDate() - 30)
|
||||
const ninetyDaysAgo = new Date(now)
|
||||
ninetyDaysAgo.setDate(now.getDate() - 90)
|
||||
|
||||
const [
|
||||
{ data: incidents },
|
||||
{ data: recentIncidents },
|
||||
{ data: zoneIncidents },
|
||||
{ data: completedCapas },
|
||||
{ data: doshPendingRows },
|
||||
] = await Promise.all([
|
||||
supabase.from('incidents').select('id, status, incident_type, sites (name)'),
|
||||
supabase
|
||||
.from('incidents')
|
||||
.select('incident_type')
|
||||
.gte('reported_at', thirtyDaysAgo.toISOString()),
|
||||
supabase
|
||||
.from('incidents')
|
||||
.select('zones (name)')
|
||||
.gte('reported_at', ninetyDaysAgo.toISOString())
|
||||
.not('zone_id', 'is', null),
|
||||
supabase
|
||||
.from('capa_actions')
|
||||
.select('due_date, completed_at, verified_at')
|
||||
.not('completed_at', 'is', null),
|
||||
supabase
|
||||
.from('dosh_reports')
|
||||
.select('id')
|
||||
.eq('status', 'pending'),
|
||||
])
|
||||
|
||||
// --- Existing metrics ---
|
||||
const rows = incidents ?? []
|
||||
const total = rows.length
|
||||
const closed = rows.filter(r => r.status === 'closed').length
|
||||
@@ -36,9 +66,45 @@ export default async function HseDashboardPage() {
|
||||
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 }))
|
||||
const by_site = Object.entries(siteMap)
|
||||
.map(([name, count]) => ({ name, count }))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
|
||||
// --- Leading / 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
|
||||
|
||||
// --- Zone heatmap (last 90 days) ---
|
||||
const zoneMap: Record<string, number> = {}
|
||||
for (const r of zoneIncidents ?? []) {
|
||||
const name = (r.zones as unknown as { name: string } | null)?.name ?? 'Unknown'
|
||||
zoneMap[name] = (zoneMap[name] ?? 0) + 1
|
||||
}
|
||||
const by_zone = Object.entries(zoneMap)
|
||||
.map(([name, count]) => ({ name, count }))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, 10)
|
||||
const zoneMax = by_zone[0]?.count ?? 1
|
||||
|
||||
// --- CAPA on-time rate ---
|
||||
const capas = completedCapas ?? []
|
||||
const onTime = capas.filter(c => {
|
||||
const due = new Date(c.due_date)
|
||||
const done = c.verified_at
|
||||
? new Date(c.verified_at as string)
|
||||
: c.completed_at
|
||||
? new Date(c.completed_at as string)
|
||||
: null
|
||||
return done !== null && done <= due
|
||||
})
|
||||
const capaOnTimeRate = capas.length > 0
|
||||
? Math.round((onTime.length / capas.length) * 100)
|
||||
: null
|
||||
|
||||
// --- DOSH pending filings ---
|
||||
const doshPendingCount = doshPendingRows?.length ?? 0
|
||||
|
||||
return (
|
||||
<main className="max-w-4xl mx-auto px-4 py-6">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
@@ -48,12 +114,72 @@ export default async function HseDashboardPage() {
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 mb-8">
|
||||
{/* Summary stats */}
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4 mb-6">
|
||||
<StatCard label="Total Incidents" value={total} />
|
||||
<StatCard label="Open" value={open} accent="yellow" sub="awaiting action" />
|
||||
<StatCard label="Closed" value={closed} accent="green" sub="resolved" />
|
||||
<StatCard
|
||||
label="DOSH Pending"
|
||||
value={doshPendingCount}
|
||||
accent={doshPendingCount > 0 ? 'yellow' : 'green'}
|
||||
sub="filings outstanding"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Leading vs lagging — last 30 days */}
|
||||
<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 reports (predict risk) · Lagging: injuries (past harm)
|
||||
</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>
|
||||
{capaOnTimeRate !== null && (
|
||||
<div className="flex-1 text-center bg-green-50 rounded-lg p-4">
|
||||
<p className="text-3xl font-bold text-green-600">{capaOnTimeRate}%</p>
|
||||
<p className="text-xs text-green-700 mt-1">CAPA On-Time Rate</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Zone heatmap — last 90 days */}
|
||||
{by_zone.length > 0 && (
|
||||
<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">
|
||||
Zone Incident Heatmap — Last 90 Days
|
||||
</h2>
|
||||
<div className="space-y-2">
|
||||
{by_zone.map(({ name, count }) => (
|
||||
<div key={name} className="flex items-center gap-3">
|
||||
<span className="text-sm text-gray-600 w-36 shrink-0 truncate">{name}</span>
|
||||
<div className="flex-1 bg-gray-100 rounded-full h-3">
|
||||
<div
|
||||
className="h-3 rounded-full"
|
||||
style={{
|
||||
width: `${(count / zoneMax) * 100}%`,
|
||||
backgroundColor: `hsl(${Math.round((1 - count / zoneMax) * 120)}, 70%, 50%)`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-sm font-semibold text-gray-900 w-6 text-right">{count}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Incident type breakdown */}
|
||||
<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">By Incident Type</h2>
|
||||
<div className="space-y-2">
|
||||
@@ -75,6 +201,7 @@ export default async function HseDashboardPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* By site */}
|
||||
<div className="bg-white rounded-xl shadow-sm p-5">
|
||||
<h2 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-4">By Site</h2>
|
||||
<div className="space-y-2">
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
|
||||
// Pure helpers extracted (conceptually) from dashboard logic — tested here as standalone functions
|
||||
|
||||
function computeCapaOnTimeRate(
|
||||
capas: Array<{ due_date: string; completed_at: string | null; verified_at: string | null }>
|
||||
): number | null {
|
||||
if (capas.length === 0) return null
|
||||
const onTime = capas.filter(c => {
|
||||
const due = new Date(c.due_date)
|
||||
const done = c.verified_at
|
||||
? new Date(c.verified_at)
|
||||
: c.completed_at
|
||||
? new Date(c.completed_at)
|
||||
: null
|
||||
return done !== null && done <= due
|
||||
})
|
||||
return Math.round((onTime.length / capas.length) * 100)
|
||||
}
|
||||
|
||||
function classifyIndicators(incidents: Array<{ incident_type: string }>) {
|
||||
const leading = incidents.filter(i => ['hazard', 'near_miss'].includes(i.incident_type)).length
|
||||
const lagging = incidents.filter(i => i.incident_type === 'injury').length
|
||||
return { leading, lagging }
|
||||
}
|
||||
|
||||
describe('CAPA on-time rate', () => {
|
||||
it('returns null for empty list', () => {
|
||||
expect(computeCapaOnTimeRate([])).toBeNull()
|
||||
})
|
||||
|
||||
it('returns 100% when all CAPAs completed on time', () => {
|
||||
const capas = [
|
||||
{ due_date: '2026-07-10', completed_at: '2026-07-09', verified_at: null },
|
||||
{ due_date: '2026-07-10', completed_at: null, verified_at: '2026-07-08' },
|
||||
]
|
||||
expect(computeCapaOnTimeRate(capas)).toBe(100)
|
||||
})
|
||||
|
||||
it('returns 50% when half are late', () => {
|
||||
const capas = [
|
||||
{ due_date: '2026-07-10', completed_at: '2026-07-09', verified_at: null },
|
||||
{ due_date: '2026-07-10', completed_at: '2026-07-12', verified_at: null },
|
||||
]
|
||||
expect(computeCapaOnTimeRate(capas)).toBe(50)
|
||||
})
|
||||
|
||||
it('returns 0% when all CAPAs are overdue', () => {
|
||||
const capas = [
|
||||
{ due_date: '2026-07-10', completed_at: '2026-07-15', verified_at: null },
|
||||
]
|
||||
expect(computeCapaOnTimeRate(capas)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('leading vs lagging indicators', () => {
|
||||
it('counts hazard and near_miss as leading', () => {
|
||||
const incidents = [
|
||||
{ incident_type: 'hazard' },
|
||||
{ incident_type: 'near_miss' },
|
||||
{ incident_type: 'injury' },
|
||||
{ incident_type: 'fire' },
|
||||
]
|
||||
const { leading, lagging } = classifyIndicators(incidents)
|
||||
expect(leading).toBe(2)
|
||||
expect(lagging).toBe(1)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user