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>
This commit is contained in:
Weei Han
2026-11-06 21:34:10 +08:00
co-authored by Claude Sonnet 5.5
parent 701fefd286
commit 813395700f
31 changed files with 123 additions and 96 deletions
+1 -1
View File
@@ -85,7 +85,7 @@ Source of truth: `design-system/design.md`. Visual references: `design-system/IM
- Radius comes from the scale: `rounded-md` (8) buttons, chips, inputs, pills; `rounded-xl` (12) cards and mobile controls; `rounded-[5px]` checkbox. Headings and labels are flush left.
- Status and priority colours only via `StatusTag` / `PriorityTag` (design.md §4.2): dark text on a light tint, text label always present, no icon required. Add new statuses in `components/ui/status-tag.tsx`, not per page.
- Every list is a `TableCard` (design.md §4.9): saved views, toolbar, sortable header, row hover quick actions, selected tint, footer pager, floating bulk bar, empty state, mobile stacked variant. Do not hand-build tables.
- Build UI with `components/ui/*`: `Button`, `StatusTag`, `PriorityTag`, `Checkbox`, `Field`/`Input`/`Select`/`Textarea`, `FilterChip`, `Segmented`, `Avatar`, `Card`, `Drawer`, `TableCard`; pages sit in `AppShell` (desktop) or `MobileShell` (reporter / CAPA owner).
- Build UI with `components/ui/*`: `Button`, `StatusTag`, `PriorityTag`, `Checkbox`, `Field`/`Input`/`Select`/`Textarea`, `FilterChip`, `Segmented`, `Avatar`, `Card`, `Drawer`, `TableCard`; pages sit in `AppShell` (desktop) or `MobileShell` (SSA).
- Icons: Lucide (`lucide-react`), 16px stroke 2 in UI, 12px stroke 2.5 inside chips and checks, 22px stroke 1.8 in the mobile tab bar.
- Interaction: hover/active values per component in design.md §4; `:focus-visible` 2px accent ring is global; transitions 120ms on bg/shadow only; mobile hit targets ≥ 44px.
- Incident evidence photos stay full colour.
+6 -14
View File
@@ -3,22 +3,14 @@ import { describe, it, expect } from 'vitest'
import { getRoleHome, ROLE_HOME, ALL_ROLES } from '@/lib/auth/roles'
describe('getRoleHome', () => {
it('returns /reporter for reporter role', () => {
expect(getRoleHome('reporter')).toBe('/reporter')
})
it('returns /supervisor for supervisor role', () => {
expect(getRoleHome('supervisor')).toBe('/supervisor')
it('returns /ssa for ssa role', () => {
expect(getRoleHome('ssa')).toBe('/ssa')
})
it('returns /hse for hse role', () => {
expect(getRoleHome('hse')).toBe('/hse')
})
it('returns /capa-owner for capa_owner role', () => {
expect(getRoleHome('capa_owner')).toBe('/capa-owner')
})
it('returns /management for management role', () => {
expect(getRoleHome('management')).toBe('/management')
})
@@ -27,11 +19,11 @@ describe('getRoleHome', () => {
expect(getRoleHome('admin')).toBe('/admin')
})
it('ROLE_HOME covers exactly 6 roles', () => {
expect(Object.keys(ROLE_HOME)).toHaveLength(6)
it('ROLE_HOME covers exactly 4 roles', () => {
expect(Object.keys(ROLE_HOME)).toHaveLength(4)
})
it('ALL_ROLES lists exactly 6 roles', () => {
expect(ALL_ROLES).toHaveLength(6)
it('ALL_ROLES lists exactly 4 roles', () => {
expect(ALL_ROLES).toHaveLength(4)
})
})
@@ -21,10 +21,10 @@ const STATUS_LABELS: Record<string, string> = {
closed: 'Closed',
}
export default async function CapaOwnerPage() {
export default async function MyCapasPage() {
const session = await getSession()
if (!session) redirect('/login')
if (!['capa_owner', 'admin', 'hse', 'supervisor'].includes(session.role)) redirect('/')
if (!['ssa', 'admin', 'hse'].includes(session.role)) redirect('/')
const rows = await asAdmin(db =>
db.select({
@@ -14,7 +14,7 @@ interface Props {
params: Promise<{ id: string }>
}
export default async function SupervisorIncidentDetailPage({ params }: Props) {
export default async function SsaIncidentDetailPage({ params }: Props) {
const { id } = await params
const session = await getSession()
@@ -136,7 +136,7 @@ export default async function SupervisorIncidentDetailPage({ params }: Props) {
return (
<main className="max-w-3xl mx-auto px-4 py-6">
<Link href="/supervisor/incidents" className="text-sm text-accent-700 hover:underline mb-4 inline-block">
<Link href="/ssa/incidents" className="text-sm text-accent-700 hover:underline mb-4 inline-block">
← Back to inbox
</Link>
<IncidentDetail incident={incidentProp} />
@@ -8,7 +8,7 @@ import { IncidentTable } from '@/components/incidents/incident-table'
import { loadIncidentList } from '@/lib/incidents/list-query'
import { parseListParams } from '@/lib/incidents/list-params'
export default async function SupervisorInboxPage({
export default async function SsaInboxPage({
searchParams,
}: {
searchParams: Promise<Record<string, string | undefined>>
@@ -27,7 +27,7 @@ export default async function SupervisorInboxPage({
</div>
<IncidentTable
incidents={data.incidents}
basePath="/supervisor"
basePath="/ssa"
total={data.total}
counts={data.counts}
params={params}
@@ -12,7 +12,7 @@ const STATUS_LABELS: Record<string, string> = {
reported: 'Reported', triaged: 'Triaged', investigating: 'Investigating',
capa_pending: 'CAPA Pending', verification: 'Verification', closed: 'Closed',
}
export default async function ReporterIncidentDetail({
export default async function MyReportDetail({
params,
}: {
params: Promise<{ id: string }>
@@ -60,7 +60,7 @@ export default async function ReporterIncidentDetail({
return (
<main className="max-w-2xl mx-auto px-4 py-6 space-y-4">
<div className="flex items-center gap-2 mb-2">
<Link href="/reporter" className="text-sm text-accent-700 hover:underline">← My Reports</Link>
<Link href="/ssa/my-reports" className="text-sm text-accent-700 hover:underline">← My Reports</Link>
</div>
<div className="bg-surface shadow-sm p-5">
@@ -22,7 +22,7 @@ const TYPE_LABELS: Record<string, string> = {
asset_damage: 'Asset Damage', environmental: 'Environmental', security: 'Security', fire: 'Fire',
}
export default async function ReporterPage() {
export default async function MyReportsPage() {
const session = await getSession()
if (!session) redirect('/login')
@@ -83,7 +83,7 @@ export default async function ReporterPage() {
) : (
<div className="bg-surface shadow-sm divide-y divide-gray-50">
{rows.map(inc => (
<Link key={inc.id} href={`/reporter/incidents/${inc.id}`} className="block p-4 cursor-pointer hover:bg-gray-50 transition-colors">
<Link key={inc.id} href={`/ssa/my-reports/${inc.id}`} className="block p-4 cursor-pointer hover:bg-gray-50 transition-colors">
<div className="flex items-start justify-between gap-3">
<div className="flex-1 min-w-0">
<p className="text-sm font-semibold text-gray-900">
@@ -19,15 +19,15 @@ const STATUS_LABELS: Record<string, string> = {
closed: 'Closed',
}
export default async function SupervisorPage() {
export default async function SsaPage() {
const session = await getSession()
if (!session) redirect('/login')
if (!['supervisor', 'admin'].includes(session.role)) redirect('/')
if (!['ssa', 'admin'].includes(session.role)) redirect('/')
if (!session.siteId) {
return (
<main className="max-w-4xl mx-auto px-4 py-6">
<h1 className="text-2xl font-bold text-gray-900 mb-4">Supervisor Portal</h1>
<h1 className="text-2xl font-bold text-gray-900 mb-4">Site Safety Assistant Portal</h1>
<p className="text-sm text-gray-500">No site assigned — contact your administrator.</p>
</main>
)
@@ -108,10 +108,10 @@ export default async function SupervisorPage() {
<main className="max-w-4xl mx-auto px-4 py-6">
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-gray-900">Supervisor Portal</h1>
<h1 className="text-2xl font-bold text-gray-900">Site Safety Assistant Portal</h1>
<p className="text-sm text-gray-500 mt-1">{siteName}</p>
</div>
<Link href="/supervisor/incidents" className="text-sm text-accent-700 hover:underline">
<Link href="/ssa/incidents" className="text-sm text-accent-700 hover:underline">
All incidents →
</Link>
</div>
@@ -134,7 +134,7 @@ export default async function SupervisorPage() {
{openIncidents.map(inc => (
<Link
key={inc.id}
href={`/supervisor/incidents/${inc.id}`}
href={`/ssa/incidents/${inc.id}`}
className="flex items-center justify-between py-2 border-b border-gray-50 last:border-0 hover:bg-gray-50 -mx-2 px-2"
>
<div>
+2 -2
View File
@@ -69,7 +69,7 @@ export async function POST(request: NextRequest) {
name: body.name ?? '',
email,
phone: (body.phone ?? '').trim() || null,
role: (body.role as typeof users.$inferInsert['role']) ?? 'reporter',
role: (body.role as typeof users.$inferInsert['role']) ?? 'ssa',
siteId: body.site_id ?? null,
department: body.department ?? null,
passwordHash,
@@ -78,7 +78,7 @@ export async function POST(request: NextRequest) {
if (!created) throw new Error('User creation failed')
createdId = created.id
await writeAuditLog(tx, 'users', created.id, 'created', {
email, role: body.role ?? 'reporter', site_id: body.site_id ?? null,
email, role: body.role ?? 'ssa', site_id: body.site_id ?? null,
})
})
})
+1 -1
View File
@@ -50,7 +50,7 @@ export async function GET(
const role = session.role
const isOwner = row.ownerUserId === session.sub
const canRead = ['hse', 'admin', 'supervisor'].includes(role) || isOwner
const canRead = ['hse', 'admin', 'ssa'].includes(role) || isOwner
if (!canRead) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const ownerField = ['hse', 'admin'].includes(role)
+1 -1
View File
@@ -40,7 +40,7 @@ export async function GET() {
.leftJoin(incidents, eq(capaActions.incidentId, incidents.id))
.orderBy(asc(capaActions.dueDate))
if (session.role === 'supervisor' || session.role === 'worker') {
if (session.role === 'ssa') {
q = q.where(eq(capaActions.ownerUserId, session.sub)) as typeof q
}
+2 -2
View File
@@ -15,7 +15,7 @@ export async function GET(
const { id } = await params
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin', 'supervisor'].includes(session.role))
if (!['hse', 'admin', 'ssa'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const authorAlias = aliasedTable(users, 'author_user')
@@ -45,7 +45,7 @@ export async function POST(
const { id } = await params
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin', 'supervisor'].includes(session.role))
if (!['hse', 'admin', 'ssa'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const body: { body?: string } = await request.json().catch(() => ({}))
+1 -1
View File
@@ -51,7 +51,7 @@ export async function POST(
await createInAppNotifications([{
userId: incident.reportedBy,
title: `Your incident report ${incident.referenceNo ?? ''} has been closed`,
link: '/reporter',
link: '/ssa/my-reports',
incidentId: id,
}])
}
+1 -1
View File
@@ -46,7 +46,7 @@ export async function GET(_req: Request, { params }: { params: Promise<{ id: str
if (!incident) return NextResponse.json({ error: 'Not found' }, { status: 404 })
const isOwner = incident.reporterId === session.sub
const isSiteStaff = ['hse', 'supervisor', 'admin'].includes(session.role)
const isSiteStaff = ['hse', 'ssa', 'admin'].includes(session.role)
if (!isOwner && !isSiteStaff) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const evidenceFileRows = await withUser(session.sub, async tx =>
+1 -1
View File
@@ -188,7 +188,7 @@ async function handlePost(request: Request) {
db.select({ id: users.id, phone: users.phone })
.from(users)
.where(and(
inArray(users.role, ['supervisor', 'hse']),
inArray(users.role, ['ssa', 'hse']),
eq(users.siteId, zone.siteId),
))
)
+1 -1
View File
@@ -19,7 +19,7 @@ export default async function ReportSuccessPage({ searchParams }: Props) {
</p>
)}
<p className="text-sm text-gray-500 mb-6">
The supervisor and HSE officer have been notified.
The Site Safety Assistants and HSE officer have been notified.
</p>
<Link href="/report" className="text-sm text-accent-700 hover:underline">
Submit another report
+4 -4
View File
@@ -2,7 +2,7 @@
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { ALL_ROLES, type UserRole } from '@/lib/auth/roles'
import { ALL_ROLES, ROLE_LABELS, type UserRole } from '@/lib/auth/roles'
import { Modal } from '@/components/ui/modal'
import { INPUT_CLASS as inp } from '@/components/ui/field'
@@ -23,7 +23,7 @@ interface Props {
sites: SiteOption[]
}
const EMPTY = { email: '', name: '', phone: '', role: 'reporter' as UserRole, site_id: '', password: '' }
const EMPTY = { email: '', name: '', phone: '', role: 'ssa' as UserRole, site_id: '', password: '' }
const lbl = 'block text-xs font-medium text-gray-600 mb-1'
@@ -135,7 +135,7 @@ export function UserManager({ users, sites }: Props) {
<select value={u.role} disabled={busyId === u.id}
onChange={e => patchUser(u.id, { role: e.target.value })}
className="border border-divider px-2 py-1 text-xs focus:outline-none focus:ring-1 focus:ring-accent cursor-pointer">
{ALL_ROLES.map(r => <option key={r} value={r}>{r.replace(/_/g, ' ')}</option>)}
{ALL_ROLES.map(r => <option key={r} value={r}>{ROLE_LABELS[r]}</option>)}
</select>
</td>
<td className="px-5 py-3">
@@ -224,7 +224,7 @@ export function UserManager({ users, sites }: Props) {
<select id="au-role" value={form.role}
onChange={e => setForm(v => ({ ...v, role: e.target.value as UserRole }))}
className={inp}>
{ALL_ROLES.map(r => <option key={r} value={r}>{r.replace(/_/g, ' ')}</option>)}
{ALL_ROLES.map(r => <option key={r} value={r}>{ROLE_LABELS[r]}</option>)}
</select>
</div>
<div>
+8 -10
View File
@@ -16,14 +16,13 @@ export interface NavItem {
}
const NAV_ITEMS: Record<string, NavItem[]> = {
reporter: [
{ label: 'My Reports', href: '/reporter', icon: ClipboardList },
ssa: [
{ label: 'Overview', href: '/ssa', icon: AlignLeft },
{ label: 'My Reports', href: '/ssa/my-reports', icon: ClipboardList },
{ label: 'Site Incidents', href: '/ssa/incidents', icon: ClipboardList },
{ label: 'My CAPAs', href: '/ssa/capas', icon: CircleCheck },
{ label: 'New Incident', href: '/report', icon: Plus },
],
supervisor: [
{ label: 'Overview', href: '/supervisor', icon: AlignLeft },
{ label: 'Incidents', href: '/supervisor/incidents', icon: ClipboardList },
],
hse: [
{ label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard },
{ label: 'Incidents', href: '/hse/incidents', icon: ClipboardList },
@@ -31,7 +30,6 @@ const NAV_ITEMS: Record<string, NavItem[]> = {
{ label: 'Settings', href: '/hse/settings', icon: Settings },
],
management: [{ label: 'Dashboard', href: '/management', icon: LayoutDashboard }],
capa_owner: [{ label: 'My CAPAs', href: '/capa-owner', icon: CircleCheck }],
admin: [
{ label: 'Admin', href: '/admin', icon: Users },
{ label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard },
@@ -42,10 +40,10 @@ const NAV_ITEMS: Record<string, NavItem[]> = {
],
}
const EXACT_ROOTS = ['/reporter', '/supervisor', '/management', '/capa-owner', '/admin', '/report', '/account']
const EXACT_ROOTS = ['/ssa', '/management', '/admin', '/report', '/account']
export function navItemsFor(role: string): NavItem[] {
return NAV_ITEMS[role] ?? NAV_ITEMS.reporter
return NAV_ITEMS[role] ?? NAV_ITEMS.ssa
}
export function isActivePath(href: string, pathname: string): boolean {
@@ -54,6 +52,6 @@ export function isActivePath(href: string, pathname: string): boolean {
export function searchHrefFor(role: string): string | null {
if (role === 'hse' || role === 'admin') return '/hse/incidents'
if (role === 'supervisor') return '/supervisor/incidents'
if (role === 'ssa') return '/ssa/incidents'
return null
}
@@ -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.
+11 -11
View File
@@ -56,7 +56,7 @@ CREATE POLICY "trucks_admin_all" ON trucks FOR ALL USING (auth_user_role() =
-- users
CREATE POLICY "users_read_own" ON users FOR SELECT USING (id = app_current_user_id());
CREATE POLICY "users_read_elevated" ON users FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor'));
USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa'));
CREATE POLICY "users_update_own" ON users FOR UPDATE
USING (id = app_current_user_id())
WITH CHECK (
@@ -70,12 +70,12 @@ CREATE POLICY "incidents_insert" ON incidents FOR INSERT
WITH CHECK (reported_by = app_current_user_id());
CREATE POLICY "incidents_read_reporter" ON incidents FOR SELECT
USING (reported_by = app_current_user_id());
CREATE POLICY "incidents_read_supervisor" ON incidents FOR SELECT
USING (auth_user_role() = 'supervisor' AND site_id = auth_user_site_id());
CREATE POLICY "incidents_read_ssa" ON incidents FOR SELECT
USING (auth_user_role() = 'ssa' AND site_id = auth_user_site_id());
CREATE POLICY "incidents_read_elevated" ON incidents FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management'));
CREATE POLICY "incidents_update_elevated" ON incidents FOR UPDATE
USING (auth_user_role() IN ('hse', 'admin', 'supervisor'));
USING (auth_user_role() IN ('hse', 'admin', 'ssa'));
-- evidence_files
CREATE POLICY "evidence_insert" ON evidence_files FOR INSERT
@@ -83,14 +83,14 @@ CREATE POLICY "evidence_insert" ON evidence_files FOR INSERT
CREATE POLICY "evidence_read_uploader" ON evidence_files FOR SELECT
USING (uploaded_by = app_current_user_id());
CREATE POLICY "evidence_read_elevated" ON evidence_files FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor'));
USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa'));
-- No DELETE policy: files are never deleted (soft-delete only via `deleted` flag)
-- investigations
CREATE POLICY "investigations_hse_admin" ON investigations FOR ALL
USING (auth_user_role() IN ('hse', 'admin'));
CREATE POLICY "investigations_read_supervisor" ON investigations FOR SELECT
USING (auth_user_role() = 'supervisor');
CREATE POLICY "investigations_read_ssa" ON investigations FOR SELECT
USING (auth_user_role() = 'ssa');
-- capa_actions (capa_update_owner is tightened — no department clause)
CREATE POLICY "capa_read_owner" ON capa_actions FOR SELECT
@@ -98,7 +98,7 @@ CREATE POLICY "capa_read_owner" ON capa_actions FOR SELECT
CREATE POLICY "capa_update_owner" ON capa_actions FOR UPDATE
USING (owner_user_id = app_current_user_id());
CREATE POLICY "capa_read_elevated" ON capa_actions FOR SELECT
USING (auth_user_role() IN ('hse', 'admin', 'management', 'supervisor'));
USING (auth_user_role() IN ('hse', 'admin', 'management', 'ssa'));
CREATE POLICY "capa_hse_admin_all" ON capa_actions FOR ALL
USING (auth_user_role() IN ('hse', 'admin'));
@@ -108,7 +108,7 @@ CREATE POLICY "dosh_hse_admin" ON dosh_reports FOR ALL
-- notifications_log (final state after migration 19 fix)
CREATE POLICY "notifications_insert_elevated" ON notifications_log FOR INSERT
WITH CHECK (auth_user_role() IN ('hse', 'admin', 'supervisor'));
WITH CHECK (auth_user_role() IN ('hse', 'admin', 'ssa'));
CREATE POLICY "notifications_read_own" ON notifications_log FOR SELECT
USING (recipient_user_id = app_current_user_id());
CREATE POLICY "notifications_read_admin" ON notifications_log FOR SELECT
@@ -130,7 +130,7 @@ CREATE POLICY "admin_update_settings" ON app_settings FOR ALL
-- incident_addenda
CREATE POLICY "addenda_read" ON incident_addenda FOR SELECT
USING (
auth_user_role() IN ('hse', 'admin', 'supervisor', 'management')
auth_user_role() IN ('hse', 'admin', 'ssa', 'management')
OR EXISTS (
SELECT 1 FROM incidents i
WHERE i.id = incident_id AND i.reported_by = app_current_user_id()
@@ -139,5 +139,5 @@ CREATE POLICY "addenda_read" ON incident_addenda FOR SELECT
CREATE POLICY "addenda_insert" ON incident_addenda FOR INSERT
WITH CHECK (
author = app_current_user_id()
AND auth_user_role() IN ('hse', 'admin', 'supervisor')
AND auth_user_role() IN ('hse', 'admin', 'ssa')
);
+2 -2
View File
@@ -16,7 +16,7 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Enums
-- ---------------------------------------------------------------------------
CREATE TYPE user_role AS ENUM (
'reporter', 'supervisor', 'hse', 'capa_owner', 'management', 'admin'
'ssa', 'hse', 'management', 'admin'
);
CREATE TYPE incident_type AS ENUM (
@@ -80,7 +80,7 @@ CREATE TABLE users (
name TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '' UNIQUE,
phone TEXT,
role user_role NOT NULL DEFAULT 'reporter',
role user_role NOT NULL DEFAULT 'ssa',
department TEXT,
site_id UUID REFERENCES sites(id),
active BOOLEAN NOT NULL DEFAULT true,
+11 -9
View File
@@ -1,26 +1,28 @@
// lib/auth/roles.ts
// 'ssa' = Site Safety Assistant. Replaces the former reporter, supervisor and capa_owner roles.
export type UserRole =
| 'reporter'
| 'supervisor'
| 'ssa'
| 'hse'
| 'capa_owner'
| 'management'
| 'admin'
export const ALL_ROLES: UserRole[] = [
'reporter',
'supervisor',
'ssa',
'hse',
'capa_owner',
'management',
'admin',
]
export const ROLE_LABELS: Record<UserRole, string> = {
ssa: 'Site Safety Assistant (SSA)',
hse: 'HSE',
management: 'Management',
admin: 'Admin',
}
export const ROLE_HOME: Record<UserRole, string> = {
reporter: '/reporter',
supervisor: '/supervisor',
ssa: '/ssa',
hse: '/hse',
capa_owner: '/capa-owner',
management: '/management',
admin: '/admin',
}
+2 -2
View File
@@ -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),
+1 -1
View File
@@ -97,7 +97,7 @@ export async function escalateOverdueCapa(): Promise<{ notified: number }> {
.from(users)
.where(and(
eq(users.siteId, capa.siteId!),
inArray(users.role, ['hse', 'supervisor', 'management']),
inArray(users.role, ['hse', 'ssa', 'management']),
))
)
to.push(...hseUsers.map(u => u.email).filter(Boolean) as string[])
+1 -1
View File
@@ -15,7 +15,7 @@ export async function sendNewIncidentEmail(
db.select({ email: users.email })
.from(users)
.where(and(
inArray(users.role, ['supervisor', 'hse']),
inArray(users.role, ['ssa', 'hse']),
eq(users.siteId, siteId),
))
)
+1 -1
View File
@@ -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', () => ({
+2 -2
View File
@@ -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 () => {
+1 -1
View File
@@ -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)
})
+1 -1
View File
@@ -50,7 +50,7 @@ describe('AppShell', () => {
})
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="ssa" userName="Ada"><span /></AppShell>)
expect(container.querySelector('header form')).toBeNull()
})
+5 -7
View File
@@ -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')
})
})
+3 -3
View File
@@ -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')
})