Author SHA1 Message Date
admin e130b039d4 Merge pull request 'Chore/remove supabase legacy' (#2) from chore/remove-supabase-legacy into main
Reviewed-on: #2
2026-11-06 22:08:46 +08:00
adminandClaude Sonnet 5.5 1a2f9fbd47 docs(claude): drop removed Supabase leftovers, note ssa role
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 22:08:21 +08:00
adminandClaude Sonnet 5.5 2bda9d06a7 chore: remove legacy Supabase code and dependencies
The app no longer imports Supabase (migrated to local PostgreSQL 2026-09-30).
Remove lib/supabase/*, the supabase/ migrations folder, the @supabase/ssr and
@supabase/supabase-js dependencies, and the storage test for the removed client.
db/schema.sql and db/rls.sql remain the schema source of truth.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 22:07:21 +08:00
admin f32c6e8c60 Merge pull request 'Feat/ssa role' (#1) from feat/ssa-role into main
Reviewed-on: #1
2026-11-06 21:58:37 +08:00
adminandClaude Sonnet 5.5 4ec37bd078 test(layout): update app-shell search test for ssa role
ssa now has a site incident list, so its header search targets /ssa/incidents.
Use management for the no-search case.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 21:50:59 +08:00
Weei HanandClaude Sonnet 5.5 f52e63ad09 fix(db): make ssa role migration a single self-contained transaction
Drop and recreate auth_user_role() for the new user_role enum and re-apply all RLS policies inside the migration, so no separate db/rls.sql step is needed and there is no access gap.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 21:41:08 +08:00
Weei HanandClaude Sonnet 5.5 813395700f feat(auth): merge reporter, supervisor, capa_owner into ssa role
Add Site Safety Assistant (ssa) role replacing reporter, supervisor and
capa_owner. Portals move under /ssa (overview, my-reports, incidents,
capas). Update RLS, schema, API role checks, notification recipients,
nav and tests. Add db/ops/2026-11-06-merge-roles-into-ssa.sql (not yet
applied; needs owner go-ahead and a pg_dump first).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 21:34:10 +08:00
adminandClaude Sonnet 5.5 701fefd286 feat(report): show all trucks regardless of site
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 13:52:46 +08:00
adminandClaude Sonnet 5.5 f3c62d9225 Merge feat/truck-site: link trucks to a site, filter report truck list
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 12:01:16 +08:00
adminandClaude Sonnet 5.5 17c32ecd04 fix(trucks): skip active-site check when PATCH leaves site unchanged
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 11:53:32 +08:00
adminandClaude Sonnet 5.5 5f1d7a6ed4 feat(report): filter truck list by selected site
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 11:50:00 +08:00
adminandClaude Sonnet 5.5 149704898d feat(trucks): site select, site label and edit modal in admin
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 11:48:15 +08:00
adminandClaude Sonnet 5.5 f3f3aec59f feat(trucks): admin API accepts site_id and partial edits
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 11:46:31 +08:00
adminandClaude Sonnet 5.5 867b725262 feat(trucks): site_id column and site/truck helpers
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 11:44:37 +08:00
adminandClaude Sonnet 5.5 fd7a55337f docs: implementation plan for truck-to-site link
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 11:25:16 +08:00
adminandClaude Sonnet 5.5 2a9d32d1d0 docs: spec for linking trucks to a site
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 11:17:15 +08:00
adminandClaude Sonnet 5.5 c4377fb705 Merge feat/zone-capa-proof: zone picker, CAPA completion proof, test-data cleanup
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-15 11:07:32 +08:00
adminandClaude Sonnet 5.5 275a1ef3e9 docs(ops): cleanup must run as RLS-bypassing role, stop on error
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 11:18:20 +08:00
adminandClaude Sonnet 5.5 10f22b5cd5 chore(ops): test-data cleanup script and runbook
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 11:14:57 +08:00
adminandClaude Sonnet 5.5 1b84ed8625 fix(capa): handle network errors, keep form locked after submit, extend tests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 11:13:53 +08:00
adminandClaude Sonnet 5.5 550a61cedc feat(capa): proof form for owners and photo gallery for HSE
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 11:12:22 +08:00
adminandClaude Sonnet 5.5 de7fb298f7 fix(capa): atomic in_progress guard on submit, add behavioural tests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 11:11:10 +08:00
adminandClaude Sonnet 5.5 51986b7ae5 feat(capa): require note and photos via /submit, block PATCH bypass
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 11:10:03 +08:00
adminandClaude Sonnet 5.5 cf5719883c feat(report): site and zone picker when no QR zone is detected
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 11:08:18 +08:00
adminandClaude Sonnet 5.5 98cc7c4ac9 docs: implementation plan for zone picker, CAPA proof, cleanup
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 11:05:57 +08:00
adminandClaude Sonnet 5.5 29bdb39506 docs: spec for zone picker, CAPA completion proof, test-data cleanup
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 11:02:12 +08:00
adminandClaude Haiku 4.5 99eca7d242 fix(ai): use correct llama.cpp model name
- Update model to qwen2.5-coder-32b-instruct-Q4_K_M
- Match actual model available in llama.cpp on port 8081

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 21:59:01 +08:00
adminandClaude Haiku 4.5 e89ecdd5c4 fix(ai): update endpoint to llama.cpp on port 8081
- Switch from Ollama (11434) to llama.cpp (8081)
- Point to OpenAI-compatible API at localhost:8081/v1

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 21:56:48 +08:00
adminandClaude Haiku 4.5 7424fe4f9b feat(ai): switch to qwen2.5-coder-8k model
- Use larger coder model (32.8B params) for better reasoning
- Update client default model
- Update all AI routes to use qwen2.5-coder-8k:latest
- Already installed and available on server Ollama

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 13:19:41 +08:00
adminandClaude Haiku 4.5 0ca92182ff feat(branding): add Setia logo favicon
- Crop Setia logo icon to 256x256 favicon
- Reference favicon in app metadata
- Displays in browser tabs and bookmarks

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 12:59:23 +08:00
adminandClaude Haiku 4.5 aac988010a fix: disable embeddings gracefully when GOOGLE_AI_API_KEY missing
- Catch and log GOOGLE_AI_API_KEY errors instead of failing
- Allows endpoints to work without embeddings configured

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 12:03:07 +08:00
adminandClaude Haiku 4.5 4f9ca6e37f docs(design): record slice 2 (CAPA) and the mockup features that need a backend
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 11:37:41 +08:00
adminandClaude Haiku 4.5 48b77458dd test(capa): fix the fetch mock typing in the create form test
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 11:37:11 +08:00
adminandClaude Haiku 4.5 7e129b2781 feat(capa): restyle the create CAPA form and page with the shared field primitives
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 11:35:46 +08:00
adminandClaude Haiku 4.5 4f75dd5887 feat(ai): switch from DeepSeek to local Ollama (qwen3:14b)
- Point AI client to localhost:11434/v1 (Ollama)
- Remove DeepSeek API key dependency
- Update model name to qwen3:14b across all routes
- Update test mocks to use createLocalLLMClient
- Removes need for DEEPSEEK_API_KEY setting

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 11:34:05 +08:00
adminandClaude Haiku 4.5 69e510af74 feat(capa): restyle the CAPA detail page, verification form, close card, owner actions and notes
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 11:20:57 +08:00
adminandClaude Haiku 4.5 04437926c2 feat(capa): replace the CAPA board with a workspace (TableCard list and status board) with search, filters and saved views
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 10:47:04 +08:00
adminandClaude Haiku 4.5 9dca2a51d2 feat(capa): add pure list helpers for filtering, saved views, sorting and paging
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 10:26:34 +08:00
adminandClaude Haiku 4.5 9f0331d190 docs: add IMS Admin refresh slice 2 (CAPA) implementation plan
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 10:20:01 +08:00
129 changed files with 6558 additions and 2149 deletions
+4 -5
View File
@@ -19,7 +19,8 @@ Replaces WhatsApp/Excel safety reporting. Client: Ms. Agnes, Mr. Terence, Mr. Ya
## Current Phase
**All phases (0–6) complete as of 2026-07-12.** Supabase to local PostgreSQL migration completed and live 2026-09-30.
**UI refresh in progress:** follow `design-system/design.md` §8 build order (tokens → ui primitives → TableCard → shells → migrate Incidents list → remaining screens).
Legacy leftovers to remove when convenient: `lib/supabase/*`, the `@supabase/*` dependencies and the `supabase/` folder (the app no longer imports them; `db/schema.sql` + `db/rls.sql` are the schema source of truth).
Legacy Supabase code (`lib/supabase/*`, `@supabase/*` deps, `supabase/` folder) was removed 2026-11-06; `db/schema.sql` + `db/rls.sql` are the schema source of truth.
**Roles (since 2026-11-06):** `ssa` (Site Safety Assistant, replaces reporter + supervisor + capa_owner), `hse`, `management`, `admin`. SSA pages live under `app/(protected)/ssa/`.
See `[[phases]]` memory for full phase breakdown and deliverables.
## Deployment (Production)
@@ -62,10 +63,8 @@ IMS/
│ ├── auth/ # bcryptjs passwords, jose sessions, roles
│ ├── storage/ # evidence files on disk + signed URLs
│ ├── claude/ # AI client (DeepSeek) + Google embeddings
│ ├── notifications/ # Brevo email + WhatsApp senders, in-app
│ └── supabase/ # LEGACY, unused, to be removed
│ └── notifications/ # Brevo email + WhatsApp senders, in-app
├── db/ # schema.sql, rls.sql, migration/ops scripts
├── supabase/ # LEGACY migrations, to be removed
└── public/
```
@@ -85,7 +84,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.
- 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.
- 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).
- 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).
- 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.
- Incident evidence photos stay full colour.
+6 -14
View File
@@ -3,22 +3,14 @@ import { describe, it, expect } from 'vitest'
import { getRoleHome, ROLE_HOME, ALL_ROLES } from '@/lib/auth/roles'
describe('getRoleHome', () => {
it('returns /reporter for reporter role', () => {
expect(getRoleHome('reporter')).toBe('/reporter')
})
it('returns /supervisor for supervisor role', () => {
expect(getRoleHome('supervisor')).toBe('/supervisor')
it('returns /ssa for ssa role', () => {
expect(getRoleHome('ssa')).toBe('/ssa')
})
it('returns /hse for hse role', () => {
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', () => {
expect(getRoleHome('management')).toBe('/management')
})
@@ -27,11 +19,11 @@ describe('getRoleHome', () => {
expect(getRoleHome('admin')).toBe('/admin')
})
it('ROLE_HOME covers exactly 6 roles', () => {
expect(Object.keys(ROLE_HOME)).toHaveLength(6)
it('ROLE_HOME covers exactly 4 roles', () => {
expect(Object.keys(ROLE_HOME)).toHaveLength(4)
})
it('ALL_ROLES lists exactly 6 roles', () => {
expect(ALL_ROLES).toHaveLength(6)
it('ALL_ROLES lists exactly 4 roles', () => {
expect(ALL_ROLES).toHaveLength(4)
})
})
+5 -2
View File
@@ -29,7 +29,7 @@ export default async function AdminHome() {
qrCodeToken: zones.qrCodeToken, active: zones.active,
}).from(zones)),
asAdmin(db => db.select({
id: trucks.id, truckNo: trucks.truckNo, carrier: trucks.carrier, active: trucks.active,
id: trucks.id, truckNo: trucks.truckNo, carrier: trucks.carrier, siteId: trucks.siteId, active: trucks.active,
}).from(trucks).orderBy(asc(trucks.truckNo))),
])
@@ -46,8 +46,10 @@ export default async function AdminHome() {
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 => ({
id: t.id, truck_no: t.truckNo, carrier: t.carrier ?? null, active: t.active,
id: t.id, truck_no: t.truckNo, carrier: t.carrier ?? null, site_id: t.siteId ?? null, active: t.active,
}))
return (
@@ -66,6 +68,7 @@ export default async function AdminHome() {
sites={sitesWithZones}
siteOptions={siteOptions}
trucks={truckList}
truckSites={truckSites}
/>
</main>
)
+101 -55
View File
@@ -2,20 +2,32 @@ export const dynamic = 'force-dynamic'
import { notFound, redirect } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { capaActions, incidents, users } from '@/lib/db/schema'
import { eq } from 'drizzle-orm'
import { capaActions, evidenceFiles, incidents, users } from '@/lib/db/schema'
import { eq, and, asc } from 'drizzle-orm'
import { aliasedTable } from 'drizzle-orm'
import { VerifyForm } from '@/components/capa/verify-form'
import { CloseCapaButton } from '@/components/capa/close-capa-button'
import { CapaOwnerActions } from '@/components/capa/capa-owner-actions'
import { PriorityTag } from '@/components/ui/status-tag'
import { Avatar } from '@/components/ui/avatar'
import { PriorityTag, StatusTag } from '@/components/ui/status-tag'
import { daysLate } from '@/lib/capa/list'
interface Props {
params: Promise<{ id: string }>
}
function Row({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="flex items-center justify-between gap-3 border-b border-rule py-2.5 last:border-0">
<dt className="text-xs text-muted">{label}</dt>
<dd className="text-right text-[13px]">{children}</dd>
</div>
)
}
export default async function CapaDetailPage({ params }: Props) {
const { id } = await params
const session = await getSession()
@@ -48,77 +60,111 @@ export default async function CapaDetailPage({ params }: Props) {
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 status = capa.status
const today = new Date().toISOString().slice(0, 10)
const pastDue = (status === 'open' || status === 'in_progress') && Boolean(capa.dueDate) && capa.dueDate < today
const shownStatus = pastDue ? 'overdue' : status
const late = shownStatus === 'overdue' ? daysLate(capa.dueDate, today) : 0
const canAct = ['open', 'in_progress', 'overdue', 'reopened'].includes(status) &&
(isHse || session?.sub === capa.ownerUserId)
return (
<main className="max-w-2xl mx-auto px-4 py-6">
<Link href="/hse/capa" className="text-sm text-accent-700 hover:underline mb-4 inline-block">
← CAPA Board
<div className="space-y-4 px-4 py-5 md:px-8 md:py-6">
<Link href="/hse/capa" className="inline-flex items-center gap-1 text-[13px] text-accent hover:underline">
<ArrowLeft size={14} strokeWidth={2} aria-hidden />
CAPA
</Link>
<div className="bg-surface shadow-sm p-5 mb-4 space-y-4">
<div className="flex items-start justify-between">
<div>
<p className="text-xs text-gray-500 mb-1">
Incident: {capa.incidentRefNo ?? '—'}
</p>
<p className="text-gray-900 font-medium">{capa.description}</p>
</div>
<div className="space-y-2">
<h1 className="text-xl font-[650]">{capa.description}</h1>
<div className="flex flex-wrap items-center gap-2">
<StatusTag status={shownStatus} />
<PriorityTag priority={capa.priority} />
<span className="text-[13px] text-muted">
From{' '}
<Link href={`/hse/incidents/${capa.incidentId}`} className="font-mono text-[12.5px] text-accent hover:underline">
{capa.incidentRefNo ?? '—'}
</Link>
</span>
</div>
{capa.rootCauseRef && <p className="text-[13px] text-muted">Root cause: {capa.rootCauseRef}</p>}
</div>
<div className="grid grid-cols-2 gap-3 text-sm">
<div className="grid gap-4 lg:grid-cols-[1fr_320px]">
<div className="space-y-4">
{canAct && (
<div>
<p className="text-xs text-gray-500">Owner</p>
<p className="text-gray-800">{capa.ownerName ?? '—'}</p>
</div>
<div>
<p className="text-xs text-gray-500">Department</p>
<p className="text-gray-800">{capa.department}</p>
</div>
<div>
<p className="text-xs text-gray-500">Due Date</p>
<p className="text-gray-800">{capa.dueDate}</p>
</div>
<div>
<p className="text-xs text-gray-500">Status</p>
<p className="text-gray-800 capitalize">{status.replace(/_/g, ' ')}</p>
</div>
{capa.ownerNotes && (
<div className="col-span-2">
<p className="text-xs text-gray-500">Owner Notes</p>
<p className="text-sm text-gray-800 whitespace-pre-wrap">{capa.ownerNotes}</p>
</div>
)}
</div>
{capa.rootCauseRef && (
<div>
<p className="text-xs text-gray-500">Root Cause Reference</p>
<p className="text-sm text-gray-800">{capa.rootCauseRef}</p>
<CapaOwnerActions capaId={id} currentStatus={status} />
</div>
)}
{isHse && status === 'pending_verification' && <VerifyForm capaId={id} />}
{isHse && status === 'verified' && <CloseCapaButton capaId={id} />}
{(capa.ownerNotes || capa.completedAt || photos.length > 0) && (
<section className="space-y-2 rounded-xl bg-surface p-5 shadow-card">
<h2 className="text-sm font-semibold">Completion report</h2>
{capa.completedAt && (
<p className="text-xs text-gray-500">
Completed: {new Date(capa.completedAt).toLocaleString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })}
<p className="text-xs text-muted">
Completed {new Date(capa.completedAt).toLocaleString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })}
</p>
)}
{capa.ownerNotes && (
<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>
)}
</div>
{['open', 'in_progress', 'overdue', 'reopened'].includes(status) &&
(isHse || session?.sub === capa.ownerUserId) && (
<CapaOwnerActions capaId={id} currentStatus={status} />
<aside>
<section className="rounded-xl bg-surface p-5 shadow-card">
<h2 className="mb-1 text-sm font-semibold">Details</h2>
<dl>
<Row label="Owner">
{capa.ownerName ? (
<span className="inline-flex items-center gap-2">
<Avatar name={capa.ownerName} />
{capa.ownerName}
</span>
) : (
'—'
)}
{isHse && status === 'pending_verification' && (
<VerifyForm capaId={id} />
</Row>
<Row label="Department">{capa.department}</Row>
<Row label="Priority"><PriorityTag priority={capa.priority} /></Row>
<Row label="Due">
{capa.dueDate}
{late > 0 && <span className="ml-1.5 text-xs text-danger">{`${late} day${late === 1 ? '' : 's'} late`}</span>}
</Row>
{capa.completedAt && (
<Row label="Completed">
{new Date(capa.completedAt).toLocaleDateString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })}
</Row>
)}
{isHse && status === 'verified' && (
<CloseCapaButton capaId={id} />
)}
</main>
</dl>
</section>
</aside>
</div>
</div>
)
}
+10 -16
View File
@@ -1,13 +1,13 @@
export const dynamic = 'force-dynamic'
import { redirect } from 'next/navigation'
import Link from 'next/link'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { capaActions, incidents, users } from '@/lib/db/schema'
import { eq, asc } from 'drizzle-orm'
import { aliasedTable } from 'drizzle-orm'
import { CapaBoard } from '@/components/capa/capa-board'
import { CapaWorkspace } from '@/components/capa/capa-workspace'
import type { CapaRow, CapaStatus } from '@/lib/capa/list'
export default async function CapaListPage() {
const session = await getSession()
@@ -34,29 +34,23 @@ export default async function CapaListPage() {
)
const today = new Date().toISOString().slice(0, 10)
const capas = rows.map(r => ({
const capas: CapaRow[] = rows.map(r => ({
id: r.id,
incident_id: r.incidentId,
description: r.description,
department: r.department,
due_date: r.dueDate,
priority: r.priority,
status: (r.status === 'open' || r.status === 'in_progress') && r.dueDate && r.dueDate < today
? 'overdue' as const
: r.status,
incidents: { reference_no: r.incidentRefNo ?? null },
owner: r.ownerName ? { name: r.ownerName } : null,
status: ((r.status === 'open' || r.status === 'in_progress') && r.dueDate && r.dueDate < today
? 'overdue'
: r.status) as CapaStatus,
incident_ref: r.incidentRefNo ?? null,
owner_name: r.ownerName ?? null,
}))
return (
<main className="max-w-6xl mx-auto px-4 py-6">
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-bold text-gray-900">CAPA Board</h1>
<Link href="/hse/incidents" className="text-sm text-accent-700 hover:underline">
← Incidents
</Link>
<div className="px-4 py-5 md:px-8 md:py-6">
<CapaWorkspace capas={capas} today={today} />
</div>
<CapaBoard capas={capas} />
</main>
)
}
@@ -1,5 +1,6 @@
import { notFound, redirect } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { incidents } from '@/lib/db/schema'
@@ -30,15 +31,18 @@ export default async function NewCapaPage({ params }: Props) {
if (!incident) notFound()
return (
<main className="max-w-lg mx-auto px-4 py-6">
<Link href={`/hse/incidents/${id}`} className="text-sm text-accent-700 hover:underline mb-4 inline-block">
← Back to incident
<div className="max-w-xl space-y-4 px-4 py-5 md:px-8 md:py-6">
<Link href={`/hse/incidents/${id}`} className="inline-flex items-center gap-1 text-[13px] text-accent hover:underline">
<ArrowLeft size={14} strokeWidth={2} aria-hidden />
Back to incident
</Link>
<h1 className="text-xl font-bold text-gray-900 mb-1">Add CAPA Action</h1>
<p className="text-sm text-gray-500 mb-6">
{incident.referenceNo ?? id}
</p>
<div>
<h1 className="text-xl font-[650]">Add CAPA action</h1>
<p className="mt-0.5 font-mono text-[12.5px] text-muted">{incident.referenceNo ?? id}</p>
</div>
<div className="rounded-xl bg-surface p-5 shadow-card">
<CapaForm incidentId={id} />
</main>
</div>
</div>
)
}
@@ -21,10 +21,10 @@ const STATUS_LABELS: Record<string, string> = {
closed: 'Closed',
}
export default async function CapaOwnerPage() {
export default async function MyCapasPage() {
const session = await getSession()
if (!session) redirect('/login')
if (!['capa_owner', 'admin', 'hse', 'supervisor'].includes(session.role)) redirect('/')
if (!['ssa', 'admin', 'hse'].includes(session.role)) redirect('/')
const rows = await asAdmin(db =>
db.select({
@@ -14,7 +14,7 @@ interface Props {
params: Promise<{ id: string }>
}
export default async function SupervisorIncidentDetailPage({ params }: Props) {
export default async function SsaIncidentDetailPage({ params }: Props) {
const { id } = await params
const session = await getSession()
@@ -136,7 +136,7 @@ export default async function SupervisorIncidentDetailPage({ params }: Props) {
return (
<main className="max-w-3xl mx-auto px-4 py-6">
<Link href="/supervisor/incidents" className="text-sm text-accent-700 hover:underline mb-4 inline-block">
<Link href="/ssa/incidents" className="text-sm text-accent-700 hover:underline mb-4 inline-block">
← Back to inbox
</Link>
<IncidentDetail incident={incidentProp} />
@@ -8,7 +8,7 @@ import { IncidentTable } from '@/components/incidents/incident-table'
import { loadIncidentList } from '@/lib/incidents/list-query'
import { parseListParams } from '@/lib/incidents/list-params'
export default async function SupervisorInboxPage({
export default async function SsaInboxPage({
searchParams,
}: {
searchParams: Promise<Record<string, string | undefined>>
@@ -27,7 +27,7 @@ export default async function SupervisorInboxPage({
</div>
<IncidentTable
incidents={data.incidents}
basePath="/supervisor"
basePath="/ssa"
total={data.total}
counts={data.counts}
params={params}
@@ -12,7 +12,7 @@ const STATUS_LABELS: Record<string, string> = {
reported: 'Reported', triaged: 'Triaged', investigating: 'Investigating',
capa_pending: 'CAPA Pending', verification: 'Verification', closed: 'Closed',
}
export default async function ReporterIncidentDetail({
export default async function MyReportDetail({
params,
}: {
params: Promise<{ id: string }>
@@ -60,7 +60,7 @@ export default async function ReporterIncidentDetail({
return (
<main className="max-w-2xl mx-auto px-4 py-6 space-y-4">
<div className="flex items-center gap-2 mb-2">
<Link href="/reporter" className="text-sm text-accent-700 hover:underline">← My Reports</Link>
<Link href="/ssa/my-reports" className="text-sm text-accent-700 hover:underline">← My Reports</Link>
</div>
<div className="bg-surface shadow-sm p-5">
@@ -22,7 +22,7 @@ const TYPE_LABELS: Record<string, string> = {
asset_damage: 'Asset Damage', environmental: 'Environmental', security: 'Security', fire: 'Fire',
}
export default async function ReporterPage() {
export default async function MyReportsPage() {
const session = await getSession()
if (!session) redirect('/login')
@@ -83,7 +83,7 @@ export default async function ReporterPage() {
) : (
<div className="bg-surface shadow-sm divide-y divide-gray-50">
{rows.map(inc => (
<Link key={inc.id} href={`/reporter/incidents/${inc.id}`} className="block p-4 cursor-pointer hover:bg-gray-50 transition-colors">
<Link key={inc.id} href={`/ssa/my-reports/${inc.id}`} className="block p-4 cursor-pointer hover:bg-gray-50 transition-colors">
<div className="flex items-start justify-between gap-3">
<div className="flex-1 min-w-0">
<p className="text-sm font-semibold text-gray-900">
@@ -19,15 +19,15 @@ const STATUS_LABELS: Record<string, string> = {
closed: 'Closed',
}
export default async function SupervisorPage() {
export default async function SsaPage() {
const session = await getSession()
if (!session) redirect('/login')
if (!['supervisor', 'admin'].includes(session.role)) redirect('/')
if (!['ssa', 'admin'].includes(session.role)) redirect('/')
if (!session.siteId) {
return (
<main className="max-w-4xl mx-auto px-4 py-6">
<h1 className="text-2xl font-bold text-gray-900 mb-4">Supervisor Portal</h1>
<h1 className="text-2xl font-bold text-gray-900 mb-4">Site Safety Assistant Portal</h1>
<p className="text-sm text-gray-500">No site assigned — contact your administrator.</p>
</main>
)
@@ -108,10 +108,10 @@ export default async function SupervisorPage() {
<main className="max-w-4xl mx-auto px-4 py-6">
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-gray-900">Supervisor Portal</h1>
<h1 className="text-2xl font-bold text-gray-900">Site Safety Assistant Portal</h1>
<p className="text-sm text-gray-500 mt-1">{siteName}</p>
</div>
<Link href="/supervisor/incidents" className="text-sm text-accent-700 hover:underline">
<Link href="/ssa/incidents" className="text-sm text-accent-700 hover:underline">
All incidents →
</Link>
</div>
@@ -134,7 +134,7 @@ export default async function SupervisorPage() {
{openIncidents.map(inc => (
<Link
key={inc.id}
href={`/supervisor/incidents/${inc.id}`}
href={`/ssa/incidents/${inc.id}`}
className="flex items-center justify-between py-2 border-b border-gray-50 last:border-0 hover:bg-gray-50 -mx-2 px-2"
>
<div>
+50 -9
View File
@@ -3,27 +3,43 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { requireAdmin } from '@/lib/auth/require-admin'
import { asAdmin } from '@/lib/db/with-user'
import { trucks, incidents } from '@/lib/db/schema'
import { trucks, incidents, sites } from '@/lib/db/schema'
import { parseSiteId } from '@/lib/admin/truck-input'
import { writeAuditLog } from '@/lib/db/audit'
import { eq, sql } from 'drizzle-orm'
import { and, 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) {
const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const body: { truck_no?: string; carrier?: string } = await request.json().catch(() => ({}))
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: (body.carrier ?? '').trim() || null }).returning({ id: trucks.id })
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: (body.carrier ?? '').trim() || null })
await writeAuditLog(tx, 'trucks', truck.id, 'INSERT', { truck_no, carrier, site_id: siteId })
})
})
if (!truckId) return NextResponse.json({ error: 'Insert failed' }, { status: 400 })
@@ -41,21 +57,46 @@ 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 } = await request.json().catch(() => ({}))
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 && set.siteId !== before?.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({ active: body.active }).where(eq(trucks.id, body.id!))
await writeAuditLog(tx, 'trucks', body.id!, 'admin_update', { active: body.active }, before ?? null)
await tx.update(trucks).set(set).where(eq(trucks.id, body.id!))
await writeAuditLog(tx, 'trucks', body.id!, 'admin_update', set, before ?? null)
})
})
} catch {
} 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 })
+2 -2
View File
@@ -69,7 +69,7 @@ export async function POST(request: NextRequest) {
name: body.name ?? '',
email,
phone: (body.phone ?? '').trim() || null,
role: (body.role as typeof users.$inferInsert['role']) ?? 'reporter',
role: (body.role as typeof users.$inferInsert['role']) ?? 'ssa',
siteId: body.site_id ?? null,
department: body.department ?? null,
passwordHash,
@@ -78,7 +78,7 @@ export async function POST(request: NextRequest) {
if (!created) throw new Error('User creation failed')
createdId = created.id
await writeAuditLog(tx, 'users', created.id, 'created', {
email, role: body.role ?? 'reporter', site_id: body.site_id ?? null,
email, role: body.role ?? 'ssa', site_id: body.site_id ?? null,
})
})
})
+8 -3
View File
@@ -50,7 +50,7 @@ export async function GET(
const role = session.role
const isOwner = row.ownerUserId === session.sub
const canRead = ['hse', 'admin', 'supervisor'].includes(role) || isOwner
const canRead = ['hse', 'admin', 'ssa'].includes(role) || isOwner
if (!canRead) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const ownerField = ['hse', 'admin'].includes(role)
@@ -105,6 +105,13 @@ export async function PATCH(
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']
if (body.status && privilegedStatuses.includes(body.status) && !['hse', 'admin'].includes(role)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
@@ -122,14 +129,12 @@ export async function PATCH(
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 ('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
const auditNew: Record<string, unknown> = {}
for (const key of allowed) {
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 => {
let oldNotes: string | null = null
+98
View File
@@ -0,0 +1,98 @@
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))
.orderBy(asc(capaActions.dueDate))
if (session.role === 'supervisor' || session.role === 'worker') {
if (session.role === 'ssa') {
q = q.where(eq(capaActions.ownerUserId, session.sub)) as typeof q
}
+4 -6
View File
@@ -6,8 +6,7 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit'
import { incidents, sites, zones, auditLog } from '@/lib/db/schema'
import { eq, and, gte, desc } from 'drizzle-orm'
import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
import { createLocalLLMClient } from '@/lib/claude/client'
type ZoneAggregate = {
zone: string
@@ -103,13 +102,12 @@ export async function POST() {
return NextResponse.json({ error: 'Rate limit: wait 60 seconds between AI requests' }, { status: 429 })
}
const deepseekKey = await getApiKey('DEEPSEEK_API_KEY')
const client = createDeepSeekClient(deepseekKey)
const client = createLocalLLMClient()
let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try {
res = await client.chat.completions.create({
model: 'deepseek-v4-pro',
model: 'qwen2.5-coder-32b-instruct-Q4_K_M',
max_tokens: 2048,
messages: [
{
@@ -168,7 +166,7 @@ Flag only zones with rising or elevated risk (at most 5 flags; do not flag healt
await withUser(session.sub, async tx =>
writeAuditLog(tx, 'incidents', session.sub, 'ai_risk_flags',
{ flags, summary: input.summary, model: 'deepseek-v4-pro' })
{ flags, summary: input.summary, model: 'qwen2.5-coder-32b-instruct-Q4_K_M' })
)
return NextResponse.json({ flags, summary: input.summary })
+2 -2
View File
@@ -15,7 +15,7 @@ export async function GET(
const { id } = await params
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin', 'supervisor'].includes(session.role))
if (!['hse', 'admin', 'ssa'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const authorAlias = aliasedTable(users, 'author_user')
@@ -45,7 +45,7 @@ export async function POST(
const { id } = await params
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin', 'supervisor'].includes(session.role))
if (!['hse', 'admin', 'ssa'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const body: { body?: string } = await request.json().catch(() => ({}))
+4 -6
View File
@@ -6,8 +6,7 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit'
import { incidents, auditLog, sites, zones } from '@/lib/db/schema'
import { eq, and, gte, sql } from 'drizzle-orm'
import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
import { createLocalLLMClient } from '@/lib/claude/client'
export async function POST(
_request: NextRequest,
@@ -32,8 +31,7 @@ export async function POST(
if (Number(rateRow?.cnt ?? 0) > 0)
return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 })
const deepseekKey = await getApiKey('DEEPSEEK_API_KEY')
const client = createDeepSeekClient(deepseekKey)
const client = createLocalLLMClient()
const [incident] = await withUser(session.sub, async tx =>
tx.select({
@@ -59,7 +57,7 @@ export async function POST(
let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try {
res = await client.chat.completions.create({
model: 'deepseek-v4-pro',
model: 'qwen2.5-coder-32b-instruct-Q4_K_M',
max_tokens: 2048,
messages: [
{
@@ -107,7 +105,7 @@ Provide 3–5 Why steps drilling from immediate cause to root cause. Frame CAPA
await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'incidents', id, 'ai_rca_draft', {
root_cause_summary: draft.root_cause_summary as string,
model: 'deepseek-v4-pro',
model: 'qwen2.5-coder-32b-instruct-Q4_K_M',
})
})
@@ -6,8 +6,7 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit'
import { incidents, auditLog } from '@/lib/db/schema'
import { eq, and, gte, sql } from 'drizzle-orm'
import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
import { createLocalLLMClient } from '@/lib/claude/client'
export async function POST(
_request: NextRequest,
@@ -32,8 +31,7 @@ export async function POST(
if (Number(rateRow?.cnt ?? 0) > 0)
return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 })
const deepseekKey = await getApiKey('DEEPSEEK_API_KEY')
const client = createDeepSeekClient(deepseekKey)
const client = createLocalLLMClient()
const [incident] = await withUser(session.sub, async tx =>
tx.select({
@@ -50,7 +48,7 @@ export async function POST(
let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try {
res = await client.chat.completions.create({
model: 'deepseek-v4-pro',
model: 'qwen2.5-coder-32b-instruct-Q4_K_M',
max_tokens: 1024,
messages: [
{
@@ -105,7 +103,7 @@ Output exactly this JSON structure:
}
await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'incidents', id, 'ai_triage_suggest', { suggestion: input, model: 'deepseek-v4-pro' })
await writeAuditLog(tx, 'incidents', id, 'ai_triage_suggest', { suggestion: input, model: 'qwen2.5-coder-32b-instruct-Q4_K_M' })
})
return NextResponse.json(input)
+1 -1
View File
@@ -51,7 +51,7 @@ export async function POST(
await createInAppNotifications([{
userId: incident.reportedBy,
title: `Your incident report ${incident.referenceNo ?? ''} has been closed`,
link: '/reporter',
link: '/ssa/my-reports',
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 })
const isOwner = incident.reporterId === session.sub
const isSiteStaff = ['hse', 'supervisor', 'admin'].includes(session.role)
const isSiteStaff = ['hse', 'ssa', 'admin'].includes(session.role)
if (!isOwner && !isSiteStaff) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const evidenceFileRows = await withUser(session.sub, async tx =>
+4 -6
View File
@@ -6,8 +6,7 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit'
import { auditLog } from '@/lib/db/schema'
import { eq, and, gte, sql } from 'drizzle-orm'
import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
import { createLocalLLMClient } from '@/lib/claude/client'
export async function POST(request: NextRequest) {
const session = await getSession()
@@ -26,8 +25,7 @@ export async function POST(request: NextRequest) {
if (Number(rateRow?.cnt ?? 0) > 0)
return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 })
const deepseekKey = await getApiKey('DEEPSEEK_API_KEY')
const client = createDeepSeekClient(deepseekKey)
const client = createLocalLLMClient()
let body: { description?: string; incident_type?: string }
try {
@@ -42,7 +40,7 @@ export async function POST(request: NextRequest) {
let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try {
res = await client.chat.completions.create({
model: 'deepseek-v4-pro',
model: 'qwen2.5-coder-32b-instruct-Q4_K_M',
max_tokens: 1024,
messages: [
{
@@ -89,7 +87,7 @@ Scoring criteria: specificity (location, time, persons involved), completeness (
await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'incidents', session.sub, 'ai_quality_check', {
score: input.score, passes: input.passes, model: 'deepseek-v4-pro',
score: input.score, passes: input.passes, model: 'qwen2.5-coder-32b-instruct-Q4_K_M',
})
})
+12 -4
View File
@@ -188,7 +188,7 @@ async function handlePost(request: Request) {
db.select({ id: users.id, phone: users.phone })
.from(users)
.where(and(
inArray(users.role, ['supervisor', 'hse']),
inArray(users.role, ['ssa', 'hse']),
eq(users.siteId, zone.siteId),
))
)
@@ -212,8 +212,9 @@ async function handlePost(request: Request) {
}
})()
// Embed description asynchronously
getApiKey('GOOGLE_AI_API_KEY').then(googleAiKey =>
// Embed description asynchronously (disabled if no GOOGLE_AI_API_KEY)
getApiKey('GOOGLE_AI_API_KEY')
.then(googleAiKey =>
import('@/lib/claude/embed').then(({ embedText }) =>
embedText(input.description.trim(), googleAiKey).then(embeddingVec => {
const embStr = `[${(embeddingVec as number[]).join(',')}]`
@@ -222,7 +223,14 @@ 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 })
}
+3
View File
@@ -17,6 +17,9 @@ const geistMono = Geist_Mono({
export const metadata: Metadata = {
title: 'IMS — HSE Incident Management',
description: 'Setia Corporation HSE Incident Management System',
icons: {
icon: '/favicon.ico',
},
}
export default async function RootLayout({
+29 -6
View File
@@ -3,8 +3,9 @@ export const dynamic = 'force-dynamic'
import { redirect } from 'next/navigation'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { zones, sites, trucks } from '@/lib/db/schema'
import { eq, asc } from 'drizzle-orm'
import { zones, sites, trucks, users } from '@/lib/db/schema'
import { eq, asc, and } from 'drizzle-orm'
import { groupSites } from '@/lib/report/zones'
import { ReportForm } from '@/components/incidents/report-form'
import { LanguageSwitcher } from '@/components/language-switcher'
import { OfflineSync } from '@/components/incidents/offline-sync'
@@ -43,6 +44,7 @@ export default async function ReportPage({ searchParams }: Props) {
id: trucks.id,
truckNo: trucks.truckNo,
carrier: trucks.carrier,
siteId: trucks.siteId,
})
.from(trucks)
.where(eq(trucks.active, true))
@@ -53,8 +55,29 @@ export default async function ReportPage({ searchParams }: Props) {
id: t.id,
truck_no: t.truckNo,
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 (
<main className="min-h-screen bg-gray-50 py-6 px-4 max-w-lg mx-auto">
<div className="mb-6">
@@ -62,18 +85,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>
<LanguageSwitcher />
</div>
{zoneName ? (
{zoneName && (
<p className="text-sm text-gray-600 mt-1">
{siteName ?? 'Unknown Site'} — {zoneName}
</p>
) : (
<p className="text-sm text-accent-700 mt-1">No zone detected — zone will not be recorded</p>
)}
</div>
<ReportForm
zoneToken={zone ?? null}
zoneToken={zoneName ? (zone ?? null) : null}
zoneName={zoneName}
siteName={siteName}
sites={siteOptions}
defaultSiteId={defaultSiteId}
trucks={truckList}
initialTruckId={truck_id ?? null}
/>
+1 -1
View File
@@ -19,7 +19,7 @@ export default async function ReportSuccessPage({ searchParams }: Props) {
</p>
)}
<p className="text-sm text-gray-500 mb-6">
The supervisor and HSE officer have been notified.
The Site Safety Assistants and HSE officer have been notified.
</p>
<Link href="/report" className="text-sm text-accent-700 hover:underline">
Submit another report
+4 -3
View File
@@ -3,7 +3,7 @@
import { useState } from 'react'
import { UserManager, type AdminUser, type SiteOption } from './user-manager'
import { SiteZoneManager, type SiteWithZones } from './site-zone-manager'
import { TruckManager, type Truck } from './truck-manager'
import { TruckManager, type Truck, type TruckSite } from './truck-manager'
type Tab = 'users' | 'sites' | 'trucks'
@@ -12,9 +12,10 @@ interface Props {
sites: SiteWithZones[]
siteOptions: SiteOption[]
trucks: Truck[]
truckSites: TruckSite[]
}
export function AdminPanel({ users, sites, siteOptions, trucks }: Props) {
export function AdminPanel({ users, sites, siteOptions, trucks, truckSites }: Props) {
const [tab, setTab] = useState<Tab>('users')
const tabs: { id: Tab; label: string; count: number }[] = [
@@ -45,7 +46,7 @@ export function AdminPanel({ users, sites, siteOptions, trucks }: Props) {
</div>
{tab === 'users' && <UserManager users={users} sites={siteOptions} />}
{tab === 'sites' && <SiteZoneManager sites={sites} />}
{tab === 'trucks' && <TruckManager trucks={trucks} />}
{tab === 'trucks' && <TruckManager trucks={trucks} sites={truckSites} />}
</div>
)
}
+88 -4
View File
@@ -9,16 +9,20 @@ 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[]
}
const lbl = 'block text-xs font-medium text-gray-600 mb-1'
export function TruckManager({ trucks }: Props) {
export function TruckManager({ trucks, sites }: Props) {
const router = useRouter()
const [truckNo, setTruckNo] = useState('')
const [carrier, setCarrier] = useState('')
@@ -27,6 +31,22 @@ export function TruckManager({ trucks }: Props) {
const [error, setError] = useState<string | null>(null)
const [showAdd, setShowAdd] = useState(false)
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 no = truckNo.trim()
@@ -37,12 +57,13 @@ export function TruckManager({ trucks }: Props) {
const res = await fetch('/api/admin/trucks', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ truck_no: no, carrier: carrier.trim() || null }),
body: JSON.stringify({ truck_no: no, carrier: carrier.trim() || null, site_id: siteId || null }),
})
const data = await res.json()
if (!res.ok) { setError(data.error ?? 'Failed to add truck'); return }
setTruckNo('')
setCarrier('')
setSiteId('')
setShowAdd(false)
router.refresh()
} catch {
@@ -82,6 +103,19 @@ export function TruckManager({ trucks }: Props) {
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 (
<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">
@@ -106,8 +140,15 @@ export function TruckManager({ trucks }: Props) {
<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>
<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"
className="text-xs text-accent-700 hover:underline cursor-pointer">
Report link
@@ -134,11 +175,11 @@ export function TruckManager({ trucks }: Props) {
</div>
{/* Add Truck Modal */}
<Modal open={showAdd} onClose={() => { setShowAdd(false); setTruckNo(''); setCarrier(''); setError(null) }}
<Modal open={showAdd} onClose={() => { setShowAdd(false); setTruckNo(''); setCarrier(''); setSiteId(''); setError(null) }}
title="Add Truck" width="sm"
footer={
<>
<button onClick={() => { setShowAdd(false); setTruckNo(''); setCarrier(''); setError(null) }}
<button onClick={() => { setShowAdd(false); setTruckNo(''); setCarrier(''); setSiteId(''); 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>
@@ -165,6 +206,49 @@ export function TruckManager({ trucks }: Props) {
onKeyDown={e => e.key === 'Enter' && handleAdd()}
className={inp} />
</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>
</Modal>
+4 -4
View File
@@ -2,7 +2,7 @@
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { ALL_ROLES, type UserRole } from '@/lib/auth/roles'
import { ALL_ROLES, ROLE_LABELS, type UserRole } from '@/lib/auth/roles'
import { Modal } from '@/components/ui/modal'
import { INPUT_CLASS as inp } from '@/components/ui/field'
@@ -23,7 +23,7 @@ interface Props {
sites: SiteOption[]
}
const EMPTY = { email: '', name: '', phone: '', role: 'reporter' as UserRole, site_id: '', password: '' }
const EMPTY = { email: '', name: '', phone: '', role: 'ssa' as UserRole, site_id: '', password: '' }
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}
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">
{ALL_ROLES.map(r => <option key={r} value={r}>{r.replace(/_/g, ' ')}</option>)}
{ALL_ROLES.map(r => <option key={r} value={r}>{ROLE_LABELS[r]}</option>)}
</select>
</td>
<td className="px-5 py-3">
@@ -224,7 +224,7 @@ export function UserManager({ users, sites }: Props) {
<select id="au-role" value={form.role}
onChange={e => setForm(v => ({ ...v, role: e.target.value as UserRole }))}
className={inp}>
{ALL_ROLES.map(r => <option key={r} value={r}>{r.replace(/_/g, ' ')}</option>)}
{ALL_ROLES.map(r => <option key={r} value={r}>{ROLE_LABELS[r]}</option>)}
</select>
</div>
<div>
+47
View File
@@ -0,0 +1,47 @@
import Link from 'next/link'
import { Avatar } from '@/components/ui/avatar'
import { PriorityTag, StatusTag } from '@/components/ui/status-tag'
import { STATUS_ORDER, type CapaRow } from '@/lib/capa/list'
export function CapaBoardView({ capas }: { capas: CapaRow[] }) {
return (
<div className="flex gap-3 overflow-x-auto pb-2">
{STATUS_ORDER.map(status => {
const items = capas.filter(c => c.status === status)
return (
<section
key={status}
aria-label={`${status.replace(/_/g, ' ')} column`}
className="w-72 shrink-0 rounded-xl bg-surface-2 p-2"
>
<header className="flex items-center gap-2 px-1.5 pb-2">
<StatusTag status={status} />
<span className="text-xs text-faint">{items.length}</span>
</header>
<div className="space-y-2 max-h-[70vh] overflow-y-auto">
{items.map(c => (
<Link
key={c.id}
href={`/hse/capa/${c.id}`}
className="block rounded-md bg-surface p-3 shadow-card transition-shadow hover:shadow-float"
>
<p className="text-[13px] font-medium line-clamp-2">{c.description}</p>
<p className="mt-1 font-mono text-[12px] text-accent">{c.incident_ref ?? '—'}</p>
<div className="mt-2 flex items-center justify-between gap-2">
<span className="flex min-w-0 items-center gap-1.5 text-xs text-muted">
{c.owner_name && <Avatar name={c.owner_name} />}
<span className="truncate">{c.owner_name ?? '—'}</span>
</span>
<PriorityTag priority={c.priority} />
</div>
<p className="mt-1.5 text-xs text-faint">Due {c.due_date}</p>
</Link>
))}
{items.length === 0 && <p className="px-1.5 py-3 text-xs text-faint">Empty</p>}
</div>
</section>
)
})}
</div>
)
}
-129
View File
@@ -1,129 +0,0 @@
'use client'
import { useState } from 'react'
import Link from 'next/link'
import { PriorityTag } from '@/components/ui/status-tag'
type CapaStatus = 'open' | 'in_progress' | 'overdue' | 'pending_verification' | 'verified' | 'reopened' | 'closed'
type CapaAction = {
id: string
incident_id: string
description: string
department: string
due_date: string
priority: 'low' | 'med' | 'high'
status: CapaStatus
incidents: { reference_no: string | null } | null
owner: { name: string } | null
}
const STATUS_ORDER: CapaStatus[] = ['open', 'in_progress', 'overdue', 'pending_verification', 'verified', 'closed']
const STATUS_LABELS: Record<CapaStatus, string> = {
open: 'Open',
in_progress: 'In Progress',
overdue: 'Overdue',
pending_verification: 'Pending Verification',
verified: 'Verified',
reopened: 'Reopened',
closed: 'Closed',
}
const COLUMN_BORDER: Record<CapaStatus, string> = {
open: 'border-divider',
in_progress: 'border-divider',
overdue: 'border-accent',
pending_verification: 'border-divider',
verified: 'border-divider',
reopened: 'border-accent',
closed: 'border-divider',
}
interface Props {
capas: CapaAction[]
}
export function CapaBoard({ capas }: Props) {
const [view, setView] = useState<'board' | 'table'>('board')
const byStatus = STATUS_ORDER.reduce<Record<CapaStatus, CapaAction[]>>((acc, s) => {
acc[s] = capas.filter(c => c.status === s)
return acc
}, {} as Record<CapaStatus, CapaAction[]>)
if (view === 'table') {
return (
<div>
<div className="flex justify-end mb-3">
<button onClick={() => setView('board')} className="text-sm text-accent-700 hover:underline">Board view</button>
</div>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-left text-xs text-gray-500 uppercase border-b">
<th className="pb-2 pr-4">Ref</th>
<th className="pb-2 pr-4">Action</th>
<th className="pb-2 pr-4">Owner</th>
<th className="pb-2 pr-4">Due</th>
<th className="pb-2 pr-4">Priority</th>
<th className="pb-2">Status</th>
</tr>
</thead>
<tbody className="divide-y divide-divider">
{capas.map(c => (
<tr key={c.id}>
<td className="py-2 pr-4 text-gray-500 text-xs">
{(c.incidents as { reference_no: string | null } | null)?.reference_no ?? '—'}
</td>
<td className="py-2 pr-4">
<Link href={`/hse/capa/${c.id}`} className="text-accent-700 hover:underline line-clamp-2">
{c.description}
</Link>
</td>
<td className="py-2 pr-4 text-gray-600">{(c.owner as { name: string } | null)?.name ?? '—'}</td>
<td className="py-2 pr-4 text-gray-600">{c.due_date}</td>
<td className="py-2 pr-4">
<PriorityTag priority={c.priority} />
</td>
<td className="py-2 text-gray-600 text-xs">{STATUS_LABELS[c.status]}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)
}
return (
<div>
<div className="flex justify-end mb-3">
<button onClick={() => setView('table')} className="text-sm text-accent-700 hover:underline">Table view</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{STATUS_ORDER.filter(s => s !== 'reopened').map(status => (
<div key={status} className={`border p-4 bg-ground ${COLUMN_BORDER[status]}`}>
<h3 className="text-xs font-extrabold uppercase tracking-wide text-ink/70 mb-3 pb-2 border-b border-divider">
{STATUS_LABELS[status]} ({byStatus[status].length})
</h3>
<div className="space-y-2 max-h-96 overflow-y-auto pr-2">
{byStatus[status].map(c => (
<Link key={c.id} href={`/hse/capa/${c.id}`}
className="block bg-surface p-3 shadow-sm hover:shadow-md transition-shadow border border-divider">
<p className="text-sm text-gray-800 line-clamp-2 mb-1">{c.description}</p>
<div className="flex items-center justify-between text-xs text-gray-500">
<span>{(c.owner as { name: string } | null)?.name ?? '—'}</span>
<PriorityTag priority={c.priority} />
</div>
<p className="text-xs text-gray-400 mt-1">Due {c.due_date}</p>
</Link>
))}
{byStatus[status].length === 0 && (
<p className="text-xs text-gray-400 text-center py-3">Empty</p>
)}
</div>
</div>
))}
</div>
</div>
)
}
+38 -33
View File
@@ -2,6 +2,8 @@
import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Field, Input, Select, Textarea } from '@/components/ui/field'
interface User {
id: string
@@ -71,59 +73,62 @@ export function CapaForm({ incidentId }: Props) {
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Action Description *</label>
<textarea
<Field label="Action Description *" htmlFor="capa-description">
<Textarea
id="capa-description"
value={description}
onChange={e => setDescription(e.target.value)}
rows={3} required
className="w-full border border-divider px-3 py-2 text-sm"
rows={3}
required
placeholder="What corrective action will be taken?"
/>
</div>
</Field>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Root Cause Reference</label>
<input type="text" value={rootCauseRef}
<Field label="Root Cause Reference" htmlFor="capa-root-cause">
<Input
id="capa-root-cause"
type="text"
value={rootCauseRef}
onChange={e => setRootCauseRef(e.target.value)}
className="w-full border border-divider px-3 py-2 text-sm"
placeholder="e.g. Why #3 — inadequate training" />
</div>
placeholder="e.g. Why #3 — inadequate training"
/>
</Field>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Assigned To *</label>
<select value={ownerId} onChange={e => handleOwnerChange(e.target.value)} required
className="w-full border border-divider px-3 py-2 text-sm">
<Field label="Assigned To *" htmlFor="capa-owner">
<Select id="capa-owner" value={ownerId} onChange={e => handleOwnerChange(e.target.value)} required>
<option value="">Select owner…</option>
{users.map(u => (
<option key={u.id} value={u.id}>{u.name} ({u.department})</option>
))}
</select>
</div>
</Select>
</Field>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Due Date *</label>
<input type="date" value={dueDate} onChange={e => setDueDate(e.target.value)} required
className="w-full border border-divider px-3 py-2 text-sm" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Priority</label>
<select value={priority} onChange={e => setPriority(e.target.value as 'low' | 'med' | 'high')}
className="w-full border border-divider px-3 py-2 text-sm">
<Field label="Due Date *" htmlFor="capa-due">
<Input id="capa-due" type="date" value={dueDate} onChange={e => setDueDate(e.target.value)} required />
</Field>
<Field label="Priority" htmlFor="capa-priority">
<Select
id="capa-priority"
value={priority}
onChange={e => setPriority(e.target.value as 'low' | 'med' | 'high')}
>
<option value="low">Low</option>
<option value="med">Medium</option>
<option value="high">High</option>
</select>
</div>
</Select>
</Field>
</div>
{error && <p className="text-sm text-red-600">{error}</p>}
{error && (
<p role="alert" className="rounded-md bg-st-red-bg px-3 py-2 text-[13px] text-st-red-fg">
{error}
</p>
)}
<button type="submit" disabled={saving}
className="w-full bg-accent text-white py-2 text-sm font-semibold disabled:opacity-50">
<Button type="submit" block disabled={saving}>
{saving ? 'Creating…' : 'Create CAPA Action'}
</button>
</Button>
</form>
)
}
+5 -15
View File
@@ -2,6 +2,8 @@
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { SubmitVerificationForm } from '@/components/capa/submit-verification-form'
interface Props {
capaId: string
@@ -33,26 +35,14 @@ export function CapaOwnerActions({ capaId, currentStatus }: Props) {
if (currentStatus === 'open' || currentStatus === 'reopened' || currentStatus === 'overdue') {
return (
<button
onClick={() => updateStatus('in_progress')}
disabled={loading}
className="text-sm px-3 py-1.5 border border-divider hover:bg-gray-50 disabled:opacity-50"
>
<Button variant="secondary" onClick={() => updateStatus('in_progress')} disabled={loading}>
{loading ? '…' : 'Mark In Progress'}
</button>
</Button>
)
}
if (currentStatus === 'in_progress') {
return (
<button
onClick={() => updateStatus('pending_verification')}
disabled={loading}
className="text-sm px-3 py-1.5 bg-accent text-white hover:bg-accent-600 disabled:opacity-50"
>
{loading ? '…' : 'Submit for Verification'}
</button>
)
return <SubmitVerificationForm capaId={capaId} />
}
return null
+11 -12
View File
@@ -1,6 +1,8 @@
'use client'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Field, Textarea } from '@/components/ui/field'
interface Props {
capaId: string
@@ -32,25 +34,22 @@ export function CapaOwnerNotesForm({ capaId, initialNotes }: Props) {
}
return (
<div className="mt-3 space-y-1">
<label className="text-xs text-gray-500 font-medium">Remarks / Notes</label>
<textarea
<div className="mt-3 space-y-2">
<Field label="Remarks / Notes" htmlFor={`notes-${capaId}`}>
<Textarea
id={`notes-${capaId}`}
value={notes}
onChange={e => { setNotes(e.target.value); setSaved(false) }}
rows={2}
placeholder="Add any notes or updates for this action…"
className="w-full border border-divider px-3 py-2 text-sm text-gray-800 resize-none focus:outline-none focus:ring-2 focus:ring-accent"
/>
{error && <p className="text-xs text-red-600">{error}</p>}
</Field>
{error && <p role="alert" className="text-xs text-danger">{error}</p>}
<div className="flex items-center gap-2">
<button
onClick={handleSave}
disabled={saving}
className="text-xs px-3 py-1 bg-gray-800 text-white hover:bg-gray-700 disabled:opacity-50"
>
<Button variant="secondary" onClick={handleSave} disabled={saving}>
{saving ? 'Saving…' : 'Save Notes'}
</button>
{saved && <span className="text-xs text-ink">Saved</span>}
</Button>
{saved && <span className="text-xs text-st-green-fg">Saved</span>}
</div>
</div>
)
+167
View File
@@ -0,0 +1,167 @@
'use client'
import { useMemo, useState } from 'react'
import { useRouter } from 'next/navigation'
import { ChevronRight, Columns3, List, Search } from 'lucide-react'
import { Avatar } from '@/components/ui/avatar'
import { FilterChip } from '@/components/ui/filter-chip'
import { Segmented } from '@/components/ui/segmented'
import { PriorityTag, StatusTag } from '@/components/ui/status-tag'
import { TableCard, type Column } from '@/components/ui/table-card'
import {
EMPTY_FILTERS, PAGE_SIZE, VIEWS, daysLate, distinct, filterCapas, nextSort, paginate, sortCapas, viewCounts,
type CapaFilters, type CapaRow, type CapaSort, type CapaSortKey, type CapaViewKey,
} from '@/lib/capa/list'
import { CapaBoardView } from './capa-board-view'
const PRIORITY_OPTIONS = [
{ value: 'high', label: 'High' },
{ value: 'med', label: 'Medium' },
{ value: 'low', label: 'Low' },
]
const toOptions = (values: string[]) => values.map(v => ({ value: v, label: v }))
function Owner({ name }: { name: string | null }) {
if (!name) return <span className="text-faint">—</span>
return (
<span className="inline-flex items-center gap-2">
<Avatar name={name} />
{name}
</span>
)
}
function Due({ row, today }: { row: CapaRow; today: string }) {
const late = row.status === 'overdue' ? daysLate(row.due_date, today) : 0
return (
<span className="whitespace-nowrap">
{row.due_date}
{late > 0 && <span className="ml-1.5 text-xs text-danger">{`${late} day${late === 1 ? '' : 's'} late`}</span>}
</span>
)
}
export function CapaWorkspace({ capas, today }: { capas: CapaRow[]; today: string }) {
const router = useRouter()
const [mode, setMode] = useState<'list' | 'board'>('list')
const [filters, setFilters] = useState<CapaFilters>(EMPTY_FILTERS)
const [sort, setSort] = useState<CapaSort>({ key: 'due_date', dir: 'asc' })
const [page, setPage] = useState(1)
const patch = (next: Partial<CapaFilters>) => {
setFilters(f => ({ ...f, ...next }))
setPage(1)
}
const owners = useMemo(() => distinct(capas.map(c => c.owner_name)), [capas])
const departments = useMemo(() => distinct(capas.map(c => c.department)), [capas])
const counts = useMemo(() => viewCounts(capas, filters), [capas, filters])
const sorted = useMemo(() => sortCapas(filterCapas(capas, filters), sort), [capas, filters, sort])
const boardRows = useMemo(
() => sortCapas(filterCapas(capas, { ...filters, view: 'all' }), { key: 'due_date', dir: 'asc' }),
[capas, filters],
)
const pageData = paginate(sorted, page, PAGE_SIZE)
const clearable = Boolean(filters.q || filters.owner || filters.department || filters.priority)
const columns: Column<CapaRow>[] = [
{ key: 'action', header: 'Action', cell: r => <span className="line-clamp-2 font-medium">{r.description}</span> },
{ key: 'incident', header: 'Incident', cell: r => <span className="font-mono text-[12.5px] text-accent">{r.incident_ref ?? '—'}</span> },
{ key: 'owner', header: 'Owner', cell: r => <Owner name={r.owner_name} /> },
{ key: 'department', header: 'Department', cell: r => r.department },
{ key: 'priority', header: 'Priority', sortKey: 'priority', cell: r => <PriorityTag priority={r.priority} /> },
{ key: 'due', header: 'Due', sortKey: 'due_date', cell: r => <Due row={r} today={today} /> },
{ key: 'status', header: 'Status', sortKey: 'status', cell: r => <StatusTag status={r.status} /> },
]
const toolbar = (
<>
<label className="flex h-8 min-w-[260px] items-center gap-2 rounded-md bg-surface px-2.5 text-[13px] shadow-input">
<Search size={16} strokeWidth={2} className="text-muted" aria-hidden />
<input
type="search"
aria-label="Search actions"
placeholder="Search action, incident or owner"
value={filters.q}
onChange={e => patch({ q: e.target.value })}
className="flex-1 bg-transparent outline-none placeholder:text-faint"
/>
</label>
<FilterChip label="Owner" value={filters.owner} options={toOptions(owners)} onChange={v => patch({ owner: v })} />
<FilterChip label="Department" value={filters.department} options={toOptions(departments)} onChange={v => patch({ department: v })} />
<FilterChip label="Priority" value={filters.priority} options={PRIORITY_OPTIONS} onChange={v => patch({ priority: v })} />
{clearable && (
<button
type="button"
onClick={() => patch({ q: '', owner: '', department: '', priority: '' })}
className="cursor-pointer text-[12.5px] text-muted hover:text-ink"
>
Clear filters
</button>
)}
</>
)
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-[22px] font-[650] md:text-xl">CAPA</h1>
<Segmented
value={mode}
onChange={v => setMode(v as 'list' | 'board')}
options={[
{ value: 'list', label: <><List size={14} strokeWidth={2} aria-hidden />List</> },
{ value: 'board', label: <><Columns3 size={14} strokeWidth={2} aria-hidden />Board</> },
]}
/>
</div>
{mode === 'list' ? (
<TableCard
columns={columns}
rows={pageData.items}
rowKey={r => r.id}
onRowOpen={r => router.push(`/hse/capa/${r.id}`)}
views={{
items: VIEWS.map(v => ({ key: v.key, label: v.label, count: counts[v.key] })),
active: filters.view,
onChange: key => patch({ view: key as CapaViewKey }),
}}
toolbar={toolbar}
sort={sort}
onSortChange={key => {
setSort(nextSort(sort, key as CapaSortKey))
setPage(1)
}}
footer={
pageData.total > 0
? { from: pageData.from, to: pageData.to, total: pageData.total, page: pageData.page, pageCount: pageData.pageCount, onPage: setPage }
: undefined
}
empty={{ title: 'No CAPA actions match' }}
mobileRow={r => (
<div className="flex items-start gap-3">
<div className="min-w-0 flex-1 space-y-1">
<p className="line-clamp-2 text-[13px] font-medium">{r.description}</p>
<div className="flex items-center gap-2">
<StatusTag status={r.status} />
<PriorityTag priority={r.priority} />
</div>
<p className="text-xs text-faint">
{[r.incident_ref, r.owner_name, `Due ${r.due_date}`].filter(Boolean).join(' · ')}
</p>
</div>
<ChevronRight size={16} strokeWidth={2} className="mt-1 text-faint" aria-hidden />
</div>
)}
/>
) : (
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-2">{toolbar}</div>
<CapaBoardView capas={boardRows} />
</div>
)}
</div>
)
}
+13 -10
View File
@@ -2,6 +2,7 @@
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
interface Props {
capaId: string
@@ -31,19 +32,21 @@ export function CloseCapaButton({ capaId }: Props) {
}
return (
<div className="border border-divider p-5 space-y-3 bg-neutral-100">
<h3 className="text-sm font-semibold text-gray-800">Close CAPA</h3>
<p className="text-sm text-gray-600">
<div className="space-y-3 rounded-xl bg-surface p-5 shadow-card">
<div>
<h3 className="text-sm font-semibold">Close CAPA</h3>
<p className="mt-0.5 text-xs text-muted">
This CAPA has been verified as effective. Close it to mark it fully resolved.
</p>
{error && <p className="text-sm text-red-600">{error}</p>}
<button
onClick={handleClose}
disabled={loading}
className="w-full bg-accent text-white py-2 text-sm font-semibold hover:bg-accent-700 disabled:opacity-50"
>
</div>
{error && (
<p role="alert" className="rounded-md bg-st-red-bg px-3 py-2 text-[13px] text-st-red-fg">
{error}
</p>
)}
<Button onClick={handleClose} disabled={loading}>
{loading ? 'Closing…' : 'Close CAPA'}
</button>
</Button>
</div>
)
}
@@ -0,0 +1,108 @@
'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>
)
}
+73 -40
View File
@@ -2,14 +2,47 @@
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Field, Textarea } from '@/components/ui/field'
import { cx } from '@/components/ui/cx'
interface Props {
capaId: string
}
type Verdict = 'verified' | 'reopened'
function Choice({
selected,
onSelect,
title,
hint,
}: {
selected: boolean
onSelect: () => void
title: string
hint: string
}) {
return (
<button
type="button"
role="radio"
aria-checked={selected}
onClick={onSelect}
className={cx(
'cursor-pointer rounded-xl p-3 text-left transition-colors',
selected ? 'bg-accent-tint shadow-chip-set' : 'bg-surface shadow-chip hover:bg-surface-2',
)}
>
<span className="block text-[13px] font-semibold">{title}</span>
<span className="mt-0.5 block text-xs text-muted">{hint}</span>
</button>
)
}
export function VerifyForm({ capaId }: Props) {
const router = useRouter()
const [verdict, setVerdict] = useState<'verified' | 'reopened' | null>(null)
const [verdict, setVerdict] = useState<Verdict | null>(null)
const [reopenReason, setReopenReason] = useState('')
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
@@ -39,50 +72,50 @@ export function VerifyForm({ capaId }: Props) {
}
return (
<form onSubmit={handleSubmit} className="border border-divider p-5 space-y-4 bg-accent-100">
<h3 className="text-sm font-semibold text-gray-800">HSE Verification</h3>
<div className="flex gap-3">
<button
type="button"
onClick={() => setVerdict('verified')}
className={`flex-1 py-2 text-sm font-medium border ${
verdict === 'verified'
? 'bg-accent text-white border-accent'
: 'bg-surface text-gray-700 border-divider hover:border-accent'
}`}
>
Verified — Effective
</button>
<button
type="button"
onClick={() => setVerdict('reopened')}
className={`flex-1 py-2 text-sm font-medium border ${
verdict === 'reopened'
? 'bg-accent text-white border-accent'
: 'bg-surface text-gray-700 border-divider hover:border-accent'
}`}
>
Reopen — Ineffective
</button>
</div>
{verdict === 'reopened' && (
<form onSubmit={handleSubmit} className="space-y-4 rounded-xl bg-surface p-5 shadow-card">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Why is the action ineffective? *</label>
<textarea
value={reopenReason}
onChange={e => setReopenReason(e.target.value)}
rows={2} required
className="w-full border border-divider px-3 py-2 text-sm"
placeholder="Describe why the corrective action did not resolve the root cause…"
<h3 className="text-sm font-semibold">Verify this action</h3>
<p className="mt-0.5 text-xs text-muted">Confirm the corrective action fixed the root cause, or send it back.</p>
</div>
<div role="radiogroup" aria-label="Verification verdict" className="grid gap-3 sm:grid-cols-2">
<Choice
selected={verdict === 'verified'}
onSelect={() => setVerdict('verified')}
title="Verified, effective"
hint="Root cause addressed. The action is marked verified."
/>
<Choice
selected={verdict === 'reopened'}
onSelect={() => setVerdict('reopened')}
title="Reopen, ineffective"
hint="Returns to the owner with a required reason."
/>
</div>
{verdict === 'reopened' && (
<Field label="Why is the action ineffective? *" htmlFor="reopen-reason">
<Textarea
id="reopen-reason"
value={reopenReason}
onChange={e => setReopenReason(e.target.value)}
rows={2}
required
placeholder="Describe why the corrective action did not resolve the root cause…"
/>
</Field>
)}
{error && <p className="text-sm text-red-600">{error}</p>}
{error && (
<p role="alert" className="rounded-md bg-st-red-bg px-3 py-2 text-[13px] text-st-red-fg">
{error}
</p>
)}
{verdict && (
<button type="submit" disabled={saving}
className="w-full bg-gray-900 text-white py-2 text-sm font-semibold disabled:opacity-50">
{saving ? 'Saving…' : 'Submit Verification'}
</button>
<Button type="submit" disabled={saving}>
{saving ? 'Saving…' : verdict === 'verified' ? 'Confirm verification' : 'Reopen action'}
</Button>
)}
</form>
)
+52 -5
View File
@@ -5,16 +5,20 @@ import { useRouter } from 'next/navigation'
import { FileUpload } from '@/components/incidents/file-upload'
import type { IncidentType, MedicalStatus } from '@/lib/incidents/validate'
import { useTranslations } from '@/lib/i18n/context'
import { zonesForSite, resolveZoneToken, type SiteOption } from '@/lib/report/zones'
import { siteForTruck } from '@/lib/report/trucks'
interface Props {
zoneToken: string | null
zoneName: string | null
siteName: string | null
trucks: Array<{ id: string; truck_no: string; carrier: string | null }>
sites: SiteOption[]
defaultSiteId: string
trucks: Array<{ id: string; truck_no: string; carrier: string | null; site_id: string | null }>
initialTruckId?: string | null
}
export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
export function ReportForm({ zoneToken, sites, defaultSiteId, trucks, initialTruckId }: Props) {
const router = useRouter()
const t = useTranslations('ReportForm')
const itLabels = useTranslations('IncidentType')
@@ -52,6 +56,15 @@ export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
} | null>(null)
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({
incident_type: (initialTruckId ? 'transport' : '') as IncidentType | '',
description: '',
@@ -113,7 +126,7 @@ export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
try {
const { addPendingReport } = await import('@/lib/offline/db')
await addPendingReport({
zone_token: zoneToken ?? '',
zone_token: effectiveZoneToken ?? '',
incident_type: form.incident_type as IncidentType,
description: form.description,
injury_involved: form.injury_involved,
@@ -162,7 +175,7 @@ export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
try {
const fd = new FormData()
if (zoneToken) fd.append('zone_token', zoneToken)
if (effectiveZoneToken) fd.append('zone_token', effectiveZoneToken)
fd.append('incident_type', form.incident_type)
fd.append('description', form.description)
fd.append('injury_involved', String(form.injury_involved))
@@ -225,6 +238,40 @@ export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
</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>
<label className="block text-sm font-medium text-gray-700 mb-1">
{t.incidentTypeLabel} <span className="text-red-500">*</span>
@@ -382,7 +429,7 @@ export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
<button
type="submit"
disabled={submitting || !form.incident_type || (form.incident_type === 'transport' && !form.truck_id)}
disabled={submitting || !effectiveZoneToken || !form.incident_type || (form.incident_type === 'transport' && !form.truck_id)}
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"
>
+8 -10
View File
@@ -16,14 +16,13 @@ export interface NavItem {
}
const NAV_ITEMS: Record<string, NavItem[]> = {
reporter: [
{ label: 'My Reports', href: '/reporter', icon: ClipboardList },
ssa: [
{ label: 'Overview', href: '/ssa', icon: AlignLeft },
{ 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 },
],
supervisor: [
{ label: 'Overview', href: '/supervisor', icon: AlignLeft },
{ label: 'Incidents', href: '/supervisor/incidents', icon: ClipboardList },
],
hse: [
{ label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard },
{ label: 'Incidents', href: '/hse/incidents', icon: ClipboardList },
@@ -31,7 +30,6 @@ const NAV_ITEMS: Record<string, NavItem[]> = {
{ label: 'Settings', href: '/hse/settings', icon: Settings },
],
management: [{ label: 'Dashboard', href: '/management', icon: LayoutDashboard }],
capa_owner: [{ label: 'My CAPAs', href: '/capa-owner', icon: CircleCheck }],
admin: [
{ label: 'Admin', href: '/admin', icon: Users },
{ label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard },
@@ -42,10 +40,10 @@ const NAV_ITEMS: Record<string, NavItem[]> = {
],
}
const EXACT_ROOTS = ['/reporter', '/supervisor', '/management', '/capa-owner', '/admin', '/report', '/account']
const EXACT_ROOTS = ['/ssa', '/management', '/admin', '/report', '/account']
export function navItemsFor(role: string): NavItem[] {
return NAV_ITEMS[role] ?? NAV_ITEMS.reporter
return NAV_ITEMS[role] ?? NAV_ITEMS.ssa
}
export function isActivePath(href: string, pathname: string): boolean {
@@ -54,6 +52,6 @@ export function isActivePath(href: string, pathname: string): boolean {
export function searchHrefFor(role: string): string | null {
if (role === 'hse' || role === 'admin') return '/hse/incidents'
if (role === 'supervisor') return '/supervisor/incidents'
if (role === 'ssa') return '/ssa/incidents'
return null
}
+5
View File
@@ -0,0 +1,5 @@
-- 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
@@ -0,0 +1,5 @@
-- 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
@@ -0,0 +1,166 @@
-- 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
@@ -0,0 +1,67 @@
-- 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
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', 'supervisor'));
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 (
@@ -70,12 +70,12 @@ 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_supervisor" ON incidents FOR SELECT
USING (auth_user_role() = 'supervisor' AND site_id = auth_user_site_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', 'supervisor'));
USING (auth_user_role() IN ('hse', 'admin', 'ssa'));
-- evidence_files
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
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', 'supervisor'));
USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa'));
-- No DELETE policy: files are never deleted (soft-delete only via `deleted` flag)
-- investigations
CREATE POLICY "investigations_hse_admin" ON investigations FOR ALL
USING (auth_user_role() IN ('hse', 'admin'));
CREATE POLICY "investigations_read_supervisor" ON investigations FOR SELECT
USING (auth_user_role() = 'supervisor');
CREATE POLICY "investigations_read_ssa" ON investigations FOR SELECT
USING (auth_user_role() = 'ssa');
-- capa_actions (capa_update_owner is tightened — no department clause)
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
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', 'supervisor'));
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'));
@@ -108,7 +108,7 @@ CREATE POLICY "dosh_hse_admin" ON dosh_reports FOR ALL
-- notifications_log (final state after migration 19 fix)
CREATE POLICY "notifications_insert_elevated" ON notifications_log FOR INSERT
WITH CHECK (auth_user_role() IN ('hse', 'admin', 'supervisor'));
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
@@ -130,7 +130,7 @@ CREATE POLICY "admin_update_settings" ON app_settings FOR ALL
-- incident_addenda
CREATE POLICY "addenda_read" ON incident_addenda FOR SELECT
USING (
auth_user_role() IN ('hse', 'admin', 'supervisor', 'management')
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()
@@ -139,5 +139,5 @@ CREATE POLICY "addenda_read" ON incident_addenda FOR SELECT
CREATE POLICY "addenda_insert" ON incident_addenda FOR INSERT
WITH CHECK (
author = app_current_user_id()
AND auth_user_role() IN ('hse', 'admin', 'supervisor')
AND auth_user_role() IN ('hse', 'admin', 'ssa')
);
+8 -2
View File
@@ -16,7 +16,7 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Enums
-- ---------------------------------------------------------------------------
CREATE TYPE user_role AS ENUM (
'reporter', 'supervisor', 'hse', 'capa_owner', 'management', 'admin'
'ssa', 'hse', 'management', 'admin'
);
CREATE TYPE incident_type AS ENUM (
@@ -80,7 +80,7 @@ CREATE TABLE users (
name TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '' UNIQUE,
phone TEXT,
role user_role NOT NULL DEFAULT 'reporter',
role user_role NOT NULL DEFAULT 'ssa',
department TEXT,
site_id UUID REFERENCES sites(id),
active BOOLEAN NOT NULL DEFAULT true,
@@ -101,6 +101,9 @@ CREATE TABLE trucks (
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
CREATE TABLE incidents (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
@@ -197,6 +200,9 @@ 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_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 (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
incident_id UUID NOT NULL REFERENCES incidents(id) ON DELETE RESTRICT,
+3 -1
View File
@@ -172,6 +172,8 @@ Notifications drawer: absolute, top/right/bottom 8px, width 420px, white, radius
| 12-15 | Mobile, new incident 1/3 to saved offline | `/report` |
| 16 | Mobile, CAPA owner action | `/capa-owner` |
Mockup features with no backend yet (do not fake them in the UI): CAPA export, bulk actions on a selection (send reminder, reassign, escalate), group-by, department and due-date range filters, the activity and comments feed, cost, evidence files on a CAPA, the verification note, "ask owner a question", and edit. Add them in a slice that also adds the backend.
New routes in the mockup that do not exist yet: audit log (05d), DOSH reporting entry (02d), and any "new tab" marked above. Treat them as separate features; do not build them as part of the restyle.
## 6. Accessibility
@@ -193,7 +195,7 @@ This file covers look and component structure. Routes, queries, permissions and
5. **Migrate the Incidents list** (screen 01 and 10) as the first full screen.
6. **Remaining screens**, in §5 order, one plan per group.
Slice 1 (gate, tokens, primitives, TableCard, shells, Incidents list) is implemented; the remaining screens follow in later plans.
Slice 1 (gate, tokens, primitives, TableCard, shells, Incidents list) and slice 2 (CAPA list, board, detail, verification, create form) are implemented; the remaining screens follow in later plans.
Gate first: before step 1, update `scripts/check-design-gates.mjs` to allow `rounded-*`, flag `border-b-2` and `border-2`, and flag Archivo and `#ec3013`. `npm run check:design` must pass at the end of each step.
+24
View File
@@ -0,0 +1,24 @@
# 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
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,886 @@
# 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"
```
@@ -0,0 +1,72 @@
# 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.
@@ -0,0 +1,43 @@
# 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
@@ -0,0 +1,11 @@
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 }
}
+11 -9
View File
@@ -1,26 +1,28 @@
// lib/auth/roles.ts
// 'ssa' = Site Safety Assistant. Replaces the former reporter, supervisor and capa_owner roles.
export type UserRole =
| 'reporter'
| 'supervisor'
| 'ssa'
| 'hse'
| 'capa_owner'
| 'management'
| 'admin'
export const ALL_ROLES: UserRole[] = [
'reporter',
'supervisor',
'ssa',
'hse',
'capa_owner',
'management',
'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> = {
reporter: '/reporter',
supervisor: '/supervisor',
ssa: '/ssa',
hse: '/hse',
capa_owner: '/capa-owner',
management: '/management',
admin: '/admin',
}
+111
View File
@@ -0,0 +1,111 @@
export type CapaStatus =
| 'open' | 'in_progress' | 'overdue' | 'pending_verification' | 'verified' | 'reopened' | 'closed'
export type CapaPriority = 'low' | 'med' | 'high'
export interface CapaRow {
id: string
incident_id: string
description: string
department: string
due_date: string
priority: CapaPriority
status: CapaStatus
incident_ref: string | null
owner_name: string | null
}
export const PAGE_SIZE = 25
export const STATUS_ORDER: CapaStatus[] = [
'open', 'in_progress', 'overdue', 'reopened', 'pending_verification', 'verified', 'closed',
]
export type CapaViewKey = 'all' | 'active' | 'overdue' | 'verification' | 'done'
export const VIEWS: Array<{ key: CapaViewKey; label: string; statuses: CapaStatus[] | null }> = [
{ key: 'all', label: 'All', statuses: null },
{ key: 'active', label: 'Active', statuses: ['open', 'in_progress', 'reopened'] },
{ key: 'overdue', label: 'Overdue', statuses: ['overdue'] },
{ key: 'verification', label: 'Verification', statuses: ['pending_verification'] },
{ key: 'done', label: 'Done', statuses: ['verified', 'closed'] },
]
export interface CapaFilters {
q: string
owner: string
department: string
priority: string
view: CapaViewKey
}
export const EMPTY_FILTERS: CapaFilters = { q: '', owner: '', department: '', priority: '', view: 'all' }
export type CapaSortKey = 'due_date' | 'priority' | 'status'
export type CapaSort = { key: CapaSortKey; dir: 'asc' | 'desc' }
function matchesOthers(r: CapaRow, f: CapaFilters): boolean {
if (f.owner && r.owner_name !== f.owner) return false
if (f.department && r.department !== f.department) return false
if (f.priority && r.priority !== f.priority) return false
if (f.q) {
const q = f.q.toLowerCase()
const hay = `${r.description} ${r.incident_ref ?? ''} ${r.owner_name ?? ''}`.toLowerCase()
if (!hay.includes(q)) return false
}
return true
}
function inView(r: CapaRow, view: CapaViewKey): boolean {
const statuses = VIEWS.find(v => v.key === view)?.statuses ?? null
return statuses === null || statuses.includes(r.status)
}
export function filterCapas(rows: CapaRow[], f: CapaFilters): CapaRow[] {
return rows.filter(r => matchesOthers(r, f) && inView(r, f.view))
}
export function viewCounts(rows: CapaRow[], f: CapaFilters): Record<CapaViewKey, number> {
const scoped = rows.filter(r => matchesOthers(r, f))
const counts = {} as Record<CapaViewKey, number>
for (const v of VIEWS) counts[v.key] = scoped.filter(r => inView(r, v.key)).length
return counts
}
const PRIORITY_RANK: Record<CapaPriority, number> = { high: 0, med: 1, low: 2 }
export function sortCapas(rows: CapaRow[], sort: CapaSort): CapaRow[] {
const sign = sort.dir === 'asc' ? 1 : -1
const key = (r: CapaRow): number | string =>
sort.key === 'priority' ? PRIORITY_RANK[r.priority]
: sort.key === 'status' ? STATUS_ORDER.indexOf(r.status)
: r.due_date
return [...rows].sort((a, b) => {
const ka = key(a)
const kb = key(b)
return ka < kb ? -sign : ka > kb ? sign : 0
})
}
export function nextSort(current: CapaSort, key: CapaSortKey): CapaSort {
if (current.key === key) return { key, dir: current.dir === 'asc' ? 'desc' : 'asc' }
return { key, dir: 'asc' }
}
export function paginate<T>(rows: T[], page: number, size: number) {
const total = rows.length
const pageCount = Math.max(1, Math.ceil(total / size))
const p = Math.min(Math.max(1, page), pageCount)
const items = rows.slice((p - 1) * size, p * size)
const from = items.length === 0 ? 0 : (p - 1) * size + 1
const to = items.length === 0 ? 0 : from + items.length - 1
return { items, from, to, total, page: p, pageCount }
}
export function distinct(values: Array<string | null | undefined>): string[] {
return [...new Set(values.filter((v): v is string => Boolean(v)))].sort()
}
export function daysLate(due: string, today: string): number {
const diff = Math.round((Date.parse(today) - Date.parse(due)) / 86_400_000)
return Math.max(0, diff)
}
+18
View File
@@ -0,0 +1,18 @@
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,3 +3,7 @@ import OpenAI from 'openai'
export function createDeepSeekClient(apiKey: string): OpenAI {
return new OpenAI({ apiKey, baseURL: 'https://api.deepseek.com' })
}
export function createLocalLLMClient(): OpenAI {
return new OpenAI({ apiKey: 'local', baseURL: 'http://localhost:8081/v1' })
}
+5 -2
View File
@@ -10,6 +10,7 @@ import {
date,
jsonb,
customType,
type AnyPgColumn,
} from 'drizzle-orm/pg-core'
// ---------------------------------------------------------------------------
@@ -25,7 +26,7 @@ const vector = customType<{ data: number[]; driverData: string }>({
// Enums
// ---------------------------------------------------------------------------
export const userRoleEnum = pgEnum('user_role', [
'reporter', 'supervisor', 'hse', 'capa_owner', 'management', 'admin',
'ssa', 'hse', 'management', 'admin',
])
export const incidentTypeEnum = pgEnum('incident_type', [
@@ -88,7 +89,7 @@ export const users = pgTable('users', {
name: text('name').notNull().default(''),
email: text('email').notNull().default('').unique(),
phone: text('phone'),
role: userRoleEnum('role').notNull().default('reporter'),
role: userRoleEnum('role').notNull().default('ssa'),
department: text('department'),
siteId: uuid('site_id').references(() => sites.id),
active: boolean('active').notNull().default(true),
@@ -102,6 +103,7 @@ export const trucks = pgTable('trucks', {
id: uuid('id').primaryKey().defaultRandom(),
truckNo: text('truck_no').notNull().unique(),
carrier: text('carrier'),
siteId: uuid('site_id').references(() => sites.id),
active: boolean('active').notNull().default(true),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
})
@@ -145,6 +147,7 @@ export const evidenceFiles = pgTable('evidence_files', {
uploadedBy: uuid('uploaded_by').notNull().references(() => users.id),
uploadedAt: timestamp('uploaded_at', { withTimezone: true }).notNull().defaultNow(),
deleted: boolean('deleted').notNull().default(false),
capaId: uuid('capa_id').references((): AnyPgColumn => capaActions.id),
})
export const investigations = pgTable('investigations', {
+1 -1
View File
@@ -97,7 +97,7 @@ export async function escalateOverdueCapa(): Promise<{ notified: number }> {
.from(users)
.where(and(
eq(users.siteId, capa.siteId!),
inArray(users.role, ['hse', 'supervisor', 'management']),
inArray(users.role, ['hse', 'ssa', 'management']),
))
)
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 })
.from(users)
.where(and(
inArray(users.role, ['supervisor', 'hse']),
inArray(users.role, ['ssa', 'hse']),
eq(users.siteId, siteId),
))
)
+12
View File
@@ -0,0 +1,12 @@
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
@@ -0,0 +1,38 @@
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 ?? ''
}
-15
View File
@@ -1,15 +0,0 @@
import 'server-only'
import { createClient as createSupabaseClient, type SupabaseClient } from '@supabase/supabase-js'
// Service-role client — bypasses RLS. Server-side only, and only for operations
// the anon client cannot perform (auth admin user invites). Never import in client code.
export function createAdminClient(): SupabaseClient {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL
const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!url || !serviceRoleKey) {
throw new Error('SUPABASE_SERVICE_ROLE_KEY not configured')
}
return createSupabaseClient(url, serviceRoleKey, {
auth: { autoRefreshToken: false, persistSession: false },
})
}
-9
View File
@@ -1,9 +0,0 @@
// lib/supabase/client.ts
import { createBrowserClient } from '@supabase/ssr'
export function createClient() {
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
)
}
-27
View File
@@ -1,27 +0,0 @@
// lib/supabase/server.ts
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'
export async function createClient() {
const cookieStore = await cookies()
return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return cookieStore.getAll()
},
setAll(cookiesToSet) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options),
)
} catch {
// Server Component — cookie setting handled by middleware
}
},
},
},
)
}
-71
View File
@@ -1,71 +0,0 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import { fileTypeFromBuffer } from 'file-type'
export type EvidenceStage = 'report' | 'response' | 'investigation' | 'capa' | 'verification'
const ALLOWED_MIME_TYPES = new Set([
'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/heic', 'image/avif',
'video/mp4', 'video/quicktime', 'video/webm', 'video/x-msvideo',
'application/pdf',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
])
export async function uploadEvidenceFile(
supabase: SupabaseClient,
file: File,
incidentId: string,
stage: EvidenceStage,
userId: string,
): Promise<{ path: string; publicUrl: string; hash: string }> {
// Server-side size limit before processing
const isVideo = file.type.startsWith('video/')
const maxBytes = isVideo ? 200 * 1024 * 1024 : 10 * 1024 * 1024
if (file.size > maxBytes) {
throw new Error(`File too large: max ${isVideo ? '200MB' : '10MB'} for this file type`)
}
// Magic-byte validation — do not trust client-supplied MIME type
const buffer = await file.arrayBuffer()
const detected = await fileTypeFromBuffer(buffer)
const detectedMime = detected?.mime ?? null
if (!detectedMime || !ALLOWED_MIME_TYPES.has(detectedMime)) {
throw new Error(`File type not allowed: ${detectedMime ?? 'unknown'}`)
}
const ext = detected?.ext ?? file.name.split('.').pop() ?? 'bin'
const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`
const path = `${userId}/${incidentId}/${stage}/${filename}`
const hash = await computeHashFromBuffer(buffer)
const { data: uploadData, error } = await supabase.storage
.from('evidence')
.upload(path, buffer, { contentType: detectedMime, upsert: false })
if (error) throw new Error(error.message)
// Fix 1: Use createSignedUrl (private bucket) — 10-year URL for DB storage
const { data: signedData, error: signedError } = await supabase.storage
.from('evidence')
.createSignedUrl(uploadData.path, 315360000) // ~10 years
if (signedError || !signedData) throw new Error(signedError?.message ?? 'Failed to sign URL')
return { path: uploadData.path, publicUrl: signedData.signedUrl, hash }
}
// Fix 1: getEvidenceUrl is now async, uses 1-hour signed URL
export async function getEvidenceUrl(supabase: SupabaseClient, path: string): Promise<string> {
const { data, error } = await supabase.storage.from('evidence').createSignedUrl(path, 3600)
if (error || !data) throw new Error(error?.message ?? 'Failed to sign URL')
return data.signedUrl
}
async function computeHashFromBuffer(buffer: ArrayBuffer): Promise<string> {
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)
return Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('')
}
+5 -1
View File
@@ -18,7 +18,11 @@
"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.",
"truckLabel": "Truck",
"truckPlaceholder": "Select truck…"
"truckPlaceholder": "Select truck…",
"siteLabel": "Site",
"sitePlaceholder": "Select site…",
"zoneLabel": "Zone",
"zonePlaceholder": "Select zone…"
},
"IncidentType": {
"injury": "Injury / Medical",
+5 -1
View File
@@ -18,7 +18,11 @@
"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.",
"truckLabel": "Trak",
"truckPlaceholder": "Pilih trak…"
"truckPlaceholder": "Pilih trak…",
"siteLabel": "Tapak",
"sitePlaceholder": "Pilih tapak…",
"zoneLabel": "Zon",
"zonePlaceholder": "Pilih zon…"
},
"IncidentType": {
"injury": "Kecederaan / Perubatan",
+5 -1
View File
@@ -18,7 +18,11 @@
"savedOffline": "报告已保存。当您重新联网时将自动提交。",
"offlineBanner": "您处于离线状态。您的报告将在重新联网时自动提交。",
"truckLabel": "货车",
"truckPlaceholder": "选择货车…"
"truckPlaceholder": "选择货车…",
"siteLabel": "场地",
"sitePlaceholder": "选择场地…",
"zoneLabel": "区域",
"zonePlaceholder": "选择区域…"
},
"IncidentType": {
"injury": "受伤/医疗",
-120
View File
@@ -9,8 +9,6 @@
"version": "1.2.2",
"dependencies": {
"@anthropic-ai/sdk": "^0.111.0",
"@supabase/ssr": "^0.12.0",
"@supabase/supabase-js": "^2.110.2",
"bcryptjs": "^3.0.3",
"drizzle-orm": "^0.45.2",
"file-type": "^22.0.1",
@@ -2639,102 +2637,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/@supabase/auth-js": {
"version": "2.110.2",
"resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.110.2.tgz",
"integrity": "sha512-Qj7a6EDP+AMMQFWqGv+qFa8r6re//dk+qQI5bA0KK+PZmnI3JPu97TDeNt6SMiQ2FkklP79hP2yDFYSnA989OA==",
"license": "MIT",
"dependencies": {
"tslib": "2.8.1"
},
"engines": {
"node": ">=22.0.0"
}
},
"node_modules/@supabase/functions-js": {
"version": "2.110.2",
"resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.110.2.tgz",
"integrity": "sha512-ZjjqrXpxM9/rE+eAtZxiK45EWy9EBoJQ322Q5Y75LccYQNh212neHTgXP/o4MIzmH0LNXT8UzvTZtQOfOzyoeQ==",
"license": "MIT",
"dependencies": {
"tslib": "2.8.1"
},
"engines": {
"node": ">=22.0.0"
}
},
"node_modules/@supabase/phoenix": {
"version": "0.4.4",
"resolved": "https://registry.npmjs.org/@supabase/phoenix/-/phoenix-0.4.4.tgz",
"integrity": "sha512-Gt0pqoXuIqX/8dvG0OKp/wMCobXNH3klNbUPBNyOfN0YA1IswrM3HyWFMOPk1Jy+BRaIyDPcFx4jLBwHNmlyfQ==",
"license": "MIT"
},
"node_modules/@supabase/postgrest-js": {
"version": "2.110.2",
"resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.110.2.tgz",
"integrity": "sha512-++LBmcIMwCtgO4tISQUmo9+2xkRwHQqS8ZKMCnhXLe9P8k8YQRXuMoh/RiSzQSoev8gqet0W7yOboW0cUxnt0Q==",
"license": "MIT",
"dependencies": {
"tslib": "2.8.1"
},
"engines": {
"node": ">=22.0.0"
}
},
"node_modules/@supabase/realtime-js": {
"version": "2.110.2",
"resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.110.2.tgz",
"integrity": "sha512-z3jTOTPgyn6E3r6dVOOQ10He4yAMB2czjFw7xVdX3s16MHElna5rY1gVaePs0NIo6xvtMYbtmOXlFaFt/ePLpg==",
"license": "MIT",
"dependencies": {
"@supabase/phoenix": "0.4.4",
"tslib": "2.8.1"
},
"engines": {
"node": ">=22.0.0"
}
},
"node_modules/@supabase/ssr": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/@supabase/ssr/-/ssr-0.12.0.tgz",
"integrity": "sha512-d9XV5XzJvzzZbeAIM7fWTCUYxQJZ2Ru6ny3dJHmHGp/LIrJ+o9FpD7N9Rf/UhhWEvHXSoDe8SI32Z2ouOdMjBg==",
"license": "MIT",
"dependencies": {
"cookie": "^1.0.2"
},
"peerDependencies": {
"@supabase/supabase-js": "^2.108.0"
}
},
"node_modules/@supabase/storage-js": {
"version": "2.110.2",
"resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.110.2.tgz",
"integrity": "sha512-EhsRSwSnmQefKJsAxoRUZ0hvHr92ECM8DDGAKR5z0HdoJx4heI60PjHUTruVNZxKX6XeobLGDyLud020Bw1iwg==",
"license": "MIT",
"dependencies": {
"iceberg-js": "^0.8.1",
"tslib": "2.8.1"
},
"engines": {
"node": ">=22.0.0"
}
},
"node_modules/@supabase/supabase-js": {
"version": "2.110.2",
"resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.110.2.tgz",
"integrity": "sha512-r9q9w4ZQ6mOjh36aqUNFSisBF611vzpO8JphBESr2Q1SWvmGFQeI7Jq7Y+PaNMZ6Zszz+S2yTlJStCpnaMSnQg==",
"license": "MIT",
"dependencies": {
"@supabase/auth-js": "2.110.2",
"@supabase/functions-js": "2.110.2",
"@supabase/postgrest-js": "2.110.2",
"@supabase/realtime-js": "2.110.2",
"@supabase/storage-js": "2.110.2"
},
"engines": {
"node": ">=22.0.0"
}
},
"node_modules/@swc/helpers": {
"version": "0.5.23",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz",
@@ -4629,19 +4531,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/cookie": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -6993,15 +6882,6 @@
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
}
},
"node_modules/iceberg-js": {
"version": "0.8.1",
"resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz",
"integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==",
"license": "MIT",
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/idb": {
"version": "8.0.3",
"resolved": "https://registry.npmjs.org/idb/-/idb-8.0.3.tgz",
-2
View File
@@ -14,8 +14,6 @@
},
"dependencies": {
"@anthropic-ai/sdk": "^0.111.0",
"@supabase/ssr": "^0.12.0",
"@supabase/supabase-js": "^2.110.2",
"bcryptjs": "^3.0.3",
"drizzle-orm": "^0.45.2",
"file-type": "^22.0.1",
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

-8
View File
@@ -1,8 +0,0 @@
# Supabase
.branches
.temp
# dotenvx
.env.keys
.env.local
.env.*.local
-414
View File
@@ -1,414 +0,0 @@
# For detailed configuration reference documentation, visit:
# https://supabase.com/docs/guides/local-development/cli/config
# A string used to distinguish different Supabase projects on the same host. Defaults to the
# working directory name when running `supabase init`.
project_id = "IMS.nosync"
[api]
enabled = true
# Port to use for the API URL.
port = 54321
# Schemas to expose in your API. Tables, views and stored procedures in this schema will get API
# endpoints. `public` and `graphql_public` schemas are included by default.
schemas = ["public", "graphql_public"]
# Extra schemas to add to the search_path of every request.
extra_search_path = ["public", "extensions"]
# The maximum number of rows returns from a view, table, or stored procedure. Limits payload size
# for accidental or malicious requests.
max_rows = 1000
# Controls whether new tables, views, sequences and functions created in the `public` schema by
# `postgres` are reachable through the Data API roles (`anon`, `authenticated`, `service_role`)
# without explicit GRANTs. When unset, new entities are NOT auto-exposed, matching the new cloud
# default. Set to `true` to keep the legacy behaviour of auto-exposing new entities; this is
# deprecated and the field is removed on 2026-10-30 once the always-revoked behaviour is permanent.
# auto_expose_new_tables = true
[api.tls]
# Enable HTTPS endpoints locally using a self-signed certificate.
enabled = false
# Paths to self-signed certificate pair.
# cert_path = "../certs/my-cert.pem"
# key_path = "../certs/my-key.pem"
[db]
# Port to use for the local database URL.
port = 54322
# Port used by db diff command to initialize the shadow database.
shadow_port = 54320
# Maximum amount of time to wait for health check when starting the local database.
health_timeout = "2m"
# The database major version to use. This has to be the same as your remote database's. Run `SHOW
# server_version;` on the remote database to check.
major_version = 17
[db.pooler]
enabled = false
# Port to use for the local connection pooler.
port = 54329
# Specifies when a server connection can be reused by other clients.
# Configure one of the supported pooler modes: `transaction`, `session`.
pool_mode = "transaction"
# How many server connections to allow per user/database pair.
default_pool_size = 20
# Maximum number of client connections allowed.
max_client_conn = 100
# [db.vault]
# secret_key = "env(SECRET_VALUE)"
[db.migrations]
# If disabled, migrations will be skipped during a db push or reset.
enabled = true
# Specifies an ordered list of schema files, directories, or glob patterns that describe your database.
# Supports paths relative to supabase directory: "./schemas/*.sql", "./database".
schema_paths = []
[db.seed]
# If enabled, seeds the database after migrations during a db reset.
enabled = true
# Specifies an ordered list of seed files to load during db reset.
# Supports glob patterns relative to supabase directory: "./seeds/*.sql"
sql_paths = ["./seed.sql"]
[db.network_restrictions]
# Enable management of network restrictions.
enabled = false
# List of IPv4 CIDR blocks allowed to connect to the database.
# Defaults to allow all IPv4 connections. Set empty array to block all IPs.
allowed_cidrs = ["0.0.0.0/0"]
# List of IPv6 CIDR blocks allowed to connect to the database.
# Defaults to allow all IPv6 connections. Set empty array to block all IPs.
allowed_cidrs_v6 = ["::/0"]
# Uncomment to reject non-secure connections to the database.
# [db.ssl_enforcement]
# enabled = true
[realtime]
enabled = true
# Bind realtime via either IPv4 or IPv6. (default: IPv4)
# ip_version = "IPv6"
# The maximum length in bytes of HTTP request headers. (default: 4096)
# max_header_length = 4096
[studio]
enabled = true
# Port to use for Supabase Studio.
port = 54323
# External URL of the API server that frontend connects to.
api_url = "http://127.0.0.1"
# OpenAI API Key to use for Supabase AI in the Supabase Studio.
openai_api_key = "env(OPENAI_API_KEY)"
# Email testing server. Emails sent with the local dev setup are not actually sent - rather, they
# are monitored, and you can view the emails that would have been sent from the web interface.
[local_smtp]
enabled = true
# Port to use for the email testing server web interface.
port = 54324
# Uncomment to expose additional ports for testing user applications that send emails.
# smtp_port = 54325
# pop3_port = 54326
# admin_email = "admin@email.com"
# sender_name = "Admin"
[storage]
enabled = true
# The maximum file size allowed (e.g. "5MB", "500KB").
file_size_limit = "50MiB"
# Uncomment to configure local storage buckets
# [storage.buckets.images]
# public = false
# file_size_limit = "50MiB"
# allowed_mime_types = ["image/png", "image/jpeg"]
# objects_path = "./images"
# Allow connections via S3 compatible clients
[storage.s3_protocol]
enabled = true
# Image transformation API is available to Supabase Pro plan.
# [storage.image_transformation]
# enabled = true
# Store analytical data in S3 for running ETL jobs over Iceberg Catalog
# This feature is only available on the hosted platform.
[storage.analytics]
enabled = false
max_namespaces = 5
max_tables = 10
max_catalogs = 2
# Analytics Buckets is available to Supabase Pro plan.
# [storage.analytics.buckets.my-warehouse]
# Store vector embeddings in S3 for large and durable datasets
[storage.vector]
enabled = true
max_buckets = 10
max_indexes = 5
# Vector Buckets is available to Supabase Pro plan.
# [storage.vector.buckets.documents-openai]
[auth]
enabled = true
# The base URL of your website. Used as an allow-list for redirects and for constructing URLs used
# in emails.
site_url = "http://127.0.0.1:3000"
# The public URL that Auth serves on. Defaults to the API external URL with `/auth/v1` appended.
# external_url = ""
# A list of *exact* URLs that auth providers are permitted to redirect to post authentication.
additional_redirect_urls = ["https://127.0.0.1:3000"]
# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week).
jwt_expiry = 3600
# JWT issuer URL. If not set, defaults to auth.external_url.
# jwt_issuer = ""
# Path to JWT signing key. DO NOT commit your signing keys file to git.
# signing_keys_path = "./signing_keys.json"
# If disabled, the refresh token will never expire.
enable_refresh_token_rotation = true
# Allows refresh tokens to be reused after expiry, up to the specified interval in seconds.
# Requires enable_refresh_token_rotation = true.
refresh_token_reuse_interval = 10
# Allow/disallow new user signups to your project.
enable_signup = true
# Allow/disallow anonymous sign-ins to your project.
enable_anonymous_sign_ins = false
# Allow/disallow testing manual linking of accounts
enable_manual_linking = false
# Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more.
minimum_password_length = 6
# Passwords that do not meet the following requirements will be rejected as weak. Supported values
# are: `letters_digits`, `lower_upper_letters_digits`, `lower_upper_letters_digits_symbols`
password_requirements = ""
# Configure passkey sign-ins.
# [auth.passkey]
# enabled = false
# Configure WebAuthn relying party settings (required when passkey is enabled).
# [auth.webauthn]
# rp_display_name = "Supabase"
# rp_id = "localhost"
# rp_origins = ["http://127.0.0.1:3000"]
[auth.rate_limit]
# Number of emails that can be sent per hour. Requires auth.email.smtp to be enabled.
email_sent = 2
# Number of SMS messages that can be sent per hour. Requires auth.sms to be enabled.
sms_sent = 30
# Number of anonymous sign-ins that can be made per hour per IP address. Requires enable_anonymous_sign_ins = true.
anonymous_users = 30
# Number of sessions that can be refreshed in a 5 minute interval per IP address.
token_refresh = 150
# Number of sign up and sign-in requests that can be made in a 5 minute interval per IP address (excludes anonymous users).
sign_in_sign_ups = 30
# Number of OTP / Magic link verifications that can be made in a 5 minute interval per IP address.
token_verifications = 30
# Number of Web3 logins that can be made in a 5 minute interval per IP address.
web3 = 30
# Configure one of the supported captcha providers: `hcaptcha`, `turnstile`.
# [auth.captcha]
# enabled = true
# provider = "hcaptcha"
# secret = ""
[auth.email]
# Allow/disallow new user signups via email to your project.
enable_signup = true
# If enabled, a user will be required to confirm any email change on both the old, and new email
# addresses. If disabled, only the new email is required to confirm.
double_confirm_changes = true
# If enabled, users need to confirm their email address before signing in.
enable_confirmations = false
# If enabled, users will need to reauthenticate or have logged in recently to change their password.
secure_password_change = false
# Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.
max_frequency = "1s"
# Number of characters used in the email OTP.
otp_length = 6
# Number of seconds before the email OTP expires (defaults to 1 hour).
otp_expiry = 3600
# Use a production-ready SMTP server
# [auth.email.smtp]
# enabled = true
# host = "smtp.sendgrid.net"
# port = 587
# user = "apikey"
# pass = "env(SENDGRID_API_KEY)"
# admin_email = "admin@email.com"
# sender_name = "Admin"
# Uncomment to customize email template
# [auth.email.template.invite]
# subject = "You have been invited"
# content_path = "./supabase/templates/invite.html"
# Uncomment to customize notification email template
# [auth.email.notification.password_changed]
# enabled = true
# subject = "Your password has been changed"
# content_path = "./templates/password_changed_notification.html"
[auth.sms]
# Allow/disallow new user signups via SMS to your project.
enable_signup = false
# If enabled, users need to confirm their phone number before signing in.
enable_confirmations = false
# Template for sending OTP to users
template = "Your code is {{ `{{ .Code }}` }}"
# Controls the minimum amount of time that must pass before sending another sms otp.
max_frequency = "5s"
# Use pre-defined map of phone number to OTP for testing.
# [auth.sms.test_otp]
# 4152127777 = "123456"
# Configure logged in session timeouts.
# [auth.sessions]
# Force log out after the specified duration.
# timebox = "24h"
# Force log out if the user has been inactive longer than the specified duration.
# inactivity_timeout = "8h"
# This hook runs before a new user is created and allows developers to reject the request based on the incoming user object.
# [auth.hook.before_user_created]
# enabled = true
# uri = "pg-functions://postgres/auth/before-user-created-hook"
# This hook runs before a token is issued and allows you to add additional claims based on the authentication method used.
# [auth.hook.custom_access_token]
# enabled = true
# uri = "pg-functions://<database>/<schema>/<hook_name>"
# Configure one of the supported SMS providers: `twilio`, `twilio_verify`, `messagebird`, `textlocal`, `vonage`.
[auth.sms.twilio]
enabled = false
account_sid = ""
message_service_sid = ""
# DO NOT commit your Twilio auth token to git. Use environment variable substitution instead:
auth_token = "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)"
# Multi-factor-authentication is available to Supabase Pro plan.
[auth.mfa]
# Control how many MFA factors can be enrolled at once per user.
max_enrolled_factors = 10
# Control MFA via App Authenticator (TOTP)
[auth.mfa.totp]
enroll_enabled = false
verify_enabled = false
# Configure MFA via Phone Messaging
[auth.mfa.phone]
enroll_enabled = false
verify_enabled = false
otp_length = 6
template = "Your code is {{ `{{ .Code }}` }}"
max_frequency = "5s"
# Configure MFA via WebAuthn
# [auth.mfa.web_authn]
# enroll_enabled = true
# verify_enabled = true
# Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`,
# `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin_oidc`, `notion`, `twitch`,
# `twitter`, `x`, `slack`, `spotify`, `workos`, `zoom`.
[auth.external.apple]
enabled = false
client_id = ""
# DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead:
secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)"
# Overrides the default auth callback URL derived from auth.external_url.
redirect_uri = ""
# Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure,
# or any other third-party OIDC providers.
url = ""
# If enabled, the nonce check will be skipped. Required for local sign in with Google auth.
skip_nonce_check = false
# If enabled, it will allow the user to successfully authenticate when the provider does not return an email address.
email_optional = false
# Allow Solana wallet holders to sign in to your project via the Sign in with Solana (SIWS, EIP-4361) standard.
# You can configure "web3" rate limit in the [auth.rate_limit] section and set up [auth.captcha] if self-hosting.
[auth.web3.solana]
enabled = false
# Use Firebase Auth as a third-party provider alongside Supabase Auth.
[auth.third_party.firebase]
enabled = false
# project_id = "my-firebase-project"
# Use Auth0 as a third-party provider alongside Supabase Auth.
[auth.third_party.auth0]
enabled = false
# tenant = "my-auth0-tenant"
# tenant_region = "us"
# Use AWS Cognito (Amplify) as a third-party provider alongside Supabase Auth.
[auth.third_party.aws_cognito]
enabled = false
# user_pool_id = "my-user-pool-id"
# user_pool_region = "us-east-1"
# Use Clerk as a third-party provider alongside Supabase Auth.
[auth.third_party.clerk]
enabled = false
# Obtain from https://clerk.com/setup/supabase
# domain = "example.clerk.accounts.dev"
# OAuth server configuration
[auth.oauth_server]
# Enable OAuth server functionality
enabled = false
# Path for OAuth consent flow UI
authorization_url_path = "/oauth/consent"
# Allow dynamic client registration
allow_dynamic_registration = false
[edge_runtime]
enabled = true
# Supported request policies: `oneshot`, `per_worker`.
# `per_worker` (default) — enables hot reload during local development.
# `oneshot` — fallback mode if hot reload causes issues (e.g. in large repos or with symlinks).
policy = "per_worker"
# Port to attach the Chrome inspector for debugging edge functions.
inspector_port = 8083
# The Deno major version to use.
deno_version = 2
# [edge_runtime.secrets]
# secret_key = "env(SECRET_VALUE)"
[analytics]
enabled = true
port = 54327
# Configure one of the supported backends: `postgres`, `bigquery`.
backend = "postgres"
# Experimental features may be deprecated any time
[experimental]
# Configures Postgres storage engine to use OrioleDB (S3)
orioledb_version = ""
# Configures S3 bucket URL, eg. <bucket_name>.s3-<region>.amazonaws.com
s3_host = "env(S3_HOST)"
# Configures S3 bucket region, eg. us-east-1
s3_region = "env(S3_REGION)"
# Configures AWS_ACCESS_KEY_ID for S3 bucket
s3_access_key = "env(S3_ACCESS_KEY)"
# Configures AWS_SECRET_ACCESS_KEY for S3 bucket
s3_secret_key = "env(S3_SECRET_KEY)"
# pg-delta is the schema diff engine for db diff / db pull / db remote commit.
# Set enabled = false to fall back to the legacy migra engine.
[experimental.pgdelta]
enabled = true
# Directory under `supabase/` where declarative files are written.
# declarative_schema_path = "./database"
# JSON string passed through to pg-delta SQL formatting.
# format_options = "{\"keywordCase\":\"upper\",\"indent\":2,\"maxWidth\":80,\"commaStyle\":\"trailing\"}"
@@ -1,19 +0,0 @@
-- supabase/migrations/20260709000001_sites_zones.sql
CREATE TABLE sites (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name TEXT NOT NULL,
address TEXT,
region TEXT,
active BOOLEAN NOT NULL DEFAULT true,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE zones (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
site_id UUID NOT NULL REFERENCES sites(id) ON DELETE CASCADE,
name TEXT NOT NULL,
qr_code_token TEXT NOT NULL UNIQUE DEFAULT gen_random_uuid()::TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX zones_site_id_idx ON zones(site_id);
@@ -1,40 +0,0 @@
-- supabase/migrations/20260709000002_users.sql
CREATE TYPE user_role AS ENUM (
'reporter', 'supervisor', 'hse', 'capa_owner', 'management', 'admin'
);
CREATE TABLE users (
id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
name TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '',
phone TEXT,
role user_role NOT NULL DEFAULT 'reporter',
department TEXT,
site_id UUID REFERENCES sites(id),
active BOOLEAN NOT NULL DEFAULT true,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Auto-create users row when auth user signs up
CREATE OR REPLACE FUNCTION public.handle_new_auth_user()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
INSERT INTO public.users (id, email, name)
VALUES (
NEW.id,
NEW.email,
COALESCE(NEW.raw_user_meta_data->>'full_name', NEW.email)
)
ON CONFLICT (id) DO NOTHING;
RETURN NEW;
END;
$$;
CREATE TRIGGER on_auth_user_created
AFTER INSERT ON auth.users
FOR EACH ROW
EXECUTE FUNCTION public.handle_new_auth_user();
@@ -1,69 +0,0 @@
-- supabase/migrations/20260709000003_incidents.sql
CREATE TYPE incident_type AS ENUM (
'injury', 'near_miss', 'hazard', 'asset_damage', 'environmental', 'security', 'fire'
);
CREATE TYPE incident_status AS ENUM (
'reported', 'triaged', 'investigating', 'capa_pending', 'verification', 'closed'
);
CREATE TYPE medical_status AS ENUM (
'none', 'first_aid', 'medical_treatment', 'lti'
);
CREATE TABLE incidents (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
reference_no TEXT UNIQUE,
incident_type incident_type NOT NULL,
site_id UUID NOT NULL REFERENCES sites(id),
zone_id UUID REFERENCES zones(id),
reported_by UUID NOT NULL REFERENCES users(id),
reported_at TIMESTAMPTZ NOT NULL DEFAULT now(),
description TEXT NOT NULL,
severity SMALLINT CHECK (severity BETWEEN 1 AND 5),
status incident_status NOT NULL DEFAULT 'reported',
injury_involved BOOLEAN NOT NULL DEFAULT false,
asset_involved BOOLEAN NOT NULL DEFAULT false,
medical_status medical_status,
lost_days INT CHECK (lost_days >= 0),
closed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Auto-generate reference_no: SITECODE-YYYYMM-#### (e.g. SCW1-202607-0001)
CREATE OR REPLACE FUNCTION public.generate_incident_reference()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
DECLARE
v_site_code TEXT;
v_month TEXT;
v_seq INT;
BEGIN
SELECT UPPER(REGEXP_REPLACE(SUBSTRING(name, 1, 6), '[^A-Za-z0-9]', '', 'g'))
INTO v_site_code
FROM sites
WHERE id = NEW.site_id;
v_month := TO_CHAR(NEW.reported_at, 'YYYYMM');
SELECT COUNT(*) + 1
INTO v_seq
FROM incidents
WHERE site_id = NEW.site_id
AND TO_CHAR(reported_at, 'YYYYMM') = v_month;
NEW.reference_no := v_site_code || '-' || v_month || '-' || LPAD(v_seq::TEXT, 4, '0');
RETURN NEW;
END;
$$;
CREATE TRIGGER set_incident_reference
BEFORE INSERT ON incidents
FOR EACH ROW
WHEN (NEW.reference_no IS NULL)
EXECUTE FUNCTION public.generate_incident_reference();
CREATE INDEX incidents_site_id_idx ON incidents(site_id);
CREATE INDEX incidents_reported_by_idx ON incidents(reported_by);
CREATE INDEX incidents_status_idx ON incidents(status);
@@ -1,34 +0,0 @@
-- supabase/migrations/20260709000004_evidence_investigations.sql
CREATE TYPE evidence_stage AS ENUM (
'report', 'response', 'investigation', 'capa', 'verification'
);
CREATE TABLE evidence_files (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
incident_id UUID NOT NULL REFERENCES incidents(id) ON DELETE RESTRICT,
stage evidence_stage NOT NULL,
file_url TEXT NOT NULL,
file_type TEXT NOT NULL,
file_hash TEXT NOT NULL, -- immutable after upload (DOSH audit integrity)
uploaded_by UUID NOT NULL REFERENCES users(id),
uploaded_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deleted BOOLEAN NOT NULL DEFAULT false -- NEVER hard-delete; use this flag
);
CREATE TYPE rca_method AS ENUM ('five_why', 'fishbone', 'other');
CREATE TABLE investigations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
incident_id UUID NOT NULL REFERENCES incidents(id) ON DELETE RESTRICT,
investigator_id UUID NOT NULL REFERENCES users(id),
method rca_method NOT NULL DEFAULT 'five_why',
findings_text TEXT,
root_cause_summary TEXT,
alcohol_test_result TEXT,
witness_statement_refs TEXT[],
completed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX evidence_files_incident_idx ON evidence_files(incident_id);
CREATE INDEX investigations_incident_idx ON investigations(incident_id);
@@ -1,43 +0,0 @@
-- supabase/migrations/20260709000005_capa_dosh.sql
CREATE TYPE capa_priority AS ENUM ('low', 'med', 'high');
CREATE TYPE capa_status AS ENUM (
'open', 'in_progress', 'overdue', 'pending_verification',
'verified', 'reopened', 'closed'
);
CREATE TABLE capa_actions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
incident_id UUID NOT NULL REFERENCES incidents(id) ON DELETE RESTRICT,
root_cause_ref TEXT,
description TEXT NOT NULL,
owner_user_id UUID NOT NULL REFERENCES users(id),
department TEXT NOT NULL,
due_date DATE NOT NULL,
priority capa_priority NOT NULL DEFAULT 'med',
status capa_status NOT NULL DEFAULT 'open',
completed_at TIMESTAMPTZ,
verified_by UUID REFERENCES users(id),
verified_at TIMESTAMPTZ,
effectiveness_recheck_date DATE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TYPE dosh_form_type AS ENUM ('jkkp6', 'jkkp7', 'jkkp8');
CREATE TYPE dosh_status AS ENUM ('not_required', 'pending', 'submitted');
CREATE TABLE dosh_reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
incident_id UUID NOT NULL REFERENCES incidents(id) ON DELETE RESTRICT,
form_type dosh_form_type NOT NULL,
status dosh_status NOT NULL DEFAULT 'not_required',
submitted_at TIMESTAMPTZ,
submitted_by UUID REFERENCES users(id),
file_url TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX capa_actions_incident_idx ON capa_actions(incident_id);
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_due_date_idx ON capa_actions(due_date);
@@ -1,26 +0,0 @@
-- supabase/migrations/20260709000006_notifications_audit.sql
CREATE TYPE notification_channel AS ENUM ('email', 'whatsapp', 'in_app');
CREATE TABLE notifications_log (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
incident_id UUID REFERENCES incidents(id),
capa_id UUID REFERENCES capa_actions(id),
channel notification_channel NOT NULL,
recipient TEXT NOT NULL,
sent_at TIMESTAMPTZ NOT NULL DEFAULT now(),
status TEXT NOT NULL DEFAULT 'sent'
);
CREATE TABLE audit_log (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
table_name TEXT NOT NULL,
record_id UUID NOT NULL,
action TEXT NOT NULL,
changed_by UUID REFERENCES users(id),
changed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
old_value JSONB,
new_value JSONB
);
CREATE INDEX audit_log_table_record_idx ON audit_log(table_name, record_id);
CREATE INDEX audit_log_changed_by_idx ON audit_log(changed_by);
@@ -1,99 +0,0 @@
-- supabase/migrations/20260709000007_rls_policies.sql
-- Enable RLS on all application tables
ALTER TABLE sites ENABLE ROW LEVEL SECURITY;
ALTER TABLE zones ENABLE ROW LEVEL SECURITY;
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
ALTER TABLE incidents ENABLE ROW LEVEL SECURITY;
ALTER TABLE evidence_files ENABLE ROW LEVEL SECURITY;
ALTER TABLE investigations ENABLE ROW LEVEL SECURITY;
ALTER TABLE capa_actions ENABLE ROW LEVEL SECURITY;
ALTER TABLE dosh_reports ENABLE ROW LEVEL SECURITY;
ALTER TABLE notifications_log ENABLE ROW LEVEL SECURITY;
ALTER TABLE audit_log ENABLE ROW LEVEL SECURITY;
-- Helper functions (SECURITY DEFINER avoids recursion through RLS)
CREATE OR REPLACE FUNCTION public.auth_user_role()
RETURNS user_role
LANGUAGE sql
SECURITY DEFINER
STABLE
AS $$ SELECT role FROM public.users WHERE id = auth.uid() $$;
CREATE OR REPLACE FUNCTION public.auth_user_site_id()
RETURNS UUID
LANGUAGE sql
SECURITY DEFINER
STABLE
AS $$ SELECT site_id FROM public.users WHERE id = auth.uid() $$;
CREATE OR REPLACE FUNCTION public.auth_user_department()
RETURNS TEXT
LANGUAGE sql
SECURITY DEFINER
STABLE
AS $$ SELECT department FROM public.users WHERE id = auth.uid() $$;
-- sites: everyone reads active sites; only admin manages
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: everyone reads; only admin manages
CREATE POLICY "zones_read" ON zones FOR SELECT USING (true);
CREATE POLICY "zones_admin_all" ON zones FOR ALL USING (auth_user_role() = 'admin');
-- users: own profile always readable; elevated roles see all; admin manages
CREATE POLICY "users_read_own" ON users FOR SELECT USING (id = auth.uid());
CREATE POLICY "users_read_elevated" ON users FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor'));
CREATE POLICY "users_update_own" ON users FOR UPDATE USING (id = auth.uid());
CREATE POLICY "users_admin_all" ON users FOR ALL USING (auth_user_role() = 'admin');
-- incidents: reporter sees own; supervisor sees own site; elevated sees all
CREATE POLICY "incidents_insert" ON incidents FOR INSERT
WITH CHECK (reported_by = auth.uid());
CREATE POLICY "incidents_read_reporter" ON incidents FOR SELECT
USING (reported_by = auth.uid());
CREATE POLICY "incidents_read_supervisor" ON incidents FOR SELECT
USING (auth_user_role() = 'supervisor' 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', 'supervisor'));
-- evidence_files: inserter or incident owner sees own; elevated sees all; no delete
CREATE POLICY "evidence_insert" ON evidence_files FOR INSERT
WITH CHECK (uploaded_by = auth.uid());
CREATE POLICY "evidence_read_uploader" ON evidence_files FOR SELECT
USING (uploaded_by = auth.uid());
CREATE POLICY "evidence_read_elevated" ON evidence_files FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor'));
-- No DELETE policy -- files are never deleted (soft-delete only via `deleted` flag)
-- investigations: hse/admin full access; supervisor read-only
CREATE POLICY "investigations_hse_admin" ON investigations FOR ALL
USING (auth_user_role() IN ('hse', 'admin'));
CREATE POLICY "investigations_read_supervisor" ON investigations FOR SELECT
USING (auth_user_role() = 'supervisor');
-- capa_actions: owner/dept reads and updates own; elevated reads all; hse/admin manages
CREATE POLICY "capa_read_owner" ON capa_actions FOR SELECT
USING (owner_user_id = auth.uid() OR department = auth_user_department());
CREATE POLICY "capa_update_owner" ON capa_actions FOR UPDATE
USING (owner_user_id = auth.uid() OR department = auth_user_department());
CREATE POLICY "capa_read_elevated" ON capa_actions FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor'));
CREATE POLICY "capa_hse_admin_all" ON capa_actions FOR ALL
USING (auth_user_role() IN ('hse', 'admin'));
-- dosh_reports: hse/admin only
CREATE POLICY "dosh_hse_admin" ON dosh_reports FOR ALL
USING (auth_user_role() IN ('hse', 'admin'));
-- notifications_log: hse/admin read
CREATE POLICY "notifications_read_elevated" ON notifications_log FOR SELECT
USING (auth_user_role() IN ('hse', 'admin'));
-- audit_log: hse/admin read only -- no writes from app (writes via SECURITY DEFINER functions)
CREATE POLICY "audit_read_elevated" ON audit_log FOR SELECT
USING (auth_user_role() IN ('hse', 'admin'));
@@ -1,34 +0,0 @@
-- supabase/migrations/20260709000008_seed.sql
-- Test site: Setia Corp Warehouse 1
INSERT INTO sites (id, name, address, region, active)
VALUES (
'00000000-0000-0000-0000-000000000001'::UUID,
'SCW1',
'No. 1, Jalan Industri 1, Shah Alam, Selangor',
'Central',
true
)
ON CONFLICT (id) DO NOTHING;
-- Zones for SCW1
INSERT INTO zones (id, site_id, name, qr_code_token)
VALUES
(
'00000000-0000-0000-0000-000000000010'::UUID,
'00000000-0000-0000-0000-000000000001'::UUID,
'Dock A',
'scw1-dock-a-qr-2026'
),
(
'00000000-0000-0000-0000-000000000011'::UUID,
'00000000-0000-0000-0000-000000000001'::UUID,
'Cold Storage',
'scw1-cold-storage-qr-2026'
),
(
'00000000-0000-0000-0000-000000000012'::UUID,
'00000000-0000-0000-0000-000000000001'::UUID,
'Loading Bay',
'scw1-loading-bay-qr-2026'
)
ON CONFLICT (id) DO NOTHING;
@@ -1,113 +0,0 @@
-- supabase/migrations/20260709000009_security_fixes.sql
-- Security fixes from IMS Phase 0 final code review
-- =============================================================================
-- 1. CRITICAL: Drop and recreate users_update_own with WITH CHECK to prevent
-- role self-escalation (any user setting their own role to admin)
-- =============================================================================
DROP POLICY IF EXISTS "users_update_own" ON users;
CREATE POLICY "users_update_own" ON users
FOR UPDATE
USING (id = auth.uid())
WITH CHECK (
id = auth.uid()
AND role = (SELECT role FROM public.users WHERE id = auth.uid())
);
-- =============================================================================
-- 2. IMPORTANT: SECURITY DEFINER audit writer function — app code calls this
-- instead of direct INSERT on audit_log
-- =============================================================================
CREATE OR REPLACE FUNCTION public.write_audit_log(
p_table_name TEXT,
p_record_id UUID,
p_action TEXT,
p_old_value JSONB DEFAULT NULL,
p_new_value JSONB DEFAULT NULL
)
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
INSERT INTO public.audit_log (table_name, record_id, action, changed_by, old_value, new_value)
VALUES (p_table_name, p_record_id, p_action, auth.uid(), p_old_value, p_new_value);
END;
$$;
-- =============================================================================
-- 3. IMPORTANT: notifications_log INSERT policy for elevated roles
-- =============================================================================
CREATE POLICY "notifications_insert_elevated" ON notifications_log
FOR INSERT
WITH CHECK (auth_user_role() IN ('hse', 'admin', 'supervisor'));
-- =============================================================================
-- 4. IMPORTANT: Recreate generate_incident_reference trigger function with
-- SECURITY DEFINER and SET search_path to prevent search_path injection
-- =============================================================================
CREATE OR REPLACE FUNCTION public.generate_incident_reference()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_site_code TEXT;
v_month TEXT;
v_seq INT;
BEGIN
SELECT UPPER(REGEXP_REPLACE(SUBSTRING(name, 1, 6), '[^A-Za-z0-9]', '', 'g'))
INTO v_site_code
FROM sites
WHERE id = NEW.site_id;
v_month := TO_CHAR(NEW.reported_at, 'YYYYMM');
SELECT COUNT(*) + 1
INTO v_seq
FROM incidents
WHERE site_id = NEW.site_id
AND TO_CHAR(reported_at, 'YYYYMM') = v_month;
NEW.reference_no := COALESCE(v_site_code, 'UNK') || '-' || v_month || '-' || LPAD(v_seq::TEXT, 4, '0');
RETURN NEW;
END;
$$;
-- =============================================================================
-- 5. IMPORTANT: Recreate helper functions with SET search_path to prevent
-- search_path hijacking attacks
-- =============================================================================
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 = auth.uid() $$;
CREATE OR REPLACE FUNCTION public.auth_user_site_id()
RETURNS UUID
LANGUAGE sql
SECURITY DEFINER
STABLE
SET search_path = public
AS $$ SELECT site_id FROM public.users WHERE id = auth.uid() $$;
CREATE OR REPLACE FUNCTION public.auth_user_department()
RETURNS TEXT
LANGUAGE sql
SECURITY DEFINER
STABLE
SET search_path = public
AS $$ SELECT department FROM public.users WHERE id = auth.uid() $$;
-- =============================================================================
-- 6. IMPORTANT: Add UNIQUE constraint to dosh_reports to prevent duplicate
-- form submissions for the same incident
-- =============================================================================
ALTER TABLE dosh_reports
ADD CONSTRAINT dosh_reports_incident_form_uq UNIQUE (incident_id, form_type);
@@ -1,37 +0,0 @@
-- Create evidence storage bucket (private)
INSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
VALUES (
'evidence',
'evidence',
false,
209715200, -- 200MB
ARRAY[
'image/jpeg', 'image/png', 'image/heic', 'image/webp',
'video/mp4', 'video/quicktime',
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
]
)
ON CONFLICT (id) DO NOTHING;
-- RLS on storage.objects for the evidence bucket
CREATE POLICY "evidence_upload_authenticated"
ON storage.objects FOR INSERT
TO authenticated
WITH CHECK (bucket_id = 'evidence');
CREATE POLICY "evidence_read_uploader"
ON storage.objects FOR SELECT
TO authenticated
USING (
bucket_id = 'evidence'
AND auth.uid()::text = (storage.foldername(name))[1]
);
CREATE POLICY "evidence_read_elevated"
ON storage.objects FOR SELECT
TO authenticated
USING (
bucket_id = 'evidence'
AND public.auth_user_role() IN ('hse', 'admin', 'management', 'supervisor')
);
@@ -1,33 +0,0 @@
-- Triage classification fields on incidents
ALTER TABLE incidents
ADD COLUMN IF NOT EXISTS is_fatality BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN IF NOT EXISTS is_serious_bodily_injury BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN IF NOT EXISTS is_dangerous_occurrence BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN IF NOT EXISTS is_occupational_disease BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN IF NOT EXISTS triage_notes TEXT,
ADD COLUMN IF NOT EXISTS triaged_by UUID REFERENCES users(id),
ADD COLUMN IF NOT EXISTS triaged_at TIMESTAMPTZ;
-- Structured RCA data on investigations
ALTER TABLE investigations
ADD COLUMN IF NOT EXISTS five_why_steps JSONB,
ADD COLUMN IF NOT EXISTS fishbone_categories JSONB;
-- Audit log write helper — SECURITY DEFINER so callers cannot bypass RLS
DROP FUNCTION IF EXISTS public.write_audit_log CASCADE;
CREATE OR REPLACE FUNCTION public.write_audit_log(
p_table_name TEXT,
p_record_id UUID,
p_action TEXT,
p_new_value JSONB DEFAULT NULL,
p_old_value JSONB DEFAULT NULL
)
RETURNS VOID
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
BEGIN
INSERT INTO audit_log (table_name, record_id, action, changed_by, new_value, old_value)
VALUES (p_table_name, p_record_id, p_action, auth.uid(), p_new_value, p_old_value);
END;
$$;
@@ -1,42 +0,0 @@
-- Enable pgvector
create extension if not exists vector;
-- Add embedding column to incidents (nullable — populated async after creation)
alter table incidents
add column if not exists embedding vector(1024);
-- IVFFlat index for cosine similarity (10 lists sufficient for <10k rows)
create index if not exists incidents_embedding_idx
on incidents using ivfflat (embedding vector_cosine_ops)
with (lists = 10);
-- Similarity search — returns top-N most similar incidents (cosine)
create or replace function match_incidents(
query_embedding vector(1024),
exclude_id uuid,
match_count int default 5
)
returns table (
id uuid,
reference_no text,
incident_type text,
description text,
severity int,
similarity float
)
language sql
security definer
as $$
select
i.id,
i.reference_no,
i.incident_type,
i.description,
i.severity,
1 - (i.embedding <=> query_embedding) as similarity
from incidents i
where i.id != exclude_id
and i.embedding is not null
order by i.embedding <=> query_embedding
limit match_count;
$$;
@@ -1,43 +0,0 @@
-- Add authorization guard to match_incidents to enforce DB-level access control.
-- Without this, SECURITY DEFINER bypasses RLS for any direct caller.
create or replace function match_incidents(
query_embedding vector(1024),
exclude_id uuid,
match_count int default 5
)
returns table (
id uuid,
reference_no text,
incident_type text,
description text,
severity int,
similarity float
)
language plpgsql
security definer
as $$
begin
-- Enforce that only hse/admin roles can call this function directly
if not exists (
select 1 from public.users
where id = auth.uid()
and role in ('hse', 'admin')
) then
raise exception 'Forbidden' using errcode = 'PGRST301';
end if;
return query
select
i.id,
i.reference_no,
i.incident_type,
i.description,
i.severity,
1 - (i.embedding <=> query_embedding) as similarity
from incidents i
where i.id != exclude_id
and i.embedding is not null
order by i.embedding <=> query_embedding
limit match_count;
end;
$$;
@@ -1,25 +0,0 @@
create table if not exists app_settings (
key text primary key,
value text not null,
updated_at timestamptz not null default now(),
updated_by uuid references users(id)
);
-- Only admins can read or write settings
alter table app_settings enable row level security;
create policy "admin_select_settings" on app_settings
for select using (
exists (select 1 from users where id = auth.uid() and role = 'admin')
);
create policy "admin_update_settings" on app_settings
for all using (
exists (select 1 from users where id = auth.uid() and role = 'admin')
);
-- Placeholder rows (empty value means "use env var")
insert into app_settings (key, value) values
('ANTHROPIC_API_KEY', ''),
('VOYAGE_API_KEY', '')
on conflict (key) do nothing;
@@ -1,10 +0,0 @@
-- Add effectiveness recheck round tracking to capa_actions
ALTER TABLE capa_actions
ADD COLUMN IF NOT EXISTS effectiveness_recheck_round INT NOT NULL DEFAULT 0;
-- WhatsApp credentials for Settings UI
INSERT INTO app_settings (key, value, updated_at, updated_by)
VALUES
('META_WHATSAPP_PHONE_NUMBER_ID', '', now(), NULL),
('META_WHATSAPP_ACCESS_TOKEN', '', now(), NULL)
ON CONFLICT (key) DO NOTHING;
@@ -1,50 +0,0 @@
-- supabase/migrations/20260712000016_in_app_notifications.sql
-- Phase 5: in-app notification bell — read state, content columns, per-user RLS,
-- and a SECURITY DEFINER writer so non-elevated reporters can trigger alerts.
ALTER TABLE notifications_log
ADD COLUMN recipient_user_id UUID REFERENCES users(id),
ADD COLUMN read_at TIMESTAMPTZ,
ADD COLUMN title TEXT,
ADD COLUMN link TEXT;
CREATE INDEX notifications_in_app_unread_idx
ON notifications_log (recipient_user_id, sent_at DESC)
WHERE channel = 'in_app' AND read_at IS NULL;
-- Users see their own in-app notifications (elevated read policy already exists)
CREATE POLICY "notifications_read_own" ON notifications_log
FOR SELECT
USING (recipient_user_id = auth.uid());
-- Users may only mark their own notifications read
CREATE POLICY "notifications_update_own" ON notifications_log
FOR UPDATE
USING (recipient_user_id = auth.uid())
WITH CHECK (recipient_user_id = auth.uid());
-- Writer RPC: INSERT policy on notifications_log is elevated-roles-only, but a
-- reporter submitting an incident must notify supervisors/HSE. Mirrors write_audit_log.
CREATE OR REPLACE FUNCTION public.create_in_app_notification(
p_recipient UUID,
p_title TEXT,
p_link TEXT DEFAULT NULL,
p_incident_id UUID DEFAULT NULL,
p_capa_id UUID DEFAULT NULL
)
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
IF auth.uid() IS NULL THEN
RAISE EXCEPTION 'authentication required';
END IF;
INSERT INTO public.notifications_log
(channel, recipient, recipient_user_id, title, link, incident_id, capa_id)
VALUES
('in_app', p_recipient::text, p_recipient, p_title, p_link, p_incident_id, p_capa_id);
END;
$$;
@@ -1,57 +0,0 @@
-- supabase/migrations/20260712000017_closure_lock_addenda.sql
-- Phase 5: closed incidents become immutable (addenda-only), per PRD §4 Phase 4.
CREATE TABLE incident_addenda (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
incident_id UUID NOT NULL REFERENCES incidents(id),
author UUID NOT NULL REFERENCES users(id),
body TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX incident_addenda_incident_idx ON incident_addenda(incident_id);
ALTER TABLE incident_addenda ENABLE ROW LEVEL SECURITY;
CREATE POLICY "addenda_read" ON incident_addenda
FOR SELECT
USING (
auth_user_role() IN ('hse', 'admin', 'supervisor', 'management')
OR EXISTS (
SELECT 1 FROM incidents i
WHERE i.id = incident_id AND i.reported_by = auth.uid()
)
);
CREATE POLICY "addenda_insert" ON incident_addenda
FOR INSERT
WITH CHECK (
author = auth.uid()
AND auth_user_role() IN ('hse', 'admin', 'supervisor')
);
-- No UPDATE/DELETE policies: addenda are append-only.
-- DB-level lock: once closed, the incident row cannot change or be deleted.
CREATE OR REPLACE FUNCTION public.prevent_closed_incident_change()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
RAISE EXCEPTION 'incident % is closed and locked — add an addendum instead', OLD.id;
END;
$$;
CREATE TRIGGER incidents_closed_lock_update
BEFORE UPDATE ON incidents
FOR EACH ROW
WHEN (OLD.status = 'closed')
EXECUTE FUNCTION prevent_closed_incident_change();
CREATE TRIGGER incidents_closed_lock_delete
BEFORE DELETE ON incidents
FOR EACH ROW
WHEN (OLD.status = 'closed')
EXECUTE FUNCTION prevent_closed_incident_change();
@@ -1,5 +0,0 @@
-- supabase/migrations/20260712000018_type_details.sql
-- Phase 5: type-specific intake fields (PRD §3 — each incident type has its own
-- lightweight form). Stored as validated JSONB; keys whitelisted in app code.
ALTER TABLE incidents ADD COLUMN type_details JSONB;
@@ -1,12 +0,0 @@
-- Fix: notifications_log RLS was allowing any hse/admin to read ALL notifications.
-- Replace with per-user policy (everyone reads own) + admin-only policy for oversight.
DROP POLICY IF EXISTS "notifications_read_elevated" ON notifications_log;
DROP POLICY IF EXISTS "notifications_read_own" ON notifications_log;
DROP POLICY IF EXISTS "notifications_read_admin" ON notifications_log;
CREATE POLICY "notifications_read_own" ON notifications_log
FOR SELECT USING (recipient_user_id = auth.uid());
CREATE POLICY "notifications_read_admin" ON notifications_log
FOR SELECT USING (auth_user_role() = 'admin');
@@ -1,4 +0,0 @@
-- Add DEEPSEEK_API_KEY placeholder to app_settings
insert into app_settings (key, value) values
('DEEPSEEK_API_KEY', '')
on conflict (key) do nothing;
@@ -1,49 +0,0 @@
-- Migrate embeddings from Voyage AI (1024-dim) to Gemini text-embedding-004 (768-dim)
-- Drop dependent objects first
drop index if exists incidents_embedding_idx;
drop function if exists match_incidents;
-- Replace column (dimension change requires drop+add)
alter table incidents drop column if exists embedding;
alter table incidents add column embedding vector(768);
-- Recreate index
create index incidents_embedding_idx
on incidents using ivfflat (embedding vector_cosine_ops)
with (lists = 10);
-- Recreate similarity function at 768-dim
create or replace function match_incidents(
query_embedding vector(768),
exclude_id uuid,
match_count int default 5
)
returns table (
id uuid,
reference_no text,
incident_type text,
description text,
severity int,
similarity float
)
language sql
security definer
as $$
select
i.id,
i.reference_no,
i.incident_type,
i.description,
i.severity,
1 - (i.embedding <=> query_embedding) as similarity
from incidents i
where i.id != exclude_id
and i.embedding is not null
order by i.embedding <=> query_embedding
limit match_count;
$$;
-- Register Gemini key slot, remove Voyage slot
insert into app_settings (key, value) values ('GOOGLE_AI_API_KEY', '') on conflict (key) do nothing;
delete from app_settings where key = 'VOYAGE_API_KEY';
@@ -1,23 +0,0 @@
-- Reconcile app_settings after provider switches:
-- DeepSeek key was saved under ANTHROPIC_API_KEY slot (before rename) — recover it.
-- Remove retired ANTHROPIC_API_KEY and VOYAGE_API_KEY slots.
-- Ensure DeepSeek slot exists
insert into app_settings (key, value) values ('DEEPSEEK_API_KEY', '')
on conflict (key) do nothing;
-- Copy orphaned value: ANTHROPIC_API_KEY → DEEPSEEK_API_KEY (only when DEEPSEEK_API_KEY is empty and ANTHROPIC has a value)
update app_settings dk
set value = ak.value, updated_at = now()
from app_settings ak
where dk.key = 'DEEPSEEK_API_KEY'
and ak.key = 'ANTHROPIC_API_KEY'
and coalesce(dk.value, '') = ''
and coalesce(ak.value, '') <> '';
-- Ensure Gemini slot exists
insert into app_settings (key, value) values ('GOOGLE_AI_API_KEY', '')
on conflict (key) do nothing;
-- Remove retired provider slots
delete from app_settings where key in ('ANTHROPIC_API_KEY', 'VOYAGE_API_KEY');
@@ -1,3 +0,0 @@
-- Add 'transport' to the incident_type enum. Isolated so the new value is
-- committed before any later migration references it.
ALTER TYPE incident_type ADD VALUE IF NOT EXISTS 'transport';

Some files were not shown because too many files have changed in this diff Show More