9 Commits
Author SHA1 Message Date
admin a1f5f3126a Merge pull request 'chore(release): 2.0.0, merge roles into SSA' (#3) from chore/release-2.0.0 into main
Reviewed-on: #3
2026-11-06 22:16:39 +08:00
adminandClaude Sonnet 5.5 2fed177fdc chore(release): 2.0.0, merge roles into SSA
Bump version to 2.0.0 (breaking: reporter, supervisor and capa_owner merged
into ssa, routes moved under /ssa). Add 2.0.0 release notes to docs/CHANGELOG.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 22:16:01 +08:00
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
71 changed files with 339 additions and 1742 deletions
+4 -5
View File
@@ -19,7 +19,8 @@ Replaces WhatsApp/Excel safety reporting. Client: Ms. Agnes, Mr. Terence, Mr. Ya
## Current Phase ## Current Phase
**All phases (0–6) complete as of 2026-07-12.** Supabase to local PostgreSQL migration completed and live 2026-09-30. **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). **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. See `[[phases]]` memory for full phase breakdown and deliverables.
## Deployment (Production) ## Deployment (Production)
@@ -62,10 +63,8 @@ IMS/
│ ├── auth/ # bcryptjs passwords, jose sessions, roles │ ├── auth/ # bcryptjs passwords, jose sessions, roles
│ ├── storage/ # evidence files on disk + signed URLs │ ├── storage/ # evidence files on disk + signed URLs
│ ├── claude/ # AI client (DeepSeek) + Google embeddings │ ├── claude/ # AI client (DeepSeek) + Google embeddings
│ ├── notifications/ # Brevo email + WhatsApp senders, in-app │ └── notifications/ # Brevo email + WhatsApp senders, in-app
│ └── supabase/ # LEGACY, unused, to be removed
├── db/ # schema.sql, rls.sql, migration/ops scripts ├── db/ # schema.sql, rls.sql, migration/ops scripts
├── supabase/ # LEGACY migrations, to be removed
└── public/ └── 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. - Radius comes from the scale: `rounded-md` (8) buttons, chips, inputs, pills; `rounded-xl` (12) cards and mobile controls; `rounded-[5px]` checkbox. Headings and labels are flush left.
- Status and priority colours only via `StatusTag` / `PriorityTag` (design.md §4.2): dark text on a light tint, text label always present, no icon required. Add new statuses in `components/ui/status-tag.tsx`, not per page. - Status and priority colours only via `StatusTag` / `PriorityTag` (design.md §4.2): dark text on a light tint, text label always present, no icon required. Add new statuses in `components/ui/status-tag.tsx`, not per page.
- Every list is a `TableCard` (design.md §4.9): saved views, toolbar, sortable header, row hover quick actions, selected tint, footer pager, floating bulk bar, empty state, mobile stacked variant. Do not hand-build tables. - Every list is a `TableCard` (design.md §4.9): saved views, toolbar, sortable header, row hover quick actions, selected tint, footer pager, floating bulk bar, empty state, mobile stacked variant. Do not hand-build tables.
- Build UI with `components/ui/*`: `Button`, `StatusTag`, `PriorityTag`, `Checkbox`, `Field`/`Input`/`Select`/`Textarea`, `FilterChip`, `Segmented`, `Avatar`, `Card`, `Drawer`, `TableCard`; pages sit in `AppShell` (desktop) or `MobileShell` (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. - Icons: Lucide (`lucide-react`), 16px stroke 2 in UI, 12px stroke 2.5 inside chips and checks, 22px stroke 1.8 in the mobile tab bar.
- Interaction: hover/active values per component in design.md §4; `:focus-visible` 2px accent ring is global; transitions 120ms on bg/shadow only; mobile hit targets ≥ 44px. - Interaction: hover/active values per component in design.md §4; `:focus-visible` 2px accent ring is global; transitions 120ms on bg/shadow only; mobile hit targets ≥ 44px.
- Incident evidence photos stay full colour. - Incident evidence photos stay full colour.
+6 -14
View File
@@ -3,22 +3,14 @@ import { describe, it, expect } from 'vitest'
import { getRoleHome, ROLE_HOME, ALL_ROLES } from '@/lib/auth/roles' import { getRoleHome, ROLE_HOME, ALL_ROLES } from '@/lib/auth/roles'
describe('getRoleHome', () => { describe('getRoleHome', () => {
it('returns /reporter for reporter role', () => { it('returns /ssa for ssa role', () => {
expect(getRoleHome('reporter')).toBe('/reporter') expect(getRoleHome('ssa')).toBe('/ssa')
})
it('returns /supervisor for supervisor role', () => {
expect(getRoleHome('supervisor')).toBe('/supervisor')
}) })
it('returns /hse for hse role', () => { it('returns /hse for hse role', () => {
expect(getRoleHome('hse')).toBe('/hse') expect(getRoleHome('hse')).toBe('/hse')
}) })
it('returns /capa-owner for capa_owner role', () => {
expect(getRoleHome('capa_owner')).toBe('/capa-owner')
})
it('returns /management for management role', () => { it('returns /management for management role', () => {
expect(getRoleHome('management')).toBe('/management') expect(getRoleHome('management')).toBe('/management')
}) })
@@ -27,11 +19,11 @@ describe('getRoleHome', () => {
expect(getRoleHome('admin')).toBe('/admin') expect(getRoleHome('admin')).toBe('/admin')
}) })
it('ROLE_HOME covers exactly 6 roles', () => { it('ROLE_HOME covers exactly 4 roles', () => {
expect(Object.keys(ROLE_HOME)).toHaveLength(6) expect(Object.keys(ROLE_HOME)).toHaveLength(4)
}) })
it('ALL_ROLES lists exactly 6 roles', () => { it('ALL_ROLES lists exactly 4 roles', () => {
expect(ALL_ROLES).toHaveLength(6) expect(ALL_ROLES).toHaveLength(4)
}) })
}) })
@@ -21,10 +21,10 @@ const STATUS_LABELS: Record<string, string> = {
closed: 'Closed', closed: 'Closed',
} }
export default async function CapaOwnerPage() { export default async function MyCapasPage() {
const session = await getSession() const session = await getSession()
if (!session) redirect('/login') 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 => const rows = await asAdmin(db =>
db.select({ db.select({
@@ -14,7 +14,7 @@ interface Props {
params: Promise<{ id: string }> params: Promise<{ id: string }>
} }
export default async function SupervisorIncidentDetailPage({ params }: Props) { export default async function SsaIncidentDetailPage({ params }: Props) {
const { id } = await params const { id } = await params
const session = await getSession() const session = await getSession()
@@ -136,7 +136,7 @@ export default async function SupervisorIncidentDetailPage({ params }: Props) {
return ( return (
<main className="max-w-3xl mx-auto px-4 py-6"> <main className="max-w-3xl mx-auto px-4 py-6">
<Link href="/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 ← Back to inbox
</Link> </Link>
<IncidentDetail incident={incidentProp} /> <IncidentDetail incident={incidentProp} />
@@ -8,7 +8,7 @@ import { IncidentTable } from '@/components/incidents/incident-table'
import { loadIncidentList } from '@/lib/incidents/list-query' import { loadIncidentList } from '@/lib/incidents/list-query'
import { parseListParams } from '@/lib/incidents/list-params' import { parseListParams } from '@/lib/incidents/list-params'
export default async function SupervisorInboxPage({ export default async function SsaInboxPage({
searchParams, searchParams,
}: { }: {
searchParams: Promise<Record<string, string | undefined>> searchParams: Promise<Record<string, string | undefined>>
@@ -27,7 +27,7 @@ export default async function SupervisorInboxPage({
</div> </div>
<IncidentTable <IncidentTable
incidents={data.incidents} incidents={data.incidents}
basePath="/supervisor" basePath="/ssa"
total={data.total} total={data.total}
counts={data.counts} counts={data.counts}
params={params} params={params}
@@ -12,7 +12,7 @@ const STATUS_LABELS: Record<string, string> = {
reported: 'Reported', triaged: 'Triaged', investigating: 'Investigating', reported: 'Reported', triaged: 'Triaged', investigating: 'Investigating',
capa_pending: 'CAPA Pending', verification: 'Verification', closed: 'Closed', capa_pending: 'CAPA Pending', verification: 'Verification', closed: 'Closed',
} }
export default async function ReporterIncidentDetail({ export default async function MyReportDetail({
params, params,
}: { }: {
params: Promise<{ id: string }> params: Promise<{ id: string }>
@@ -60,7 +60,7 @@ export default async function ReporterIncidentDetail({
return ( return (
<main className="max-w-2xl mx-auto px-4 py-6 space-y-4"> <main className="max-w-2xl mx-auto px-4 py-6 space-y-4">
<div className="flex items-center gap-2 mb-2"> <div className="flex items-center gap-2 mb-2">
<Link href="/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>
<div className="bg-surface shadow-sm p-5"> <div className="bg-surface shadow-sm p-5">
@@ -22,7 +22,7 @@ const TYPE_LABELS: Record<string, string> = {
asset_damage: 'Asset Damage', environmental: 'Environmental', security: 'Security', fire: 'Fire', asset_damage: 'Asset Damage', environmental: 'Environmental', security: 'Security', fire: 'Fire',
} }
export default async function ReporterPage() { export default async function MyReportsPage() {
const session = await getSession() const session = await getSession()
if (!session) redirect('/login') if (!session) redirect('/login')
@@ -83,7 +83,7 @@ export default async function ReporterPage() {
) : ( ) : (
<div className="bg-surface shadow-sm divide-y divide-gray-50"> <div className="bg-surface shadow-sm divide-y divide-gray-50">
{rows.map(inc => ( {rows.map(inc => (
<Link key={inc.id} href={`/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 items-start justify-between gap-3">
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<p className="text-sm font-semibold text-gray-900"> <p className="text-sm font-semibold text-gray-900">
@@ -19,15 +19,15 @@ const STATUS_LABELS: Record<string, string> = {
closed: 'Closed', closed: 'Closed',
} }
export default async function SupervisorPage() { export default async function SsaPage() {
const session = await getSession() const session = await getSession()
if (!session) redirect('/login') if (!session) redirect('/login')
if (!['supervisor', 'admin'].includes(session.role)) redirect('/') if (!['ssa', 'admin'].includes(session.role)) redirect('/')
if (!session.siteId) { if (!session.siteId) {
return ( return (
<main className="max-w-4xl mx-auto px-4 py-6"> <main className="max-w-4xl mx-auto px-4 py-6">
<h1 className="text-2xl font-bold text-gray-900 mb-4">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> <p className="text-sm text-gray-500">No site assigned — contact your administrator.</p>
</main> </main>
) )
@@ -108,10 +108,10 @@ export default async function SupervisorPage() {
<main className="max-w-4xl mx-auto px-4 py-6"> <main className="max-w-4xl mx-auto px-4 py-6">
<div className="flex items-center justify-between mb-6"> <div className="flex items-center justify-between mb-6">
<div> <div>
<h1 className="text-2xl font-bold text-gray-900">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> <p className="text-sm text-gray-500 mt-1">{siteName}</p>
</div> </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 → All incidents →
</Link> </Link>
</div> </div>
@@ -134,7 +134,7 @@ export default async function SupervisorPage() {
{openIncidents.map(inc => ( {openIncidents.map(inc => (
<Link <Link
key={inc.id} 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" className="flex items-center justify-between py-2 border-b border-gray-50 last:border-0 hover:bg-gray-50 -mx-2 px-2"
> >
<div> <div>
+2 -2
View File
@@ -69,7 +69,7 @@ export async function POST(request: NextRequest) {
name: body.name ?? '', name: body.name ?? '',
email, email,
phone: (body.phone ?? '').trim() || null, phone: (body.phone ?? '').trim() || null,
role: (body.role as typeof users.$inferInsert['role']) ?? 'reporter', role: (body.role as typeof users.$inferInsert['role']) ?? 'ssa',
siteId: body.site_id ?? null, siteId: body.site_id ?? null,
department: body.department ?? null, department: body.department ?? null,
passwordHash, passwordHash,
@@ -78,7 +78,7 @@ export async function POST(request: NextRequest) {
if (!created) throw new Error('User creation failed') if (!created) throw new Error('User creation failed')
createdId = created.id createdId = created.id
await writeAuditLog(tx, 'users', created.id, 'created', { await writeAuditLog(tx, 'users', created.id, 'created', {
email, role: body.role ?? 'reporter', site_id: body.site_id ?? null, email, role: body.role ?? 'ssa', site_id: body.site_id ?? null,
}) })
}) })
}) })
+1 -1
View File
@@ -50,7 +50,7 @@ export async function GET(
const role = session.role const role = session.role
const isOwner = row.ownerUserId === session.sub const isOwner = row.ownerUserId === session.sub
const canRead = ['hse', 'admin', 'supervisor'].includes(role) || isOwner const canRead = ['hse', 'admin', 'ssa'].includes(role) || isOwner
if (!canRead) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) if (!canRead) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const ownerField = ['hse', 'admin'].includes(role) const ownerField = ['hse', 'admin'].includes(role)
+1 -1
View File
@@ -40,7 +40,7 @@ export async function GET() {
.leftJoin(incidents, eq(capaActions.incidentId, incidents.id)) .leftJoin(incidents, eq(capaActions.incidentId, incidents.id))
.orderBy(asc(capaActions.dueDate)) .orderBy(asc(capaActions.dueDate))
if (session.role === 'supervisor' || session.role === 'worker') { if (session.role === 'ssa') {
q = q.where(eq(capaActions.ownerUserId, session.sub)) as typeof q q = q.where(eq(capaActions.ownerUserId, session.sub)) as typeof q
} }
+2 -2
View File
@@ -15,7 +15,7 @@ export async function GET(
const { id } = await params const { id } = await params
const session = await getSession() const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin', 'supervisor'].includes(session.role)) if (!['hse', 'admin', 'ssa'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const authorAlias = aliasedTable(users, 'author_user') const authorAlias = aliasedTable(users, 'author_user')
@@ -45,7 +45,7 @@ export async function POST(
const { id } = await params const { id } = await params
const session = await getSession() const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin', 'supervisor'].includes(session.role)) if (!['hse', 'admin', 'ssa'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const body: { body?: string } = await request.json().catch(() => ({})) const body: { body?: string } = await request.json().catch(() => ({}))
+1 -1
View File
@@ -51,7 +51,7 @@ export async function POST(
await createInAppNotifications([{ await createInAppNotifications([{
userId: incident.reportedBy, userId: incident.reportedBy,
title: `Your incident report ${incident.referenceNo ?? ''} has been closed`, title: `Your incident report ${incident.referenceNo ?? ''} has been closed`,
link: '/reporter', link: '/ssa/my-reports',
incidentId: id, incidentId: id,
}]) }])
} }
+1 -1
View File
@@ -46,7 +46,7 @@ export async function GET(_req: Request, { params }: { params: Promise<{ id: str
if (!incident) return NextResponse.json({ error: 'Not found' }, { status: 404 }) if (!incident) return NextResponse.json({ error: 'Not found' }, { status: 404 })
const isOwner = incident.reporterId === session.sub const isOwner = incident.reporterId === session.sub
const isSiteStaff = ['hse', 'supervisor', 'admin'].includes(session.role) const isSiteStaff = ['hse', 'ssa', 'admin'].includes(session.role)
if (!isOwner && !isSiteStaff) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) if (!isOwner && !isSiteStaff) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const evidenceFileRows = await withUser(session.sub, async tx => const evidenceFileRows = await withUser(session.sub, async tx =>
+1 -1
View File
@@ -188,7 +188,7 @@ async function handlePost(request: Request) {
db.select({ id: users.id, phone: users.phone }) db.select({ id: users.id, phone: users.phone })
.from(users) .from(users)
.where(and( .where(and(
inArray(users.role, ['supervisor', 'hse']), inArray(users.role, ['ssa', 'hse']),
eq(users.siteId, zone.siteId), eq(users.siteId, zone.siteId),
)) ))
) )
+1 -1
View File
@@ -19,7 +19,7 @@ export default async function ReportSuccessPage({ searchParams }: Props) {
</p> </p>
)} )}
<p className="text-sm text-gray-500 mb-6"> <p className="text-sm text-gray-500 mb-6">
The supervisor and HSE officer have been notified. The Site Safety Assistants and HSE officer have been notified.
</p> </p>
<Link href="/report" className="text-sm text-accent-700 hover:underline"> <Link href="/report" className="text-sm text-accent-700 hover:underline">
Submit another report Submit another report
+4 -4
View File
@@ -2,7 +2,7 @@
import { useState } from 'react' import { useState } from 'react'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { ALL_ROLES, type UserRole } from '@/lib/auth/roles' import { ALL_ROLES, ROLE_LABELS, type UserRole } from '@/lib/auth/roles'
import { Modal } from '@/components/ui/modal' import { Modal } from '@/components/ui/modal'
import { INPUT_CLASS as inp } from '@/components/ui/field' import { INPUT_CLASS as inp } from '@/components/ui/field'
@@ -23,7 +23,7 @@ interface Props {
sites: SiteOption[] sites: SiteOption[]
} }
const EMPTY = { email: '', name: '', phone: '', role: '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' const lbl = 'block text-xs font-medium text-gray-600 mb-1'
@@ -135,7 +135,7 @@ export function UserManager({ users, sites }: Props) {
<select value={u.role} disabled={busyId === u.id} <select value={u.role} disabled={busyId === u.id}
onChange={e => patchUser(u.id, { role: e.target.value })} onChange={e => patchUser(u.id, { role: e.target.value })}
className="border border-divider px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-accent cursor-pointer"> className="border border-divider px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-accent cursor-pointer">
{ALL_ROLES.map(r => <option key={r} value={r}>{r.replace(/_/g, ' ')}</option>)} {ALL_ROLES.map(r => <option key={r} value={r}>{ROLE_LABELS[r]}</option>)}
</select> </select>
</td> </td>
<td className="px-5 py-3"> <td className="px-5 py-3">
@@ -224,7 +224,7 @@ export function UserManager({ users, sites }: Props) {
<select id="au-role" value={form.role} <select id="au-role" value={form.role}
onChange={e => setForm(v => ({ ...v, role: e.target.value as UserRole }))} onChange={e => setForm(v => ({ ...v, role: e.target.value as UserRole }))}
className={inp}> className={inp}>
{ALL_ROLES.map(r => <option key={r} value={r}>{r.replace(/_/g, ' ')}</option>)} {ALL_ROLES.map(r => <option key={r} value={r}>{ROLE_LABELS[r]}</option>)}
</select> </select>
</div> </div>
<div> <div>
+1 -1
View File
@@ -123,7 +123,7 @@ export function AppShell({
<LogOut size={16} strokeWidth={2} className="text-ink-3" aria-hidden /> <LogOut size={16} strokeWidth={2} className="text-ink-3" aria-hidden />
Log out Log out
</button> </button>
<p className="px-2.5 pt-2 text-xs text-faint">v1.2.2</p> <p className="px-2.5 pt-2 text-xs text-faint">v2.0.0</p>
</div> </div>
</aside> </aside>
+8 -10
View File
@@ -16,14 +16,13 @@ export interface NavItem {
} }
const NAV_ITEMS: Record<string, NavItem[]> = { const NAV_ITEMS: Record<string, NavItem[]> = {
reporter: [ ssa: [
{ label: 'My Reports', href: '/reporter', icon: ClipboardList }, { 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 }, { label: 'New Incident', href: '/report', icon: Plus },
], ],
supervisor: [
{ label: 'Overview', href: '/supervisor', icon: AlignLeft },
{ label: 'Incidents', href: '/supervisor/incidents', icon: ClipboardList },
],
hse: [ hse: [
{ label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard }, { label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard },
{ label: 'Incidents', href: '/hse/incidents', icon: ClipboardList }, { label: 'Incidents', href: '/hse/incidents', icon: ClipboardList },
@@ -31,7 +30,6 @@ const NAV_ITEMS: Record<string, NavItem[]> = {
{ label: 'Settings', href: '/hse/settings', icon: Settings }, { label: 'Settings', href: '/hse/settings', icon: Settings },
], ],
management: [{ label: 'Dashboard', href: '/management', icon: LayoutDashboard }], management: [{ label: 'Dashboard', href: '/management', icon: LayoutDashboard }],
capa_owner: [{ label: 'My CAPAs', href: '/capa-owner', icon: CircleCheck }],
admin: [ admin: [
{ label: 'Admin', href: '/admin', icon: Users }, { label: 'Admin', href: '/admin', icon: Users },
{ label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard }, { label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard },
@@ -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[] { 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 { 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 { export function searchHrefFor(role: string): string | null {
if (role === 'hse' || role === 'admin') return '/hse/incidents' if (role === 'hse' || role === 'admin') return '/hse/incidents'
if (role === 'supervisor') return '/supervisor/incidents' if (role === 'ssa') return '/ssa/incidents'
return null return null
} }
+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)
-- ============================================================================
+11 -11
View File
@@ -56,7 +56,7 @@ CREATE POLICY "trucks_admin_all" ON trucks FOR ALL USING (auth_user_role() =
-- users -- users
CREATE POLICY "users_read_own" ON users FOR SELECT USING (id = app_current_user_id()); CREATE POLICY "users_read_own" ON users FOR SELECT USING (id = app_current_user_id());
CREATE POLICY "users_read_elevated" ON users FOR SELECT CREATE POLICY "users_read_elevated" ON users FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor')); USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa'));
CREATE POLICY "users_update_own" ON users FOR UPDATE CREATE POLICY "users_update_own" ON users FOR UPDATE
USING (id = app_current_user_id()) USING (id = app_current_user_id())
WITH CHECK ( WITH CHECK (
@@ -70,12 +70,12 @@ CREATE POLICY "incidents_insert" ON incidents FOR INSERT
WITH CHECK (reported_by = app_current_user_id()); WITH CHECK (reported_by = app_current_user_id());
CREATE POLICY "incidents_read_reporter" ON incidents FOR SELECT CREATE POLICY "incidents_read_reporter" ON incidents FOR SELECT
USING (reported_by = app_current_user_id()); USING (reported_by = app_current_user_id());
CREATE POLICY "incidents_read_supervisor" ON incidents FOR SELECT CREATE POLICY "incidents_read_ssa" ON incidents FOR SELECT
USING (auth_user_role() = 'supervisor' AND site_id = auth_user_site_id()); USING (auth_user_role() = 'ssa' AND site_id = auth_user_site_id());
CREATE POLICY "incidents_read_elevated" ON incidents FOR SELECT CREATE POLICY "incidents_read_elevated" ON incidents FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management')); USING (auth_user_role() IN ('hse', 'admin', 'management'));
CREATE POLICY "incidents_update_elevated" ON incidents FOR UPDATE CREATE POLICY "incidents_update_elevated" ON incidents FOR UPDATE
USING (auth_user_role() IN ('hse', 'admin', 'supervisor')); USING (auth_user_role() IN ('hse', 'admin', 'ssa'));
-- evidence_files -- evidence_files
CREATE POLICY "evidence_insert" ON evidence_files FOR INSERT CREATE POLICY "evidence_insert" ON evidence_files FOR INSERT
@@ -83,14 +83,14 @@ CREATE POLICY "evidence_insert" ON evidence_files FOR INSERT
CREATE POLICY "evidence_read_uploader" ON evidence_files FOR SELECT CREATE POLICY "evidence_read_uploader" ON evidence_files FOR SELECT
USING (uploaded_by = app_current_user_id()); USING (uploaded_by = app_current_user_id());
CREATE POLICY "evidence_read_elevated" ON evidence_files FOR SELECT CREATE POLICY "evidence_read_elevated" ON evidence_files FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor')); USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa'));
-- No DELETE policy: files are never deleted (soft-delete only via `deleted` flag) -- No DELETE policy: files are never deleted (soft-delete only via `deleted` flag)
-- investigations -- investigations
CREATE POLICY "investigations_hse_admin" ON investigations FOR ALL CREATE POLICY "investigations_hse_admin" ON investigations FOR ALL
USING (auth_user_role() IN ('hse', 'admin')); USING (auth_user_role() IN ('hse', 'admin'));
CREATE POLICY "investigations_read_supervisor" ON investigations FOR SELECT CREATE POLICY "investigations_read_ssa" ON investigations FOR SELECT
USING (auth_user_role() = 'supervisor'); USING (auth_user_role() = 'ssa');
-- capa_actions (capa_update_owner is tightened — no department clause) -- capa_actions (capa_update_owner is tightened — no department clause)
CREATE POLICY "capa_read_owner" ON capa_actions FOR SELECT CREATE POLICY "capa_read_owner" ON capa_actions FOR SELECT
@@ -98,7 +98,7 @@ CREATE POLICY "capa_read_owner" ON capa_actions FOR SELECT
CREATE POLICY "capa_update_owner" ON capa_actions FOR UPDATE CREATE POLICY "capa_update_owner" ON capa_actions FOR UPDATE
USING (owner_user_id = app_current_user_id()); USING (owner_user_id = app_current_user_id());
CREATE POLICY "capa_read_elevated" ON capa_actions FOR SELECT CREATE POLICY "capa_read_elevated" ON capa_actions FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor')); USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa'));
CREATE POLICY "capa_hse_admin_all" ON capa_actions FOR ALL CREATE POLICY "capa_hse_admin_all" ON capa_actions FOR ALL
USING (auth_user_role() IN ('hse', 'admin')); USING (auth_user_role() IN ('hse', 'admin'));
@@ -108,7 +108,7 @@ CREATE POLICY "dosh_hse_admin" ON dosh_reports FOR ALL
-- notifications_log (final state after migration 19 fix) -- notifications_log (final state after migration 19 fix)
CREATE POLICY "notifications_insert_elevated" ON notifications_log FOR INSERT CREATE POLICY "notifications_insert_elevated" ON notifications_log FOR INSERT
WITH CHECK (auth_user_role() IN ('hse', 'admin', 'supervisor')); WITH CHECK (auth_user_role() IN ('hse', 'admin', 'ssa'));
CREATE POLICY "notifications_read_own" ON notifications_log FOR SELECT CREATE POLICY "notifications_read_own" ON notifications_log FOR SELECT
USING (recipient_user_id = app_current_user_id()); USING (recipient_user_id = app_current_user_id());
CREATE POLICY "notifications_read_admin" ON notifications_log FOR SELECT CREATE POLICY "notifications_read_admin" ON notifications_log FOR SELECT
@@ -130,7 +130,7 @@ CREATE POLICY "admin_update_settings" ON app_settings FOR ALL
-- incident_addenda -- incident_addenda
CREATE POLICY "addenda_read" ON incident_addenda FOR SELECT CREATE POLICY "addenda_read" ON incident_addenda FOR SELECT
USING ( USING (
auth_user_role() IN ('hse', 'admin', 'supervisor', 'management') auth_user_role() IN ('hse', 'admin', 'ssa', 'management')
OR EXISTS ( OR EXISTS (
SELECT 1 FROM incidents i SELECT 1 FROM incidents i
WHERE i.id = incident_id AND i.reported_by = app_current_user_id() WHERE i.id = incident_id AND i.reported_by = app_current_user_id()
@@ -139,5 +139,5 @@ CREATE POLICY "addenda_read" ON incident_addenda FOR SELECT
CREATE POLICY "addenda_insert" ON incident_addenda FOR INSERT CREATE POLICY "addenda_insert" ON incident_addenda FOR INSERT
WITH CHECK ( WITH CHECK (
author = app_current_user_id() author = app_current_user_id()
AND auth_user_role() IN ('hse', 'admin', 'supervisor') AND auth_user_role() IN ('hse', 'admin', 'ssa')
); );
+2 -2
View File
@@ -16,7 +16,7 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Enums -- Enums
-- --------------------------------------------------------------------------- -- ---------------------------------------------------------------------------
CREATE TYPE user_role AS ENUM ( CREATE TYPE user_role AS ENUM (
'reporter', 'supervisor', 'hse', 'capa_owner', 'management', 'admin' 'ssa', 'hse', 'management', 'admin'
); );
CREATE TYPE incident_type AS ENUM ( CREATE TYPE incident_type AS ENUM (
@@ -80,7 +80,7 @@ CREATE TABLE users (
name TEXT NOT NULL DEFAULT '', name TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '' UNIQUE, email TEXT NOT NULL DEFAULT '' UNIQUE,
phone TEXT, phone TEXT,
role user_role NOT NULL DEFAULT 'reporter', role user_role NOT NULL DEFAULT 'ssa',
department TEXT, department TEXT,
site_id UUID REFERENCES sites(id), site_id UUID REFERENCES sites(id),
active BOOLEAN NOT NULL DEFAULT true, active BOOLEAN NOT NULL DEFAULT true,
+74
View File
@@ -21,6 +21,80 @@ _Nothing yet._
--- ---
## [2.0.0] - 2026-11-06
**Breaking:** the Reporter, Supervisor and CAPA Owner roles are merged into one
role, **Site Safety Assistant (SSA)**. Existing sessions carry the old role, so
those users must log out and in again after the deploy.
### Changed
- **Roles — `reporter`, `supervisor` and `capa_owner` become `ssa`.**
The role set is now `ssa`, `hse`, `management`, `admin`.
- SSA sees incidents for their own site and their own reports, can update
incidents, and works their assigned CAPAs.
- Role checks in the API, the nav, notifications (e.g. new-incident and CAPA
escalation emails) and the user manager now use `ssa`.
- Unknown roles fall back to the SSA navigation.
- **Pages moved under `/ssa`:** `/reporter` → `/ssa/my-reports`,
`/supervisor` → `/ssa`, `/supervisor/incidents` → `/ssa/incidents`,
`/capa-owner` → `/ssa/capas`. The header search for SSA targets `/ssa/incidents`.
### Removed
- Legacy Supabase code and dependencies: `lib/supabase/*`, `@supabase/ssr`,
`@supabase/supabase-js` and the `supabase/` migrations folder. The app already
ran on local PostgreSQL; `db/schema.sql` and `db/rls.sql` are the schema source
of truth.
### Affected modules
Auth and roles (`lib/auth/roles.ts`), navigation and shell (`components/layout/*`),
SSA pages (`app/(protected)/ssa/*`), incident, CAPA and addenda API routes,
admin user manager, email and CAPA-escalation notifications, RLS policies.
### Database migrations
- **`db/ops/2026-11-06-merge-roles-into-ssa.sql`**, applied by hand to production
on 2026-11-06 as the `postgres` superuser (the app DB user cannot bypass RLS).
One transaction: converts `reporter`/`supervisor`/`capa_owner` users to `ssa`,
recreates the `user_role` enum as `ssa, hse, management, admin`, recreates
`auth_user_role()`, then drops and re-creates all 34 RLS policies.
Take a `pg_dump` first. Users with the old role in their session cookie must log
out and in again.
- No migration is needed for the Supabase removal.
### API changes
- No endpoint was added or removed. The role value in the session and in
`/api/admin/users` is now `ssa` instead of `reporter`, `supervisor` or
`capa_owner`. Creating or updating a user with any role outside the four new
ones returns `422 Invalid role`; the default role for a new user is `ssa`.
- Page routes changed as listed under **Changed**.
### Testing
1. Log in as an `ssa` user. Check `/ssa`, `/ssa/my-reports`, `/ssa/incidents`
(site incidents only) and `/ssa/capas`.
2. Submit a new incident at `/report` and confirm it shows under **My Reports**.
3. Open an assigned CAPA and submit proof (note and photos).
4. As `hse` and `admin`, confirm dashboards, incident lists and the user manager
still work, and that the user manager offers only the four new roles.
5. Run `npm run test` and `npm run build`. Seven tests fail on `main` as well
(AI routes, bulk-import, email); no new failures were introduced.
6. In Postgres: `SELECT DISTINCT role FROM users;` returns only
`ssa`, `hse`, `management`, `admin`.
### Also in this version since 1.2.2 (summarised from git history)
- IMS Admin UI refresh: new tokens, Geist, `TableCard`, new shells; Incidents and
CAPA lists migrated.
- CAPA owners submit proof with a note and photos; HSE sees a photo gallery.
- Trucks are linked to a site; the report form lists all trucks.
- AI provider switched to a local model.
---
## [1.1.0] - 2026-07-16 ## [1.1.0] - 2026-07-16
### Fixed ### Fixed
+11 -9
View File
@@ -1,26 +1,28 @@
// lib/auth/roles.ts // lib/auth/roles.ts
// 'ssa' = Site Safety Assistant. Replaces the former reporter, supervisor and capa_owner roles.
export type UserRole = export type UserRole =
| 'reporter' | 'ssa'
| 'supervisor'
| 'hse' | 'hse'
| 'capa_owner'
| 'management' | 'management'
| 'admin' | 'admin'
export const ALL_ROLES: UserRole[] = [ export const ALL_ROLES: UserRole[] = [
'reporter', 'ssa',
'supervisor',
'hse', 'hse',
'capa_owner',
'management', 'management',
'admin', 'admin',
] ]
export const ROLE_LABELS: Record<UserRole, string> = {
ssa: 'Site Safety Assistant (SSA)',
hse: 'HSE',
management: 'Management',
admin: 'Admin',
}
export const ROLE_HOME: Record<UserRole, string> = { export const ROLE_HOME: Record<UserRole, string> = {
reporter: '/reporter', ssa: '/ssa',
supervisor: '/supervisor',
hse: '/hse', hse: '/hse',
capa_owner: '/capa-owner',
management: '/management', management: '/management',
admin: '/admin', admin: '/admin',
} }
+2 -2
View File
@@ -26,7 +26,7 @@ const vector = customType<{ data: number[]; driverData: string }>({
// Enums // Enums
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
export const userRoleEnum = pgEnum('user_role', [ export const userRoleEnum = pgEnum('user_role', [
'reporter', 'supervisor', 'hse', 'capa_owner', 'management', 'admin', 'ssa', 'hse', 'management', 'admin',
]) ])
export const incidentTypeEnum = pgEnum('incident_type', [ export const incidentTypeEnum = pgEnum('incident_type', [
@@ -89,7 +89,7 @@ export const users = pgTable('users', {
name: text('name').notNull().default(''), name: text('name').notNull().default(''),
email: text('email').notNull().default('').unique(), email: text('email').notNull().default('').unique(),
phone: text('phone'), phone: text('phone'),
role: userRoleEnum('role').notNull().default('reporter'), role: userRoleEnum('role').notNull().default('ssa'),
department: text('department'), department: text('department'),
siteId: uuid('site_id').references(() => sites.id), siteId: uuid('site_id').references(() => sites.id),
active: boolean('active').notNull().default(true), active: boolean('active').notNull().default(true),
+1 -1
View File
@@ -97,7 +97,7 @@ export async function escalateOverdueCapa(): Promise<{ notified: number }> {
.from(users) .from(users)
.where(and( .where(and(
eq(users.siteId, capa.siteId!), eq(users.siteId, capa.siteId!),
inArray(users.role, ['hse', 'supervisor', 'management']), inArray(users.role, ['hse', 'ssa', 'management']),
)) ))
) )
to.push(...hseUsers.map(u => u.email).filter(Boolean) as string[]) to.push(...hseUsers.map(u => u.email).filter(Boolean) as string[])
+1 -1
View File
@@ -15,7 +15,7 @@ export async function sendNewIncidentEmail(
db.select({ email: users.email }) db.select({ email: users.email })
.from(users) .from(users)
.where(and( .where(and(
inArray(users.role, ['supervisor', 'hse']), inArray(users.role, ['ssa', 'hse']),
eq(users.siteId, siteId), eq(users.siteId, siteId),
)) ))
) )
-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('')
}
+2 -122
View File
@@ -1,16 +1,14 @@
{ {
"name": "ims-app", "name": "ims-app",
"version": "1.2.2", "version": "2.0.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ims-app", "name": "ims-app",
"version": "1.2.2", "version": "2.0.0",
"dependencies": { "dependencies": {
"@anthropic-ai/sdk": "^0.111.0", "@anthropic-ai/sdk": "^0.111.0",
"@supabase/ssr": "^0.12.0",
"@supabase/supabase-js": "^2.110.2",
"bcryptjs": "^3.0.3", "bcryptjs": "^3.0.3",
"drizzle-orm": "^0.45.2", "drizzle-orm": "^0.45.2",
"file-type": "^22.0.1", "file-type": "^22.0.1",
@@ -2639,102 +2637,6 @@
"dev": true, "dev": true,
"license": "MIT" "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": { "node_modules/@swc/helpers": {
"version": "0.5.23", "version": "0.5.23",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz", "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz",
@@ -4629,19 +4531,6 @@
"dev": true, "dev": true,
"license": "MIT" "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": { "node_modules/cross-spawn": {
"version": "7.0.6", "version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "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": "^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": { "node_modules/idb": {
"version": "8.0.3", "version": "8.0.3",
"resolved": "https://registry.npmjs.org/idb/-/idb-8.0.3.tgz", "resolved": "https://registry.npmjs.org/idb/-/idb-8.0.3.tgz",
+1 -3
View File
@@ -1,6 +1,6 @@
{ {
"name": "ims-app", "name": "ims-app",
"version": "1.2.2", "version": "2.0.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",
@@ -14,8 +14,6 @@
}, },
"dependencies": { "dependencies": {
"@anthropic-ai/sdk": "^0.111.0", "@anthropic-ai/sdk": "^0.111.0",
"@supabase/ssr": "^0.12.0",
"@supabase/supabase-js": "^2.110.2",
"bcryptjs": "^3.0.3", "bcryptjs": "^3.0.3",
"drizzle-orm": "^0.45.2", "drizzle-orm": "^0.45.2",
"file-type": "^22.0.1", "file-type": "^22.0.1",
-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';
@@ -1,14 +0,0 @@
CREATE TABLE trucks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
truck_no TEXT NOT NULL UNIQUE,
carrier TEXT,
active BOOLEAN NOT NULL DEFAULT true,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
ALTER TABLE incidents ADD COLUMN truck_id UUID REFERENCES trucks(id);
CREATE INDEX incidents_truck_id_idx ON incidents(truck_id);
ALTER TABLE trucks ENABLE ROW LEVEL SECURITY;
CREATE POLICY "trucks_read" ON trucks FOR SELECT USING (true);
CREATE POLICY "trucks_admin_all" ON trucks FOR ALL USING (auth_user_role() = 'admin');
@@ -1,4 +0,0 @@
-- Add soft-delete support to zones (sites and trucks already have this column).
-- Leave zones_read as USING (true) so deactivated zones still render on historical incidents.
-- Deactivation is enforced for new reports in the create-incident API, not via RLS.
ALTER TABLE zones ADD COLUMN active BOOLEAN NOT NULL DEFAULT true;
@@ -1,3 +0,0 @@
ALTER TABLE investigations
ADD COLUMN IF NOT EXISTS urine_test_result text
CHECK (urine_test_result IN ('negative','positive','refused','pending'));
@@ -1 +0,0 @@
ALTER TABLE capa_actions ADD COLUMN owner_notes TEXT;
@@ -1,6 +0,0 @@
-- Tighten capa_update_owner RLS policy: remove department clause so only the
-- assigned owner can UPDATE their own CAPA row directly. Route-level auth
-- enforces field-level restrictions; this ensures DB-level enforcement matches.
DROP POLICY IF EXISTS "capa_update_owner" ON capa_actions;
CREATE POLICY "capa_update_owner" ON capa_actions FOR UPDATE
USING (owner_user_id = auth.uid());
@@ -1,14 +0,0 @@
CREATE TABLE password_reset_tokens (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
used_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX password_reset_tokens_user_idx ON password_reset_tokens(user_id);
CREATE INDEX password_reset_tokens_hash_idx ON password_reset_tokens(token_hash);
-- password_reset_tokens: accessed via app_admin only (BYPASSRLS); no user-facing policies needed
-- GRANT already covered by: GRANT ALL ON ALL TABLES IN SCHEMA public TO app_admin
+1 -1
View File
@@ -2,7 +2,7 @@
import { describe, it, expect, vi } from 'vitest' import { describe, it, expect, vi } from 'vitest'
vi.mock('@/lib/auth/get-session', () => ({ vi.mock('@/lib/auth/get-session', () => ({
getSession: async () => ({ sub: 'owner-1', role: 'capa_owner' }), getSession: async () => ({ sub: 'owner-1', role: 'ssa' }),
})) }))
vi.mock('@/lib/db/audit', () => ({ writeAuditLog: vi.fn() })) vi.mock('@/lib/db/audit', () => ({ writeAuditLog: vi.fn() }))
vi.mock('@/lib/db/with-user', () => ({ vi.mock('@/lib/db/with-user', () => ({
+2 -2
View File
@@ -38,7 +38,7 @@ function req(note: string | null, fileCount: number) {
const ctx = { params: Promise.resolve({ id: 'capa-1' }) } const ctx = { params: Promise.resolve({ id: 'capa-1' }) }
beforeEach(() => { beforeEach(() => {
h.session = { sub: 'owner-1', role: 'capa_owner' } h.session = { sub: 'owner-1', role: 'ssa' }
h.capa = { incidentId: 'inc-1', ownerUserId: 'owner-1', status: 'in_progress' } h.capa = { incidentId: 'inc-1', ownerUserId: 'owner-1', status: 'in_progress' }
h.updates = [] h.updates = []
h.inserts = [] h.inserts = []
@@ -56,7 +56,7 @@ describe('POST /api/capa/[id]/submit', () => {
expect((await POST(req('done', 1) as never, ctx)).status).toBe(404) expect((await POST(req('done', 1) as never, ctx)).status).toBe(404)
}) })
it('403 for a user who is neither owner nor hse/admin', async () => { it('403 for a user who is neither owner nor hse/admin', async () => {
h.session = { sub: 'other', role: 'reporter' } h.session = { sub: 'other', role: 'ssa' }
expect((await POST(req('done', 1) as never, ctx)).status).toBe(403) expect((await POST(req('done', 1) as never, ctx)).status).toBe(403)
}) })
it('409 when status is not in_progress', async () => { it('409 when status is not in_progress', async () => {
+1 -1
View File
@@ -64,7 +64,7 @@ describe('GET /api/incidents/[id]/report-pdf', () => {
}) })
it('returns 403 for non-hse/admin roles', async () => { it('returns 403 for non-hse/admin roles', async () => {
vi.mocked(getSession).mockResolvedValue({ ...mockSession, role: 'reporter' as never }) vi.mocked(getSession).mockResolvedValue({ ...mockSession, role: 'ssa' as never })
const res = await GET(makeRequest('inc-1'), { params: Promise.resolve({ id: 'inc-1' }) }) const res = await GET(makeRequest('inc-1'), { params: Promise.resolve({ id: 'inc-1' }) })
expect(res.status).toBe(403) expect(res.status).toBe(403)
}) })
+7 -2
View File
@@ -49,15 +49,20 @@ describe('AppShell', () => {
expect(document.activeElement?.getAttribute('name')).toBe('q') expect(document.activeElement?.getAttribute('name')).toBe('q')
}) })
it('targets the site incident list for the SSA role', () => {
const { container } = render(<AppShell role="ssa" userName="Ada"><span /></AppShell>)
expect(container.querySelector('header form')!.getAttribute('action')).toBe('/ssa/incidents')
})
it('hides the search box for roles without an incident list', () => { it('hides the search box for roles without an incident list', () => {
const { container } = render(<AppShell role="reporter" userName="Ada"><span /></AppShell>) const { container } = render(<AppShell role="management" userName="Ada"><span /></AppShell>)
expect(container.querySelector('header form')).toBeNull() expect(container.querySelector('header form')).toBeNull()
}) })
it('shows the user chip, version label, and logs out', async () => { it('shows the user chip, version label, and logs out', async () => {
render(<AppShell role="hse" userName="Ada Lovelace"><span /></AppShell>) render(<AppShell role="hse" userName="Ada Lovelace"><span /></AppShell>)
expect(screen.getAllByText('AL').length).toBeGreaterThan(0) expect(screen.getAllByText('AL').length).toBeGreaterThan(0)
expect(screen.getByText('v1.2.2')).toBeTruthy() expect(screen.getByText('v2.0.0')).toBeTruthy()
fireEvent.click(screen.getAllByRole('button', { name: /Log ?out/i })[0]) fireEvent.click(screen.getAllByRole('button', { name: /Log ?out/i })[0])
await Promise.resolve() await Promise.resolve()
expect(fetch).toHaveBeenCalledWith('/api/auth/logout', { method: 'POST' }) expect(fetch).toHaveBeenCalledWith('/api/auth/logout', { method: 'POST' })
+5 -7
View File
@@ -2,23 +2,21 @@ import { describe, it, expect } from 'vitest'
import { navItemsFor, isActivePath, searchHrefFor } from '@/components/layout/nav-items' import { navItemsFor, isActivePath, searchHrefFor } from '@/components/layout/nav-items'
describe('nav items', () => { describe('nav items', () => {
it('returns the role menu and falls back to reporter', () => { it('returns the role menu and falls back to ssa', () => {
expect(navItemsFor('hse').map(i => i.label)).toEqual(['Dashboard', 'Incidents', 'CAPA', 'Settings']) expect(navItemsFor('hse').map(i => i.label)).toEqual(['Dashboard', 'Incidents', 'CAPA', 'Settings'])
expect(navItemsFor('admin')[0].label).toBe('Admin') expect(navItemsFor('admin')[0].label).toBe('Admin')
expect(navItemsFor('nobody')).toEqual(navItemsFor('reporter')) expect(navItemsFor('nobody')).toEqual(navItemsFor('ssa'))
}) })
it('matches root pages exactly and nested pages by prefix', () => { it('matches root pages exactly and nested pages by prefix', () => {
expect(isActivePath('/reporter', '/reporter')).toBe(true) expect(isActivePath('/ssa', '/ssa')).toBe(true)
expect(isActivePath('/reporter', '/reporter/incidents/1')).toBe(false) expect(isActivePath('/ssa', '/ssa/incidents/1')).toBe(false)
expect(isActivePath('/hse/incidents', '/hse/incidents/abc')).toBe(true) expect(isActivePath('/hse/incidents', '/hse/incidents/abc')).toBe(true)
}) })
it('offers the search box only to roles that have an incident list', () => { it('offers the search box only to roles that have an incident list', () => {
expect(searchHrefFor('hse')).toBe('/hse/incidents') expect(searchHrefFor('hse')).toBe('/hse/incidents')
expect(searchHrefFor('admin')).toBe('/hse/incidents') expect(searchHrefFor('admin')).toBe('/hse/incidents')
expect(searchHrefFor('supervisor')).toBe('/supervisor/incidents') expect(searchHrefFor('ssa')).toBe('/ssa/incidents')
expect(searchHrefFor('reporter')).toBeNull()
expect(searchHrefFor('capa_owner')).toBeNull()
}) })
}) })
+3 -3
View File
@@ -14,7 +14,7 @@ vi.mock('resend', () => {
// Mock asAdmin: first call returns recipients, second returns incident+join rows // Mock asAdmin: first call returns recipients, second returns incident+join rows
let asAdminCallCount = 0 let asAdminCallCount = 0
const mockRecipients = [ const mockRecipients = [
{ email: 'supervisor@setiacorp.com' }, { email: 'ssa@setiacorp.com' },
{ email: 'hse@setiacorp.com' }, { email: 'hse@setiacorp.com' },
] ]
const mockIncidentRows = [{ const mockIncidentRows = [{
@@ -44,11 +44,11 @@ beforeEach(() => {
}) })
describe('sendNewIncidentEmail', () => { describe('sendNewIncidentEmail', () => {
it('sends email to supervisor and hse users', async () => { it('sends email to ssa and hse users', async () => {
await sendNewIncidentEmail('inc-001', 'site-001', 'SCW1-202607-0001', 'near_miss') await sendNewIncidentEmail('inc-001', 'site-001', 'SCW1-202607-0001', 'near_miss')
expect(mockSend).toHaveBeenCalledTimes(1) expect(mockSend).toHaveBeenCalledTimes(1)
const call = mockSend.mock.calls[0][0] const call = mockSend.mock.calls[0][0]
expect(call.to).toEqual(expect.arrayContaining(['supervisor@setiacorp.com', 'hse@setiacorp.com'])) expect(call.to).toEqual(expect.arrayContaining(['ssa@setiacorp.com', 'hse@setiacorp.com']))
expect(call.subject).toContain('SCW1-202607-0001') expect(call.subject).toContain('SCW1-202607-0001')
}) })
-59
View File
@@ -1,59 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { uploadEvidenceFile, getEvidenceUrl } from '@/lib/supabase/storage'
vi.mock('file-type', () => ({
fileTypeFromBuffer: vi.fn().mockResolvedValue({ mime: 'image/jpeg', ext: 'jpg' }),
}))
const mockUpload = vi.fn()
const mockCreateSignedUrl = vi.fn()
const mockSupabase = {
storage: {
from: vi.fn(() => ({
upload: mockUpload,
createSignedUrl: mockCreateSignedUrl,
})),
},
} as any
beforeEach(() => {
vi.clearAllMocks()
mockUpload.mockResolvedValue({ data: { path: 'user-123/incident-abc/report/photo.jpg' }, error: null })
mockCreateSignedUrl.mockResolvedValue({ data: { signedUrl: 'https://example.com/photo.jpg' }, error: null })
})
describe('uploadEvidenceFile', () => {
it('uploads to path user-id/incident-id/stage/filename', async () => {
const file = new File(['content'], 'photo.jpg', { type: 'image/jpeg' })
const result = await uploadEvidenceFile(mockSupabase, file, 'incident-abc', 'report', 'user-123')
expect(mockSupabase.storage.from).toHaveBeenCalledWith('evidence')
expect(mockUpload).toHaveBeenCalledWith(
expect.stringContaining('user-123/incident-abc/report/'),
expect.any(ArrayBuffer),
expect.objectContaining({ contentType: 'image/jpeg', upsert: false })
)
expect(mockCreateSignedUrl).toHaveBeenCalledWith(expect.stringContaining('user-123/incident-abc/report/'), 315360000)
expect(result.path).toContain('user-123/incident-abc/report/')
expect(result.hash).toBeTruthy()
})
it('throws on upload error', async () => {
mockUpload.mockResolvedValue({ data: null, error: { message: 'Bucket not found' } })
const file = new File(['x'], 'f.jpg', { type: 'image/jpeg' })
await expect(uploadEvidenceFile(mockSupabase, file, 'inc', 'report', 'user-123')).rejects.toThrow('Bucket not found')
})
it('throws when photo exceeds 10MB', async () => {
const bigFile = new File([new Uint8Array(11 * 1024 * 1024)], 'big.jpg', { type: 'image/jpeg' })
await expect(uploadEvidenceFile(mockSupabase, bigFile, 'inc', 'report', 'user-123')).rejects.toThrow('File too large')
})
})
describe('getEvidenceUrl', () => {
it('returns signed URL for path', async () => {
const url = await getEvidenceUrl(mockSupabase, 'user-123/incident-abc/report/photo.jpg')
expect(mockSupabase.storage.from).toHaveBeenCalledWith('evidence')
expect(mockCreateSignedUrl).toHaveBeenCalledWith('user-123/incident-abc/report/photo.jpg', 3600)
expect(url).toBe('https://example.com/photo.jpg')
})
})