feat(db): phase 4 group 6 — server component pages to Drizzle

Converts all 18 server component page files from Supabase client queries
to Drizzle ORM using asAdmin. Adds getSession() + redirect to the three
pages (hse/incidents, hse/incidents/[id], hse/dashboard) that lacked it.
Maps snake_case component prop shapes explicitly where required.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-07-23 17:29:22 +08:00
co-authored by Claude Sonnet 4.6
parent c2db693d9f
commit f591c0be18
18 changed files with 932 additions and 450 deletions
@@ -1,7 +1,9 @@
import { notFound, redirect } from 'next/navigation'
import Link from 'next/link'
import { createClient } from '@/lib/supabase/server'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { incidents } from '@/lib/db/schema'
import { eq } from 'drizzle-orm'
import { CapaForm } from '@/components/capa/capa-form'
interface Props {
@@ -14,10 +16,17 @@ export default async function NewCapaPage({ params }: Props) {
if (!session) redirect(`/login?redirect=/hse/incidents/${id}/capa/new`)
if (!['hse', 'admin'].includes(session.role)) redirect('/hse/incidents')
const supabase = await createClient()
const [incident] = await asAdmin(db =>
db.select({
id: incidents.id,
referenceNo: incidents.referenceNo,
status: incidents.status,
})
.from(incidents)
.where(eq(incidents.id, id))
.limit(1)
)
const { data: incident } = await supabase
.from('incidents').select('id, reference_no, status').eq('id', id).single()
if (!incident) notFound()
return (
@@ -27,7 +36,7 @@ export default async function NewCapaPage({ params }: Props) {
</Link>
<h1 className="text-xl font-bold text-gray-900 mb-1">Add CAPA Action</h1>
<p className="text-sm text-gray-500 mb-6">
{(incident as { reference_no: string | null }).reference_no ?? id}
{incident.referenceNo ?? id}
</p>
<CapaForm incidentId={id} />
</main>
@@ -2,8 +2,10 @@ export const dynamic = 'force-dynamic'
import { notFound, redirect } from 'next/navigation'
import Link from 'next/link'
import { createClient } from '@/lib/supabase/server'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { incidents, investigations } from '@/lib/db/schema'
import { eq, desc } from 'drizzle-orm'
import { InvestigationForm } from '@/components/incidents/investigation-form'
interface Props {
@@ -16,25 +18,28 @@ export default async function InvestigationPage({ params }: Props) {
if (!session) redirect(`/login?redirect=/hse/incidents/${id}/investigation`)
if (!['hse', 'admin'].includes(session.role)) redirect('/hse/incidents')
const supabase = await createClient()
const { data: incident } = await supabase
.from('incidents')
.select('id, reference_no, status')
.eq('id', id)
.single()
const [incident] = await asAdmin(db =>
db.select({
id: incidents.id,
referenceNo: incidents.referenceNo,
status: incidents.status,
})
.from(incidents)
.where(eq(incidents.id, id))
.limit(1)
)
if (!incident) notFound()
if (!['triaged', 'investigating'].includes((incident as { status: string }).status))
if (!['triaged', 'investigating'].includes(incident.status))
redirect(`/hse/incidents/${id}`)
const { data: existing } = await supabase
.from('investigations')
.select('id')
.eq('incident_id', id)
.order('created_at', { ascending: false })
const [existing] = await asAdmin(db =>
db.select({ id: investigations.id })
.from(investigations)
.where(eq(investigations.incidentId, id))
.orderBy(desc(investigations.createdAt))
.limit(1)
.maybeSingle()
)
return (
<main className="max-w-2xl mx-auto px-4 py-6">
@@ -42,10 +47,10 @@ export default async function InvestigationPage({ params }: Props) {
Back to incident
</Link>
<h1 className="text-xl font-bold text-gray-900 mb-1">Investigation Workspace</h1>
<p className="text-sm text-gray-500 mb-6">{(incident as { reference_no: string | null }).reference_no ?? id}</p>
<p className="text-sm text-gray-500 mb-6">{incident.referenceNo ?? id}</p>
<InvestigationForm
incidentId={id}
existingInvestigationId={(existing as { id: string } | null)?.id ?? null}
existingInvestigationId={existing?.id ?? null}
/>
</main>
)
+136 -39
View File
@@ -1,7 +1,11 @@
export const dynamic = 'force-dynamic'
import { notFound } from 'next/navigation'
import { createClient } from '@/lib/supabase/server'
import { notFound, redirect } from 'next/navigation'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
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 { IncidentHeader } from '@/components/incidents/incident-header'
import { SimilarIncidentsPanel } from '@/components/incidents/similar-incidents-panel'
@@ -14,52 +18,145 @@ interface Props {
export default async function HseIncidentDetailPage({ params }: Props) {
const { id } = await params
const supabase = await createClient()
const session = await getSession()
if (!session) redirect('/login')
const { data: incident, error } = await supabase
.from('incidents')
.select(`
id, reference_no, incident_type, description, severity, status,
injury_involved, asset_involved, medical_status, lost_days, type_details,
is_fatality, is_serious_bodily_injury, is_dangerous_occurrence, is_occupational_disease,
reported_at, closed_at,
sites (id, name),
zones (id, name),
trucks (id, truck_no, carrier),
reporter:users!reported_by (id, name, email),
evidence_files (id, stage, file_url, file_type, uploaded_at)
`)
.eq('id', id)
.eq('evidence_files.deleted', false)
.single()
const reporterAlias = aliasedTable(users, 'reporter')
const investigatorAlias = aliasedTable(users, 'investigator')
if (error || !incident) notFound()
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,
typeDetails: incidents.typeDetails,
isFatality: incidents.isFatality,
isSeriousBodilyInjury: incidents.isSeriousBodilyInjury,
isDangerousOccurrence: incidents.isDangerousOccurrence,
isOccupationalDisease: incidents.isOccupationalDisease,
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)
)
const status = (incident as { status: string }).status
if (!incident) notFound()
const { data: investigation } = await supabase
.from('investigations')
.select(`
id, method, five_why_steps, fishbone_categories,
findings_text, root_cause_summary, alcohol_test_result, urine_test_result,
witness_statement_refs, completed_at,
investigator:users!investigator_id (name, email)
`)
.eq('incident_id', id)
.maybeSingle()
const [evidenceRows, invRows] = await Promise.all([
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)))
),
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 status = incident.status
const needsJkkp = Boolean(
(incident as { is_fatality?: boolean }).is_fatality ||
(incident as { is_serious_bodily_injury?: boolean }).is_serious_bodily_injury ||
(incident as { is_dangerous_occurrence?: boolean }).is_dangerous_occurrence ||
((incident as { lost_days?: number | null }).lost_days ?? 0) >= 4
incident.isFatality ||
incident.isSeriousBodilyInjury ||
incident.isDangerousOccurrence ||
(incident.lostDays ?? 0) >= 4
)
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,
type_details: incident.typeDetails as Record<string, string | boolean> | null,
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 inv = invRows[0]
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 (
<>
<IncidentHeader
incidentId={id}
referenceNo={(incident as { reference_no: string | null }).reference_no}
referenceNo={incident.referenceNo}
status={status}
backHref="/hse/incidents"
canTriage={status === 'reported'}
@@ -67,10 +164,10 @@ export default async function HseIncidentDetailPage({ params }: Props) {
canAddCapa={(['investigating', 'capa_pending'] as string[]).includes(status)}
/>
<main className="max-w-3xl mx-auto px-4 py-6">
<IncidentDetail incident={incident as unknown as Incident} />
<IncidentDetail incident={incidentProp} />
{investigation && (
<InvestigationPanel investigation={investigation as never} />
{investigationProp && (
<InvestigationPanel investigation={investigationProp} />
)}
{needsJkkp && (
@@ -2,8 +2,10 @@ export const dynamic = 'force-dynamic'
import { notFound, redirect } from 'next/navigation'
import Link from 'next/link'
import { createClient } from '@/lib/supabase/server'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { incidents } from '@/lib/db/schema'
import { eq } from 'drizzle-orm'
import { TriageForm } from '@/components/incidents/triage-form'
interface Props {
@@ -16,13 +18,17 @@ export default async function TriagePage({ params }: Props) {
if (!session) redirect(`/login?redirect=/hse/incidents/${id}/triage`)
if (!['hse', 'admin'].includes(session.role)) redirect('/hse/incidents')
const supabase = await createClient()
const { data: incident } = await supabase
.from('incidents')
.select('id, reference_no, incident_type, status, severity')
.eq('id', id)
.single()
const [incident] = await asAdmin(db =>
db.select({
id: incidents.id,
referenceNo: incidents.referenceNo,
status: incidents.status,
severity: incidents.severity,
})
.from(incidents)
.where(eq(incidents.id, id))
.limit(1)
)
if (!incident) notFound()
if (incident.status !== 'reported') redirect(`/hse/incidents/${id}`)
@@ -33,10 +39,10 @@ export default async function TriagePage({ params }: Props) {
Back to incident
</Link>
<h1 className="text-xl font-bold text-gray-900 mb-1">Triage Incident</h1>
<p className="text-sm text-gray-500 mb-6">{incident.reference_no ?? id}</p>
<p className="text-sm text-gray-500 mb-6">{incident.referenceNo ?? id}</p>
<TriageForm
incidentId={id}
currentSeverity={(incident as { severity: number | null }).severity}
currentSeverity={incident.severity}
/>
</main>
)
+75 -28
View File
@@ -1,6 +1,11 @@
export const dynamic = 'force-dynamic'
import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { incidents, sites, zones, trucks, users } from '@/lib/db/schema'
import { eq, and, or, ilike, desc, asc, sql } from 'drizzle-orm'
import { aliasedTable } from 'drizzle-orm'
import { IncidentList, type Incident } from '@/components/incidents/incident-list'
import { Pagination } from '@/components/incidents/pagination'
import { IncidentFilters, type SiteOption, type TruckOption } from '@/components/incidents/incident-filters'
@@ -12,48 +17,90 @@ export default async function HseInboxPage({
}: {
searchParams: Promise<{ page?: string; q?: string; status?: string; type?: string; site_id?: string; truck_id?: string }>
}) {
const supabase = await createClient()
const session = await getSession()
if (!session) redirect('/login')
const params = await searchParams
const page = Math.max(1, Number.parseInt(params.page ?? '1', 10) || 1)
const from = (page - 1) * PAGE_SIZE
let query = supabase
.from('incidents')
.select(`
id, reference_no, incident_type, status, severity, reported_at,
sites (name),
zones (name),
trucks (truck_no),
reporter:users!reported_by (name)
`, { count: 'exact' })
.order('reported_at', { ascending: false })
const reporterAlias = aliasedTable(users, 'reporter')
if (params.q) {
query = query.or(`reference_no.ilike.%${params.q}%,description.ilike.%${params.q}%`)
}
if (params.status) query = query.eq('status', params.status)
if (params.type) query = query.eq('incident_type', params.type)
if (params.site_id) query = query.eq('site_id', params.site_id)
if (params.truck_id) query = query.eq('truck_id', params.truck_id)
const conditions = []
if (params.q) conditions.push(or(ilike(incidents.referenceNo, `%${params.q}%`), ilike(incidents.description, `%${params.q}%`)))
if (params.status) conditions.push(eq(incidents.status, params.status as never))
if (params.type) conditions.push(eq(incidents.incidentType, params.type as never))
if (params.site_id) conditions.push(eq(incidents.siteId, params.site_id))
if (params.truck_id) conditions.push(eq(incidents.truckId, params.truck_id))
const where = conditions.length ? and(...conditions) : undefined
const [{ data: incidents, count }, { data: sites }, { data: trucks }] = await Promise.all([
query.range(from, from + PAGE_SIZE - 1),
supabase.from('sites').select('id, name').order('name'),
supabase.from('trucks').select('id, truck_no').eq('active', true).order('truck_no'),
const [[countRow], incidentRows, siteRows, truckRows] = await Promise.all([
asAdmin(db =>
db.select({ count: sql<number>`count(*)` })
.from(incidents)
.where(where)
),
asAdmin(db =>
db.select({
id: incidents.id,
referenceNo: incidents.referenceNo,
incidentType: incidents.incidentType,
status: incidents.status,
severity: incidents.severity,
reportedAt: incidents.reportedAt,
siteName: sites.name,
zoneName: zones.name,
reporterName: reporterAlias.name,
truckNo: trucks.truckNo,
})
.from(incidents)
.leftJoin(sites, eq(incidents.siteId, sites.id))
.leftJoin(zones, eq(incidents.zoneId, zones.id))
.leftJoin(reporterAlias, eq(incidents.reportedBy, reporterAlias.id))
.leftJoin(trucks, eq(incidents.truckId, trucks.id))
.where(where)
.orderBy(desc(incidents.reportedAt))
.limit(PAGE_SIZE)
.offset(from)
),
asAdmin(db =>
db.select({ id: sites.id, name: sites.name }).from(sites).orderBy(asc(sites.name))
),
asAdmin(db =>
db.select({ id: trucks.id, truckNo: trucks.truckNo })
.from(trucks)
.where(eq(trucks.active, true))
.orderBy(asc(trucks.truckNo))
),
])
const siteOptions: SiteOption[] = (sites ?? []).map(s => ({ id: s.id, name: s.name }))
const truckOptions: TruckOption[] = (trucks ?? []).map(tk => ({ id: tk.id, truck_no: tk.truck_no }))
const total = Number(countRow?.count ?? 0)
const incidentList: Incident[] = incidentRows.map(r => ({
id: r.id,
reference_no: r.referenceNo,
incident_type: r.incidentType,
status: r.status,
severity: r.severity,
reported_at: r.reportedAt.toISOString(),
sites: r.siteName ? { name: r.siteName } : null,
zones: r.zoneName ? { name: r.zoneName } : null,
trucks: r.truckNo ? { truck_no: r.truckNo } : null,
reporter: r.reporterName ? { name: r.reporterName } : null,
}))
const siteOptions: SiteOption[] = siteRows.map(s => ({ id: s.id, name: s.name }))
const truckOptions: TruckOption[] = truckRows.map(t => ({ id: t.id, truck_no: t.truckNo }))
return (
<main className="max-w-4xl mx-auto px-4 py-6">
<div className="flex items-center justify-between mb-4">
<h1 className="text-2xl font-bold text-gray-900">Incident Inbox</h1>
<span className="text-sm text-gray-500">{count ?? incidents?.length ?? 0} incidents</span>
<span className="text-sm text-gray-500">{total} incidents</span>
</div>
<IncidentFilters sites={siteOptions} trucks={truckOptions} />
<IncidentList incidents={(incidents ?? []) as unknown as Incident[]} basePath="/hse" />
<Pagination page={page} pageSize={PAGE_SIZE} total={count ?? 0} href="/hse/incidents" />
<IncidentList incidents={incidentList} basePath="/hse" />
<Pagination page={page} pageSize={PAGE_SIZE} total={total} href="/hse/incidents" />
</main>
)
}