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>
This commit is contained in:
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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 = total === 0 ? 0 : (params.page - 1) * PAGE_SIZE + 1
|
||||
const to = Math.min(total, 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={{ from, to, total, page: params.page, pageCount, onPage: p => update({ page: String(p) }) }}
|
||||
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>
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
+11
-11
@@ -19,18 +19,18 @@ type Props = ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||
mobile?: boolean
|
||||
}
|
||||
|
||||
export function Button({ variant = 'primary', block = false, mobile = false, className, type = 'button', ...rest }: Props) {
|
||||
return (
|
||||
<button
|
||||
type={type}
|
||||
className={cx(
|
||||
export function buttonClass(
|
||||
variant: Variant = 'primary',
|
||||
opts: { block?: boolean; mobile?: boolean } = {},
|
||||
): string {
|
||||
return cx(
|
||||
BASE,
|
||||
VARIANTS[variant],
|
||||
mobile && variant !== 'icon' && 'h-12 rounded-xl text-sm',
|
||||
block && 'w-full',
|
||||
className,
|
||||
)}
|
||||
{...rest}
|
||||
/>
|
||||
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} />
|
||||
}
|
||||
|
||||
@@ -2423,8 +2423,8 @@ 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')[0].className).toContain('bg-st-amber-bg')
|
||||
expect(screen.getAllByText('CAPA pending')[0].className).toContain('bg-st-orange-bg')
|
||||
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)
|
||||
})
|
||||
@@ -2450,7 +2450,7 @@ describe('IncidentTable', () => {
|
||||
render(<IncidentTable {...props} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Reference/ }))
|
||||
expect(replace).toHaveBeenCalledWith('/hse/incidents?sort=reference_no&dir=asc')
|
||||
expect(screen.getByText('Reported').closest('th')?.getAttribute('aria-sort')).toBe('descending')
|
||||
expect(screen.getByRole('columnheader', { name: /Reported/ }).getAttribute('aria-sort')).toBe('descending')
|
||||
})
|
||||
|
||||
it('changes a filter chip through the URL and clears it', () => {
|
||||
|
||||
@@ -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}` : ''
|
||||
}
|
||||
@@ -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 })),
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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,107 @@
|
||||
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('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')
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
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'
|
||||
@@ -35,6 +35,12 @@ describe('Button', () => {
|
||||
expect(b.className).toContain('h-7')
|
||||
})
|
||||
|
||||
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' })
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user