feat(auth): merge reporter, supervisor, capa_owner into ssa role
Add Site Safety Assistant (ssa) role replacing reporter, supervisor and capa_owner. Portals move under /ssa (overview, my-reports, incidents, capas). Update RLS, schema, API role checks, notification recipients, nav and tests. Add db/ops/2026-11-06-merge-roles-into-ssa.sql (not yet applied; needs owner go-ahead and a pg_dump first). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
701fefd286
commit
813395700f
@@ -0,0 +1,131 @@
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { asAdmin } from '@/lib/db/with-user'
|
||||
import { redirect } from 'next/navigation'
|
||||
import { getSession } from '@/lib/auth/get-session'
|
||||
import { capaActions, incidents } from '@/lib/db/schema'
|
||||
import { eq, asc } from 'drizzle-orm'
|
||||
import { StatCard } from '@/components/dashboard/stat-card'
|
||||
import { CapaOwnerActions } from '@/components/capa/capa-owner-actions'
|
||||
import { CapaOwnerNotesForm } from '@/components/capa/capa-owner-notes-form'
|
||||
import { StatusTag } from '@/components/ui/status-tag'
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
open: 'Open',
|
||||
in_progress: 'In Progress',
|
||||
overdue: 'Overdue',
|
||||
pending_verification: 'Pending Verification',
|
||||
verified: 'Verified',
|
||||
reopened: 'Reopened',
|
||||
closed: 'Closed',
|
||||
}
|
||||
|
||||
export default async function MyCapasPage() {
|
||||
const session = await getSession()
|
||||
if (!session) redirect('/login')
|
||||
if (!['ssa', 'admin', 'hse'].includes(session.role)) redirect('/')
|
||||
|
||||
const rows = await asAdmin(db =>
|
||||
db.select({
|
||||
id: capaActions.id,
|
||||
description: capaActions.description,
|
||||
dueDate: capaActions.dueDate,
|
||||
priority: capaActions.priority,
|
||||
status: capaActions.status,
|
||||
incidentId: capaActions.incidentId,
|
||||
ownerNotes: capaActions.ownerNotes,
|
||||
incidentRefNo: incidents.referenceNo,
|
||||
})
|
||||
.from(capaActions)
|
||||
.leftJoin(incidents, eq(capaActions.incidentId, incidents.id))
|
||||
.where(eq(capaActions.ownerUserId, session.sub))
|
||||
.orderBy(asc(capaActions.dueDate))
|
||||
)
|
||||
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
function isCapaOverdue(c: { status: string; dueDate: string | null }): boolean {
|
||||
if (c.status === 'overdue') return true
|
||||
return (c.status === 'open' || c.status === 'in_progress') && !!c.dueDate && c.dueDate < today
|
||||
}
|
||||
|
||||
const openCount = rows.filter(c => ['open', 'in_progress', 'reopened'].includes(c.status) && !isCapaOverdue(c)).length
|
||||
const overdueCount = rows.filter(c => isCapaOverdue(c)).length
|
||||
const doneCount = rows.filter(c => ['verified', 'closed'].includes(c.status)).length
|
||||
|
||||
const PRIORITY_COLORS: Record<string, string> = {
|
||||
high: 'text-accent-700 font-extrabold',
|
||||
med: 'text-accent-700 font-medium',
|
||||
low: 'text-ink/50',
|
||||
}
|
||||
|
||||
const activeRows = rows.filter(c => !['verified', 'closed'].includes(c.status))
|
||||
const doneRows = rows.filter(c => ['verified', 'closed'].includes(c.status))
|
||||
|
||||
return (
|
||||
<main className="max-w-4xl mx-auto px-4 py-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-6">My CAPAs</h1>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4 mb-6">
|
||||
<StatCard label="Active" value={openCount} accent={openCount > 0 ? 'yellow' : 'green'} />
|
||||
<StatCard label="Overdue" value={overdueCount} accent={overdueCount > 0 ? 'red' : 'green'} />
|
||||
<StatCard label="Completed" value={doneCount} accent="green" />
|
||||
</div>
|
||||
|
||||
{activeRows.length === 0 ? (
|
||||
<div className="bg-surface shadow-sm p-8 text-center">
|
||||
<p className="text-gray-400 text-sm">No active CAPAs assigned to you.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-surface shadow-sm divide-y divide-gray-50">
|
||||
{activeRows.map(capa => {
|
||||
const isOverdue = isCapaOverdue(capa)
|
||||
return (
|
||||
<div key={capa.id} className={`p-4 ${isOverdue ? 'bg-red-50' : ''}`}>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm text-gray-800">{capa.description}</p>
|
||||
{capa.incidentRefNo && (
|
||||
<Link href={`/hse/incidents/${capa.incidentId}`} className="text-xs text-accent-700 hover:underline mt-0.5 inline-block">
|
||||
{capa.incidentRefNo}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
<div className="shrink-0 text-right space-y-1">
|
||||
<StatusTag status={capa.status}>{STATUS_LABELS[capa.status] ?? capa.status}</StatusTag>
|
||||
<p className={`text-xs ${isOverdue ? 'text-red-600 font-semibold' : 'text-gray-400'}`}>
|
||||
{capa.dueDate ? `Due ${new Date(capa.dueDate).toLocaleDateString('en-MY')}` : 'No due date'}
|
||||
</p>
|
||||
{capa.priority && (
|
||||
<p className={`text-xs ${PRIORITY_COLORS[capa.priority] ?? ''}`}>
|
||||
{capa.priority.toUpperCase()} priority
|
||||
</p>
|
||||
)}
|
||||
<CapaOwnerActions capaId={capa.id} currentStatus={capa.status} />
|
||||
</div>
|
||||
</div>
|
||||
{capa.status !== 'pending_verification' && (
|
||||
<CapaOwnerNotesForm capaId={capa.id} initialNotes={capa.ownerNotes} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{doneRows.length > 0 && (
|
||||
<div className="mt-6">
|
||||
<h2 className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-2">Completed ({doneCount})</h2>
|
||||
<div className="bg-surface shadow-sm divide-y divide-gray-50 opacity-60">
|
||||
{doneRows.map(capa => (
|
||||
<div key={capa.id} className="p-4 flex items-center justify-between">
|
||||
<p className="text-sm text-gray-500 line-clamp-1">{capa.description}</p>
|
||||
<span className="shrink-0"><StatusTag status={capa.status}>{STATUS_LABELS[capa.status] ?? capa.status}</StatusTag></span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
import { notFound, redirect } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { getSession } from '@/lib/auth/get-session'
|
||||
import { asAdmin } from '@/lib/db/with-user'
|
||||
import { incidents, sites, zones, trucks, users, evidenceFiles, investigations } from '@/lib/db/schema'
|
||||
import { eq, and } from 'drizzle-orm'
|
||||
import { aliasedTable } from 'drizzle-orm'
|
||||
import { IncidentDetail, type Incident } from '@/components/incidents/incident-detail'
|
||||
import { InvestigationPanel } from '@/components/incidents/investigation-panel'
|
||||
|
||||
interface Props {
|
||||
params: Promise<{ id: string }>
|
||||
}
|
||||
|
||||
export default async function SsaIncidentDetailPage({ params }: Props) {
|
||||
const { id } = await params
|
||||
|
||||
const session = await getSession()
|
||||
if (!session) redirect('/login')
|
||||
|
||||
const reporterAlias = aliasedTable(users, 'reporter')
|
||||
const investigatorAlias = aliasedTable(users, 'investigator')
|
||||
|
||||
const [incident] = await asAdmin(db =>
|
||||
db.select({
|
||||
id: incidents.id,
|
||||
referenceNo: incidents.referenceNo,
|
||||
incidentType: incidents.incidentType,
|
||||
description: incidents.description,
|
||||
severity: incidents.severity,
|
||||
status: incidents.status,
|
||||
injuryInvolved: incidents.injuryInvolved,
|
||||
assetInvolved: incidents.assetInvolved,
|
||||
medicalStatus: incidents.medicalStatus,
|
||||
lostDays: incidents.lostDays,
|
||||
reportedAt: incidents.reportedAt,
|
||||
closedAt: incidents.closedAt,
|
||||
siteId: sites.id,
|
||||
siteName: sites.name,
|
||||
zoneId: zones.id,
|
||||
zoneName: zones.name,
|
||||
truckId: trucks.id,
|
||||
truckNo: trucks.truckNo,
|
||||
truckCarrier: trucks.carrier,
|
||||
reporterId: reporterAlias.id,
|
||||
reporterName: reporterAlias.name,
|
||||
reporterEmail: reporterAlias.email,
|
||||
})
|
||||
.from(incidents)
|
||||
.leftJoin(sites, eq(incidents.siteId, sites.id))
|
||||
.leftJoin(zones, eq(incidents.zoneId, zones.id))
|
||||
.leftJoin(trucks, eq(incidents.truckId, trucks.id))
|
||||
.leftJoin(reporterAlias, eq(incidents.reportedBy, reporterAlias.id))
|
||||
.where(eq(incidents.id, id))
|
||||
.limit(1)
|
||||
)
|
||||
|
||||
if (!incident) notFound()
|
||||
|
||||
const evidenceRows = await asAdmin(db =>
|
||||
db.select({
|
||||
id: evidenceFiles.id,
|
||||
stage: evidenceFiles.stage,
|
||||
fileUrl: evidenceFiles.fileUrl,
|
||||
fileType: evidenceFiles.fileType,
|
||||
uploadedAt: evidenceFiles.uploadedAt,
|
||||
})
|
||||
.from(evidenceFiles)
|
||||
.where(and(eq(evidenceFiles.incidentId, id), eq(evidenceFiles.deleted, false)))
|
||||
)
|
||||
|
||||
const [inv] = await asAdmin(db =>
|
||||
db.select({
|
||||
id: investigations.id,
|
||||
method: investigations.method,
|
||||
fiveWhySteps: investigations.fiveWhySteps,
|
||||
fishboneCategories: investigations.fishboneCategories,
|
||||
findingsText: investigations.findingsText,
|
||||
rootCauseSummary: investigations.rootCauseSummary,
|
||||
alcoholTestResult: investigations.alcoholTestResult,
|
||||
urineTestResult: investigations.urineTestResult,
|
||||
witnessStatementRefs: investigations.witnessStatementRefs,
|
||||
completedAt: investigations.completedAt,
|
||||
investigatorName: investigatorAlias.name,
|
||||
investigatorEmail: investigatorAlias.email,
|
||||
})
|
||||
.from(investigations)
|
||||
.leftJoin(investigatorAlias, eq(investigations.investigatorId, investigatorAlias.id))
|
||||
.where(eq(investigations.incidentId, id))
|
||||
.limit(1)
|
||||
)
|
||||
|
||||
const incidentProp: Incident = {
|
||||
id: incident.id,
|
||||
reference_no: incident.referenceNo,
|
||||
incident_type: incident.incidentType,
|
||||
description: incident.description,
|
||||
status: incident.status,
|
||||
severity: incident.severity,
|
||||
injury_involved: incident.injuryInvolved,
|
||||
asset_involved: incident.assetInvolved,
|
||||
medical_status: incident.medicalStatus,
|
||||
lost_days: incident.lostDays,
|
||||
reported_at: incident.reportedAt.toISOString(),
|
||||
closed_at: incident.closedAt?.toISOString() ?? null,
|
||||
sites: incident.siteId ? { id: incident.siteId, name: incident.siteName! } : null,
|
||||
zones: incident.zoneId ? { id: incident.zoneId, name: incident.zoneName! } : null,
|
||||
trucks: incident.truckId ? { id: incident.truckId, truck_no: incident.truckNo!, carrier: incident.truckCarrier ?? null } : null,
|
||||
reporter: incident.reporterId ? { id: incident.reporterId, name: incident.reporterName!, email: incident.reporterEmail! } : null,
|
||||
evidence_files: evidenceRows.map(e => ({
|
||||
id: e.id,
|
||||
stage: e.stage,
|
||||
file_url: e.fileUrl,
|
||||
file_type: e.fileType,
|
||||
uploaded_at: e.uploadedAt.toISOString(),
|
||||
})),
|
||||
}
|
||||
|
||||
const investigationProp = inv ? {
|
||||
id: inv.id,
|
||||
method: inv.method,
|
||||
five_why_steps: inv.fiveWhySteps as { why: string; answer: string }[] | null,
|
||||
fishbone_categories: inv.fishboneCategories as Record<string, string> | null,
|
||||
findings_text: inv.findingsText,
|
||||
root_cause_summary: inv.rootCauseSummary,
|
||||
alcohol_test_result: inv.alcoholTestResult,
|
||||
urine_test_result: inv.urineTestResult,
|
||||
witness_statement_refs: inv.witnessStatementRefs ?? [],
|
||||
completed_at: inv.completedAt?.toISOString() ?? null,
|
||||
investigator: inv.investigatorEmail
|
||||
? { name: inv.investigatorName ?? null, email: inv.investigatorEmail }
|
||||
: null,
|
||||
} : null
|
||||
|
||||
return (
|
||||
<main className="max-w-3xl mx-auto px-4 py-6">
|
||||
<Link href="/ssa/incidents" className="text-sm text-accent-700 hover:underline mb-4 inline-block">
|
||||
← Back to inbox
|
||||
</Link>
|
||||
<IncidentDetail incident={incidentProp} />
|
||||
{investigationProp && (
|
||||
<InvestigationPanel investigation={investigationProp} />
|
||||
)}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { redirect } from 'next/navigation'
|
||||
import { getSession } from '@/lib/auth/get-session'
|
||||
import { buttonClass } from '@/components/ui/button'
|
||||
import { IncidentTable } from '@/components/incidents/incident-table'
|
||||
import { loadIncidentList } from '@/lib/incidents/list-query'
|
||||
import { parseListParams } from '@/lib/incidents/list-params'
|
||||
|
||||
export default async function SsaInboxPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<Record<string, string | undefined>>
|
||||
}) {
|
||||
const session = await getSession()
|
||||
if (!session) redirect('/login')
|
||||
|
||||
const params = parseListParams(await searchParams)
|
||||
const data = await loadIncidentList(params)
|
||||
|
||||
return (
|
||||
<div className="px-4 py-5 md:px-8 md:py-6 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-[22px] md:text-xl font-[650]">Incidents</h1>
|
||||
<Link href="/report" className={buttonClass('primary')}>Report incident</Link>
|
||||
</div>
|
||||
<IncidentTable
|
||||
incidents={data.incidents}
|
||||
basePath="/ssa"
|
||||
total={data.total}
|
||||
counts={data.counts}
|
||||
params={params}
|
||||
sites={data.sites}
|
||||
trucks={data.trucks}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { asAdmin } from '@/lib/db/with-user'
|
||||
import { redirect, notFound } from 'next/navigation'
|
||||
import { getSession } from '@/lib/auth/get-session'
|
||||
import { incidents, sites, zones, capaActions } from '@/lib/db/schema'
|
||||
import { eq, and } from 'drizzle-orm'
|
||||
import { StatusTag } from '@/components/ui/status-tag'
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
reported: 'Reported', triaged: 'Triaged', investigating: 'Investigating',
|
||||
capa_pending: 'CAPA Pending', verification: 'Verification', closed: 'Closed',
|
||||
}
|
||||
export default async function MyReportDetail({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>
|
||||
}) {
|
||||
const { id } = await params
|
||||
const session = await getSession()
|
||||
if (!session) redirect('/login')
|
||||
|
||||
const [inc] = await asAdmin(db =>
|
||||
db.select({
|
||||
id: incidents.id,
|
||||
referenceNo: incidents.referenceNo,
|
||||
incidentType: incidents.incidentType,
|
||||
status: incidents.status,
|
||||
severity: incidents.severity,
|
||||
reportedAt: incidents.reportedAt,
|
||||
closedAt: incidents.closedAt,
|
||||
description: incidents.description,
|
||||
injuryInvolved: incidents.injuryInvolved,
|
||||
medicalStatus: incidents.medicalStatus,
|
||||
lostDays: incidents.lostDays,
|
||||
siteName: sites.name,
|
||||
zoneName: zones.name,
|
||||
})
|
||||
.from(incidents)
|
||||
.leftJoin(sites, eq(incidents.siteId, sites.id))
|
||||
.leftJoin(zones, eq(incidents.zoneId, zones.id))
|
||||
.where(and(eq(incidents.id, id), eq(incidents.reportedBy, session.sub)))
|
||||
.limit(1)
|
||||
)
|
||||
|
||||
if (!inc) notFound()
|
||||
|
||||
const capas = await asAdmin(db =>
|
||||
db.select({
|
||||
id: capaActions.id,
|
||||
description: capaActions.description,
|
||||
status: capaActions.status,
|
||||
dueDate: capaActions.dueDate,
|
||||
})
|
||||
.from(capaActions)
|
||||
.where(eq(capaActions.incidentId, id))
|
||||
)
|
||||
|
||||
return (
|
||||
<main className="max-w-2xl mx-auto px-4 py-6 space-y-4">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Link href="/ssa/my-reports" className="text-sm text-accent-700 hover:underline">← My Reports</Link>
|
||||
</div>
|
||||
|
||||
<div className="bg-surface shadow-sm p-5">
|
||||
<div className="flex items-start justify-between gap-3 mb-4">
|
||||
<div>
|
||||
<h1 className="text-lg font-bold text-gray-900">{inc.referenceNo ?? inc.id.slice(0, 8)}</h1>
|
||||
<p className="text-sm text-gray-500 capitalize">{inc.incidentType?.replace(/_/g, ' ')}</p>
|
||||
</div>
|
||||
<span className="shrink-0"><StatusTag status={inc.status}>{STATUS_LABELS[inc.status] ?? inc.status}</StatusTag></span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3 text-sm mb-4">
|
||||
{inc.siteName && <div><p className="text-xs text-gray-500">Site</p><p className="font-medium">{inc.siteName}</p></div>}
|
||||
{inc.zoneName && <div><p className="text-xs text-gray-500">Zone</p><p className="font-medium">{inc.zoneName}</p></div>}
|
||||
{inc.severity && <div><p className="text-xs text-gray-500">Severity</p><p className="font-medium">{inc.severity} / 5</p></div>}
|
||||
{inc.reportedAt && (
|
||||
<div>
|
||||
<p className="text-xs text-gray-500">Reported</p>
|
||||
<p className="font-medium">{new Date(inc.reportedAt).toLocaleDateString('en-MY')}</p>
|
||||
</div>
|
||||
)}
|
||||
{inc.closedAt && (
|
||||
<div>
|
||||
<p className="text-xs text-gray-500">Closed</p>
|
||||
<p className="font-medium">{new Date(inc.closedAt).toLocaleDateString('en-MY')}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{inc.description && (
|
||||
<div className="border-t border-divider pt-4">
|
||||
<p className="text-xs text-gray-500 mb-1">Description</p>
|
||||
<p className="text-sm text-gray-800 whitespace-pre-line">{inc.description}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{capas.length > 0 && (
|
||||
<div className="bg-surface shadow-sm p-5">
|
||||
<h2 className="text-sm font-semibold text-gray-900 mb-3">Corrective Actions ({capas.length})</h2>
|
||||
<div className="space-y-2">
|
||||
{capas.map(c => (
|
||||
<div key={c.id} className="flex items-start justify-between gap-3 text-sm">
|
||||
<p className="text-gray-700 flex-1">{c.description}</p>
|
||||
<span className={`text-xs px-2 py-0.5 shrink-0 ${
|
||||
c.status === 'verified' ? 'bg-st-green-bg text-st-green-fg' :
|
||||
c.status === 'pending_verification' ? 'bg-st-indigo-bg text-st-indigo-fg' :
|
||||
'bg-st-grey-bg text-st-grey-fg'
|
||||
}`}>{c.status.replace(/_/g, ' ')}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { asAdmin } from '@/lib/db/with-user'
|
||||
import { redirect } from 'next/navigation'
|
||||
import { getSession } from '@/lib/auth/get-session'
|
||||
import { incidents, sites } from '@/lib/db/schema'
|
||||
import { eq, desc } from 'drizzle-orm'
|
||||
import { StatusTag } from '@/components/ui/status-tag'
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
reported: 'Reported',
|
||||
triaged: 'Triaged',
|
||||
investigating: 'Investigating',
|
||||
capa_pending: 'CAPA Pending',
|
||||
verification: 'Verification',
|
||||
closed: 'Closed',
|
||||
}
|
||||
|
||||
const TYPE_LABELS: Record<string, string> = {
|
||||
injury: 'Injury', near_miss: 'Near Miss', hazard: 'Hazard',
|
||||
asset_damage: 'Asset Damage', environmental: 'Environmental', security: 'Security', fire: 'Fire',
|
||||
}
|
||||
|
||||
export default async function MyReportsPage() {
|
||||
const session = await getSession()
|
||||
if (!session) redirect('/login')
|
||||
|
||||
const rows = await asAdmin(db =>
|
||||
db.select({
|
||||
id: incidents.id,
|
||||
referenceNo: incidents.referenceNo,
|
||||
incidentType: incidents.incidentType,
|
||||
status: incidents.status,
|
||||
reportedAt: incidents.reportedAt,
|
||||
severity: incidents.severity,
|
||||
siteName: sites.name,
|
||||
})
|
||||
.from(incidents)
|
||||
.leftJoin(sites, eq(incidents.siteId, sites.id))
|
||||
.where(eq(incidents.reportedBy, session.sub))
|
||||
.orderBy(desc(incidents.reportedAt))
|
||||
)
|
||||
|
||||
const openCount = rows.filter(r => r.status !== 'closed').length
|
||||
const closedCount = rows.filter(r => r.status === 'closed').length
|
||||
|
||||
return (
|
||||
<main className="max-w-2xl mx-auto px-4 py-6">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">My Reports</h1>
|
||||
<p className="text-sm text-gray-400 mt-0.5">Welcome, {session.name}</p>
|
||||
</div>
|
||||
<Link
|
||||
href="/report"
|
||||
className="bg-accent text-white px-4 py-2 text-sm font-semibold hover:bg-accent-600"
|
||||
>
|
||||
+ New Report
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-4 mb-6 text-sm">
|
||||
<div className="bg-surface shadow-sm p-4 flex-1 text-center">
|
||||
<p className="text-2xl font-bold text-gray-900">{rows.length}</p>
|
||||
<p className="text-xs text-gray-500 mt-1">Total Submitted</p>
|
||||
</div>
|
||||
<div className="bg-surface shadow-sm p-4 flex-1 text-center">
|
||||
<p className="text-2xl font-bold text-accent-700">{openCount}</p>
|
||||
<p className="text-xs text-gray-500 mt-1">In Progress</p>
|
||||
</div>
|
||||
<div className="bg-surface shadow-sm p-4 flex-1 text-center">
|
||||
<p className="text-2xl font-bold text-ink">{closedCount}</p>
|
||||
<p className="text-xs text-gray-500 mt-1">Closed</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{rows.length === 0 ? (
|
||||
<div className="bg-surface shadow-sm p-8 text-center">
|
||||
<p className="text-gray-400 text-sm mb-4">No incidents reported yet.</p>
|
||||
<Link href="/report" className="text-accent-700 text-sm hover:underline">Submit your first report →</Link>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-surface shadow-sm divide-y divide-gray-50">
|
||||
{rows.map(inc => (
|
||||
<Link key={inc.id} href={`/ssa/my-reports/${inc.id}`} className="block p-4 cursor-pointer hover:bg-gray-50 transition-colors">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-semibold text-gray-900">
|
||||
{inc.referenceNo ?? inc.id.slice(0, 8)}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 mt-0.5">
|
||||
{TYPE_LABELS[inc.incidentType] ?? inc.incidentType}
|
||||
{inc.siteName ? ` · ${inc.siteName}` : ''}
|
||||
{inc.severity ? ` · Severity ${inc.severity}` : ''}
|
||||
</p>
|
||||
{inc.reportedAt && (
|
||||
<p className="text-xs text-gray-400 mt-0.5">
|
||||
{new Date(inc.reportedAt).toLocaleDateString('en-MY', {
|
||||
day: 'numeric', month: 'short', year: 'numeric',
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<span className="shrink-0"><StatusTag status={inc.status}>{STATUS_LABELS[inc.status] ?? inc.status}</StatusTag></span>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { asAdmin } from '@/lib/db/with-user'
|
||||
import { redirect } from 'next/navigation'
|
||||
import { getSession } from '@/lib/auth/get-session'
|
||||
import { incidents, sites, capaActions, users } from '@/lib/db/schema'
|
||||
import { eq, not, and, inArray, sql, desc } from 'drizzle-orm'
|
||||
import { aliasedTable } from 'drizzle-orm'
|
||||
import { StatCard } from '@/components/dashboard/stat-card'
|
||||
import { StatusTag } from '@/components/ui/status-tag'
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
reported: 'Reported',
|
||||
triaged: 'Triaged',
|
||||
investigating: 'Investigating',
|
||||
capa_pending: 'CAPA Pending',
|
||||
verification: 'Verification',
|
||||
closed: 'Closed',
|
||||
}
|
||||
|
||||
export default async function SsaPage() {
|
||||
const session = await getSession()
|
||||
if (!session) redirect('/login')
|
||||
if (!['ssa', 'admin'].includes(session.role)) redirect('/')
|
||||
|
||||
if (!session.siteId) {
|
||||
return (
|
||||
<main className="max-w-4xl mx-auto px-4 py-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-4">Site Safety Assistant Portal</h1>
|
||||
<p className="text-sm text-gray-500">No site assigned — contact your administrator.</p>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
const [siteRow] = await asAdmin(db =>
|
||||
db.select({ name: sites.name }).from(sites).where(eq(sites.id, session.siteId!)).limit(1)
|
||||
)
|
||||
const siteName = siteRow?.name ?? 'Your Site'
|
||||
|
||||
// Get all incident IDs for this site
|
||||
const siteIncidents = await asAdmin(db =>
|
||||
db.select({ id: incidents.id }).from(incidents).where(eq(incidents.siteId, session.siteId!))
|
||||
)
|
||||
const incidentIds = siteIncidents.map(r => r.id)
|
||||
|
||||
const ownerAlias = aliasedTable(users, 'owner')
|
||||
|
||||
const [openIncidents, closedCountRow, openCountRow, overdueCapas, allCapas] = await Promise.all([
|
||||
asAdmin(db =>
|
||||
db.select({
|
||||
id: incidents.id,
|
||||
referenceNo: incidents.referenceNo,
|
||||
incidentType: incidents.incidentType,
|
||||
status: incidents.status,
|
||||
reportedAt: incidents.reportedAt,
|
||||
})
|
||||
.from(incidents)
|
||||
.where(and(eq(incidents.siteId, session.siteId!), not(eq(incidents.status, 'closed'))))
|
||||
.orderBy(desc(incidents.reportedAt))
|
||||
.limit(10)
|
||||
),
|
||||
asAdmin(db =>
|
||||
db.select({ count: sql<number>`count(*)` })
|
||||
.from(incidents)
|
||||
.where(and(eq(incidents.siteId, session.siteId!), eq(incidents.status, 'closed')))
|
||||
),
|
||||
asAdmin(db =>
|
||||
db.select({ count: sql<number>`count(*)` })
|
||||
.from(incidents)
|
||||
.where(and(eq(incidents.siteId, session.siteId!), not(eq(incidents.status, 'closed'))))
|
||||
),
|
||||
incidentIds.length > 0
|
||||
? asAdmin(db =>
|
||||
db.select({
|
||||
id: capaActions.id,
|
||||
description: capaActions.description,
|
||||
dueDate: capaActions.dueDate,
|
||||
ownerName: ownerAlias.name,
|
||||
})
|
||||
.from(capaActions)
|
||||
.leftJoin(ownerAlias, eq(capaActions.ownerUserId, ownerAlias.id))
|
||||
.where(and(eq(capaActions.status, 'overdue'), inArray(capaActions.incidentId, incidentIds)))
|
||||
)
|
||||
: Promise.resolve([]),
|
||||
incidentIds.length > 0
|
||||
? asAdmin(db =>
|
||||
db.select({ id: capaActions.id, status: capaActions.status })
|
||||
.from(capaActions)
|
||||
.where(inArray(capaActions.incidentId, incidentIds))
|
||||
)
|
||||
: Promise.resolve([]),
|
||||
])
|
||||
|
||||
const resolvedOpenCount = Number(openCountRow[0]?.count ?? 0)
|
||||
const resolvedClosedCount = Number(closedCountRow[0]?.count ?? 0)
|
||||
const overdueCount = overdueCapas.length
|
||||
const capaRows = allCapas
|
||||
const capaOpenCount = capaRows.filter(c => ['open', 'in_progress'].includes(c.status)).length
|
||||
const capaVerifiedCount = capaRows.filter(c => c.status === 'verified').length
|
||||
|
||||
const TYPE_LABELS: Record<string, string> = {
|
||||
injury: 'Injury', near_miss: 'Near Miss', hazard: 'Hazard',
|
||||
asset_damage: 'Asset Damage', environmental: 'Environmental', security: 'Security', fire: 'Fire',
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="max-w-4xl mx-auto px-4 py-6">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Site Safety Assistant Portal</h1>
|
||||
<p className="text-sm text-gray-500 mt-1">{siteName}</p>
|
||||
</div>
|
||||
<Link href="/ssa/incidents" className="text-sm text-accent-700 hover:underline">
|
||||
All incidents →
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4 mb-6">
|
||||
<StatCard label="Open Incidents" value={resolvedOpenCount} accent={resolvedOpenCount > 0 ? 'yellow' : 'green'} />
|
||||
<StatCard label="Closed Incidents" value={resolvedClosedCount} accent="green" />
|
||||
<StatCard label="Open CAPAs" value={capaOpenCount} accent={capaOpenCount > 0 ? 'yellow' : 'green'} />
|
||||
<StatCard label="CAPA Overdue" value={overdueCount} accent={overdueCount > 0 ? 'red' : 'green'} />
|
||||
</div>
|
||||
|
||||
{/* Open incidents */}
|
||||
<div className="bg-surface shadow-sm p-5 mb-4">
|
||||
<h2 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-4">Open Incidents</h2>
|
||||
{openIncidents.length === 0 ? (
|
||||
<p className="text-sm text-gray-400">No open incidents.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{openIncidents.map(inc => (
|
||||
<Link
|
||||
key={inc.id}
|
||||
href={`/ssa/incidents/${inc.id}`}
|
||||
className="flex items-center justify-between py-2 border-b border-gray-50 last:border-0 hover:bg-gray-50 -mx-2 px-2"
|
||||
>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-900">{inc.referenceNo ?? inc.id.slice(0, 8)}</p>
|
||||
<p className="text-xs text-gray-500">{TYPE_LABELS[inc.incidentType] ?? inc.incidentType}</p>
|
||||
</div>
|
||||
<StatusTag status={inc.status}>{STATUS_LABELS[inc.status] ?? inc.status}</StatusTag>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Overdue CAPAs */}
|
||||
{overdueCount > 0 && (
|
||||
<div className="bg-surface shadow-sm p-5">
|
||||
<h2 className="text-sm font-semibold text-red-600 uppercase tracking-wide mb-4">Overdue CAPAs</h2>
|
||||
<div className="space-y-2">
|
||||
{overdueCapas.map(capa => (
|
||||
<div key={capa.id} className="flex items-start justify-between py-2 border-b border-gray-50 last:border-0">
|
||||
<div className="flex-1 min-w-0 mr-4">
|
||||
<p className="text-sm text-gray-800 line-clamp-2">{capa.description}</p>
|
||||
<p className="text-xs text-gray-500 mt-0.5">
|
||||
Owner: {capa.ownerName ?? 'Unassigned'}
|
||||
</p>
|
||||
</div>
|
||||
<span className="text-xs text-red-600 font-semibold shrink-0">
|
||||
Due {capa.dueDate ? new Date(capa.dueDate).toLocaleDateString('en-MY') : '—'}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-gray-400 mt-3">CAPA verification rate: {capaRows.length > 0 ? Math.round((capaVerifiedCount / capaRows.length) * 100) : 'N/A'}%</p>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user