From 813395700f17670ceeba4424a79790c191ebc47d Mon Sep 17 00:00:00 2001 From: Weei Han Date: Fri, 6 Nov 2026 21:34:10 +0800 Subject: [PATCH 1/3] 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 --- CLAUDE.md | 2 +- __tests__/lib/auth/roles.test.ts | 20 +++------- .../{capa-owner => ssa/capas}/page.tsx | 4 +- .../incidents/[id]/page.tsx | 4 +- .../{supervisor => ssa}/incidents/page.tsx | 4 +- .../my-reports}/[id]/page.tsx | 4 +- .../{reporter => ssa/my-reports}/page.tsx | 4 +- app/(protected)/{supervisor => ssa}/page.tsx | 12 +++--- app/api/admin/users/route.ts | 4 +- app/api/capa/[id]/route.ts | 2 +- app/api/capa/route.ts | 2 +- app/api/incidents/[id]/addenda/route.ts | 4 +- app/api/incidents/[id]/close/route.ts | 2 +- app/api/incidents/[id]/route.ts | 2 +- app/api/incidents/route.ts | 2 +- app/report/success/page.tsx | 2 +- components/admin/user-manager.tsx | 8 ++-- components/layout/nav-items.ts | 18 ++++----- db/ops/2026-11-06-merge-roles-into-ssa.sql | 37 +++++++++++++++++++ db/rls.sql | 22 +++++------ db/schema.sql | 4 +- lib/auth/roles.ts | 20 +++++----- lib/db/schema.ts | 4 +- lib/notifications/capa-escalation.ts | 2 +- lib/notifications/email.ts | 2 +- tests/api/capa-patch.test.ts | 2 +- tests/api/capa-submit.test.ts | 4 +- tests/app/api/incidents/report-pdf.test.ts | 2 +- tests/components/layout/app-shell.test.tsx | 2 +- tests/components/layout/nav-items.test.ts | 12 +++--- tests/lib/notifications/email.test.ts | 6 +-- 31 files changed, 123 insertions(+), 96 deletions(-) rename app/(protected)/{capa-owner => ssa/capas}/page.tsx (97%) rename app/(protected)/{supervisor => ssa}/incidents/[id]/page.tsx (96%) rename app/(protected)/{supervisor => ssa}/incidents/page.tsx (93%) rename app/(protected)/{reporter/incidents => ssa/my-reports}/[id]/page.tsx (96%) rename app/(protected)/{reporter => ssa/my-reports}/page.tsx (95%) rename app/(protected)/{supervisor => ssa}/page.tsx (93%) create mode 100644 db/ops/2026-11-06-merge-roles-into-ssa.sql diff --git a/CLAUDE.md b/CLAUDE.md index ee005cc..90d18af 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -85,7 +85,7 @@ Source of truth: `design-system/design.md`. Visual references: `design-system/IM - Radius comes from the scale: `rounded-md` (8) buttons, chips, inputs, pills; `rounded-xl` (12) cards and mobile controls; `rounded-[5px]` checkbox. Headings and labels are flush left. - Status and priority colours only via `StatusTag` / `PriorityTag` (design.md §4.2): dark text on a light tint, text label always present, no icon required. Add new statuses in `components/ui/status-tag.tsx`, not per page. - Every list is a `TableCard` (design.md §4.9): saved views, toolbar, sortable header, row hover quick actions, selected tint, footer pager, floating bulk bar, empty state, mobile stacked variant. Do not hand-build tables. -- Build UI with `components/ui/*`: `Button`, `StatusTag`, `PriorityTag`, `Checkbox`, `Field`/`Input`/`Select`/`Textarea`, `FilterChip`, `Segmented`, `Avatar`, `Card`, `Drawer`, `TableCard`; pages sit in `AppShell` (desktop) or `MobileShell` (reporter / CAPA owner). +- Build UI with `components/ui/*`: `Button`, `StatusTag`, `PriorityTag`, `Checkbox`, `Field`/`Input`/`Select`/`Textarea`, `FilterChip`, `Segmented`, `Avatar`, `Card`, `Drawer`, `TableCard`; pages sit in `AppShell` (desktop) or `MobileShell` (SSA). - Icons: Lucide (`lucide-react`), 16px stroke 2 in UI, 12px stroke 2.5 inside chips and checks, 22px stroke 1.8 in the mobile tab bar. - Interaction: hover/active values per component in design.md §4; `:focus-visible` 2px accent ring is global; transitions 120ms on bg/shadow only; mobile hit targets ≥ 44px. - Incident evidence photos stay full colour. diff --git a/__tests__/lib/auth/roles.test.ts b/__tests__/lib/auth/roles.test.ts index ca91b17..d0b8692 100644 --- a/__tests__/lib/auth/roles.test.ts +++ b/__tests__/lib/auth/roles.test.ts @@ -3,22 +3,14 @@ import { describe, it, expect } from 'vitest' import { getRoleHome, ROLE_HOME, ALL_ROLES } from '@/lib/auth/roles' describe('getRoleHome', () => { - it('returns /reporter for reporter role', () => { - expect(getRoleHome('reporter')).toBe('/reporter') - }) - - it('returns /supervisor for supervisor role', () => { - expect(getRoleHome('supervisor')).toBe('/supervisor') + it('returns /ssa for ssa role', () => { + expect(getRoleHome('ssa')).toBe('/ssa') }) it('returns /hse for hse role', () => { expect(getRoleHome('hse')).toBe('/hse') }) - it('returns /capa-owner for capa_owner role', () => { - expect(getRoleHome('capa_owner')).toBe('/capa-owner') - }) - it('returns /management for management role', () => { expect(getRoleHome('management')).toBe('/management') }) @@ -27,11 +19,11 @@ describe('getRoleHome', () => { expect(getRoleHome('admin')).toBe('/admin') }) - it('ROLE_HOME covers exactly 6 roles', () => { - expect(Object.keys(ROLE_HOME)).toHaveLength(6) + it('ROLE_HOME covers exactly 4 roles', () => { + expect(Object.keys(ROLE_HOME)).toHaveLength(4) }) - it('ALL_ROLES lists exactly 6 roles', () => { - expect(ALL_ROLES).toHaveLength(6) + it('ALL_ROLES lists exactly 4 roles', () => { + expect(ALL_ROLES).toHaveLength(4) }) }) diff --git a/app/(protected)/capa-owner/page.tsx b/app/(protected)/ssa/capas/page.tsx similarity index 97% rename from app/(protected)/capa-owner/page.tsx rename to app/(protected)/ssa/capas/page.tsx index 9ea8ae7..bd5dd17 100644 --- a/app/(protected)/capa-owner/page.tsx +++ b/app/(protected)/ssa/capas/page.tsx @@ -21,10 +21,10 @@ const STATUS_LABELS: Record = { closed: 'Closed', } -export default async function CapaOwnerPage() { +export default async function MyCapasPage() { const session = await getSession() if (!session) redirect('/login') - if (!['capa_owner', 'admin', 'hse', 'supervisor'].includes(session.role)) redirect('/') + if (!['ssa', 'admin', 'hse'].includes(session.role)) redirect('/') const rows = await asAdmin(db => db.select({ diff --git a/app/(protected)/supervisor/incidents/[id]/page.tsx b/app/(protected)/ssa/incidents/[id]/page.tsx similarity index 96% rename from app/(protected)/supervisor/incidents/[id]/page.tsx rename to app/(protected)/ssa/incidents/[id]/page.tsx index 0d88a7c..405f549 100644 --- a/app/(protected)/supervisor/incidents/[id]/page.tsx +++ b/app/(protected)/ssa/incidents/[id]/page.tsx @@ -14,7 +14,7 @@ interface Props { params: Promise<{ id: string }> } -export default async function SupervisorIncidentDetailPage({ params }: Props) { +export default async function SsaIncidentDetailPage({ params }: Props) { const { id } = await params const session = await getSession() @@ -136,7 +136,7 @@ export default async function SupervisorIncidentDetailPage({ params }: Props) { return (
- + ← Back to inbox diff --git a/app/(protected)/supervisor/incidents/page.tsx b/app/(protected)/ssa/incidents/page.tsx similarity index 93% rename from app/(protected)/supervisor/incidents/page.tsx rename to app/(protected)/ssa/incidents/page.tsx index 00db86c..63f48c0 100644 --- a/app/(protected)/supervisor/incidents/page.tsx +++ b/app/(protected)/ssa/incidents/page.tsx @@ -8,7 +8,7 @@ import { IncidentTable } from '@/components/incidents/incident-table' import { loadIncidentList } from '@/lib/incidents/list-query' import { parseListParams } from '@/lib/incidents/list-params' -export default async function SupervisorInboxPage({ +export default async function SsaInboxPage({ searchParams, }: { searchParams: Promise> @@ -27,7 +27,7 @@ export default async function SupervisorInboxPage({ = { reported: 'Reported', triaged: 'Triaged', investigating: 'Investigating', capa_pending: 'CAPA Pending', verification: 'Verification', closed: 'Closed', } -export default async function ReporterIncidentDetail({ +export default async function MyReportDetail({ params, }: { params: Promise<{ id: string }> @@ -60,7 +60,7 @@ export default async function ReporterIncidentDetail({ return (
- ← My Reports + ← My Reports
diff --git a/app/(protected)/reporter/page.tsx b/app/(protected)/ssa/my-reports/page.tsx similarity index 95% rename from app/(protected)/reporter/page.tsx rename to app/(protected)/ssa/my-reports/page.tsx index 949405d..124fcb0 100644 --- a/app/(protected)/reporter/page.tsx +++ b/app/(protected)/ssa/my-reports/page.tsx @@ -22,7 +22,7 @@ const TYPE_LABELS: Record = { asset_damage: 'Asset Damage', environmental: 'Environmental', security: 'Security', fire: 'Fire', } -export default async function ReporterPage() { +export default async function MyReportsPage() { const session = await getSession() if (!session) redirect('/login') @@ -83,7 +83,7 @@ export default async function ReporterPage() { ) : (
{rows.map(inc => ( - +

diff --git a/app/(protected)/supervisor/page.tsx b/app/(protected)/ssa/page.tsx similarity index 93% rename from app/(protected)/supervisor/page.tsx rename to app/(protected)/ssa/page.tsx index f4a6c5d..3c215f4 100644 --- a/app/(protected)/supervisor/page.tsx +++ b/app/(protected)/ssa/page.tsx @@ -19,15 +19,15 @@ const STATUS_LABELS: Record = { closed: 'Closed', } -export default async function SupervisorPage() { +export default async function SsaPage() { const session = await getSession() if (!session) redirect('/login') - if (!['supervisor', 'admin'].includes(session.role)) redirect('/') + if (!['ssa', 'admin'].includes(session.role)) redirect('/') if (!session.siteId) { return (

-

Supervisor Portal

+

Site Safety Assistant Portal

No site assigned — contact your administrator.

) @@ -108,10 +108,10 @@ export default async function SupervisorPage() {
-

Supervisor Portal

+

Site Safety Assistant Portal

{siteName}

- + All incidents →
@@ -134,7 +134,7 @@ export default async function SupervisorPage() { {openIncidents.map(inc => (
diff --git a/app/api/admin/users/route.ts b/app/api/admin/users/route.ts index 408a58c..f7b65af 100644 --- a/app/api/admin/users/route.ts +++ b/app/api/admin/users/route.ts @@ -69,7 +69,7 @@ export async function POST(request: NextRequest) { name: body.name ?? '', email, phone: (body.phone ?? '').trim() || null, - role: (body.role as typeof users.$inferInsert['role']) ?? 'reporter', + role: (body.role as typeof users.$inferInsert['role']) ?? 'ssa', siteId: body.site_id ?? null, department: body.department ?? null, passwordHash, @@ -78,7 +78,7 @@ export async function POST(request: NextRequest) { if (!created) throw new Error('User creation failed') createdId = created.id await writeAuditLog(tx, 'users', created.id, 'created', { - email, role: body.role ?? 'reporter', site_id: body.site_id ?? null, + email, role: body.role ?? 'ssa', site_id: body.site_id ?? null, }) }) }) diff --git a/app/api/capa/[id]/route.ts b/app/api/capa/[id]/route.ts index e148f11..6d713de 100644 --- a/app/api/capa/[id]/route.ts +++ b/app/api/capa/[id]/route.ts @@ -50,7 +50,7 @@ export async function GET( const role = session.role const isOwner = row.ownerUserId === session.sub - const canRead = ['hse', 'admin', 'supervisor'].includes(role) || isOwner + const canRead = ['hse', 'admin', 'ssa'].includes(role) || isOwner if (!canRead) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) const ownerField = ['hse', 'admin'].includes(role) diff --git a/app/api/capa/route.ts b/app/api/capa/route.ts index 3824de9..d7fc80e 100644 --- a/app/api/capa/route.ts +++ b/app/api/capa/route.ts @@ -40,7 +40,7 @@ export async function GET() { .leftJoin(incidents, eq(capaActions.incidentId, incidents.id)) .orderBy(asc(capaActions.dueDate)) - if (session.role === 'supervisor' || session.role === 'worker') { + if (session.role === 'ssa') { q = q.where(eq(capaActions.ownerUserId, session.sub)) as typeof q } diff --git a/app/api/incidents/[id]/addenda/route.ts b/app/api/incidents/[id]/addenda/route.ts index 6f028fd..49d7fc6 100644 --- a/app/api/incidents/[id]/addenda/route.ts +++ b/app/api/incidents/[id]/addenda/route.ts @@ -15,7 +15,7 @@ export async function GET( const { id } = await params const session = await getSession() if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) - if (!['hse', 'admin', 'supervisor'].includes(session.role)) + if (!['hse', 'admin', 'ssa'].includes(session.role)) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) const authorAlias = aliasedTable(users, 'author_user') @@ -45,7 +45,7 @@ export async function POST( const { id } = await params const session = await getSession() if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) - if (!['hse', 'admin', 'supervisor'].includes(session.role)) + if (!['hse', 'admin', 'ssa'].includes(session.role)) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) const body: { body?: string } = await request.json().catch(() => ({})) diff --git a/app/api/incidents/[id]/close/route.ts b/app/api/incidents/[id]/close/route.ts index 7f4551f..f2fb5a7 100644 --- a/app/api/incidents/[id]/close/route.ts +++ b/app/api/incidents/[id]/close/route.ts @@ -51,7 +51,7 @@ export async function POST( await createInAppNotifications([{ userId: incident.reportedBy, title: `Your incident report ${incident.referenceNo ?? ''} has been closed`, - link: '/reporter', + link: '/ssa/my-reports', incidentId: id, }]) } diff --git a/app/api/incidents/[id]/route.ts b/app/api/incidents/[id]/route.ts index 42a7699..c3a2832 100644 --- a/app/api/incidents/[id]/route.ts +++ b/app/api/incidents/[id]/route.ts @@ -46,7 +46,7 @@ export async function GET(_req: Request, { params }: { params: Promise<{ id: str if (!incident) return NextResponse.json({ error: 'Not found' }, { status: 404 }) const isOwner = incident.reporterId === session.sub - const isSiteStaff = ['hse', 'supervisor', 'admin'].includes(session.role) + const isSiteStaff = ['hse', 'ssa', 'admin'].includes(session.role) if (!isOwner && !isSiteStaff) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) const evidenceFileRows = await withUser(session.sub, async tx => diff --git a/app/api/incidents/route.ts b/app/api/incidents/route.ts index b8648a2..7e997b9 100644 --- a/app/api/incidents/route.ts +++ b/app/api/incidents/route.ts @@ -188,7 +188,7 @@ async function handlePost(request: Request) { db.select({ id: users.id, phone: users.phone }) .from(users) .where(and( - inArray(users.role, ['supervisor', 'hse']), + inArray(users.role, ['ssa', 'hse']), eq(users.siteId, zone.siteId), )) ) diff --git a/app/report/success/page.tsx b/app/report/success/page.tsx index 7f84ab1..68c6754 100644 --- a/app/report/success/page.tsx +++ b/app/report/success/page.tsx @@ -19,7 +19,7 @@ export default async function ReportSuccessPage({ searchParams }: Props) {

)}

- The supervisor and HSE officer have been notified. + The Site Safety Assistants and HSE officer have been notified.

Submit another report diff --git a/components/admin/user-manager.tsx b/components/admin/user-manager.tsx index b96d080..2b19b09 100644 --- a/components/admin/user-manager.tsx +++ b/components/admin/user-manager.tsx @@ -2,7 +2,7 @@ import { useState } from 'react' import { useRouter } from 'next/navigation' -import { ALL_ROLES, type UserRole } from '@/lib/auth/roles' +import { ALL_ROLES, ROLE_LABELS, type UserRole } from '@/lib/auth/roles' import { Modal } from '@/components/ui/modal' import { INPUT_CLASS as inp } from '@/components/ui/field' @@ -23,7 +23,7 @@ interface Props { sites: SiteOption[] } -const EMPTY = { email: '', name: '', phone: '', role: 'reporter' as UserRole, site_id: '', password: '' } +const EMPTY = { email: '', name: '', phone: '', role: 'ssa' as UserRole, site_id: '', password: '' } const lbl = 'block text-xs font-medium text-gray-600 mb-1' @@ -135,7 +135,7 @@ export function UserManager({ users, sites }: Props) { @@ -224,7 +224,7 @@ export function UserManager({ users, sites }: Props) {
diff --git a/components/layout/nav-items.ts b/components/layout/nav-items.ts index d16a419..f805c5b 100644 --- a/components/layout/nav-items.ts +++ b/components/layout/nav-items.ts @@ -16,14 +16,13 @@ export interface NavItem { } const NAV_ITEMS: Record = { - reporter: [ - { label: 'My Reports', href: '/reporter', icon: ClipboardList }, + ssa: [ + { label: 'Overview', href: '/ssa', icon: AlignLeft }, + { label: 'My Reports', href: '/ssa/my-reports', icon: ClipboardList }, + { label: 'Site Incidents', href: '/ssa/incidents', icon: ClipboardList }, + { label: 'My CAPAs', href: '/ssa/capas', icon: CircleCheck }, { label: 'New Incident', href: '/report', icon: Plus }, ], - supervisor: [ - { label: 'Overview', href: '/supervisor', icon: AlignLeft }, - { label: 'Incidents', href: '/supervisor/incidents', icon: ClipboardList }, - ], hse: [ { label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard }, { label: 'Incidents', href: '/hse/incidents', icon: ClipboardList }, @@ -31,7 +30,6 @@ const NAV_ITEMS: Record = { { label: 'Settings', href: '/hse/settings', icon: Settings }, ], management: [{ label: 'Dashboard', href: '/management', icon: LayoutDashboard }], - capa_owner: [{ label: 'My CAPAs', href: '/capa-owner', icon: CircleCheck }], admin: [ { label: 'Admin', href: '/admin', icon: Users }, { label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard }, @@ -42,10 +40,10 @@ const NAV_ITEMS: Record = { ], } -const EXACT_ROOTS = ['/reporter', '/supervisor', '/management', '/capa-owner', '/admin', '/report', '/account'] +const EXACT_ROOTS = ['/ssa', '/management', '/admin', '/report', '/account'] export function navItemsFor(role: string): NavItem[] { - return NAV_ITEMS[role] ?? NAV_ITEMS.reporter + return NAV_ITEMS[role] ?? NAV_ITEMS.ssa } export function isActivePath(href: string, pathname: string): boolean { @@ -54,6 +52,6 @@ export function isActivePath(href: string, pathname: string): boolean { export function searchHrefFor(role: string): string | null { if (role === 'hse' || role === 'admin') return '/hse/incidents' - if (role === 'supervisor') return '/supervisor/incidents' + if (role === 'ssa') return '/ssa/incidents' return null } diff --git a/db/ops/2026-11-06-merge-roles-into-ssa.sql b/db/ops/2026-11-06-merge-roles-into-ssa.sql new file mode 100644 index 0000000..7e56265 --- /dev/null +++ b/db/ops/2026-11-06-merge-roles-into-ssa.sql @@ -0,0 +1,37 @@ +-- 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. +-- After this, re-apply db/rls.sql policies that reference role names (drop + recreate; see below). +BEGIN; + +ALTER TYPE user_role ADD VALUE IF NOT EXISTS 'ssa'; +COMMIT; -- new enum value must be committed before use + +BEGIN; +UPDATE users SET role = 'ssa' WHERE role IN ('reporter', 'supervisor', 'capa_owner'); + +-- Recreate enum without legacy values. +ALTER TYPE user_role RENAME TO user_role_old; +CREATE TYPE user_role AS ENUM ('ssa', 'hse', 'management', 'admin'); + +-- Policies reference auth_user_role() (returns user_role); drop them so the column/function can switch type. +-- Easiest: drop all policies from db/rls.sql, change types, then re-run db/rls.sql (policies are recreated). +-- 1) DROP POLICY ... for every policy in db/rls.sql (or: DROP OWNED-style loop below) +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 $$; + +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'; + +-- If auth_user_role() is declared RETURNS user_role, recreate it after the type swap +-- (copy its definition from db/schema.sql), then DROP TYPE user_role_old. +-- DROP TYPE user_role_old; -- only after nothing depends on it +COMMIT; + +-- Finally: psql -f db/rls.sql (recreates all policies with 'ssa') +-- Users also need their ims_session cookie refreshed (role is in the JWT): ask them to log out and in. diff --git a/db/rls.sql b/db/rls.sql index 68232b1..f31a980 100644 --- a/db/rls.sql +++ b/db/rls.sql @@ -56,7 +56,7 @@ CREATE POLICY "trucks_admin_all" ON trucks FOR ALL USING (auth_user_role() = -- users CREATE POLICY "users_read_own" ON users FOR SELECT USING (id = app_current_user_id()); CREATE POLICY "users_read_elevated" ON users FOR SELECT - USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor')); + USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa')); CREATE POLICY "users_update_own" ON users FOR UPDATE USING (id = app_current_user_id()) WITH CHECK ( @@ -70,12 +70,12 @@ CREATE POLICY "incidents_insert" ON incidents FOR INSERT WITH CHECK (reported_by = app_current_user_id()); CREATE POLICY "incidents_read_reporter" ON incidents FOR SELECT USING (reported_by = app_current_user_id()); -CREATE POLICY "incidents_read_supervisor" ON incidents FOR SELECT - USING (auth_user_role() = 'supervisor' AND site_id = auth_user_site_id()); +CREATE POLICY "incidents_read_ssa" ON incidents FOR SELECT + USING (auth_user_role() = 'ssa' AND site_id = auth_user_site_id()); CREATE POLICY "incidents_read_elevated" ON incidents FOR SELECT USING (auth_user_role() IN ('hse', 'admin', 'management')); CREATE POLICY "incidents_update_elevated" ON incidents FOR UPDATE - USING (auth_user_role() IN ('hse', 'admin', 'supervisor')); + USING (auth_user_role() IN ('hse', 'admin', 'ssa')); -- evidence_files CREATE POLICY "evidence_insert" ON evidence_files FOR INSERT @@ -83,14 +83,14 @@ CREATE POLICY "evidence_insert" ON evidence_files FOR INSERT CREATE POLICY "evidence_read_uploader" ON evidence_files FOR SELECT USING (uploaded_by = app_current_user_id()); CREATE POLICY "evidence_read_elevated" ON evidence_files FOR SELECT - USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor')); + USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa')); -- No DELETE policy: files are never deleted (soft-delete only via `deleted` flag) -- investigations CREATE POLICY "investigations_hse_admin" ON investigations FOR ALL USING (auth_user_role() IN ('hse', 'admin')); -CREATE POLICY "investigations_read_supervisor" ON investigations FOR SELECT - USING (auth_user_role() = 'supervisor'); +CREATE POLICY "investigations_read_ssa" ON investigations FOR SELECT + USING (auth_user_role() = 'ssa'); -- capa_actions (capa_update_owner is tightened — no department clause) CREATE POLICY "capa_read_owner" ON capa_actions FOR SELECT @@ -98,7 +98,7 @@ CREATE POLICY "capa_read_owner" ON capa_actions FOR SELECT CREATE POLICY "capa_update_owner" ON capa_actions FOR UPDATE USING (owner_user_id = app_current_user_id()); CREATE POLICY "capa_read_elevated" ON capa_actions FOR SELECT - USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor')); + USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa')); CREATE POLICY "capa_hse_admin_all" ON capa_actions FOR ALL USING (auth_user_role() IN ('hse', 'admin')); @@ -108,7 +108,7 @@ CREATE POLICY "dosh_hse_admin" ON dosh_reports FOR ALL -- notifications_log (final state after migration 19 fix) CREATE POLICY "notifications_insert_elevated" ON notifications_log FOR INSERT - WITH CHECK (auth_user_role() IN ('hse', 'admin', 'supervisor')); + WITH CHECK (auth_user_role() IN ('hse', 'admin', 'ssa')); CREATE POLICY "notifications_read_own" ON notifications_log FOR SELECT USING (recipient_user_id = app_current_user_id()); CREATE POLICY "notifications_read_admin" ON notifications_log FOR SELECT @@ -130,7 +130,7 @@ CREATE POLICY "admin_update_settings" ON app_settings FOR ALL -- incident_addenda CREATE POLICY "addenda_read" ON incident_addenda FOR SELECT USING ( - auth_user_role() IN ('hse', 'admin', 'supervisor', 'management') + auth_user_role() IN ('hse', 'admin', 'ssa', 'management') OR EXISTS ( SELECT 1 FROM incidents i WHERE i.id = incident_id AND i.reported_by = app_current_user_id() @@ -139,5 +139,5 @@ CREATE POLICY "addenda_read" ON incident_addenda FOR SELECT CREATE POLICY "addenda_insert" ON incident_addenda FOR INSERT WITH CHECK ( author = app_current_user_id() - AND auth_user_role() IN ('hse', 'admin', 'supervisor') + AND auth_user_role() IN ('hse', 'admin', 'ssa') ); diff --git a/db/schema.sql b/db/schema.sql index 8391254..5215e5b 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -16,7 +16,7 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto; -- Enums -- --------------------------------------------------------------------------- CREATE TYPE user_role AS ENUM ( - 'reporter', 'supervisor', 'hse', 'capa_owner', 'management', 'admin' + 'ssa', 'hse', 'management', 'admin' ); CREATE TYPE incident_type AS ENUM ( @@ -80,7 +80,7 @@ CREATE TABLE users ( name TEXT NOT NULL DEFAULT '', email TEXT NOT NULL DEFAULT '' UNIQUE, phone TEXT, - role user_role NOT NULL DEFAULT 'reporter', + role user_role NOT NULL DEFAULT 'ssa', department TEXT, site_id UUID REFERENCES sites(id), active BOOLEAN NOT NULL DEFAULT true, diff --git a/lib/auth/roles.ts b/lib/auth/roles.ts index 4a44bf0..b17114f 100644 --- a/lib/auth/roles.ts +++ b/lib/auth/roles.ts @@ -1,26 +1,28 @@ // lib/auth/roles.ts +// 'ssa' = Site Safety Assistant. Replaces the former reporter, supervisor and capa_owner roles. export type UserRole = - | 'reporter' - | 'supervisor' + | 'ssa' | 'hse' - | 'capa_owner' | 'management' | 'admin' export const ALL_ROLES: UserRole[] = [ - 'reporter', - 'supervisor', + 'ssa', 'hse', - 'capa_owner', 'management', 'admin', ] +export const ROLE_LABELS: Record = { + ssa: 'Site Safety Assistant (SSA)', + hse: 'HSE', + management: 'Management', + admin: 'Admin', +} + export const ROLE_HOME: Record = { - reporter: '/reporter', - supervisor: '/supervisor', + ssa: '/ssa', hse: '/hse', - capa_owner: '/capa-owner', management: '/management', admin: '/admin', } diff --git a/lib/db/schema.ts b/lib/db/schema.ts index 445437a..e7579bf 100644 --- a/lib/db/schema.ts +++ b/lib/db/schema.ts @@ -26,7 +26,7 @@ const vector = customType<{ data: number[]; driverData: string }>({ // Enums // --------------------------------------------------------------------------- export const userRoleEnum = pgEnum('user_role', [ - 'reporter', 'supervisor', 'hse', 'capa_owner', 'management', 'admin', + 'ssa', 'hse', 'management', 'admin', ]) export const incidentTypeEnum = pgEnum('incident_type', [ @@ -89,7 +89,7 @@ export const users = pgTable('users', { name: text('name').notNull().default(''), email: text('email').notNull().default('').unique(), phone: text('phone'), - role: userRoleEnum('role').notNull().default('reporter'), + role: userRoleEnum('role').notNull().default('ssa'), department: text('department'), siteId: uuid('site_id').references(() => sites.id), active: boolean('active').notNull().default(true), diff --git a/lib/notifications/capa-escalation.ts b/lib/notifications/capa-escalation.ts index 9cd555b..6ef795b 100644 --- a/lib/notifications/capa-escalation.ts +++ b/lib/notifications/capa-escalation.ts @@ -97,7 +97,7 @@ export async function escalateOverdueCapa(): Promise<{ notified: number }> { .from(users) .where(and( eq(users.siteId, capa.siteId!), - inArray(users.role, ['hse', 'supervisor', 'management']), + inArray(users.role, ['hse', 'ssa', 'management']), )) ) to.push(...hseUsers.map(u => u.email).filter(Boolean) as string[]) diff --git a/lib/notifications/email.ts b/lib/notifications/email.ts index 6d36e0d..dc31fe6 100644 --- a/lib/notifications/email.ts +++ b/lib/notifications/email.ts @@ -15,7 +15,7 @@ export async function sendNewIncidentEmail( db.select({ email: users.email }) .from(users) .where(and( - inArray(users.role, ['supervisor', 'hse']), + inArray(users.role, ['ssa', 'hse']), eq(users.siteId, siteId), )) ) diff --git a/tests/api/capa-patch.test.ts b/tests/api/capa-patch.test.ts index 6a2cd6a..91c4e56 100644 --- a/tests/api/capa-patch.test.ts +++ b/tests/api/capa-patch.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, vi } from 'vitest' 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/with-user', () => ({ diff --git a/tests/api/capa-submit.test.ts b/tests/api/capa-submit.test.ts index 3b414c4..a3675c4 100644 --- a/tests/api/capa-submit.test.ts +++ b/tests/api/capa-submit.test.ts @@ -38,7 +38,7 @@ function req(note: string | null, fileCount: number) { const ctx = { params: Promise.resolve({ id: 'capa-1' }) } 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.updates = [] h.inserts = [] @@ -56,7 +56,7 @@ describe('POST /api/capa/[id]/submit', () => { expect((await POST(req('done', 1) as never, ctx)).status).toBe(404) }) it('403 for a user who is neither owner nor hse/admin', async () => { - h.session = { sub: 'other', role: 'reporter' } + h.session = { sub: 'other', role: 'ssa' } expect((await POST(req('done', 1) as never, ctx)).status).toBe(403) }) it('409 when status is not in_progress', async () => { diff --git a/tests/app/api/incidents/report-pdf.test.ts b/tests/app/api/incidents/report-pdf.test.ts index f05ccc2..ef2853f 100644 --- a/tests/app/api/incidents/report-pdf.test.ts +++ b/tests/app/api/incidents/report-pdf.test.ts @@ -64,7 +64,7 @@ describe('GET /api/incidents/[id]/report-pdf', () => { }) 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' }) }) expect(res.status).toBe(403) }) diff --git a/tests/components/layout/app-shell.test.tsx b/tests/components/layout/app-shell.test.tsx index 833c81a..c769ba8 100644 --- a/tests/components/layout/app-shell.test.tsx +++ b/tests/components/layout/app-shell.test.tsx @@ -50,7 +50,7 @@ describe('AppShell', () => { }) it('hides the search box for roles without an incident list', () => { - const { container } = render() + const { container } = render() expect(container.querySelector('header form')).toBeNull() }) diff --git a/tests/components/layout/nav-items.test.ts b/tests/components/layout/nav-items.test.ts index c5cdbe1..eb5f354 100644 --- a/tests/components/layout/nav-items.test.ts +++ b/tests/components/layout/nav-items.test.ts @@ -2,23 +2,21 @@ import { describe, it, expect } from 'vitest' import { navItemsFor, isActivePath, searchHrefFor } from '@/components/layout/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('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', () => { - expect(isActivePath('/reporter', '/reporter')).toBe(true) - expect(isActivePath('/reporter', '/reporter/incidents/1')).toBe(false) + expect(isActivePath('/ssa', '/ssa')).toBe(true) + expect(isActivePath('/ssa', '/ssa/incidents/1')).toBe(false) expect(isActivePath('/hse/incidents', '/hse/incidents/abc')).toBe(true) }) it('offers the search box only to roles that have an incident list', () => { expect(searchHrefFor('hse')).toBe('/hse/incidents') expect(searchHrefFor('admin')).toBe('/hse/incidents') - expect(searchHrefFor('supervisor')).toBe('/supervisor/incidents') - expect(searchHrefFor('reporter')).toBeNull() - expect(searchHrefFor('capa_owner')).toBeNull() + expect(searchHrefFor('ssa')).toBe('/ssa/incidents') }) }) diff --git a/tests/lib/notifications/email.test.ts b/tests/lib/notifications/email.test.ts index 22c900c..70898b5 100644 --- a/tests/lib/notifications/email.test.ts +++ b/tests/lib/notifications/email.test.ts @@ -14,7 +14,7 @@ vi.mock('resend', () => { // Mock asAdmin: first call returns recipients, second returns incident+join rows let asAdminCallCount = 0 const mockRecipients = [ - { email: 'supervisor@setiacorp.com' }, + { email: 'ssa@setiacorp.com' }, { email: 'hse@setiacorp.com' }, ] const mockIncidentRows = [{ @@ -44,11 +44,11 @@ beforeEach(() => { }) 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') expect(mockSend).toHaveBeenCalledTimes(1) 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') }) From f52e63ad09fd099072a25b69dc6ac113f4c30f25 Mon Sep 17 00:00:00 2001 From: Weei Han Date: Fri, 6 Nov 2026 21:41:08 +0800 Subject: [PATCH 2/3] 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 --- db/ops/2026-11-06-merge-roles-into-ssa.sql | 159 +++++++++++++++++++-- 1 file changed, 144 insertions(+), 15 deletions(-) diff --git a/db/ops/2026-11-06-merge-roles-into-ssa.sql b/db/ops/2026-11-06-merge-roles-into-ssa.sql index 7e56265..11894bd 100644 --- a/db/ops/2026-11-06-merge-roles-into-ssa.sql +++ b/db/ops/2026-11-06-merge-roles-into-ssa.sql @@ -1,21 +1,25 @@ -- 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. --- After this, re-apply db/rls.sql policies that reference role names (drop + recreate; see below). -BEGIN; +-- 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; -- new enum value must be committed before use +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'); --- Recreate enum without legacy values. -ALTER TYPE user_role RENAME TO user_role_old; -CREATE TYPE user_role AS ENUM ('ssa', 'hse', 'management', 'admin'); - --- Policies reference auth_user_role() (returns user_role); drop them so the column/function can switch type. --- Easiest: drop all policies from db/rls.sql, change types, then re-run db/rls.sql (policies are recreated). --- 1) DROP POLICY ... for every policy in db/rls.sql (or: DROP OWNED-style loop below) +-- Drop all existing RLS policies (safe: RLS still ON during migration) DO $$ DECLARE r record; BEGIN @@ -24,14 +28,139 @@ BEGIN 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'; --- If auth_user_role() is declared RETURNS user_role, recreate it after the type swap --- (copy its definition from db/schema.sql), then DROP TYPE user_role_old. --- DROP TYPE user_role_old; -- only after nothing depends on it +-- 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; --- Finally: psql -f db/rls.sql (recreates all policies with 'ssa') --- Users also need their ims_session cookie refreshed (role is in the JWT): ask them to log out and in. +-- ============================================================================ +-- 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) +-- ============================================================================ From 4ec37bd078e793db54996a0b4cc8893ab1d1d804 Mon Sep 17 00:00:00 2001 From: weeihan Date: Fri, 6 Nov 2026 21:50:23 +0800 Subject: [PATCH 3/3] 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 --- tests/components/layout/app-shell.test.tsx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/components/layout/app-shell.test.tsx b/tests/components/layout/app-shell.test.tsx index c769ba8..023257d 100644 --- a/tests/components/layout/app-shell.test.tsx +++ b/tests/components/layout/app-shell.test.tsx @@ -49,8 +49,13 @@ describe('AppShell', () => { expect(document.activeElement?.getAttribute('name')).toBe('q') }) - it('hides the search box for roles without an incident list', () => { + it('targets the site incident list for the SSA role', () => { const { container } = render() + expect(container.querySelector('header form')!.getAttribute('action')).toBe('/ssa/incidents') + }) + + it('hides the search box for roles without an incident list', () => { + const { container } = render() expect(container.querySelector('header form')).toBeNull() })