74 changed files with 185 additions and 3770 deletions
+1 -1
View File
@@ -85,7 +85,7 @@ Source of truth: `design-system/design.md`. Visual references: `design-system/IM
- Radius comes from the scale: `rounded-md` (8) buttons, chips, inputs, pills; `rounded-xl` (12) cards and mobile controls; `rounded-[5px]` checkbox. Headings and labels are flush left. - Radius comes from the scale: `rounded-md` (8) buttons, chips, inputs, pills; `rounded-xl` (12) cards and mobile controls; `rounded-[5px]` checkbox. Headings and labels are flush left.
- Status and priority colours only via `StatusTag` / `PriorityTag` (design.md §4.2): dark text on a light tint, text label always present, no icon required. Add new statuses in `components/ui/status-tag.tsx`, not per page. - Status and priority colours only via `StatusTag` / `PriorityTag` (design.md §4.2): dark text on a light tint, text label always present, no icon required. Add new statuses in `components/ui/status-tag.tsx`, not per page.
- Every list is a `TableCard` (design.md §4.9): saved views, toolbar, sortable header, row hover quick actions, selected tint, footer pager, floating bulk bar, empty state, mobile stacked variant. Do not hand-build tables. - Every list is a `TableCard` (design.md §4.9): saved views, toolbar, sortable header, row hover quick actions, selected tint, footer pager, floating bulk bar, empty state, mobile stacked variant. Do not hand-build tables.
- Build UI with `components/ui/*`: `Button`, `StatusTag`, `PriorityTag`, `Checkbox`, `Field`/`Input`/`Select`/`Textarea`, `FilterChip`, `Segmented`, `Avatar`, `Card`, `Drawer`, `TableCard`; pages sit in `AppShell` (desktop) or `MobileShell` (SSA). - Build UI with `components/ui/*`: `Button`, `StatusTag`, `PriorityTag`, `Checkbox`, `Field`/`Input`/`Select`/`Textarea`, `FilterChip`, `Segmented`, `Avatar`, `Card`, `Drawer`, `TableCard`; pages sit in `AppShell` (desktop) or `MobileShell` (reporter / CAPA owner).
- Icons: Lucide (`lucide-react`), 16px stroke 2 in UI, 12px stroke 2.5 inside chips and checks, 22px stroke 1.8 in the mobile tab bar. - Icons: Lucide (`lucide-react`), 16px stroke 2 in UI, 12px stroke 2.5 inside chips and checks, 22px stroke 1.8 in the mobile tab bar.
- Interaction: hover/active values per component in design.md §4; `:focus-visible` 2px accent ring is global; transitions 120ms on bg/shadow only; mobile hit targets ≥ 44px. - Interaction: hover/active values per component in design.md §4; `:focus-visible` 2px accent ring is global; transitions 120ms on bg/shadow only; mobile hit targets ≥ 44px.
- Incident evidence photos stay full colour. - Incident evidence photos stay full colour.
+14 -6
View File
@@ -3,14 +3,22 @@ import { describe, it, expect } from 'vitest'
import { getRoleHome, ROLE_HOME, ALL_ROLES } from '@/lib/auth/roles' import { getRoleHome, ROLE_HOME, ALL_ROLES } from '@/lib/auth/roles'
describe('getRoleHome', () => { describe('getRoleHome', () => {
it('returns /ssa for ssa role', () => { it('returns /reporter for reporter role', () => {
expect(getRoleHome('ssa')).toBe('/ssa') expect(getRoleHome('reporter')).toBe('/reporter')
})
it('returns /supervisor for supervisor role', () => {
expect(getRoleHome('supervisor')).toBe('/supervisor')
}) })
it('returns /hse for hse role', () => { it('returns /hse for hse role', () => {
expect(getRoleHome('hse')).toBe('/hse') expect(getRoleHome('hse')).toBe('/hse')
}) })
it('returns /capa-owner for capa_owner role', () => {
expect(getRoleHome('capa_owner')).toBe('/capa-owner')
})
it('returns /management for management role', () => { it('returns /management for management role', () => {
expect(getRoleHome('management')).toBe('/management') expect(getRoleHome('management')).toBe('/management')
}) })
@@ -19,11 +27,11 @@ describe('getRoleHome', () => {
expect(getRoleHome('admin')).toBe('/admin') expect(getRoleHome('admin')).toBe('/admin')
}) })
it('ROLE_HOME covers exactly 4 roles', () => { it('ROLE_HOME covers exactly 6 roles', () => {
expect(Object.keys(ROLE_HOME)).toHaveLength(4) expect(Object.keys(ROLE_HOME)).toHaveLength(6)
}) })
it('ALL_ROLES lists exactly 4 roles', () => { it('ALL_ROLES lists exactly 6 roles', () => {
expect(ALL_ROLES).toHaveLength(4) expect(ALL_ROLES).toHaveLength(6)
}) })
}) })
+2 -5
View File
@@ -29,7 +29,7 @@ export default async function AdminHome() {
qrCodeToken: zones.qrCodeToken, active: zones.active, qrCodeToken: zones.qrCodeToken, active: zones.active,
}).from(zones)), }).from(zones)),
asAdmin(db => db.select({ asAdmin(db => db.select({
id: trucks.id, truckNo: trucks.truckNo, carrier: trucks.carrier, siteId: trucks.siteId, active: trucks.active, id: trucks.id, truckNo: trucks.truckNo, carrier: trucks.carrier, active: trucks.active,
}).from(trucks).orderBy(asc(trucks.truckNo))), }).from(trucks).orderBy(asc(trucks.truckNo))),
]) ])
@@ -46,10 +46,8 @@ export default async function AdminHome() {
const siteOptions: SiteOption[] = siteRows.map(s => ({ id: s.id, name: s.name })) const siteOptions: SiteOption[] = siteRows.map(s => ({ id: s.id, name: s.name }))
const truckSites = siteRows.map(s => ({ id: s.id, name: s.name, active: s.active }))
const truckList: Truck[] = truckRows.map(t => ({ const truckList: Truck[] = truckRows.map(t => ({
id: t.id, truck_no: t.truckNo, carrier: t.carrier ?? null, site_id: t.siteId ?? null, active: t.active, id: t.id, truck_no: t.truckNo, carrier: t.carrier ?? null, active: t.active,
})) }))
return ( return (
@@ -68,7 +66,6 @@ export default async function AdminHome() {
sites={sitesWithZones} sites={sitesWithZones}
siteOptions={siteOptions} siteOptions={siteOptions}
trucks={truckList} trucks={truckList}
truckSites={truckSites}
/> />
</main> </main>
) )
@@ -21,10 +21,10 @@ const STATUS_LABELS: Record<string, string> = {
closed: 'Closed', closed: 'Closed',
} }
export default async function MyCapasPage() { export default async function CapaOwnerPage() {
const session = await getSession() const session = await getSession()
if (!session) redirect('/login') if (!session) redirect('/login')
if (!['ssa', 'admin', 'hse'].includes(session.role)) redirect('/') if (!['capa_owner', 'admin', 'hse', 'supervisor'].includes(session.role)) redirect('/')
const rows = await asAdmin(db => const rows = await asAdmin(db =>
db.select({ db.select({
+3 -22
View File
@@ -5,8 +5,8 @@ import Link from 'next/link'
import { ArrowLeft } from 'lucide-react' import { ArrowLeft } from 'lucide-react'
import { asAdmin } from '@/lib/db/with-user' import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session' import { getSession } from '@/lib/auth/get-session'
import { capaActions, evidenceFiles, incidents, users } from '@/lib/db/schema' import { capaActions, incidents, users } from '@/lib/db/schema'
import { eq, and, asc } from 'drizzle-orm' import { eq } from 'drizzle-orm'
import { aliasedTable } from 'drizzle-orm' import { aliasedTable } from 'drizzle-orm'
import { VerifyForm } from '@/components/capa/verify-form' import { VerifyForm } from '@/components/capa/verify-form'
import { CloseCapaButton } from '@/components/capa/close-capa-button' import { CloseCapaButton } from '@/components/capa/close-capa-button'
@@ -60,13 +60,6 @@ export default async function CapaDetailPage({ params }: Props) {
if (!capa) notFound() if (!capa) notFound()
const photos = await asAdmin(db =>
db.select({ id: evidenceFiles.id, fileUrl: evidenceFiles.fileUrl })
.from(evidenceFiles)
.where(and(eq(evidenceFiles.capaId, id), eq(evidenceFiles.deleted, false)))
.orderBy(asc(evidenceFiles.uploadedAt))
)
const isHse = session && ['hse', 'admin'].includes(session.role) const isHse = session && ['hse', 'admin'].includes(session.role)
const status = capa.status const status = capa.status
const today = new Date().toISOString().slice(0, 10) const today = new Date().toISOString().slice(0, 10)
@@ -109,7 +102,7 @@ export default async function CapaDetailPage({ params }: Props) {
{isHse && status === 'pending_verification' && <VerifyForm capaId={id} />} {isHse && status === 'pending_verification' && <VerifyForm capaId={id} />}
{isHse && status === 'verified' && <CloseCapaButton capaId={id} />} {isHse && status === 'verified' && <CloseCapaButton capaId={id} />}
{(capa.ownerNotes || capa.completedAt || photos.length > 0) && ( {(capa.ownerNotes || capa.completedAt) && (
<section className="space-y-2 rounded-xl bg-surface p-5 shadow-card"> <section className="space-y-2 rounded-xl bg-surface p-5 shadow-card">
<h2 className="text-sm font-semibold">Completion report</h2> <h2 className="text-sm font-semibold">Completion report</h2>
{capa.completedAt && ( {capa.completedAt && (
@@ -120,18 +113,6 @@ export default async function CapaDetailPage({ params }: Props) {
{capa.ownerNotes && ( {capa.ownerNotes && (
<p className="whitespace-pre-wrap text-[13px] text-ink-3">{capa.ownerNotes}</p> <p className="whitespace-pre-wrap text-[13px] text-ink-3">{capa.ownerNotes}</p>
)} )}
{photos.length > 0 && (
<ul className="grid grid-cols-2 gap-2 sm:grid-cols-3">
{photos.map((p, i) => (
<li key={p.id}>
<a href={p.fileUrl} target="_blank" rel="noreferrer" className="block overflow-hidden rounded-md shadow-card">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={p.fileUrl} alt={`CAPA completion evidence ${i + 1} of ${photos.length}`} className="aspect-square w-full object-cover" />
</a>
</li>
))}
</ul>
)}
</section> </section>
)} )}
</div> </div>
@@ -12,7 +12,7 @@ const STATUS_LABELS: Record<string, string> = {
reported: 'Reported', triaged: 'Triaged', investigating: 'Investigating', reported: 'Reported', triaged: 'Triaged', investigating: 'Investigating',
capa_pending: 'CAPA Pending', verification: 'Verification', closed: 'Closed', capa_pending: 'CAPA Pending', verification: 'Verification', closed: 'Closed',
} }
export default async function MyReportDetail({ export default async function ReporterIncidentDetail({
params, params,
}: { }: {
params: Promise<{ id: string }> params: Promise<{ id: string }>
@@ -60,7 +60,7 @@ export default async function MyReportDetail({
return ( return (
<main className="max-w-2xl mx-auto px-4 py-6 space-y-4"> <main className="max-w-2xl mx-auto px-4 py-6 space-y-4">
<div className="flex items-center gap-2 mb-2"> <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> <Link href="/reporter" className="text-sm text-accent-700 hover:underline">← My Reports</Link>
</div> </div>
<div className="bg-surface shadow-sm p-5"> <div className="bg-surface shadow-sm p-5">
@@ -22,7 +22,7 @@ const TYPE_LABELS: Record<string, string> = {
asset_damage: 'Asset Damage', environmental: 'Environmental', security: 'Security', fire: 'Fire', asset_damage: 'Asset Damage', environmental: 'Environmental', security: 'Security', fire: 'Fire',
} }
export default async function MyReportsPage() { export default async function ReporterPage() {
const session = await getSession() const session = await getSession()
if (!session) redirect('/login') if (!session) redirect('/login')
@@ -83,7 +83,7 @@ export default async function MyReportsPage() {
) : ( ) : (
<div className="bg-surface shadow-sm divide-y divide-gray-50"> <div className="bg-surface shadow-sm divide-y divide-gray-50">
{rows.map(inc => ( {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"> <Link key={inc.id} href={`/reporter/incidents/${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 items-start justify-between gap-3">
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<p className="text-sm font-semibold text-gray-900"> <p className="text-sm font-semibold text-gray-900">
@@ -14,7 +14,7 @@ interface Props {
params: Promise<{ id: string }> params: Promise<{ id: string }>
} }
export default async function SsaIncidentDetailPage({ params }: Props) { export default async function SupervisorIncidentDetailPage({ params }: Props) {
const { id } = await params const { id } = await params
const session = await getSession() const session = await getSession()
@@ -136,7 +136,7 @@ export default async function SsaIncidentDetailPage({ params }: Props) {
return ( return (
<main className="max-w-3xl mx-auto px-4 py-6"> <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"> <Link href="/supervisor/incidents" className="text-sm text-accent-700 hover:underline mb-4 inline-block">
← Back to inbox ← Back to inbox
</Link> </Link>
<IncidentDetail incident={incidentProp} /> <IncidentDetail incident={incidentProp} />
@@ -8,7 +8,7 @@ import { IncidentTable } from '@/components/incidents/incident-table'
import { loadIncidentList } from '@/lib/incidents/list-query' import { loadIncidentList } from '@/lib/incidents/list-query'
import { parseListParams } from '@/lib/incidents/list-params' import { parseListParams } from '@/lib/incidents/list-params'
export default async function SsaInboxPage({ export default async function SupervisorInboxPage({
searchParams, searchParams,
}: { }: {
searchParams: Promise<Record<string, string | undefined>> searchParams: Promise<Record<string, string | undefined>>
@@ -27,7 +27,7 @@ export default async function SsaInboxPage({
</div> </div>
<IncidentTable <IncidentTable
incidents={data.incidents} incidents={data.incidents}
basePath="/ssa" basePath="/supervisor"
total={data.total} total={data.total}
counts={data.counts} counts={data.counts}
params={params} params={params}
@@ -19,15 +19,15 @@ const STATUS_LABELS: Record<string, string> = {
closed: 'Closed', closed: 'Closed',
} }
export default async function SsaPage() { export default async function SupervisorPage() {
const session = await getSession() const session = await getSession()
if (!session) redirect('/login') if (!session) redirect('/login')
if (!['ssa', 'admin'].includes(session.role)) redirect('/') if (!['supervisor', 'admin'].includes(session.role)) redirect('/')
if (!session.siteId) { if (!session.siteId) {
return ( return (
<main className="max-w-4xl mx-auto px-4 py-6"> <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> <h1 className="text-2xl font-bold text-gray-900 mb-4">Supervisor Portal</h1>
<p className="text-sm text-gray-500">No site assigned — contact your administrator.</p> <p className="text-sm text-gray-500">No site assigned — contact your administrator.</p>
</main> </main>
) )
@@ -108,10 +108,10 @@ export default async function SsaPage() {
<main className="max-w-4xl mx-auto px-4 py-6"> <main className="max-w-4xl mx-auto px-4 py-6">
<div className="flex items-center justify-between mb-6"> <div className="flex items-center justify-between mb-6">
<div> <div>
<h1 className="text-2xl font-bold text-gray-900">Site Safety Assistant Portal</h1> <h1 className="text-2xl font-bold text-gray-900">Supervisor Portal</h1>
<p className="text-sm text-gray-500 mt-1">{siteName}</p> <p className="text-sm text-gray-500 mt-1">{siteName}</p>
</div> </div>
<Link href="/ssa/incidents" className="text-sm text-accent-700 hover:underline"> <Link href="/supervisor/incidents" className="text-sm text-accent-700 hover:underline">
All incidents → All incidents →
</Link> </Link>
</div> </div>
@@ -134,7 +134,7 @@ export default async function SsaPage() {
{openIncidents.map(inc => ( {openIncidents.map(inc => (
<Link <Link
key={inc.id} key={inc.id}
href={`/ssa/incidents/${inc.id}`} href={`/supervisor/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" 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> <div>
+9 -50
View File
@@ -3,43 +3,27 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
import { requireAdmin } from '@/lib/auth/require-admin' import { requireAdmin } from '@/lib/auth/require-admin'
import { asAdmin } from '@/lib/db/with-user' import { asAdmin } from '@/lib/db/with-user'
import { trucks, incidents, sites } from '@/lib/db/schema' import { trucks, incidents } from '@/lib/db/schema'
import { parseSiteId } from '@/lib/admin/truck-input'
import { writeAuditLog } from '@/lib/db/audit' import { writeAuditLog } from '@/lib/db/audit'
import { and, eq, sql } from 'drizzle-orm' import { eq, sql } from 'drizzle-orm'
async function activeSiteExists(id: string): Promise<boolean> {
const [row] = await asAdmin(db =>
db.select({ id: sites.id }).from(sites).where(and(eq(sites.id, id), eq(sites.active, true))).limit(1)
)
return !!row
}
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
const { session } = await requireAdmin() const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const body: { truck_no?: string; carrier?: string; site_id?: unknown } = await request.json().catch(() => ({})) const body: { truck_no?: string; carrier?: string } = await request.json().catch(() => ({}))
const truck_no = (body.truck_no ?? '').trim() const truck_no = (body.truck_no ?? '').trim()
if (!truck_no) return NextResponse.json({ error: 'truck_no required' }, { status: 422 }) if (!truck_no) return NextResponse.json({ error: 'truck_no required' }, { status: 422 })
const parsedSite = parseSiteId(body.site_id)
if (!parsedSite.ok) return NextResponse.json({ error: 'site_id invalid' }, { status: 422 })
const siteId = parsedSite.value ?? null
if (siteId && !(await activeSiteExists(siteId)))
return NextResponse.json({ error: 'Site not found or inactive' }, { status: 422 })
const carrier = (body.carrier ?? '').trim() || null
try { try {
let truckId: string | undefined let truckId: string | undefined
await asAdmin(async db => { await asAdmin(async db => {
await db.transaction(async tx => { await db.transaction(async tx => {
await tx.execute(sql`SELECT set_config('app.user_id', ${session.sub}, true)`) await tx.execute(sql`SELECT set_config('app.user_id', ${session.sub}, true)`)
const [truck] = await tx.insert(trucks).values({ truckNo: truck_no, carrier, siteId }).returning({ id: trucks.id }) const [truck] = await tx.insert(trucks).values({ truckNo: truck_no, carrier: (body.carrier ?? '').trim() || null }).returning({ id: trucks.id })
if (!truck) throw new Error('Insert failed') if (!truck) throw new Error('Insert failed')
truckId = truck.id truckId = truck.id
await writeAuditLog(tx, 'trucks', truck.id, 'INSERT', { truck_no, carrier, site_id: siteId }) await writeAuditLog(tx, 'trucks', truck.id, 'INSERT', { truck_no, carrier: (body.carrier ?? '').trim() || null })
}) })
}) })
if (!truckId) return NextResponse.json({ error: 'Insert failed' }, { status: 400 }) if (!truckId) return NextResponse.json({ error: 'Insert failed' }, { status: 400 })
@@ -57,46 +41,21 @@ export async function PATCH(request: NextRequest) {
const { session } = await requireAdmin() const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const body: { const body: { id?: string; active?: boolean } = await request.json().catch(() => ({}))
id?: string
active?: boolean
truck_no?: string
carrier?: string | null
site_id?: unknown
} = await request.json().catch(() => ({}))
if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 }) if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 })
const set: { active?: boolean; truckNo?: string; carrier?: string | null; siteId?: string | null } = {}
if (typeof body.active === 'boolean') set.active = body.active
if (body.truck_no !== undefined) {
const no = String(body.truck_no).trim()
if (!no) return NextResponse.json({ error: 'truck_no required' }, { status: 422 })
set.truckNo = no
}
if (body.carrier !== undefined) set.carrier = (body.carrier ?? '').trim() || null
const parsedSite = parseSiteId(body.site_id)
if (!parsedSite.ok) return NextResponse.json({ error: 'site_id invalid' }, { status: 422 })
if (parsedSite.value !== undefined) set.siteId = parsedSite.value
if (Object.keys(set).length === 0)
return NextResponse.json({ error: 'nothing to update' }, { status: 422 })
const [before] = await asAdmin(db => const [before] = await asAdmin(db =>
db.select().from(trucks).where(eq(trucks.id, body.id!)).limit(1) db.select().from(trucks).where(eq(trucks.id, body.id!)).limit(1)
) )
if (set.siteId && set.siteId !== before?.siteId && !(await activeSiteExists(set.siteId)))
return NextResponse.json({ error: 'Site not found or inactive' }, { status: 422 })
try { try {
await asAdmin(async db => { await asAdmin(async db => {
await db.transaction(async tx => { await db.transaction(async tx => {
await tx.execute(sql`SELECT set_config('app.user_id', ${session.sub}, true)`) await tx.execute(sql`SELECT set_config('app.user_id', ${session.sub}, true)`)
await tx.update(trucks).set(set).where(eq(trucks.id, body.id!)) await tx.update(trucks).set({ active: body.active }).where(eq(trucks.id, body.id!))
await writeAuditLog(tx, 'trucks', body.id!, 'admin_update', set, before ?? null) await writeAuditLog(tx, 'trucks', body.id!, 'admin_update', { active: body.active }, before ?? null)
}) })
}) })
} catch (e) { } catch {
const code = (e as { code?: string }).code
if (code === '23505') return NextResponse.json({ error: 'Truck number already exists' }, { status: 409 })
return NextResponse.json({ error: 'Update failed' }, { status: 500 }) return NextResponse.json({ error: 'Update failed' }, { status: 500 })
} }
return NextResponse.json({ ok: true }) return NextResponse.json({ ok: true })
+2 -2
View File
@@ -69,7 +69,7 @@ export async function POST(request: NextRequest) {
name: body.name ?? '', name: body.name ?? '',
email, email,
phone: (body.phone ?? '').trim() || null, phone: (body.phone ?? '').trim() || null,
role: (body.role as typeof users.$inferInsert['role']) ?? 'ssa', role: (body.role as typeof users.$inferInsert['role']) ?? 'reporter',
siteId: body.site_id ?? null, siteId: body.site_id ?? null,
department: body.department ?? null, department: body.department ?? null,
passwordHash, passwordHash,
@@ -78,7 +78,7 @@ export async function POST(request: NextRequest) {
if (!created) throw new Error('User creation failed') if (!created) throw new Error('User creation failed')
createdId = created.id createdId = created.id
await writeAuditLog(tx, 'users', created.id, 'created', { await writeAuditLog(tx, 'users', created.id, 'created', {
email, role: body.role ?? 'ssa', site_id: body.site_id ?? null, email, role: body.role ?? 'reporter', site_id: body.site_id ?? null,
}) })
}) })
}) })
+3 -8
View File
@@ -50,7 +50,7 @@ export async function GET(
const role = session.role const role = session.role
const isOwner = row.ownerUserId === session.sub const isOwner = row.ownerUserId === session.sub
const canRead = ['hse', 'admin', 'ssa'].includes(role) || isOwner const canRead = ['hse', 'admin', 'supervisor'].includes(role) || isOwner
if (!canRead) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) if (!canRead) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const ownerField = ['hse', 'admin'].includes(role) const ownerField = ['hse', 'admin'].includes(role)
@@ -105,13 +105,6 @@ export async function PATCH(
const body = await request.json() const body = await request.json()
if (body.status === 'pending_verification') {
return NextResponse.json(
{ error: 'Use POST /api/capa/[id]/submit to submit for verification' },
{ status: 403 },
)
}
const privilegedStatuses = ['verified', 'reopened', 'closed'] const privilegedStatuses = ['verified', 'reopened', 'closed']
if (body.status && privilegedStatuses.includes(body.status) && !['hse', 'admin'].includes(role)) { if (body.status && privilegedStatuses.includes(body.status) && !['hse', 'admin'].includes(role)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
@@ -129,12 +122,14 @@ export async function PATCH(
if ('department' in body && allowed.includes('department')) updateSet.department = body.department if ('department' in body && allowed.includes('department')) updateSet.department = body.department
if ('root_cause_ref' in body && allowed.includes('root_cause_ref')) updateSet.rootCauseRef = body.root_cause_ref if ('root_cause_ref' in body && allowed.includes('root_cause_ref')) updateSet.rootCauseRef = body.root_cause_ref
if ('owner_notes' in body && allowed.includes('owner_notes')) updateSet.ownerNotes = body.owner_notes if ('owner_notes' in body && allowed.includes('owner_notes')) updateSet.ownerNotes = body.owner_notes
if (body.status === 'pending_verification') updateSet.completedAt = new Date()
// Build audit new/old value from original snake_case body keys for consistency // Build audit new/old value from original snake_case body keys for consistency
const auditNew: Record<string, unknown> = {} const auditNew: Record<string, unknown> = {}
for (const key of allowed) { for (const key of allowed) {
if (key in body) auditNew[key] = body[key] if (key in body) auditNew[key] = body[key]
} }
if (body.status === 'pending_verification') auditNew.completed_at = updateSet.completedAt?.toISOString()
await withUser(session.sub, async tx => { await withUser(session.sub, async tx => {
let oldNotes: string | null = null let oldNotes: string | null = null
-98
View File
@@ -1,98 +0,0 @@
export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { and, eq } from 'drizzle-orm'
import { getSession } from '@/lib/auth/get-session'
import { withUser } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit'
import { capaActions, evidenceFiles } from '@/lib/db/schema'
import { uploadEvidenceFile } from '@/lib/storage/evidence'
import { validateCapaSubmission } from '@/lib/capa/submit-validation'
class StatusConflict extends Error {}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const [capa] = await withUser(session.sub, async tx =>
tx.select({
incidentId: capaActions.incidentId,
ownerUserId: capaActions.ownerUserId,
status: capaActions.status,
}).from(capaActions).where(eq(capaActions.id, id)).limit(1)
)
if (!capa) return NextResponse.json({ error: 'Not found' }, { status: 404 })
const isElevated = ['hse', 'admin'].includes(session.role)
if (capa.ownerUserId !== session.sub && !isElevated)
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
if (capa.status !== 'in_progress')
return NextResponse.json({ error: 'CAPA must be in_progress' }, { status: 409 })
const form = await request.formData()
const files = form.getAll('files').filter((f): f is File => f instanceof File)
const check = validateCapaSubmission(String(form.get('note') ?? ''), files)
if (!check.ok)
return NextResponse.json({ error: 'Validation failed', details: check.errors }, { status: 422 })
const uploaded: Array<{ publicUrl: string; hash: string; type: string }> = []
try {
for (const file of files) {
const { publicUrl, hash } = await uploadEvidenceFile(file, capa.incidentId, 'capa', session.sub)
uploaded.push({ publicUrl, hash, type: file.type })
}
} catch (err) {
return NextResponse.json(
{ error: 'Photo upload failed', details: [err instanceof Error ? err.message : 'unknown error'] },
{ status: 422 },
)
}
const completedAt = new Date()
try {
await withUser(session.sub, async tx => {
const updated = await tx.update(capaActions).set({
status: 'pending_verification',
ownerNotes: check.note,
completedAt,
}).where(and(eq(capaActions.id, id), eq(capaActions.status, 'in_progress')))
.returning({ id: capaActions.id })
if (updated.length === 0) throw new StatusConflict()
const rows = await tx.insert(evidenceFiles).values(
uploaded.map(u => ({
incidentId: capa.incidentId,
capaId: id,
stage: 'capa' as const,
fileUrl: u.publicUrl,
fileType: u.type,
fileHash: u.hash,
uploadedBy: session.sub,
}))
).returning({ id: evidenceFiles.id })
await writeAuditLog(
tx, 'capa_actions', id, 'submitted_for_verification',
{
status: 'pending_verification',
owner_notes: check.note,
completed_at: completedAt.toISOString(),
evidence_file_ids: rows.map(r => r.id),
},
{ status: 'in_progress' },
)
})
} catch (err) {
if (err instanceof StatusConflict)
return NextResponse.json({ error: 'CAPA must be in_progress' }, { status: 409 })
throw err
}
return NextResponse.json({ ok: true })
}
+1 -1
View File
@@ -40,7 +40,7 @@ export async function GET() {
.leftJoin(incidents, eq(capaActions.incidentId, incidents.id)) .leftJoin(incidents, eq(capaActions.incidentId, incidents.id))
.orderBy(asc(capaActions.dueDate)) .orderBy(asc(capaActions.dueDate))
if (session.role === 'ssa') { if (session.role === 'supervisor' || session.role === 'worker') {
q = q.where(eq(capaActions.ownerUserId, session.sub)) as typeof q q = q.where(eq(capaActions.ownerUserId, session.sub)) as typeof q
} }
+6 -4
View File
@@ -6,7 +6,8 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit' import { writeAuditLog } from '@/lib/db/audit'
import { incidents, sites, zones, auditLog } from '@/lib/db/schema' import { incidents, sites, zones, auditLog } from '@/lib/db/schema'
import { eq, and, gte, desc } from 'drizzle-orm' import { eq, and, gte, desc } from 'drizzle-orm'
import { createLocalLLMClient } from '@/lib/claude/client' import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
type ZoneAggregate = { type ZoneAggregate = {
zone: string zone: string
@@ -102,12 +103,13 @@ export async function POST() {
return NextResponse.json({ error: 'Rate limit: wait 60 seconds between AI requests' }, { status: 429 }) return NextResponse.json({ error: 'Rate limit: wait 60 seconds between AI requests' }, { status: 429 })
} }
const client = createLocalLLMClient() const deepseekKey = await getApiKey('DEEPSEEK_API_KEY')
const client = createDeepSeekClient(deepseekKey)
let res: Awaited<ReturnType<typeof client.chat.completions.create>> let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try { try {
res = await client.chat.completions.create({ res = await client.chat.completions.create({
model: 'qwen2.5-coder-32b-instruct-Q4_K_M', model: 'deepseek-v4-pro',
max_tokens: 2048, max_tokens: 2048,
messages: [ messages: [
{ {
@@ -166,7 +168,7 @@ Flag only zones with rising or elevated risk (at most 5 flags; do not flag healt
await withUser(session.sub, async tx => await withUser(session.sub, async tx =>
writeAuditLog(tx, 'incidents', session.sub, 'ai_risk_flags', writeAuditLog(tx, 'incidents', session.sub, 'ai_risk_flags',
{ flags, summary: input.summary, model: 'qwen2.5-coder-32b-instruct-Q4_K_M' }) { flags, summary: input.summary, model: 'deepseek-v4-pro' })
) )
return NextResponse.json({ flags, summary: input.summary }) return NextResponse.json({ flags, summary: input.summary })
+2 -2
View File
@@ -15,7 +15,7 @@ export async function GET(
const { id } = await params const { id } = await params
const session = await getSession() const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin', 'ssa'].includes(session.role)) if (!['hse', 'admin', 'supervisor'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const authorAlias = aliasedTable(users, 'author_user') const authorAlias = aliasedTable(users, 'author_user')
@@ -45,7 +45,7 @@ export async function POST(
const { id } = await params const { id } = await params
const session = await getSession() const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin', 'ssa'].includes(session.role)) if (!['hse', 'admin', 'supervisor'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const body: { body?: string } = await request.json().catch(() => ({})) const body: { body?: string } = await request.json().catch(() => ({}))
+6 -4
View File
@@ -6,7 +6,8 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit' import { writeAuditLog } from '@/lib/db/audit'
import { incidents, auditLog, sites, zones } from '@/lib/db/schema' import { incidents, auditLog, sites, zones } from '@/lib/db/schema'
import { eq, and, gte, sql } from 'drizzle-orm' import { eq, and, gte, sql } from 'drizzle-orm'
import { createLocalLLMClient } from '@/lib/claude/client' import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
export async function POST( export async function POST(
_request: NextRequest, _request: NextRequest,
@@ -31,7 +32,8 @@ export async function POST(
if (Number(rateRow?.cnt ?? 0) > 0) if (Number(rateRow?.cnt ?? 0) > 0)
return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 }) return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 })
const client = createLocalLLMClient() const deepseekKey = await getApiKey('DEEPSEEK_API_KEY')
const client = createDeepSeekClient(deepseekKey)
const [incident] = await withUser(session.sub, async tx => const [incident] = await withUser(session.sub, async tx =>
tx.select({ tx.select({
@@ -57,7 +59,7 @@ export async function POST(
let res: Awaited<ReturnType<typeof client.chat.completions.create>> let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try { try {
res = await client.chat.completions.create({ res = await client.chat.completions.create({
model: 'qwen2.5-coder-32b-instruct-Q4_K_M', model: 'deepseek-v4-pro',
max_tokens: 2048, max_tokens: 2048,
messages: [ messages: [
{ {
@@ -105,7 +107,7 @@ Provide 3–5 Why steps drilling from immediate cause to root cause. Frame CAPA
await withUser(session.sub, async tx => { await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'incidents', id, 'ai_rca_draft', { await writeAuditLog(tx, 'incidents', id, 'ai_rca_draft', {
root_cause_summary: draft.root_cause_summary as string, root_cause_summary: draft.root_cause_summary as string,
model: 'qwen2.5-coder-32b-instruct-Q4_K_M', model: 'deepseek-v4-pro',
}) })
}) })
@@ -6,7 +6,8 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit' import { writeAuditLog } from '@/lib/db/audit'
import { incidents, auditLog } from '@/lib/db/schema' import { incidents, auditLog } from '@/lib/db/schema'
import { eq, and, gte, sql } from 'drizzle-orm' import { eq, and, gte, sql } from 'drizzle-orm'
import { createLocalLLMClient } from '@/lib/claude/client' import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
export async function POST( export async function POST(
_request: NextRequest, _request: NextRequest,
@@ -31,7 +32,8 @@ export async function POST(
if (Number(rateRow?.cnt ?? 0) > 0) if (Number(rateRow?.cnt ?? 0) > 0)
return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 }) return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 })
const client = createLocalLLMClient() const deepseekKey = await getApiKey('DEEPSEEK_API_KEY')
const client = createDeepSeekClient(deepseekKey)
const [incident] = await withUser(session.sub, async tx => const [incident] = await withUser(session.sub, async tx =>
tx.select({ tx.select({
@@ -48,7 +50,7 @@ export async function POST(
let res: Awaited<ReturnType<typeof client.chat.completions.create>> let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try { try {
res = await client.chat.completions.create({ res = await client.chat.completions.create({
model: 'qwen2.5-coder-32b-instruct-Q4_K_M', model: 'deepseek-v4-pro',
max_tokens: 1024, max_tokens: 1024,
messages: [ messages: [
{ {
@@ -103,7 +105,7 @@ Output exactly this JSON structure:
} }
await withUser(session.sub, async tx => { await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'incidents', id, 'ai_triage_suggest', { suggestion: input, model: 'qwen2.5-coder-32b-instruct-Q4_K_M' }) await writeAuditLog(tx, 'incidents', id, 'ai_triage_suggest', { suggestion: input, model: 'deepseek-v4-pro' })
}) })
return NextResponse.json(input) return NextResponse.json(input)
+1 -1
View File
@@ -51,7 +51,7 @@ export async function POST(
await createInAppNotifications([{ await createInAppNotifications([{
userId: incident.reportedBy, userId: incident.reportedBy,
title: `Your incident report ${incident.referenceNo ?? ''} has been closed`, title: `Your incident report ${incident.referenceNo ?? ''} has been closed`,
link: '/ssa/my-reports', link: '/reporter',
incidentId: id, incidentId: id,
}]) }])
} }
+1 -1
View File
@@ -46,7 +46,7 @@ export async function GET(_req: Request, { params }: { params: Promise<{ id: str
if (!incident) return NextResponse.json({ error: 'Not found' }, { status: 404 }) if (!incident) return NextResponse.json({ error: 'Not found' }, { status: 404 })
const isOwner = incident.reporterId === session.sub const isOwner = incident.reporterId === session.sub
const isSiteStaff = ['hse', 'ssa', 'admin'].includes(session.role) const isSiteStaff = ['hse', 'supervisor', 'admin'].includes(session.role)
if (!isOwner && !isSiteStaff) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) if (!isOwner && !isSiteStaff) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const evidenceFileRows = await withUser(session.sub, async tx => const evidenceFileRows = await withUser(session.sub, async tx =>
+6 -4
View File
@@ -6,7 +6,8 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit' import { writeAuditLog } from '@/lib/db/audit'
import { auditLog } from '@/lib/db/schema' import { auditLog } from '@/lib/db/schema'
import { eq, and, gte, sql } from 'drizzle-orm' import { eq, and, gte, sql } from 'drizzle-orm'
import { createLocalLLMClient } from '@/lib/claude/client' import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
const session = await getSession() const session = await getSession()
@@ -25,7 +26,8 @@ export async function POST(request: NextRequest) {
if (Number(rateRow?.cnt ?? 0) > 0) if (Number(rateRow?.cnt ?? 0) > 0)
return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 }) return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 })
const client = createLocalLLMClient() const deepseekKey = await getApiKey('DEEPSEEK_API_KEY')
const client = createDeepSeekClient(deepseekKey)
let body: { description?: string; incident_type?: string } let body: { description?: string; incident_type?: string }
try { try {
@@ -40,7 +42,7 @@ export async function POST(request: NextRequest) {
let res: Awaited<ReturnType<typeof client.chat.completions.create>> let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try { try {
res = await client.chat.completions.create({ res = await client.chat.completions.create({
model: 'qwen2.5-coder-32b-instruct-Q4_K_M', model: 'deepseek-v4-pro',
max_tokens: 1024, max_tokens: 1024,
messages: [ messages: [
{ {
@@ -87,7 +89,7 @@ Scoring criteria: specificity (location, time, persons involved), completeness (
await withUser(session.sub, async tx => { await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'incidents', session.sub, 'ai_quality_check', { await writeAuditLog(tx, 'incidents', session.sub, 'ai_quality_check', {
score: input.score, passes: input.passes, model: 'qwen2.5-coder-32b-instruct-Q4_K_M', score: input.score, passes: input.passes, model: 'deepseek-v4-pro',
}) })
}) })
+4 -12
View File
@@ -188,7 +188,7 @@ async function handlePost(request: Request) {
db.select({ id: users.id, phone: users.phone }) db.select({ id: users.id, phone: users.phone })
.from(users) .from(users)
.where(and( .where(and(
inArray(users.role, ['ssa', 'hse']), inArray(users.role, ['supervisor', 'hse']),
eq(users.siteId, zone.siteId), eq(users.siteId, zone.siteId),
)) ))
) )
@@ -212,9 +212,8 @@ async function handlePost(request: Request) {
} }
})() })()
// Embed description asynchronously (disabled if no GOOGLE_AI_API_KEY) // Embed description asynchronously
getApiKey('GOOGLE_AI_API_KEY') getApiKey('GOOGLE_AI_API_KEY').then(googleAiKey =>
.then(googleAiKey =>
import('@/lib/claude/embed').then(({ embedText }) => import('@/lib/claude/embed').then(({ embedText }) =>
embedText(input.description.trim(), googleAiKey).then(embeddingVec => { embedText(input.description.trim(), googleAiKey).then(embeddingVec => {
const embStr = `[${(embeddingVec as number[]).join(',')}]` const embStr = `[${(embeddingVec as number[]).join(',')}]`
@@ -223,14 +222,7 @@ async function handlePost(request: Request) {
) )
}) })
) )
) ).catch(err => console.error('embed error:', err))
.catch(err => {
if (String(err).includes('GOOGLE_AI_API_KEY')) {
console.debug('Embeddings disabled: GOOGLE_AI_API_KEY not configured')
} else {
console.error('Embed error:', err)
}
})
return NextResponse.json({ id: incidentId, reference_no: referenceNo }, { status: 201 }) return NextResponse.json({ id: incidentId, reference_no: referenceNo }, { status: 201 })
} }
-3
View File
@@ -17,9 +17,6 @@ const geistMono = Geist_Mono({
export const metadata: Metadata = { export const metadata: Metadata = {
title: 'IMS — HSE Incident Management', title: 'IMS — HSE Incident Management',
description: 'Setia Corporation HSE Incident Management System', description: 'Setia Corporation HSE Incident Management System',
icons: {
icon: '/favicon.ico',
},
} }
export default async function RootLayout({ export default async function RootLayout({
+6 -29
View File
@@ -3,9 +3,8 @@ export const dynamic = 'force-dynamic'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
import { asAdmin } from '@/lib/db/with-user' import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session' import { getSession } from '@/lib/auth/get-session'
import { zones, sites, trucks, users } from '@/lib/db/schema' import { zones, sites, trucks } from '@/lib/db/schema'
import { eq, asc, and } from 'drizzle-orm' import { eq, asc } from 'drizzle-orm'
import { groupSites } from '@/lib/report/zones'
import { ReportForm } from '@/components/incidents/report-form' import { ReportForm } from '@/components/incidents/report-form'
import { LanguageSwitcher } from '@/components/language-switcher' import { LanguageSwitcher } from '@/components/language-switcher'
import { OfflineSync } from '@/components/incidents/offline-sync' import { OfflineSync } from '@/components/incidents/offline-sync'
@@ -44,7 +43,6 @@ export default async function ReportPage({ searchParams }: Props) {
id: trucks.id, id: trucks.id,
truckNo: trucks.truckNo, truckNo: trucks.truckNo,
carrier: trucks.carrier, carrier: trucks.carrier,
siteId: trucks.siteId,
}) })
.from(trucks) .from(trucks)
.where(eq(trucks.active, true)) .where(eq(trucks.active, true))
@@ -55,29 +53,8 @@ export default async function ReportPage({ searchParams }: Props) {
id: t.id, id: t.id,
truck_no: t.truckNo, truck_no: t.truckNo,
carrier: t.carrier ?? null, carrier: t.carrier ?? null,
site_id: t.siteId ?? null,
})) }))
const zoneRows = await asAdmin(db =>
db.select({
siteId: sites.id,
siteName: sites.name,
zoneId: zones.id,
zoneName: zones.name,
token: zones.qrCodeToken,
})
.from(zones)
.innerJoin(sites, eq(zones.siteId, sites.id))
.where(and(eq(zones.active, true), eq(sites.active, true)))
.orderBy(asc(sites.name), asc(zones.name))
)
const siteOptions = groupSites(zoneRows)
const [me] = await asAdmin(db =>
db.select({ siteId: users.siteId }).from(users).where(eq(users.id, session.sub)).limit(1)
)
const defaultSiteId = me?.siteId ?? ''
return ( return (
<main className="min-h-screen bg-gray-50 py-6 px-4 max-w-lg mx-auto"> <main className="min-h-screen bg-gray-50 py-6 px-4 max-w-lg mx-auto">
<div className="mb-6"> <div className="mb-6">
@@ -85,18 +62,18 @@ export default async function ReportPage({ searchParams }: Props) {
<h1 className="text-2xl font-bold text-gray-900">{/* will be translated via ReportForm */}Report an Incident</h1> <h1 className="text-2xl font-bold text-gray-900">{/* will be translated via ReportForm */}Report an Incident</h1>
<LanguageSwitcher /> <LanguageSwitcher />
</div> </div>
{zoneName && ( {zoneName ? (
<p className="text-sm text-gray-600 mt-1"> <p className="text-sm text-gray-600 mt-1">
{siteName ?? 'Unknown Site'} — {zoneName} {siteName ?? 'Unknown Site'} — {zoneName}
</p> </p>
) : (
<p className="text-sm text-accent-700 mt-1">No zone detected — zone will not be recorded</p>
)} )}
</div> </div>
<ReportForm <ReportForm
zoneToken={zoneName ? (zone ?? null) : null} zoneToken={zone ?? null}
zoneName={zoneName} zoneName={zoneName}
siteName={siteName} siteName={siteName}
sites={siteOptions}
defaultSiteId={defaultSiteId}
trucks={truckList} trucks={truckList}
initialTruckId={truck_id ?? null} initialTruckId={truck_id ?? null}
/> />
+1 -1
View File
@@ -19,7 +19,7 @@ export default async function ReportSuccessPage({ searchParams }: Props) {
</p> </p>
)} )}
<p className="text-sm text-gray-500 mb-6"> <p className="text-sm text-gray-500 mb-6">
The Site Safety Assistants and HSE officer have been notified. The supervisor and HSE officer have been notified.
</p> </p>
<Link href="/report" className="text-sm text-accent-700 hover:underline"> <Link href="/report" className="text-sm text-accent-700 hover:underline">
Submit another report Submit another report
+3 -4
View File
@@ -3,7 +3,7 @@
import { useState } from 'react' import { useState } from 'react'
import { UserManager, type AdminUser, type SiteOption } from './user-manager' import { UserManager, type AdminUser, type SiteOption } from './user-manager'
import { SiteZoneManager, type SiteWithZones } from './site-zone-manager' import { SiteZoneManager, type SiteWithZones } from './site-zone-manager'
import { TruckManager, type Truck, type TruckSite } from './truck-manager' import { TruckManager, type Truck } from './truck-manager'
type Tab = 'users' | 'sites' | 'trucks' type Tab = 'users' | 'sites' | 'trucks'
@@ -12,10 +12,9 @@ interface Props {
sites: SiteWithZones[] sites: SiteWithZones[]
siteOptions: SiteOption[] siteOptions: SiteOption[]
trucks: Truck[] trucks: Truck[]
truckSites: TruckSite[]
} }
export function AdminPanel({ users, sites, siteOptions, trucks, truckSites }: Props) { export function AdminPanel({ users, sites, siteOptions, trucks }: Props) {
const [tab, setTab] = useState<Tab>('users') const [tab, setTab] = useState<Tab>('users')
const tabs: { id: Tab; label: string; count: number }[] = [ const tabs: { id: Tab; label: string; count: number }[] = [
@@ -46,7 +45,7 @@ export function AdminPanel({ users, sites, siteOptions, trucks, truckSites }: Pr
</div> </div>
{tab === 'users' && <UserManager users={users} sites={siteOptions} />} {tab === 'users' && <UserManager users={users} sites={siteOptions} />}
{tab === 'sites' && <SiteZoneManager sites={sites} />} {tab === 'sites' && <SiteZoneManager sites={sites} />}
{tab === 'trucks' && <TruckManager trucks={trucks} sites={truckSites} />} {tab === 'trucks' && <TruckManager trucks={trucks} />}
</div> </div>
) )
} }
+4 -88
View File
@@ -9,20 +9,16 @@ export type Truck = {
id: string id: string
truck_no: string truck_no: string
carrier: string | null carrier: string | null
site_id: string | null
active: boolean active: boolean
} }
export type TruckSite = { id: string; name: string; active: boolean }
interface Props { interface Props {
trucks: Truck[] trucks: Truck[]
sites: TruckSite[]
} }
const lbl = 'block text-xs font-medium text-gray-600 mb-1' const lbl = 'block text-xs font-medium text-gray-600 mb-1'
export function TruckManager({ trucks, sites }: Props) { export function TruckManager({ trucks }: Props) {
const router = useRouter() const router = useRouter()
const [truckNo, setTruckNo] = useState('') const [truckNo, setTruckNo] = useState('')
const [carrier, setCarrier] = useState('') const [carrier, setCarrier] = useState('')
@@ -31,22 +27,6 @@ export function TruckManager({ trucks, sites }: Props) {
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [showAdd, setShowAdd] = useState(false) const [showAdd, setShowAdd] = useState(false)
const [confirmDelete, setConfirmDelete] = useState<Truck | null>(null) const [confirmDelete, setConfirmDelete] = useState<Truck | null>(null)
const [siteId, setSiteId] = useState('')
const [editing, setEditing] = useState<Truck | null>(null)
const [editNo, setEditNo] = useState('')
const [editCarrier, setEditCarrier] = useState('')
const [editSiteId, setEditSiteId] = useState('')
const siteName = (id: string | null) => sites.find(s => s.id === id)?.name ?? null
const siteChoices = (currentId: string) => sites.filter(s => s.active || s.id === currentId)
const openEdit = (tk: Truck) => {
setEditing(tk)
setEditNo(tk.truck_no)
setEditCarrier(tk.carrier ?? '')
setEditSiteId(tk.site_id ?? '')
setError(null)
}
const handleAdd = async () => { const handleAdd = async () => {
const no = truckNo.trim() const no = truckNo.trim()
@@ -57,13 +37,12 @@ export function TruckManager({ trucks, sites }: Props) {
const res = await fetch('/api/admin/trucks', { const res = await fetch('/api/admin/trucks', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ truck_no: no, carrier: carrier.trim() || null, site_id: siteId || null }), body: JSON.stringify({ truck_no: no, carrier: carrier.trim() || null }),
}) })
const data = await res.json() const data = await res.json()
if (!res.ok) { setError(data.error ?? 'Failed to add truck'); return } if (!res.ok) { setError(data.error ?? 'Failed to add truck'); return }
setTruckNo('') setTruckNo('')
setCarrier('') setCarrier('')
setSiteId('')
setShowAdd(false) setShowAdd(false)
router.refresh() router.refresh()
} catch { } catch {
@@ -103,19 +82,6 @@ export function TruckManager({ trucks, sites }: Props) {
setConfirmDelete(null) setConfirmDelete(null)
} }
const handleSaveEdit = async () => {
if (!editing) return
const no = editNo.trim()
if (!no) return
const ok = await send('PATCH', {
id: editing.id,
truck_no: no,
carrier: editCarrier.trim() || null,
site_id: editSiteId || null,
})
if (ok) setEditing(null)
}
return ( return (
<div className="bg-surface border border-divider shadow-sm overflow-hidden"> <div className="bg-surface border border-divider shadow-sm overflow-hidden">
<div className="flex items-center justify-between px-5 py-4 border-b border-divider"> <div className="flex items-center justify-between px-5 py-4 border-b border-divider">
@@ -140,15 +106,8 @@ export function TruckManager({ trucks, sites }: Props) {
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<span className="text-sm font-semibold text-gray-900">{tk.truck_no}</span> <span className="text-sm font-semibold text-gray-900">{tk.truck_no}</span>
{tk.carrier && <span className="text-xs text-gray-400">{tk.carrier}</span>} {tk.carrier && <span className="text-xs text-gray-400">{tk.carrier}</span>}
<span className={`text-xs px-2 py-0.5 ${tk.site_id ? 'bg-neutral-100 text-ink' : 'bg-gray-100 text-gray-500'}`}>
{siteName(tk.site_id) ?? 'Unassigned'}
</span>
</div> </div>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<button disabled={busyId === tk.id} onClick={() => openEdit(tk)}
className="text-xs text-accent-700 hover:underline cursor-pointer disabled:opacity-50">
Edit
</button>
<a href={`/report?truck_id=${tk.id}`} target="_blank" <a href={`/report?truck_id=${tk.id}`} target="_blank"
className="text-xs text-accent-700 hover:underline cursor-pointer"> className="text-xs text-accent-700 hover:underline cursor-pointer">
Report link Report link
@@ -175,11 +134,11 @@ export function TruckManager({ trucks, sites }: Props) {
</div> </div>
{/* Add Truck Modal */} {/* Add Truck Modal */}
<Modal open={showAdd} onClose={() => { setShowAdd(false); setTruckNo(''); setCarrier(''); setSiteId(''); setError(null) }} <Modal open={showAdd} onClose={() => { setShowAdd(false); setTruckNo(''); setCarrier(''); setError(null) }}
title="Add Truck" width="sm" title="Add Truck" width="sm"
footer={ footer={
<> <>
<button onClick={() => { setShowAdd(false); setTruckNo(''); setCarrier(''); setSiteId(''); setError(null) }} <button onClick={() => { setShowAdd(false); setTruckNo(''); setCarrier(''); setError(null) }}
className="px-4 py-2 text-sm font-medium border border-divider text-gray-700 hover:bg-gray-50 cursor-pointer transition-colors"> className="px-4 py-2 text-sm font-medium border border-divider text-gray-700 hover:bg-gray-50 cursor-pointer transition-colors">
Cancel Cancel
</button> </button>
@@ -206,49 +165,6 @@ export function TruckManager({ trucks, sites }: Props) {
onKeyDown={e => e.key === 'Enter' && handleAdd()} onKeyDown={e => e.key === 'Enter' && handleAdd()}
className={inp} /> className={inp} />
</div> </div>
<div>
<label className={lbl} htmlFor="add-truck-site">Site</label>
<select id="add-truck-site" value={siteId} onChange={e => setSiteId(e.target.value)} className={inp}>
<option value="">No site</option>
{siteChoices('').map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select>
</div>
</div>
</Modal>
{/* Edit Truck Modal */}
<Modal open={!!editing} onClose={() => { setEditing(null); setError(null) }}
title="Edit Truck" width="sm"
footer={
<>
<button onClick={() => { setEditing(null); setError(null) }}
className="px-4 py-2 text-sm font-medium border border-divider text-gray-700 hover:bg-gray-50 cursor-pointer transition-colors">
Cancel
</button>
<button disabled={busyId === editing?.id || !editNo.trim()} onClick={handleSaveEdit}
className="px-4 py-2 bg-accent text-white text-sm font-semibold hover:bg-accent-600 disabled:opacity-50 cursor-pointer transition-colors">
{busyId === editing?.id ? 'Saving…' : 'Save'}
</button>
</>
}
>
{error && <p className="text-xs text-red-600 bg-red-50 px-3 py-2 mb-3">{error}</p>}
<div className="space-y-4">
<div>
<label className={lbl} htmlFor="edit-truck-no">Truck Number *</label>
<input id="edit-truck-no" type="text" value={editNo} onChange={e => setEditNo(e.target.value)} className={inp} />
</div>
<div>
<label className={lbl} htmlFor="edit-truck-carrier">Carrier (optional)</label>
<input id="edit-truck-carrier" type="text" value={editCarrier} onChange={e => setEditCarrier(e.target.value)} className={inp} />
</div>
<div>
<label className={lbl} htmlFor="edit-truck-site">Site</label>
<select id="edit-truck-site" value={editSiteId} onChange={e => setEditSiteId(e.target.value)} className={inp}>
<option value="">No site</option>
{siteChoices(editing?.site_id ?? '').map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select>
</div>
</div> </div>
</Modal> </Modal>
+4 -4
View File
@@ -2,7 +2,7 @@
import { useState } from 'react' import { useState } from 'react'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { ALL_ROLES, ROLE_LABELS, type UserRole } from '@/lib/auth/roles' import { ALL_ROLES, type UserRole } from '@/lib/auth/roles'
import { Modal } from '@/components/ui/modal' import { Modal } from '@/components/ui/modal'
import { INPUT_CLASS as inp } from '@/components/ui/field' import { INPUT_CLASS as inp } from '@/components/ui/field'
@@ -23,7 +23,7 @@ interface Props {
sites: SiteOption[] sites: SiteOption[]
} }
const EMPTY = { email: '', name: '', phone: '', role: 'ssa' as UserRole, site_id: '', password: '' } const EMPTY = { email: '', name: '', phone: '', role: 'reporter' as UserRole, site_id: '', password: '' }
const lbl = 'block text-xs font-medium text-gray-600 mb-1' const lbl = 'block text-xs font-medium text-gray-600 mb-1'
@@ -135,7 +135,7 @@ export function UserManager({ users, sites }: Props) {
<select value={u.role} disabled={busyId === u.id} <select value={u.role} disabled={busyId === u.id}
onChange={e => patchUser(u.id, { role: e.target.value })} onChange={e => patchUser(u.id, { role: e.target.value })}
className="border border-divider px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-accent cursor-pointer"> className="border border-divider px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-accent cursor-pointer">
{ALL_ROLES.map(r => <option key={r} value={r}>{ROLE_LABELS[r]}</option>)} {ALL_ROLES.map(r => <option key={r} value={r}>{r.replace(/_/g, ' ')}</option>)}
</select> </select>
</td> </td>
<td className="px-5 py-3"> <td className="px-5 py-3">
@@ -224,7 +224,7 @@ export function UserManager({ users, sites }: Props) {
<select id="au-role" value={form.role} <select id="au-role" value={form.role}
onChange={e => setForm(v => ({ ...v, role: e.target.value as UserRole }))} onChange={e => setForm(v => ({ ...v, role: e.target.value as UserRole }))}
className={inp}> className={inp}>
{ALL_ROLES.map(r => <option key={r} value={r}>{ROLE_LABELS[r]}</option>)} {ALL_ROLES.map(r => <option key={r} value={r}>{r.replace(/_/g, ' ')}</option>)}
</select> </select>
</div> </div>
<div> <div>
+5 -2
View File
@@ -3,7 +3,6 @@
import { useState } from 'react' import { useState } from 'react'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { SubmitVerificationForm } from '@/components/capa/submit-verification-form'
interface Props { interface Props {
capaId: string capaId: string
@@ -42,7 +41,11 @@ export function CapaOwnerActions({ capaId, currentStatus }: Props) {
} }
if (currentStatus === 'in_progress') { if (currentStatus === 'in_progress') {
return <SubmitVerificationForm capaId={capaId} /> return (
<Button onClick={() => updateStatus('pending_verification')} disabled={loading}>
{loading ? '…' : 'Submit for Verification'}
</Button>
)
} }
return null return null
@@ -1,108 +0,0 @@
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Field, Textarea } from '@/components/ui/field'
import { MAX_CAPA_PHOTOS, validateCapaSubmission } from '@/lib/capa/submit-validation'
interface Props {
capaId: string
}
export function SubmitVerificationForm({ capaId }: Props) {
const router = useRouter()
const [note, setNote] = useState('')
const [files, setFiles] = useState<File[]>([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const check = validateCapaSubmission(note, files)
function addFiles(list: FileList | null) {
if (!list) return
setFiles(prev => [...prev, ...Array.from(list)].slice(0, MAX_CAPA_PHOTOS))
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (!check.ok) return
setLoading(true)
setError(null)
try {
const fd = new FormData()
fd.append('note', check.note)
files.forEach(f => fd.append('files', f))
const res = await fetch(`/api/capa/${capaId}/submit`, { method: 'POST', body: fd })
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setError(Array.isArray(data.details) ? data.details.join('. ') : (data.error ?? 'Submit failed. Please try again.'))
setLoading(false)
return
}
router.refresh()
return
} catch {
setError('Network error. Please try again.')
}
setLoading(false)
}
return (
<form onSubmit={handleSubmit} className="space-y-3 rounded-xl bg-surface p-5 shadow-card">
<div>
<h2 className="text-sm font-semibold">Proof of completion</h2>
<p className="text-xs text-muted">Describe what was done and attach 1 to {MAX_CAPA_PHOTOS} photos as evidence.</p>
</div>
<Field label="Completion note" htmlFor={`note-${capaId}`}>
<Textarea
id={`note-${capaId}`}
value={note}
onChange={e => setNote(e.target.value)}
rows={3}
placeholder="What action was carried out?"
disabled={loading}
/>
</Field>
<Field label="Photos" htmlFor={`photos-${capaId}`}>
<input
id={`photos-${capaId}`}
type="file"
accept="image/*"
multiple
disabled={loading || files.length >= MAX_CAPA_PHOTOS}
onChange={e => { addFiles(e.target.files); e.target.value = '' }}
className="block w-full text-[13px] text-ink"
/>
</Field>
{files.length > 0 && (
<ul className="space-y-1">
{files.map((f, i) => (
<li key={`${f.name}-${i}`} className="flex items-center justify-between gap-2 text-[13px]">
<span className="truncate">{f.name}</span>
<button
type="button"
aria-label={`Remove ${f.name}`}
onClick={() => setFiles(prev => prev.filter((_, j) => j !== i))}
disabled={loading}
className="text-muted hover:text-ink"
>
<X size={14} strokeWidth={2} aria-hidden />
</button>
</li>
))}
</ul>
)}
{error && <p role="alert" className="text-xs text-danger">{error}</p>}
<Button type="submit" disabled={!check.ok || loading}>
{loading ? 'Submitting…' : 'Submit for Verification'}
</Button>
</form>
)
}
+5 -52
View File
@@ -5,20 +5,16 @@ import { useRouter } from 'next/navigation'
import { FileUpload } from '@/components/incidents/file-upload' import { FileUpload } from '@/components/incidents/file-upload'
import type { IncidentType, MedicalStatus } from '@/lib/incidents/validate' import type { IncidentType, MedicalStatus } from '@/lib/incidents/validate'
import { useTranslations } from '@/lib/i18n/context' import { useTranslations } from '@/lib/i18n/context'
import { zonesForSite, resolveZoneToken, type SiteOption } from '@/lib/report/zones'
import { siteForTruck } from '@/lib/report/trucks'
interface Props { interface Props {
zoneToken: string | null zoneToken: string | null
zoneName: string | null zoneName: string | null
siteName: string | null siteName: string | null
sites: SiteOption[] trucks: Array<{ id: string; truck_no: string; carrier: string | null }>
defaultSiteId: string
trucks: Array<{ id: string; truck_no: string; carrier: string | null; site_id: string | null }>
initialTruckId?: string | null initialTruckId?: string | null
} }
export function ReportForm({ zoneToken, sites, defaultSiteId, trucks, initialTruckId }: Props) { export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
const router = useRouter() const router = useRouter()
const t = useTranslations('ReportForm') const t = useTranslations('ReportForm')
const itLabels = useTranslations('IncidentType') const itLabels = useTranslations('IncidentType')
@@ -56,15 +52,6 @@ export function ReportForm({ zoneToken, sites, defaultSiteId, trucks, initialTru
} | null>(null) } | null>(null)
const [overrideQuality, setOverrideQuality] = useState(false) const [overrideQuality, setOverrideQuality] = useState(false)
const truckSite = !zoneToken ? siteForTruck(trucks, initialTruckId) : null
const [siteId, setSiteId] = useState(
truckSite && sites.some(s => s.id === truckSite)
? truckSite
: sites.some(s => s.id === defaultSiteId) ? defaultSiteId : (sites.length === 1 ? sites[0].id : '')
)
const [zoneId, setZoneId] = useState('')
const effectiveZoneToken = resolveZoneToken({ zoneToken, sites, zoneId })
const [form, setForm] = useState({ const [form, setForm] = useState({
incident_type: (initialTruckId ? 'transport' : '') as IncidentType | '', incident_type: (initialTruckId ? 'transport' : '') as IncidentType | '',
description: '', description: '',
@@ -126,7 +113,7 @@ export function ReportForm({ zoneToken, sites, defaultSiteId, trucks, initialTru
try { try {
const { addPendingReport } = await import('@/lib/offline/db') const { addPendingReport } = await import('@/lib/offline/db')
await addPendingReport({ await addPendingReport({
zone_token: effectiveZoneToken ?? '', zone_token: zoneToken ?? '',
incident_type: form.incident_type as IncidentType, incident_type: form.incident_type as IncidentType,
description: form.description, description: form.description,
injury_involved: form.injury_involved, injury_involved: form.injury_involved,
@@ -175,7 +162,7 @@ export function ReportForm({ zoneToken, sites, defaultSiteId, trucks, initialTru
try { try {
const fd = new FormData() const fd = new FormData()
if (effectiveZoneToken) fd.append('zone_token', effectiveZoneToken) if (zoneToken) fd.append('zone_token', zoneToken)
fd.append('incident_type', form.incident_type) fd.append('incident_type', form.incident_type)
fd.append('description', form.description) fd.append('description', form.description)
fd.append('injury_involved', String(form.injury_involved)) fd.append('injury_involved', String(form.injury_involved))
@@ -238,40 +225,6 @@ export function ReportForm({ zoneToken, sites, defaultSiteId, trucks, initialTru
</div> </div>
)} )}
{!zoneToken && (
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
{t.siteLabel} <span className="text-red-500">*</span>
</label>
<select
required
className="w-full border border-divider px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-accent"
value={siteId}
onChange={e => { setSiteId(e.target.value); setZoneId('') }}
>
<option value="">{t.sitePlaceholder}</option>
{sites.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
{t.zoneLabel} <span className="text-red-500">*</span>
</label>
<select
required
disabled={!siteId}
className="w-full border border-divider px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-accent disabled:opacity-50"
value={zoneId}
onChange={e => setZoneId(e.target.value)}
>
<option value="">{t.zonePlaceholder}</option>
{zonesForSite(sites, siteId).map(z => <option key={z.id} value={z.id}>{z.name}</option>)}
</select>
</div>
</div>
)}
<div> <div>
<label className="block text-sm font-medium text-gray-700 mb-1"> <label className="block text-sm font-medium text-gray-700 mb-1">
{t.incidentTypeLabel} <span className="text-red-500">*</span> {t.incidentTypeLabel} <span className="text-red-500">*</span>
@@ -429,7 +382,7 @@ export function ReportForm({ zoneToken, sites, defaultSiteId, trucks, initialTru
<button <button
type="submit" type="submit"
disabled={submitting || !effectiveZoneToken || !form.incident_type || (form.incident_type === 'transport' && !form.truck_id)} disabled={submitting || !form.incident_type || (form.incident_type === 'transport' && !form.truck_id)}
className="w-full bg-accent text-white py-3 font-medium text-sm className="w-full bg-accent text-white py-3 font-medium text-sm
hover:bg-accent-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors" hover:bg-accent-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
> >
+10 -8
View File
@@ -16,13 +16,14 @@ export interface NavItem {
} }
const NAV_ITEMS: Record<string, NavItem[]> = { const NAV_ITEMS: Record<string, NavItem[]> = {
ssa: [ reporter: [
{ label: 'Overview', href: '/ssa', icon: AlignLeft }, { label: 'My Reports', href: '/reporter', icon: ClipboardList },
{ label: 'My Reports', href: '/ssa/my-reports', icon: ClipboardList },
{ label: 'Site Incidents', href: '/ssa/incidents', icon: ClipboardList },
{ label: 'My CAPAs', href: '/ssa/capas', icon: CircleCheck },
{ label: 'New Incident', href: '/report', icon: Plus }, { label: 'New Incident', href: '/report', icon: Plus },
], ],
supervisor: [
{ label: 'Overview', href: '/supervisor', icon: AlignLeft },
{ label: 'Incidents', href: '/supervisor/incidents', icon: ClipboardList },
],
hse: [ hse: [
{ label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard }, { label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard },
{ label: 'Incidents', href: '/hse/incidents', icon: ClipboardList }, { label: 'Incidents', href: '/hse/incidents', icon: ClipboardList },
@@ -30,6 +31,7 @@ const NAV_ITEMS: Record<string, NavItem[]> = {
{ label: 'Settings', href: '/hse/settings', icon: Settings }, { label: 'Settings', href: '/hse/settings', icon: Settings },
], ],
management: [{ label: 'Dashboard', href: '/management', icon: LayoutDashboard }], management: [{ label: 'Dashboard', href: '/management', icon: LayoutDashboard }],
capa_owner: [{ label: 'My CAPAs', href: '/capa-owner', icon: CircleCheck }],
admin: [ admin: [
{ label: 'Admin', href: '/admin', icon: Users }, { label: 'Admin', href: '/admin', icon: Users },
{ label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard }, { label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard },
@@ -40,10 +42,10 @@ const NAV_ITEMS: Record<string, NavItem[]> = {
], ],
} }
const EXACT_ROOTS = ['/ssa', '/management', '/admin', '/report', '/account'] const EXACT_ROOTS = ['/reporter', '/supervisor', '/management', '/capa-owner', '/admin', '/report', '/account']
export function navItemsFor(role: string): NavItem[] { export function navItemsFor(role: string): NavItem[] {
return NAV_ITEMS[role] ?? NAV_ITEMS.ssa return NAV_ITEMS[role] ?? NAV_ITEMS.reporter
} }
export function isActivePath(href: string, pathname: string): boolean { export function isActivePath(href: string, pathname: string): boolean {
@@ -52,6 +54,6 @@ export function isActivePath(href: string, pathname: string): boolean {
export function searchHrefFor(role: string): string | null { export function searchHrefFor(role: string): string | null {
if (role === 'hse' || role === 'admin') return '/hse/incidents' if (role === 'hse' || role === 'admin') return '/hse/incidents'
if (role === 'ssa') return '/ssa/incidents' if (role === 'supervisor') return '/supervisor/incidents'
return null return null
} }
-5
View File
@@ -1,5 +0,0 @@
-- Apply by hand on the server DB with the owner's go-ahead. Not run by deploy.
BEGIN;
ALTER TABLE evidence_files ADD COLUMN IF NOT EXISTS capa_id UUID REFERENCES capa_actions(id) ON DELETE RESTRICT;
CREATE INDEX IF NOT EXISTS evidence_files_capa_id_idx ON evidence_files(capa_id);
COMMIT;
-5
View File
@@ -1,5 +0,0 @@
-- Apply by hand on the server DB with the owner's go-ahead. Not run by deploy.
BEGIN;
ALTER TABLE trucks ADD COLUMN IF NOT EXISTS site_id UUID REFERENCES sites(id);
CREATE INDEX IF NOT EXISTS trucks_site_id_idx ON trucks(site_id);
COMMIT;
-166
View File
@@ -1,166 +0,0 @@
-- Merge reporter + supervisor + capa_owner into one role: ssa (Site Safety Assistant).
-- Run by hand on the production DB with the owner's go-ahead. Take a pg_dump first.
-- This migration drops all RLS policies, migrates the enum type, recreates auth_user_role(),
-- then re-applies all policies in a single transaction to avoid access gaps.
-- After this, users must log out and in again (role is in the JWT cookie).
-- ============================================================================
-- STEP 1: Add new 'ssa' value to enum (must be separate transaction)
-- ============================================================================
BEGIN;
ALTER TYPE user_role ADD VALUE IF NOT EXISTS 'ssa';
COMMIT;
-- ============================================================================
-- STEP 2: Full migration in one transaction (no RLS gaps)
-- ============================================================================
BEGIN;
-- Update all old role names to 'ssa'
UPDATE users SET role = 'ssa' WHERE role IN ('reporter', 'supervisor', 'capa_owner');
-- Drop all existing RLS policies (safe: RLS still ON during migration)
DO $$
DECLARE r record;
BEGIN
FOR r IN SELECT schemaname, tablename, policyname FROM pg_policies WHERE schemaname = 'public' LOOP
EXECUTE format('DROP POLICY %I ON %I.%I', r.policyname, r.schemaname, r.tablename);
END LOOP;
END $$;
-- Recreate enum type with final values only
ALTER TYPE user_role RENAME TO user_role_old;
CREATE TYPE user_role AS ENUM ('ssa', 'hse', 'management', 'admin');
-- Alter column to new enum type
ALTER TABLE users ALTER COLUMN role DROP DEFAULT;
ALTER TABLE users ALTER COLUMN role TYPE user_role USING role::text::user_role;
ALTER TABLE users ALTER COLUMN role SET DEFAULT 'ssa';
-- Drop and recreate auth_user_role() to return new enum type
DROP FUNCTION IF EXISTS public.auth_user_role();
CREATE OR REPLACE FUNCTION public.auth_user_role()
RETURNS user_role
LANGUAGE sql
SECURITY DEFINER
STABLE
SET search_path = public
AS $$
SELECT role FROM public.users WHERE id = app_current_user_id()
$$;
-- Clean up old enum type
DROP TYPE user_role_old;
-- ============================================================================
-- STEP 3: Re-apply all RLS policies (same as db/rls.sql)
-- ============================================================================
-- sites
CREATE POLICY "sites_read" ON sites FOR SELECT USING (active = true);
CREATE POLICY "sites_admin_all" ON sites FOR ALL USING (auth_user_role() = 'admin');
-- zones
CREATE POLICY "zones_read" ON zones FOR SELECT USING (true);
CREATE POLICY "zones_admin_all" ON zones FOR ALL USING (auth_user_role() = 'admin');
-- trucks
CREATE POLICY "trucks_read" ON trucks FOR SELECT USING (true);
CREATE POLICY "trucks_admin_all" ON trucks FOR ALL USING (auth_user_role() = 'admin');
-- users
CREATE POLICY "users_read_own" ON users FOR SELECT USING (id = app_current_user_id());
CREATE POLICY "users_read_elevated" ON users FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa'));
CREATE POLICY "users_update_own" ON users FOR UPDATE
USING (id = app_current_user_id())
WITH CHECK (
id = app_current_user_id()
AND role = (SELECT role FROM public.users WHERE id = app_current_user_id())
);
CREATE POLICY "users_admin_all" ON users FOR ALL USING (auth_user_role() = 'admin');
-- incidents
CREATE POLICY "incidents_insert" ON incidents FOR INSERT
WITH CHECK (reported_by = app_current_user_id());
CREATE POLICY "incidents_read_reporter" ON incidents FOR SELECT
USING (reported_by = app_current_user_id());
CREATE POLICY "incidents_read_ssa" ON incidents FOR SELECT
USING (auth_user_role() = 'ssa' AND site_id = auth_user_site_id());
CREATE POLICY "incidents_read_elevated" ON incidents FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management'));
CREATE POLICY "incidents_update_elevated" ON incidents FOR UPDATE
USING (auth_user_role() IN ('hse', 'admin', 'ssa'));
-- evidence_files
CREATE POLICY "evidence_insert" ON evidence_files FOR INSERT
WITH CHECK (uploaded_by = app_current_user_id());
CREATE POLICY "evidence_read_uploader" ON evidence_files FOR SELECT
USING (uploaded_by = app_current_user_id());
CREATE POLICY "evidence_read_elevated" ON evidence_files FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa'));
-- investigations
CREATE POLICY "investigations_hse_admin" ON investigations FOR ALL
USING (auth_user_role() IN ('hse', 'admin'));
CREATE POLICY "investigations_read_ssa" ON investigations FOR SELECT
USING (auth_user_role() = 'ssa');
-- capa_actions
CREATE POLICY "capa_read_owner" ON capa_actions FOR SELECT
USING (owner_user_id = app_current_user_id() OR department = auth_user_department());
CREATE POLICY "capa_update_owner" ON capa_actions FOR UPDATE
USING (owner_user_id = app_current_user_id());
CREATE POLICY "capa_read_elevated" ON capa_actions FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa'));
CREATE POLICY "capa_hse_admin_all" ON capa_actions FOR ALL
USING (auth_user_role() IN ('hse', 'admin'));
-- dosh_reports
CREATE POLICY "dosh_hse_admin" ON dosh_reports FOR ALL
USING (auth_user_role() IN ('hse', 'admin'));
-- notifications_log
CREATE POLICY "notifications_insert_elevated" ON notifications_log FOR INSERT
WITH CHECK (auth_user_role() IN ('hse', 'admin', 'ssa'));
CREATE POLICY "notifications_read_own" ON notifications_log FOR SELECT
USING (recipient_user_id = app_current_user_id());
CREATE POLICY "notifications_read_admin" ON notifications_log FOR SELECT
USING (auth_user_role() = 'admin');
CREATE POLICY "notifications_update_own" ON notifications_log FOR UPDATE
USING (recipient_user_id = app_current_user_id())
WITH CHECK (recipient_user_id = app_current_user_id());
-- audit_log
CREATE POLICY "audit_read_elevated" ON audit_log FOR SELECT
USING (auth_user_role() IN ('hse', 'admin'));
-- app_settings
CREATE POLICY "admin_select_settings" ON app_settings FOR SELECT
USING (auth_user_role() = 'admin');
CREATE POLICY "admin_update_settings" ON app_settings FOR ALL
USING (auth_user_role() = 'admin');
-- incident_addenda
CREATE POLICY "addenda_read" ON incident_addenda FOR SELECT
USING (
auth_user_role() IN ('hse', 'admin', 'ssa', 'management')
OR EXISTS (
SELECT 1 FROM incidents i
WHERE i.id = incident_id AND i.reported_by = app_current_user_id()
)
);
CREATE POLICY "addenda_insert" ON incident_addenda FOR INSERT
WITH CHECK (
author = app_current_user_id()
AND auth_user_role() IN ('hse', 'admin', 'ssa')
);
COMMIT;
-- ============================================================================
-- After migration succeeds:
-- 1. Verify all users have role = 'ssa' (no 'reporter', 'supervisor', 'capa_owner')
-- 2. Ask users to log out and in again (clears old JWT with old role)
-- 3. Deploy the new code (app/api, auth checks, RLS already match)
-- ============================================================================
-67
View File
@@ -1,67 +0,0 @@
-- One-off: delete ALL incidents (and children) and every user with role <> 'admin'.
-- Usage: psql -p 5433 -d ims -v mode=dryrun -f cleanup-test-data.sql (counts only)
-- psql -p 5433 -d ims -v mode=run -f cleanup-test-data.sql (deletes, one transaction)
-- Evidence files on disk are NOT touched (5-year retention).
\set ON_ERROR_STOP on
\if :{?mode}
\else
\echo 'Set -v mode=dryrun or -v mode=run'
\quit
\endif
BEGIN;
\echo '--- admins kept ---'
SELECT id, name, email FROM users WHERE role = 'admin' ORDER BY email;
\echo '--- row counts to delete ---'
SELECT 'incidents' AS tbl, count(*) FROM incidents
UNION ALL SELECT 'evidence_files', count(*) FROM evidence_files
UNION ALL SELECT 'investigations', count(*) FROM investigations
UNION ALL SELECT 'capa_actions', count(*) FROM capa_actions
UNION ALL SELECT 'dosh_reports', count(*) FROM dosh_reports
UNION ALL SELECT 'incident_addenda', count(*) FROM incident_addenda
UNION ALL SELECT 'notifications_log', count(*) FROM notifications_log
UNION ALL SELECT 'audit_log (all)', count(*) FROM audit_log
UNION ALL SELECT 'users (non-admin)', count(*) FROM users WHERE role <> 'admin';
SELECT (:'mode' = 'run') AS do_delete \gset
\if :do_delete
-- Closed incidents are locked by triggers; disable them for this transaction only.
ALTER TABLE incidents DISABLE TRIGGER incidents_closed_lock_delete;
ALTER TABLE incidents DISABLE TRIGGER incidents_closed_lock_update;
DELETE FROM notifications_log;
DELETE FROM incident_addenda;
DELETE FROM dosh_reports;
DELETE FROM evidence_files;
DELETE FROM capa_actions;
DELETE FROM investigations;
DELETE FROM incidents;
-- audit_log: remove rows about deleted incident-side tables and about non-admin users.
DELETE FROM audit_log
WHERE table_name IN ('incidents','evidence_files','investigations','capa_actions','dosh_reports','incident_addenda')
OR changed_by IN (SELECT id FROM users WHERE role <> 'admin')
OR (table_name = 'users' AND record_id IN (SELECT id FROM users WHERE role <> 'admin'));
UPDATE app_settings SET updated_by = NULL
WHERE updated_by IN (SELECT id FROM users WHERE role <> 'admin');
DELETE FROM password_reset_tokens WHERE user_id IN (SELECT id FROM users WHERE role <> 'admin');
DELETE FROM users WHERE role <> 'admin';
ALTER TABLE incidents ENABLE TRIGGER incidents_closed_lock_delete;
ALTER TABLE incidents ENABLE TRIGGER incidents_closed_lock_update;
\echo '--- after ---'
SELECT 'incidents' AS tbl, count(*) FROM incidents
UNION ALL SELECT 'users', count(*) FROM users
UNION ALL SELECT 'admins', count(*) FROM users WHERE role = 'admin';
COMMIT;
\else
ROLLBACK;
\echo 'dry run: nothing changed'
\endif
+11 -11
View File
@@ -56,7 +56,7 @@ CREATE POLICY "trucks_admin_all" ON trucks FOR ALL USING (auth_user_role() =
-- users -- users
CREATE POLICY "users_read_own" ON users FOR SELECT USING (id = app_current_user_id()); CREATE POLICY "users_read_own" ON users FOR SELECT USING (id = app_current_user_id());
CREATE POLICY "users_read_elevated" ON users FOR SELECT CREATE POLICY "users_read_elevated" ON users FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa')); USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor'));
CREATE POLICY "users_update_own" ON users FOR UPDATE CREATE POLICY "users_update_own" ON users FOR UPDATE
USING (id = app_current_user_id()) USING (id = app_current_user_id())
WITH CHECK ( WITH CHECK (
@@ -70,12 +70,12 @@ CREATE POLICY "incidents_insert" ON incidents FOR INSERT
WITH CHECK (reported_by = app_current_user_id()); WITH CHECK (reported_by = app_current_user_id());
CREATE POLICY "incidents_read_reporter" ON incidents FOR SELECT CREATE POLICY "incidents_read_reporter" ON incidents FOR SELECT
USING (reported_by = app_current_user_id()); USING (reported_by = app_current_user_id());
CREATE POLICY "incidents_read_ssa" ON incidents FOR SELECT CREATE POLICY "incidents_read_supervisor" ON incidents FOR SELECT
USING (auth_user_role() = 'ssa' AND site_id = auth_user_site_id()); USING (auth_user_role() = 'supervisor' AND site_id = auth_user_site_id());
CREATE POLICY "incidents_read_elevated" ON incidents FOR SELECT CREATE POLICY "incidents_read_elevated" ON incidents FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management')); USING (auth_user_role() IN ('hse', 'admin', 'management'));
CREATE POLICY "incidents_update_elevated" ON incidents FOR UPDATE CREATE POLICY "incidents_update_elevated" ON incidents FOR UPDATE
USING (auth_user_role() IN ('hse', 'admin', 'ssa')); USING (auth_user_role() IN ('hse', 'admin', 'supervisor'));
-- evidence_files -- evidence_files
CREATE POLICY "evidence_insert" ON evidence_files FOR INSERT CREATE POLICY "evidence_insert" ON evidence_files FOR INSERT
@@ -83,14 +83,14 @@ CREATE POLICY "evidence_insert" ON evidence_files FOR INSERT
CREATE POLICY "evidence_read_uploader" ON evidence_files FOR SELECT CREATE POLICY "evidence_read_uploader" ON evidence_files FOR SELECT
USING (uploaded_by = app_current_user_id()); USING (uploaded_by = app_current_user_id());
CREATE POLICY "evidence_read_elevated" ON evidence_files FOR SELECT CREATE POLICY "evidence_read_elevated" ON evidence_files FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa')); USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor'));
-- No DELETE policy: files are never deleted (soft-delete only via `deleted` flag) -- No DELETE policy: files are never deleted (soft-delete only via `deleted` flag)
-- investigations -- investigations
CREATE POLICY "investigations_hse_admin" ON investigations FOR ALL CREATE POLICY "investigations_hse_admin" ON investigations FOR ALL
USING (auth_user_role() IN ('hse', 'admin')); USING (auth_user_role() IN ('hse', 'admin'));
CREATE POLICY "investigations_read_ssa" ON investigations FOR SELECT CREATE POLICY "investigations_read_supervisor" ON investigations FOR SELECT
USING (auth_user_role() = 'ssa'); USING (auth_user_role() = 'supervisor');
-- capa_actions (capa_update_owner is tightened — no department clause) -- capa_actions (capa_update_owner is tightened — no department clause)
CREATE POLICY "capa_read_owner" ON capa_actions FOR SELECT CREATE POLICY "capa_read_owner" ON capa_actions FOR SELECT
@@ -98,7 +98,7 @@ CREATE POLICY "capa_read_owner" ON capa_actions FOR SELECT
CREATE POLICY "capa_update_owner" ON capa_actions FOR UPDATE CREATE POLICY "capa_update_owner" ON capa_actions FOR UPDATE
USING (owner_user_id = app_current_user_id()); USING (owner_user_id = app_current_user_id());
CREATE POLICY "capa_read_elevated" ON capa_actions FOR SELECT CREATE POLICY "capa_read_elevated" ON capa_actions FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa')); USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor'));
CREATE POLICY "capa_hse_admin_all" ON capa_actions FOR ALL CREATE POLICY "capa_hse_admin_all" ON capa_actions FOR ALL
USING (auth_user_role() IN ('hse', 'admin')); USING (auth_user_role() IN ('hse', 'admin'));
@@ -108,7 +108,7 @@ CREATE POLICY "dosh_hse_admin" ON dosh_reports FOR ALL
-- notifications_log (final state after migration 19 fix) -- notifications_log (final state after migration 19 fix)
CREATE POLICY "notifications_insert_elevated" ON notifications_log FOR INSERT CREATE POLICY "notifications_insert_elevated" ON notifications_log FOR INSERT
WITH CHECK (auth_user_role() IN ('hse', 'admin', 'ssa')); WITH CHECK (auth_user_role() IN ('hse', 'admin', 'supervisor'));
CREATE POLICY "notifications_read_own" ON notifications_log FOR SELECT CREATE POLICY "notifications_read_own" ON notifications_log FOR SELECT
USING (recipient_user_id = app_current_user_id()); USING (recipient_user_id = app_current_user_id());
CREATE POLICY "notifications_read_admin" ON notifications_log FOR SELECT CREATE POLICY "notifications_read_admin" ON notifications_log FOR SELECT
@@ -130,7 +130,7 @@ CREATE POLICY "admin_update_settings" ON app_settings FOR ALL
-- incident_addenda -- incident_addenda
CREATE POLICY "addenda_read" ON incident_addenda FOR SELECT CREATE POLICY "addenda_read" ON incident_addenda FOR SELECT
USING ( USING (
auth_user_role() IN ('hse', 'admin', 'ssa', 'management') auth_user_role() IN ('hse', 'admin', 'supervisor', 'management')
OR EXISTS ( OR EXISTS (
SELECT 1 FROM incidents i SELECT 1 FROM incidents i
WHERE i.id = incident_id AND i.reported_by = app_current_user_id() WHERE i.id = incident_id AND i.reported_by = app_current_user_id()
@@ -139,5 +139,5 @@ CREATE POLICY "addenda_read" ON incident_addenda FOR SELECT
CREATE POLICY "addenda_insert" ON incident_addenda FOR INSERT CREATE POLICY "addenda_insert" ON incident_addenda FOR INSERT
WITH CHECK ( WITH CHECK (
author = app_current_user_id() author = app_current_user_id()
AND auth_user_role() IN ('hse', 'admin', 'ssa') AND auth_user_role() IN ('hse', 'admin', 'supervisor')
); );
+2 -8
View File
@@ -16,7 +16,7 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Enums -- Enums
-- --------------------------------------------------------------------------- -- ---------------------------------------------------------------------------
CREATE TYPE user_role AS ENUM ( CREATE TYPE user_role AS ENUM (
'ssa', 'hse', 'management', 'admin' 'reporter', 'supervisor', 'hse', 'capa_owner', 'management', 'admin'
); );
CREATE TYPE incident_type AS ENUM ( CREATE TYPE incident_type AS ENUM (
@@ -80,7 +80,7 @@ CREATE TABLE users (
name TEXT NOT NULL DEFAULT '', name TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '' UNIQUE, email TEXT NOT NULL DEFAULT '' UNIQUE,
phone TEXT, phone TEXT,
role user_role NOT NULL DEFAULT 'ssa', role user_role NOT NULL DEFAULT 'reporter',
department TEXT, department TEXT,
site_id UUID REFERENCES sites(id), site_id UUID REFERENCES sites(id),
active BOOLEAN NOT NULL DEFAULT true, active BOOLEAN NOT NULL DEFAULT true,
@@ -101,9 +101,6 @@ CREATE TABLE trucks (
created_at TIMESTAMPTZ NOT NULL DEFAULT now() created_at TIMESTAMPTZ NOT NULL DEFAULT now()
); );
ALTER TABLE trucks ADD COLUMN IF NOT EXISTS site_id UUID REFERENCES sites(id);
CREATE INDEX IF NOT EXISTS trucks_site_id_idx ON trucks(site_id);
-- incidents: final column set includes all columns added in later migrations -- incidents: final column set includes all columns added in later migrations
CREATE TABLE incidents ( CREATE TABLE incidents (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
@@ -200,9 +197,6 @@ CREATE INDEX capa_actions_owner_idx ON capa_actions(owner_user_id);
CREATE INDEX capa_actions_status_idx ON capa_actions(status); CREATE INDEX capa_actions_status_idx ON capa_actions(status);
CREATE INDEX capa_actions_due_date_idx ON capa_actions(due_date); CREATE INDEX capa_actions_due_date_idx ON capa_actions(due_date);
ALTER TABLE evidence_files ADD COLUMN capa_id UUID REFERENCES capa_actions(id) ON DELETE RESTRICT;
CREATE INDEX evidence_files_capa_id_idx ON evidence_files(capa_id);
CREATE TABLE dosh_reports ( CREATE TABLE dosh_reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
incident_id UUID NOT NULL REFERENCES incidents(id) ON DELETE RESTRICT, incident_id UUID NOT NULL REFERENCES incidents(id) ON DELETE RESTRICT,
-24
View File
@@ -1,24 +0,0 @@
# Cleanup: delete test incidents and non-admin users
Owner go-ahead required before step 4. Never run during business hours without telling HSE.
1. **Backup** (on the server, `ssh -p 9321 setia@175.136.239.121`):
```bash
D=$(date +%Y%m%d-%H%M)
pg_dump -p 5433 -Fc ims > /srv/apps/ims/backups/ims-pre-cleanup-$D.dump
tar -czf /srv/apps/ims/backups/evidence-pre-cleanup-$D.tgz /var/lib/ims-evidence
ls -lh /srv/apps/ims/backups/*pre-cleanup-$D*
```
Create `/srv/apps/ims/backups` first if missing. Both files must be non-empty.
2. **Upload** `db/ops/cleanup-test-data.sql` to `/srv/apps/ims/backups/` (not into `app/`).
3. **Dry run.** Use a DB role that owns the tables and bypasses RLS (superuser, or the owner role with BYPASSRLS). The tables have FORCE RLS and no DELETE policies, so as `app_user` or a plain owner the counts can read 0 and deletes silently remove nothing. Check first: `psql -p 5433 -d ims -Atc "select rolsuper or rolbypassrls from pg_roles where rolname = current_user"` must print `t`. Then:
```bash
psql -p 5433 -d ims -v mode=dryrun -f /srv/apps/ims/backups/cleanup-test-data.sql
```
Send the admins list and the row counts to the owner. If incidents or users show 0 when the app shows rows, you are on the wrong role: stop. Mention that audit_log rows written by non-admin users about other tables (zones, trucks, settings) are also removed. Stop here until they confirm.
4. **Run** after explicit confirmation:
```bash
psql -p 5433 -d ims -v ON_ERROR_STOP=1 -v mode=run -f /srv/apps/ims/backups/cleanup-test-data.sql
```
5. **Verify**: `systemctl is-active ims` is `active`; log in as an admin at https://ims.setia.com.my/login; Incidents page is empty; Users page lists only admins.
6. **Rollback** (only if wrong): `pg_restore -p 5433 -d ims --clean --if-exists <dump>`; evidence files were never touched.
File diff suppressed because it is too large Load Diff
@@ -1,886 +0,0 @@
# Truck to Site Link Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Let admin link a truck to one site (with edit), and make the Report an Incident truck dropdown show only trucks for the selected site plus unassigned trucks.
**Architecture:** Nullable `trucks.site_id` column (hand-applied SQL). `/api/admin/trucks` POST and PATCH accept `site_id` and PATCH becomes a partial edit (truck_no, carrier, site_id, active). The Trucks admin tab gets a Site select on add, a site label per row and an Edit modal. The report form filters trucks with a pure helper `trucksForSite`.
**Tech Stack:** Next.js 16 App Router, Drizzle ORM + `pg`, vitest + Testing Library.
Spec: `docs/superpowers/specs/2026-10-15-truck-site-link-design.md`
## Global Constraints
- A truck links to **one** site, optional. Existing trucks stay unassigned.
- A truck with no site shows for **every** site on the report form.
- `POST /api/incidents` is NOT changed and does not reject a truck/site mismatch.
- Schema change is hand-applied: write `db/ops/2026-10-15-trucks-site-id.sql`, edit `db/schema.sql` and `lib/db/schema.ts`. Do NOT run any SQL against any database. No RLS change.
- Every DB mutation writes `audit_log` in the same transaction (existing pattern with `writeAuditLog`).
- Admin routes use `requireAdmin()` and `asAdmin`.
- UI uses existing tokens and classes (`bg-surface`, `border-divider`, `text-accent-700`, ...). No hard-coded hex, no `bg-white`, no 2px borders. `npm run check:design` must print `design gates: clean`.
- Baseline: 7 pre-existing failing vitest tests. Do not fix or count them. After code changes run `graphify update .`.
- Never commit `.env*`. Do not commit the unrelated dirty files (`design-system/ims-admin/MASTER.md` deletion, `*.zip`, `artifacts/`, `scripts/create-agent-*.js`, `.superpowers/sdd/progress.md`). Stage only the files named in each task.
- Work on branch `feat/truck-site`.
---
### Task 1: Schema, SQL and site/truck helpers
**Files:**
- Create: `db/ops/2026-10-15-trucks-site-id.sql`
- Modify: `db/schema.sql` (after the `CREATE TABLE trucks (...)` block, line ~96-102)
- Modify: `lib/db/schema.ts` (`trucks` table, line ~102)
- Create: `lib/report/trucks.ts`
- Create: `lib/admin/truck-input.ts`
- Modify: `lib/report/zones.ts` (add `siteIdForToken`)
- Test: `tests/lib/report/trucks.test.ts`, `tests/lib/admin/truck-input.test.ts`, `tests/lib/report/zones.test.ts` (append)
**Interfaces:**
- Produces: `trucksForSite<T extends { site_id: string | null }>(trucks: T[], siteId: string): T[]`; `siteForTruck(trucks: { id: string; site_id: string | null }[], truckId: string | null | undefined): string | null`; `parseSiteId(raw: unknown): { ok: true; value: string | null | undefined } | { ok: false }`; `siteIdForToken(sites: SiteOption[], token: string | null): string` (returns `''` when none); `trucks.siteId` Drizzle column.
- [ ] **Step 1: Write the failing tests**
`tests/lib/report/trucks.test.ts`:
```ts
import { describe, it, expect } from 'vitest'
import { trucksForSite, siteForTruck } from '@/lib/report/trucks'
const trucks = [
{ id: 't1', site_id: 'A' },
{ id: 't2', site_id: 'B' },
{ id: 't3', site_id: null },
]
describe('trucksForSite', () => {
it('returns matching and unassigned trucks', () => {
expect(trucksForSite(trucks, 'A').map(t => t.id)).toEqual(['t1', 't3'])
expect(trucksForSite(trucks, 'B').map(t => t.id)).toEqual(['t2', 't3'])
})
it('returns all trucks when no site is selected', () => {
expect(trucksForSite(trucks, '').map(t => t.id)).toEqual(['t1', 't2', 't3'])
})
it('returns only unassigned trucks for a site with none linked', () => {
expect(trucksForSite(trucks, 'C').map(t => t.id)).toEqual(['t3'])
})
})
describe('siteForTruck', () => {
it('returns the truck site', () => {
expect(siteForTruck(trucks, 't2')).toBe('B')
})
it('returns null for unassigned, unknown or missing truck', () => {
expect(siteForTruck(trucks, 't3')).toBeNull()
expect(siteForTruck(trucks, 'nope')).toBeNull()
expect(siteForTruck(trucks, null)).toBeNull()
})
})
```
`tests/lib/admin/truck-input.test.ts`:
```ts
import { describe, it, expect } from 'vitest'
import { parseSiteId } from '@/lib/admin/truck-input'
const UUID = '3f2b8c1e-9d4a-4e6f-8a1b-2c3d4e5f6a7b'
describe('parseSiteId', () => {
it('treats undefined as not provided', () => {
expect(parseSiteId(undefined)).toEqual({ ok: true, value: undefined })
})
it('treats null and empty string as clear', () => {
expect(parseSiteId(null)).toEqual({ ok: true, value: null })
expect(parseSiteId('')).toEqual({ ok: true, value: null })
})
it('accepts a uuid', () => {
expect(parseSiteId(UUID)).toEqual({ ok: true, value: UUID })
})
it('rejects anything else', () => {
expect(parseSiteId('abc')).toEqual({ ok: false })
expect(parseSiteId(12)).toEqual({ ok: false })
})
})
```
Append to `tests/lib/report/zones.test.ts` (add `siteIdForToken` to its existing import from `@/lib/report/zones`):
```ts
describe('siteIdForToken', () => {
const sites = [
{ id: 'A', name: 'Site A', zones: [{ id: 'z1', name: 'Dock', qr_code_token: 'tok-1' }] },
{ id: 'B', name: 'Site B', zones: [{ id: 'z2', name: 'Yard', qr_code_token: 'tok-2' }] },
]
it('finds the site that owns the token', () => {
expect(siteIdForToken(sites, 'tok-2')).toBe('B')
})
it('returns empty string for null or unknown token', () => {
expect(siteIdForToken(sites, null)).toBe('')
expect(siteIdForToken(sites, 'nope')).toBe('')
})
})
```
- [ ] **Step 2: Run tests to verify they fail**
Run: `npx vitest run tests/lib/report/trucks.test.ts tests/lib/admin/truck-input.test.ts tests/lib/report/zones.test.ts`
Expected: FAIL (modules / export not found).
- [ ] **Step 3: Write the helpers**
`lib/report/trucks.ts`:
```ts
export function trucksForSite<T extends { site_id: string | null }>(trucks: T[], siteId: string): T[] {
if (!siteId) return trucks
return trucks.filter(t => t.site_id === null || t.site_id === siteId)
}
export function siteForTruck(
trucks: { id: string; site_id: string | null }[],
truckId: string | null | undefined,
): string | null {
if (!truckId) return null
return trucks.find(t => t.id === truckId)?.site_id ?? null
}
```
`lib/admin/truck-input.ts`:
```ts
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
export type SiteIdInput = { ok: true; value: string | null | undefined } | { ok: false }
// undefined = field not sent, null/'' = clear the link, uuid string = set it.
export function parseSiteId(raw: unknown): SiteIdInput {
if (raw === undefined) return { ok: true, value: undefined }
if (raw === null || raw === '') return { ok: true, value: null }
if (typeof raw === 'string' && UUID_RE.test(raw)) return { ok: true, value: raw }
return { ok: false }
}
```
Append to `lib/report/zones.ts`:
```ts
export function siteIdForToken(sites: SiteOption[], token: string | null): string {
if (!token) return ''
return sites.find(s => s.zones.some(z => z.qr_code_token === token))?.id ?? ''
}
```
- [ ] **Step 4: Schema and SQL**
`db/ops/2026-10-15-trucks-site-id.sql`:
```sql
-- Apply by hand on the server DB with the owner's go-ahead. Not run by deploy.
BEGIN;
ALTER TABLE trucks ADD COLUMN IF NOT EXISTS site_id UUID REFERENCES sites(id);
CREATE INDEX IF NOT EXISTS trucks_site_id_idx ON trucks(site_id);
COMMIT;
```
`db/schema.sql`: immediately after the `CREATE TABLE trucks (...);` block add
```sql
ALTER TABLE trucks ADD COLUMN IF NOT EXISTS site_id UUID REFERENCES sites(id);
CREATE INDEX IF NOT EXISTS trucks_site_id_idx ON trucks(site_id);
```
`lib/db/schema.ts`: in `trucks` add after `carrier`:
```ts
siteId: uuid('site_id').references(() => sites.id),
```
(`sites` is declared above `trucks`, so no `AnyPgColumn` needed.)
- [ ] **Step 5: Run tests and typecheck**
Run: `npx vitest run tests/lib/report/trucks.test.ts tests/lib/admin/truck-input.test.ts tests/lib/report/zones.test.ts && npx tsc --noEmit`
Expected: all PASS, tsc clean.
- [ ] **Step 6: Commit**
```bash
git add db/ops/2026-10-15-trucks-site-id.sql db/schema.sql lib/db/schema.ts lib/report/trucks.ts lib/report/zones.ts lib/admin/truck-input.ts tests/lib/report/trucks.test.ts tests/lib/report/zones.test.ts tests/lib/admin/truck-input.test.ts
git commit -m "feat(trucks): site_id column and site/truck helpers"
```
---
### Task 2: Truck API accepts site_id and edits
**Files:**
- Modify: `app/api/admin/trucks/route.ts` (POST and PATCH; DELETE unchanged)
- Test: `tests/api/admin-trucks.test.ts` (create)
**Interfaces:**
- Consumes: `parseSiteId` from `@/lib/admin/truck-input`; `trucks.siteId`.
- Produces: `POST /api/admin/trucks {truck_no, carrier?, site_id?}`: 201 `{id}`, 422 invalid/unknown/inactive site, 400 duplicate. `PATCH /api/admin/trucks {id, active?, truck_no?, carrier?, site_id?}`: 200 `{ok:true}`, 422 for missing id, empty change set, empty `truck_no`, or bad/unknown/inactive site, 409 duplicate truck number, 500 other.
- [ ] **Step 1: Write the failing tests**
`tests/api/admin-trucks.test.ts`:
```ts
// @vitest-environment node
import { describe, it, expect, vi, beforeEach } from 'vitest'
const { selectQueue, setSpy, insertSpy, audit, txError } = vi.hoisted(() => ({
selectQueue: [] as unknown[][],
setSpy: vi.fn(),
insertSpy: vi.fn(),
audit: vi.fn(),
txError: { code: null as string | null },
}))
vi.mock('@/lib/auth/require-admin', () => ({
requireAdmin: async () => ({ session: { sub: 'admin-1', role: 'admin' } }),
}))
vi.mock('@/lib/db/audit', () => ({ writeAuditLog: audit }))
vi.mock('@/lib/db/with-user', () => {
const tx = {
execute: async () => undefined,
insert: () => ({
values: (v: unknown) => {
insertSpy(v)
return { returning: async () => [{ id: 'truck-new' }] }
},
}),
update: () => ({
set: (v: unknown) => {
setSpy(v)
return {
where: async () => {
if (txError.code) throw Object.assign(new Error('db'), { code: txError.code })
},
}
},
}),
}
const db = {
select: () => ({ from: () => ({ where: () => ({ limit: async () => selectQueue.shift() ?? [] }) }) }),
transaction: async (fn: (t: unknown) => unknown) => fn(tx),
}
return { asAdmin: async (fn: (d: unknown) => unknown) => fn(db) }
})
import { POST, PATCH } from '@/app/api/admin/trucks/route'
const SITE = '3f2b8c1e-9d4a-4e6f-8a1b-2c3d4e5f6a7b'
const req = (method: string, body: unknown) =>
new Request('http://localhost/api/admin/trucks', {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}) as never
beforeEach(() => {
selectQueue.length = 0
setSpy.mockClear()
insertSpy.mockClear()
audit.mockClear()
txError.code = null
})
describe('POST /api/admin/trucks', () => {
it('creates a truck with no site', async () => {
const res = await POST(req('POST', { truck_no: 'WXY 1' }))
expect(res.status).toBe(201)
expect(insertSpy).toHaveBeenCalledWith({ truckNo: 'WXY 1', carrier: null, siteId: null })
})
it('creates a truck linked to an active site and audits it', async () => {
selectQueue.push([{ id: SITE }])
const res = await POST(req('POST', { truck_no: 'WXY 2', site_id: SITE }))
expect(res.status).toBe(201)
expect(insertSpy).toHaveBeenCalledWith({ truckNo: 'WXY 2', carrier: null, siteId: SITE })
expect(audit).toHaveBeenCalledTimes(1)
expect(audit.mock.calls[0][4]).toMatchObject({ site_id: SITE })
})
it('422 for a malformed site_id', async () => {
const res = await POST(req('POST', { truck_no: 'WXY 3', site_id: 'abc' }))
expect(res.status).toBe(422)
expect(insertSpy).not.toHaveBeenCalled()
})
it('422 for an unknown or inactive site', async () => {
selectQueue.push([])
const res = await POST(req('POST', { truck_no: 'WXY 4', site_id: SITE }))
expect(res.status).toBe(422)
expect(insertSpy).not.toHaveBeenCalled()
})
})
describe('PATCH /api/admin/trucks', () => {
it('sets site_id and audits with the previous row', async () => {
selectQueue.push([{ id: 't1', siteId: null }], [{ id: SITE }])
const res = await PATCH(req('PATCH', { id: 't1', site_id: SITE }))
expect(res.status).toBe(200)
expect(setSpy).toHaveBeenCalledWith({ siteId: SITE })
expect(audit).toHaveBeenCalledTimes(1)
expect(audit.mock.calls[0][4]).toEqual({ siteId: SITE })
expect(audit.mock.calls[0][5]).toEqual({ id: 't1', siteId: null })
})
it('clears the site with null', async () => {
selectQueue.push([{ id: 't1', siteId: SITE }])
const res = await PATCH(req('PATCH', { id: 't1', site_id: null }))
expect(res.status).toBe(200)
expect(setSpy).toHaveBeenCalledWith({ siteId: null })
})
it('edits truck_no and carrier together', async () => {
selectQueue.push([{ id: 't1' }])
const res = await PATCH(req('PATCH', { id: 't1', truck_no: ' ABC 9 ', carrier: ' ' }))
expect(res.status).toBe(200)
expect(setSpy).toHaveBeenCalledWith({ truckNo: 'ABC 9', carrier: null })
})
it('still toggles active', async () => {
selectQueue.push([{ id: 't1' }])
const res = await PATCH(req('PATCH', { id: 't1', active: false }))
expect(res.status).toBe(200)
expect(setSpy).toHaveBeenCalledWith({ active: false })
})
it('422 when nothing to change', async () => {
const res = await PATCH(req('PATCH', { id: 't1' }))
expect(res.status).toBe(422)
})
it('422 for an empty truck_no', async () => {
const res = await PATCH(req('PATCH', { id: 't1', truck_no: ' ' }))
expect(res.status).toBe(422)
expect(setSpy).not.toHaveBeenCalled()
})
it('422 for a malformed or unknown site', async () => {
expect((await PATCH(req('PATCH', { id: 't1', site_id: 'abc' }))).status).toBe(422)
selectQueue.push([{ id: 't1' }], [])
expect((await PATCH(req('PATCH', { id: 't1', site_id: SITE }))).status).toBe(422)
expect(setSpy).not.toHaveBeenCalled()
})
it('409 for a duplicate truck number', async () => {
selectQueue.push([{ id: 't1' }])
txError.code = '23505'
const res = await PATCH(req('PATCH', { id: 't1', truck_no: 'DUP 1' }))
expect(res.status).toBe(409)
})
})
```
- [ ] **Step 2: Run to verify failure**
Run: `npx vitest run tests/api/admin-trucks.test.ts`
Expected: FAIL (site_id ignored, PATCH only handles `active`).
- [ ] **Step 3: Implement**
In `app/api/admin/trucks/route.ts`:
Change imports to:
```ts
import { trucks, incidents, sites } from '@/lib/db/schema'
import { parseSiteId } from '@/lib/admin/truck-input'
import { and, eq, sql } from 'drizzle-orm'
```
Add above `POST`:
```ts
async function activeSiteExists(id: string): Promise<boolean> {
const [row] = await asAdmin(db =>
db.select({ id: sites.id }).from(sites).where(and(eq(sites.id, id), eq(sites.active, true))).limit(1)
)
return !!row
}
```
Replace the whole `POST` function with:
```ts
export async function POST(request: NextRequest) {
const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const body: { truck_no?: string; carrier?: string; site_id?: unknown } = await request.json().catch(() => ({}))
const truck_no = (body.truck_no ?? '').trim()
if (!truck_no) return NextResponse.json({ error: 'truck_no required' }, { status: 422 })
const parsedSite = parseSiteId(body.site_id)
if (!parsedSite.ok) return NextResponse.json({ error: 'site_id invalid' }, { status: 422 })
const siteId = parsedSite.value ?? null
if (siteId && !(await activeSiteExists(siteId)))
return NextResponse.json({ error: 'Site not found or inactive' }, { status: 422 })
const carrier = (body.carrier ?? '').trim() || null
try {
let truckId: string | undefined
await asAdmin(async db => {
await db.transaction(async tx => {
await tx.execute(sql`SELECT set_config('app.user_id', ${session.sub}, true)`)
const [truck] = await tx.insert(trucks).values({ truckNo: truck_no, carrier, siteId }).returning({ id: trucks.id })
if (!truck) throw new Error('Insert failed')
truckId = truck.id
await writeAuditLog(tx, 'trucks', truck.id, 'INSERT', { truck_no, carrier, site_id: siteId })
})
})
if (!truckId) return NextResponse.json({ error: 'Insert failed' }, { status: 400 })
return NextResponse.json({ id: truckId }, { status: 201 })
} catch (e) {
const code = (e as { code?: string }).code
return NextResponse.json(
{ error: code === '23505' ? 'Truck number already exists' : 'Insert failed' },
{ status: 400 },
)
}
}
```
Replace the whole `PATCH` function with:
```ts
export async function PATCH(request: NextRequest) {
const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const body: {
id?: string
active?: boolean
truck_no?: string
carrier?: string | null
site_id?: unknown
} = await request.json().catch(() => ({}))
if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 })
const set: { active?: boolean; truckNo?: string; carrier?: string | null; siteId?: string | null } = {}
if (typeof body.active === 'boolean') set.active = body.active
if (body.truck_no !== undefined) {
const no = String(body.truck_no).trim()
if (!no) return NextResponse.json({ error: 'truck_no required' }, { status: 422 })
set.truckNo = no
}
if (body.carrier !== undefined) set.carrier = (body.carrier ?? '').trim() || null
const parsedSite = parseSiteId(body.site_id)
if (!parsedSite.ok) return NextResponse.json({ error: 'site_id invalid' }, { status: 422 })
if (parsedSite.value !== undefined) set.siteId = parsedSite.value
if (Object.keys(set).length === 0)
return NextResponse.json({ error: 'nothing to update' }, { status: 422 })
const [before] = await asAdmin(db =>
db.select().from(trucks).where(eq(trucks.id, body.id!)).limit(1)
)
if (set.siteId && !(await activeSiteExists(set.siteId)))
return NextResponse.json({ error: 'Site not found or inactive' }, { status: 422 })
try {
await asAdmin(async db => {
await db.transaction(async tx => {
await tx.execute(sql`SELECT set_config('app.user_id', ${session.sub}, true)`)
await tx.update(trucks).set(set).where(eq(trucks.id, body.id!))
await writeAuditLog(tx, 'trucks', body.id!, 'admin_update', set, before ?? null)
})
})
} catch (e) {
const code = (e as { code?: string }).code
if (code === '23505') return NextResponse.json({ error: 'Truck number already exists' }, { status: 409 })
return NextResponse.json({ error: 'Update failed' }, { status: 500 })
}
return NextResponse.json({ ok: true })
}
```
Note the test for "422 for a malformed or unknown site" in PATCH: the malformed case returns before any select; the unknown case consumes `[before]` then the site check.
- [ ] **Step 4: Run tests and typecheck**
Run: `npx vitest run tests/api/admin-trucks.test.ts && npx tsc --noEmit`
Expected: all PASS, tsc clean.
- [ ] **Step 5: Commit**
```bash
git add app/api/admin/trucks/route.ts tests/api/admin-trucks.test.ts
git commit -m "feat(trucks): admin API accepts site_id and partial edits"
```
---
### Task 3: Admin Trucks tab UI (site select, label, edit modal)
**Files:**
- Modify: `app/(protected)/admin/page.tsx` (truck query + props)
- Modify: `components/admin/admin-panel.tsx`
- Modify: `components/admin/truck-manager.tsx`
- Test: `tests/components/admin/truck-manager.test.tsx` (create)
**Interfaces:**
- Consumes: `PATCH /api/admin/trucks` and `POST /api/admin/trucks` from Task 2.
- Produces: `Truck` gains `site_id: string | null`; new exported `TruckSite = { id: string; name: string; active: boolean }`; `TruckManager` props `{ trucks: Truck[]; sites: TruckSite[] }`; `AdminPanel` prop `truckSites: TruckSite[]`.
- [ ] **Step 1: Write the failing test**
`tests/components/admin/truck-manager.test.tsx`:
```tsx
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { TruckManager, type Truck, type TruckSite } from '@/components/admin/truck-manager'
const { refresh } = vi.hoisted(() => ({ refresh: vi.fn() }))
vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh }) }))
const fetchMock = vi.fn()
beforeEach(() => {
refresh.mockClear()
fetchMock.mockReset()
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ ok: true }) })
vi.stubGlobal('fetch', fetchMock)
})
const sites: TruckSite[] = [
{ id: 'site-a', name: 'Site A', active: true },
{ id: 'site-b', name: 'Site B', active: true },
{ id: 'site-old', name: 'Old Site', active: false },
]
const trucks: Truck[] = [
{ id: 't1', truck_no: 'WXY 1', carrier: null, site_id: 'site-a', active: true },
{ id: 't2', truck_no: 'WXY 2', carrier: 'Setia', site_id: null, active: true },
]
describe('TruckManager site link', () => {
it('shows the site name or Unassigned on each row', () => {
render(<TruckManager trucks={trucks} sites={sites} />)
expect(screen.getByText('Site A')).toBeTruthy()
expect(screen.getByText('Unassigned')).toBeTruthy()
})
it('edits the site of a truck via PATCH', async () => {
render(<TruckManager trucks={trucks} sites={sites} />)
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[1])
fireEvent.change(screen.getByLabelText('Site'), { target: { value: 'site-b' } })
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
await waitFor(() => expect(fetchMock).toHaveBeenCalled())
const [url, init] = fetchMock.mock.calls[0]
expect(url).toBe('/api/admin/trucks')
expect(init.method).toBe('PATCH')
expect(JSON.parse(init.body)).toEqual({ id: 't2', truck_no: 'WXY 2', carrier: 'Setia', site_id: 'site-b' })
await waitFor(() => expect(refresh).toHaveBeenCalled())
})
it('clears the site with the No site option', async () => {
render(<TruckManager trucks={trucks} sites={sites} />)
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[0])
fireEvent.change(screen.getByLabelText('Site'), { target: { value: '' } })
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
await waitFor(() => expect(fetchMock).toHaveBeenCalled())
expect(JSON.parse(fetchMock.mock.calls[0][1].body).site_id).toBeNull()
})
it('does not offer inactive sites unless already linked', () => {
render(<TruckManager trucks={trucks} sites={sites} />)
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[0])
const select = screen.getByLabelText('Site') as HTMLSelectElement
const labels = Array.from(select.options).map(o => o.textContent)
expect(labels).toEqual(['No site', 'Site A', 'Site B'])
})
it('sends site_id when adding a truck', async () => {
render(<TruckManager trucks={trucks} sites={sites} />)
fireEvent.click(screen.getByRole('button', { name: /Add Truck/ }))
fireEvent.change(screen.getByLabelText(/Truck Number/), { target: { value: 'NEW 1' } })
fireEvent.change(screen.getByLabelText('Site'), { target: { value: 'site-b' } })
fireEvent.click(screen.getAllByRole('button', { name: 'Add Truck' }).pop()!)
await waitFor(() => expect(fetchMock).toHaveBeenCalled())
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ truck_no: 'NEW 1', carrier: null, site_id: 'site-b' })
})
})
```
- [ ] **Step 2: Run to verify failure**
Run: `npx vitest run tests/components/admin/truck-manager.test.tsx`
Expected: FAIL (no `sites` prop, no Edit button).
- [ ] **Step 3: Implement `components/admin/truck-manager.tsx`**
3a. Replace the type/props block at the top:
```ts
export type Truck = {
id: string
truck_no: string
carrier: string | null
site_id: string | null
active: boolean
}
export type TruckSite = { id: string; name: string; active: boolean }
interface Props {
trucks: Truck[]
sites: TruckSite[]
}
```
and the signature `export function TruckManager({ trucks, sites }: Props) {`.
3b. After the existing `const [confirmDelete, ...]` state add:
```ts
const [siteId, setSiteId] = useState('')
const [editing, setEditing] = useState<Truck | null>(null)
const [editNo, setEditNo] = useState('')
const [editCarrier, setEditCarrier] = useState('')
const [editSiteId, setEditSiteId] = useState('')
const siteName = (id: string | null) => sites.find(s => s.id === id)?.name ?? null
const siteChoices = (currentId: string) => sites.filter(s => s.active || s.id === currentId)
const openEdit = (tk: Truck) => {
setEditing(tk)
setEditNo(tk.truck_no)
setEditCarrier(tk.carrier ?? '')
setEditSiteId(tk.site_id ?? '')
setError(null)
}
```
3c. In `handleAdd` change the body to `JSON.stringify({ truck_no: no, carrier: carrier.trim() || null, site_id: siteId || null })` and after `setCarrier('')` add `setSiteId('')`.
3d. After `handleDelete` add:
```ts
const handleSaveEdit = async () => {
if (!editing) return
const no = editNo.trim()
if (!no) return
const ok = await send('PATCH', {
id: editing.id,
truck_no: no,
carrier: editCarrier.trim() || null,
site_id: editSiteId || null,
})
if (ok) setEditing(null)
}
```
3e. In the row, replace the left block
```tsx
<div className="flex items-center gap-3">
<span className="text-sm font-semibold text-gray-900">{tk.truck_no}</span>
{tk.carrier && <span className="text-xs text-gray-400">{tk.carrier}</span>}
</div>
```
with
```tsx
<div className="flex items-center gap-3">
<span className="text-sm font-semibold text-gray-900">{tk.truck_no}</span>
{tk.carrier && <span className="text-xs text-gray-400">{tk.carrier}</span>}
<span className={`text-xs px-2 py-0.5 ${tk.site_id ? 'bg-neutral-100 text-ink' : 'bg-gray-100 text-gray-500'}`}>
{siteName(tk.site_id) ?? 'Unassigned'}
</span>
</div>
```
and, in the right-hand actions, add before the "Report link" anchor:
```tsx
<button disabled={busyId === tk.id} onClick={() => openEdit(tk)}
className="text-xs text-accent-700 hover:underline cursor-pointer disabled:opacity-50">
Edit
</button>
```
3f. In the Add modal, update both reset handlers (`onClose` and Cancel) to also call `setSiteId('')`, and add inside the `space-y-4` div after the carrier field:
```tsx
<div>
<label className={lbl} htmlFor="add-truck-site">Site</label>
<select id="add-truck-site" value={siteId} onChange={e => setSiteId(e.target.value)} className={inp}>
<option value="">No site</option>
{siteChoices('').map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select>
</div>
```
3g. Add an Edit modal before the Delete Confirm modal:
```tsx
{/* Edit Truck Modal */}
<Modal open={!!editing} onClose={() => { setEditing(null); setError(null) }}
title="Edit Truck" width="sm"
footer={
<>
<button onClick={() => { setEditing(null); setError(null) }}
className="px-4 py-2 text-sm font-medium border border-divider text-gray-700 hover:bg-gray-50 cursor-pointer transition-colors">
Cancel
</button>
<button disabled={busyId === editing?.id || !editNo.trim()} onClick={handleSaveEdit}
className="px-4 py-2 bg-accent text-white text-sm font-semibold hover:bg-accent-600 disabled:opacity-50 cursor-pointer transition-colors">
{busyId === editing?.id ? 'Saving…' : 'Save'}
</button>
</>
}
>
{error && <p className="text-xs text-red-600 bg-red-50 px-3 py-2 mb-3">{error}</p>}
<div className="space-y-4">
<div>
<label className={lbl} htmlFor="edit-truck-no">Truck Number *</label>
<input id="edit-truck-no" type="text" value={editNo} onChange={e => setEditNo(e.target.value)} className={inp} />
</div>
<div>
<label className={lbl} htmlFor="edit-truck-carrier">Carrier (optional)</label>
<input id="edit-truck-carrier" type="text" value={editCarrier} onChange={e => setEditCarrier(e.target.value)} className={inp} />
</div>
<div>
<label className={lbl} htmlFor="edit-truck-site">Site</label>
<select id="edit-truck-site" value={editSiteId} onChange={e => setEditSiteId(e.target.value)} className={inp}>
<option value="">No site</option>
{siteChoices(editing?.site_id ?? '').map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select>
</div>
</div>
</Modal>
```
Note: the delete-confirm modal and the row `Delete`/`Active` buttons stay unchanged. When only one modal is open at a time, `getByLabelText('Site')` is unambiguous.
3h. `components/admin/admin-panel.tsx`: import `TruckSite`, add prop `truckSites: TruckSite[]` to `Props`, destructure it, and render `<TruckManager trucks={trucks} sites={truckSites} />`.
3i. `app/(protected)/admin/page.tsx`: add `siteId: trucks.siteId` to the trucks select (the `id: trucks.id, truckNo: ...` object), map `site_id: t.siteId ?? null` in `truckList`, build
```ts
const truckSites = siteRows.map(s => ({ id: s.id, name: s.name, active: s.active }))
```
and pass `truckSites={truckSites}` to `<AdminPanel .../>` (find the existing `<AdminPanel` usage in that file and add the prop).
- [ ] **Step 4: Run tests, typecheck, design gate**
Run: `npx vitest run tests/components/admin/truck-manager.test.tsx && npx tsc --noEmit && npm run check:design`
Expected: tests PASS, tsc clean, `design gates: clean`.
- [ ] **Step 5: Commit**
```bash
git add components/admin/truck-manager.tsx components/admin/admin-panel.tsx "app/(protected)/admin/page.tsx" tests/components/admin/truck-manager.test.tsx
git commit -m "feat(trucks): site select, site label and edit modal in admin"
```
---
### Task 4: Report form filters trucks by site
**Files:**
- Modify: `app/report/page.tsx` (truck query adds `siteId`, list adds `site_id`)
- Modify: `components/incidents/report-form.tsx`
- Test: `tests/components/incidents/report-form-trucks.test.tsx` (create)
**Interfaces:**
- Consumes: `trucksForSite`, `siteForTruck` from `@/lib/report/trucks`; `siteIdForToken` from `@/lib/report/zones` (Task 1).
- Produces: `ReportForm` prop `trucks: Array<{ id; truck_no; carrier; site_id: string | null }>`.
- [ ] **Step 1: Write the failing test**
`tests/components/incidents/report-form-trucks.test.tsx`:
```tsx
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent, within } from '@testing-library/react'
import { ReportForm } from '@/components/incidents/report-form'
import { I18nProvider } from '@/lib/i18n/context'
import en from '@/messages/en.json'
vi.mock('next/navigation', () => ({ useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }) }))
const sites = [
{ id: 'site-a', name: 'Site A', zones: [{ id: 'z1', name: 'Dock', qr_code_token: 'tok-a' }] },
{ id: 'site-b', name: 'Site B', zones: [{ id: 'z2', name: 'Yard', qr_code_token: 'tok-b' }] },
]
const trucks = [
{ id: 't1', truck_no: 'AAA 1', carrier: null, site_id: 'site-a' },
{ id: 't2', truck_no: 'BBB 2', carrier: null, site_id: 'site-b' },
{ id: 't3', truck_no: 'FREE 3', carrier: null, site_id: null },
]
function renderForm(props: Partial<React.ComponentProps<typeof ReportForm>> = {}) {
return render(
<I18nProvider messages={en}>
<ReportForm
zoneToken={null}
zoneName={null}
siteName={null}
sites={sites}
defaultSiteId=""
trucks={trucks}
initialTruckId="t1"
{...props}
/>
</I18nProvider>,
)
}
const selectWith = (text: string) =>
screen.getAllByRole('combobox').find(s => within(s).queryByText(text)) as HTMLSelectElement
const truckNos = () =>
Array.from(selectWith(en.ReportForm.truckPlaceholder).options).map(o => o.textContent)
describe('ReportForm truck filter', () => {
it('defaults the site to the preselected truck site and filters trucks', () => {
renderForm()
expect(selectWith(en.ReportForm.sitePlaceholder).value).toBe('site-a')
expect(truckNos()).toEqual([en.ReportForm.truckPlaceholder, 'AAA 1', 'FREE 3'])
})
it('changing the site refilters and clears a truck that no longer fits', () => {
renderForm()
expect(selectWith(en.ReportForm.truckPlaceholder).value).toBe('t1')
fireEvent.change(selectWith(en.ReportForm.sitePlaceholder), { target: { value: 'site-b' } })
expect(truckNos()).toEqual([en.ReportForm.truckPlaceholder, 'BBB 2', 'FREE 3'])
expect(selectWith(en.ReportForm.truckPlaceholder).value).toBe('')
})
it('uses the QR zone site when a zone token is present', () => {
renderForm({ zoneToken: 'tok-b', zoneName: 'Yard', siteName: 'Site B', initialTruckId: null })
// transport is not preselected without a truck, so pick it to reveal the truck select
fireEvent.change(screen.getAllByRole('combobox').find(s => within(s).queryByText(en.IncidentType.transport))!, {
target: { value: 'transport' },
})
expect(truckNos()).toEqual([en.ReportForm.truckPlaceholder, 'BBB 2', 'FREE 3'])
})
})
```
If the incident-type control is not a `<select>`, adapt only the third test's interaction (look at how the type picker renders in `report-form.tsx`) and keep its assertion; report the adaptation.
- [ ] **Step 2: Run to verify failure**
Run: `npx vitest run tests/components/incidents/report-form-trucks.test.tsx`
Expected: FAIL (all trucks listed, site not defaulted from truck).
- [ ] **Step 3: Implement**
`app/report/page.tsx`: add `siteId: trucks.siteId,` to the truck select, and in `truckList` add `site_id: t.siteId ?? null,`.
`components/incidents/report-form.tsx`:
3a. Imports: change the React import to `import { useState, useEffect, useMemo } from 'react'`; change the zones import to
```ts
import { zonesForSite, resolveZoneToken, siteIdForToken, type SiteOption } from '@/lib/report/zones'
import { trucksForSite, siteForTruck } from '@/lib/report/trucks'
```
3b. In `Props` change the trucks type to
`trucks: Array<{ id: string; truck_no: string; carrier: string | null; site_id: string | null }>`.
3c. Replace the `const [siteId, setSiteId] = useState(...)` block with:
```ts
const truckSite = !zoneToken ? siteForTruck(trucks, initialTruckId) : null
const [siteId, setSiteId] = useState(
truckSite && sites.some(s => s.id === truckSite)
? truckSite
: sites.some(s => s.id === defaultSiteId) ? defaultSiteId : (sites.length === 1 ? sites[0].id : '')
)
```
3d. After the `effectiveZoneToken` line add:
```ts
const effectiveSiteId = zoneToken ? siteIdForToken(sites, zoneToken) : siteId
const truckOptions = useMemo(() => trucksForSite(trucks, effectiveSiteId), [trucks, effectiveSiteId])
```
3e. After the `form` state declaration (it must come after `useState` for `form`) add:
```ts
useEffect(() => {
setForm(f => (f.truck_id && !truckOptions.some(tk => tk.id === f.truck_id) ? { ...f, truck_id: '' } : f))
}, [truckOptions])
```
(If the repo lint rule `react-hooks/set-state-in-effect` complains, add the same `// eslint-disable-next-line react-hooks/set-state-in-effect` comment used in this file above the `setForm` line.)
3f. In the Truck `<select>`, replace `{trucks.map(tk => (` with `{truckOptions.map(tk => (`.
- [ ] **Step 4: Run tests, typecheck, design gate, full suite**
Run: `npx vitest run tests/components/incidents/report-form-trucks.test.tsx && npx tsc --noEmit && npm run check:design && npx vitest run`
Expected: new tests PASS, tsc clean, `design gates: clean`, full suite shows only the 7 pre-existing failures.
- [ ] **Step 5: graphify and commit**
```bash
graphify update .
git add app/report/page.tsx components/incidents/report-form.tsx tests/components/incidents/report-form-trucks.test.tsx
git commit -m "feat(report): filter truck list by selected site"
```
@@ -1,72 +0,0 @@
# Zone picker, CAPA completion proof, test-data cleanup
Date: 2026-10-14. Status: draft for review.
Three independent changes from the 2026-10-13 field feedback. Each can ship on its own.
## 1. Zone picker on `/report`
### Problem
`/report` without `?zone=<qr_token>` shows "No zone detected — zone will not be recorded", but `POST /api/incidents` requires `zone_token` and returns 404 "Zone not found" without it. A user who opens Report from the Incidents page cannot submit.
### Design
- `app/report/page.tsx` also loads active sites with their active zones (`asAdmin`, same pattern as `trucks`) and passes `sites: { id, name, zones: { id, name, qr_code_token }[] }[]` and `defaultSiteId` (`users.site_id` of the session user) to `ReportForm`.
- With a valid QR token: unchanged ("Site — Zone" header, token sent as today).
- Without a token (or an unknown token): the "No zone detected" banner is removed. `ReportForm` shows two required selects, **Site** (default `defaultSiteId`) then **Zone** (filtered to the site). The chosen zone's `qr_code_token` is sent as `zone_token`.
- Submit button stays disabled until a zone is resolved (token or selection).
- No API or schema change; the server still validates the token and the active flags.
- New labels (Site, Zone, "Select zone…") added to the existing i18n message files.
- Offline queue: the queued payload already carries `zone_token`, so it keeps working.
### Out of scope
Making zone optional; a "General" zone per site.
## 2. CAPA completion proof
### Problem
`CapaOwnerActions` sends `PATCH /api/capa/[id] {status:'pending_verification'}` directly. The PIC can submit with no evidence and no notes.
### Design
- "Submit for Verification" opens a form: **completion note** (required) and **1 to 5 photos** (required, JPG/PNG/HEIC, same size limit as incident evidence). The submit button is disabled until both are present.
- New `POST /api/capa/[id]/submit` (multipart):
- Allowed: CAPA owner, or hse/admin. Status must be `in_progress`; otherwise 409.
- Validates note non-empty and 1 to 5 image files; otherwise 422.
- In one `withUser` transaction: store files via `lib/storage/evidence.ts`, insert `evidence_files` rows (`stage = 'capa'`, `capa_id` set, hash recorded), set `owner_notes`, `completed_at`, `status = 'pending_verification'`, and write `audit_log` (include file ids and the note).
- `PATCH /api/capa/[id]` rejects `status: 'pending_verification'` with 403 for everyone (the new endpoint is the only path). Owner `in_progress` transition is unchanged.
- CAPA detail page: "Completion report" section shows the note and a photo gallery (signed `/api/evidence/...` URLs) so HSE sees proof when verifying or reopening.
- Evidence rows are never hard-deleted (5-year retention).
### Schema change (manual, needs owner go-ahead)
```sql
ALTER TABLE evidence_files ADD COLUMN IF NOT EXISTS capa_id UUID REFERENCES capa_actions(id) ON DELETE RESTRICT;
CREATE INDEX IF NOT EXISTS evidence_files_capa_id_idx ON evidence_files(capa_id);
```
The `evidence_stage` enum already has `capa`; no enum change. Update `db/schema.sql`, `lib/db/schema.ts`, no RLS change: the PIC is the uploader and already reads own rows.
### Out of scope
Photos on "Mark In Progress"; HSE-side evidence upload; video.
## 3. Test-data cleanup (ops, one-off)
### Scope
Delete all incidents and every user with `role != 'admin'` from the production DB.
### Design
- Script `db/ops/cleanup-test-data.sql` plus a short runbook in `docs/`.
- Steps:
1. `pg_dump` of `ims` and a tar of `/var/lib/ims-evidence` on the server, kept outside the deploy folders.
2. Dry run: print row counts per table (incidents, children, users to delete, admins kept). Show the list of admins kept.
3. Wait for explicit user confirmation of those counts.
4. Run in one transaction, FK order: notifications (`notifications_log`, in-app), `capa_actions`, `investigations`, `dosh_reports`, addenda, `evidence_files`, `audit_log` rows for incidents, `incidents`, then `users` where `role != 'admin'`. Anything else referencing those users (audit_log `changed_by`, etc.) is nulled or removed per the real FK list found in the dry run.
5. Verify counts and that admin login works.
- Evidence files on disk are left in place (retention rule); orphaned files can be reviewed separately.
- Nothing runs against production without step 3 confirmation. Run after the schema change in section 2, or independently.
## Testing
- Zone picker: component test for site-to-zone filtering and submit gating; manual check with and without `?zone=`.
- CAPA submit: API tests for 401/403/409/422, success path writes files, audit row and status; PATCH bypass returns 403.
- Cleanup: dry-run counts match expectations on a restored dump before running on production.
- `npm run check:design` must print `design gates: clean` for UI changes.
## Deploy
Follow CLAUDE.md deploy steps (build locally, upload standalone build only, check `BUILD_ID`, restart, verify). Schema SQL applied by hand beforehand with the owner's go-ahead.
@@ -1,43 +0,0 @@
# Link trucks to a site
Date: 2026-10-15. Status: draft for review.
## Problem
Trucks are a flat list. The Report an Incident form shows every active truck regardless of site. Admin cannot say which site a truck belongs to.
## Decisions
- A truck links to **one** site (optional).
- The report form **filters** the Truck dropdown by the selected site.
- A truck with no site (all existing trucks) shows for **every** site until an admin assigns one.
## 1. Schema (manual, needs owner go-ahead)
```sql
ALTER TABLE trucks ADD COLUMN IF NOT EXISTS site_id UUID REFERENCES sites(id);
CREATE INDEX IF NOT EXISTS trucks_site_id_idx ON trucks(site_id);
```
- Add `db/ops/2026-10-15-trucks-site-id.sql` (wrapped in BEGIN/COMMIT), update `db/schema.sql` and `lib/db/schema.ts` (`siteId: uuid('site_id').references(() => sites.id)`).
- No RLS change: `trucks_read` (all) and `trucks_admin_all` already cover the column.
## 2. Admin, Trucks tab
- `app/(protected)/admin/page.tsx` selects `trucks.siteId`; `TruckManager` receives `site_id` per truck and the list of active sites.
- Add form: optional Site select. Each row shows the site name, or "Unassigned". Edit modal: Site select with a "No site" option.
- `POST /api/admin/trucks` and `PATCH /api/admin/trucks` accept `site_id` (uuid or null). Non-null must reference an existing active site, otherwise 422. Audit log entry stays in the same transaction and records old and new `site_id`.
## 3. Report form
- `app/report/page.tsx` passes `site_id` with each truck.
- New pure helper `trucksForSite(trucks, siteId)` in `lib/report/trucks.ts`: returns trucks where `site_id` is null or equals `siteId`; with no `siteId`, returns all.
- The site comes from the QR zone when present, otherwise from the Site select. When the site changes and the selected truck no longer fits, the selection clears.
- `?truck_id=` still pre-selects the truck. If no zone is given, the truck's `site_id` (when set) becomes the default site.
- `POST /api/incidents` is unchanged and does not reject a truck/site mismatch (UI filter only).
## Testing
- `trucksForSite` unit tests (null site, matching, other site, no site selected).
- API tests for `site_id` on create and edit: invalid site 422, valid site saved with audit row, null clears.
- Component test: truck dropdown filters on site change and clears an invalid selection.
- `npm run check:design` must print `design gates: clean`.
## Out of scope
Several sites per truck, bulk assignment, filtering the Incidents list by truck site.
## Deploy
Apply the SQL by hand first (additive, nullable, safe for the old build), then deploy per CLAUDE.md.
-11
View File
@@ -1,11 +0,0 @@
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
export type SiteIdInput = { ok: true; value: string | null | undefined } | { ok: false }
// undefined = field not sent, null/'' = clear the link, uuid string = set it.
export function parseSiteId(raw: unknown): SiteIdInput {
if (raw === undefined) return { ok: true, value: undefined }
if (raw === null || raw === '') return { ok: true, value: null }
if (typeof raw === 'string' && UUID_RE.test(raw)) return { ok: true, value: raw }
return { ok: false }
}
+9 -11
View File
@@ -1,28 +1,26 @@
// lib/auth/roles.ts // lib/auth/roles.ts
// 'ssa' = Site Safety Assistant. Replaces the former reporter, supervisor and capa_owner roles.
export type UserRole = export type UserRole =
| 'ssa' | 'reporter'
| 'supervisor'
| 'hse' | 'hse'
| 'capa_owner'
| 'management' | 'management'
| 'admin' | 'admin'
export const ALL_ROLES: UserRole[] = [ export const ALL_ROLES: UserRole[] = [
'ssa', 'reporter',
'supervisor',
'hse', 'hse',
'capa_owner',
'management', 'management',
'admin', 'admin',
] ]
export const ROLE_LABELS: Record<UserRole, string> = {
ssa: 'Site Safety Assistant (SSA)',
hse: 'HSE',
management: 'Management',
admin: 'Admin',
}
export const ROLE_HOME: Record<UserRole, string> = { export const ROLE_HOME: Record<UserRole, string> = {
ssa: '/ssa', reporter: '/reporter',
supervisor: '/supervisor',
hse: '/hse', hse: '/hse',
capa_owner: '/capa-owner',
management: '/management', management: '/management',
admin: '/admin', admin: '/admin',
} }
-18
View File
@@ -1,18 +0,0 @@
export const MAX_CAPA_PHOTOS = 5
export type CapaSubmissionResult =
| { ok: true; note: string }
| { ok: false; errors: string[] }
export function validateCapaSubmission(
note: string,
files: ReadonlyArray<{ type: string }>,
): CapaSubmissionResult {
const errors: string[] = []
const trimmed = note.trim()
if (!trimmed) errors.push('Completion note is required')
if (files.length < 1) errors.push('At least 1 photo is required')
if (files.length > MAX_CAPA_PHOTOS) errors.push(`At most ${MAX_CAPA_PHOTOS} photos are allowed`)
if (files.some(f => !f.type.startsWith('image/'))) errors.push('Only image files are allowed')
return errors.length ? { ok: false, errors } : { ok: true, note: trimmed }
}
-4
View File
@@ -3,7 +3,3 @@ import OpenAI from 'openai'
export function createDeepSeekClient(apiKey: string): OpenAI { export function createDeepSeekClient(apiKey: string): OpenAI {
return new OpenAI({ apiKey, baseURL: 'https://api.deepseek.com' }) return new OpenAI({ apiKey, baseURL: 'https://api.deepseek.com' })
} }
export function createLocalLLMClient(): OpenAI {
return new OpenAI({ apiKey: 'local', baseURL: 'http://localhost:8081/v1' })
}
+2 -5
View File
@@ -10,7 +10,6 @@ import {
date, date,
jsonb, jsonb,
customType, customType,
type AnyPgColumn,
} from 'drizzle-orm/pg-core' } from 'drizzle-orm/pg-core'
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -26,7 +25,7 @@ const vector = customType<{ data: number[]; driverData: string }>({
// Enums // Enums
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
export const userRoleEnum = pgEnum('user_role', [ export const userRoleEnum = pgEnum('user_role', [
'ssa', 'hse', 'management', 'admin', 'reporter', 'supervisor', 'hse', 'capa_owner', 'management', 'admin',
]) ])
export const incidentTypeEnum = pgEnum('incident_type', [ export const incidentTypeEnum = pgEnum('incident_type', [
@@ -89,7 +88,7 @@ export const users = pgTable('users', {
name: text('name').notNull().default(''), name: text('name').notNull().default(''),
email: text('email').notNull().default('').unique(), email: text('email').notNull().default('').unique(),
phone: text('phone'), phone: text('phone'),
role: userRoleEnum('role').notNull().default('ssa'), role: userRoleEnum('role').notNull().default('reporter'),
department: text('department'), department: text('department'),
siteId: uuid('site_id').references(() => sites.id), siteId: uuid('site_id').references(() => sites.id),
active: boolean('active').notNull().default(true), active: boolean('active').notNull().default(true),
@@ -103,7 +102,6 @@ export const trucks = pgTable('trucks', {
id: uuid('id').primaryKey().defaultRandom(), id: uuid('id').primaryKey().defaultRandom(),
truckNo: text('truck_no').notNull().unique(), truckNo: text('truck_no').notNull().unique(),
carrier: text('carrier'), carrier: text('carrier'),
siteId: uuid('site_id').references(() => sites.id),
active: boolean('active').notNull().default(true), active: boolean('active').notNull().default(true),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
}) })
@@ -147,7 +145,6 @@ export const evidenceFiles = pgTable('evidence_files', {
uploadedBy: uuid('uploaded_by').notNull().references(() => users.id), uploadedBy: uuid('uploaded_by').notNull().references(() => users.id),
uploadedAt: timestamp('uploaded_at', { withTimezone: true }).notNull().defaultNow(), uploadedAt: timestamp('uploaded_at', { withTimezone: true }).notNull().defaultNow(),
deleted: boolean('deleted').notNull().default(false), deleted: boolean('deleted').notNull().default(false),
capaId: uuid('capa_id').references((): AnyPgColumn => capaActions.id),
}) })
export const investigations = pgTable('investigations', { export const investigations = pgTable('investigations', {
+1 -1
View File
@@ -97,7 +97,7 @@ export async function escalateOverdueCapa(): Promise<{ notified: number }> {
.from(users) .from(users)
.where(and( .where(and(
eq(users.siteId, capa.siteId!), eq(users.siteId, capa.siteId!),
inArray(users.role, ['hse', 'ssa', 'management']), inArray(users.role, ['hse', 'supervisor', 'management']),
)) ))
) )
to.push(...hseUsers.map(u => u.email).filter(Boolean) as string[]) to.push(...hseUsers.map(u => u.email).filter(Boolean) as string[])
+1 -1
View File
@@ -15,7 +15,7 @@ export async function sendNewIncidentEmail(
db.select({ email: users.email }) db.select({ email: users.email })
.from(users) .from(users)
.where(and( .where(and(
inArray(users.role, ['ssa', 'hse']), inArray(users.role, ['supervisor', 'hse']),
eq(users.siteId, siteId), eq(users.siteId, siteId),
)) ))
) )
-12
View File
@@ -1,12 +0,0 @@
export function trucksForSite<T extends { site_id: string | null }>(trucks: T[], siteId: string): T[] {
if (!siteId) return trucks
return trucks.filter(t => t.site_id === null || t.site_id === siteId)
}
export function siteForTruck(
trucks: { id: string; site_id: string | null }[],
truckId: string | null | undefined,
): string | null {
if (!truckId) return null
return trucks.find(t => t.id === truckId)?.site_id ?? null
}
-38
View File
@@ -1,38 +0,0 @@
export type ZoneOption = { id: string; name: string; qr_code_token: string }
export type SiteOption = { id: string; name: string; zones: ZoneOption[] }
export type ZoneRow = { siteId: string; siteName: string; zoneId: string; zoneName: string; token: string }
export function groupSites(rows: ZoneRow[]): SiteOption[] {
const bySite = new Map<string, SiteOption>()
for (const r of rows) {
let site = bySite.get(r.siteId)
if (!site) {
site = { id: r.siteId, name: r.siteName, zones: [] }
bySite.set(r.siteId, site)
}
site.zones.push({ id: r.zoneId, name: r.zoneName, qr_code_token: r.token })
}
return [...bySite.values()]
}
export function zonesForSite(sites: SiteOption[], siteId: string): ZoneOption[] {
return sites.find(s => s.id === siteId)?.zones ?? []
}
export function resolveZoneToken(args: {
zoneToken: string | null
sites: SiteOption[]
zoneId: string
}): string | null {
if (args.zoneToken) return args.zoneToken
for (const site of args.sites) {
const zone = site.zones.find(z => z.id === args.zoneId)
if (zone) return zone.qr_code_token
}
return null
}
export function siteIdForToken(sites: SiteOption[], token: string | null): string {
if (!token) return ''
return sites.find(s => s.zones.some(z => z.qr_code_token === token))?.id ?? ''
}
+1 -5
View File
@@ -18,11 +18,7 @@
"savedOffline": "Report saved. It will be submitted automatically when you're back online.", "savedOffline": "Report saved. It will be submitted automatically when you're back online.",
"offlineBanner": "You're offline. Your report will be saved and submitted when you reconnect.", "offlineBanner": "You're offline. Your report will be saved and submitted when you reconnect.",
"truckLabel": "Truck", "truckLabel": "Truck",
"truckPlaceholder": "Select truck…", "truckPlaceholder": "Select truck…"
"siteLabel": "Site",
"sitePlaceholder": "Select site…",
"zoneLabel": "Zone",
"zonePlaceholder": "Select zone…"
}, },
"IncidentType": { "IncidentType": {
"injury": "Injury / Medical", "injury": "Injury / Medical",
+1 -5
View File
@@ -18,11 +18,7 @@
"savedOffline": "Laporan disimpan. Ia akan dihantar secara automatik apabila anda dalam talian semula.", "savedOffline": "Laporan disimpan. Ia akan dihantar secara automatik apabila anda dalam talian semula.",
"offlineBanner": "Anda tiada sambungan. Laporan anda akan disimpan dan dihantar apabila disambungkan semula.", "offlineBanner": "Anda tiada sambungan. Laporan anda akan disimpan dan dihantar apabila disambungkan semula.",
"truckLabel": "Trak", "truckLabel": "Trak",
"truckPlaceholder": "Pilih trak…", "truckPlaceholder": "Pilih trak…"
"siteLabel": "Tapak",
"sitePlaceholder": "Pilih tapak…",
"zoneLabel": "Zon",
"zonePlaceholder": "Pilih zon…"
}, },
"IncidentType": { "IncidentType": {
"injury": "Kecederaan / Perubatan", "injury": "Kecederaan / Perubatan",
+1 -5
View File
@@ -18,11 +18,7 @@
"savedOffline": "报告已保存。当您重新联网时将自动提交。", "savedOffline": "报告已保存。当您重新联网时将自动提交。",
"offlineBanner": "您处于离线状态。您的报告将在重新联网时自动提交。", "offlineBanner": "您处于离线状态。您的报告将在重新联网时自动提交。",
"truckLabel": "货车", "truckLabel": "货车",
"truckPlaceholder": "选择货车…", "truckPlaceholder": "选择货车…"
"siteLabel": "场地",
"sitePlaceholder": "选择场地…",
"zoneLabel": "区域",
"zonePlaceholder": "选择区域…"
}, },
"IncidentType": { "IncidentType": {
"injury": "受伤/医疗", "injury": "受伤/医疗",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

-149
View File
@@ -1,149 +0,0 @@
// @vitest-environment node
import { describe, it, expect, vi, beforeEach } from 'vitest'
const { selectQueue, setSpy, insertSpy, audit, txError } = vi.hoisted(() => ({
selectQueue: [] as unknown[][],
setSpy: vi.fn(),
insertSpy: vi.fn(),
audit: vi.fn(),
txError: { code: null as string | null },
}))
vi.mock('@/lib/auth/require-admin', () => ({
requireAdmin: async () => ({ session: { sub: 'admin-1', role: 'admin' } }),
}))
vi.mock('@/lib/db/audit', () => ({ writeAuditLog: audit }))
vi.mock('@/lib/db/with-user', () => {
const tx = {
execute: async () => undefined,
insert: () => ({
values: (v: unknown) => {
insertSpy(v)
return { returning: async () => [{ id: 'truck-new' }] }
},
}),
update: () => ({
set: (v: unknown) => {
setSpy(v)
return {
where: async () => {
if (txError.code) throw Object.assign(new Error('db'), { code: txError.code })
},
}
},
}),
}
const db = {
select: () => ({ from: () => ({ where: () => ({ limit: async () => selectQueue.shift() ?? [] }) }) }),
transaction: async (fn: (t: unknown) => unknown) => fn(tx),
}
return { asAdmin: async (fn: (d: unknown) => unknown) => fn(db) }
})
import { POST, PATCH } from '@/app/api/admin/trucks/route'
const SITE = '3f2b8c1e-9d4a-4e6f-8a1b-2c3d4e5f6a7b'
const req = (method: string, body: unknown) =>
new Request('http://localhost/api/admin/trucks', {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}) as never
beforeEach(() => {
selectQueue.length = 0
setSpy.mockClear()
insertSpy.mockClear()
audit.mockClear()
txError.code = null
})
describe('POST /api/admin/trucks', () => {
it('creates a truck with no site', async () => {
const res = await POST(req('POST', { truck_no: 'WXY 1' }))
expect(res.status).toBe(201)
expect(insertSpy).toHaveBeenCalledWith({ truckNo: 'WXY 1', carrier: null, siteId: null })
})
it('creates a truck linked to an active site and audits it', async () => {
selectQueue.push([{ id: SITE }])
const res = await POST(req('POST', { truck_no: 'WXY 2', site_id: SITE }))
expect(res.status).toBe(201)
expect(insertSpy).toHaveBeenCalledWith({ truckNo: 'WXY 2', carrier: null, siteId: SITE })
expect(audit).toHaveBeenCalledTimes(1)
expect(audit.mock.calls[0][4]).toMatchObject({ site_id: SITE })
})
it('422 for a malformed site_id', async () => {
const res = await POST(req('POST', { truck_no: 'WXY 3', site_id: 'abc' }))
expect(res.status).toBe(422)
expect(insertSpy).not.toHaveBeenCalled()
})
it('422 for an unknown or inactive site', async () => {
selectQueue.push([])
const res = await POST(req('POST', { truck_no: 'WXY 4', site_id: SITE }))
expect(res.status).toBe(422)
expect(insertSpy).not.toHaveBeenCalled()
})
})
describe('PATCH /api/admin/trucks', () => {
it('sets site_id and audits with the previous row', async () => {
selectQueue.push([{ id: 't1', siteId: null }], [{ id: SITE }])
const res = await PATCH(req('PATCH', { id: 't1', site_id: SITE }))
expect(res.status).toBe(200)
expect(setSpy).toHaveBeenCalledWith({ siteId: SITE })
expect(audit).toHaveBeenCalledTimes(1)
expect(audit.mock.calls[0][4]).toEqual({ siteId: SITE })
expect(audit.mock.calls[0][5]).toEqual({ id: 't1', siteId: null })
})
it('clears the site with null', async () => {
selectQueue.push([{ id: 't1', siteId: SITE }])
const res = await PATCH(req('PATCH', { id: 't1', site_id: null }))
expect(res.status).toBe(200)
expect(setSpy).toHaveBeenCalledWith({ siteId: null })
})
it('edits truck_no and carrier together', async () => {
selectQueue.push([{ id: 't1' }])
const res = await PATCH(req('PATCH', { id: 't1', truck_no: ' ABC 9 ', carrier: ' ' }))
expect(res.status).toBe(200)
expect(setSpy).toHaveBeenCalledWith({ truckNo: 'ABC 9', carrier: null })
})
it('still toggles active', async () => {
selectQueue.push([{ id: 't1' }])
const res = await PATCH(req('PATCH', { id: 't1', active: false }))
expect(res.status).toBe(200)
expect(setSpy).toHaveBeenCalledWith({ active: false })
})
it('422 when nothing to change', async () => {
const res = await PATCH(req('PATCH', { id: 't1' }))
expect(res.status).toBe(422)
})
it('422 for an empty truck_no', async () => {
const res = await PATCH(req('PATCH', { id: 't1', truck_no: ' ' }))
expect(res.status).toBe(422)
expect(setSpy).not.toHaveBeenCalled()
})
it('422 for a malformed or unknown site', async () => {
expect((await PATCH(req('PATCH', { id: 't1', site_id: 'abc' }))).status).toBe(422)
selectQueue.push([{ id: 't1' }], [])
expect((await PATCH(req('PATCH', { id: 't1', site_id: SITE }))).status).toBe(422)
expect(setSpy).not.toHaveBeenCalled()
})
it('skips the active-site check when the site is unchanged', async () => {
selectQueue.push([{ id: 't1', siteId: SITE }])
const res = await PATCH(req('PATCH', { id: 't1', truck_no: 'NEW 1', site_id: SITE }))
expect(res.status).toBe(200)
expect(setSpy).toHaveBeenCalledWith({ truckNo: 'NEW 1', siteId: SITE })
})
it('422 when moving a site-less truck to an inactive site', async () => {
selectQueue.push([{ id: 't1', siteId: null }], [])
const res = await PATCH(req('PATCH', { id: 't1', site_id: SITE }))
expect(res.status).toBe(422)
expect(setSpy).not.toHaveBeenCalled()
})
it('409 for a duplicate truck number', async () => {
selectQueue.push([{ id: 't1' }])
txError.code = '23505'
const res = await PATCH(req('PATCH', { id: 't1', truck_no: 'DUP 1' }))
expect(res.status).toBe(409)
})
})
-35
View File
@@ -1,35 +0,0 @@
// @vitest-environment node
import { describe, it, expect, vi } from 'vitest'
vi.mock('@/lib/auth/get-session', () => ({
getSession: async () => ({ sub: 'owner-1', role: 'ssa' }),
}))
vi.mock('@/lib/db/audit', () => ({ writeAuditLog: vi.fn() }))
vi.mock('@/lib/db/with-user', () => ({
withUser: async (_id: string, fn: (tx: unknown) => unknown) =>
fn({
select: () => ({ from: () => ({ where: () => ({ limit: async () => [{ ownerUserId: 'owner-1', status: 'in_progress' }] }) }) }),
update: () => ({ set: () => ({ where: async () => undefined }) }),
}),
}))
import { PATCH } from '@/app/api/capa/[id]/route'
const ctx = { params: Promise.resolve({ id: 'capa-1' }) }
const patch = (body: unknown) =>
new Request('http://localhost/api/capa/capa-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
describe('PATCH /api/capa/[id]', () => {
it('rejects pending_verification (must use /submit)', async () => {
const res = await PATCH(patch({ status: 'pending_verification' }) as never, ctx)
expect(res.status).toBe(403)
})
it('still allows in_progress', async () => {
const res = await PATCH(patch({ status: 'in_progress' }) as never, ctx)
expect(res.status).toBe(200)
})
})
-117
View File
@@ -1,117 +0,0 @@
// @vitest-environment node
import { describe, it, expect, vi, beforeEach } from 'vitest'
const h = vi.hoisted(() => ({
session: null as null | { sub: string; role: string },
capa: null as null | { incidentId: string; ownerUserId: string; status: string },
updates: [] as unknown[],
inserts: [] as unknown[],
updateRows: [{ id: 'capa-1' }] as unknown[],
}))
vi.mock('@/lib/auth/get-session', () => ({ getSession: async () => h.session }))
vi.mock('@/lib/db/audit', () => ({ writeAuditLog: vi.fn() }))
vi.mock('@/lib/storage/evidence', () => ({
uploadEvidenceFile: vi.fn(async () => ({ path: 'p', publicUrl: '/api/evidence/p?token=t', hash: 'h' })),
}))
vi.mock('@/lib/db/with-user', () => ({
withUser: async (_id: string, fn: (tx: unknown) => unknown) => {
const tx = {
select: () => ({ from: () => ({ where: () => ({ limit: async () => (h.capa ? [h.capa] : []) }) }) }),
insert: () => ({ values: (v: unknown) => { h.inserts.push(v); return { returning: async () => [{ id: 'ev-1' }] } } }),
update: () => ({ set: (v: unknown) => { h.updates.push(v); return { where: () => ({ returning: async () => h.updateRows }) } } }),
}
return fn(tx)
},
}))
import { writeAuditLog } from '@/lib/db/audit'
import { uploadEvidenceFile } from '@/lib/storage/evidence'
import { POST } from '@/app/api/capa/[id]/submit/route'
function req(note: string | null, fileCount: number) {
const fd = new FormData()
if (note !== null) fd.append('note', note)
for (let i = 0; i < fileCount; i++) fd.append('files', new File(['x'], `p${i}.jpg`, { type: 'image/jpeg' }))
return new Request('http://localhost/api/capa/capa-1/submit', { method: 'POST', body: fd })
}
const ctx = { params: Promise.resolve({ id: 'capa-1' }) }
beforeEach(() => {
h.session = { sub: 'owner-1', role: 'ssa' }
h.capa = { incidentId: 'inc-1', ownerUserId: 'owner-1', status: 'in_progress' }
h.updates = []
h.inserts = []
h.updateRows = [{ id: 'capa-1' }]
vi.mocked(writeAuditLog).mockClear()
})
describe('POST /api/capa/[id]/submit', () => {
it('401 without a session', async () => {
h.session = null
expect((await POST(req('done', 1) as never, ctx)).status).toBe(401)
})
it('404 when the CAPA does not exist', async () => {
h.capa = null
expect((await POST(req('done', 1) as never, ctx)).status).toBe(404)
})
it('403 for a user who is neither owner nor hse/admin', async () => {
h.session = { sub: 'other', role: 'ssa' }
expect((await POST(req('done', 1) as never, ctx)).status).toBe(403)
})
it('409 when status is not in_progress', async () => {
h.capa!.status = 'open'
expect((await POST(req('done', 1) as never, ctx)).status).toBe(409)
})
it('422 when no photo is attached', async () => {
const res = await POST(req('done', 0) as never, ctx)
expect(res.status).toBe(422)
expect((await res.json()).details).toContain('At least 1 photo is required')
})
it('422 when the note is empty', async () => {
expect((await POST(req(' ', 1) as never, ctx)).status).toBe(422)
})
it('stores evidence, sets status and audits on success', async () => {
const res = await POST(req(' fixed the rack ', 2) as never, ctx)
expect(res.status).toBe(200)
expect(h.inserts[0]).toEqual([
expect.objectContaining({ incidentId: 'inc-1', capaId: 'capa-1', stage: 'capa', uploadedBy: 'owner-1' }),
expect.objectContaining({ incidentId: 'inc-1', capaId: 'capa-1', stage: 'capa', uploadedBy: 'owner-1' }),
])
expect(h.updates[0]).toEqual(
expect.objectContaining({ status: 'pending_verification', ownerNotes: 'fixed the rack', completedAt: expect.any(Date) }),
)
expect(writeAuditLog).toHaveBeenCalledWith(
expect.anything(), 'capa_actions', 'capa-1', 'submitted_for_verification',
expect.objectContaining({ status: 'pending_verification' }),
expect.objectContaining({ status: 'in_progress' }),
)
})
it('409 on a lost race: no evidence insert, no audit', async () => {
h.updateRows = []
const res = await POST(req('done', 1) as never, ctx)
expect(res.status).toBe(409)
expect(h.inserts).toHaveLength(0)
expect(writeAuditLog).not.toHaveBeenCalled()
})
it('422 with details and no DB writes when upload fails', async () => {
vi.mocked(uploadEvidenceFile).mockRejectedValueOnce(new Error('disk full'))
const res = await POST(req('done', 1) as never, ctx)
expect(res.status).toBe(422)
expect((await res.json()).details).toContain('disk full')
expect(h.inserts).toHaveLength(0)
expect(h.updates).toHaveLength(0)
expect(writeAuditLog).not.toHaveBeenCalled()
})
it('200 for an hse non-owner, evidence uploadedBy is the hse user', async () => {
h.session = { sub: 'hse-1', role: 'hse' }
const res = await POST(req('done', 1) as never, ctx)
expect(res.status).toBe(200)
expect(h.inserts[0]).toEqual([expect.objectContaining({ uploadedBy: 'hse-1' })])
})
it('422 for 6 files at route level', async () => {
const res = await POST(req('done', 6) as never, ctx)
expect(res.status).toBe(422)
expect((await res.json()).details).toContain('At most 5 photos are allowed')
})
})
+6 -2
View File
@@ -17,7 +17,7 @@ vi.mock('@/lib/supabase/server', () => ({
})) }))
vi.mock('@/lib/claude/client', () => ({ vi.mock('@/lib/claude/client', () => ({
createLocalLLMClient: vi.fn().mockReturnValue({ createDeepSeekClient: vi.fn().mockReturnValue({
chat: { chat: {
completions: { completions: {
create: vi.fn().mockResolvedValue({ create: vi.fn().mockResolvedValue({
@@ -38,6 +38,10 @@ vi.mock('@/lib/claude/client', () => ({
}), }),
})) }))
vi.mock('@/lib/settings', () => ({
getApiKey: vi.fn().mockResolvedValue('sk-test-key'),
}))
describe('POST /api/incidents/ai/quality-check', () => { describe('POST /api/incidents/ai/quality-check', () => {
it('returns 422 when description is missing', async () => { it('returns 422 when description is missing', async () => {
const { POST } = await import('@/app/api/incidents/ai/quality-check/route') const { POST } = await import('@/app/api/incidents/ai/quality-check/route')
@@ -50,7 +54,7 @@ describe('POST /api/incidents/ai/quality-check', () => {
expect(res.status).toBe(422) expect(res.status).toBe(422)
}) })
it('returns quality assessment from local LLM', async () => { it('returns quality assessment from DeepSeek', async () => {
const { POST } = await import('@/app/api/incidents/ai/quality-check/route') const { POST } = await import('@/app/api/incidents/ai/quality-check/route')
const req = new Request('http://localhost/api/incidents/ai/quality-check', { const req = new Request('http://localhost/api/incidents/ai/quality-check', {
method: 'POST', method: 'POST',
+5 -1
View File
@@ -46,7 +46,7 @@ vi.mock('@/lib/supabase/server', () => ({
})) }))
vi.mock('@/lib/claude/client', () => ({ vi.mock('@/lib/claude/client', () => ({
createLocalLLMClient: vi.fn().mockReturnValue({ createDeepSeekClient: vi.fn().mockReturnValue({
chat: { chat: {
completions: { completions: {
create: vi.fn().mockResolvedValue({ create: vi.fn().mockResolvedValue({
@@ -67,6 +67,10 @@ vi.mock('@/lib/claude/client', () => ({
}), }),
})) }))
vi.mock('@/lib/settings', () => ({
getApiKey: vi.fn().mockResolvedValue('sk-test-key'),
}))
describe('POST /api/incidents/[id]/ai/rca-draft', () => { describe('POST /api/incidents/[id]/ai/rca-draft', () => {
it('returns five_why_steps, root_cause_summary, and capa_suggestions', async () => { it('returns five_why_steps, root_cause_summary, and capa_suggestions', async () => {
const { POST } = await import('@/app/api/incidents/[id]/ai/rca-draft/route') const { POST } = await import('@/app/api/incidents/[id]/ai/rca-draft/route')
+5 -1
View File
@@ -36,7 +36,7 @@ vi.mock('@/lib/supabase/server', () => ({
})) }))
vi.mock('@/lib/claude/client', () => ({ vi.mock('@/lib/claude/client', () => ({
createLocalLLMClient: vi.fn().mockReturnValue({ createDeepSeekClient: vi.fn().mockReturnValue({
chat: { chat: {
completions: { completions: {
create: vi.fn().mockResolvedValue({ create: vi.fn().mockResolvedValue({
@@ -57,6 +57,10 @@ vi.mock('@/lib/claude/client', () => ({
}), }),
})) }))
vi.mock('@/lib/settings', () => ({
getApiKey: vi.fn().mockResolvedValue('sk-test-key'),
}))
describe('POST /api/incidents/[id]/ai/triage-suggest', () => { describe('POST /api/incidents/[id]/ai/triage-suggest', () => {
it('returns triage suggestion with severity and DOSH flags', async () => { it('returns triage suggestion with severity and DOSH flags', async () => {
const { POST } = await import('@/app/api/incidents/[id]/ai/triage-suggest/route') const { POST } = await import('@/app/api/incidents/[id]/ai/triage-suggest/route')
+1 -1
View File
@@ -64,7 +64,7 @@ describe('GET /api/incidents/[id]/report-pdf', () => {
}) })
it('returns 403 for non-hse/admin roles', async () => { it('returns 403 for non-hse/admin roles', async () => {
vi.mocked(getSession).mockResolvedValue({ ...mockSession, role: 'ssa' as never }) vi.mocked(getSession).mockResolvedValue({ ...mockSession, role: 'reporter' as never })
const res = await GET(makeRequest('inc-1'), { params: Promise.resolve({ id: 'inc-1' }) }) const res = await GET(makeRequest('inc-1'), { params: Promise.resolve({ id: 'inc-1' }) })
expect(res.status).toBe(403) expect(res.status).toBe(403)
}) })
@@ -1,83 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { TruckManager, type Truck, type TruckSite } from '@/components/admin/truck-manager'
const { refresh } = vi.hoisted(() => ({ refresh: vi.fn() }))
vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh }) }))
const fetchMock = vi.fn()
beforeEach(() => {
refresh.mockClear()
fetchMock.mockReset()
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ ok: true }) })
vi.stubGlobal('fetch', fetchMock)
})
const sites: TruckSite[] = [
{ id: 'site-a', name: 'Site A', active: true },
{ id: 'site-b', name: 'Site B', active: true },
{ id: 'site-old', name: 'Old Site', active: false },
]
const trucks: Truck[] = [
{ id: 't1', truck_no: 'WXY 1', carrier: null, site_id: 'site-a', active: true },
{ id: 't2', truck_no: 'WXY 2', carrier: 'Setia', site_id: null, active: true },
]
describe('TruckManager site link', () => {
it('shows the site name or Unassigned on each row', () => {
render(<TruckManager trucks={trucks} sites={sites} />)
expect(screen.getByText('Site A')).toBeTruthy()
expect(screen.getByText('Unassigned')).toBeTruthy()
})
it('edits the site of a truck via PATCH', async () => {
render(<TruckManager trucks={trucks} sites={sites} />)
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[1])
fireEvent.change(screen.getByLabelText('Site'), { target: { value: 'site-b' } })
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
await waitFor(() => expect(fetchMock).toHaveBeenCalled())
const [url, init] = fetchMock.mock.calls[0]
expect(url).toBe('/api/admin/trucks')
expect(init.method).toBe('PATCH')
expect(JSON.parse(init.body)).toEqual({ id: 't2', truck_no: 'WXY 2', carrier: 'Setia', site_id: 'site-b' })
await waitFor(() => expect(refresh).toHaveBeenCalled())
})
it('clears the site with the No site option', async () => {
render(<TruckManager trucks={trucks} sites={sites} />)
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[0])
fireEvent.change(screen.getByLabelText('Site'), { target: { value: '' } })
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
await waitFor(() => expect(fetchMock).toHaveBeenCalled())
expect(JSON.parse(fetchMock.mock.calls[0][1].body).site_id).toBeNull()
})
it('does not offer inactive sites unless already linked', () => {
render(<TruckManager trucks={trucks} sites={sites} />)
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[0])
const select = screen.getByLabelText('Site') as HTMLSelectElement
const labels = Array.from(select.options).map(o => o.textContent)
expect(labels).toEqual(['No site', 'Site A', 'Site B'])
})
it('keeps the inactive site selectable for a truck already linked to it', () => {
const oldTrucks: Truck[] = [
{ id: 't9', truck_no: 'OLD 9', carrier: null, site_id: 'site-old', active: true },
]
render(<TruckManager trucks={oldTrucks} sites={sites} />)
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[0])
const select = screen.getByLabelText('Site') as HTMLSelectElement
const labels = Array.from(select.options).map(o => o.textContent)
expect(labels).toEqual(['No site', 'Site A', 'Site B', 'Old Site'])
})
it('sends site_id when adding a truck', async () => {
render(<TruckManager trucks={trucks} sites={sites} />)
fireEvent.click(screen.getByRole('button', { name: /Add Truck/ }))
fireEvent.change(screen.getByLabelText(/Truck Number/), { target: { value: 'NEW 1' } })
fireEvent.change(screen.getByLabelText('Site'), { target: { value: 'site-b' } })
fireEvent.click(screen.getAllByRole('button', { name: 'Add Truck' }).pop()!)
await waitFor(() => expect(fetchMock).toHaveBeenCalled())
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ truck_no: 'NEW 1', carrier: null, site_id: 'site-b' })
})
})
@@ -1,91 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { SubmitVerificationForm } from '@/components/capa/submit-verification-form'
const { refresh } = vi.hoisted(() => ({ refresh: vi.fn() }))
vi.mock('next/navigation', () => ({
useRouter: () => ({ refresh }),
}))
const fetchMock = vi.fn()
beforeEach(() => {
refresh.mockClear()
fetchMock.mockReset()
vi.stubGlobal('fetch', fetchMock)
})
function fill(container: HTMLElement, names: string[] = ['proof.jpg']) {
fireEvent.change(screen.getByLabelText('Completion note'), { target: { value: 'Rack fixed' } })
const input = container.querySelector('input[type="file"]') as HTMLInputElement
const files = names.map(n => new File(['x'], n, { type: 'image/jpeg' }))
fireEvent.change(input, { target: { files } })
}
function button() {
return screen.getByRole('button', { name: 'Submit for Verification' }) as HTMLButtonElement
}
describe('SubmitVerificationForm', () => {
it('is disabled until a note and a photo are provided', () => {
const { container } = render(<SubmitVerificationForm capaId="abc" />)
expect(button().disabled).toBe(true)
fireEvent.change(screen.getByLabelText('Completion note'), { target: { value: 'Rack fixed' } })
expect(button().disabled).toBe(true)
const input = container.querySelector('input[type="file"]') as HTMLInputElement
const file = new File(['x'], 'proof.jpg', { type: 'image/jpeg' })
fireEvent.change(input, { target: { files: [file] } })
expect(button().disabled).toBe(false)
expect(screen.getByText('proof.jpg')).toBeTruthy()
})
it('posts FormData on success, refreshes and stays disabled', async () => {
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ ok: true }) })
const { container } = render(<SubmitVerificationForm capaId="abc" />)
fill(container)
fireEvent.click(button())
await waitFor(() => expect(refresh).toHaveBeenCalledTimes(1))
const [url, init] = fetchMock.mock.calls[0]
expect(url).toBe('/api/capa/abc/submit')
expect(init.method).toBe('POST')
const fd = init.body as FormData
expect(fd.get('note')).toBe('Rack fixed')
expect((fd.getAll('files') as File[]).map(f => f.name)).toEqual(['proof.jpg'])
expect((screen.getByRole('button', { name: 'Submitting…' }) as HTMLButtonElement).disabled).toBe(true)
})
it('shows server details and re-enables on 422', async () => {
fetchMock.mockResolvedValue({ ok: false, json: async () => ({ error: 'bad', details: ['Note too short', 'Bad photo'] }) })
const { container } = render(<SubmitVerificationForm capaId="abc" />)
fill(container)
fireEvent.click(button())
expect((await screen.findByRole('alert')).textContent).toBe('Note too short. Bad photo')
expect(button().disabled).toBe(false)
expect(refresh).not.toHaveBeenCalled()
})
it('shows a network error and re-enables when fetch rejects', async () => {
fetchMock.mockRejectedValue(new Error('offline'))
const { container } = render(<SubmitVerificationForm capaId="abc" />)
fill(container)
fireEvent.click(button())
expect((await screen.findByRole('alert')).textContent).toBe('Network error. Please try again.')
expect(button().disabled).toBe(false)
})
it('disables submit again after removing the only file', () => {
const { container } = render(<SubmitVerificationForm capaId="abc" />)
fill(container)
expect(button().disabled).toBe(false)
fireEvent.click(screen.getByLabelText('Remove proof.jpg'))
expect(button().disabled).toBe(true)
})
it('caps the list at 5 photos', () => {
const { container } = render(<SubmitVerificationForm capaId="abc" />)
fill(container, ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'])
expect(screen.getAllByText(/^\d\.jpg$/)).toHaveLength(5)
expect(screen.queryByText('6.jpg')).toBeNull()
})
})
@@ -1,64 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent, within } from '@testing-library/react'
import { ReportForm } from '@/components/incidents/report-form'
import { I18nProvider } from '@/lib/i18n/context'
import en from '@/messages/en.json'
vi.mock('next/navigation', () => ({ useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }) }))
const sites = [
{ id: 'site-a', name: 'Site A', zones: [{ id: 'z1', name: 'Dock', qr_code_token: 'tok-a' }] },
{ id: 'site-b', name: 'Site B', zones: [{ id: 'z2', name: 'Yard', qr_code_token: 'tok-b' }] },
]
const trucks = [
{ id: 't1', truck_no: 'AAA 1', carrier: null, site_id: 'site-a' },
{ id: 't2', truck_no: 'BBB 2', carrier: null, site_id: 'site-b' },
{ id: 't3', truck_no: 'FREE 3', carrier: null, site_id: null },
]
function renderForm(props: Partial<React.ComponentProps<typeof ReportForm>> = {}) {
return render(
<I18nProvider messages={en}>
<ReportForm
zoneToken={null}
zoneName={null}
siteName={null}
sites={sites}
defaultSiteId=""
trucks={trucks}
initialTruckId="t1"
{...props}
/>
</I18nProvider>,
)
}
const selectWith = (text: string) =>
screen.getAllByRole('combobox').find(s => within(s).queryByText(text)) as HTMLSelectElement
const truckNos = () =>
Array.from(selectWith(en.ReportForm.truckPlaceholder).options).map(o => o.textContent)
describe('ReportForm truck list', () => {
const all = [en.ReportForm.truckPlaceholder, 'AAA 1', 'BBB 2', 'FREE 3']
it('shows every truck regardless of site', () => {
renderForm()
expect(truckNos()).toEqual(all)
})
it('keeps the chosen truck when the site changes', () => {
renderForm()
fireEvent.change(selectWith(en.ReportForm.sitePlaceholder), { target: { value: 'site-b' } })
expect(truckNos()).toEqual(all)
expect(selectWith(en.ReportForm.truckPlaceholder).value).toBe('t1')
})
it('shows every truck with a QR zone token', () => {
renderForm({ zoneToken: 'tok-b', zoneName: 'Yard', siteName: 'Site B', initialTruckId: null })
fireEvent.change(screen.getAllByRole('combobox').find(s => within(s).queryByText(en.IncidentType.transport))!, {
target: { value: 'transport' },
})
expect(truckNos()).toEqual(all)
})
})
+1 -6
View File
@@ -49,13 +49,8 @@ describe('AppShell', () => {
expect(document.activeElement?.getAttribute('name')).toBe('q') expect(document.activeElement?.getAttribute('name')).toBe('q')
}) })
it('targets the site incident list for the SSA role', () => {
const { container } = render(<AppShell role="ssa" userName="Ada"><span /></AppShell>)
expect(container.querySelector('header form')!.getAttribute('action')).toBe('/ssa/incidents')
})
it('hides the search box for roles without an incident list', () => { it('hides the search box for roles without an incident list', () => {
const { container } = render(<AppShell role="management" userName="Ada"><span /></AppShell>) const { container } = render(<AppShell role="reporter" userName="Ada"><span /></AppShell>)
expect(container.querySelector('header form')).toBeNull() expect(container.querySelector('header form')).toBeNull()
}) })
+7 -5
View File
@@ -2,21 +2,23 @@ import { describe, it, expect } from 'vitest'
import { navItemsFor, isActivePath, searchHrefFor } from '@/components/layout/nav-items' import { navItemsFor, isActivePath, searchHrefFor } from '@/components/layout/nav-items'
describe('nav items', () => { describe('nav items', () => {
it('returns the role menu and falls back to ssa', () => { it('returns the role menu and falls back to reporter', () => {
expect(navItemsFor('hse').map(i => i.label)).toEqual(['Dashboard', 'Incidents', 'CAPA', 'Settings']) expect(navItemsFor('hse').map(i => i.label)).toEqual(['Dashboard', 'Incidents', 'CAPA', 'Settings'])
expect(navItemsFor('admin')[0].label).toBe('Admin') expect(navItemsFor('admin')[0].label).toBe('Admin')
expect(navItemsFor('nobody')).toEqual(navItemsFor('ssa')) expect(navItemsFor('nobody')).toEqual(navItemsFor('reporter'))
}) })
it('matches root pages exactly and nested pages by prefix', () => { it('matches root pages exactly and nested pages by prefix', () => {
expect(isActivePath('/ssa', '/ssa')).toBe(true) expect(isActivePath('/reporter', '/reporter')).toBe(true)
expect(isActivePath('/ssa', '/ssa/incidents/1')).toBe(false) expect(isActivePath('/reporter', '/reporter/incidents/1')).toBe(false)
expect(isActivePath('/hse/incidents', '/hse/incidents/abc')).toBe(true) expect(isActivePath('/hse/incidents', '/hse/incidents/abc')).toBe(true)
}) })
it('offers the search box only to roles that have an incident list', () => { it('offers the search box only to roles that have an incident list', () => {
expect(searchHrefFor('hse')).toBe('/hse/incidents') expect(searchHrefFor('hse')).toBe('/hse/incidents')
expect(searchHrefFor('admin')).toBe('/hse/incidents') expect(searchHrefFor('admin')).toBe('/hse/incidents')
expect(searchHrefFor('ssa')).toBe('/ssa/incidents') expect(searchHrefFor('supervisor')).toBe('/supervisor/incidents')
expect(searchHrefFor('reporter')).toBeNull()
expect(searchHrefFor('capa_owner')).toBeNull()
}) })
}) })
-21
View File
@@ -1,21 +0,0 @@
import { describe, it, expect } from 'vitest'
import { parseSiteId } from '@/lib/admin/truck-input'
const UUID = '3f2b8c1e-9d4a-4e6f-8a1b-2c3d4e5f6a7b'
describe('parseSiteId', () => {
it('treats undefined as not provided', () => {
expect(parseSiteId(undefined)).toEqual({ ok: true, value: undefined })
})
it('treats null and empty string as clear', () => {
expect(parseSiteId(null)).toEqual({ ok: true, value: null })
expect(parseSiteId('')).toEqual({ ok: true, value: null })
})
it('accepts a uuid', () => {
expect(parseSiteId(UUID)).toEqual({ ok: true, value: UUID })
})
it('rejects anything else', () => {
expect(parseSiteId('abc')).toEqual({ ok: false })
expect(parseSiteId(12)).toEqual({ ok: false })
})
})
-30
View File
@@ -1,30 +0,0 @@
import { describe, it, expect } from 'vitest'
import { validateCapaSubmission, MAX_CAPA_PHOTOS } from '@/lib/capa/submit-validation'
const img = { type: 'image/jpeg' }
describe('validateCapaSubmission', () => {
it('accepts a note with 1 image and trims the note', () => {
expect(validateCapaSubmission(' done ', [img])).toEqual({ ok: true, note: 'done' })
})
it('rejects an empty or whitespace note', () => {
const r = validateCapaSubmission(' ', [img])
expect(r.ok).toBe(false)
if (!r.ok) expect(r.errors).toContain('Completion note is required')
})
it('rejects zero files', () => {
const r = validateCapaSubmission('done', [])
expect(r.ok).toBe(false)
if (!r.ok) expect(r.errors).toContain('At least 1 photo is required')
})
it('rejects more than the max', () => {
const r = validateCapaSubmission('done', Array(MAX_CAPA_PHOTOS + 1).fill(img))
expect(r.ok).toBe(false)
if (!r.ok) expect(r.errors).toContain(`At most ${MAX_CAPA_PHOTOS} photos are allowed`)
})
it('rejects non-image files', () => {
const r = validateCapaSubmission('done', [{ type: 'application/pdf' }])
expect(r.ok).toBe(false)
if (!r.ok) expect(r.errors).toContain('Only image files are allowed')
})
})
+3 -3
View File
@@ -14,7 +14,7 @@ vi.mock('resend', () => {
// Mock asAdmin: first call returns recipients, second returns incident+join rows // Mock asAdmin: first call returns recipients, second returns incident+join rows
let asAdminCallCount = 0 let asAdminCallCount = 0
const mockRecipients = [ const mockRecipients = [
{ email: 'ssa@setiacorp.com' }, { email: 'supervisor@setiacorp.com' },
{ email: 'hse@setiacorp.com' }, { email: 'hse@setiacorp.com' },
] ]
const mockIncidentRows = [{ const mockIncidentRows = [{
@@ -44,11 +44,11 @@ beforeEach(() => {
}) })
describe('sendNewIncidentEmail', () => { describe('sendNewIncidentEmail', () => {
it('sends email to ssa and hse users', async () => { it('sends email to supervisor and hse users', async () => {
await sendNewIncidentEmail('inc-001', 'site-001', 'SCW1-202607-0001', 'near_miss') await sendNewIncidentEmail('inc-001', 'site-001', 'SCW1-202607-0001', 'near_miss')
expect(mockSend).toHaveBeenCalledTimes(1) expect(mockSend).toHaveBeenCalledTimes(1)
const call = mockSend.mock.calls[0][0] const call = mockSend.mock.calls[0][0]
expect(call.to).toEqual(expect.arrayContaining(['ssa@setiacorp.com', 'hse@setiacorp.com'])) expect(call.to).toEqual(expect.arrayContaining(['supervisor@setiacorp.com', 'hse@setiacorp.com']))
expect(call.subject).toContain('SCW1-202607-0001') expect(call.subject).toContain('SCW1-202607-0001')
}) })
-32
View File
@@ -1,32 +0,0 @@
import { describe, it, expect } from 'vitest'
import { trucksForSite, siteForTruck } from '@/lib/report/trucks'
const trucks = [
{ id: 't1', site_id: 'A' },
{ id: 't2', site_id: 'B' },
{ id: 't3', site_id: null },
]
describe('trucksForSite', () => {
it('returns matching and unassigned trucks', () => {
expect(trucksForSite(trucks, 'A').map(t => t.id)).toEqual(['t1', 't3'])
expect(trucksForSite(trucks, 'B').map(t => t.id)).toEqual(['t2', 't3'])
})
it('returns all trucks when no site is selected', () => {
expect(trucksForSite(trucks, '').map(t => t.id)).toEqual(['t1', 't2', 't3'])
})
it('returns only unassigned trucks for a site with none linked', () => {
expect(trucksForSite(trucks, 'C').map(t => t.id)).toEqual(['t3'])
})
})
describe('siteForTruck', () => {
it('returns the truck site', () => {
expect(siteForTruck(trucks, 't2')).toBe('B')
})
it('returns null for unassigned, unknown or missing truck', () => {
expect(siteForTruck(trucks, 't3')).toBeNull()
expect(siteForTruck(trucks, 'nope')).toBeNull()
expect(siteForTruck(trucks, null)).toBeNull()
})
})
-60
View File
@@ -1,60 +0,0 @@
import { describe, it, expect } from 'vitest'
import { groupSites, zonesForSite, resolveZoneToken, siteIdForToken, type ZoneRow } from '@/lib/report/zones'
const rows: ZoneRow[] = [
{ siteId: 's1', siteName: 'SC1', zoneId: 'z1', zoneName: 'Dock A', token: 'tok-a' },
{ siteId: 's1', siteName: 'SC1', zoneId: 'z2', zoneName: 'Dock B', token: 'tok-b' },
{ siteId: 's2', siteName: 'SC2', zoneId: 'z3', zoneName: 'Cold Room', token: 'tok-c' },
]
describe('groupSites', () => {
it('groups zone rows under their site, keeping order', () => {
const sites = groupSites(rows)
expect(sites.map(s => s.name)).toEqual(['SC1', 'SC2'])
expect(sites[0].zones.map(z => z.name)).toEqual(['Dock A', 'Dock B'])
expect(sites[1].zones[0]).toEqual({ id: 'z3', name: 'Cold Room', qr_code_token: 'tok-c' })
})
it('returns [] for no rows', () => {
expect(groupSites([])).toEqual([])
})
})
describe('zonesForSite', () => {
const sites = groupSites(rows)
it('returns the zones of the given site', () => {
expect(zonesForSite(sites, 's2').map(z => z.id)).toEqual(['z3'])
})
it('returns [] for an unknown or empty site id', () => {
expect(zonesForSite(sites, 'nope')).toEqual([])
expect(zonesForSite(sites, '')).toEqual([])
})
})
describe('resolveZoneToken', () => {
const sites = groupSites(rows)
it('prefers the QR token', () => {
expect(resolveZoneToken({ zoneToken: 'qr-1', sites, zoneId: 'z1' })).toBe('qr-1')
})
it('falls back to the selected zone token', () => {
expect(resolveZoneToken({ zoneToken: null, sites, zoneId: 'z2' })).toBe('tok-b')
})
it('returns null when nothing is chosen or the zone is unknown', () => {
expect(resolveZoneToken({ zoneToken: null, sites, zoneId: '' })).toBeNull()
expect(resolveZoneToken({ zoneToken: null, sites, zoneId: 'zz' })).toBeNull()
})
})
describe('siteIdForToken', () => {
const sites = [
{ id: 'A', name: 'Site A', zones: [{ id: 'z1', name: 'Dock', qr_code_token: 'tok-1' }] },
{ id: 'B', name: 'Site B', zones: [{ id: 'z2', name: 'Yard', qr_code_token: 'tok-2' }] },
]
it('finds the site that owns the token', () => {
expect(siteIdForToken(sites, 'tok-2')).toBe('B')
})
it('returns empty string for null or unknown token', () => {
expect(siteIdForToken(sites, null)).toBe('')
expect(siteIdForToken(sites, 'nope')).toBe('')
})
})