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

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 11:34:05 +08:00
adminandClaude Haiku 4.5 69e510af74 feat(capa): restyle the CAPA detail page, verification form, close card, owner actions and notes
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 11:20:57 +08:00
adminandClaude Haiku 4.5 04437926c2 feat(capa): replace the CAPA board with a workspace (TableCard list and status board) with search, filters and saved views
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 10:47:04 +08:00
adminandClaude Haiku 4.5 9dca2a51d2 feat(capa): add pure list helpers for filtering, saved views, sorting and paging
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 10:26:34 +08:00
adminandClaude Haiku 4.5 9f0331d190 docs: add IMS Admin refresh slice 2 (CAPA) implementation plan
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 10:20:01 +08:00
adminandClaude Haiku 4.5 87f553321b fix(design): correct the incident list footer range on empty and out-of-range pages
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 09:43:44 +08:00
adminandClaude Haiku 4.5 582504c24b feat(design): colour banners and badges by meaning, document slice 1 and update design notes
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 09:36:01 +08:00
adminandClaude Haiku 4.5 a64b951922 feat(design): migrate the Incidents list to TableCard with server-side views, sort, filters and paging
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 09:33:44 +08:00
adminandClaude Haiku 4.5 9ba708ecb7 feat(design): add AppShell, MobileShell and the notifications drawer
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 09:31:12 +08:00
adminandClaude Haiku 4.5 32dd42ac79 feat(design): add TableCard (views, toolbar, sortable header, selection, bulk bar, footer pager, empty, mobile list)
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 09:29:35 +08:00
adminandClaude Haiku 4.5 2a5b9332c7 feat(design): add IMS Admin primitives (Button, StatusTag, Checkbox, FilterChip, Segmented, Avatar, Drawer) and restyle Field, Card, Modal
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 09:28:34 +08:00
adminandClaude Haiku 4.5 01343d732e feat(design): switch to IMS Admin tokens, Geist and the 1px-rule gate
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 09:26:08 +08:00
adminandClaude Haiku 4.5 9ed8c97c24 docs: add IMS Admin refresh slice 1 implementation plan
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 09:21:28 +08:00
adminandClaude Haiku 4.5 f117605775 docs(design): add design.md for the IMS Admin refresh and track its mockup references
Derived from IMS Admin Spec.dc.html and IMS Admin.dc.html. Defines tokens,
components (StatusTag, TableCard, shells, drawer), screen index, build order
and the changes from the live Modernist build. CLAUDE.md already cites it as
the source of truth.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-10-01 08:37:36 +08:00
90 changed files with 10779 additions and 1646 deletions
+1 -1
View File
@@ -91,7 +91,7 @@ Source of truth: `design-system/design.md`. Visual references: `design-system/IM
- Incident evidence photos stay full colour.
- New pattern needed? Check design.md first. If it isn't there, design it in the design tool, then add it to design.md in the same PR as the component.
- Gotcha: never write `*/` inside a CSS comment in `globals.css`; it ends the comment and silently swallows the `@theme` block.
- Run `npm run check:design` before committing UI changes; it must print `design gates: clean`. Update `scripts/check-design-gates.mjs` first: allow `rounded-*`, flag `border-b-2`/`border-2`, flag Archivo and `#ec3013`.
- Run `npm run check:design` before committing UI changes; it must print `design gates: clean`. The gate flags 2px borders, `Archivo`, hard-coded hex, `bg-white`, `shadow-xl/2xl`, centered button labels and off-palette hues; rounded corners are allowed. Extend `scripts/check-design-gates.mjs` when design.md adds a rule.
## graphify
When graphify-out/graph.json exists:
+2 -2
View File
@@ -10,11 +10,11 @@ export default async function LoginPage({ searchParams }: Props) {
return (
<main className="min-h-screen flex items-center justify-center bg-ground p-4">
{message === 'password_reset' && (
<div className="fixed top-4 left-1/2 -translate-x-1/2 bg-neutral-100 border border-divider text-ink text-sm px-4 py-2 shadow">
<div className="fixed top-4 left-1/2 -translate-x-1/2 bg-st-green-bg text-st-green-fg text-[13px] px-4 py-2 rounded-md shadow-float">
Password updated — sign in with your new password.
</div>
)}
<div className="bg-surface border-2 border-divider p-8 w-full max-w-sm">
<div className="bg-surface rounded-xl shadow-card p-8 w-full max-w-sm">
<LoginForm />
</div>
</main>
+80 -53
View File
@@ -2,6 +2,7 @@ export const dynamic = 'force-dynamic'
import { notFound, redirect } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { capaActions, incidents, users } from '@/lib/db/schema'
@@ -10,12 +11,23 @@ import { aliasedTable } from 'drizzle-orm'
import { VerifyForm } from '@/components/capa/verify-form'
import { CloseCapaButton } from '@/components/capa/close-capa-button'
import { CapaOwnerActions } from '@/components/capa/capa-owner-actions'
import { PriorityTag } from '@/components/ui/status-tag'
import { Avatar } from '@/components/ui/avatar'
import { PriorityTag, StatusTag } from '@/components/ui/status-tag'
import { daysLate } from '@/lib/capa/list'
interface Props {
params: Promise<{ id: string }>
}
function Row({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="flex items-center justify-between gap-3 border-b border-rule py-2.5 last:border-0">
<dt className="text-xs text-muted">{label}</dt>
<dd className="text-right text-[13px]">{children}</dd>
</div>
)
}
export default async function CapaDetailPage({ params }: Props) {
const { id } = await params
const session = await getSession()
@@ -50,75 +62,90 @@ export default async function CapaDetailPage({ params }: Props) {
const isHse = session && ['hse', 'admin'].includes(session.role)
const status = capa.status
const today = new Date().toISOString().slice(0, 10)
const pastDue = (status === 'open' || status === 'in_progress') && Boolean(capa.dueDate) && capa.dueDate < today
const shownStatus = pastDue ? 'overdue' : status
const late = shownStatus === 'overdue' ? daysLate(capa.dueDate, today) : 0
const canAct = ['open', 'in_progress', 'overdue', 'reopened'].includes(status) &&
(isHse || session?.sub === capa.ownerUserId)
return (
<main className="max-w-2xl mx-auto px-4 py-6">
<Link href="/hse/capa" className="text-sm text-accent-700 hover:underline mb-4 inline-block">
← CAPA Board
<div className="space-y-4 px-4 py-5 md:px-8 md:py-6">
<Link href="/hse/capa" className="inline-flex items-center gap-1 text-[13px] text-accent hover:underline">
<ArrowLeft size={14} strokeWidth={2} aria-hidden />
CAPA
</Link>
<div className="bg-surface shadow-sm p-5 mb-4 space-y-4">
<div className="flex items-start justify-between">
<div>
<p className="text-xs text-gray-500 mb-1">
Incident: {capa.incidentRefNo ?? '—'}
</p>
<p className="text-gray-900 font-medium">{capa.description}</p>
</div>
<div className="space-y-2">
<h1 className="text-xl font-[650]">{capa.description}</h1>
<div className="flex flex-wrap items-center gap-2">
<StatusTag status={shownStatus} />
<PriorityTag priority={capa.priority} />
<span className="text-[13px] text-muted">
From{' '}
<Link href={`/hse/incidents/${capa.incidentId}`} className="font-mono text-[12.5px] text-accent hover:underline">
{capa.incidentRefNo ?? '—'}
</Link>
</span>
</div>
{capa.rootCauseRef && <p className="text-[13px] text-muted">Root cause: {capa.rootCauseRef}</p>}
</div>
<div className="grid grid-cols-2 gap-3 text-sm">
<div className="grid gap-4 lg:grid-cols-[1fr_320px]">
<div className="space-y-4">
{canAct && (
<div>
<p className="text-xs text-gray-500">Owner</p>
<p className="text-gray-800">{capa.ownerName ?? '—'}</p>
</div>
<div>
<p className="text-xs text-gray-500">Department</p>
<p className="text-gray-800">{capa.department}</p>
</div>
<div>
<p className="text-xs text-gray-500">Due Date</p>
<p className="text-gray-800">{capa.dueDate}</p>
</div>
<div>
<p className="text-xs text-gray-500">Status</p>
<p className="text-gray-800 capitalize">{status.replace(/_/g, ' ')}</p>
</div>
{capa.ownerNotes && (
<div className="col-span-2">
<p className="text-xs text-gray-500">Owner Notes</p>
<p className="text-sm text-gray-800 whitespace-pre-wrap">{capa.ownerNotes}</p>
</div>
)}
</div>
{capa.rootCauseRef && (
<div>
<p className="text-xs text-gray-500">Root Cause Reference</p>
<p className="text-sm text-gray-800">{capa.rootCauseRef}</p>
<CapaOwnerActions capaId={id} currentStatus={status} />
</div>
)}
{isHse && status === 'pending_verification' && <VerifyForm capaId={id} />}
{isHse && status === 'verified' && <CloseCapaButton capaId={id} />}
{(capa.ownerNotes || capa.completedAt) && (
<section className="space-y-2 rounded-xl bg-surface p-5 shadow-card">
<h2 className="text-sm font-semibold">Completion report</h2>
{capa.completedAt && (
<p className="text-xs text-gray-500">
Completed: {new Date(capa.completedAt).toLocaleString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })}
<p className="text-xs text-muted">
Completed {new Date(capa.completedAt).toLocaleString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })}
</p>
)}
{capa.ownerNotes && (
<p className="whitespace-pre-wrap text-[13px] text-ink-3">{capa.ownerNotes}</p>
)}
</section>
)}
</div>
{['open', 'in_progress', 'overdue', 'reopened'].includes(status) &&
(isHse || session?.sub === capa.ownerUserId) && (
<CapaOwnerActions capaId={id} currentStatus={status} />
<aside>
<section className="rounded-xl bg-surface p-5 shadow-card">
<h2 className="mb-1 text-sm font-semibold">Details</h2>
<dl>
<Row label="Owner">
{capa.ownerName ? (
<span className="inline-flex items-center gap-2">
<Avatar name={capa.ownerName} />
{capa.ownerName}
</span>
) : (
'—'
)}
{isHse && status === 'pending_verification' && (
<VerifyForm capaId={id} />
</Row>
<Row label="Department">{capa.department}</Row>
<Row label="Priority"><PriorityTag priority={capa.priority} /></Row>
<Row label="Due">
{capa.dueDate}
{late > 0 && <span className="ml-1.5 text-xs text-danger">{`${late} day${late === 1 ? '' : 's'} late`}</span>}
</Row>
{capa.completedAt && (
<Row label="Completed">
{new Date(capa.completedAt).toLocaleDateString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })}
</Row>
)}
{isHse && status === 'verified' && (
<CloseCapaButton capaId={id} />
)}
</main>
</dl>
</section>
</aside>
</div>
</div>
)
}
+10 -16
View File
@@ -1,13 +1,13 @@
export const dynamic = 'force-dynamic'
import { redirect } from 'next/navigation'
import Link from 'next/link'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { capaActions, incidents, users } from '@/lib/db/schema'
import { eq, asc } from 'drizzle-orm'
import { aliasedTable } from 'drizzle-orm'
import { CapaBoard } from '@/components/capa/capa-board'
import { CapaWorkspace } from '@/components/capa/capa-workspace'
import type { CapaRow, CapaStatus } from '@/lib/capa/list'
export default async function CapaListPage() {
const session = await getSession()
@@ -34,29 +34,23 @@ export default async function CapaListPage() {
)
const today = new Date().toISOString().slice(0, 10)
const capas = rows.map(r => ({
const capas: CapaRow[] = rows.map(r => ({
id: r.id,
incident_id: r.incidentId,
description: r.description,
department: r.department,
due_date: r.dueDate,
priority: r.priority,
status: (r.status === 'open' || r.status === 'in_progress') && r.dueDate && r.dueDate < today
? 'overdue' as const
: r.status,
incidents: { reference_no: r.incidentRefNo ?? null },
owner: r.ownerName ? { name: r.ownerName } : null,
status: ((r.status === 'open' || r.status === 'in_progress') && r.dueDate && r.dueDate < today
? 'overdue'
: r.status) as CapaStatus,
incident_ref: r.incidentRefNo ?? null,
owner_name: r.ownerName ?? null,
}))
return (
<main className="max-w-6xl mx-auto px-4 py-6">
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-bold text-gray-900">CAPA Board</h1>
<Link href="/hse/incidents" className="text-sm text-accent-700 hover:underline">
← Incidents
</Link>
<div className="px-4 py-5 md:px-8 md:py-6">
<CapaWorkspace capas={capas} today={today} />
</div>
<CapaBoard capas={capas} />
</main>
)
}
+2 -2
View File
@@ -187,8 +187,8 @@ export default async function HseDashboardPage({
{(tab === 'overview') && (
<>
{now.getMonth() === 0 && (
<div className="bg-accent-100 border border-accent-300 p-4 mb-6">
<p className="text-sm text-accent-700">
<div className="bg-st-amber-bg rounded-xl p-4 mb-6">
<p className="text-sm text-st-amber-fg">
<strong>JKKP 8 annual register due:</strong> the {now.getFullYear() - 1} register must be
submitted to DOSH before 31 January {now.getFullYear()}.{' '}
<a href={`/api/reports/jkkp8?year=${now.getFullYear() - 1}`} className="underline font-medium">
@@ -1,5 +1,6 @@
import { notFound, redirect } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { incidents } from '@/lib/db/schema'
@@ -30,15 +31,18 @@ export default async function NewCapaPage({ params }: Props) {
if (!incident) notFound()
return (
<main className="max-w-lg mx-auto px-4 py-6">
<Link href={`/hse/incidents/${id}`} className="text-sm text-accent-700 hover:underline mb-4 inline-block">
← Back to incident
<div className="max-w-xl space-y-4 px-4 py-5 md:px-8 md:py-6">
<Link href={`/hse/incidents/${id}`} className="inline-flex items-center gap-1 text-[13px] text-accent hover:underline">
<ArrowLeft size={14} strokeWidth={2} aria-hidden />
Back to incident
</Link>
<h1 className="text-xl font-bold text-gray-900 mb-1">Add CAPA Action</h1>
<p className="text-sm text-gray-500 mb-6">
{incident.referenceNo ?? id}
</p>
<div>
<h1 className="text-xl font-[650]">Add CAPA action</h1>
<p className="mt-0.5 font-mono text-[12.5px] text-muted">{incident.referenceNo ?? id}</p>
</div>
<div className="rounded-xl bg-surface p-5 shadow-card">
<CapaForm incidentId={id} />
</main>
</div>
</div>
)
}
+22 -89
View File
@@ -1,106 +1,39 @@
export const dynamic = 'force-dynamic'
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { incidents, sites, zones, trucks, users } from '@/lib/db/schema'
import { eq, and, or, ilike, desc, asc, sql } from 'drizzle-orm'
import { aliasedTable } from 'drizzle-orm'
import { IncidentList, type Incident } from '@/components/incidents/incident-list'
import { Pagination } from '@/components/incidents/pagination'
import { IncidentFilters, type SiteOption, type TruckOption } from '@/components/incidents/incident-filters'
const PAGE_SIZE = 25
import { buttonClass } from '@/components/ui/button'
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 HseInboxPage({
searchParams,
}: {
searchParams: Promise<{ page?: string; q?: string; status?: string; type?: string; site_id?: string; truck_id?: string }>
searchParams: Promise<Record<string, string | undefined>>
}) {
const session = await getSession()
if (!session) redirect('/login')
const params = await searchParams
const page = Math.max(1, Number.parseInt(params.page ?? '1', 10) || 1)
const from = (page - 1) * PAGE_SIZE
const reporterAlias = aliasedTable(users, 'reporter')
const conditions = []
if (params.q) conditions.push(or(ilike(incidents.referenceNo, `%${params.q}%`), ilike(incidents.description, `%${params.q}%`)))
if (params.status) conditions.push(eq(incidents.status, params.status as never))
if (params.type) conditions.push(eq(incidents.incidentType, params.type as never))
if (params.site_id) conditions.push(eq(incidents.siteId, params.site_id))
if (params.truck_id) conditions.push(eq(incidents.truckId, params.truck_id))
const where = conditions.length ? and(...conditions) : undefined
const [[countRow], incidentRows, siteRows, truckRows] = await Promise.all([
asAdmin(db =>
db.select({ count: sql<number>`count(*)` })
.from(incidents)
.where(where)
),
asAdmin(db =>
db.select({
id: incidents.id,
referenceNo: incidents.referenceNo,
incidentType: incidents.incidentType,
status: incidents.status,
severity: incidents.severity,
reportedAt: incidents.reportedAt,
siteName: sites.name,
zoneName: zones.name,
reporterName: reporterAlias.name,
truckNo: trucks.truckNo,
})
.from(incidents)
.leftJoin(sites, eq(incidents.siteId, sites.id))
.leftJoin(zones, eq(incidents.zoneId, zones.id))
.leftJoin(reporterAlias, eq(incidents.reportedBy, reporterAlias.id))
.leftJoin(trucks, eq(incidents.truckId, trucks.id))
.where(where)
.orderBy(desc(incidents.reportedAt))
.limit(PAGE_SIZE)
.offset(from)
),
asAdmin(db =>
db.select({ id: sites.id, name: sites.name }).from(sites).orderBy(asc(sites.name))
),
asAdmin(db =>
db.select({ id: trucks.id, truckNo: trucks.truckNo })
.from(trucks)
.where(eq(trucks.active, true))
.orderBy(asc(trucks.truckNo))
),
])
const total = Number(countRow?.count ?? 0)
const incidentList: Incident[] = incidentRows.map(r => ({
id: r.id,
reference_no: r.referenceNo,
incident_type: r.incidentType,
status: r.status,
severity: r.severity,
reported_at: r.reportedAt.toISOString(),
sites: r.siteName ? { name: r.siteName } : null,
zones: r.zoneName ? { name: r.zoneName } : null,
trucks: r.truckNo ? { truck_no: r.truckNo } : null,
reporter: r.reporterName ? { name: r.reporterName } : null,
}))
const siteOptions: SiteOption[] = siteRows.map(s => ({ id: s.id, name: s.name }))
const truckOptions: TruckOption[] = truckRows.map(t => ({ id: t.id, truck_no: t.truckNo }))
const params = parseListParams(await searchParams)
const data = await loadIncidentList(params)
return (
<main className="max-w-4xl mx-auto px-4 py-6">
<div className="flex items-center justify-between mb-4">
<h1 className="text-2xl font-bold text-gray-900">Incident Inbox</h1>
<span className="text-sm text-gray-500">{total} incidents</span>
<div className="px-4 py-5 md:px-8 md:py-6 space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-[22px] md:text-xl font-[650]">Incidents</h1>
<Link href="/report" className={buttonClass('primary')}>Report incident</Link>
</div>
<IncidentTable
incidents={data.incidents}
basePath="/hse"
total={data.total}
counts={data.counts}
params={params}
sites={data.sites}
trucks={data.trucks}
/>
</div>
<IncidentFilters sites={siteOptions} trucks={truckOptions} />
<IncidentList incidents={incidentList} basePath="/hse" />
<Pagination page={page} pageSize={PAGE_SIZE} total={total} href="/hse/incidents" />
</main>
)
}
+3 -10
View File
@@ -2,7 +2,7 @@ export const dynamic = 'force-dynamic'
import { redirect } from 'next/navigation'
import { getSession } from '@/lib/auth/get-session'
import { Sidebar } from '@/components/layout/sidebar'
import { AppShell } from '@/components/layout/app-shell'
export default async function ProtectedLayout({
children,
@@ -13,15 +13,8 @@ export default async function ProtectedLayout({
if (!session) redirect('/login')
return (
<div className="min-h-screen bg-ground">
<Sidebar
role={session.role}
userName={session.name}
userEmail=""
/>
<div className="sm:ml-60 pb-16 sm:pb-0">
<AppShell role={session.role} userName={session.name}>
{children}
</div>
</div>
</AppShell>
)
}
@@ -106,9 +106,9 @@ export default async function ReporterIncidentDetail({
<div key={c.id} className="flex items-start justify-between gap-3 text-sm">
<p className="text-gray-700 flex-1">{c.description}</p>
<span className={`text-xs px-2 py-0.5 shrink-0 ${
c.status === 'verified' ? 'bg-neutral-100 text-ink' :
c.status === 'pending_verification' ? 'bg-accent-100 text-accent-700' :
'bg-gray-100 text-gray-600'
c.status === 'verified' ? 'bg-st-green-bg text-st-green-fg' :
c.status === 'pending_verification' ? 'bg-st-indigo-bg text-st-indigo-fg' :
'bg-st-grey-bg text-st-grey-fg'
}`}>{c.status.replace(/_/g, ' ')}</span>
</div>
))}
+22 -89
View File
@@ -1,106 +1,39 @@
export const dynamic = 'force-dynamic'
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session'
import { incidents, sites, zones, trucks, users } from '@/lib/db/schema'
import { eq, and, or, ilike, desc, asc, sql } from 'drizzle-orm'
import { aliasedTable } from 'drizzle-orm'
import { IncidentList, type Incident } from '@/components/incidents/incident-list'
import { Pagination } from '@/components/incidents/pagination'
import { IncidentFilters, type SiteOption, type TruckOption } from '@/components/incidents/incident-filters'
const PAGE_SIZE = 25
import { buttonClass } from '@/components/ui/button'
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({
searchParams,
}: {
searchParams: Promise<{ page?: string; q?: string; status?: string; type?: string; site_id?: string; truck_id?: string }>
searchParams: Promise<Record<string, string | undefined>>
}) {
const session = await getSession()
if (!session) redirect('/login')
const params = await searchParams
const page = Math.max(1, Number.parseInt(params.page ?? '1', 10) || 1)
const from = (page - 1) * PAGE_SIZE
const reporterAlias = aliasedTable(users, 'reporter')
const conditions = []
if (params.q) conditions.push(or(ilike(incidents.referenceNo, `%${params.q}%`), ilike(incidents.description, `%${params.q}%`)))
if (params.status) conditions.push(eq(incidents.status, params.status as never))
if (params.type) conditions.push(eq(incidents.incidentType, params.type as never))
if (params.site_id) conditions.push(eq(incidents.siteId, params.site_id))
if (params.truck_id) conditions.push(eq(incidents.truckId, params.truck_id))
const where = conditions.length ? and(...conditions) : undefined
const [[countRow], incidentRows, siteRows, truckRows] = await Promise.all([
asAdmin(db =>
db.select({ count: sql<number>`count(*)` })
.from(incidents)
.where(where)
),
asAdmin(db =>
db.select({
id: incidents.id,
referenceNo: incidents.referenceNo,
incidentType: incidents.incidentType,
status: incidents.status,
severity: incidents.severity,
reportedAt: incidents.reportedAt,
siteName: sites.name,
zoneName: zones.name,
reporterName: reporterAlias.name,
truckNo: trucks.truckNo,
})
.from(incidents)
.leftJoin(sites, eq(incidents.siteId, sites.id))
.leftJoin(zones, eq(incidents.zoneId, zones.id))
.leftJoin(reporterAlias, eq(incidents.reportedBy, reporterAlias.id))
.leftJoin(trucks, eq(incidents.truckId, trucks.id))
.where(where)
.orderBy(desc(incidents.reportedAt))
.limit(PAGE_SIZE)
.offset(from)
),
asAdmin(db =>
db.select({ id: sites.id, name: sites.name }).from(sites).orderBy(asc(sites.name))
),
asAdmin(db =>
db.select({ id: trucks.id, truckNo: trucks.truckNo })
.from(trucks)
.where(eq(trucks.active, true))
.orderBy(asc(trucks.truckNo))
),
])
const total = Number(countRow?.count ?? 0)
const incidentList: Incident[] = incidentRows.map(r => ({
id: r.id,
reference_no: r.referenceNo,
incident_type: r.incidentType,
status: r.status,
severity: r.severity,
reported_at: r.reportedAt.toISOString(),
sites: r.siteName ? { name: r.siteName } : null,
zones: r.zoneName ? { name: r.zoneName } : null,
trucks: r.truckNo ? { truck_no: r.truckNo } : null,
reporter: r.reporterName ? { name: r.reporterName } : null,
}))
const siteOptions: SiteOption[] = siteRows.map(s => ({ id: s.id, name: s.name }))
const truckOptions: TruckOption[] = truckRows.map(t => ({ id: t.id, truck_no: t.truckNo }))
const params = parseListParams(await searchParams)
const data = await loadIncidentList(params)
return (
<main className="max-w-4xl mx-auto px-4 py-6">
<div className="flex items-center justify-between mb-4">
<h1 className="text-2xl font-bold text-gray-900">Incident Inbox</h1>
<span className="text-sm text-gray-500">{total} incidents</span>
<div className="px-4 py-5 md:px-8 md:py-6 space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-[22px] md:text-xl font-[650]">Incidents</h1>
<Link href="/report" className={buttonClass('primary')}>Report incident</Link>
</div>
<IncidentTable
incidents={data.incidents}
basePath="/supervisor"
total={data.total}
counts={data.counts}
params={params}
sites={data.sites}
trucks={data.trucks}
/>
</div>
<IncidentFilters sites={siteOptions} trucks={truckOptions} />
<IncidentList incidents={incidentList} basePath="/supervisor" />
<Pagination page={page} pageSize={PAGE_SIZE} total={total} href="/supervisor/incidents" />
</main>
)
}
+4 -6
View File
@@ -6,8 +6,7 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit'
import { incidents, sites, zones, auditLog } from '@/lib/db/schema'
import { eq, and, gte, desc } from 'drizzle-orm'
import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
import { createLocalLLMClient } from '@/lib/claude/client'
type ZoneAggregate = {
zone: string
@@ -103,13 +102,12 @@ export async function POST() {
return NextResponse.json({ error: 'Rate limit: wait 60 seconds between AI requests' }, { status: 429 })
}
const deepseekKey = await getApiKey('DEEPSEEK_API_KEY')
const client = createDeepSeekClient(deepseekKey)
const client = createLocalLLMClient()
let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try {
res = await client.chat.completions.create({
model: 'deepseek-v4-pro',
model: 'qwen3:14b',
max_tokens: 2048,
messages: [
{
@@ -168,7 +166,7 @@ Flag only zones with rising or elevated risk (at most 5 flags; do not flag healt
await withUser(session.sub, async tx =>
writeAuditLog(tx, 'incidents', session.sub, 'ai_risk_flags',
{ flags, summary: input.summary, model: 'deepseek-v4-pro' })
{ flags, summary: input.summary, model: 'qwen3:14b' })
)
return NextResponse.json({ flags, summary: input.summary })
+4 -6
View File
@@ -6,8 +6,7 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit'
import { incidents, auditLog, sites, zones } from '@/lib/db/schema'
import { eq, and, gte, sql } from 'drizzle-orm'
import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
import { createLocalLLMClient } from '@/lib/claude/client'
export async function POST(
_request: NextRequest,
@@ -32,8 +31,7 @@ export async function POST(
if (Number(rateRow?.cnt ?? 0) > 0)
return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 })
const deepseekKey = await getApiKey('DEEPSEEK_API_KEY')
const client = createDeepSeekClient(deepseekKey)
const client = createLocalLLMClient()
const [incident] = await withUser(session.sub, async tx =>
tx.select({
@@ -59,7 +57,7 @@ export async function POST(
let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try {
res = await client.chat.completions.create({
model: 'deepseek-v4-pro',
model: 'qwen3:14b',
max_tokens: 2048,
messages: [
{
@@ -107,7 +105,7 @@ Provide 3–5 Why steps drilling from immediate cause to root cause. Frame CAPA
await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'incidents', id, 'ai_rca_draft', {
root_cause_summary: draft.root_cause_summary as string,
model: 'deepseek-v4-pro',
model: 'qwen3:14b',
})
})
@@ -6,8 +6,7 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit'
import { incidents, auditLog } from '@/lib/db/schema'
import { eq, and, gte, sql } from 'drizzle-orm'
import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
import { createLocalLLMClient } from '@/lib/claude/client'
export async function POST(
_request: NextRequest,
@@ -32,8 +31,7 @@ export async function POST(
if (Number(rateRow?.cnt ?? 0) > 0)
return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 })
const deepseekKey = await getApiKey('DEEPSEEK_API_KEY')
const client = createDeepSeekClient(deepseekKey)
const client = createLocalLLMClient()
const [incident] = await withUser(session.sub, async tx =>
tx.select({
@@ -50,7 +48,7 @@ export async function POST(
let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try {
res = await client.chat.completions.create({
model: 'deepseek-v4-pro',
model: 'qwen3:14b',
max_tokens: 1024,
messages: [
{
@@ -105,7 +103,7 @@ Output exactly this JSON structure:
}
await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'incidents', id, 'ai_triage_suggest', { suggestion: input, model: 'deepseek-v4-pro' })
await writeAuditLog(tx, 'incidents', id, 'ai_triage_suggest', { suggestion: input, model: 'qwen3:14b' })
})
return NextResponse.json(input)
+4 -6
View File
@@ -6,8 +6,7 @@ import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit'
import { auditLog } from '@/lib/db/schema'
import { eq, and, gte, sql } from 'drizzle-orm'
import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
import { createLocalLLMClient } from '@/lib/claude/client'
export async function POST(request: NextRequest) {
const session = await getSession()
@@ -26,8 +25,7 @@ export async function POST(request: NextRequest) {
if (Number(rateRow?.cnt ?? 0) > 0)
return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 })
const deepseekKey = await getApiKey('DEEPSEEK_API_KEY')
const client = createDeepSeekClient(deepseekKey)
const client = createLocalLLMClient()
let body: { description?: string; incident_type?: string }
try {
@@ -42,7 +40,7 @@ export async function POST(request: NextRequest) {
let res: Awaited<ReturnType<typeof client.chat.completions.create>>
try {
res = await client.chat.completions.create({
model: 'deepseek-v4-pro',
model: 'qwen3:14b',
max_tokens: 1024,
messages: [
{
@@ -89,7 +87,7 @@ Scoring criteria: specificity (location, time, persons involved), completeness (
await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'incidents', session.sub, 'ai_quality_check', {
score: input.score, passes: input.passes, model: 'deepseek-v4-pro',
score: input.score, passes: input.passes, model: 'qwen3:14b',
})
})
+102 -89
View File
@@ -1,50 +1,65 @@
@import "tailwindcss";
/* Modernist tokens. Source of truth: the Modernist styles.css under design-system/_ds.
/* IMS Admin refresh tokens. Source of truth: design-system/design.md section 2.
Static emits every variable so plain CSS can use var(--color-*) too. */
@theme static {
--color-bg: #f3f2f2;
--color-surface: #eae9e9;
--color-text: #201e1d;
--color-accent: #ec3013;
--color-accent-2: #e15b47;
--color-divider: color-mix(in srgb, #201e1d 40%, transparent);
--color-ink: #1f1f1f;
--color-ink-2: #303030;
--color-ink-3: #4a4a4a;
--color-muted: #616161;
--color-faint: #8a8a8a;
--color-rule: #ebebeb;
--color-rule-2: #e3e3e3;
--color-ring: #d4d4d4;
--color-surface: #ffffff;
--color-surface-2: #f7f7f7;
--color-ground: #f1f1f1;
--color-accent: #0f766e;
--color-accent-tint: #f2f7f6;
--color-accent-tint-2: #e6f4f1;
--color-danger: #b3261e;
--color-topbar: #1a1a1a;
/* Utility-friendly aliases: bg-ground, text-ink */
--color-ground: var(--color-bg);
--color-ink: var(--color-text);
/* Status pills: a dark step on a light tint, one pair per hue. */
--color-st-amber-bg: #fff1c2;
--color-st-amber-fg: #6b4a00;
--color-st-blue-bg: #e0efff;
--color-st-blue-fg: #00527c;
--color-st-violet-bg: #ede7ff;
--color-st-violet-fg: #4b2e99;
--color-st-orange-bg: #ffe6cf;
--color-st-orange-fg: #7a3a00;
--color-st-indigo-bg: #e3e8ff;
--color-st-indigo-fg: #2c3e8f;
--color-st-green-bg: #d7f4e3;
--color-st-green-fg: #0c5132;
--color-st-grey-bg: #ebebeb;
--color-st-grey-fg: #4a4a4a;
--color-st-red-bg: #fee3e0;
--color-st-red-fg: #8e1f0b;
--color-neutral-100: #f8f4f4;
--color-neutral-200: #eae7e7;
--color-neutral-300: #d7d3d3;
--color-neutral-400: #bab6b6;
--color-neutral-500: #9b9797;
--color-neutral-600: #7d7979;
--color-neutral-700: #605d5d;
--color-neutral-800: #444141;
--color-neutral-900: #2d2b2b;
/* Legacy names kept, re-valued, until every page is migrated. */
--color-divider: #e3e3e3;
--color-neutral-100: #f7f7f7;
--color-neutral-200: #ebebeb;
--color-neutral-300: #d4d4d4;
--color-neutral-400: #c4c4c4;
--color-neutral-500: #8a8a8a;
--color-neutral-600: #616161;
--color-neutral-700: #4a4a4a;
--color-neutral-800: #303030;
--color-neutral-900: #1f1f1f;
--color-accent-100: #fff2ef;
--color-accent-200: #ffe0d9;
--color-accent-300: #ffc4b8;
--color-accent-400: #ff9783;
--color-accent-500: #ff563c;
--color-accent-600: #dd2b0f;
--color-accent-700: #ae1800;
--color-accent-800: #7c1405;
--color-accent-900: #4d170e;
--color-accent-100: #e6f4f1;
--color-accent-200: #c5e8e0;
--color-accent-300: #9fd3c7;
--color-accent-400: #5fb3a5;
--color-accent-500: #2b9488;
--color-accent-600: #0c615a;
--color-accent-700: #0b4f47;
--color-accent-800: #083b36;
--color-accent-900: #052a26;
--color-accent-2-100: #fff2ef;
--color-accent-2-200: #ffe0da;
--color-accent-2-300: #ffc4b9;
--color-accent-2-400: #ff9784;
--color-accent-2-500: #ef6853;
--color-accent-2-600: #c94b39;
--color-accent-2-700: #9e3526;
--color-accent-2-800: #71261b;
--color-accent-2-900: #471d16;
/* Existing gray-* utilities render on the neutral ramp. */
--color-gray-50: var(--color-neutral-100);
--color-gray-100: var(--color-neutral-200);
--color-gray-200: var(--color-neutral-300);
@@ -54,11 +69,9 @@
--color-gray-600: var(--color-neutral-700);
--color-gray-700: var(--color-neutral-800);
--color-gray-800: var(--color-neutral-900);
--color-gray-900: var(--color-text);
--color-gray-950: var(--color-text);
--color-gray-900: var(--color-ink);
--color-gray-950: var(--color-ink);
/* Existing blue-* utilities render on the accent ramp. 600 is the canonical
accent; 700 and darker are safe for body-size text. */
--color-blue-50: var(--color-accent-100);
--color-blue-100: var(--color-accent-100);
--color-blue-200: var(--color-accent-200);
@@ -71,59 +84,63 @@
--color-blue-900: var(--color-accent-900);
--color-blue-950: var(--color-accent-900);
/* Existing red-* utilities (errors, destructive) render on the accent ramp;
600 and 700 map to accent-700 so body-size text clears contrast. */
--color-red-50: var(--color-accent-100);
--color-red-100: var(--color-accent-100);
--color-red-200: var(--color-accent-200);
--color-red-300: var(--color-accent-300);
--color-red-400: var(--color-accent-400);
--color-red-500: var(--color-accent-600);
--color-red-600: var(--color-accent-700);
--color-red-700: var(--color-accent-700);
--color-red-800: var(--color-accent-800);
--color-red-900: var(--color-accent-900);
--color-red-50: #fee3e0;
--color-red-100: #fee3e0;
--color-red-200: #f9c4bd;
--color-red-300: #f2a198;
--color-red-400: #e06a5a;
--color-red-500: #c9382a;
--color-red-600: var(--color-danger);
--color-red-700: #8e1f0b;
--color-red-800: #6b1708;
--color-red-900: #4a1005;
/* Zero corner radius, everywhere. */
--radius: 0px;
--radius-xs: 0px;
--radius-sm: 0px;
--radius-md: 0px;
--radius-lg: 0px;
--radius-xl: 0px;
--radius-2xl: 0px;
--radius-3xl: 0px;
--radius-4xl: 0px;
/* Radius scale: 8 buttons, chips, inputs, pills; 12 cards; 14 drawer. */
--radius: 8px;
--radius-xs: 4px;
--radius-sm: 6px;
--radius-md: 8px;
--radius-lg: 8px;
--radius-xl: 12px;
--radius-2xl: 14px;
--radius-3xl: 14px;
--radius-4xl: 14px;
/* Elevation, tuned to the ground. */
--shadow-sm: 0 1px 2px color-mix(in srgb, #2d2b2b 14%, transparent);
--shadow-md: 0 3px 10px color-mix(in srgb, #2d2b2b 16%, transparent);
--shadow-lg: 0 12px 32px color-mix(in srgb, #2d2b2b 22%, transparent);
--shadow-xl: var(--shadow-lg);
--shadow-2xl: var(--shadow-lg);
--shadow-card: 0 0 0 1px rgba(0,0,0,.08), 0 1px 2px rgba(0,0,0,.06);
--shadow-float: 0 0 0 1px rgba(0,0,0,.1), 0 12px 32px rgba(0,0,0,.18);
--shadow-drawer: 0 0 0 1px rgba(0,0,0,.1), 0 24px 60px rgba(0,0,0,.24);
--shadow-primary: inset 0 -1px 0 #000, inset 0 1px 0 rgba(255,255,255,.18), 0 1px 2px rgba(0,0,0,.2);
--shadow-secondary: inset 0 0 0 1px var(--color-ring), 0 1px 0 rgba(0,0,0,.05);
--shadow-input: inset 0 0 0 1px var(--color-faint);
--shadow-chip: inset 0 0 0 1px var(--color-ring);
--shadow-chip-set: inset 0 0 0 1px var(--color-accent-300);
--shadow-sm: 0 1px 2px rgba(0,0,0,.06);
--shadow-md: 0 3px 10px rgba(0,0,0,.12);
--shadow-lg: var(--shadow-float);
--shadow-xl: var(--shadow-float);
--shadow-2xl: var(--shadow-float);
--font-sans: var(--font-archivo), system-ui, sans-serif;
--font-heading: var(--font-archivo), system-ui, sans-serif;
--font-sans: var(--font-geist), system-ui, sans-serif;
--font-mono: var(--font-geist-mono), ui-monospace, SFMono-Regular, Menlo, monospace;
}
@layer base {
html {
background: var(--color-bg);
background: var(--color-ground);
}
body {
background: var(--color-bg);
color: var(--color-text);
background: var(--color-ground);
color: var(--color-ink);
font-family: var(--font-sans);
font-size: 15px;
line-height: 1.55;
font-size: 13px;
line-height: 1.5;
}
h1, h2, h3, h4, h5, h6 {
font-family: var(--font-heading);
font-weight: 800;
line-height: 1.12;
letter-spacing: -0.015em;
font-weight: 650;
line-height: 1.25;
letter-spacing: -0.01em;
}
:focus {
@@ -136,18 +153,18 @@
}
::selection {
background: color-mix(in srgb, var(--color-accent) 30%, transparent);
background: color-mix(in srgb, var(--color-accent) 25%, transparent);
}
input,
textarea,
select {
color: var(--color-text);
color: var(--color-ink);
}
input::placeholder,
textarea::placeholder {
color: color-mix(in srgb, var(--color-text) 55%, transparent);
color: var(--color-faint);
}
button:disabled,
@@ -158,7 +175,3 @@
cursor: not-allowed;
}
}
.grayscale {
filter: grayscale(1) contrast(1.08);
}
+9 -4
View File
@@ -1,11 +1,16 @@
import type { Metadata } from 'next'
import { Archivo } from 'next/font/google'
import { Geist, Geist_Mono } from 'next/font/google'
import './globals.css'
import { I18nProvider } from '@/lib/i18n/context'
import { getLocale, loadMessages } from '@/lib/i18n/server'
const archivo = Archivo({
variable: '--font-archivo',
const geist = Geist({
variable: '--font-geist',
subsets: ['latin'],
})
const geistMono = Geist_Mono({
variable: '--font-geist-mono',
subsets: ['latin'],
})
@@ -25,7 +30,7 @@ export default async function RootLayout({
return (
<html
lang={locale}
className={`${archivo.variable} h-full antialiased`}
className={`${geist.variable} ${geistMono.variable} h-full antialiased`}
>
<head>
<link rel="manifest" href="/manifest.json" />
+1 -1
View File
@@ -30,7 +30,7 @@ export function AdminPanel({ users, sites, siteOptions, trucks }: Props) {
<button
key={t.id}
onClick={() => setTab(t.id)}
className={`px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors cursor-pointer ${
className={`px-4 py-2.5 text-sm font-medium border-b -mb-px transition-colors cursor-pointer ${
tab === t.id
? 'border-accent text-ink'
: 'border-transparent text-gray-500 hover:text-gray-700'
+1 -1
View File
@@ -83,7 +83,7 @@ export function BulkImportForm() {
if (stage === 'upload') {
return (
<div className="space-y-4">
<label className="block cursor-pointer border-2 border-dashed border-divider p-6 text-center hover:bg-gray-50">
<label className="block cursor-pointer border border-dashed border-divider p-6 text-center hover:bg-gray-50">
<input
type="file"
onChange={handleUpload}
+1 -1
View File
@@ -134,7 +134,7 @@ export function SiteZoneManager({ sites }: Props) {
</div>
{site.zones.length > 0 && (
<ul className="mt-3 space-y-1.5 pl-3 border-l-2 border-divider">
<ul className="mt-3 space-y-1.5 pl-3 border-l border-divider">
{site.zones.map(z => (
<li key={z.id} className={`flex items-center justify-between ${!z.active ? 'opacity-50' : ''}`}>
<span className="text-xs text-gray-700 font-medium">{z.name}</span>
+3 -3
View File
@@ -39,13 +39,13 @@ export function LoginForm() {
return (
<form onSubmit={handleSubmit} className="flex flex-col gap-4 w-full max-w-sm">
<div className="pb-3 border-b-2 border-divider">
<h1 className="text-3xl font-extrabold">IMS</h1>
<div className="pb-3 border-b border-rule">
<h1 className="text-[22px] font-[650]">IMS</h1>
<p className="text-sm text-ink/60 mt-1">HSE Incident Management</p>
</div>
{error && (
<p className="bg-accent-100 border border-accent text-accent-800 text-sm px-3 py-2">
<p className="bg-st-red-bg text-st-red-fg text-[13px] px-3 py-2 rounded-md">
{error}
</p>
)}
+47
View File
@@ -0,0 +1,47 @@
import Link from 'next/link'
import { Avatar } from '@/components/ui/avatar'
import { PriorityTag, StatusTag } from '@/components/ui/status-tag'
import { STATUS_ORDER, type CapaRow } from '@/lib/capa/list'
export function CapaBoardView({ capas }: { capas: CapaRow[] }) {
return (
<div className="flex gap-3 overflow-x-auto pb-2">
{STATUS_ORDER.map(status => {
const items = capas.filter(c => c.status === status)
return (
<section
key={status}
aria-label={`${status.replace(/_/g, ' ')} column`}
className="w-72 shrink-0 rounded-xl bg-surface-2 p-2"
>
<header className="flex items-center gap-2 px-1.5 pb-2">
<StatusTag status={status} />
<span className="text-xs text-faint">{items.length}</span>
</header>
<div className="space-y-2 max-h-[70vh] overflow-y-auto">
{items.map(c => (
<Link
key={c.id}
href={`/hse/capa/${c.id}`}
className="block rounded-md bg-surface p-3 shadow-card transition-shadow hover:shadow-float"
>
<p className="text-[13px] font-medium line-clamp-2">{c.description}</p>
<p className="mt-1 font-mono text-[12px] text-accent">{c.incident_ref ?? '—'}</p>
<div className="mt-2 flex items-center justify-between gap-2">
<span className="flex min-w-0 items-center gap-1.5 text-xs text-muted">
{c.owner_name && <Avatar name={c.owner_name} />}
<span className="truncate">{c.owner_name ?? '—'}</span>
</span>
<PriorityTag priority={c.priority} />
</div>
<p className="mt-1.5 text-xs text-faint">Due {c.due_date}</p>
</Link>
))}
{items.length === 0 && <p className="px-1.5 py-3 text-xs text-faint">Empty</p>}
</div>
</section>
)
})}
</div>
)
}
-129
View File
@@ -1,129 +0,0 @@
'use client'
import { useState } from 'react'
import Link from 'next/link'
import { PriorityTag } from '@/components/ui/status-tag'
type CapaStatus = 'open' | 'in_progress' | 'overdue' | 'pending_verification' | 'verified' | 'reopened' | 'closed'
type CapaAction = {
id: string
incident_id: string
description: string
department: string
due_date: string
priority: 'low' | 'med' | 'high'
status: CapaStatus
incidents: { reference_no: string | null } | null
owner: { name: string } | null
}
const STATUS_ORDER: CapaStatus[] = ['open', 'in_progress', 'overdue', 'pending_verification', 'verified', 'closed']
const STATUS_LABELS: Record<CapaStatus, string> = {
open: 'Open',
in_progress: 'In Progress',
overdue: 'Overdue',
pending_verification: 'Pending Verification',
verified: 'Verified',
reopened: 'Reopened',
closed: 'Closed',
}
const COLUMN_BORDER: Record<CapaStatus, string> = {
open: 'border-divider',
in_progress: 'border-divider',
overdue: 'border-accent',
pending_verification: 'border-divider',
verified: 'border-divider',
reopened: 'border-accent',
closed: 'border-divider',
}
interface Props {
capas: CapaAction[]
}
export function CapaBoard({ capas }: Props) {
const [view, setView] = useState<'board' | 'table'>('board')
const byStatus = STATUS_ORDER.reduce<Record<CapaStatus, CapaAction[]>>((acc, s) => {
acc[s] = capas.filter(c => c.status === s)
return acc
}, {} as Record<CapaStatus, CapaAction[]>)
if (view === 'table') {
return (
<div>
<div className="flex justify-end mb-3">
<button onClick={() => setView('board')} className="text-sm text-accent-700 hover:underline">Board view</button>
</div>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-left text-xs text-gray-500 uppercase border-b">
<th className="pb-2 pr-4">Ref</th>
<th className="pb-2 pr-4">Action</th>
<th className="pb-2 pr-4">Owner</th>
<th className="pb-2 pr-4">Due</th>
<th className="pb-2 pr-4">Priority</th>
<th className="pb-2">Status</th>
</tr>
</thead>
<tbody className="divide-y divide-divider">
{capas.map(c => (
<tr key={c.id}>
<td className="py-2 pr-4 text-gray-500 text-xs">
{(c.incidents as { reference_no: string | null } | null)?.reference_no ?? '—'}
</td>
<td className="py-2 pr-4">
<Link href={`/hse/capa/${c.id}`} className="text-accent-700 hover:underline line-clamp-2">
{c.description}
</Link>
</td>
<td className="py-2 pr-4 text-gray-600">{(c.owner as { name: string } | null)?.name ?? '—'}</td>
<td className="py-2 pr-4 text-gray-600">{c.due_date}</td>
<td className="py-2 pr-4">
<PriorityTag priority={c.priority} />
</td>
<td className="py-2 text-gray-600 text-xs">{STATUS_LABELS[c.status]}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)
}
return (
<div>
<div className="flex justify-end mb-3">
<button onClick={() => setView('table')} className="text-sm text-accent-700 hover:underline">Table view</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{STATUS_ORDER.filter(s => s !== 'reopened').map(status => (
<div key={status} className={`border-2 p-4 bg-ground ${COLUMN_BORDER[status]}`}>
<h3 className="text-xs font-extrabold uppercase tracking-wide text-ink/70 mb-3 pb-2 border-b-2 border-divider">
{STATUS_LABELS[status]} ({byStatus[status].length})
</h3>
<div className="space-y-2 max-h-96 overflow-y-auto pr-2">
{byStatus[status].map(c => (
<Link key={c.id} href={`/hse/capa/${c.id}`}
className="block bg-surface p-3 shadow-sm hover:shadow-md transition-shadow border border-divider">
<p className="text-sm text-gray-800 line-clamp-2 mb-1">{c.description}</p>
<div className="flex items-center justify-between text-xs text-gray-500">
<span>{(c.owner as { name: string } | null)?.name ?? '—'}</span>
<PriorityTag priority={c.priority} />
</div>
<p className="text-xs text-gray-400 mt-1">Due {c.due_date}</p>
</Link>
))}
{byStatus[status].length === 0 && (
<p className="text-xs text-gray-400 text-center py-3">Empty</p>
)}
</div>
</div>
))}
</div>
</div>
)
}
+38 -33
View File
@@ -2,6 +2,8 @@
import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Field, Input, Select, Textarea } from '@/components/ui/field'
interface User {
id: string
@@ -71,59 +73,62 @@ export function CapaForm({ incidentId }: Props) {
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Action Description *</label>
<textarea
<Field label="Action Description *" htmlFor="capa-description">
<Textarea
id="capa-description"
value={description}
onChange={e => setDescription(e.target.value)}
rows={3} required
className="w-full border border-divider px-3 py-2 text-sm"
rows={3}
required
placeholder="What corrective action will be taken?"
/>
</div>
</Field>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Root Cause Reference</label>
<input type="text" value={rootCauseRef}
<Field label="Root Cause Reference" htmlFor="capa-root-cause">
<Input
id="capa-root-cause"
type="text"
value={rootCauseRef}
onChange={e => setRootCauseRef(e.target.value)}
className="w-full border border-divider px-3 py-2 text-sm"
placeholder="e.g. Why #3 — inadequate training" />
</div>
placeholder="e.g. Why #3 — inadequate training"
/>
</Field>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Assigned To *</label>
<select value={ownerId} onChange={e => handleOwnerChange(e.target.value)} required
className="w-full border border-divider px-3 py-2 text-sm">
<Field label="Assigned To *" htmlFor="capa-owner">
<Select id="capa-owner" value={ownerId} onChange={e => handleOwnerChange(e.target.value)} required>
<option value="">Select owner…</option>
{users.map(u => (
<option key={u.id} value={u.id}>{u.name} ({u.department})</option>
))}
</select>
</div>
</Select>
</Field>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Due Date *</label>
<input type="date" value={dueDate} onChange={e => setDueDate(e.target.value)} required
className="w-full border border-divider px-3 py-2 text-sm" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Priority</label>
<select value={priority} onChange={e => setPriority(e.target.value as 'low' | 'med' | 'high')}
className="w-full border border-divider px-3 py-2 text-sm">
<Field label="Due Date *" htmlFor="capa-due">
<Input id="capa-due" type="date" value={dueDate} onChange={e => setDueDate(e.target.value)} required />
</Field>
<Field label="Priority" htmlFor="capa-priority">
<Select
id="capa-priority"
value={priority}
onChange={e => setPriority(e.target.value as 'low' | 'med' | 'high')}
>
<option value="low">Low</option>
<option value="med">Medium</option>
<option value="high">High</option>
</select>
</div>
</Select>
</Field>
</div>
{error && <p className="text-sm text-red-600">{error}</p>}
{error && (
<p role="alert" className="rounded-md bg-st-red-bg px-3 py-2 text-[13px] text-st-red-fg">
{error}
</p>
)}
<button type="submit" disabled={saving}
className="w-full bg-accent text-white py-2 text-sm font-semibold disabled:opacity-50">
<Button type="submit" block disabled={saving}>
{saving ? 'Creating…' : 'Create CAPA Action'}
</button>
</Button>
</form>
)
}
+5 -12
View File
@@ -2,6 +2,7 @@
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
interface Props {
capaId: string
@@ -33,25 +34,17 @@ export function CapaOwnerActions({ capaId, currentStatus }: Props) {
if (currentStatus === 'open' || currentStatus === 'reopened' || currentStatus === 'overdue') {
return (
<button
onClick={() => updateStatus('in_progress')}
disabled={loading}
className="text-sm px-3 py-1.5 border border-divider hover:bg-gray-50 disabled:opacity-50"
>
<Button variant="secondary" onClick={() => updateStatus('in_progress')} disabled={loading}>
{loading ? '…' : 'Mark In Progress'}
</button>
</Button>
)
}
if (currentStatus === 'in_progress') {
return (
<button
onClick={() => updateStatus('pending_verification')}
disabled={loading}
className="text-sm px-3 py-1.5 bg-accent text-white hover:bg-accent-600 disabled:opacity-50"
>
<Button onClick={() => updateStatus('pending_verification')} disabled={loading}>
{loading ? '…' : 'Submit for Verification'}
</button>
</Button>
)
}
+11 -12
View File
@@ -1,6 +1,8 @@
'use client'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Field, Textarea } from '@/components/ui/field'
interface Props {
capaId: string
@@ -32,25 +34,22 @@ export function CapaOwnerNotesForm({ capaId, initialNotes }: Props) {
}
return (
<div className="mt-3 space-y-1">
<label className="text-xs text-gray-500 font-medium">Remarks / Notes</label>
<textarea
<div className="mt-3 space-y-2">
<Field label="Remarks / Notes" htmlFor={`notes-${capaId}`}>
<Textarea
id={`notes-${capaId}`}
value={notes}
onChange={e => { setNotes(e.target.value); setSaved(false) }}
rows={2}
placeholder="Add any notes or updates for this action…"
className="w-full border border-divider px-3 py-2 text-sm text-gray-800 resize-none focus:outline-none focus:ring-2 focus:ring-accent"
/>
{error && <p className="text-xs text-red-600">{error}</p>}
</Field>
{error && <p role="alert" className="text-xs text-danger">{error}</p>}
<div className="flex items-center gap-2">
<button
onClick={handleSave}
disabled={saving}
className="text-xs px-3 py-1 bg-gray-800 text-white hover:bg-gray-700 disabled:opacity-50"
>
<Button variant="secondary" onClick={handleSave} disabled={saving}>
{saving ? 'Saving…' : 'Save Notes'}
</button>
{saved && <span className="text-xs text-ink">Saved</span>}
</Button>
{saved && <span className="text-xs text-st-green-fg">Saved</span>}
</div>
</div>
)
+167
View File
@@ -0,0 +1,167 @@
'use client'
import { useMemo, useState } from 'react'
import { useRouter } from 'next/navigation'
import { ChevronRight, Columns3, List, Search } from 'lucide-react'
import { Avatar } from '@/components/ui/avatar'
import { FilterChip } from '@/components/ui/filter-chip'
import { Segmented } from '@/components/ui/segmented'
import { PriorityTag, StatusTag } from '@/components/ui/status-tag'
import { TableCard, type Column } from '@/components/ui/table-card'
import {
EMPTY_FILTERS, PAGE_SIZE, VIEWS, daysLate, distinct, filterCapas, nextSort, paginate, sortCapas, viewCounts,
type CapaFilters, type CapaRow, type CapaSort, type CapaSortKey, type CapaViewKey,
} from '@/lib/capa/list'
import { CapaBoardView } from './capa-board-view'
const PRIORITY_OPTIONS = [
{ value: 'high', label: 'High' },
{ value: 'med', label: 'Medium' },
{ value: 'low', label: 'Low' },
]
const toOptions = (values: string[]) => values.map(v => ({ value: v, label: v }))
function Owner({ name }: { name: string | null }) {
if (!name) return <span className="text-faint">—</span>
return (
<span className="inline-flex items-center gap-2">
<Avatar name={name} />
{name}
</span>
)
}
function Due({ row, today }: { row: CapaRow; today: string }) {
const late = row.status === 'overdue' ? daysLate(row.due_date, today) : 0
return (
<span className="whitespace-nowrap">
{row.due_date}
{late > 0 && <span className="ml-1.5 text-xs text-danger">{`${late} day${late === 1 ? '' : 's'} late`}</span>}
</span>
)
}
export function CapaWorkspace({ capas, today }: { capas: CapaRow[]; today: string }) {
const router = useRouter()
const [mode, setMode] = useState<'list' | 'board'>('list')
const [filters, setFilters] = useState<CapaFilters>(EMPTY_FILTERS)
const [sort, setSort] = useState<CapaSort>({ key: 'due_date', dir: 'asc' })
const [page, setPage] = useState(1)
const patch = (next: Partial<CapaFilters>) => {
setFilters(f => ({ ...f, ...next }))
setPage(1)
}
const owners = useMemo(() => distinct(capas.map(c => c.owner_name)), [capas])
const departments = useMemo(() => distinct(capas.map(c => c.department)), [capas])
const counts = useMemo(() => viewCounts(capas, filters), [capas, filters])
const sorted = useMemo(() => sortCapas(filterCapas(capas, filters), sort), [capas, filters, sort])
const boardRows = useMemo(
() => sortCapas(filterCapas(capas, { ...filters, view: 'all' }), { key: 'due_date', dir: 'asc' }),
[capas, filters],
)
const pageData = paginate(sorted, page, PAGE_SIZE)
const clearable = Boolean(filters.q || filters.owner || filters.department || filters.priority)
const columns: Column<CapaRow>[] = [
{ key: 'action', header: 'Action', cell: r => <span className="line-clamp-2 font-medium">{r.description}</span> },
{ key: 'incident', header: 'Incident', cell: r => <span className="font-mono text-[12.5px] text-accent">{r.incident_ref ?? '—'}</span> },
{ key: 'owner', header: 'Owner', cell: r => <Owner name={r.owner_name} /> },
{ key: 'department', header: 'Department', cell: r => r.department },
{ key: 'priority', header: 'Priority', sortKey: 'priority', cell: r => <PriorityTag priority={r.priority} /> },
{ key: 'due', header: 'Due', sortKey: 'due_date', cell: r => <Due row={r} today={today} /> },
{ key: 'status', header: 'Status', sortKey: 'status', cell: r => <StatusTag status={r.status} /> },
]
const toolbar = (
<>
<label className="flex h-8 min-w-[260px] items-center gap-2 rounded-md bg-surface px-2.5 text-[13px] shadow-input">
<Search size={16} strokeWidth={2} className="text-muted" aria-hidden />
<input
type="search"
aria-label="Search actions"
placeholder="Search action, incident or owner"
value={filters.q}
onChange={e => patch({ q: e.target.value })}
className="flex-1 bg-transparent outline-none placeholder:text-faint"
/>
</label>
<FilterChip label="Owner" value={filters.owner} options={toOptions(owners)} onChange={v => patch({ owner: v })} />
<FilterChip label="Department" value={filters.department} options={toOptions(departments)} onChange={v => patch({ department: v })} />
<FilterChip label="Priority" value={filters.priority} options={PRIORITY_OPTIONS} onChange={v => patch({ priority: v })} />
{clearable && (
<button
type="button"
onClick={() => patch({ q: '', owner: '', department: '', priority: '' })}
className="cursor-pointer text-[12.5px] text-muted hover:text-ink"
>
Clear filters
</button>
)}
</>
)
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-[22px] font-[650] md:text-xl">CAPA</h1>
<Segmented
value={mode}
onChange={v => setMode(v as 'list' | 'board')}
options={[
{ value: 'list', label: <><List size={14} strokeWidth={2} aria-hidden />List</> },
{ value: 'board', label: <><Columns3 size={14} strokeWidth={2} aria-hidden />Board</> },
]}
/>
</div>
{mode === 'list' ? (
<TableCard
columns={columns}
rows={pageData.items}
rowKey={r => r.id}
onRowOpen={r => router.push(`/hse/capa/${r.id}`)}
views={{
items: VIEWS.map(v => ({ key: v.key, label: v.label, count: counts[v.key] })),
active: filters.view,
onChange: key => patch({ view: key as CapaViewKey }),
}}
toolbar={toolbar}
sort={sort}
onSortChange={key => {
setSort(nextSort(sort, key as CapaSortKey))
setPage(1)
}}
footer={
pageData.total > 0
? { from: pageData.from, to: pageData.to, total: pageData.total, page: pageData.page, pageCount: pageData.pageCount, onPage: setPage }
: undefined
}
empty={{ title: 'No CAPA actions match' }}
mobileRow={r => (
<div className="flex items-start gap-3">
<div className="min-w-0 flex-1 space-y-1">
<p className="line-clamp-2 text-[13px] font-medium">{r.description}</p>
<div className="flex items-center gap-2">
<StatusTag status={r.status} />
<PriorityTag priority={r.priority} />
</div>
<p className="text-xs text-faint">
{[r.incident_ref, r.owner_name, `Due ${r.due_date}`].filter(Boolean).join(' · ')}
</p>
</div>
<ChevronRight size={16} strokeWidth={2} className="mt-1 text-faint" aria-hidden />
</div>
)}
/>
) : (
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-2">{toolbar}</div>
<CapaBoardView capas={boardRows} />
</div>
)}
</div>
)
}
+13 -10
View File
@@ -2,6 +2,7 @@
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
interface Props {
capaId: string
@@ -31,19 +32,21 @@ export function CloseCapaButton({ capaId }: Props) {
}
return (
<div className="border border-divider p-5 space-y-3 bg-neutral-100">
<h3 className="text-sm font-semibold text-gray-800">Close CAPA</h3>
<p className="text-sm text-gray-600">
<div className="space-y-3 rounded-xl bg-surface p-5 shadow-card">
<div>
<h3 className="text-sm font-semibold">Close CAPA</h3>
<p className="mt-0.5 text-xs text-muted">
This CAPA has been verified as effective. Close it to mark it fully resolved.
</p>
{error && <p className="text-sm text-red-600">{error}</p>}
<button
onClick={handleClose}
disabled={loading}
className="w-full bg-accent text-white py-2 text-sm font-semibold hover:bg-accent-700 disabled:opacity-50"
>
</div>
{error && (
<p role="alert" className="rounded-md bg-st-red-bg px-3 py-2 text-[13px] text-st-red-fg">
{error}
</p>
)}
<Button onClick={handleClose} disabled={loading}>
{loading ? 'Closing…' : 'Close CAPA'}
</button>
</Button>
</div>
)
}
+73 -40
View File
@@ -2,14 +2,47 @@
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Field, Textarea } from '@/components/ui/field'
import { cx } from '@/components/ui/cx'
interface Props {
capaId: string
}
type Verdict = 'verified' | 'reopened'
function Choice({
selected,
onSelect,
title,
hint,
}: {
selected: boolean
onSelect: () => void
title: string
hint: string
}) {
return (
<button
type="button"
role="radio"
aria-checked={selected}
onClick={onSelect}
className={cx(
'cursor-pointer rounded-xl p-3 text-left transition-colors',
selected ? 'bg-accent-tint shadow-chip-set' : 'bg-surface shadow-chip hover:bg-surface-2',
)}
>
<span className="block text-[13px] font-semibold">{title}</span>
<span className="mt-0.5 block text-xs text-muted">{hint}</span>
</button>
)
}
export function VerifyForm({ capaId }: Props) {
const router = useRouter()
const [verdict, setVerdict] = useState<'verified' | 'reopened' | null>(null)
const [verdict, setVerdict] = useState<Verdict | null>(null)
const [reopenReason, setReopenReason] = useState('')
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
@@ -39,50 +72,50 @@ export function VerifyForm({ capaId }: Props) {
}
return (
<form onSubmit={handleSubmit} className="border border-divider p-5 space-y-4 bg-accent-100">
<h3 className="text-sm font-semibold text-gray-800">HSE Verification</h3>
<div className="flex gap-3">
<button
type="button"
onClick={() => setVerdict('verified')}
className={`flex-1 py-2 text-sm font-medium border ${
verdict === 'verified'
? 'bg-accent text-white border-accent'
: 'bg-surface text-gray-700 border-divider hover:border-accent'
}`}
>
Verified — Effective
</button>
<button
type="button"
onClick={() => setVerdict('reopened')}
className={`flex-1 py-2 text-sm font-medium border ${
verdict === 'reopened'
? 'bg-accent text-white border-accent'
: 'bg-surface text-gray-700 border-divider hover:border-accent'
}`}
>
Reopen — Ineffective
</button>
</div>
{verdict === 'reopened' && (
<form onSubmit={handleSubmit} className="space-y-4 rounded-xl bg-surface p-5 shadow-card">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Why is the action ineffective? *</label>
<textarea
value={reopenReason}
onChange={e => setReopenReason(e.target.value)}
rows={2} required
className="w-full border border-divider px-3 py-2 text-sm"
placeholder="Describe why the corrective action did not resolve the root cause…"
<h3 className="text-sm font-semibold">Verify this action</h3>
<p className="mt-0.5 text-xs text-muted">Confirm the corrective action fixed the root cause, or send it back.</p>
</div>
<div role="radiogroup" aria-label="Verification verdict" className="grid gap-3 sm:grid-cols-2">
<Choice
selected={verdict === 'verified'}
onSelect={() => setVerdict('verified')}
title="Verified, effective"
hint="Root cause addressed. The action is marked verified."
/>
<Choice
selected={verdict === 'reopened'}
onSelect={() => setVerdict('reopened')}
title="Reopen, ineffective"
hint="Returns to the owner with a required reason."
/>
</div>
{verdict === 'reopened' && (
<Field label="Why is the action ineffective? *" htmlFor="reopen-reason">
<Textarea
id="reopen-reason"
value={reopenReason}
onChange={e => setReopenReason(e.target.value)}
rows={2}
required
placeholder="Describe why the corrective action did not resolve the root cause…"
/>
</Field>
)}
{error && <p className="text-sm text-red-600">{error}</p>}
{error && (
<p role="alert" className="rounded-md bg-st-red-bg px-3 py-2 text-[13px] text-st-red-fg">
{error}
</p>
)}
{verdict && (
<button type="submit" disabled={saving}
className="w-full bg-gray-900 text-white py-2 text-sm font-semibold disabled:opacity-50">
{saving ? 'Saving…' : 'Submit Verification'}
</button>
<Button type="submit" disabled={saving}>
{saving ? 'Saving…' : verdict === 'verified' ? 'Confirm verification' : 'Reopen action'}
</Button>
)}
</form>
)
+1 -1
View File
@@ -20,7 +20,7 @@ function TabsInner({ activeTab }: { activeTab: string }) {
<button
key={tab.key}
onClick={() => router.replace(`${pathname}?tab=${tab.key}`)}
className={`px-4 py-2.5 text-sm font-medium whitespace-nowrap border-b-2 transition-colors ${
className={`px-4 py-2.5 text-sm font-medium whitespace-nowrap border-b transition-colors ${
activeTab === tab.key
? 'border-accent text-accent-700'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-divider'
+4 -4
View File
@@ -11,9 +11,9 @@ type RiskFlag = {
}
const LEVEL_COLORS: Record<RiskFlag['risk_level'], string> = {
low: 'bg-neutral-100 text-neutral-800 border-divider',
medium: 'bg-ground text-accent-700 border-accent',
high: 'bg-accent-100 text-accent-800 border-accent',
low: 'bg-st-grey-bg text-st-grey-fg border-transparent',
medium: 'bg-st-amber-bg text-st-amber-fg border-transparent',
high: 'bg-st-red-bg text-st-red-fg border-transparent',
}
export function RiskFlagsPanel() {
@@ -71,7 +71,7 @@ export function RiskFlagsPanel() {
<p className="text-sm text-gray-700 mb-3">{summary}</p>
<div className="space-y-2">
{flags.map(f => (
<div key={`${f.site}-${f.zone}`} className={`border p-3 ${LEVEL_COLORS[f.risk_level]}`}>
<div key={`${f.site}-${f.zone}`} className={`border rounded-md p-3 ${LEVEL_COLORS[f.risk_level]}`}>
<div className="flex items-center justify-between mb-1">
<span className="text-sm font-semibold">{f.zone} · {f.site}</span>
<span className="text-xs font-bold uppercase">{f.risk_level}</span>
+1 -1
View File
@@ -57,7 +57,7 @@ export function FileUpload({ onFilesChange, disabled = false }: Props) {
return (
<div className="space-y-2">
<div
className={`border-2 border-dashed p-6 text-center cursor-pointer transition-colors
className={`border border-dashed p-6 text-center cursor-pointer transition-colors
${dragging ? 'border-accent bg-accent-100' : 'border-divider hover:border-gray-400'}
${disabled ? 'opacity-50 pointer-events-none' : ''}`}
onClick={() => inputRef.current?.click()}
-138
View File
@@ -1,138 +0,0 @@
'use client'
import { useRouter, useSearchParams, usePathname } from 'next/navigation'
import { useCallback, useState, useTransition, Suspense } from 'react'
const STATUS_OPTIONS = [
{ value: '', label: 'All Statuses' },
{ value: 'reported', label: 'Reported' },
{ value: 'triaged', label: 'Triaged' },
{ value: 'investigating', label: 'Investigating' },
{ value: 'capa_pending', label: 'CAPA Pending' },
{ value: 'verification', label: 'Pending Verification' },
{ value: 'closed', label: 'Closed' },
]
const TYPE_OPTIONS = [
{ value: '', label: 'All Types' },
{ value: 'injury', label: 'Injury' },
{ value: 'near_miss', label: 'Near Miss' },
{ value: 'hazard', label: 'Hazard' },
{ value: 'asset_damage', label: 'Asset Damage' },
{ value: 'environmental', label: 'Environmental' },
{ value: 'security', label: 'Security' },
{ value: 'fire', label: 'Fire' },
{ value: 'transport', label: 'Transport' },
]
export interface SiteOption { id: string; name: string }
export interface TruckOption { id: string; truck_no: string }
interface FiltersProps {
sites: SiteOption[]
trucks: TruckOption[]
}
function FiltersInner({ sites, trucks }: FiltersProps) {
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
const [, startTransition] = useTransition()
const [search, setSearch] = useState(searchParams.get('q') ?? '')
const updateParam = useCallback((key: string, value: string) => {
const params = new URLSearchParams(searchParams.toString())
if (value) {
params.set(key, value)
} else {
params.delete(key)
}
params.delete('page')
startTransition(() => {
router.replace(`${pathname}?${params.toString()}`)
})
}, [router, pathname, searchParams])
const handleSearch = useCallback((value: string) => {
setSearch(value)
const timer = setTimeout(() => updateParam('q', value), 300)
return () => clearTimeout(timer)
}, [updateParam])
const hasFilters = searchParams.get('q') || searchParams.get('status') ||
searchParams.get('type') || searchParams.get('site_id') || searchParams.get('truck_id')
return (
<div className="flex flex-wrap gap-2 mb-4">
<div className="relative flex-1 min-w-48">
<svg
className="absolute left-2.5 top-2 h-4 w-4 text-gray-400 pointer-events-none"
fill="none" stroke="currentColor" viewBox="0 0 24 24"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<input
type="search"
placeholder="Search reference or description..."
value={search}
onChange={e => handleSearch(e.target.value)}
className="w-full pl-8 pr-3 py-1.5 text-sm border border-divider focus:outline-none focus:ring-2 focus:ring-accent"
/>
</div>
<select
value={searchParams.get('status') ?? ''}
onChange={e => updateParam('status', e.target.value)}
className="text-sm border border-divider px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-accent bg-surface"
>
{STATUS_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
</select>
<select
value={searchParams.get('type') ?? ''}
onChange={e => updateParam('type', e.target.value)}
className="text-sm border border-divider px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-accent bg-surface"
>
{TYPE_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
</select>
{sites.length > 0 && (
<select
value={searchParams.get('site_id') ?? ''}
onChange={e => updateParam('site_id', e.target.value)}
className="text-sm border border-divider px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-accent bg-surface"
>
<option value="">All Sites</option>
{sites.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select>
)}
{trucks.length > 0 && (
<select
value={searchParams.get('truck_id') ?? ''}
onChange={e => updateParam('truck_id', e.target.value)}
className="text-sm border border-divider px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-accent bg-surface"
>
<option value="">All Trucks</option>
{trucks.map(tk => <option key={tk.id} value={tk.id}>{tk.truck_no}</option>)}
</select>
)}
{hasFilters && (
<button
onClick={() => {
setSearch('')
router.replace(pathname)
}}
className="text-sm text-gray-500 hover:text-gray-700 px-2 py-1.5 underline"
>
Clear filters
</button>
)}
</div>
)
}
export function IncidentFilters({ sites, trucks }: FiltersProps) {
return (
<Suspense fallback={<div className="h-10 mb-4" />}>
<FiltersInner sites={sites} trucks={trucks} />
</Suspense>
)
}
-129
View File
@@ -1,129 +0,0 @@
'use client'
import { useState } from 'react'
import Link from 'next/link'
import { StatusTag } from '@/components/ui/status-tag'
const TYPE_LABELS: Record<string, string> = {
injury: 'Injury / Medical',
near_miss: 'Near Miss',
hazard: 'Hazard',
asset_damage: 'Asset Damage',
environmental: 'Environmental',
security: 'Security',
fire: 'Fire / Emergency',
transport: 'Transport / Vehicle',
}
const STATUS_ORDER = ['reported', 'triaged', 'investigating', 'capa_pending', 'verification', 'closed'] as const
export type Incident = {
id: string
reference_no: string | null
incident_type: string
status: string
severity: number | null
reported_at: string
sites: { name: string } | null
zones: { name: string } | null
trucks: { truck_no: string } | null
reporter: { name: string } | null
}
interface Props {
incidents: Incident[]
basePath: string
}
export function IncidentList({ incidents, basePath }: Props) {
const [typeFilter, setTypeFilter] = useState('')
const [statusFilter, setStatusFilter] = useState('')
const [search, setSearch] = useState('')
const filtered = incidents.filter(inc => {
if (typeFilter && inc.incident_type !== typeFilter) return false
if (statusFilter && inc.status !== statusFilter) return false
if (search) {
const q = search.toLowerCase()
return (
inc.reference_no?.toLowerCase().includes(q) ||
inc.incident_type.includes(q) ||
(inc.sites?.name ?? '').toLowerCase().includes(q)
)
}
return true
})
return (
<div className="space-y-4">
<div className="flex flex-wrap gap-2">
<input
type="search"
placeholder="Search ref, type, site…"
className="border border-divider px-3 py-2 text-sm w-48 focus:outline-none focus:ring-2 focus:ring-accent"
value={search}
onChange={e => setSearch(e.target.value)}
/>
<select
className="border border-divider px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-accent"
value={typeFilter}
onChange={e => setTypeFilter(e.target.value)}
>
<option value="">All types</option>
{Object.entries(TYPE_LABELS).map(([v, l]) => (
<option key={v} value={v}>{l}</option>
))}
</select>
<select
className="border border-divider px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-accent"
value={statusFilter}
onChange={e => setStatusFilter(e.target.value)}
>
<option value="">All statuses</option>
{STATUS_ORDER.map(s => (
<option key={s} value={s}>{s.replace(/_/g, ' ')}</option>
))}
</select>
</div>
{filtered.length === 0 ? (
<div className="text-center py-12 text-gray-500 text-sm">No incidents found</div>
) : (
<div className="divide-y divide-divider bg-surface shadow-sm overflow-hidden">
{filtered.map(inc => (
<Link
key={inc.id}
href={`${basePath}/incidents/${inc.id}`}
className="flex items-center justify-between px-4 py-3 hover:bg-gray-50 transition-colors"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 mb-0.5">
<span className="font-mono text-sm font-semibold text-gray-900">
{inc.reference_no ?? '—'}
</span>
<StatusTag status={inc.status}>{inc.status.replace(/_/g, ' ').toUpperCase()}</StatusTag>
</div>
<div className="text-sm text-gray-600">
{TYPE_LABELS[inc.incident_type] ?? inc.incident_type}
{inc.zones?.name && ` · ${inc.zones.name}`}
{inc.sites?.name && ` · ${inc.sites.name}`}
{inc.trucks?.truck_no && (
<span className="ml-1 text-xs text-gray-400">· {inc.trucks.truck_no}</span>
)}
</div>
</div>
<div className="ml-4 text-right">
<div className="text-xs text-gray-400">
{new Date(inc.reported_at).toLocaleDateString('en-MY')}
</div>
{inc.severity && (
<div className="text-xs text-gray-500 mt-0.5">Sev {inc.severity}</div>
)}
</div>
</Link>
))}
</div>
)}
</div>
)
}
+186
View File
@@ -0,0 +1,186 @@
'use client'
import { useEffect, useState } from 'react'
import Link from 'next/link'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { ChevronRight, Eye, Search } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { FilterChip } from '@/components/ui/filter-chip'
import { StatusTag } from '@/components/ui/status-tag'
import { TableCard, type Column } from '@/components/ui/table-card'
import { PAGE_SIZE, nextSort, withParams, type ListParams, type SortKey } from '@/lib/incidents/list-params'
import type { Incident, SiteOption, TruckOption } from '@/lib/incidents/types'
const TYPE_LABELS: Record<string, string> = {
injury: 'Injury / Medical',
near_miss: 'Near Miss',
hazard: 'Hazard',
asset_damage: 'Asset Damage',
environmental: 'Environmental',
security: 'Security',
fire: 'Fire / Emergency',
transport: 'Transport / Vehicle',
}
const STATUS_OPTIONS = [
{ value: 'reported', label: 'Reported' },
{ value: 'triaged', label: 'Triaged' },
{ value: 'investigating', label: 'Investigating' },
{ value: 'capa_pending', label: 'CAPA pending' },
{ value: 'verification', label: 'Verification' },
{ value: 'closed', label: 'Closed' },
]
const TYPE_OPTIONS = Object.entries(TYPE_LABELS).map(([value, label]) => ({ value, label }))
interface Props {
incidents: Incident[]
basePath: string
total: number
counts: { all: number; open: number; closed: number }
params: ListParams
sites: SiteOption[]
trucks: TruckOption[]
}
const fmtDate = (iso: string) => new Date(iso).toLocaleDateString('en-MY')
export function IncidentTable({ incidents, basePath, total, counts, params, sites, trucks }: Props) {
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
const search = searchParams.toString() ? `?${searchParams.toString()}` : ''
const [q, setQ] = useState(params.q)
const update = (updates: Record<string, string | null>) =>
router.replace(`${pathname}${withParams(search, updates)}`)
useEffect(() => {
if (q === params.q) return
const timer = setTimeout(() => update({ q: q || null }), 300)
return () => clearTimeout(timer)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [q])
const columns: Column<Incident>[] = [
{
key: 'reference',
header: 'Reference',
sortKey: 'reference_no',
cell: r => <span className="font-mono text-[12.5px] text-accent">{r.reference_no ?? '—'}</span>,
},
{ key: 'status', header: 'Status', sortKey: 'status', cell: r => <StatusTag status={r.status} /> },
{ key: 'type', header: 'Type', cell: r => TYPE_LABELS[r.incident_type] ?? r.incident_type },
{
key: 'location',
header: 'Location',
cell: r => [r.zones?.name, r.sites?.name, r.trucks?.truck_no].filter(Boolean).join(' · ') || '—',
},
{ key: 'severity', header: 'Severity', cell: r => (r.severity ? `Sev ${r.severity}` : '—') },
{ key: 'reported', header: 'Reported', sortKey: 'reported_at', cell: r => fmtDate(r.reported_at) },
]
const clearable = Boolean(params.q || params.status || params.type || params.siteId || params.truckId)
const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE))
const from = incidents.length === 0 ? 0 : (params.page - 1) * PAGE_SIZE + 1
const to = incidents.length === 0 ? 0 : from + incidents.length - 1
const toolbar = (
<>
<label className="flex items-center gap-2 h-8 px-2.5 rounded-md bg-surface shadow-input text-[13px] min-w-[260px]">
<Search size={16} strokeWidth={2} className="text-muted" aria-hidden />
<input
type="search"
aria-label="Search incidents"
placeholder="Search reference or description"
value={q}
onChange={e => setQ(e.target.value)}
className="flex-1 bg-transparent outline-none placeholder:text-faint"
/>
</label>
<FilterChip label="Status" value={params.status} options={STATUS_OPTIONS} onChange={v => update({ status: v || null })} />
<FilterChip label="Type" value={params.type} options={TYPE_OPTIONS} onChange={v => update({ type: v || null })} />
{sites.length > 0 && (
<FilterChip
label="Site"
value={params.siteId}
options={sites.map(s => ({ value: s.id, label: s.name }))}
onChange={v => update({ site_id: v || null })}
/>
)}
{trucks.length > 0 && (
<FilterChip
label="Truck"
value={params.truckId}
options={trucks.map(t => ({ value: t.id, label: t.truck_no }))}
onChange={v => update({ truck_id: v || null })}
/>
)}
{clearable && (
<button
type="button"
onClick={() => {
setQ('')
router.replace(pathname)
}}
className="text-[12.5px] text-muted hover:text-ink cursor-pointer"
>
Clear filters
</button>
)}
</>
)
return (
<TableCard
columns={columns}
rows={incidents}
rowKey={r => r.id}
onRowOpen={r => router.push(`${basePath}/incidents/${r.id}`)}
rowActions={r => (
<Link
href={`${basePath}/incidents/${r.id}`}
aria-label="Open incident"
className="inline-grid place-items-center w-7 h-7 rounded-md text-ink-3 hover:bg-rule"
>
<Eye size={16} strokeWidth={2} aria-hidden />
</Link>
)}
views={{
items: [
{ key: 'all', label: 'All', count: counts.all },
{ key: 'open', label: 'Open', count: counts.open },
{ key: 'closed', label: 'Closed', count: counts.closed },
],
active: params.view,
onChange: key => update({ view: key === 'all' ? null : key }),
}}
toolbar={toolbar}
sort={{ key: params.sort, dir: params.dir }}
onSortChange={key => {
const next = nextSort({ key: params.sort, dir: params.dir }, key as SortKey)
update({ sort: next.key, dir: next.dir })
}}
footer={total > 0 ? { from, to, total, page: params.page, pageCount, onPage: p => update({ page: String(p) }) } : undefined}
empty={{
title: 'No incidents found',
action: <Button onClick={() => router.push('/report')}>Report incident</Button>,
}}
mobileRow={r => (
<div className="flex items-start gap-3">
<div className="min-w-0 flex-1 space-y-1">
<div className="flex items-center gap-2">
<span className="font-mono text-[12.5px] text-accent">{r.reference_no ?? '—'}</span>
<StatusTag status={r.status} />
</div>
<p className="text-[13px] text-ink-3">
{[TYPE_LABELS[r.incident_type] ?? r.incident_type, r.zones?.name].filter(Boolean).join(' · ')}
</p>
<p className="text-xs text-faint">{fmtDate(r.reported_at)}</p>
</div>
<ChevronRight size={16} strokeWidth={2} className="mt-1 text-faint" aria-hidden />
</div>
)}
/>
)
}
+2 -2
View File
@@ -42,8 +42,8 @@ export function InvestigationPanel({ investigation: inv }: Props) {
<span className="text-xs text-gray-500">{METHOD_LABELS[inv.method] ?? inv.method}</span>
<span className={`text-xs font-medium px-2 py-0.5 ${
inv.completed_at
? 'bg-neutral-100 text-ink'
: 'bg-accent-100 text-accent-700'
? 'bg-st-green-bg text-st-green-fg'
: 'bg-st-blue-bg text-st-blue-fg'
}`}>
{inv.completed_at ? 'Completed' : 'In Progress'}
</span>
+2 -2
View File
@@ -56,8 +56,8 @@ export function OfflineSync() {
if (pendingCount === 0) return null
return (
<div className="fixed bottom-4 left-4 right-4 bg-accent-100 border border-accent-300 p-3 flex items-center justify-between shadow-md z-50">
<span className="text-sm text-accent-700 font-medium">
<div className="fixed bottom-4 left-4 right-4 bg-st-amber-bg rounded-xl p-3 flex items-center justify-between shadow-float z-50">
<span className="text-sm text-st-amber-fg font-medium">
{pendingCount} report{pendingCount > 1 ? 's' : ''} saved offline
</span>
<button
-32
View File
@@ -1,32 +0,0 @@
import Link from 'next/link'
interface Props {
page: number
pageSize: number
total: number
href: string
}
export function Pagination({ page, pageSize, total, href }: Props) {
const totalPages = Math.max(1, Math.ceil(total / pageSize))
if (totalPages <= 1) return null
const link = (p: number, label: string, disabled: boolean) =>
disabled ? (
<span className="px-3 py-1.5 text-sm text-gray-300">{label}</span>
) : (
<Link href={`${href}?page=${p}`} className="px-3 py-1.5 text-sm text-accent-700 hover:underline">
{label}
</Link>
)
return (
<nav className="flex items-center justify-between mt-4" aria-label="Pagination">
{link(page - 1, '← Previous', page <= 1)}
<span className="text-sm text-gray-500">
Page {page} of {totalPages}
</span>
{link(page + 1, 'Next →', page >= totalPages)}
</nav>
)
}
+5 -5
View File
@@ -214,7 +214,7 @@ export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
return (
<form onSubmit={handleSubmit} className="space-y-5 bg-surface shadow-sm p-5">
{!isOnline && (
<div className="bg-accent-100 border border-accent-300 p-3 text-sm text-accent-700">
<div className="bg-st-amber-bg rounded-md p-3 text-sm text-st-amber-fg">
{t.offlineBanner}
</div>
)}
@@ -308,15 +308,15 @@ export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
</div>
{qualityCheck && !qualityCheck.passes && (
<div className="bg-accent-100 border border-accent-300 p-3 space-y-2">
<p className="text-xs font-semibold text-accent-700 uppercase tracking-wide">
<div className="bg-st-amber-bg rounded-md p-3 space-y-2">
<p className="text-xs font-semibold text-st-amber-fg uppercase tracking-wide">
{t.qualityScoreLabel.replace('{score}', String(qualityCheck.score))}
</p>
<p className="text-sm text-accent-700">{qualityCheck.feedback}</p>
<p className="text-sm text-st-amber-fg">{qualityCheck.feedback}</p>
{qualityCheck.suggestions.length > 0 && (
<ul className="list-disc list-inside space-y-1">
{qualityCheck.suggestions.map((s, i) => (
<li key={i} className="text-xs text-accent-700">{s}</li>
<li key={i} className="text-xs text-st-amber-fg">{s}</li>
))}
</ul>
)}
+1 -1
View File
@@ -157,7 +157,7 @@ export function TriageForm({ incidentId, currentSeverity }: Props) {
</div>
{aiRationale && (
<div className="bg-accent-100 border border-accent-300 p-3">
<div className="bg-accent-tint rounded-md p-3">
<p className="text-xs font-semibold text-accent-700 mb-1">AI Suggestion Rationale</p>
<p className="text-xs text-accent-700">{aiRationale}</p>
<p className="text-xs text-accent-400 mt-1">Fields pre-filled — review before submitting.</p>
+135
View File
@@ -0,0 +1,135 @@
'use client'
import { useEffect, useRef } from 'react'
import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import { LogOut, Search, ShieldCheck, User } from 'lucide-react'
import { NotificationBell } from '@/components/notifications/bell'
import { Avatar } from '@/components/ui/avatar'
import { cx } from '@/components/ui/cx'
import { MobileShell } from './mobile-shell'
import { isActivePath, navItemsFor, searchHrefFor } from './nav-items'
const ITEM = 'flex items-center gap-2.5 h-8 px-2.5 rounded-md text-[13px] w-full text-left'
const ITEM_ACTIVE = 'bg-surface text-ink font-semibold shadow-chip'
const ITEM_IDLE = 'text-ink-3 hover:bg-rule-2'
export function AppShell({
role,
userName,
children,
}: {
role: string
userName: string
children: React.ReactNode
}) {
const pathname = usePathname()
const router = useRouter()
const items = navItemsFor(role)
const searchHref = searchHrefFor(role)
const searchRef = useRef<HTMLInputElement>(null)
const displayName = userName || 'User'
const roleLabel = role.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
e.preventDefault()
searchRef.current?.focus()
}
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [])
const logout = async () => {
await fetch('/api/auth/logout', { method: 'POST' })
router.push('/login')
router.refresh()
}
const accountActive = pathname === '/account'
return (
<div className="min-h-screen bg-ground">
<header className="hidden md:flex fixed top-0 left-0 right-0 z-40 h-14 items-center justify-between gap-4 pl-5 pr-4 bg-topbar">
<div className="flex items-center gap-2.5 w-56">
<span className="inline-grid place-items-center w-7 h-7 rounded-md bg-accent text-white">
<ShieldCheck size={16} strokeWidth={2} aria-hidden />
</span>
<span className="text-[15px] font-[650] text-white tracking-tight">IMS</span>
<span className="text-[13px] text-neutral-400">Setia HSE</span>
</div>
{searchHref ? (
<form action={searchHref} method="get" className="flex-1 max-w-[520px]">
<label className="flex items-center gap-2 h-[34px] px-2.5 rounded-[10px] bg-ink-2 shadow-[inset_0_0_0_1px_var(--color-ink-3)] text-neutral-400 text-[13px]">
<Search size={16} strokeWidth={2} aria-hidden />
<input
ref={searchRef}
name="q"
type="search"
placeholder="Search incidents"
aria-label="Search incidents"
className="flex-1 bg-transparent text-white placeholder:text-neutral-400 outline-none"
/>
<kbd className="font-mono text-[11px] text-neutral-400">⌘K</kbd>
</label>
</form>
) : (
<div className="flex-1" />
)}
<div className="flex items-center gap-2 w-56 justify-end">
<NotificationBell />
<div className="flex items-center gap-2 py-1 pl-1 pr-2.5 rounded-md bg-ink-2">
<Avatar name={displayName} />
<span className="text-[13px] text-rule-2 max-w-32 truncate">{displayName}</span>
</div>
</div>
</header>
<aside className="hidden md:flex fixed top-14 left-0 bottom-0 z-30 w-60 flex-col gap-0.5 p-3 bg-rule border-r border-rule-2">
{items.map(item => {
const active = isActivePath(item.href, pathname)
const Icon = item.icon
return (
<Link
key={item.href}
href={item.href}
aria-current={active ? 'page' : undefined}
className={cx(ITEM, active ? ITEM_ACTIVE : ITEM_IDLE)}
>
<Icon size={16} strokeWidth={2} className={active ? 'text-accent' : 'text-ink-3'} aria-hidden />
<span className="flex-1">{item.label}</span>
</Link>
)
})}
<div className="flex-1" />
<div className="flex flex-col gap-0.5 pt-2.5 border-t border-rule-2">
<div className="px-2.5 pb-1">
<p className="text-[13px] font-semibold truncate">{displayName}</p>
<p className="text-xs text-muted truncate">{roleLabel}</p>
</div>
<Link
href="/account"
aria-current={accountActive ? 'page' : undefined}
className={cx(ITEM, accountActive ? ITEM_ACTIVE : ITEM_IDLE)}
>
<User size={16} strokeWidth={2} className={accountActive ? 'text-accent' : 'text-ink-3'} aria-hidden />
Account
</Link>
<button type="button" onClick={logout} className={cx(ITEM, ITEM_IDLE, 'cursor-pointer')}>
<LogOut size={16} strokeWidth={2} className="text-ink-3" aria-hidden />
Log out
</button>
<p className="px-2.5 pt-2 text-xs text-faint">v1.2.2</p>
</div>
</aside>
<main className="md:pl-60 md:pt-14 pb-16 md:pb-0">{children}</main>
<MobileShell items={items} pathname={pathname} onLogout={logout} />
</div>
)
}
+53
View File
@@ -0,0 +1,53 @@
'use client'
import Link from 'next/link'
import { LogOut } from 'lucide-react'
import { isActivePath, type NavItem } from './nav-items'
import { cx } from '@/components/ui/cx'
export function MobileShell({
items,
pathname,
onLogout,
}: {
items: NavItem[]
pathname: string
onLogout: () => void
}) {
const tabs = items.slice(0, 4)
return (
<nav
aria-label="Mobile"
className="md:hidden fixed bottom-0 left-0 right-0 z-40 flex bg-surface border-t border-rule pb-[env(safe-area-inset-bottom)]"
>
{tabs.map(item => {
const active = isActivePath(item.href, pathname)
const Icon = item.icon
return (
<Link
key={item.href}
href={item.href}
aria-current={active ? 'page' : undefined}
className={cx(
'flex-1 flex flex-col items-center gap-1 pt-2 pb-1.5 text-[10.5px] font-medium',
active ? 'text-accent' : 'text-faint',
)}
>
<Icon size={22} strokeWidth={1.8} aria-hidden />
<span className="leading-none">{item.label}</span>
</Link>
)
})}
{items.length <= 4 && (
<button
type="button"
onClick={onLogout}
className="flex-1 flex flex-col items-center gap-1 pt-2 pb-1.5 text-[10.5px] font-medium text-faint cursor-pointer"
>
<LogOut size={22} strokeWidth={1.8} aria-hidden />
<span className="leading-none">Log out</span>
</button>
)}
</nav>
)
}
+59
View File
@@ -0,0 +1,59 @@
import {
AlignLeft,
CircleCheck,
ClipboardList,
LayoutDashboard,
Plus,
Settings,
Users,
type LucideIcon,
} from 'lucide-react'
export interface NavItem {
label: string
href: string
icon: LucideIcon
}
const NAV_ITEMS: Record<string, NavItem[]> = {
reporter: [
{ label: 'My Reports', href: '/reporter', icon: ClipboardList },
{ 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 },
{ label: 'CAPA', href: '/hse/capa', icon: CircleCheck },
{ 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 },
{ label: 'Incidents', href: '/hse/incidents', icon: ClipboardList },
{ label: 'CAPA', href: '/hse/capa', icon: CircleCheck },
{ label: 'Management', href: '/management', icon: AlignLeft },
{ label: 'Settings', href: '/hse/settings', icon: Settings },
],
}
const EXACT_ROOTS = ['/reporter', '/supervisor', '/management', '/capa-owner', '/admin', '/report', '/account']
export function navItemsFor(role: string): NavItem[] {
return NAV_ITEMS[role] ?? NAV_ITEMS.reporter
}
export function isActivePath(href: string, pathname: string): boolean {
return EXACT_ROOTS.includes(href) ? pathname === href : pathname.startsWith(href)
}
export function searchHrefFor(role: string): string | null {
if (role === 'hse' || role === 'admin') return '/hse/incidents'
if (role === 'supervisor') return '/supervisor/incidents'
return null
}
-202
View File
@@ -1,202 +0,0 @@
'use client'
import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import {
AlignLeft,
CircleCheck,
ClipboardList,
LayoutDashboard,
LogOut,
Plus,
Settings,
User,
Users,
} from 'lucide-react'
import { NotificationBell } from '@/components/notifications/bell'
interface NavItem {
label: string
href: string
icon: React.ReactNode
}
interface SidebarProps {
role: string
userName: string
userEmail: string
}
const IconGrid = () => <AlignLeft size={20} aria-hidden />
const IconList = () => <ClipboardList size={20} aria-hidden />
const IconCheck = () => <CircleCheck size={20} aria-hidden />
const IconChart = () => <LayoutDashboard size={20} aria-hidden />
const IconSettings = () => <Settings size={20} aria-hidden />
const IconUsers = () => <Users size={20} aria-hidden />
const IconPlus = () => <Plus size={20} aria-hidden />
const IconLogout = () => <LogOut size={16} aria-hidden />
const IconUser = () => <User size={16} aria-hidden />
const NAV_ITEMS: Record<string, NavItem[]> = {
reporter: [
{ label: 'My Reports', href: '/reporter', icon: <IconList /> },
{ label: 'New Incident', href: '/report', icon: <IconPlus /> },
],
supervisor: [
{ label: 'Overview', href: '/supervisor', icon: <IconGrid /> },
{ label: 'Incidents', href: '/supervisor/incidents', icon: <IconList /> },
],
hse: [
{ label: 'Dashboard', href: '/hse/dashboard', icon: <IconChart /> },
{ label: 'Incidents', href: '/hse/incidents', icon: <IconList /> },
{ label: 'CAPA', href: '/hse/capa', icon: <IconCheck /> },
{ label: 'Settings', href: '/hse/settings', icon: <IconSettings /> },
],
management: [
{ label: 'Dashboard', href: '/management', icon: <IconChart /> },
],
capa_owner: [
{ label: 'My CAPAs', href: '/capa-owner', icon: <IconCheck /> },
],
admin: [
{ label: 'Admin', href: '/admin', icon: <IconUsers /> },
{ label: 'Dashboard', href: '/hse/dashboard', icon: <IconChart /> },
{ label: 'Incidents', href: '/hse/incidents', icon: <IconList /> },
{ label: 'CAPA', href: '/hse/capa', icon: <IconCheck /> },
{ label: 'Management', href: '/management', icon: <IconGrid /> },
{ label: 'Settings', href: '/hse/settings', icon: <IconSettings /> },
],
}
const EXACT_ROOTS = ['/reporter', '/supervisor', '/management', '/capa-owner', '/admin', '/report', '/account']
function isActivePath(href: string, pathname: string): boolean {
return EXACT_ROOTS.includes(href) ? pathname === href : pathname.startsWith(href)
}
function initials(name: string): string {
return name
.split(' ')
.map(w => w[0] ?? '')
.join('')
.toUpperCase()
.slice(0, 2)
}
function useNavItems(role: string): NavItem[] {
return NAV_ITEMS[role] ?? NAV_ITEMS.reporter
}
const LINK_BASE = 'flex items-center gap-3 px-3 py-2 text-sm border-l-2 transition-colors'
const LINK_ACTIVE = 'border-accent text-accent-700 font-extrabold bg-accent-100/50'
const LINK_IDLE = 'border-transparent text-ink/70 font-medium hover:bg-ink/7 hover:text-ink'
function NavLink({ item, pathname }: { item: NavItem; pathname: string }) {
const active = isActivePath(item.href, pathname)
return (
<Link
href={item.href}
aria-current={active ? 'page' : undefined}
className={`${LINK_BASE} ${active ? LINK_ACTIVE : LINK_IDLE}`}
>
<span className={active ? 'text-accent-700' : 'text-ink/50'}>{item.icon}</span>
{item.label}
</Link>
)
}
export function Sidebar({ role, userName, userEmail }: SidebarProps) {
const pathname = usePathname()
const router = useRouter()
const items = useNavItems(role)
const mobileItems = items.slice(0, 4)
const logout = async () => {
await fetch('/api/auth/logout', { method: 'POST' })
router.push('/login')
router.refresh()
}
const displayName = userName || userEmail || 'User'
const roleLabel = role.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
const accountActive = pathname === '/account'
return (
<>
{/* Desktop sidebar */}
<aside className="hidden sm:flex fixed left-0 top-0 h-full w-60 bg-ground border-r-2 border-divider flex-col z-40">
<div className="flex items-center justify-between px-4 py-4 border-b-2 border-divider">
<span className="text-lg font-extrabold tracking-tight text-ink">IMS</span>
<NotificationBell />
</div>
<nav className="flex-1 overflow-y-auto py-3">
{items.map(item => (
<NavLink key={item.href} item={item} pathname={pathname} />
))}
</nav>
<div className="border-t-2 border-divider py-3">
<div className="flex items-center gap-2 px-4 py-2 mb-1">
<div className="w-8 h-8 rounded-full bg-accent flex items-center justify-center text-ground text-xs font-extrabold flex-shrink-0">
{initials(displayName)}
</div>
<div className="min-w-0">
<p className="text-sm font-extrabold text-ink truncate">{displayName}</p>
<p className="text-xs text-ink/60 truncate">{roleLabel}</p>
</div>
</div>
<Link
href="/account"
aria-current={accountActive ? 'page' : undefined}
className={`${LINK_BASE} ${accountActive ? LINK_ACTIVE : LINK_IDLE}`}
>
<span className={accountActive ? 'text-accent-700' : 'text-ink/50'}>
<IconUser />
</span>
Account
</Link>
<button
onClick={logout}
className={`${LINK_BASE} ${LINK_IDLE} w-full text-left cursor-pointer`}
>
<span className="text-ink/50"><IconLogout /></span>
Logout
</button>
<div className="mt-3 pt-3 border-t border-divider px-4">
<p className="text-xs text-ink/50">v1.2.2</p>
</div>
</div>
</aside>
{/* Mobile bottom tab bar */}
<nav className="sm:hidden fixed bottom-0 left-0 right-0 bg-ground border-t-2 border-divider flex z-40 safe-area-pb">
{mobileItems.map(item => {
const active = isActivePath(item.href, pathname)
return (
<Link
key={item.href}
href={item.href}
aria-current={active ? 'page' : undefined}
className={`flex-1 flex flex-col items-center gap-1 py-2 text-[10px] font-extrabold transition-colors ${
active ? 'text-accent-700' : 'text-ink/55'
}`}
>
{item.icon}
<span className="leading-none">{item.label}</span>
</Link>
)
})}
{items.length <= 4 && (
<button
onClick={logout}
className="flex-1 flex flex-col items-center gap-1 py-2 text-[10px] font-extrabold text-ink/55 cursor-pointer"
>
<IconLogout />
<span className="leading-none">Logout</span>
</button>
)}
</nav>
</>
)
}
+66 -37
View File
@@ -1,8 +1,10 @@
'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useState } from 'react'
import Link from 'next/link'
import { Bell } from 'lucide-react'
import { Drawer } from '@/components/ui/drawer'
import { cx } from '@/components/ui/cx'
type Notification = {
id: string
@@ -14,11 +16,15 @@ type Notification = {
const POLL_MS = 60_000
function isToday(iso: string): boolean {
return new Date(iso).toDateString() === new Date().toDateString()
}
export function NotificationBell() {
const [notifications, setNotifications] = useState<Notification[]>([])
const [unread, setUnread] = useState(0)
const [open, setOpen] = useState(false)
const panelRef = useRef<HTMLDivElement>(null)
const [tab, setTab] = useState<'all' | 'unread'>('all')
const load = useCallback(() => {
fetch('/api/notifications')
@@ -36,15 +42,6 @@ export function NotificationBell() {
return () => clearInterval(id)
}, [load])
useEffect(() => {
if (!open) return
const onClick = (e: MouseEvent) => {
if (panelRef.current && !panelRef.current.contains(e.target as Node)) setOpen(false)
}
document.addEventListener('mousedown', onClick)
return () => document.removeEventListener('mousedown', onClick)
}, [open])
const markAllRead = () => {
fetch('/api/notifications', {
method: 'POST',
@@ -58,62 +55,94 @@ export function NotificationBell() {
.catch(() => {})
}
const shown = tab === 'unread' ? notifications.filter(n => !n.read_at) : notifications
const groups: Array<{ label: string; items: Notification[] }> = [
{ label: 'Today', items: shown.filter(n => isToday(n.sent_at)) },
{ label: 'Earlier', items: shown.filter(n => !isToday(n.sent_at)) },
].filter(g => g.items.length > 0)
return (
<div ref={panelRef} className="fixed top-3 right-3 z-50">
<>
<button
onClick={() => setOpen(o => !o)}
type="button"
onClick={() => setOpen(true)}
aria-label={`Notifications${unread > 0 ? ` (${unread} unread)` : ''}`}
className="relative bg-surface border border-divider w-10 h-10 flex items-center justify-center text-ink cursor-pointer transition-colors hover:bg-ink/7 active:bg-ink/15"
className="relative inline-grid place-items-center w-8 h-8 rounded-md text-neutral-300 hover:bg-ink-2 cursor-pointer"
>
<Bell size={18} strokeWidth={2} aria-hidden />
<Bell size={16} strokeWidth={2} aria-hidden />
{unread > 0 && (
<span className="absolute -top-1 -right-1 bg-accent text-ground text-[10px] font-extrabold min-w-[18px] h-[18px] px-1 flex items-center justify-center">
<span className="absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 rounded-full bg-accent text-white text-[10px] font-semibold grid place-items-center">
{unread > 99 ? '99+' : unread}
</span>
)}
</button>
{open && (
<div className="absolute right-0 mt-2 w-80 max-h-96 overflow-y-auto bg-surface shadow-lg border border-divider">
<div className="flex items-center justify-between px-4 py-2 border-b-2 border-divider">
<span className="text-sm font-extrabold text-ink">Notifications</span>
{unread > 0 && (
<button onClick={markAllRead} className="text-xs text-accent-700 hover:underline">
<Drawer
open={open}
onClose={() => setOpen(false)}
title="Notifications"
actions={
unread > 0 ? (
<button
type="button"
onClick={markAllRead}
className="px-2 text-[12.5px] font-[550] text-accent hover:underline cursor-pointer"
>
Mark all read
</button>
) : undefined
}
>
<div className="flex gap-0.5 px-3 pb-2 border-b border-rule">
{(['all', 'unread'] as const).map(t => (
<button
key={t}
type="button"
onClick={() => setTab(t)}
className={cx(
'inline-flex items-center gap-1.5 h-7 px-2.5 rounded-md text-[13px] cursor-pointer',
tab === t ? 'bg-rule-2 font-semibold' : 'font-medium text-ink-3 hover:bg-surface-2',
)}
>
{t === 'all' ? 'All' : 'Unread'}
<span className="text-xs font-medium text-faint">{t === 'all' ? notifications.length : unread}</span>
</button>
))}
</div>
{notifications.length === 0 ? (
<p className="px-4 py-6 text-sm text-gray-400 text-center">No notifications</p>
{groups.length === 0 ? (
<p className="px-4 py-10 text-sm text-faint text-center">No notifications</p>
) : (
groups.map(g => (
<section key={g.label}>
<h3 className="px-4 pt-3 pb-1 text-[11.5px] font-semibold tracking-wide uppercase text-faint">{g.label}</h3>
<ul>
{notifications.map(n => {
const inner = (
{g.items.map(n => {
const body = (
<>
<p className={`text-sm ${n.read_at ? 'text-gray-500' : 'text-gray-900 font-medium'}`}>
<p className={cx('text-[13px]', n.read_at ? 'text-muted' : 'text-ink font-medium')}>
{n.title ?? 'Notification'}
</p>
<p className="text-xs text-gray-400 mt-0.5">
{new Date(n.sent_at).toLocaleString()}
</p>
<p className="text-xs text-faint mt-0.5">{new Date(n.sent_at).toLocaleString()}</p>
</>
)
return (
<li key={n.id} className="border-b border-gray-50 last:border-0">
<li key={n.id} className={cx('border-b border-rule', !n.read_at && 'bg-accent-tint')}>
{n.link ? (
<Link href={n.link} className="block px-4 py-3 hover:bg-gray-50" onClick={() => setOpen(false)}>
{inner}
<Link href={n.link} className="block px-4 py-3" onClick={() => setOpen(false)}>
{body}
</Link>
) : (
<div className="px-4 py-3">{inner}</div>
<div className="px-4 py-3">{body}</div>
)}
</li>
)
})}
</ul>
</section>
))
)}
</div>
)}
</div>
</Drawer>
</>
)
}
+2 -2
View File
@@ -49,8 +49,8 @@ export function ApiKeyForm({ settings }: Props) {
<label className="text-sm font-semibold text-gray-800">{KEY_LABELS[key]}</label>
<span className={`text-xs font-medium px-2 py-0.5 ${
status?.set
? 'bg-neutral-100 text-ink'
: 'bg-accent-100 text-accent-700'
? 'bg-st-green-bg text-st-green-fg'
: 'bg-st-amber-bg text-st-amber-fg'
}`}>
{status?.set ? 'Configured' : 'Not set'}
</span>
+16
View File
@@ -0,0 +1,16 @@
export function initials(name: string): string {
return name
.split(' ')
.map(w => w[0] ?? '')
.join('')
.toUpperCase()
.slice(0, 2)
}
export function Avatar({ name }: { name: string }) {
return (
<span className="inline-grid place-items-center w-6 h-6 rounded-[6px] bg-accent-200 text-accent-700 text-[11px] font-[650]">
{initials(name)}
</span>
)
}
+20 -9
View File
@@ -1,25 +1,36 @@
import type { ButtonHTMLAttributes } from 'react'
import { cx } from './cx'
type Variant = 'primary' | 'secondary' | 'ghost' | 'icon'
type Variant = 'primary' | 'secondary' | 'icon'
const BASE =
'inline-flex items-center gap-1.5 text-left font-extrabold text-sm leading-tight ' +
'border border-transparent cursor-pointer transition-colors ' +
'inline-flex items-center justify-center gap-1.5 whitespace-nowrap transition-colors cursor-pointer ' +
'disabled:opacity-45 disabled:cursor-not-allowed'
const VARIANTS: Record<Variant, string> = {
primary: 'justify-start bg-accent text-ground px-3.5 py-2 hover:bg-accent-600 active:bg-accent-700',
secondary: 'justify-start border-divider text-ink px-3.5 py-2 hover:bg-ink/7 active:bg-ink/15',
ghost: 'justify-start text-accent-700 px-1 py-2 hover:bg-accent/10 active:bg-accent/20',
icon: 'justify-center w-9 h-9 p-0 text-ink hover:bg-ink/7 active:bg-ink/15',
primary: 'h-8 px-3 rounded-md bg-ink-2 text-white text-[13px] font-semibold shadow-primary hover:bg-ink active:bg-black',
secondary: 'h-8 px-3 rounded-md bg-surface text-ink text-[13px] font-medium shadow-secondary hover:bg-surface-2 active:bg-rule',
icon: 'w-7 h-7 rounded-md text-ink-3 hover:bg-rule',
}
type Props = ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: Variant
block?: boolean
mobile?: boolean
}
export function Button({ variant = 'primary', block = false, className, type = 'button', ...rest }: Props) {
return <button type={type} className={cx(BASE, VARIANTS[variant], block && 'w-full', className)} {...rest} />
export function buttonClass(
variant: Variant = 'primary',
opts: { block?: boolean; mobile?: boolean } = {},
): string {
return cx(
BASE,
VARIANTS[variant],
opts.mobile && variant !== 'icon' && 'h-12 rounded-xl text-sm',
opts.block && 'w-full',
)
}
export function Button({ variant = 'primary', block = false, mobile = false, className, type = 'button', ...rest }: Props) {
return <button type={type} className={cx(buttonClass(variant, { block, mobile }), className)} {...rest} />
}
+5 -5
View File
@@ -12,11 +12,11 @@ export function Card({
children?: ReactNode
}) {
return (
<div className="flex flex-col gap-2 p-3 bg-surface">
{kicker && <span className="text-[10px] tracking-[0.1em] uppercase text-accent-700">{kicker}</span>}
{title && <h3 className="text-[17px] leading-tight font-extrabold">{title}</h3>}
{children && <div className="flex-1 text-[13px] opacity-80">{children}</div>}
{meta && <div className="flex items-center gap-1.5 text-[11px] text-ink/50">{meta}</div>}
<div className="flex flex-col gap-2 p-4 bg-surface rounded-xl shadow-card">
{kicker && <span className="text-[11px] font-semibold tracking-wide uppercase text-muted">{kicker}</span>}
{title && <h3 className="text-base font-[650]">{title}</h3>}
{children && <div className="flex-1 text-[13px] text-ink-3">{children}</div>}
{meta && <div className="flex items-center gap-1.5 text-xs text-faint">{meta}</div>}
</div>
)
}
+34
View File
@@ -0,0 +1,34 @@
import { Check, Minus } from 'lucide-react'
import { cx } from './cx'
export function Checkbox({
checked,
indeterminate = false,
onChange,
label,
}: {
checked: boolean
indeterminate?: boolean
onChange: (next: boolean) => void
label: string
}) {
const on = checked || indeterminate
return (
<button
type="button"
role="checkbox"
aria-checked={indeterminate ? 'mixed' : checked}
aria-label={label}
onClick={e => {
e.stopPropagation()
onChange(!checked)
}}
className={cx(
'inline-grid place-items-center w-4 h-4 rounded-[5px] cursor-pointer',
on ? 'bg-accent text-white' : 'bg-surface shadow-[inset_0_0_0_1.5px_var(--color-faint)]',
)}
>
{indeterminate ? <Minus size={12} strokeWidth={3} aria-hidden /> : checked ? <Check size={12} strokeWidth={3} aria-hidden /> : null}
</button>
)
}
+51
View File
@@ -0,0 +1,51 @@
'use client'
import { useEffect } from 'react'
import { X } from 'lucide-react'
import { Button } from './button'
export function Drawer({
open,
onClose,
title,
actions,
children,
}: {
open: boolean
onClose: () => void
title: string
actions?: React.ReactNode
children: React.ReactNode
}) {
useEffect(() => {
if (!open) return
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [open, onClose])
if (!open) return null
return (
<div className="fixed inset-0 z-50">
<div className="absolute inset-0 bg-black/30" onClick={onClose} aria-hidden />
<aside
role="dialog"
aria-modal="true"
aria-label={title}
className="absolute top-2 right-2 bottom-2 w-[420px] max-w-[calc(100vw-16px)] flex flex-col overflow-hidden rounded-2xl bg-surface shadow-drawer"
>
<div className="flex items-center justify-between px-4 pt-3.5 pb-2.5">
<h2 className="text-base font-[650]">{title}</h2>
<div className="flex items-center gap-1">
{actions}
<Button variant="icon" aria-label="Close" onClick={onClose}>
<X size={16} strokeWidth={2} aria-hidden />
</Button>
</div>
</div>
<div className="flex-1 overflow-y-auto">{children}</div>
</aside>
</div>
)
}
+4 -5
View File
@@ -2,14 +2,13 @@ import type { InputHTMLAttributes, ReactNode, SelectHTMLAttributes, TextareaHTML
import { cx } from './cx'
export const INPUT_CLASS =
'w-full min-h-9 px-2.5 py-1.5 text-sm text-ink caret-accent bg-surface border border-divider ' +
'hover:border-ink/45 focus-visible:border-accent focus-visible:outline-offset-0 ' +
'disabled:opacity-45 disabled:cursor-not-allowed'
'w-full h-9 px-3 rounded-md bg-surface text-[13px] text-ink caret-accent shadow-input ' +
'placeholder:text-faint disabled:opacity-45 disabled:cursor-not-allowed'
export function Field({ label, htmlFor, children }: { label: string; htmlFor: string; children: ReactNode }) {
return (
<div>
<label htmlFor={htmlFor} className="block text-xs mb-[5px] text-ink/70">
<label htmlFor={htmlFor} className="block text-xs text-muted mb-[5px]">
{label}
</label>
{children}
@@ -22,7 +21,7 @@ export function Input({ className, ...rest }: InputHTMLAttributes<HTMLInputEleme
}
export function Textarea({ className, ...rest }: TextareaHTMLAttributes<HTMLTextAreaElement>) {
return <textarea className={cx(INPUT_CLASS, 'min-h-[90px] resize-y', className)} {...rest} />
return <textarea className={cx(INPUT_CLASS, 'h-auto min-h-[90px] py-2 resize-y', className)} {...rest} />
}
export function Select({ className, ...rest }: SelectHTMLAttributes<HTMLSelectElement>) {
+49
View File
@@ -0,0 +1,49 @@
import { ChevronDown, X } from 'lucide-react'
import { cx } from './cx'
export function FilterChip({
label,
value,
options,
onChange,
}: {
label: string
value: string
options: Array<{ value: string; label: string }>
onChange: (value: string) => void
}) {
const selected = options.find(o => o.value === value)
const set = Boolean(value && selected)
return (
<label
className={cx(
'relative inline-flex items-center gap-1 h-7 px-2.5 rounded-md text-[12.5px] whitespace-nowrap cursor-pointer',
set ? 'bg-accent-tint-2 text-accent-700 shadow-chip-set' : 'bg-surface text-ink-2 shadow-chip',
)}
>
<span>{set ? `${label}: ${selected!.label}` : label}</span>
{!set && <ChevronDown size={12} strokeWidth={2.5} aria-hidden />}
<select
aria-label={label}
value={value}
onChange={e => onChange(e.target.value)}
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
>
<option value="">{label}</option>
{options.map(o => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
</select>
{set && (
<button
type="button"
aria-label={`Clear ${label}`}
onClick={() => onChange('')}
className="relative z-10 inline-grid place-items-center w-4 h-4 cursor-pointer"
>
<X size={12} strokeWidth={2.5} aria-hidden />
</button>
)}
</label>
)
}
+10 -13
View File
@@ -2,6 +2,7 @@
import { useEffect } from 'react'
import { X } from 'lucide-react'
import { Button } from './button'
interface ModalProps {
open: boolean
@@ -26,21 +27,17 @@ export function Modal({ open, onClose, title, children, footer, width = 'md' }:
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4" role="dialog" aria-modal="true">
<div className="absolute inset-0 bg-neutral-900/50" onClick={onClose} />
<div className={`relative w-full ${maxW} bg-surface shadow-lg`}>
<div className="flex items-center justify-between px-6 py-4 border-b-2 border-divider">
<h2 className="text-xl font-extrabold text-ink">{title}</h2>
<button
onClick={onClose}
aria-label="Close"
className="inline-flex w-9 h-9 items-center justify-center text-ink cursor-pointer transition-colors hover:bg-ink/7 active:bg-ink/15"
>
<X size={18} strokeWidth={2} aria-hidden />
</button>
<div className="absolute inset-0 bg-black/30" onClick={onClose} />
<div className={`relative w-full ${maxW} bg-surface rounded-xl shadow-float`}>
<div className="flex items-center justify-between px-5 py-3.5 border-b border-rule">
<h2 className="text-base font-[650]">{title}</h2>
<Button variant="icon" aria-label="Close" onClick={onClose}>
<X size={16} strokeWidth={2} aria-hidden />
</Button>
</div>
<div className="px-6 py-5">{children}</div>
<div className="px-5 py-4">{children}</div>
{footer && (
<div className="px-6 py-4 border-t border-divider flex justify-end gap-2">
<div className="px-5 py-3.5 border-t border-rule flex justify-end gap-2">
{footer}
</div>
)}
+31
View File
@@ -0,0 +1,31 @@
import type { ReactNode } from 'react'
import { cx } from './cx'
export function Segmented({
value,
onChange,
options,
}: {
value: string
onChange: (v: string) => void
options: Array<{ value: string; label: ReactNode }>
}) {
return (
<div className="inline-flex p-0.5 rounded-[10px] bg-rule-2">
{options.map(o => (
<button
key={o.value}
type="button"
aria-pressed={o.value === value}
onClick={() => onChange(o.value)}
className={cx(
'inline-flex items-center gap-1.5 px-2.5 py-[5px] rounded-md text-[13px] cursor-pointer whitespace-nowrap',
o.value === value ? 'bg-surface font-semibold shadow-sm' : 'text-ink-3',
)}
>
{o.label}
</button>
))}
</div>
)
}
+43 -55
View File
@@ -1,72 +1,60 @@
import type { ReactNode } from 'react'
import {
AlarmClock,
BadgeCheck,
Circle,
CircleAlert,
CircleCheck,
ClipboardList,
ListChecks,
Loader,
RotateCcw,
Search,
type LucideIcon,
} from 'lucide-react'
import { Tag, type TagVariant } from './tag'
import { cx } from './cx'
const TONES: Record<string, TagVariant> = {
reported: 'accent',
triaged: 'outline',
investigating: 'outline',
capa_pending: 'outline',
verification: 'outline',
closed: 'neutral',
open: 'accent',
in_progress: 'outline',
overdue: 'accent',
pending_verification: 'outline',
verified: 'neutral',
reopened: 'accent',
export type StatusHue = 'amber' | 'blue' | 'violet' | 'orange' | 'indigo' | 'green' | 'grey' | 'red'
const HUES: Record<string, StatusHue> = {
reported: 'amber', triaged: 'blue', investigating: 'violet', capa_pending: 'orange',
verification: 'indigo', closed: 'green',
open: 'grey', in_progress: 'blue', overdue: 'red', pending_verification: 'indigo',
verified: 'green', reopened: 'red',
critical: 'red', high: 'orange', med: 'amber', medium: 'amber', low: 'grey', active: 'green',
}
const ICONS: Record<string, LucideIcon> = {
reported: CircleAlert,
triaged: ListChecks,
investigating: Search,
capa_pending: ClipboardList,
verification: BadgeCheck,
closed: CircleCheck,
open: Circle,
in_progress: Loader,
overdue: AlarmClock,
pending_verification: BadgeCheck,
verified: CircleCheck,
reopened: RotateCcw,
const LABELS: Record<string, string> = {
capa_pending: 'CAPA pending', pending_verification: 'Verification', in_progress: 'In progress', med: 'Medium',
}
export function statusTone(status: string): TagVariant {
return TONES[status] ?? 'neutral'
// Full literal class strings so Tailwind can see them.
const HUE_CLASS: Record<StatusHue, string> = {
amber: 'bg-st-amber-bg text-st-amber-fg',
blue: 'bg-st-blue-bg text-st-blue-fg',
violet: 'bg-st-violet-bg text-st-violet-fg',
orange: 'bg-st-orange-bg text-st-orange-fg',
indigo: 'bg-st-indigo-bg text-st-indigo-fg',
green: 'bg-st-green-bg text-st-green-fg',
grey: 'bg-st-grey-bg text-st-grey-fg',
red: 'bg-st-red-bg text-st-red-fg',
}
function humanize(value: string): string {
return value
.split('_')
.map(w => (w === 'capa' ? 'CAPA' : w.charAt(0).toUpperCase() + w.slice(1)))
.join(' ')
export function statusHue(key: string): StatusHue {
return HUES[key] ?? 'grey'
}
export function StatusTag({ status, children }: { status: string; children?: ReactNode }) {
const Icon = ICONS[status]
function label(key: string): string {
if (LABELS[key]) return LABELS[key]
const words = key.split('_').join(' ')
return words.charAt(0).toUpperCase() + words.slice(1)
}
function Pill({ hue, className, children }: { hue: StatusHue; className?: string; children: ReactNode }) {
return (
<Tag variant={statusTone(status)}>
{Icon && <Icon size={12} strokeWidth={2} aria-hidden />}
{children ?? humanize(status)}
</Tag>
<span
className={cx(
'inline-flex items-center px-2 py-0.5 rounded-md text-xs font-[550] whitespace-nowrap',
HUE_CLASS[hue],
className,
)}
>
{children}
</span>
)
}
const PRIORITY_TONES: Record<string, TagVariant> = { high: 'accent', med: 'outline', low: 'neutral' }
export function StatusTag({ status, children }: { status: string; children?: ReactNode }) {
return <Pill hue={statusHue(status)}>{children ?? label(status)}</Pill>
}
export function PriorityTag({ priority, children }: { priority: string; children?: ReactNode }) {
return <Tag variant={PRIORITY_TONES[priority] ?? 'neutral'}>{children ?? humanize(priority)}</Tag>
return <Pill hue={statusHue(priority)}>{children ?? label(priority)}</Pill>
}
+226
View File
@@ -0,0 +1,226 @@
'use client'
import type { ReactNode } from 'react'
import { ArrowDown, ArrowUp, ChevronLeft, ChevronRight, ChevronsUpDown, Inbox } from 'lucide-react'
import { Checkbox } from './checkbox'
import { cx } from './cx'
export type Column<T> = { key: string; header: string; sortKey?: string; cell: (row: T) => ReactNode }
export type Sort = { key: string; dir: 'asc' | 'desc' }
export type TableView = { key: string; label: string; count?: number }
export interface TableCardProps<T> {
columns: Column<T>[]
rows: T[]
rowKey: (row: T) => string
onRowOpen?: (row: T) => void
rowActions?: (row: T) => ReactNode
views?: { items: TableView[]; active: string; onChange: (key: string) => void }
toolbar?: ReactNode
sort?: Sort
onSortChange?: (sortKey: string) => void
selection?: { selected: Set<string>; onChange: (next: Set<string>) => void }
bulkActions?: ReactNode
footer?: { from: number; to: number; total: number; page: number; pageCount: number; onPage: (page: number) => void }
empty?: { title: string; action?: ReactNode }
mobileRow?: (row: T) => ReactNode
}
const TH = 'px-3 py-[9px] text-xs font-[550] text-muted text-left bg-surface-2 border-b border-rule-2 whitespace-nowrap'
const TD = 'px-3 py-3 text-[13px] border-b border-rule'
export function TableCard<T>({
columns, rows, rowKey, onRowOpen, rowActions, views, toolbar, sort, onSortChange,
selection, bulkActions, footer, empty, mobileRow,
}: TableCardProps<T>) {
const selectedOnPage = selection ? rows.filter(r => selection.selected.has(rowKey(r))).length : 0
const allSelected = rows.length > 0 && selectedOnPage === rows.length
const setAll = (next: boolean) => {
if (!selection) return
const s = new Set(selection.selected)
rows.forEach(r => (next ? s.add(rowKey(r)) : s.delete(rowKey(r))))
selection.onChange(s)
}
const setOne = (id: string, next: boolean) => {
if (!selection) return
const s = new Set(selection.selected)
if (next) s.add(id)
else s.delete(id)
selection.onChange(s)
}
const open = (row: T) => onRowOpen?.(row)
const isEmpty = rows.length === 0 && empty
return (
<div className="relative bg-surface rounded-xl shadow-card overflow-hidden">
{views && (
<div className="flex items-center gap-0.5 p-2 border-b border-rule">
{views.items.map(v => (
<button
key={v.key}
type="button"
onClick={() => views.onChange(v.key)}
className={cx(
'inline-flex items-center gap-1.5 h-7 px-2.5 rounded-md text-[13px] cursor-pointer',
v.key === views.active ? 'bg-rule-2 font-semibold text-ink' : 'font-medium text-ink-3 hover:bg-surface-2',
)}
>
{v.label}
{v.count !== undefined && <span className="text-xs font-medium text-faint">{v.count}</span>}
</button>
))}
</div>
)}
{toolbar && <div className="flex flex-wrap items-center gap-2 px-3 py-2.5 border-b border-rule">{toolbar}</div>}
{isEmpty ? (
<div className="flex flex-col items-center gap-3 px-4 py-14 text-center">
<span className="inline-grid place-items-center w-16 h-16 rounded-xl bg-surface-2 text-faint">
<Inbox size={28} strokeWidth={1.8} aria-hidden />
</span>
<p className="text-sm text-ink-3">{empty.title}</p>
{empty.action}
</div>
) : (
<>
<div className="hidden md:block overflow-x-auto">
<table className="w-full border-collapse">
<thead>
<tr>
{selection && (
<th className={cx(TH, 'w-7 pl-4')}>
<Checkbox
checked={allSelected}
indeterminate={selectedOnPage > 0 && !allSelected}
onChange={setAll}
label="Select all rows"
/>
</th>
)}
{columns.map(c => {
const sorted = sort && c.sortKey && sort.key === c.sortKey ? sort.dir : null
return (
<th
key={c.key}
className={TH}
aria-sort={sorted ? (sorted === 'asc' ? 'ascending' : 'descending') : undefined}
>
{c.sortKey && onSortChange ? (
<button
type="button"
onClick={() => onSortChange(c.sortKey!)}
className="inline-flex items-center gap-1 cursor-pointer"
>
{c.header}
{sorted === 'asc' ? (
<ArrowUp size={12} strokeWidth={2.5} className="text-ink" aria-hidden />
) : sorted === 'desc' ? (
<ArrowDown size={12} strokeWidth={2.5} className="text-ink" aria-hidden />
) : (
<ChevronsUpDown size={12} strokeWidth={2} className="text-neutral-400" aria-hidden />
)}
</button>
) : (
c.header
)}
</th>
)
})}
{rowActions && <th className={cx(TH, 'w-24')} />}
</tr>
</thead>
<tbody>
{rows.map(row => {
const id = rowKey(row)
const selected = Boolean(selection?.selected.has(id))
return (
<tr
key={id}
tabIndex={onRowOpen ? 0 : undefined}
onClick={() => open(row)}
onKeyDown={e => { if (e.key === 'Enter') open(row) }}
className={cx(
'group',
onRowOpen && 'cursor-pointer',
selected ? 'bg-accent-tint' : 'bg-surface hover:bg-surface-2',
)}
>
{selection && (
<td className={cx(TD, 'pl-4')} onClick={e => e.stopPropagation()}>
<Checkbox checked={selected} onChange={next => setOne(id, next)} label="Select row" />
</td>
)}
{columns.map(c => (
<td key={c.key} className={TD}>{c.cell(row)}</td>
))}
{rowActions && (
<td className={TD} onClick={e => e.stopPropagation()}>
<div className="flex justify-end gap-1 opacity-0 group-hover:opacity-100 focus-within:opacity-100">
{rowActions(row)}
</div>
</td>
)}
</tr>
)
})}
</tbody>
</table>
</div>
{mobileRow && (
<ul className="md:hidden">
{rows.map(row => (
<li
key={rowKey(row)}
onClick={() => open(row)}
className={cx('px-4 py-3 border-b border-rule', onRowOpen && 'cursor-pointer')}
>
{mobileRow(row)}
</li>
))}
</ul>
)}
</>
)}
{footer && (
<div className="flex items-center justify-between px-4 py-2.5 bg-surface-2 text-[13px] text-muted">
<span>{`Showing ${footer.from}–${footer.to} of ${footer.total}`}</span>
<div className="flex">
<button
type="button"
aria-label="Previous page"
disabled={footer.page <= 1}
onClick={() => footer.onPage(footer.page - 1)}
className="inline-flex items-center h-8 px-[7px] rounded-l-md bg-surface text-ink shadow-chip disabled:text-neutral-400 cursor-pointer"
>
<ChevronLeft size={16} strokeWidth={2} aria-hidden />
</button>
<button
type="button"
aria-label="Next page"
disabled={footer.page >= footer.pageCount}
onClick={() => footer.onPage(footer.page + 1)}
className="inline-flex items-center h-8 px-[7px] rounded-r-md bg-surface text-ink shadow-chip -ml-px disabled:text-neutral-400 cursor-pointer"
>
<ChevronRight size={16} strokeWidth={2} aria-hidden />
</button>
</div>
</div>
)}
{selection && bulkActions && selection.selected.size > 0 && (
<div className="sticky bottom-3 flex justify-center px-4 pb-3 pt-5 bg-gradient-to-t from-surface">
<div className="flex items-center gap-1.5 py-1.5 pr-1.5 pl-3 rounded-xl bg-surface shadow-float">
<span className="text-[13px] font-semibold px-2">{`${selection.selected.size} selected`}</span>
<span className="w-px h-5 bg-rule-2" />
{bulkActions}
</div>
</div>
)}
</div>
)
}
-5
View File
@@ -1,5 +0,0 @@
export const TABLE = 'w-full border-collapse text-sm'
export const TH =
'text-left text-[11px] uppercase tracking-[0.08em] text-ink/60 px-2 py-2 border-b-2 border-divider'
export const TR = 'hover:bg-ink/4'
export const TD = 'px-2 py-2 border-b border-divider'
-24
View File
@@ -1,24 +0,0 @@
import type { ReactNode } from 'react'
import { cx } from './cx'
export type TagVariant = 'accent' | 'neutral' | 'outline'
const VARIANTS: Record<TagVariant, string> = {
accent: 'bg-accent-100 text-accent-800',
neutral: 'bg-neutral-100 text-neutral-800',
outline: 'border border-accent text-accent-700',
}
export function Tag({ variant, children, className }: { variant: TagVariant; children: ReactNode; className?: string }) {
return (
<span
className={cx(
'inline-flex items-center gap-1 text-[11px] font-medium tracking-wide px-2.5 py-[3px] whitespace-nowrap',
VARIANTS[variant],
className,
)}
>
{children}
</span>
)
}
+143
View File
@@ -0,0 +1,143 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./support.js"></script>
</head>
<body>
<x-dc>
<helmet>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<style>
body{margin:0;background:#f7f7f7;color:#1f1f1f;font-family:Geist,system-ui,sans-serif;-webkit-font-smoothing:antialiased}
a{color:#0f766e;text-decoration:none}a:hover{text-decoration:underline}
</style>
</helmet>
<div style="max-width:1080px;margin:0 auto;padding:56px 40px 96px;display:flex;flex-direction:column;gap:56px">
<div style="display:flex;flex-direction:column;gap:12px">
<div style="font:600 12px 'Geist Mono',monospace;color:#616161;letter-spacing:.04em">IMS · UI REFRESH · HANDOFF SPEC</div>
<div style="font-size:30px;font-weight:600;letter-spacing:-.02em">Patterns, tokens and states</div>
<div style="font-size:15px;line-height:1.55;color:#4a4a4a;max-width:720px;text-wrap:pretty">Everything in <a href="IMS Admin.dc.html">IMS Admin.dc.html</a> is built from the pieces below. Values are the ones used in the mockups; map them to Tailwind theme tokens once and the screens follow. Type is Geist (UI) and Geist Mono (references, keyboard hints).</div>
</div>
<div style="display:flex;flex-direction:column;gap:20px">
<div style="font-size:18px;font-weight:600;letter-spacing:-.01em;padding-bottom:10px;border-bottom:1px solid #dcdcdc">1 · Color</div>
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:12px">
<sc-for list="{{ colors }}" as="c" hint-placeholder-count="12"><div style="display:flex;flex-direction:column;gap:8px"><div style="height:56px;border-radius:10px;background:{{ c.hex }};box-shadow:inset 0 0 0 1px rgba(0,0,0,.08)"></div><div style="font-size:13px;font-weight:550">{{ c.name }}</div><div style="font:500 12px 'Geist Mono',monospace;color:#616161">{{ c.hex }}</div><div style="font-size:12px;color:#616161;line-height:1.4">{{ c.use }}</div></div></sc-for>
</div>
<div style="font-size:14px;font-weight:600;margin-top:8px">Status pills</div>
<div style="display:flex;flex-wrap:wrap;gap:8px">
<sc-for list="{{ pills }}" as="p" hint-placeholder-count="12"><span style="display:inline-flex;align-items:center;gap:8px;padding:2px 8px 2px 8px;border-radius:8px;font-size:12px;font-weight:550;white-space:nowrap;background:{{ p.bg }};color:{{ p.fg }}">{{ p.label }}<span style="font:500 11px 'Geist Mono',monospace;opacity:.75">{{ p.bg }} / {{ p.fg }}</span></span></sc-for>
</div>
<div style="font-size:13px;color:#4a4a4a;line-height:1.5;max-width:720px">Pill text is always a dark ramp step on a light tint — never white on a saturated fill. Priority uses the same scale: Critical = red, High = orange, Medium = yellow, Low = neutral. Incident status and CAPA status share one palette so the dashboard reads consistently.</div>
</div>
<div style="display:flex;flex-direction:column;gap:20px">
<div style="font-size:18px;font-weight:600;letter-spacing:-.01em;padding-bottom:10px;border-bottom:1px solid #dcdcdc">2 · Type, radius, shadow</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:24px">
<div style="display:flex;flex-direction:column;gap:10px">
<sc-for list="{{ type }}" as="t" hint-placeholder-count="7"><div style="display:grid;grid-template-columns:150px 1fr;gap:16px;align-items:baseline;padding:8px 0;border-bottom:1px solid #ebebeb"><span style="font:500 12px 'Geist Mono',monospace;color:#616161">{{ t.spec }}</span><span style="font-size:{{ t.size }};font-weight:{{ t.w }};font-family:{{ t.fam }};letter-spacing:{{ t.ls }}">{{ t.sample }}</span></div></sc-for>
</div>
<div style="display:flex;flex-direction:column;gap:10px">
<sc-for list="{{ shape }}" as="s" hint-placeholder-count="6"><div style="display:grid;grid-template-columns:150px 1fr;gap:16px;align-items:center;padding:8px 0;border-bottom:1px solid #ebebeb"><span style="font:500 12px 'Geist Mono',monospace;color:#616161">{{ s.k }}</span><span style="font-size:13px;color:#303030">{{ s.v }}</span></div></sc-for>
</div>
</div>
</div>
<div style="display:flex;flex-direction:column;gap:20px">
<div style="font-size:18px;font-weight:600;letter-spacing:-.01em;padding-bottom:10px;border-bottom:1px solid #dcdcdc">3 · Buttons and controls</div>
<div style="display:flex;flex-wrap:wrap;gap:24px;align-items:flex-start">
<div style="display:flex;flex-direction:column;gap:10px"><span style="font-size:12px;color:#616161">Primary · 32px · #303030, inset highlight</span><span style="display:inline-flex;align-items:center;gap:6px;height:32px;padding:0 12px;border-radius:8px;background:#303030;color:#fff;font-size:13px;font-weight:600;box-shadow:inset 0 -1px 0 #000,inset 0 1px 0 rgba(255,255,255,.18),0 1px 2px rgba(0,0,0,.2);cursor:pointer;white-space:nowrap;align-self:flex-start">{{ ic.plus }}Report incident</span><span style="font-size:12px;color:#616161">hover #1f1f1f · active #000 · focus 2px ring #0f766e offset 2px</span></div>
<div style="display:flex;flex-direction:column;gap:10px"><span style="font-size:12px;color:#616161">Secondary · white, 1px #d4d4d4 ring</span><span style="display:inline-flex;align-items:center;gap:6px;height:32px;padding:0 12px;border-radius:8px;background:#fff;color:#1f1f1f;font-size:13px;font-weight:550;box-shadow:inset 0 0 0 1px #d4d4d4,0 1px 0 rgba(0,0,0,.05);cursor:pointer;white-space:nowrap;align-self:flex-start">{{ ic.download }}Export</span><span style="font-size:12px;color:#616161">hover bg #f7f7f7 · active bg #ebebeb</span></div>
<div style="display:flex;flex-direction:column;gap:10px"><span style="font-size:12px;color:#616161">Icon button · 28px, ghost</span><span style="width:28px;height:28px;border-radius:8px;display:grid;place-items:center;color:#4a4a4a;cursor:pointer;background:#ebebeb">{{ ic.more }}</span><span style="font-size:12px;color:#616161">rest transparent · hover #ebebeb</span></div>
<div style="display:flex;flex-direction:column;gap:10px"><span style="font-size:12px;color:#616161">Filter chip · 28px</span><div style="display:flex;gap:6px"><span style="display:inline-flex;align-items:center;gap:4px;height:28px;padding:0 10px;border-radius:8px;font-size:12.5px;color:#303030;box-shadow:inset 0 0 0 1px #d4d4d4;background:#fff;cursor:pointer;white-space:nowrap">Owner{{ ic.chev12 }}</span><span style="display:inline-flex;align-items:center;gap:4px;height:28px;padding:0 10px;border-radius:8px;font-size:12.5px;background:#e6f4f1;box-shadow:inset 0 0 0 1px #9fd3c7;color:#0b4f47;cursor:pointer;white-space:nowrap">Priority: Critical{{ ic.x12 }}</span></div><span style="font-size:12px;color:#616161">unset: chevron · set: teal tint + value + clear ×</span></div>
<div style="display:flex;flex-direction:column;gap:10px"><span style="font-size:12px;color:#616161">Segmented · 2px padding on #e3e3e3</span><div style="display:flex;padding:2px;border-radius:10px;background:#e3e3e3;align-self:flex-start"><span style="display:flex;align-items:center;gap:6px;padding:5px 10px;border-radius:8px;background:#fff;font-size:13px;font-weight:600;box-shadow:0 1px 2px rgba(0,0,0,.1);white-space:nowrap">{{ ic.rows }}List</span><span style="display:flex;align-items:center;gap:6px;padding:5px 10px;font-size:13px;color:#4a4a4a;white-space:nowrap">{{ ic.kanban }}Board</span></div></div>
<div style="display:flex;flex-direction:column;gap:10px"><span style="font-size:12px;color:#616161">Checkbox · 16px, radius 5</span><div style="display:flex;gap:8px;align-items:center"><span style="width:16px;height:16px;border-radius:5px;box-shadow:inset 0 0 0 1.5px #8a8a8a;background:#fff;display:block"></span><span style="width:16px;height:16px;border-radius:5px;background:#0f766e;color:#fff;display:grid;place-items:center">{{ ic.tick12 }}</span><span style="width:16px;height:16px;border-radius:5px;background:#0f766e;color:#fff;display:grid;place-items:center">{{ ic.minus12 }}</span></div><span style="font-size:12px;color:#616161">off · on · indeterminate (header)</span></div>
<div style="display:flex;flex-direction:column;gap:10px"><span style="font-size:12px;color:#616161">Text input · 36px desktop, 48px mobile</span><div style="height:36px;padding:0 12px;border-radius:8px;box-shadow:inset 0 0 0 1px #8a8a8a;background:#fff;font-size:13px;display:flex;align-items:center;color:#8a8a8a;width:220px">Placeholder</div><span style="font-size:12px;color:#616161">rest ring #8a8a8a · focus ring 2px #0f766e · error #b3261e</span></div>
</div>
</div>
<div style="display:flex;flex-direction:column;gap:20px">
<div style="font-size:18px;font-weight:600;letter-spacing:-.01em;padding-bottom:10px;border-bottom:1px solid #dcdcdc">4 · Table card</div>
<div style="font-size:13px;color:#4a4a4a;line-height:1.5;max-width:720px;text-wrap:pretty">One component wraps every list in the app. Anatomy top to bottom; every part is optional except the table and the card.</div>
<div style="background:#fff;border-radius:12px;box-shadow:0 0 0 1px rgba(0,0,0,.08),0 1px 2px rgba(0,0,0,.06);overflow:hidden;position:relative">
<div style="display:flex;align-items:center;justify-content:space-between;padding:8px;border-bottom:1px solid #ebebeb"><div style="display:flex;gap:2px;align-items:center"><div style="display:flex;align-items:center;gap:6px;height:28px;padding:0 10px;border-radius:8px;font-size:13px;font-weight:600;background:#e3e3e3;color:#1f1f1f">All <span style="font-size:12px;color:#8a8a8a;font-weight:500">248</span></div><div style="display:flex;align-items:center;gap:6px;height:28px;padding:0 10px;border-radius:8px;font-size:13px;font-weight:500;color:#4a4a4a">Open <span style="font-size:12px;color:#8a8a8a">37</span></div><div style="width:28px;height:28px;border-radius:8px;display:grid;place-items:center;color:#4a4a4a">{{ ic.plus }}</div></div><span style="font:500 11px 'Geist Mono',monospace;color:#8a8a8a;padding-right:4px">A · saved views · padding 8 · active #e3e3e3</span></div>
<div style="display:flex;align-items:center;gap:8px;padding:10px 12px;border-bottom:1px solid #ebebeb"><div style="display:flex;align-items:center;gap:8px;height:32px;padding:0 10px;border-radius:8px;box-shadow:inset 0 0 0 1px #8a8a8a;background:#fff;color:#616161;font-size:13px;min-width:260px">{{ ic.search }}<span>Search</span></div><span style="display:inline-flex;align-items:center;gap:4px;height:28px;padding:0 10px;border-radius:8px;font-size:12.5px;color:#303030;box-shadow:inset 0 0 0 1px #d4d4d4;background:#fff;white-space:nowrap">Site{{ ic.chev12 }}</span><span style="flex:1"></span><span style="font:500 11px 'Geist Mono',monospace;color:#8a8a8a">B · search + filter chips · padding 10/12</span></div>
<table><thead><tr><th style="padding:9px 12px;font-size:12px;font-weight:550;color:#616161;text-align:left;background:#f7f7f7;border-bottom:1px solid #e3e3e3;white-space:nowrap;width:28px;padding-left:16px"><span style="width:16px;height:16px;border-radius:5px;box-shadow:inset 0 0 0 1.5px #8a8a8a;background:#fff;display:block"></span></th><th style="padding:9px 12px;font-size:12px;font-weight:550;color:#616161;text-align:left;background:#f7f7f7;border-bottom:1px solid #e3e3e3;white-space:nowrap"><span style="display:inline-flex;align-items:center;gap:4px">Reference<span style="color:#1f1f1f">{{ ic.down12 }}</span></span></th><th style="padding:9px 12px;font-size:12px;font-weight:550;color:#616161;text-align:left;background:#f7f7f7;border-bottom:1px solid #e3e3e3;white-space:nowrap"><span style="display:inline-flex;align-items:center;gap:4px">Status<span style="color:#c4c4c4">{{ ic.sort12 }}</span></span></th><th style="padding:9px 12px;font-size:12px;font-weight:550;color:#616161;text-align:left;background:#f7f7f7;border-bottom:1px solid #e3e3e3;white-space:nowrap;width:100%"><span style="font:500 11px 'Geist Mono',monospace;color:#8a8a8a;font-weight:500">C · header #f7f7f7 · 12px/550 · sorted column ink, others #c4c4c4</span></th><th style="padding:9px 12px;background:#f7f7f7;border-bottom:1px solid #e3e3e3;width:100px"></th></tr></thead>
<tbody>
<tr style="background:#fff"><td style="padding:12px;font-size:13px;border-bottom:1px solid #ebebeb;padding-left:16px"><span style="width:16px;height:16px;border-radius:5px;box-shadow:inset 0 0 0 1.5px #8a8a8a;background:#fff;display:block"></span></td><td style="padding:12px;font-size:13px;border-bottom:1px solid #ebebeb"><a href="#" style="font-family:'Geist Mono',monospace;font-size:12.5px">IMS-2026-0248</a></td><td style="padding:12px;font-size:13px;border-bottom:1px solid #ebebeb"><span style="display:inline-flex;align-items:center;padding:2px 8px;border-radius:8px;font-size:12px;font-weight:550;background:#ede7ff;color:#4b2e99">Investigating</span></td><td style="padding:12px;font-size:13px;border-bottom:1px solid #ebebeb;color:#8a8a8a;font:500 11px 'Geist Mono',monospace">D · row rest · #fff · 13px · 12px cell padding · 1px #ebebeb rule</td><td style="padding:12px;border-bottom:1px solid #ebebeb"></td></tr>
<tr style="background:#f7f7f7"><td style="padding:12px;font-size:13px;border-bottom:1px solid #ebebeb;padding-left:16px"><span style="width:16px;height:16px;border-radius:5px;box-shadow:inset 0 0 0 1.5px #8a8a8a;background:#fff;display:block"></span></td><td style="padding:12px;font-size:13px;border-bottom:1px solid #ebebeb"><a href="#" style="font-family:'Geist Mono',monospace;font-size:12.5px">IMS-2026-0247</a></td><td style="padding:12px;font-size:13px;border-bottom:1px solid #ebebeb"><span style="display:inline-flex;align-items:center;padding:2px 8px;border-radius:8px;font-size:12px;font-weight:550;background:#e0efff;color:#00527c">Triaged</span></td><td style="padding:12px;font-size:13px;border-bottom:1px solid #ebebeb;color:#8a8a8a;font:500 11px 'Geist Mono',monospace">E · row hover · #f7f7f7 · quick actions appear right</td><td style="padding:12px;border-bottom:1px solid #ebebeb"><div style="display:flex;gap:4px;justify-content:flex-end"><span style="width:28px;height:28px;border-radius:8px;display:grid;place-items:center;color:#4a4a4a">{{ ic.eye }}</span><span style="width:28px;height:28px;border-radius:8px;display:grid;place-items:center;color:#4a4a4a">{{ ic.more }}</span></div></td></tr>
<tr style="background:#f2f7f6"><td style="padding:12px;font-size:13px;border-bottom:1px solid #ebebeb;padding-left:16px"><span style="width:16px;height:16px;border-radius:5px;background:#0f766e;color:#fff;display:grid;place-items:center">{{ ic.tick12 }}</span></td><td style="padding:12px;font-size:13px;border-bottom:1px solid #ebebeb"><a href="#" style="font-family:'Geist Mono',monospace;font-size:12.5px">IMS-2026-0246</a></td><td style="padding:12px;font-size:13px;border-bottom:1px solid #ebebeb"><span style="display:inline-flex;align-items:center;padding:2px 8px;border-radius:8px;font-size:12px;font-weight:550;background:#fff1c2;color:#6b4a00">Reported</span></td><td style="padding:12px;font-size:13px;border-bottom:1px solid #ebebeb;color:#8a8a8a;font:500 11px 'Geist Mono',monospace">F · row selected · #f2f7f6</td><td style="padding:12px;border-bottom:1px solid #ebebeb"></td></tr>
</tbody></table>
<div style="display:flex;align-items:center;justify-content:space-between;padding:10px 16px;background:#f7f7f7;font-size:13px;color:#616161"><span>Showing 1–3 of 248</span><span style="font:500 11px 'Geist Mono',monospace;color:#8a8a8a">G · footer #f7f7f7 · count left, pager right</span><div style="display:flex"><span style="display:inline-flex;align-items:center;height:32px;padding:0 7px;border-radius:8px 0 0 8px;background:#fff;box-shadow:inset 0 0 0 1px #d4d4d4;color:#b5b5b5">{{ ic.chevLeft }}</span><span style="display:inline-flex;align-items:center;height:32px;padding:0 7px;border-radius:0 8px 8px 0;background:#fff;box-shadow:inset 0 0 0 1px #d4d4d4;margin-left:-1px;color:#1f1f1f">{{ ic.chevRight }}</span></div></div>
<div style="display:flex;justify-content:center;padding:20px 16px 24px;background:#fcfcfc;border-top:1px solid #ebebeb"><div style="display:flex;align-items:center;gap:6px;padding:6px 6px 6px 12px;border-radius:12px;background:#fff;box-shadow:0 0 0 1px rgba(0,0,0,.1),0 12px 32px rgba(0,0,0,.18)"><span style="width:16px;height:16px;border-radius:5px;background:#0f766e;color:#fff;display:grid;place-items:center">{{ ic.tick12 }}</span><span style="font-size:13px;font-weight:600;padding:0 8px 0 4px;white-space:nowrap">1 selected</span><span style="width:1px;height:20px;background:#e3e3e3"></span><span style="display:inline-flex;align-items:center;height:32px;padding:0 12px;border-radius:8px;font-size:13px;font-weight:550">Assign</span><span style="display:inline-flex;align-items:center;height:32px;padding:0 12px;border-radius:8px;font-size:13px;font-weight:550">Export</span><span style="font:500 11px 'Geist Mono',monospace;color:#8a8a8a;padding:0 8px">H · bulk bar · floats centred above footer, appears on first selection</span></div></div>
</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;font-size:13px;color:#4a4a4a;line-height:1.55">
<div style="display:flex;flex-direction:column;gap:8px"><span style="font-weight:600;color:#1f1f1f">Behaviour</span><span>Whole row is clickable and opens the record; the checkbox cell, links and quick actions stop propagation.</span><span>Sorting is single-column; the sorted header shows a filled arrow, others a faint double chevron.</span><span>Saved views are server-side filters; the + opens "Save current filters as view". Counts update live.</span><span>Empty state replaces thead + tbody with a 64px icon tile, one line of copy and the primary action (see artboard 08).</span></div>
<div style="display:flex;flex-direction:column;gap:8px"><span style="font-weight:600;color:#1f1f1f">Mobile</span><span>Below 768px the table becomes a stacked list in the same card: reference + status on line one, type · zone on line two, date on line three, chevron right (artboard 10).</span><span>Saved views become horizontally scrolling 999px chips; filters collapse to one "Filter" button opening a sheet.</span><span>Bulk bar is replaced by a bottom sheet.</span></div>
</div>
</div>
<div style="display:flex;flex-direction:column;gap:20px">
<div style="font-size:18px;font-weight:600;letter-spacing:-.01em;padding-bottom:10px;border-bottom:1px solid #dcdcdc">5 · Layout shell</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;font-size:13px;color:#4a4a4a;line-height:1.55">
<div style="display:flex;flex-direction:column;gap:8px"><span style="font-weight:600;color:#1f1f1f">Desktop</span><span>Top bar 56px #1a1a1a: brand 224px · ⌘K search max 520px #303030 · bell + user chip 224px.</span><span>Sidebar 240px #ebebeb, padding 12, items 32px radius 8; active item white with 1px ring and teal icon; badges 999px #dcdcdc.</span><span>Main padding 24/32, column gap 16. Page title 20px/650 with actions right. Detail pages use 1fr + 320–340px side rail.</span><span>Page background #f1f1f1; cards white, radius 12, ring rgba(0,0,0,.08) + 1px shadow.</span></div>
<div style="display:flex;flex-direction:column;gap:8px"><span style="font-weight:600;color:#1f1f1f">Mobile (reporter)</span><span>390px reference. Page title 22px/650, horizontal padding 16, card gap 12.</span><span>Tab bar: white, 1px top rule, 3 items, 22px icons, 10.5px labels; active #0f766e.</span><span>Form controls 48px tall, radius 12; primary button full width 48px. Footers sit on #f1f1f1 with a 1px top rule and 30px bottom safe area.</span><span>Minimum hit target 44px everywhere.</span></div>
</div>
</div>
<div style="display:flex;flex-direction:column;gap:12px">
<div style="font-size:18px;font-weight:600;letter-spacing:-.01em;padding-bottom:10px;border-bottom:1px solid #dcdcdc">6 · Screen index</div>
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:6px 24px">
<sc-for list="{{ screens }}" as="s" hint-placeholder-count="24"><div style="display:flex;gap:10px;padding:6px 0;border-bottom:1px solid #ebebeb;font-size:13px"><span style="font:600 11px 'Geist Mono',monospace;color:#616161;width:32px;flex:none;padding-top:2px">{{ s.id }}</span><span style="flex:1">{{ s.name }}</span><span style="font-size:12px;color:#8a8a8a;white-space:nowrap">{{ s.route }}</span></div></sc-for>
</div>
</div>
</div>
</x-dc>
<script type="text/x-dc" data-dc-script>
class Component extends DCLogic {
renderVals() {
const I = (paths, s = 16, w = 2) => React.createElement('svg', { width: s, height: s, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: w, strokeLinecap: 'round', strokeLinejoin: 'round', style: { flex: 'none' } }, paths.map((d, i) => React.createElement('path', { key: i, d })));
const P = {
plus: ['M12 5v14', 'M5 12h14'], download: ['M12 3v12', 'm7 10 5 5 5-5', 'M4 19h16'], more: ['M12 12h.01', 'M19 12h.01', 'M5 12h.01'],
chevDown: ['m6 9 6 6 6-6'], x: ['M18 6 6 18', 'm6 6 12 12'], rows: ['M3 5h18v14H3z', 'M3 12h18'], kanban: ['M6 5v11', 'M12 5v6', 'M18 5v14'],
tick: ['M20 6 9 17l-5-5'], minus: ['M5 12h14'], search: ['M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z', 'm21 21-4.3-4.3'],
sort: ['m7 15 5 5 5-5', 'm7 9 5-5 5 5'], down: ['M12 5v14', 'm19 12-7 7-7-7'], eye: ['M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z', 'M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z'],
chevLeft: ['m15 18-6-6 6-6'], chevRight: ['m9 18 6-6-6-6']
};
const ic = {}; Object.keys(P).forEach(k => { ic[k] = I(P[k]); });
ic.tick12 = I(P.tick, 12, 3); ic.minus12 = I(P.minus, 12, 3); ic.more = I(P.more, 16, 3); ic.sort12 = I(P.sort, 12); ic.down12 = I(P.down, 12, 2.5); ic.x12 = I(P.x, 12, 2.5); ic.chev12 = I(P.chevDown, 12, 2.5);
const colors = [
['Ink', '#1f1f1f', 'Primary text, active sidebar text'], ['Ink 2', '#303030', 'Primary button, chip text'], ['Ink 3', '#4a4a4a', 'Secondary text, icons'], ['Muted', '#616161', 'Labels, helper text'], ['Faint', '#8a8a8a', 'Placeholders, input ring'],
['Rule', '#ebebeb', 'Row rules, sidebar bg'], ['Rule 2', '#e3e3e3', 'Header rule, segmented bg'], ['Ring', '#d4d4d4', 'Secondary button and chip ring'], ['Surface 2', '#f7f7f7', 'Table header, footer, row hover'], ['Ground', '#f1f1f1', 'Page background'],
['Teal', '#0f766e', 'Accent: checks, links, active tab icon'], ['Teal tint', '#f2f7f6', 'Selected row, selected card'], ['Teal tint 2', '#e6f4f1', 'Set filter chip (ring #9fd3c7, text #0b4f47)'], ['Danger', '#b3261e', 'Overdue text, required marks'], ['Top bar', '#1a1a1a', 'App header (#303030 for its controls)']
].map(c => ({ name: c[0], hex: c[1], use: c[2] }));
const pills = [
['Reported', '#fff1c2', '#6b4a00'], ['Triaged', '#e0efff', '#00527c'], ['Investigating', '#ede7ff', '#4b2e99'], ['CAPA pending', '#ffe6cf', '#7a3a00'], ['Verification', '#e3e8ff', '#2c3e8f'], ['Closed', '#d7f4e3', '#0c5132'],
['Open', '#ebebeb', '#4a4a4a'], ['In progress', '#e0efff', '#00527c'], ['Overdue · Critical', '#fee3e0', '#8e1f0b'], ['High', '#ffe6cf', '#7a3a00'], ['Medium', '#fff1c2', '#6b4a00'], ['Active', '#d7f4e3', '#0c5132']
].map(p => ({ label: p[0], bg: p[1], fg: p[2] }));
const type = [
['32 / 600 / -0.02em', '32px', 600, 'Geist', '-.02em', 'Cover title'], ['22 / 650 / -0.02em', '22px', 650, 'Geist', '-.02em', 'Mobile page title'], ['20 / 650 / -0.01em', '20px', 650, 'Geist', '-.01em', 'Page title'], ['16 / 650', '16px', 650, 'Geist', '-.01em', 'Card title (detail)'], ['14 / 600', '14px', 600, 'Geist', '0', 'Section heading'], ['13 / 400–550', '13px', 450, 'Geist', '0', 'Body, table cells, buttons'], ['12 / 550', '12px', 550, 'Geist', '0', 'Table header, pill, helper'], ['12.5 mono', '12.5px', 500, "'Geist Mono'", '0', 'IMS-2026-0247']
].map(t => ({ spec: t[0], size: t[1], w: t[2], fam: t[3], ls: t[4], sample: t[5] }));
const shape = [
['radius', '12 cards, phones' + ' · 10 drawer/inputs mobile · 8 buttons, chips, inputs, pills, sidebar items · 6 avatars 24px · 5 checkbox · 999 badges'],
['card', 'bg #fff · box-shadow 0 0 0 1px rgba(0,0,0,.08), 0 1px 2px rgba(0,0,0,.06)'],
['floating', 'box-shadow 0 0 0 1px rgba(0,0,0,.1), 0 12px 32px rgba(0,0,0,.18) (bulk bar, drawer uses 24/60 .24)'],
['focus', 'outline 2px #0f766e, offset 2px, on every interactive element'],
['spacing', '4 · 6 · 8 · 10 · 12 · 16 · 20 · 24 · 32. Card padding 16–20 · table cell 12 · toolbar 10/12'],
['icons', 'Lucide, 16px stroke 2 in UI · 12px stroke 2.5 inside chips/checks · 22px stroke 1.8 in mobile tab bar']
].map(s => ({ k: s[0], v: s[1] }));
const screens = [
['01', 'Incidents list', '/hse/incidents'], ['01b', 'Notifications drawer', 'global'], ['02', 'Incident detail', '/hse/incidents/[id]'], ['02b', 'Triage form', '/hse/incidents/[id] · triage'], ['02c', 'Investigation form', '/hse/incidents/[id] · investigation'], ['02d', 'DOSH reporting · JKKP 6', '/hse/incidents/[id] · new'],
['03', 'Dashboard', '/hse/dashboard'], ['04', 'CAPA list', '/hse/capa'], ['04b', 'CAPA board', '/hse/capa · board'], ['04c', 'CAPA detail · verification', '/hse/capa · new'],
['05', 'Admin · users', '/admin'], ['05b', 'Admin · sites & zones', '/admin · tab'], ['05c', 'Admin · trucks', '/admin · tab'], ['05d', 'Admin · audit log', '/admin · new tab'], ['06', 'Settings', '/hse/settings'], ['07', 'Reporter · my reports', '/reporter'], ['08', 'Empty state', 'pattern'],
['09', 'Mobile · reporter home', '/reporter'], ['10', 'Mobile · incidents', '/hse/incidents'], ['11', 'Mobile · incident detail', '/hse/incidents/[id]'], ['12–15', 'Mobile · new incident 1/3 → saved offline', '/report'], ['16', 'Mobile · CAPA owner action', '/capa-owner']
].map(s => ({ id: s[0], name: s[1], route: s[2] }));
return { ic, colors, pills, type, shape, screens };
}
}
</script>
</body>
</html>
File diff suppressed because one or more lines are too long
+214
View File
@@ -0,0 +1,214 @@
# IMS Design System: Admin refresh
Source of truth for IMS UI. Derived from `IMS Admin Spec.dc.html` (patterns, tokens, states) and `IMS Admin.dc.html` (25 artboards: 7 desktop screens plus variants, 9 mobile screens). When this file and the mockups disagree, fix this file and say so in the PR. The earlier Modernist system (`design-system/_ds/`) is retired.
Rules in `CLAUDE.md` ("Design system") summarise this file. Tokens in `app/globals.css` mirror §2.
## 1. Principles
- Neutral commerce-admin look: grey ground, white cards, dark primary action, one teal accent used sparingly.
- Every list is a `TableCard` (§4.9). Do not hand-build tables.
- Status is always a dark text step on a light tint, with a text label (§4.2). Never white text on a saturated fill, never colour alone.
- Rules are 1px. Corners come from the radius scale in §2.3. Text and headings are flush left.
- Minimum hit target 44px on mobile.
## 2. Tokens
### 2.1 Colour
| Token | Hex | Use |
| --- | --- | --- |
| `ink` | `#1f1f1f` | Primary text, active sidebar text |
| `ink-2` | `#303030` | Primary button, chip text |
| `ink-3` | `#4a4a4a` | Secondary text, icons |
| `muted` | `#616161` | Labels, helper text |
| `faint` | `#8a8a8a` | Placeholders, input ring |
| `rule` | `#ebebeb` | Row rules, sidebar background |
| `rule-2` | `#e3e3e3` | Header rule, segmented background |
| `ring` | `#d4d4d4` | Secondary button and chip ring |
| `surface` | `#ffffff` | Cards, rows, inputs |
| `surface-2` | `#f7f7f7` | Table header, footer, row hover |
| `ground` | `#f1f1f1` | Page background |
| `accent` | `#0f766e` | Checks, links, focus ring, active tab icon |
| `accent-tint` | `#f2f7f6` | Selected row, selected card |
| `accent-tint-2` | `#e6f4f1` | Set filter chip (ring `#9fd3c7`, text `#0b4f47`) |
| `danger` | `#b3261e` | Overdue text, required marks, input error |
| `topbar` | `#1a1a1a` | App header (its controls use `#303030`, ring `#3d3d3d`, text `#a3a3a3`) |
Tailwind names: `bg-ground`, `bg-surface`, `bg-surface-2`, `text-ink`, `text-ink-2`, `text-ink-3`, `text-muted`, `text-faint`, `border-rule`, `border-rule-2`, `border-ring`, `bg-accent`, `text-accent`, `bg-accent-tint`, `bg-accent-tint-2`, `text-danger`, `bg-topbar`.
### 2.2 Type
Geist for UI, Geist Mono for references and keyboard hints. Exposed as `--font-geist` and `--font-geist-mono`.
| Spec | Use |
| --- | --- |
| 32 / 600 / -0.02em | Cover title |
| 22 / 650 / -0.02em | Mobile page title |
| 20 / 650 / -0.01em | Page title |
| 16 / 650 / -0.01em | Card title (detail) |
| 14 / 600 | Section heading |
| 13 / 400-550 | Body, table cells, buttons |
| 12 / 550 | Table header, pill, helper |
| 12.5 mono / 500 | References such as `IMS-2026-0247` |
### 2.3 Radius, shadow, spacing, icons
- **Radius:** 12 cards and phones; 10 mobile drawer and mobile inputs; 8 buttons, chips, inputs, pills, sidebar items; 6 avatars (24px); 5 checkbox; 999 badges. Tailwind: `rounded-md` = 8, `rounded-xl` = 12, `rounded-[5px]` checkbox.
- **Card shadow** (`shadow-card`): `0 0 0 1px rgba(0,0,0,.08), 0 1px 2px rgba(0,0,0,.06)`.
- **Floating shadow** (`shadow-float`, bulk bar): `0 0 0 1px rgba(0,0,0,.1), 0 12px 32px rgba(0,0,0,.18)`. Drawer: `0 0 0 1px rgba(0,0,0,.1), 0 24px 60px rgba(0,0,0,.24)`.
- **Focus:** `outline: 2px solid accent; outline-offset: 2px` on every interactive element.
- **Spacing:** 4, 6, 8, 10, 12, 16, 20, 24, 32. Card padding 16-20, table cell 12, toolbar 10/12.
- **Icons:** Lucide. 16px stroke 2 in UI; 12px stroke 2.5 inside chips and checks; 22px stroke 1.8 in the mobile tab bar.
- **Motion:** transitions 120ms on background and shadow only.
## 3. Layout shell
**Desktop (`AppShell`)**
- Top bar 56px `topbar`: brand 224px (28px teal tile radius 8, "IMS", muted "Setia HSE"), search max 520px (34px, radius 10, shows a Cmd-K hint), bell and user chip on the right.
- Sidebar 240px `rule` background, 1px right border `#e0e0e0`, padding 12, items 32px radius 8, 13px. Active item: white, 1px ring, teal icon. Badges 999 `#dcdcdc`, 11px/600. Footer block has a 1px `#dcdcdc` top rule.
- Main: padding 24/32, column gap 16. Page title 20px/650 with actions on the right. Detail pages use `1fr` plus a 320-340px side rail.
- Page background `ground`; cards `surface`, radius 12, `shadow-card`.
**Mobile (`MobileShell`, reporter and CAPA owner)**
- 390px reference. Page title 22px/650, horizontal padding 16, card gap 12.
- Tab bar: white, 1px top rule, 3 items, 22px icons, 10.5px labels, active `accent`.
- Controls 48px tall, radius 12; primary button full width 48px. Footers sit on `ground` with a 1px top rule and 30px bottom safe area.
## 4. Components
Hover and active values below are per component. Every interactive element also gets the global focus ring (§2.3). Disabled controls drop to 45% opacity.
### 4.1 Button
- **Primary** 32px, radius 8, `#303030`, white 13px/600, inset highlight `inset 0 -1px 0 #000, inset 0 1px 0 rgba(255,255,255,.18), 0 1px 2px rgba(0,0,0,.2)`. Hover `#1f1f1f`, active `#000`.
- **Secondary** white, 13px/550, ring `inset 0 0 0 1px #d4d4d4, 0 1px 0 rgba(0,0,0,.05)`. Hover `#f7f7f7`, active `#ebebeb`.
- **Icon** 28px ghost, radius 8, `ink-3`. Hover `#ebebeb`.
- Mobile primary: full width, 48px, radius 12.
### 4.2 StatusTag and PriorityTag
Pill: `inline-flex`, padding 2px 8px, radius 8, 12px/550, no wrap. Dark text on a light tint. Incident status and CAPA status share one palette.
| Label | Background | Text |
| --- | --- | --- |
| Reported | `#fff1c2` | `#6b4a00` |
| Triaged | `#e0efff` | `#00527c` |
| Investigating | `#ede7ff` | `#4b2e99` |
| CAPA pending | `#ffe6cf` | `#7a3a00` |
| Verification | `#e3e8ff` | `#2c3e8f` |
| Closed | `#d7f4e3` | `#0c5132` |
| Open | `#ebebeb` | `#4a4a4a` |
| In progress | `#e0efff` | `#00527c` |
| Overdue / Critical | `#fee3e0` | `#8e1f0b` |
| High | `#ffe6cf` | `#7a3a00` |
| Medium | `#fff1c2` | `#6b4a00` |
| Low | `#ebebeb` | `#4a4a4a` |
| Active | `#d7f4e3` | `#0c5132` |
| Verified | `#d7f4e3` | `#0c5132` |
| Reopened | `#fee3e0` | `#8e1f0b` |
Mapping from the data model: incident `reported/triaged/investigating/capa_pending/verification/closed` use the matching rows; CAPA `open/in_progress/overdue/pending_verification/verified/reopened/closed` map to Open, In progress, Overdue, Verification, Verified, Reopened, Closed; priority `high/med/low` map to High, Medium, Low. Severity 5 and Critical use the Overdue / Critical row. Tailwind: one pair per hue, `bg-st-<hue>-bg` / `text-st-<hue>-fg`, hue in `amber blue violet orange indigo green grey red`; `StatusTag` maps each status to a hue (reported amber, triaged blue, investigating violet, capa_pending orange, verification and pending_verification indigo, closed and verified green, open and low grey, in_progress blue, overdue and reopened red, high orange, med amber). Banners follow the same pairs: error red, warning or offline amber, success green; AI suggestions and hints use `bg-accent-tint`. No icon required; the text label is always present.
### 4.3 FilterChip
28px, radius 8, 12.5px, padding 0 10px. Unset: white, ring `#d4d4d4`, text `#303030`, trailing 12px chevron. Set: `accent-tint-2`, ring `#9fd3c7`, text `#0b4f47`, shows "Label: value" and a clear x.
### 4.4 Segmented
Container padding 2px, background `#e3e3e3`, radius 10. Option 13px, padding 5px 10px, radius 8. Active: white, 13px/600, `0 1px 2px rgba(0,0,0,.1)`. Used for List / Board.
### 4.5 Checkbox
16px, radius 5. Off: white with `inset 0 0 0 1.5px #8a8a8a`. On and indeterminate (header): `accent` fill, white 12px tick or minus at stroke 3.
### 4.6 Field and Input
Input 36px desktop, 48px mobile, padding 0 12px, radius 8 (12 on mobile), 13px, white. Rest ring `inset 0 0 0 1px #8a8a8a`; focus ring 2px `accent`; error ring `danger`. Placeholder `faint`. Label 12px `muted`, 5px above. Textarea and Select share the ring.
### 4.7 Avatar
24px, radius 6, background `#c5e8e0`, text `#0b4f47`, 11px/650, initials. Top bar variant sits in a `#303030` chip.
### 4.8 Card
White, radius 12, `shadow-card`, padding 16-20. Selected card uses `accent-tint`. Detail card title 16px/650.
### 4.9 TableCard
One component wraps every list. Parts top to bottom, all optional except the table and the card:
- **A. Saved views:** padding 8, bottom rule `#ebebeb`. View chip 28px radius 8, 13px; active `#e3e3e3` 13px/600 with a faint count (12px `#8a8a8a`); trailing + button opens "Save current filters as view". Saved views are server-side filters; counts update live.
- **B. Toolbar:** padding 10/12, bottom rule. Search 32px, radius 8, ring `#8a8a8a`, min-width 260. Filter chips (§4.3). Right-aligned actions.
- **C. Header:** `surface-2`, 12px/550 `muted`, padding 9/12, bottom rule `#e3e3e3`. Single-column sort: sorted column shows a filled arrow in `ink`, others a faint `#c4c4c4` double chevron.
- **D. Row rest:** white, 13px, cell padding 12, 1px `#ebebeb` rule. References in Geist Mono 12.5px in `accent`.
- **E. Row hover:** `surface-2`; quick actions (eye, more) appear on the right as 28px icon buttons.
- **F. Row selected:** `accent-tint` and a filled checkbox.
- **G. Footer:** `surface-2`, padding 10/16, "Showing 1-3 of 248" left, pager right (32px segmented chevrons, radius 8 on outer ends, ring `#d4d4d4`).
- **H. Bulk bar:** floats centred above the footer on first selection. White, radius 12, `shadow-float`, padding 6 6 6 12; checkbox, "N selected", divider, ghost actions (Assign, Export).
- **Empty state:** replaces thead and tbody: 64px icon tile, one line of copy, the primary action.
Behaviour: the whole row opens the record; the checkbox cell, links and quick actions stop propagation.
**Mobile:** below 768px the table becomes a stacked list in the same card: reference + status on line one, type and zone on line two, date on line three, chevron right. Saved views become horizontally scrolling 999px chips; filters collapse to one "Filter" button opening a sheet; the bulk bar becomes a bottom sheet.
### 4.10 Drawer
Notifications drawer: absolute, top/right/bottom 8px, width 420px, white, radius 14, shadow `0 0 0 1px rgba(0,0,0,.1), 0 24px 60px rgba(0,0,0,.24)`; scrim `rgba(0,0,0,.28)`. Header 16px/650 title with "Mark all read" (12.5px/550 `accent`), settings and close icon buttons. Tab row of 28px view chips with counts. Group labels 11.5px/600 uppercase `faint`. Items: 32px radius-9 icon tile, padding 12/16, rule `#f0f0f0`, unread items tinted.
## 5. Screen index
| Id | Screen | Route |
| --- | --- | --- |
| 01 | Incidents list | `/hse/incidents` |
| 01b | Notifications drawer | global |
| 02 | Incident detail | `/hse/incidents/[id]` |
| 02b | Triage form | `/hse/incidents/[id]` triage |
| 02c | Investigation form | `/hse/incidents/[id]` investigation |
| 02d | DOSH reporting (JKKP 6) | `/hse/incidents/[id]` new |
| 03 | Dashboard | `/hse/dashboard` |
| 04 | CAPA list | `/hse/capa` |
| 04b | CAPA board | `/hse/capa` board |
| 04c | CAPA detail, verification | `/hse/capa` new |
| 05 | Admin, users | `/admin` |
| 05b | Admin, sites and zones | `/admin` tab |
| 05c | Admin, trucks | `/admin` tab |
| 05d | Admin, audit log | `/admin` new tab |
| 06 | Settings, API keys | `/hse/settings` |
| 07 | Reporter, my reports | `/reporter` |
| 08 | Empty state | pattern |
| 09 | Mobile, reporter home | `/reporter` |
| 10 | Mobile, incidents | `/hse/incidents` |
| 11 | Mobile, incident detail | `/hse/incidents/[id]` |
| 12-15 | Mobile, new incident 1/3 to saved offline | `/report` |
| 16 | Mobile, CAPA owner action | `/capa-owner` |
Mockup features with no backend yet (do not fake them in the UI): CAPA export, bulk actions on a selection (send reminder, reassign, escalate), group-by, department and due-date range filters, the activity and comments feed, cost, evidence files on a CAPA, the verification note, "ask owner a question", and edit. Add them in a slice that also adds the backend.
New routes in the mockup that do not exist yet: audit log (05d), DOSH reporting entry (02d), and any "new tab" marked above. Treat them as separate features; do not build them as part of the restyle.
## 6. Accessibility
- Text on tints passes contrast because pills use dark steps. Body text is `ink` or `ink-3` on white or `ground`; `faint` is for placeholders only.
- Focus ring on every interactive element; nothing relies on colour alone.
- Hit targets 44px minimum on mobile.
## 7. Scope
This file covers look and component structure. Routes, queries, permissions and audit logging do not change as part of a restyle.
## 8. Build order
1. **Tokens:** replace the Modernist tokens in `app/globals.css` with §2 (`@theme static`), Geist via `next/font`, `shadow-card`, `shadow-float`, `st-*` pairs. Keep the `gray-*`/`blue-*`/`red-*` remaps pointing at the new neutral and teal values so unmigrated pages stay readable.
2. **UI primitives:** `Button`, `StatusTag`, `PriorityTag`, `Checkbox`, `Field`/`Input`/`Select`/`Textarea`, `FilterChip`, `Segmented`, `Avatar`, `Card`, `Drawer` in `components/ui/`.
3. **TableCard** (§4.9) with the desktop and mobile variants.
4. **Shells:** `AppShell` (top bar, sidebar, notifications drawer) and `MobileShell`.
5. **Migrate the Incidents list** (screen 01 and 10) as the first full screen.
6. **Remaining screens**, in §5 order, one plan per group.
Slice 1 (gate, tokens, primitives, TableCard, shells, Incidents list) and slice 2 (CAPA list, board, detail, verification, create form) are implemented; the remaining screens follow in later plans.
Gate first: before step 1, update `scripts/check-design-gates.mjs` to allow `rounded-*`, flag `border-b-2` and `border-2`, and flag Archivo and `#ec3013`. `npm run check:design` must pass at the end of each step.
## 9. What changes from the live Modernist build
| Area | Now (Modernist) | After |
| --- | --- | --- |
| Font | Archivo | Geist and Geist Mono |
| Accent | `#ec3013` red | `#0f766e` teal (used sparingly) |
| Primary button | red, flush left | `#303030`, 32px, radius 8 |
| Radius | 0 everywhere | 8 / 10 / 12 scale |
| Rules | 2px section rules | 1px |
| Status | mono tags (accent, outline, neutral) | coloured pills (§4.2) |
| Sidebar | flat, 2px rule | dark top bar plus `#ebebeb` sidebar |
| Lists | per-page tables | `TableCard` |
| Gate | no rounded, 2px rules | rounded allowed, 2px flagged |
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+111
View File
@@ -0,0 +1,111 @@
export type CapaStatus =
| 'open' | 'in_progress' | 'overdue' | 'pending_verification' | 'verified' | 'reopened' | 'closed'
export type CapaPriority = 'low' | 'med' | 'high'
export interface CapaRow {
id: string
incident_id: string
description: string
department: string
due_date: string
priority: CapaPriority
status: CapaStatus
incident_ref: string | null
owner_name: string | null
}
export const PAGE_SIZE = 25
export const STATUS_ORDER: CapaStatus[] = [
'open', 'in_progress', 'overdue', 'reopened', 'pending_verification', 'verified', 'closed',
]
export type CapaViewKey = 'all' | 'active' | 'overdue' | 'verification' | 'done'
export const VIEWS: Array<{ key: CapaViewKey; label: string; statuses: CapaStatus[] | null }> = [
{ key: 'all', label: 'All', statuses: null },
{ key: 'active', label: 'Active', statuses: ['open', 'in_progress', 'reopened'] },
{ key: 'overdue', label: 'Overdue', statuses: ['overdue'] },
{ key: 'verification', label: 'Verification', statuses: ['pending_verification'] },
{ key: 'done', label: 'Done', statuses: ['verified', 'closed'] },
]
export interface CapaFilters {
q: string
owner: string
department: string
priority: string
view: CapaViewKey
}
export const EMPTY_FILTERS: CapaFilters = { q: '', owner: '', department: '', priority: '', view: 'all' }
export type CapaSortKey = 'due_date' | 'priority' | 'status'
export type CapaSort = { key: CapaSortKey; dir: 'asc' | 'desc' }
function matchesOthers(r: CapaRow, f: CapaFilters): boolean {
if (f.owner && r.owner_name !== f.owner) return false
if (f.department && r.department !== f.department) return false
if (f.priority && r.priority !== f.priority) return false
if (f.q) {
const q = f.q.toLowerCase()
const hay = `${r.description} ${r.incident_ref ?? ''} ${r.owner_name ?? ''}`.toLowerCase()
if (!hay.includes(q)) return false
}
return true
}
function inView(r: CapaRow, view: CapaViewKey): boolean {
const statuses = VIEWS.find(v => v.key === view)?.statuses ?? null
return statuses === null || statuses.includes(r.status)
}
export function filterCapas(rows: CapaRow[], f: CapaFilters): CapaRow[] {
return rows.filter(r => matchesOthers(r, f) && inView(r, f.view))
}
export function viewCounts(rows: CapaRow[], f: CapaFilters): Record<CapaViewKey, number> {
const scoped = rows.filter(r => matchesOthers(r, f))
const counts = {} as Record<CapaViewKey, number>
for (const v of VIEWS) counts[v.key] = scoped.filter(r => inView(r, v.key)).length
return counts
}
const PRIORITY_RANK: Record<CapaPriority, number> = { high: 0, med: 1, low: 2 }
export function sortCapas(rows: CapaRow[], sort: CapaSort): CapaRow[] {
const sign = sort.dir === 'asc' ? 1 : -1
const key = (r: CapaRow): number | string =>
sort.key === 'priority' ? PRIORITY_RANK[r.priority]
: sort.key === 'status' ? STATUS_ORDER.indexOf(r.status)
: r.due_date
return [...rows].sort((a, b) => {
const ka = key(a)
const kb = key(b)
return ka < kb ? -sign : ka > kb ? sign : 0
})
}
export function nextSort(current: CapaSort, key: CapaSortKey): CapaSort {
if (current.key === key) return { key, dir: current.dir === 'asc' ? 'desc' : 'asc' }
return { key, dir: 'asc' }
}
export function paginate<T>(rows: T[], page: number, size: number) {
const total = rows.length
const pageCount = Math.max(1, Math.ceil(total / size))
const p = Math.min(Math.max(1, page), pageCount)
const items = rows.slice((p - 1) * size, p * size)
const from = items.length === 0 ? 0 : (p - 1) * size + 1
const to = items.length === 0 ? 0 : from + items.length - 1
return { items, from, to, total, page: p, pageCount }
}
export function distinct(values: Array<string | null | undefined>): string[] {
return [...new Set(values.filter((v): v is string => Boolean(v)))].sort()
}
export function daysLate(due: string, today: string): number {
const diff = Math.round((Date.parse(today) - Date.parse(due)) / 86_400_000)
return Math.max(0, diff)
}
+4
View File
@@ -3,3 +3,7 @@ import OpenAI from 'openai'
export function createDeepSeekClient(apiKey: string): OpenAI {
return new OpenAI({ apiKey, baseURL: 'https://api.deepseek.com' })
}
export function createLocalLLMClient(): OpenAI {
return new OpenAI({ apiKey: 'local', baseURL: 'http://localhost:11434/v1' })
}
+59
View File
@@ -0,0 +1,59 @@
export const PAGE_SIZE = 25
export const OPEN_STATUSES = ['reported', 'triaged', 'investigating', 'capa_pending', 'verification'] as const
export type SortKey = 'reported_at' | 'reference_no' | 'status'
export type ListView = 'all' | 'open' | 'closed'
export interface ListParams {
page: number
q: string
status: string
type: string
siteId: string
truckId: string
view: ListView
sort: SortKey
dir: 'asc' | 'desc'
}
type Raw = {
page?: string; q?: string; status?: string; type?: string; site_id?: string; truck_id?: string
view?: string; sort?: string; dir?: string
}
const SORT_KEYS: SortKey[] = ['reported_at', 'reference_no', 'status']
const VIEWS: ListView[] = ['all', 'open', 'closed']
export function parseListParams(raw: Raw): ListParams {
const page = Number.parseInt(raw.page ?? '1', 10)
return {
page: Number.isFinite(page) && page > 0 ? page : 1,
q: raw.q ?? '',
status: raw.status ?? '',
type: raw.type ?? '',
siteId: raw.site_id ?? '',
truckId: raw.truck_id ?? '',
view: VIEWS.includes(raw.view as ListView) ? (raw.view as ListView) : 'all',
sort: SORT_KEYS.includes(raw.sort as SortKey) ? (raw.sort as SortKey) : 'reported_at',
dir: raw.dir === 'asc' ? 'asc' : 'desc',
}
}
export function nextSort(
current: { key: SortKey; dir: 'asc' | 'desc' },
key: SortKey,
): { key: SortKey; dir: 'asc' | 'desc' } {
if (current.key === key) return { key, dir: current.dir === 'asc' ? 'desc' : 'asc' }
return { key, dir: key === 'reported_at' ? 'desc' : 'asc' }
}
export function withParams(search: string, updates: Record<string, string | null>): string {
const p = new URLSearchParams(search)
for (const [k, v] of Object.entries(updates)) {
if (v) p.set(k, v)
else p.delete(k)
}
if (!('page' in updates)) p.delete('page')
const s = p.toString()
return s ? `?${s}` : ''
}
+97
View File
@@ -0,0 +1,97 @@
import { and, asc, desc, eq, ilike, inArray, or, sql, aliasedTable } from 'drizzle-orm'
import { asAdmin } from '@/lib/db/with-user'
import { incidents, sites, trucks, users, zones } from '@/lib/db/schema'
import { OPEN_STATUSES, PAGE_SIZE, type ListParams } from './list-params'
import type { Incident, SiteOption, TruckOption } from './types'
export interface IncidentListData {
incidents: Incident[]
total: number
counts: { all: number; open: number; closed: number }
sites: SiteOption[]
trucks: TruckOption[]
}
export async function loadIncidentList(p: ListParams): Promise<IncidentListData> {
const reporter = aliasedTable(users, 'reporter')
const base = []
if (p.q) base.push(or(ilike(incidents.referenceNo, `%${p.q}%`), ilike(incidents.description, `%${p.q}%`)))
if (p.type) base.push(eq(incidents.incidentType, p.type as never))
if (p.siteId) base.push(eq(incidents.siteId, p.siteId))
if (p.truckId) base.push(eq(incidents.truckId, p.truckId))
const scoped = [...base]
if (p.status) scoped.push(eq(incidents.status, p.status as never))
if (p.view === 'open') scoped.push(inArray(incidents.status, [...OPEN_STATUSES] as never))
if (p.view === 'closed') scoped.push(eq(incidents.status, 'closed' as never))
const where = scoped.length ? and(...scoped) : undefined
const baseWhere = base.length ? and(...base) : undefined
const sortColumn = { reported_at: incidents.reportedAt, reference_no: incidents.referenceNo, status: incidents.status }[p.sort]
const orderBy = p.dir === 'asc' ? asc(sortColumn) : desc(sortColumn)
const [[countRow], rows, statusCounts, siteRows, truckRows] = await Promise.all([
asAdmin(db => db.select({ count: sql<number>`count(*)` }).from(incidents).where(where)),
asAdmin(db =>
db.select({
id: incidents.id,
referenceNo: incidents.referenceNo,
incidentType: incidents.incidentType,
status: incidents.status,
severity: incidents.severity,
reportedAt: incidents.reportedAt,
siteName: sites.name,
zoneName: zones.name,
reporterName: reporter.name,
truckNo: trucks.truckNo,
})
.from(incidents)
.leftJoin(sites, eq(incidents.siteId, sites.id))
.leftJoin(zones, eq(incidents.zoneId, zones.id))
.leftJoin(reporter, eq(incidents.reportedBy, reporter.id))
.leftJoin(trucks, eq(incidents.truckId, trucks.id))
.where(where)
.orderBy(orderBy)
.limit(PAGE_SIZE)
.offset((p.page - 1) * PAGE_SIZE)
),
asAdmin(db =>
db.select({ status: incidents.status, count: sql<number>`count(*)` })
.from(incidents)
.where(baseWhere)
.groupBy(incidents.status)
),
asAdmin(db => db.select({ id: sites.id, name: sites.name }).from(sites).orderBy(asc(sites.name))),
asAdmin(db =>
db.select({ id: trucks.id, truckNo: trucks.truckNo })
.from(trucks)
.where(eq(trucks.active, true))
.orderBy(asc(trucks.truckNo))
),
])
const byStatus = new Map(statusCounts.map(r => [r.status as string, Number(r.count)]))
const all = [...byStatus.values()].reduce((a, b) => a + b, 0)
const open = OPEN_STATUSES.reduce((sum, s) => sum + (byStatus.get(s) ?? 0), 0)
return {
incidents: rows.map(r => ({
id: r.id,
reference_no: r.referenceNo,
incident_type: r.incidentType,
status: r.status,
severity: r.severity,
reported_at: r.reportedAt.toISOString(),
sites: r.siteName ? { name: r.siteName } : null,
zones: r.zoneName ? { name: r.zoneName } : null,
trucks: r.truckNo ? { truck_no: r.truckNo } : null,
reporter: r.reporterName ? { name: r.reporterName } : null,
})),
total: Number(countRow?.count ?? 0),
counts: { all, open, closed: byStatus.get('closed') ?? 0 },
sites: siteRows.map(s => ({ id: s.id, name: s.name })),
trucks: truckRows.map(t => ({ id: t.id, truck_no: t.truckNo })),
}
}
+15
View File
@@ -0,0 +1,15 @@
export type Incident = {
id: string
reference_no: string | null
incident_type: string
status: string
severity: number | null
reported_at: string
sites: { name: string } | null
zones: { name: string } | null
trucks: { truck_no: string } | null
reporter: { name: string } | null
}
export interface SiteOption { id: string; name: string }
export interface TruckOption { id: string; truck_no: string }
+3 -13
View File
@@ -2,14 +2,9 @@ import { readdirSync, readFileSync, statSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
// Files where a circular element is legitimate (avatar). Add others only with a reason.
export const ROUND_ALLOWED = ['components/layout/sidebar.tsx']
const RULES = [
{
rule: 'no-rounded',
re: /(?<=[\s"'`:{])(?:[\w-]+:)*rounded(?:-(?!full(?![\w-]))[\w]+)*(?=[\s"'`}])/,
},
{ rule: 'no-2px-border', re: /(?<![\w-])border(?:-[tblrxy])?-2(?![\w-])/ },
{ rule: 'no-archivo', re: /Archivo/ },
{ rule: 'no-bg-white', re: /(?<![\w-])bg-white(?![\w-])/ },
{ rule: 'no-heavy-shadow', re: /(?<![\w-])shadow-(?:xl|2xl)(?![\w-])/ },
{
@@ -22,14 +17,9 @@ const RULES = [
export function findViolations(src, file) {
const out = []
const roundAllowed = ROUND_ALLOWED.includes(file)
src.split('\n').forEach((text, i) => {
const line = i + 1
for (const { rule, re } of RULES) {
if (re.test(text)) out.push({ file, line, rule, text: text.trim() })
}
if (!roundAllowed && /(?<=[\s"'`:{])(?:[\w-]+:)*rounded-full(?=[\s"'`}])/.test(text)) {
out.push({ file, line, rule: 'no-rounded-full', text: text.trim() })
if (re.test(text)) out.push({ file, line: i + 1, rule, text: text.trim() })
}
})
return out
+2 -6
View File
@@ -17,7 +17,7 @@ vi.mock('@/lib/supabase/server', () => ({
}))
vi.mock('@/lib/claude/client', () => ({
createDeepSeekClient: vi.fn().mockReturnValue({
createLocalLLMClient: vi.fn().mockReturnValue({
chat: {
completions: {
create: vi.fn().mockResolvedValue({
@@ -38,10 +38,6 @@ vi.mock('@/lib/claude/client', () => ({
}),
}))
vi.mock('@/lib/settings', () => ({
getApiKey: vi.fn().mockResolvedValue('sk-test-key'),
}))
describe('POST /api/incidents/ai/quality-check', () => {
it('returns 422 when description is missing', async () => {
const { POST } = await import('@/app/api/incidents/ai/quality-check/route')
@@ -54,7 +50,7 @@ describe('POST /api/incidents/ai/quality-check', () => {
expect(res.status).toBe(422)
})
it('returns quality assessment from DeepSeek', async () => {
it('returns quality assessment from local LLM', async () => {
const { POST } = await import('@/app/api/incidents/ai/quality-check/route')
const req = new Request('http://localhost/api/incidents/ai/quality-check', {
method: 'POST',
+1 -5
View File
@@ -46,7 +46,7 @@ vi.mock('@/lib/supabase/server', () => ({
}))
vi.mock('@/lib/claude/client', () => ({
createDeepSeekClient: vi.fn().mockReturnValue({
createLocalLLMClient: vi.fn().mockReturnValue({
chat: {
completions: {
create: vi.fn().mockResolvedValue({
@@ -67,10 +67,6 @@ vi.mock('@/lib/claude/client', () => ({
}),
}))
vi.mock('@/lib/settings', () => ({
getApiKey: vi.fn().mockResolvedValue('sk-test-key'),
}))
describe('POST /api/incidents/[id]/ai/rca-draft', () => {
it('returns five_why_steps, root_cause_summary, and capa_suggestions', async () => {
const { POST } = await import('@/app/api/incidents/[id]/ai/rca-draft/route')
+1 -5
View File
@@ -36,7 +36,7 @@ vi.mock('@/lib/supabase/server', () => ({
}))
vi.mock('@/lib/claude/client', () => ({
createDeepSeekClient: vi.fn().mockReturnValue({
createLocalLLMClient: vi.fn().mockReturnValue({
chat: {
completions: {
create: vi.fn().mockResolvedValue({
@@ -57,10 +57,6 @@ vi.mock('@/lib/claude/client', () => ({
}),
}))
vi.mock('@/lib/settings', () => ({
getApiKey: vi.fn().mockResolvedValue('sk-test-key'),
}))
describe('POST /api/incidents/[id]/ai/triage-suggest', () => {
it('returns triage suggestion with severity and DOSH flags', async () => {
const { POST } = await import('@/app/api/incidents/[id]/ai/triage-suggest/route')
+82
View File
@@ -0,0 +1,82 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
const push = vi.fn()
const refresh = vi.fn()
vi.mock('next/navigation', () => ({ useRouter: () => ({ push, refresh }) }))
import { CapaForm } from '@/components/capa/capa-form'
const users = [{ id: 'u1', name: 'Tan Mei Ling', department: 'Facilities' }]
function stubFetch(postResponse: { ok: boolean; body?: unknown } = { ok: true }) {
const fn = vi.fn(async (url: string, init?: RequestInit) => {
void init
if (url === '/api/users') return { ok: true, json: async () => users }
return { ok: postResponse.ok, json: async () => postResponse.body ?? {} }
})
vi.stubGlobal('fetch', fn)
return fn
}
const postCall = (fn: ReturnType<typeof stubFetch>) => fn.mock.calls.find(c => c[0] === '/api/capa')
beforeEach(() => {
push.mockClear()
refresh.mockClear()
})
describe('CapaForm', () => {
it('uses the shared labelled fields', async () => {
stubFetch()
render(<CapaForm incidentId="inc1" />)
expect(screen.getByLabelText('Action Description *').className).toContain('rounded-md')
expect(screen.getByLabelText('Due Date *').className).toContain('shadow-input')
expect(await screen.findByRole('option', { name: /Tan Mei Ling/ })).toBeTruthy()
})
it('rejects an empty submission without calling the API', async () => {
const fn = stubFetch()
const { container } = render(<CapaForm incidentId="inc1" />)
await screen.findByRole('option', { name: /Tan Mei Ling/ })
fireEvent.submit(container.querySelector('form')!)
expect((await screen.findByRole('alert')).textContent).toBe('Description, owner, and due date are required')
expect(postCall(fn)).toBeUndefined()
})
it('creates the action with the owner department and returns to the incident', async () => {
const fn = stubFetch()
const { container } = render(<CapaForm incidentId="inc1" />)
await screen.findByRole('option', { name: /Tan Mei Ling/ })
fireEvent.change(screen.getByLabelText('Action Description *'), { target: { value: 'Re-coat the ramp' } })
fireEvent.change(screen.getByLabelText('Root Cause Reference'), { target: { value: 'Why #2' } })
fireEvent.change(screen.getByLabelText('Assigned To *'), { target: { value: 'u1' } })
fireEvent.change(screen.getByLabelText('Due Date *'), { target: { value: '2026-11-01' } })
fireEvent.change(screen.getByLabelText('Priority'), { target: { value: 'high' } })
fireEvent.submit(container.querySelector('form')!)
await waitFor(() => expect(push).toHaveBeenCalledWith('/hse/incidents/inc1'))
expect(JSON.parse(postCall(fn)![1]!.body as string)).toEqual({
incident_id: 'inc1',
description: 'Re-coat the ramp',
owner_user_id: 'u1',
department: 'Facilities',
due_date: '2026-11-01',
priority: 'high',
root_cause_ref: 'Why #2',
})
})
it('shows the API error in a red banner and stays on the page', async () => {
stubFetch({ ok: false, body: { error: 'Owner inactive' } })
const { container } = render(<CapaForm incidentId="inc1" />)
await screen.findByRole('option', { name: /Tan Mei Ling/ })
fireEvent.change(screen.getByLabelText('Action Description *'), { target: { value: 'x' } })
fireEvent.change(screen.getByLabelText('Assigned To *'), { target: { value: 'u1' } })
fireEvent.change(screen.getByLabelText('Due Date *'), { target: { value: '2026-11-01' } })
fireEvent.submit(container.querySelector('form')!)
const alert = await screen.findByRole('alert')
expect(alert.textContent).toBe('Owner inactive')
expect(alert.className).toContain('bg-st-red-bg')
expect(push).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,29 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { CapaOwnerNotesForm } from '@/components/capa/capa-owner-notes-form'
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }))
})
describe('CapaOwnerNotesForm', () => {
it('shows the saved notes and saves edits with PATCH', async () => {
render(<CapaOwnerNotesForm capaId="c9" initialNotes="Ramp ground back" />)
const box = screen.getByLabelText('Remarks / Notes') as HTMLTextAreaElement
expect(box.value).toBe('Ramp ground back')
fireEvent.change(box, { target: { value: 'Ramp ground back and coated' } })
fireEvent.click(screen.getByRole('button', { name: 'Save Notes' }))
await waitFor(() => expect(screen.getByText('Saved')).toBeTruthy())
expect(fetch).toHaveBeenCalledWith('/api/capa/c9', expect.objectContaining({
method: 'PATCH',
body: JSON.stringify({ owner_notes: 'Ramp ground back and coated' }),
}))
})
it('shows an error when the save fails', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, json: async () => ({}) }))
render(<CapaOwnerNotesForm capaId="c9" initialNotes={null} />)
fireEvent.click(screen.getByRole('button', { name: 'Save Notes' }))
expect((await screen.findByRole('alert')).textContent).toBe('Failed to save. Please try again.')
})
})
@@ -0,0 +1,104 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, within } from '@testing-library/react'
const push = vi.fn()
vi.mock('next/navigation', () => ({ useRouter: () => ({ push }) }))
import { CapaWorkspace } from '@/components/capa/capa-workspace'
import type { CapaRow } from '@/lib/capa/list'
const row = (over: Partial<CapaRow>): CapaRow => ({
id: 'x', incident_id: 'i', description: 'Fit guard rail', department: 'Facilities', due_date: '2026-10-10',
priority: 'med', status: 'open', incident_ref: 'SC1-202607-0001', owner_name: 'Tan Mei Ling', ...over,
})
const capas: CapaRow[] = [
row({ id: '1', description: 'Anti-slip coating', due_date: '2026-09-12', priority: 'high', status: 'overdue', owner_name: 'Tan Mei Ling', department: 'Facilities' }),
row({ id: '2', description: 'Forklift refresher', due_date: '2026-10-20', priority: 'low', status: 'in_progress', owner_name: 'Ravi Kumar', department: 'Operations', incident_ref: 'SC3-202607-0002' }),
row({ id: '3', description: 'Guard rail repair', due_date: '2026-10-01', priority: 'med', status: 'pending_verification', owner_name: 'Tan Mei Ling', department: 'Facilities' }),
row({ id: '4', description: 'Signage', due_date: '2026-08-30', priority: 'low', status: 'closed', owner_name: null, department: 'Operations' }),
]
const today = '2026-09-27'
const desktopRows = () => screen.getAllByRole('row').slice(1)
beforeEach(() => push.mockClear())
describe('CapaWorkspace list', () => {
it('renders a TableCard with the action, incident, owner, tags and a late indicator', () => {
render(<CapaWorkspace capas={capas} today={today} />)
expect(screen.getAllByText('Anti-slip coating').length).toBeGreaterThan(0)
expect(screen.getAllByText('SC1-202607-0001').length).toBeGreaterThan(0)
expect(screen.getAllByText('Ravi Kumar').length).toBeGreaterThan(0)
expect(screen.getAllByText('Overdue').some(el => el.className.includes('bg-st-red-bg'))).toBe(true)
expect(screen.getAllByText('High').some(el => el.className.includes('bg-st-orange-bg'))).toBe(true)
expect(screen.getByText('15 days late')).toBeTruthy()
expect(screen.getByText('Showing 1–4 of 4')).toBeTruthy()
})
it('shows saved views with counts and filters by view', () => {
render(<CapaWorkspace capas={capas} today={today} />)
expect(screen.getByRole('button', { name: /All/ }).className).toContain('bg-rule-2')
fireEvent.click(screen.getByRole('button', { name: /Overdue/ }))
expect(screen.queryAllByText('Forklift refresher')).toHaveLength(0)
expect(screen.getAllByText('Anti-slip coating').length).toBeGreaterThan(0)
expect(screen.getByText('Showing 1–1 of 1')).toBeTruthy()
})
it('searches across action, incident and owner', () => {
render(<CapaWorkspace capas={capas} today={today} />)
fireEvent.change(screen.getByRole('searchbox', { name: 'Search actions' }), { target: { value: 'guard' } })
expect(screen.getAllByText('Guard rail repair').length).toBeGreaterThan(0)
expect(screen.queryAllByText('Signage')).toHaveLength(0)
})
it('filters by owner chip and clears the filters', () => {
render(<CapaWorkspace capas={capas} today={today} />)
fireEvent.change(screen.getByLabelText('Owner'), { target: { value: 'Ravi Kumar' } })
expect(screen.queryAllByText('Anti-slip coating')).toHaveLength(0)
expect(screen.getAllByText('Forklift refresher').length).toBeGreaterThan(0)
fireEvent.click(screen.getByRole('button', { name: 'Clear filters' }))
expect(screen.getAllByText('Anti-slip coating').length).toBeGreaterThan(0)
})
it('sorts by due date ascending by default and flips on the header', () => {
render(<CapaWorkspace capas={capas} today={today} />)
expect(desktopRows()[0].textContent).toContain('Signage')
fireEvent.click(screen.getByRole('button', { name: /Due/ }))
expect(desktopRows()[0].textContent).toContain('Forklift refresher')
})
it('opens a CAPA from its row', () => {
render(<CapaWorkspace capas={capas} today={today} />)
fireEvent.click(desktopRows().find(r => r.textContent?.includes('Anti-slip coating'))!)
expect(push).toHaveBeenCalledWith('/hse/capa/1')
})
it('shows an empty state when nothing matches', () => {
render(<CapaWorkspace capas={capas} today={today} />)
fireEvent.change(screen.getByRole('searchbox', { name: 'Search actions' }), { target: { value: 'zzzz' } })
expect(screen.getByText('No CAPA actions match')).toBeTruthy()
expect(screen.queryByText(/Showing/)).toBeNull()
})
})
describe('CapaWorkspace board', () => {
it('switches to a board of status columns with counts and card links', () => {
render(<CapaWorkspace capas={capas} today={today} />)
fireEvent.click(screen.getByRole('button', { name: 'Board' }))
expect(screen.queryByRole('table')).toBeNull()
const col = screen.getByRole('region', { name: 'in progress column' })
expect(within(col).getByText('1')).toBeTruthy()
expect(within(col).getByRole('link', { name: /Forklift refresher/ }).getAttribute('href')).toBe('/hse/capa/2')
expect(screen.getByRole('region', { name: 'reopened column' })).toBeTruthy()
expect(within(screen.getByRole('region', { name: 'reopened column' })).getByText('Empty')).toBeTruthy()
})
it('keeps the search and chip filters on the board', () => {
render(<CapaWorkspace capas={capas} today={today} />)
fireEvent.click(screen.getByRole('button', { name: 'Board' }))
fireEvent.change(screen.getByLabelText('Owner'), { target: { value: 'Ravi Kumar' } })
expect(screen.queryByRole('link', { name: /Anti-slip coating/ })).toBeNull()
expect(screen.getByRole('link', { name: /Forklift refresher/ })).toBeTruthy()
})
})
@@ -0,0 +1,76 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
const push = vi.fn()
const refresh = vi.fn()
vi.mock('next/navigation', () => ({ useRouter: () => ({ push, refresh }) }))
import { VerifyForm } from '@/components/capa/verify-form'
const ok = () => vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) })
beforeEach(() => {
push.mockClear()
refresh.mockClear()
vi.stubGlobal('fetch', ok())
})
describe('VerifyForm', () => {
it('offers two verdict cards and no submit button until one is chosen', () => {
render(<VerifyForm capaId="c1" />)
expect(screen.getByRole('radio', { name: /Verified, effective/ })).toBeTruthy()
expect(screen.getByRole('radio', { name: /Reopen, ineffective/ })).toBeTruthy()
expect(screen.queryByRole('button', { name: /Confirm verification|Reopen action/ })).toBeNull()
})
it('marks the chosen card and shows the matching submit label', () => {
render(<VerifyForm capaId="c1" />)
fireEvent.click(screen.getByRole('radio', { name: /Verified, effective/ }))
expect(screen.getByRole('radio', { name: /Verified, effective/ }).getAttribute('aria-checked')).toBe('true')
expect(screen.getByRole('radio', { name: /Reopen, ineffective/ }).getAttribute('aria-checked')).toBe('false')
expect(screen.getByRole('button', { name: 'Confirm verification' })).toBeTruthy()
fireEvent.click(screen.getByRole('radio', { name: /Reopen, ineffective/ }))
expect(screen.getByRole('button', { name: 'Reopen action' })).toBeTruthy()
})
it('posts a verified verdict and returns to the CAPA list', async () => {
render(<VerifyForm capaId="c1" />)
fireEvent.click(screen.getByRole('radio', { name: /Verified, effective/ }))
fireEvent.click(screen.getByRole('button', { name: 'Confirm verification' }))
await waitFor(() => expect(push).toHaveBeenCalledWith('/hse/capa'))
expect(fetch).toHaveBeenCalledWith('/api/capa/c1/verify', expect.objectContaining({
method: 'POST',
body: JSON.stringify({ verdict: 'verified', reopen_reason: null }),
}))
})
it('requires a reason to reopen and does not call the API without one', () => {
const { container } = render(<VerifyForm capaId="c1" />)
fireEvent.click(screen.getByRole('radio', { name: /Reopen, ineffective/ }))
fireEvent.submit(container.querySelector('form')!)
expect(screen.getByRole('alert').textContent).toBe('Reopen reason is required')
expect(fetch).not.toHaveBeenCalled()
})
it('posts the reason when reopening', async () => {
const { container } = render(<VerifyForm capaId="c1" />)
fireEvent.click(screen.getByRole('radio', { name: /Reopen, ineffective/ }))
fireEvent.change(screen.getByLabelText(/Why is the action ineffective/), { target: { value: 'Coating peeled' } })
fireEvent.submit(container.querySelector('form')!)
await waitFor(() => expect(push).toHaveBeenCalledWith('/hse/capa'))
expect(fetch).toHaveBeenCalledWith('/api/capa/c1/verify', expect.objectContaining({
body: JSON.stringify({ verdict: 'reopened', reopen_reason: 'Coating peeled' }),
}))
})
it('shows the API error in a red banner and stays on the page', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, json: async () => ({ error: 'Not allowed' }) }))
render(<VerifyForm capaId="c1" />)
fireEvent.click(screen.getByRole('radio', { name: /Verified, effective/ }))
fireEvent.click(screen.getByRole('button', { name: 'Confirm verification' }))
const alert = await screen.findByRole('alert')
expect(alert.textContent).toBe('Not allowed')
expect(alert.className).toContain('bg-st-red-bg')
expect(push).not.toHaveBeenCalled()
})
})
@@ -1,53 +0,0 @@
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import { IncidentList } from '@/components/incidents/incident-list'
const mockIncidents = [
{
id: 'inc-001',
reference_no: 'SCW1-202607-0001',
incident_type: 'near_miss',
status: 'reported',
severity: null,
reported_at: '2026-07-10T09:00:00Z',
sites: { name: 'SCW1' },
zones: { name: 'Dock A' },
reporter: { name: 'John Doe' },
},
{
id: 'inc-002',
reference_no: 'SCW1-202607-0002',
incident_type: 'injury',
status: 'triaged',
severity: 3,
reported_at: '2026-07-10T10:00:00Z',
sites: { name: 'SCW1' },
zones: { name: 'Loading Bay' },
reporter: { name: 'Jane Smith' },
},
]
describe('IncidentList', () => {
it('renders all incident rows', () => {
render(<IncidentList incidents={mockIncidents as any} basePath="/hse" />)
expect(screen.getByText('SCW1-202607-0001')).toBeTruthy()
expect(screen.getByText('SCW1-202607-0002')).toBeTruthy()
})
it('shows incident type labels', () => {
render(<IncidentList incidents={mockIncidents as any} basePath="/hse" />)
expect(screen.getByText('Near Miss')).toBeTruthy()
expect(screen.getByText('Injury / Medical')).toBeTruthy()
})
it('shows status badges', () => {
render(<IncidentList incidents={mockIncidents as any} basePath="/hse" />)
expect(screen.getByText('REPORTED')).toBeTruthy()
expect(screen.getByText('TRIAGED')).toBeTruthy()
})
it('renders empty state when no incidents', () => {
render(<IncidentList incidents={[]} basePath="/hse" />)
expect(screen.getByText(/no incidents/i)).toBeTruthy()
})
})
@@ -0,0 +1,122 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, fireEvent, within, act } from '@testing-library/react'
const push = vi.fn()
const replace = vi.fn()
let search = ''
vi.mock('next/navigation', () => ({
useRouter: () => ({ push, replace }),
usePathname: () => '/hse/incidents',
useSearchParams: () => new URLSearchParams(search),
}))
import { IncidentTable } from '@/components/incidents/incident-table'
import type { Incident } from '@/lib/incidents/types'
const incidents: Incident[] = [
{ id: 'a', reference_no: 'SCW1-202607-0001', incident_type: 'near_miss', status: 'reported', severity: null,
reported_at: '2026-07-10T09:00:00Z', sites: { name: 'SCW1' }, zones: { name: 'Dock A' }, trucks: null, reporter: { name: 'John' } },
{ id: 'b', reference_no: 'SCW1-202607-0002', incident_type: 'injury', status: 'capa_pending', severity: 3,
reported_at: '2026-07-11T10:00:00Z', sites: { name: 'SCW1' }, zones: { name: 'Loading Bay' }, trucks: { truck_no: 'WXY1234' }, reporter: { name: 'Jane' } },
]
const props = {
incidents,
basePath: '/hse',
total: 248,
counts: { all: 248, open: 37, closed: 211 },
params: { page: 1, q: '', status: '', type: '', siteId: '', truckId: '', view: 'all' as const, sort: 'reported_at' as const, dir: 'desc' as const },
sites: [{ id: 's1', name: 'SCW1' }],
trucks: [{ id: 't1', truck_no: 'WXY1234' }],
}
beforeEach(() => {
push.mockClear()
replace.mockClear()
search = ''
})
afterEach(() => vi.useRealTimers())
describe('IncidentTable', () => {
it('renders rows with reference, label pills and type', () => {
render(<IncidentTable {...props} />)
expect(screen.getAllByText('SCW1-202607-0001').length).toBeGreaterThan(0)
expect(screen.getAllByText('Reported').some(el => el.className.includes('bg-st-amber-bg'))).toBe(true)
expect(screen.getAllByText('CAPA pending').some(el => el.className.includes('bg-st-orange-bg'))).toBe(true)
expect(screen.getAllByText('Near Miss').length).toBeGreaterThan(0)
expect(screen.getAllByText('Injury / Medical').length).toBeGreaterThan(0)
})
it('shows saved views with counts and switches view through the URL', () => {
search = '?status=closed&page=2'
render(<IncidentTable {...props} />)
expect(screen.getByText('248')).toBeTruthy()
expect(screen.getByText('37')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: /Open/ }))
expect(replace).toHaveBeenCalledWith('/hse/incidents?status=closed&view=open')
})
it('opens an incident from the row and from the eye action', () => {
render(<IncidentTable {...props} />)
const row = screen.getAllByText('SCW1-202607-0002')[0].closest('tr')!
fireEvent.click(row)
expect(push).toHaveBeenCalledWith('/hse/incidents/b')
expect(within(row).getByRole('link', { name: 'Open incident' }).getAttribute('href')).toBe('/hse/incidents/b')
})
it('sorts server-side by writing sort and dir to the URL', () => {
render(<IncidentTable {...props} />)
fireEvent.click(screen.getByRole('button', { name: /Reference/ }))
expect(replace).toHaveBeenCalledWith('/hse/incidents?sort=reference_no&dir=asc')
expect(screen.getByRole('columnheader', { name: /Reported/ }).getAttribute('aria-sort')).toBe('descending')
})
it('changes a filter chip through the URL and clears it', () => {
render(<IncidentTable {...props} />)
fireEvent.change(screen.getByLabelText('Status'), { target: { value: 'closed' } })
expect(replace).toHaveBeenCalledWith('/hse/incidents?status=closed')
})
it('debounces search into the q param', () => {
vi.useFakeTimers()
render(<IncidentTable {...props} />)
fireEvent.change(screen.getByRole('searchbox', { name: 'Search incidents' }), { target: { value: 'forklift' } })
expect(replace).not.toHaveBeenCalled()
act(() => { vi.advanceTimersByTime(300) })
expect(replace).toHaveBeenCalledWith('/hse/incidents?q=forklift')
})
it('shows the footer count and pages through the URL', () => {
render(<IncidentTable {...props} />)
expect(screen.getByText('Showing 1–2 of 248')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Next page' }))
expect(replace).toHaveBeenCalledWith('/hse/incidents?page=2')
})
it('hides the footer when there are no results', () => {
render(<IncidentTable {...props} incidents={[]} total={0} counts={{ all: 0, open: 0, closed: 0 }} />)
expect(screen.queryByText(/Showing/)).toBeNull()
})
it('shows a sane range on a page past the end', () => {
render(<IncidentTable {...props} incidents={[]} total={7} params={{ ...props.params, page: 2 }} />)
expect(screen.getByText('Showing 0–0 of 7')).toBeTruthy()
})
it('shows the range for a partial last page', () => {
render(<IncidentTable {...props} total={27} params={{ ...props.params, page: 2 }} />)
expect(screen.getByText('Showing 26–27 of 27')).toBeTruthy()
})
it('renders the stacked mobile list', () => {
const { container } = render(<IncidentTable {...props} />)
expect(container.querySelector('ul.md\\:hidden')).not.toBeNull()
})
it('shows the empty state with a report action', () => {
render(<IncidentTable {...props} incidents={[]} total={0} counts={{ all: 0, open: 0, closed: 0 }} />)
expect(screen.getByText('No incidents found')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Report incident' }))
expect(push).toHaveBeenCalledWith('/report')
})
})
@@ -0,0 +1,77 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
const push = vi.fn()
const refresh = vi.fn()
vi.mock('next/navigation', () => ({
usePathname: () => '/hse/capa',
useRouter: () => ({ push, refresh }),
}))
vi.mock('@/components/notifications/bell', () => ({ NotificationBell: () => <button aria-label="Notifications" /> }))
import { AppShell } from '@/components/layout/app-shell'
beforeEach(() => {
push.mockClear()
refresh.mockClear()
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }))
})
describe('AppShell', () => {
it('has a 56px dark top bar, a grey sidebar and the page content', () => {
const { container } = render(<AppShell role="hse" userName="Ada Lovelace"><p>page body</p></AppShell>)
expect(container.querySelector('header')?.className).toContain('h-14')
expect(container.querySelector('header')?.className).toContain('bg-topbar')
expect(container.querySelector('aside')?.className).toContain('bg-rule')
expect(container.querySelector('aside')?.className).toContain('w-60')
expect(screen.getByText('page body')).toBeTruthy()
expect(screen.getByText('Setia HSE')).toBeTruthy()
})
it('marks the active sidebar item with aria-current on a white ringed item', () => {
render(<AppShell role="hse" userName="Ada"><span /></AppShell>)
const active = screen.getAllByRole('link', { name: /CAPA/ }).find(a => a.getAttribute('aria-current') === 'page')!
expect(active.className).toContain('bg-surface')
expect(active.className).toContain('shadow-chip')
})
it('shows a GET search form that targets the incident list for HSE roles', () => {
const { container } = render(<AppShell role="hse" userName="Ada"><span /></AppShell>)
const form = container.querySelector('header form')!
expect(form.getAttribute('action')).toBe('/hse/incidents')
expect(form.getAttribute('method')).toBe('get')
expect((form.querySelector('input') as HTMLInputElement).name).toBe('q')
})
it('focuses the search box on Cmd-K', () => {
render(<AppShell role="hse" userName="Ada"><span /></AppShell>)
fireEvent.keyDown(document, { key: 'k', metaKey: true })
expect(document.activeElement?.getAttribute('name')).toBe('q')
})
it('hides the search box for roles without an incident list', () => {
const { container } = render(<AppShell role="reporter" userName="Ada"><span /></AppShell>)
expect(container.querySelector('header form')).toBeNull()
})
it('shows the user chip, version label, and logs out', async () => {
render(<AppShell role="hse" userName="Ada Lovelace"><span /></AppShell>)
expect(screen.getAllByText('AL').length).toBeGreaterThan(0)
expect(screen.getByText('v1.2.2')).toBeTruthy()
fireEvent.click(screen.getAllByRole('button', { name: /Log ?out/i })[0])
await Promise.resolve()
expect(fetch).toHaveBeenCalledWith('/api/auth/logout', { method: 'POST' })
})
it('renders a mobile tab bar that is hidden from md up', () => {
const { container } = render(<AppShell role="hse" userName="Ada"><span /></AppShell>)
const nav = container.querySelector('nav[aria-label="Mobile"]')!
expect(nav.className).toContain('md:hidden')
expect(nav.className).toContain('border-t')
})
it('has no 2px rules', () => {
const { container } = render(<AppShell role="admin" userName="Ada"><span /></AppShell>)
expect(container.innerHTML).not.toMatch(/border-[a-z]?-?2\b/)
})
})
+24
View File
@@ -0,0 +1,24 @@
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', () => {
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'))
})
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('/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()
})
})
-41
View File
@@ -1,41 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
vi.mock('next/navigation', () => ({
usePathname: () => '/hse/capa',
useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }),
}))
vi.mock('@/components/notifications/bell', () => ({ NotificationBell: () => null }))
import { Sidebar } from '@/components/layout/sidebar'
describe('Sidebar (Modernist shell)', () => {
it('renders the role nav with Lucide icons instead of inline paths', () => {
const { container } = render(<Sidebar role="hse" userName="Ada Lovelace" userEmail="" />)
expect(screen.getAllByText('Dashboard').length).toBeGreaterThan(0)
expect(screen.getAllByText('CAPA').length).toBeGreaterThan(0)
expect(container.querySelectorAll('svg.lucide').length).toBeGreaterThan(4)
})
it('marks the active link in the accent with an aria-current', () => {
render(<Sidebar role="hse" userName="Ada" userEmail="" />)
const active = screen.getAllByRole('link', { name: /CAPA/ }).find(a => a.getAttribute('aria-current') === 'page')
expect(active).toBeTruthy()
expect(active?.className).toContain('text-accent-700')
expect(active?.className).toContain('border-accent')
})
it('is flat: a 2px divider rule, ground fill and no rounded corners except the avatar', () => {
const { container } = render(<Sidebar role="hse" userName="Ada" userEmail="" />)
const aside = container.querySelector('aside')
expect(aside?.className).toContain('border-r-2')
expect(aside?.className).toContain('bg-ground')
const rounded = container.innerHTML.match(/rounded[\w-]*/g) ?? []
expect(rounded.every(r => r === 'rounded-full')).toBe(true)
})
it('keeps the version label', () => {
render(<Sidebar role="hse" userName="Ada" userEmail="" />)
expect(screen.getByText('v1.2.2')).toBeTruthy()
})
})
@@ -0,0 +1,44 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { NotificationBell } from '@/components/notifications/bell'
const payload = {
unread: 2,
notifications: [
{ id: 'n1', title: 'CAPA overdue', link: '/hse/capa/1', sent_at: new Date().toISOString(), read_at: null },
{ id: 'n2', title: 'New incident', link: null, sent_at: '2020-01-01T08:00:00Z', read_at: '2020-01-01T09:00:00Z' },
],
}
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => payload }))
})
describe('NotificationBell', () => {
it('shows the unread count on the bell', async () => {
render(<NotificationBell />)
await waitFor(() => expect(screen.getByRole('button', { name: 'Notifications (2 unread)' })).toBeTruthy())
expect(screen.getByText('2')).toBeTruthy()
})
it('opens a drawer with grouped notifications and an Unread tab', async () => {
render(<NotificationBell />)
fireEvent.click(await screen.findByRole('button', { name: /Notifications/ }))
expect(screen.getByRole('dialog', { name: 'Notifications' })).toBeTruthy()
expect(screen.getByText('CAPA overdue')).toBeTruthy()
expect(screen.getByText('Today')).toBeTruthy()
expect(screen.getByText('Earlier')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: /Unread/ }))
expect(screen.queryByText('New incident')).toBeNull()
expect(screen.getByText('CAPA overdue')).toBeTruthy()
})
it('marks everything read', async () => {
render(<NotificationBell />)
fireEvent.click(await screen.findByRole('button', { name: /Notifications/ }))
fireEvent.click(screen.getByRole('button', { name: 'Mark all read' }))
await waitFor(() =>
expect(fetch).toHaveBeenCalledWith('/api/notifications', expect.objectContaining({ method: 'POST', body: JSON.stringify({ all: true }) })),
)
})
})
+9 -31
View File
@@ -2,49 +2,27 @@ import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { Modal } from '@/components/ui/modal'
describe('Modal (Modernist dialog)', () => {
describe('Modal', () => {
it('renders nothing when closed', () => {
const { container } = render(
<Modal open={false} onClose={() => {}} title="T">
body
</Modal>,
)
const { container } = render(<Modal open={false} onClose={() => {}} title="T">body</Modal>)
expect(container.firstChild).toBeNull()
})
it('renders a dialog with title, body and footer on the surface fill', () => {
render(
<Modal open onClose={() => {}} title="Confirm" footer={<span>actions</span>}>
body text
</Modal>,
)
it('renders a 12px card dialog with the floating shadow and a 1px header rule', () => {
render(<Modal open onClose={() => {}} title="Confirm" footer={<span>actions</span>}>body text</Modal>)
const dialog = screen.getByRole('dialog')
expect(dialog).toBeTruthy()
expect(screen.getByText('Confirm')).toBeTruthy()
expect(screen.getByText('body text')).toBeTruthy()
expect(screen.getByText('actions')).toBeTruthy()
expect(dialog.innerHTML).toContain('bg-surface')
expect(dialog.innerHTML).toContain('shadow-lg')
})
it('has no rounded corners and uses a 2px title rule', () => {
render(
<Modal open onClose={() => {}} title="T">
x
</Modal>,
)
const html = screen.getByRole('dialog').innerHTML
expect(html).not.toMatch(/rounded/)
expect(html).toContain('border-b-2')
expect(dialog.innerHTML).toContain('rounded-xl')
expect(dialog.innerHTML).toContain('shadow-float')
expect(dialog.innerHTML).toContain('border-b border-rule')
expect(dialog.innerHTML).not.toContain('border-b-2')
})
it('closes from the X button and on Escape', () => {
const onClose = vi.fn()
render(
<Modal open onClose={onClose} title="T">
x
</Modal>,
)
render(<Modal open onClose={onClose} title="T">x</Modal>)
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
fireEvent.keyDown(document, { key: 'Escape' })
expect(onClose).toHaveBeenCalledTimes(2)
+150 -100
View File
@@ -1,132 +1,182 @@
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import { Button } from '@/components/ui/button'
import { Tag } from '@/components/ui/tag'
import { StatusTag, PriorityTag, statusTone } from '@/components/ui/status-tag'
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { Button, buttonClass } from '@/components/ui/button'
import { StatusTag, PriorityTag, statusHue } from '@/components/ui/status-tag'
import { Checkbox } from '@/components/ui/checkbox'
import { FilterChip } from '@/components/ui/filter-chip'
import { Segmented } from '@/components/ui/segmented'
import { Avatar } from '@/components/ui/avatar'
import { Drawer } from '@/components/ui/drawer'
import { Field, Input } from '@/components/ui/field'
import { Card } from '@/components/ui/card'
import { TABLE, TH, TR, TD } from '@/components/ui/table-styles'
describe('Button', () => {
it('renders a primary accent button that is type=button and flush left', () => {
render(<Button variant="primary">Save</Button>)
const btn = screen.getByRole('button', { name: 'Save' })
expect(btn.getAttribute('type')).toBe('button')
expect(btn.className).toContain('bg-accent')
expect(btn.className).toContain('justify-start')
expect(btn.className).not.toContain('justify-center')
it('primary is the dark 32px button, type=button by default', () => {
render(<Button>Report incident</Button>)
const b = screen.getByRole('button', { name: 'Report incident' })
expect(b.getAttribute('type')).toBe('button')
expect(b.className).toContain('bg-ink-2')
expect(b.className).toContain('h-8')
expect(b.className).toContain('rounded-md')
expect(b.className).toContain('shadow-primary')
})
it('block buttons span the row and stay flush left', () => {
render(<Button block>Go</Button>)
const btn = screen.getByRole('button', { name: 'Go' })
expect(btn.className).toContain('w-full')
expect(btn.className).toContain('justify-start')
it('secondary is white with a ring', () => {
render(<Button variant="secondary">Export</Button>)
const b = screen.getByRole('button', { name: 'Export' })
expect(b.className).toContain('bg-surface')
expect(b.className).toContain('shadow-secondary')
})
it('icon buttons are square and centered', () => {
render(<Button variant="icon" aria-label="Close" />)
const btn = screen.getByRole('button', { name: 'Close' })
expect(btn.className).toContain('w-9')
expect(btn.className).toContain('justify-center')
expect(btn.className).not.toContain('justify-start')
it('icon is a 28px ghost button', () => {
render(<Button variant="icon" aria-label="More" />)
const b = screen.getByRole('button', { name: 'More' })
expect(b.className).toContain('w-7')
expect(b.className).toContain('h-7')
})
it('never uses a rounded class', () => {
render(<Button variant="secondary">x</Button>)
expect(screen.getByRole('button').className).not.toMatch(/rounded/)
it('buttonClass gives links the same look as buttons', () => {
expect(buttonClass()).toContain('bg-ink-2')
expect(buttonClass('secondary')).toContain('shadow-secondary')
expect(buttonClass('primary', { block: true })).toContain('w-full')
})
it('mobile and block make a full-width 48px button', () => {
render(<Button block mobile>Submit</Button>)
const b = screen.getByRole('button', { name: 'Submit' })
expect(b.className).toContain('w-full')
expect(b.className).toContain('h-12')
expect(b.className).toContain('rounded-xl')
})
})
describe('Tag', () => {
describe('StatusTag and PriorityTag', () => {
it.each([
['accent', 'bg-accent-100'],
['neutral', 'bg-neutral-100'],
['outline', 'border-accent'],
] as const)('%s variant carries %s', (variant, cls) => {
render(<Tag variant={variant}>Label</Tag>)
expect(screen.getByText('Label').className).toContain(cls)
})
['reported', 'amber'], ['triaged', 'blue'], ['investigating', 'violet'], ['capa_pending', 'orange'],
['verification', 'indigo'], ['closed', 'green'], ['open', 'grey'], ['in_progress', 'blue'],
['overdue', 'red'], ['pending_verification', 'indigo'], ['verified', 'green'], ['reopened', 'red'],
['high', 'orange'], ['med', 'amber'], ['low', 'grey'], ['nonsense', 'grey'],
])('%s uses the %s pair', (key, hue) => {
expect(statusHue(key)).toBe(hue)
})
describe('statusTone', () => {
it.each([
['reported', 'accent'],
['triaged', 'outline'],
['investigating', 'outline'],
['capa_pending', 'outline'],
['verification', 'outline'],
['closed', 'neutral'],
['open', 'accent'],
['in_progress', 'outline'],
['overdue', 'accent'],
['pending_verification', 'outline'],
['verified', 'neutral'],
['reopened', 'accent'],
['something_else', 'neutral'],
])('%s maps to %s', (status, tone) => {
expect(statusTone(status)).toBe(tone)
})
})
describe('StatusTag', () => {
it('shows a humanized text label plus an icon, never color alone', () => {
const { container } = render(<StatusTag status="capa_pending" />)
expect(screen.getByText('CAPA Pending')).toBeTruthy()
expect(container.querySelector('svg')).not.toBeNull()
it('renders a dark-on-tint pill with a text label', () => {
render(<StatusTag status="capa_pending" />)
const el = screen.getByText('CAPA pending')
expect(el.className).toContain('bg-st-orange-bg')
expect(el.className).toContain('text-st-orange-fg')
expect(el.className).toContain('rounded-md')
})
it('accepts a label override', () => {
render(<StatusTag status="overdue">Late</StatusTag>)
expect(screen.getByText('Late')).toBeTruthy()
expect(screen.getByText('Late').className).toContain('bg-st-red-bg')
})
it('priority med reads Medium on the amber pair', () => {
render(<PriorityTag priority="med" />)
expect(screen.getByText('Medium').className).toContain('bg-st-amber-bg')
})
it('never uses white text on a saturated fill', () => {
const { container } = render(<StatusTag status="closed" />)
expect(container.innerHTML).not.toContain('text-white')
})
})
describe('PriorityTag', () => {
it.each([
['high', 'bg-accent-100'],
['med', 'border-accent'],
['low', 'bg-neutral-100'],
])('%s priority uses %s', (priority, cls) => {
const { container } = render(<PriorityTag priority={priority} />)
expect(container.firstElementChild?.className).toContain(cls)
describe('Checkbox', () => {
it('toggles and reports the next value', () => {
const onChange = vi.fn()
render(<Checkbox checked={false} onChange={onChange} label="Select row" />)
const cb = screen.getByRole('checkbox', { name: 'Select row' })
expect(cb.getAttribute('aria-checked')).toBe('false')
fireEvent.click(cb)
expect(onChange).toHaveBeenCalledWith(true)
})
it('shows checked and indeterminate states', () => {
const { rerender } = render(<Checkbox checked onChange={() => {}} label="a" />)
expect(screen.getByRole('checkbox').getAttribute('aria-checked')).toBe('true')
expect(screen.getByRole('checkbox').className).toContain('bg-accent')
rerender(<Checkbox checked={false} indeterminate onChange={() => {}} label="a" />)
expect(screen.getByRole('checkbox').getAttribute('aria-checked')).toBe('mixed')
})
})
describe('Field and Input', () => {
it('associates the label with the input', () => {
render(
<Field label="Email" htmlFor="email">
<Input id="email" />
</Field>,
)
describe('FilterChip', () => {
const options = [{ value: 'open', label: 'Open' }, { value: 'closed', label: 'Closed' }]
it('unset shows the label and a select with an empty option', () => {
const { container } = render(<FilterChip label="Status" value="" options={options} onChange={() => {}} />)
expect(container.querySelector('label > span')?.textContent).toBe('Status')
expect((screen.getByLabelText('Status') as HTMLSelectElement).value).toBe('')
})
it('changes through the select', () => {
const onChange = vi.fn()
render(<FilterChip label="Status" value="" options={options} onChange={onChange} />)
fireEvent.change(screen.getByLabelText('Status'), { target: { value: 'closed' } })
expect(onChange).toHaveBeenCalledWith('closed')
})
it('set shows Label: value in the teal tint with a clear button', () => {
const onChange = vi.fn()
render(<FilterChip label="Status" value="closed" options={options} onChange={onChange} />)
expect(screen.getByText('Status: Closed').closest('label')?.className).toContain('bg-accent-tint-2')
fireEvent.click(screen.getByRole('button', { name: 'Clear Status' }))
expect(onChange).toHaveBeenCalledWith('')
})
})
describe('Segmented', () => {
it('marks the active option and reports changes', () => {
const onChange = vi.fn()
render(<Segmented value="list" onChange={onChange} options={[{ value: 'list', label: 'List' }, { value: 'board', label: 'Board' }]} />)
expect(screen.getByRole('button', { name: 'List' }).getAttribute('aria-pressed')).toBe('true')
fireEvent.click(screen.getByRole('button', { name: 'Board' }))
expect(onChange).toHaveBeenCalledWith('board')
})
})
describe('Avatar', () => {
it('shows up to two initials on the teal tile', () => {
render(<Avatar name="Ada Lovelace King" />)
const el = screen.getByText('AL')
expect(el.className).toContain('bg-accent-200')
expect(el.className).toContain('rounded-[6px]')
})
})
describe('Drawer', () => {
it('renders nothing when closed', () => {
const { container } = render(<Drawer open={false} onClose={() => {}} title="Notifications">x</Drawer>)
expect(container.firstChild).toBeNull()
})
it('renders a labelled dialog, closes on the X button and on Escape', () => {
const onClose = vi.fn()
render(<Drawer open onClose={onClose} title="Notifications" actions={<span>Mark all read</span>}>body</Drawer>)
expect(screen.getByRole('dialog', { name: 'Notifications' })).toBeTruthy()
expect(screen.getByText('Mark all read')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
fireEvent.keyDown(document, { key: 'Escape' })
expect(onClose).toHaveBeenCalledTimes(2)
})
})
describe('Field, Input, Card', () => {
it('Input is 36px with the faint ring and is labelled', () => {
render(<Field label="Email" htmlFor="email"><Input id="email" /></Field>)
const input = screen.getByLabelText('Email')
expect(input.className).toContain('bg-surface')
expect(input.className).toContain('border-divider')
})
expect(input.className).toContain('h-9')
expect(input.className).toContain('shadow-input')
expect(input.className).toContain('rounded-md')
})
describe('Card', () => {
it('renders kicker, title, body and meta on the surface fill', () => {
const { container } = render(
<Card kicker="Open" title="Forklift" meta="Due Friday">
Body text
</Card>,
)
expect(screen.getByText('Open')).toBeTruthy()
it('Card is a white 12px card with the card shadow', () => {
const { container } = render(<Card title="Forklift" kicker="Open" meta="Due Friday">Body</Card>)
expect(container.firstElementChild?.className).toContain('rounded-xl')
expect(container.firstElementChild?.className).toContain('shadow-card')
expect(screen.getByText('Forklift')).toBeTruthy()
expect(screen.getByText('Body text')).toBeTruthy()
expect(screen.getByText('Due Friday')).toBeTruthy()
expect(container.firstElementChild?.className).toContain('bg-surface')
})
})
describe('table styles', () => {
it('uses a 2px header rule and 1px row rules', () => {
expect(TH).toContain('border-b-2')
expect(TH).toContain('border-divider')
expect(TD).toContain('border-b')
expect(TR).toContain('hover:bg-ink/4')
expect(TABLE).toContain('w-full')
})
})
+108
View File
@@ -0,0 +1,108 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent, within } from '@testing-library/react'
import { TableCard, type Column } from '@/components/ui/table-card'
type Row = { id: string; ref: string; status: string }
const rows: Row[] = [
{ id: '1', ref: 'IMS-0001', status: 'Open' },
{ id: '2', ref: 'IMS-0002', status: 'Closed' },
{ id: '3', ref: 'IMS-0003', status: 'Open' },
]
const columns: Column<Row>[] = [
{ key: 'ref', header: 'Reference', sortKey: 'ref', cell: r => r.ref },
{ key: 'status', header: 'Status', cell: r => r.status },
]
const base = { columns, rows, rowKey: (r: Row) => r.id }
describe('TableCard', () => {
it('renders a 12px card with a grey header and the rows', () => {
const { container } = render(<TableCard {...base} />)
expect(container.firstElementChild?.className).toContain('rounded-xl')
expect(container.firstElementChild?.className).toContain('shadow-card')
expect(screen.getByText('Reference').closest('th')?.className).toContain('bg-surface-2')
expect(screen.getByText('IMS-0002')).toBeTruthy()
expect(screen.getAllByRole('row')).toHaveLength(4)
})
it('opens a row on click and on Enter, but not from the actions cell', () => {
const onRowOpen = vi.fn()
render(<TableCard {...base} onRowOpen={onRowOpen} rowActions={() => <button>quick</button>} />)
fireEvent.click(screen.getByText('IMS-0001'))
expect(onRowOpen).toHaveBeenCalledWith(rows[0])
fireEvent.keyDown(screen.getByText('IMS-0002').closest('tr')!, { key: 'Enter' })
expect(onRowOpen).toHaveBeenCalledWith(rows[1])
onRowOpen.mockClear()
fireEvent.click(screen.getAllByText('quick')[0])
expect(onRowOpen).not.toHaveBeenCalled()
})
it('sorts a single column: sortable header is a button, aria-sort reflects state', () => {
const onSortChange = vi.fn()
render(<TableCard {...base} sort={{ key: 'ref', dir: 'asc' }} onSortChange={onSortChange} />)
expect(screen.getByText('Reference').closest('th')?.getAttribute('aria-sort')).toBe('ascending')
expect(screen.getByText('Status').closest('th')?.getAttribute('aria-sort')).toBeNull()
expect(screen.queryByRole('button', { name: /Status/ })).toBeNull()
fireEvent.click(screen.getByRole('button', { name: /Reference/ }))
expect(onSortChange).toHaveBeenCalledWith('ref')
})
it('selects rows and all rows, and shows the bulk bar with the count', () => {
const onChange = vi.fn()
const { rerender } = render(
<TableCard {...base} selection={{ selected: new Set(), onChange }} bulkActions={<button>Export</button>} />,
)
expect(screen.queryByText(/selected/)).toBeNull()
fireEvent.click(screen.getByRole('checkbox', { name: 'Select all rows' }))
expect(onChange).toHaveBeenLastCalledWith(new Set(['1', '2', '3']))
fireEvent.click(screen.getAllByRole('checkbox', { name: 'Select row' })[1])
expect(onChange).toHaveBeenLastCalledWith(new Set(['2']))
rerender(<TableCard {...base} selection={{ selected: new Set(['1']), onChange }} bulkActions={<button>Export</button>} />)
expect(screen.getByText('1 selected')).toBeTruthy()
expect(screen.getByRole('button', { name: 'Export' })).toBeTruthy()
expect(screen.getByRole('checkbox', { name: 'Select all rows' }).getAttribute('aria-checked')).toBe('mixed')
expect(screen.getByText('IMS-0001').closest('tr')?.className).toContain('bg-accent-tint')
})
it('renders saved views with counts and reports changes', () => {
const onChange = vi.fn()
render(
<TableCard
{...base}
views={{ items: [{ key: 'all', label: 'All', count: 248 }, { key: 'open', label: 'Open', count: 37 }], active: 'all', onChange }}
/>,
)
expect(screen.getByRole('button', { name: /All/ }).className).toContain('bg-rule-2')
expect(screen.getByText('248')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: /Open/ }))
expect(onChange).toHaveBeenCalledWith('open')
})
it('renders the footer count and pager', () => {
const onPage = vi.fn()
render(<TableCard {...base} footer={{ from: 1, to: 3, total: 248, page: 1, pageCount: 83, onPage }} />)
expect(screen.getByText('Showing 1–3 of 248')).toBeTruthy()
expect((screen.getByRole('button', { name: 'Previous page' }) as HTMLButtonElement).disabled).toBe(true)
fireEvent.click(screen.getByRole('button', { name: 'Next page' }))
expect(onPage).toHaveBeenCalledWith(2)
})
it('shows the empty state instead of the table', () => {
render(<TableCard {...base} rows={[]} empty={{ title: 'No incidents found', action: <button>Report incident</button> }} />)
expect(screen.queryByRole('table')).toBeNull()
expect(screen.getByText('No incidents found')).toBeTruthy()
expect(screen.getByRole('button', { name: 'Report incident' })).toBeTruthy()
})
it('renders a stacked mobile list beside the desktop table', () => {
const onRowOpen = vi.fn()
const { container } = render(<TableCard {...base} onRowOpen={onRowOpen} mobileRow={r => <span>mobile {r.ref}</span>} />)
const list = container.querySelector('ul')!
expect(list.className).toContain('md:hidden')
expect(within(list).getByText('mobile IMS-0003')).toBeTruthy()
expect(container.querySelector('table')!.parentElement!.className).toContain('hidden md:block')
fireEvent.click(within(list).getByText('mobile IMS-0003'))
expect(onRowOpen).toHaveBeenCalledWith(rows[2])
})
})
+66 -43
View File
@@ -4,59 +4,82 @@ import path from 'path'
const css = readFileSync(path.resolve(__dirname, '../../app/globals.css'), 'utf8')
describe('Modernist tokens in globals.css', () => {
describe('IMS Admin tokens in globals.css', () => {
it.each([
['--color-bg', '#f3f2f2'],
['--color-surface', '#eae9e9'],
['--color-text', '#201e1d'],
['--color-accent', '#ec3013'],
['--color-accent-700', '#ae1800'],
['--color-neutral-900', '#2d2b2b'],
['--color-ink', '#1f1f1f'],
['--color-ink-2', '#303030'],
['--color-ink-3', '#4a4a4a'],
['--color-muted', '#616161'],
['--color-faint', '#8a8a8a'],
['--color-rule', '#ebebeb'],
['--color-rule-2', '#e3e3e3'],
['--color-ring', '#d4d4d4'],
['--color-surface', '#ffffff'],
['--color-surface-2', '#f7f7f7'],
['--color-ground', '#f1f1f1'],
['--color-accent', '#0f766e'],
['--color-accent-tint', '#f2f7f6'],
['--color-accent-tint-2', '#e6f4f1'],
['--color-danger', '#b3261e'],
['--color-topbar', '#1a1a1a'],
])('declares %s as %s', (name, value) => {
expect(css).toMatch(new RegExp(`${name}:\\s*${value}`, 'i'))
expect(css).toMatch(new RegExp(`${name}:\\s*${value}\\b`, 'i'))
})
it.each(['xs', 'sm', 'md', 'lg', 'xl', '2xl', '3xl', '4xl'])('zeroes --radius-%s', size => {
expect(css).toMatch(new RegExp(`--radius-${size}:\\s*0px`))
it.each([
['amber', '#fff1c2', '#6b4a00'],
['blue', '#e0efff', '#00527c'],
['violet', '#ede7ff', '#4b2e99'],
['orange', '#ffe6cf', '#7a3a00'],
['indigo', '#e3e8ff', '#2c3e8f'],
['green', '#d7f4e3', '#0c5132'],
['grey', '#ebebeb', '#4a4a4a'],
['red', '#fee3e0', '#8e1f0b'],
])('declares the %s status pair', (hue, bg, fg) => {
expect(css).toMatch(new RegExp(`--color-st-${hue}-bg:\\s*${bg}`, 'i'))
expect(css).toMatch(new RegExp(`--color-st-${hue}-fg:\\s*${fg}`, 'i'))
})
it('zeroes the bare --radius used by the plain rounded class', () => {
expect(css).toMatch(/--radius:\s*0px/)
it('sets the radius scale: md 8, xl 12', () => {
expect(css).toMatch(/--radius-md:\s*8px/)
expect(css).toMatch(/--radius-xl:\s*12px/)
})
it('declares the card and floating shadows', () => {
expect(css).toMatch(/--shadow-card:\s*0 0 0 1px rgba\(0, ?0, ?0, ?\.08\), 0 1px 2px rgba\(0, ?0, ?0, ?\.06\)/)
expect(css).toMatch(/--shadow-float:\s*0 0 0 1px rgba\(0, ?0, ?0, ?\.1\), 0 12px 32px rgba\(0, ?0, ?0, ?\.18\)/)
})
it('declares the component shadows', () => {
for (const name of ['drawer', 'primary', 'secondary', 'input', 'chip', 'chip-set']) {
expect(css).toMatch(new RegExp(`--shadow-${name}:`))
}
})
it('uses Geist through the next/font variables', () => {
expect(css).toMatch(/--font-sans:\s*var\(--font-geist\)/)
expect(css).toMatch(/--font-mono:\s*var\(--font-geist-mono\)/)
})
it('keeps the legacy remaps so unmigrated pages still render', () => {
expect(css).toMatch(/--color-gray-100:\s*var\(--color-neutral-200\)/)
expect(css).toMatch(/--color-blue-600:\s*var\(--color-accent\)/)
expect(css).toMatch(/--color-red-600:\s*var\(--color-danger\)/)
expect(css).toMatch(/--color-divider:/)
})
it('styles keyboard focus with the 2px accent ring', () => {
expect(css).toMatch(/:focus-visible\s*\{[^}]*outline:\s*2px solid var\(--color-accent\)/)
})
it('has no dark mode block and no Modernist leftovers', () => {
expect(css).not.toContain('prefers-color-scheme')
expect(css).not.toMatch(/ec3013/i)
expect(css).not.toMatch(/archivo/i)
})
it('has no stray comment terminator before @theme', () => {
const head = css.slice(0, css.indexOf('@theme'))
expect(head.match(/\*\//g)?.length).toBe(head.match(/\/\*/g)?.length)
})
it('remaps the gray ramp onto the neutral ramp', () => {
expect(css).toMatch(/--color-gray-100:\s*var\(--color-neutral-200\)/)
expect(css).toMatch(/--color-gray-900:\s*var\(--color-text\)/)
})
it('remaps the blue ramp onto the accent ramp', () => {
expect(css).toMatch(/--color-blue-600:\s*var\(--color-accent\)/)
expect(css).toMatch(/--color-blue-700:\s*var\(--color-accent-700\)/)
})
it('remaps the red ramp onto the accent ramp, with body-size steps on accent-700', () => {
expect(css).toMatch(/--color-red-600:\s*var\(--color-accent-700\)/)
expect(css).toMatch(/--color-red-50:\s*var\(--color-accent-100\)/)
})
it('maps shadows onto the Modernist elevation tokens', () => {
expect(css).toMatch(/--shadow-2xl:\s*var\(--shadow-lg\)/)
})
it('uses Archivo through the next/font variable', () => {
expect(css).toMatch(/--font-sans:\s*var\(--font-archivo\)/)
})
it('has no dark mode block', () => {
expect(css).not.toContain('prefers-color-scheme')
})
it('styles keyboard focus with the 2px accent ring', () => {
expect(css).toMatch(/:focus-visible\s*\{[^}]*outline:\s*2px solid var\(--color-accent\)/)
})
})
+109
View File
@@ -0,0 +1,109 @@
import { describe, it, expect } from 'vitest'
import {
EMPTY_FILTERS, PAGE_SIZE, STATUS_ORDER, VIEWS,
daysLate, distinct, filterCapas, nextSort, paginate, sortCapas, viewCounts,
type CapaRow,
} from '@/lib/capa/list'
const row = (over: Partial<CapaRow>): CapaRow => ({
id: 'x', incident_id: 'i', description: 'Fit guard rail', department: 'Facilities', due_date: '2026-10-10',
priority: 'med', status: 'open', incident_ref: 'SC1-202607-0001', owner_name: 'Tan Mei Ling', ...over,
})
const rows: CapaRow[] = [
row({ id: '1', description: 'Anti-slip coating', due_date: '2026-09-12', priority: 'high', status: 'overdue', owner_name: 'Tan Mei Ling', department: 'Facilities' }),
row({ id: '2', description: 'Forklift refresher', due_date: '2026-10-20', priority: 'low', status: 'in_progress', owner_name: 'Ravi Kumar', department: 'Operations', incident_ref: 'SC3-202607-0002' }),
row({ id: '3', description: 'Guard rail repair', due_date: '2026-10-01', priority: 'med', status: 'pending_verification', owner_name: 'Tan Mei Ling', department: 'Facilities' }),
row({ id: '4', description: 'Signage', due_date: '2026-08-30', priority: 'low', status: 'closed', owner_name: null, department: 'Operations' }),
]
describe('constants', () => {
it('orders statuses for the board and defines the saved views', () => {
expect(STATUS_ORDER).toEqual(['open', 'in_progress', 'overdue', 'reopened', 'pending_verification', 'verified', 'closed'])
expect(VIEWS.map(v => v.key)).toEqual(['all', 'active', 'overdue', 'verification', 'done'])
expect(PAGE_SIZE).toBe(25)
})
})
describe('filterCapas', () => {
it('returns everything for the empty filters', () => {
expect(filterCapas(rows, EMPTY_FILTERS)).toHaveLength(4)
})
it('searches description, incident reference and owner, case-insensitively', () => {
expect(filterCapas(rows, { ...EMPTY_FILTERS, q: 'GUARD' }).map(r => r.id)).toEqual(['3'])
expect(filterCapas(rows, { ...EMPTY_FILTERS, q: 'sc3-' }).map(r => r.id)).toEqual(['2'])
expect(filterCapas(rows, { ...EMPTY_FILTERS, q: 'ravi' }).map(r => r.id)).toEqual(['2'])
})
it('filters by owner, department and priority', () => {
expect(filterCapas(rows, { ...EMPTY_FILTERS, owner: 'Tan Mei Ling' }).map(r => r.id)).toEqual(['1', '3'])
expect(filterCapas(rows, { ...EMPTY_FILTERS, department: 'Operations' }).map(r => r.id)).toEqual(['2', '4'])
expect(filterCapas(rows, { ...EMPTY_FILTERS, priority: 'low' }).map(r => r.id)).toEqual(['2', '4'])
})
it('filters by saved view', () => {
expect(filterCapas(rows, { ...EMPTY_FILTERS, view: 'overdue' }).map(r => r.id)).toEqual(['1'])
expect(filterCapas(rows, { ...EMPTY_FILTERS, view: 'active' }).map(r => r.id)).toEqual(['2'])
expect(filterCapas(rows, { ...EMPTY_FILTERS, view: 'verification' }).map(r => r.id)).toEqual(['3'])
expect(filterCapas(rows, { ...EMPTY_FILTERS, view: 'done' }).map(r => r.id)).toEqual(['4'])
})
it('combines filters', () => {
expect(filterCapas(rows, { ...EMPTY_FILTERS, owner: 'Tan Mei Ling', view: 'overdue' }).map(r => r.id)).toEqual(['1'])
})
})
describe('viewCounts', () => {
it('counts each view with the other filters applied', () => {
expect(viewCounts(rows, EMPTY_FILTERS)).toEqual({ all: 4, active: 1, overdue: 1, verification: 1, done: 1 })
expect(viewCounts(rows, { ...EMPTY_FILTERS, owner: 'Tan Mei Ling', view: 'done' })).toEqual({ all: 2, active: 0, overdue: 1, verification: 1, done: 0 })
})
})
describe('sortCapas', () => {
it('sorts by due date both ways without mutating the input', () => {
const copy = [...rows]
expect(sortCapas(rows, { key: 'due_date', dir: 'asc' }).map(r => r.id)).toEqual(['4', '1', '3', '2'])
expect(sortCapas(rows, { key: 'due_date', dir: 'desc' }).map(r => r.id)).toEqual(['2', '3', '1', '4'])
expect(rows).toEqual(copy)
})
it('sorts priority high first and status in board order', () => {
expect(sortCapas(rows, { key: 'priority', dir: 'asc' }).map(r => r.id)).toEqual(['1', '3', '2', '4'])
expect(sortCapas(rows, { key: 'status', dir: 'asc' }).map(r => r.id)).toEqual(['2', '1', '3', '4'])
})
})
describe('nextSort', () => {
it('flips the direction on the same column and starts a new one ascending', () => {
expect(nextSort({ key: 'due_date', dir: 'asc' }, 'due_date')).toEqual({ key: 'due_date', dir: 'desc' })
expect(nextSort({ key: 'due_date', dir: 'desc' }, 'priority')).toEqual({ key: 'priority', dir: 'asc' })
})
})
describe('paginate', () => {
const many = Array.from({ length: 27 }, (_, i) => i + 1)
it('slices a page and reports the range', () => {
expect(paginate(many, 1, 25)).toMatchObject({ from: 1, to: 25, total: 27, page: 1, pageCount: 2 })
expect(paginate(many, 2, 25)).toMatchObject({ from: 26, to: 27, items: [26, 27], page: 2 })
})
it('clamps an out-of-range page and handles empty input', () => {
expect(paginate(many, 9, 25).page).toBe(2)
expect(paginate(many, 0, 25).page).toBe(1)
expect(paginate([], 1, 25)).toMatchObject({ from: 0, to: 0, total: 0, page: 1, pageCount: 1, items: [] })
})
})
describe('distinct and daysLate', () => {
it('returns sorted unique non-empty values', () => {
expect(distinct(['b', 'a', 'b', null, undefined, ''])).toEqual(['a', 'b'])
})
it('counts whole days past the due date, never negative', () => {
expect(daysLate('2026-09-12', '2026-09-27')).toBe(15)
expect(daysLate('2026-10-10', '2026-09-27')).toBe(0)
})
})
+45
View File
@@ -0,0 +1,45 @@
import { describe, it, expect } from 'vitest'
import { parseListParams, nextSort, withParams, PAGE_SIZE, OPEN_STATUSES } from '@/lib/incidents/list-params'
describe('parseListParams', () => {
it('applies defaults', () => {
expect(parseListParams({})).toEqual({
page: 1, q: '', status: '', type: '', siteId: '', truckId: '', view: 'all', sort: 'reported_at', dir: 'desc',
})
})
it('reads every param and rejects bad values', () => {
const p = parseListParams({ page: '3', q: 'fork', status: 'closed', type: 'injury', site_id: 's1', truck_id: 't1', view: 'open', sort: 'status', dir: 'asc' })
expect(p).toMatchObject({ page: 3, q: 'fork', status: 'closed', siteId: 's1', truckId: 't1', view: 'open', sort: 'status', dir: 'asc' })
expect(parseListParams({ page: '-4' }).page).toBe(1)
expect(parseListParams({ page: 'x' }).page).toBe(1)
expect(parseListParams({ view: 'bogus' }).view).toBe('all')
expect(parseListParams({ sort: 'drop table' }).sort).toBe('reported_at')
expect(parseListParams({ dir: 'sideways' }).dir).toBe('desc')
})
it('exposes the page size and the open statuses', () => {
expect(PAGE_SIZE).toBe(25)
expect(OPEN_STATUSES).toEqual(['reported', 'triaged', 'investigating', 'capa_pending', 'verification'])
})
})
describe('nextSort', () => {
it('flips the direction on the same column', () => {
expect(nextSort({ key: 'reference_no', dir: 'asc' }, 'reference_no')).toEqual({ key: 'reference_no', dir: 'desc' })
expect(nextSort({ key: 'reference_no', dir: 'desc' }, 'reference_no')).toEqual({ key: 'reference_no', dir: 'asc' })
})
it('starts a new column ascending, but the date column newest first', () => {
expect(nextSort({ key: 'reported_at', dir: 'desc' }, 'status')).toEqual({ key: 'status', dir: 'asc' })
expect(nextSort({ key: 'status', dir: 'asc' }, 'reported_at')).toEqual({ key: 'reported_at', dir: 'desc' })
})
})
describe('withParams', () => {
it('sets and removes params and resets the page', () => {
expect(withParams('?status=closed&page=3', { q: 'fork' })).toBe('?status=closed&q=fork')
expect(withParams('?status=closed', { status: null })).toBe('')
expect(withParams('?page=2', { page: '4' })).toBe('?page=4')
})
})
+22 -12
View File
@@ -1,18 +1,24 @@
import { describe, it, expect } from 'vitest'
import { findViolations, ROUND_ALLOWED } from '../../scripts/check-design-gates.mjs'
import { findViolations } from '../../scripts/check-design-gates.mjs'
const rules = (src: string, file = 'components/x.tsx'): string[] =>
(findViolations(src, file) as Array<{ rule: string }>).map(v => v.rule)
describe('design gates', () => {
it('flags rounded corner classes', () => {
expect(rules('<div className="rounded-lg p-2" />')).toContain('no-rounded')
expect(rules('<div className="p-2 hover:rounded-md" />')).toContain('no-rounded')
describe('design gates (IMS Admin refresh)', () => {
it('allows the radius scale, including rounded-full', () => {
expect(rules('<div className="rounded-md rounded-xl rounded-[5px] rounded-full" />')).toEqual([])
})
it('flags rounded-full outside the allowlist and accepts it inside', () => {
expect(rules('<div className="rounded-full" />')).toContain('no-rounded-full')
expect(rules('<div className="rounded-full" />', ROUND_ALLOWED[0])).not.toContain('no-rounded-full')
it.each(['border-2', 'border-b-2', 'border-t-2', 'border-l-2', 'border-r-2'])('flags %s', cls => {
expect(rules(`<div className="${cls}" />`)).toContain('no-2px-border')
})
it('accepts 1px rules', () => {
expect(rules('<div className="border border-b border-rule" />')).toEqual([])
})
it('flags the retired Archivo font', () => {
expect(rules("import { Archivo } from 'next/font/google'")).toContain('no-archivo')
})
it('flags off-palette colors but accepts remapped gray, blue and red', () => {
@@ -21,7 +27,11 @@ describe('design gates', () => {
expect(rules('<p className="text-gray-500 text-blue-700 bg-red-50" />')).toEqual([])
})
it('flags hard-coded hex colors', () => {
it('accepts the status token classes', () => {
expect(rules('<span className="bg-st-green-bg text-st-green-fg" />')).toEqual([])
})
it('flags hard-coded hex colors, including the retired Modernist red', () => {
expect(rules('<div style={{ color: "#ec3013" }} />')).toContain('no-hex')
expect(rules('<p>&#39;quoted&#39;</p>')).not.toContain('no-hex')
})
@@ -35,11 +45,11 @@ describe('design gates', () => {
})
it('reports file and 1-based line numbers', () => {
const v = findViolations('a\n<div className="rounded-md" />', 'components/y.tsx')
expect(v[0]).toMatchObject({ file: 'components/y.tsx', line: 2, rule: 'no-rounded' })
const v = findViolations('a\n<div className="border-2" />', 'components/y.tsx')
expect(v[0]).toMatchObject({ file: 'components/y.tsx', line: 2, rule: 'no-2px-border' })
})
it('accepts clean on-system markup', () => {
expect(rules('<div className="bg-surface border border-divider p-4 text-ink shadow-sm" />')).toEqual([])
expect(rules('<div className="bg-surface border border-rule p-4 text-ink shadow-card rounded-xl" />')).toEqual([])
})
})