Compare commits
3
Commits
701fefd286
...
4ec37bd078
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ec37bd078 | ||
|
|
f52e63ad09 | ||
|
|
813395700f |
@@ -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.
|
||||
|
||||
@@ -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({
|
||||
+2
-2
@@ -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} />
|
||||
+2
-2
@@ -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}
|
||||
+2
-2
@@ -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>
|
||||
@@ -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,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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(() => ({}))
|
||||
|
||||
@@ -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,
|
||||
}])
|
||||
}
|
||||
|
||||
@@ -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 =>
|
||||
|
||||
@@ -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),
|
||||
))
|
||||
)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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,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
@@ -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
@@ -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
@@ -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
@@ -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),
|
||||
|
||||
@@ -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[])
|
||||
|
||||
@@ -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),
|
||||
))
|
||||
)
|
||||
|
||||
@@ -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', () => ({
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
|
||||
@@ -49,8 +49,13 @@ describe('AppShell', () => {
|
||||
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', () => {
|
||||
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()
|
||||
})
|
||||
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user