Merge feat/truck-site: link trucks to a site, filter report truck list
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -29,7 +29,7 @@ export default async function AdminHome() {
|
||||
qrCodeToken: zones.qrCodeToken, active: zones.active,
|
||||
}).from(zones)),
|
||||
asAdmin(db => db.select({
|
||||
id: trucks.id, truckNo: trucks.truckNo, carrier: trucks.carrier, active: trucks.active,
|
||||
id: trucks.id, truckNo: trucks.truckNo, carrier: trucks.carrier, siteId: trucks.siteId, active: trucks.active,
|
||||
}).from(trucks).orderBy(asc(trucks.truckNo))),
|
||||
])
|
||||
|
||||
@@ -46,8 +46,10 @@ export default async function AdminHome() {
|
||||
|
||||
const siteOptions: SiteOption[] = siteRows.map(s => ({ id: s.id, name: s.name }))
|
||||
|
||||
const truckSites = siteRows.map(s => ({ id: s.id, name: s.name, active: s.active }))
|
||||
|
||||
const truckList: Truck[] = truckRows.map(t => ({
|
||||
id: t.id, truck_no: t.truckNo, carrier: t.carrier ?? null, active: t.active,
|
||||
id: t.id, truck_no: t.truckNo, carrier: t.carrier ?? null, site_id: t.siteId ?? null, active: t.active,
|
||||
}))
|
||||
|
||||
return (
|
||||
@@ -66,6 +68,7 @@ export default async function AdminHome() {
|
||||
sites={sitesWithZones}
|
||||
siteOptions={siteOptions}
|
||||
trucks={truckList}
|
||||
truckSites={truckSites}
|
||||
/>
|
||||
</main>
|
||||
)
|
||||
|
||||
@@ -3,27 +3,43 @@ export const dynamic = 'force-dynamic'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { requireAdmin } from '@/lib/auth/require-admin'
|
||||
import { asAdmin } from '@/lib/db/with-user'
|
||||
import { trucks, incidents } from '@/lib/db/schema'
|
||||
import { trucks, incidents, sites } from '@/lib/db/schema'
|
||||
import { parseSiteId } from '@/lib/admin/truck-input'
|
||||
import { writeAuditLog } from '@/lib/db/audit'
|
||||
import { eq, sql } from 'drizzle-orm'
|
||||
import { and, eq, sql } from 'drizzle-orm'
|
||||
|
||||
async function activeSiteExists(id: string): Promise<boolean> {
|
||||
const [row] = await asAdmin(db =>
|
||||
db.select({ id: sites.id }).from(sites).where(and(eq(sites.id, id), eq(sites.active, true))).limit(1)
|
||||
)
|
||||
return !!row
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { session } = await requireAdmin()
|
||||
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
const body: { truck_no?: string; carrier?: string } = await request.json().catch(() => ({}))
|
||||
const body: { truck_no?: string; carrier?: string; site_id?: unknown } = await request.json().catch(() => ({}))
|
||||
const truck_no = (body.truck_no ?? '').trim()
|
||||
if (!truck_no) return NextResponse.json({ error: 'truck_no required' }, { status: 422 })
|
||||
|
||||
const parsedSite = parseSiteId(body.site_id)
|
||||
if (!parsedSite.ok) return NextResponse.json({ error: 'site_id invalid' }, { status: 422 })
|
||||
const siteId = parsedSite.value ?? null
|
||||
if (siteId && !(await activeSiteExists(siteId)))
|
||||
return NextResponse.json({ error: 'Site not found or inactive' }, { status: 422 })
|
||||
|
||||
const carrier = (body.carrier ?? '').trim() || null
|
||||
|
||||
try {
|
||||
let truckId: string | undefined
|
||||
await asAdmin(async db => {
|
||||
await db.transaction(async tx => {
|
||||
await tx.execute(sql`SELECT set_config('app.user_id', ${session.sub}, true)`)
|
||||
const [truck] = await tx.insert(trucks).values({ truckNo: truck_no, carrier: (body.carrier ?? '').trim() || null }).returning({ id: trucks.id })
|
||||
const [truck] = await tx.insert(trucks).values({ truckNo: truck_no, carrier, siteId }).returning({ id: trucks.id })
|
||||
if (!truck) throw new Error('Insert failed')
|
||||
truckId = truck.id
|
||||
await writeAuditLog(tx, 'trucks', truck.id, 'INSERT', { truck_no, carrier: (body.carrier ?? '').trim() || null })
|
||||
await writeAuditLog(tx, 'trucks', truck.id, 'INSERT', { truck_no, carrier, site_id: siteId })
|
||||
})
|
||||
})
|
||||
if (!truckId) return NextResponse.json({ error: 'Insert failed' }, { status: 400 })
|
||||
@@ -41,21 +57,46 @@ export async function PATCH(request: NextRequest) {
|
||||
const { session } = await requireAdmin()
|
||||
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
const body: { id?: string; active?: boolean } = await request.json().catch(() => ({}))
|
||||
const body: {
|
||||
id?: string
|
||||
active?: boolean
|
||||
truck_no?: string
|
||||
carrier?: string | null
|
||||
site_id?: unknown
|
||||
} = await request.json().catch(() => ({}))
|
||||
if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 })
|
||||
|
||||
const set: { active?: boolean; truckNo?: string; carrier?: string | null; siteId?: string | null } = {}
|
||||
if (typeof body.active === 'boolean') set.active = body.active
|
||||
if (body.truck_no !== undefined) {
|
||||
const no = String(body.truck_no).trim()
|
||||
if (!no) return NextResponse.json({ error: 'truck_no required' }, { status: 422 })
|
||||
set.truckNo = no
|
||||
}
|
||||
if (body.carrier !== undefined) set.carrier = (body.carrier ?? '').trim() || null
|
||||
const parsedSite = parseSiteId(body.site_id)
|
||||
if (!parsedSite.ok) return NextResponse.json({ error: 'site_id invalid' }, { status: 422 })
|
||||
if (parsedSite.value !== undefined) set.siteId = parsedSite.value
|
||||
if (Object.keys(set).length === 0)
|
||||
return NextResponse.json({ error: 'nothing to update' }, { status: 422 })
|
||||
|
||||
const [before] = await asAdmin(db =>
|
||||
db.select().from(trucks).where(eq(trucks.id, body.id!)).limit(1)
|
||||
)
|
||||
if (set.siteId && set.siteId !== before?.siteId && !(await activeSiteExists(set.siteId)))
|
||||
return NextResponse.json({ error: 'Site not found or inactive' }, { status: 422 })
|
||||
|
||||
try {
|
||||
await asAdmin(async db => {
|
||||
await db.transaction(async tx => {
|
||||
await tx.execute(sql`SELECT set_config('app.user_id', ${session.sub}, true)`)
|
||||
await tx.update(trucks).set({ active: body.active }).where(eq(trucks.id, body.id!))
|
||||
await writeAuditLog(tx, 'trucks', body.id!, 'admin_update', { active: body.active }, before ?? null)
|
||||
await tx.update(trucks).set(set).where(eq(trucks.id, body.id!))
|
||||
await writeAuditLog(tx, 'trucks', body.id!, 'admin_update', set, before ?? null)
|
||||
})
|
||||
})
|
||||
} catch {
|
||||
} catch (e) {
|
||||
const code = (e as { code?: string }).code
|
||||
if (code === '23505') return NextResponse.json({ error: 'Truck number already exists' }, { status: 409 })
|
||||
return NextResponse.json({ error: 'Update failed' }, { status: 500 })
|
||||
}
|
||||
return NextResponse.json({ ok: true })
|
||||
|
||||
@@ -44,6 +44,7 @@ export default async function ReportPage({ searchParams }: Props) {
|
||||
id: trucks.id,
|
||||
truckNo: trucks.truckNo,
|
||||
carrier: trucks.carrier,
|
||||
siteId: trucks.siteId,
|
||||
})
|
||||
.from(trucks)
|
||||
.where(eq(trucks.active, true))
|
||||
@@ -54,6 +55,7 @@ export default async function ReportPage({ searchParams }: Props) {
|
||||
id: t.id,
|
||||
truck_no: t.truckNo,
|
||||
carrier: t.carrier ?? null,
|
||||
site_id: t.siteId ?? null,
|
||||
}))
|
||||
|
||||
const zoneRows = await asAdmin(db =>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useState } from 'react'
|
||||
import { UserManager, type AdminUser, type SiteOption } from './user-manager'
|
||||
import { SiteZoneManager, type SiteWithZones } from './site-zone-manager'
|
||||
import { TruckManager, type Truck } from './truck-manager'
|
||||
import { TruckManager, type Truck, type TruckSite } from './truck-manager'
|
||||
|
||||
type Tab = 'users' | 'sites' | 'trucks'
|
||||
|
||||
@@ -12,9 +12,10 @@ interface Props {
|
||||
sites: SiteWithZones[]
|
||||
siteOptions: SiteOption[]
|
||||
trucks: Truck[]
|
||||
truckSites: TruckSite[]
|
||||
}
|
||||
|
||||
export function AdminPanel({ users, sites, siteOptions, trucks }: Props) {
|
||||
export function AdminPanel({ users, sites, siteOptions, trucks, truckSites }: Props) {
|
||||
const [tab, setTab] = useState<Tab>('users')
|
||||
|
||||
const tabs: { id: Tab; label: string; count: number }[] = [
|
||||
@@ -45,7 +46,7 @@ export function AdminPanel({ users, sites, siteOptions, trucks }: Props) {
|
||||
</div>
|
||||
{tab === 'users' && <UserManager users={users} sites={siteOptions} />}
|
||||
{tab === 'sites' && <SiteZoneManager sites={sites} />}
|
||||
{tab === 'trucks' && <TruckManager trucks={trucks} />}
|
||||
{tab === 'trucks' && <TruckManager trucks={trucks} sites={truckSites} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -9,16 +9,20 @@ export type Truck = {
|
||||
id: string
|
||||
truck_no: string
|
||||
carrier: string | null
|
||||
site_id: string | null
|
||||
active: boolean
|
||||
}
|
||||
|
||||
export type TruckSite = { id: string; name: string; active: boolean }
|
||||
|
||||
interface Props {
|
||||
trucks: Truck[]
|
||||
sites: TruckSite[]
|
||||
}
|
||||
|
||||
const lbl = 'block text-xs font-medium text-gray-600 mb-1'
|
||||
|
||||
export function TruckManager({ trucks }: Props) {
|
||||
export function TruckManager({ trucks, sites }: Props) {
|
||||
const router = useRouter()
|
||||
const [truckNo, setTruckNo] = useState('')
|
||||
const [carrier, setCarrier] = useState('')
|
||||
@@ -27,6 +31,22 @@ export function TruckManager({ trucks }: Props) {
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [showAdd, setShowAdd] = useState(false)
|
||||
const [confirmDelete, setConfirmDelete] = useState<Truck | null>(null)
|
||||
const [siteId, setSiteId] = useState('')
|
||||
const [editing, setEditing] = useState<Truck | null>(null)
|
||||
const [editNo, setEditNo] = useState('')
|
||||
const [editCarrier, setEditCarrier] = useState('')
|
||||
const [editSiteId, setEditSiteId] = useState('')
|
||||
|
||||
const siteName = (id: string | null) => sites.find(s => s.id === id)?.name ?? null
|
||||
const siteChoices = (currentId: string) => sites.filter(s => s.active || s.id === currentId)
|
||||
|
||||
const openEdit = (tk: Truck) => {
|
||||
setEditing(tk)
|
||||
setEditNo(tk.truck_no)
|
||||
setEditCarrier(tk.carrier ?? '')
|
||||
setEditSiteId(tk.site_id ?? '')
|
||||
setError(null)
|
||||
}
|
||||
|
||||
const handleAdd = async () => {
|
||||
const no = truckNo.trim()
|
||||
@@ -37,12 +57,13 @@ export function TruckManager({ trucks }: Props) {
|
||||
const res = await fetch('/api/admin/trucks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ truck_no: no, carrier: carrier.trim() || null }),
|
||||
body: JSON.stringify({ truck_no: no, carrier: carrier.trim() || null, site_id: siteId || null }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) { setError(data.error ?? 'Failed to add truck'); return }
|
||||
setTruckNo('')
|
||||
setCarrier('')
|
||||
setSiteId('')
|
||||
setShowAdd(false)
|
||||
router.refresh()
|
||||
} catch {
|
||||
@@ -82,6 +103,19 @@ export function TruckManager({ trucks }: Props) {
|
||||
setConfirmDelete(null)
|
||||
}
|
||||
|
||||
const handleSaveEdit = async () => {
|
||||
if (!editing) return
|
||||
const no = editNo.trim()
|
||||
if (!no) return
|
||||
const ok = await send('PATCH', {
|
||||
id: editing.id,
|
||||
truck_no: no,
|
||||
carrier: editCarrier.trim() || null,
|
||||
site_id: editSiteId || null,
|
||||
})
|
||||
if (ok) setEditing(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-surface border border-divider shadow-sm overflow-hidden">
|
||||
<div className="flex items-center justify-between px-5 py-4 border-b border-divider">
|
||||
@@ -106,8 +140,15 @@ export function TruckManager({ trucks }: Props) {
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm font-semibold text-gray-900">{tk.truck_no}</span>
|
||||
{tk.carrier && <span className="text-xs text-gray-400">{tk.carrier}</span>}
|
||||
<span className={`text-xs px-2 py-0.5 ${tk.site_id ? 'bg-neutral-100 text-ink' : 'bg-gray-100 text-gray-500'}`}>
|
||||
{siteName(tk.site_id) ?? 'Unassigned'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<button disabled={busyId === tk.id} onClick={() => openEdit(tk)}
|
||||
className="text-xs text-accent-700 hover:underline cursor-pointer disabled:opacity-50">
|
||||
Edit
|
||||
</button>
|
||||
<a href={`/report?truck_id=${tk.id}`} target="_blank"
|
||||
className="text-xs text-accent-700 hover:underline cursor-pointer">
|
||||
Report link
|
||||
@@ -134,11 +175,11 @@ export function TruckManager({ trucks }: Props) {
|
||||
</div>
|
||||
|
||||
{/* Add Truck Modal */}
|
||||
<Modal open={showAdd} onClose={() => { setShowAdd(false); setTruckNo(''); setCarrier(''); setError(null) }}
|
||||
<Modal open={showAdd} onClose={() => { setShowAdd(false); setTruckNo(''); setCarrier(''); setSiteId(''); setError(null) }}
|
||||
title="Add Truck" width="sm"
|
||||
footer={
|
||||
<>
|
||||
<button onClick={() => { setShowAdd(false); setTruckNo(''); setCarrier(''); setError(null) }}
|
||||
<button onClick={() => { setShowAdd(false); setTruckNo(''); setCarrier(''); setSiteId(''); setError(null) }}
|
||||
className="px-4 py-2 text-sm font-medium border border-divider text-gray-700 hover:bg-gray-50 cursor-pointer transition-colors">
|
||||
Cancel
|
||||
</button>
|
||||
@@ -165,6 +206,49 @@ export function TruckManager({ trucks }: Props) {
|
||||
onKeyDown={e => e.key === 'Enter' && handleAdd()}
|
||||
className={inp} />
|
||||
</div>
|
||||
<div>
|
||||
<label className={lbl} htmlFor="add-truck-site">Site</label>
|
||||
<select id="add-truck-site" value={siteId} onChange={e => setSiteId(e.target.value)} className={inp}>
|
||||
<option value="">No site</option>
|
||||
{siteChoices('').map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
{/* Edit Truck Modal */}
|
||||
<Modal open={!!editing} onClose={() => { setEditing(null); setError(null) }}
|
||||
title="Edit Truck" width="sm"
|
||||
footer={
|
||||
<>
|
||||
<button onClick={() => { setEditing(null); setError(null) }}
|
||||
className="px-4 py-2 text-sm font-medium border border-divider text-gray-700 hover:bg-gray-50 cursor-pointer transition-colors">
|
||||
Cancel
|
||||
</button>
|
||||
<button disabled={busyId === editing?.id || !editNo.trim()} onClick={handleSaveEdit}
|
||||
className="px-4 py-2 bg-accent text-white text-sm font-semibold hover:bg-accent-600 disabled:opacity-50 cursor-pointer transition-colors">
|
||||
{busyId === editing?.id ? 'Saving…' : 'Save'}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{error && <p className="text-xs text-red-600 bg-red-50 px-3 py-2 mb-3">{error}</p>}
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className={lbl} htmlFor="edit-truck-no">Truck Number *</label>
|
||||
<input id="edit-truck-no" type="text" value={editNo} onChange={e => setEditNo(e.target.value)} className={inp} />
|
||||
</div>
|
||||
<div>
|
||||
<label className={lbl} htmlFor="edit-truck-carrier">Carrier (optional)</label>
|
||||
<input id="edit-truck-carrier" type="text" value={editCarrier} onChange={e => setEditCarrier(e.target.value)} className={inp} />
|
||||
</div>
|
||||
<div>
|
||||
<label className={lbl} htmlFor="edit-truck-site">Site</label>
|
||||
<select id="edit-truck-site" value={editSiteId} onChange={e => setEditSiteId(e.target.value)} className={inp}>
|
||||
<option value="">No site</option>
|
||||
{siteChoices(editing?.site_id ?? '').map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useMemo } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { FileUpload } from '@/components/incidents/file-upload'
|
||||
import type { IncidentType, MedicalStatus } from '@/lib/incidents/validate'
|
||||
import { useTranslations } from '@/lib/i18n/context'
|
||||
import { zonesForSite, resolveZoneToken, type SiteOption } from '@/lib/report/zones'
|
||||
import { zonesForSite, resolveZoneToken, siteIdForToken, type SiteOption } from '@/lib/report/zones'
|
||||
import { trucksForSite, siteForTruck } from '@/lib/report/trucks'
|
||||
|
||||
interface Props {
|
||||
zoneToken: string | null
|
||||
@@ -13,7 +14,7 @@ interface Props {
|
||||
siteName: string | null
|
||||
sites: SiteOption[]
|
||||
defaultSiteId: string
|
||||
trucks: Array<{ id: string; truck_no: string; carrier: string | null }>
|
||||
trucks: Array<{ id: string; truck_no: string; carrier: string | null; site_id: string | null }>
|
||||
initialTruckId?: string | null
|
||||
}
|
||||
|
||||
@@ -55,11 +56,16 @@ export function ReportForm({ zoneToken, sites, defaultSiteId, trucks, initialTru
|
||||
} | null>(null)
|
||||
const [overrideQuality, setOverrideQuality] = useState(false)
|
||||
|
||||
const truckSite = !zoneToken ? siteForTruck(trucks, initialTruckId) : null
|
||||
const [siteId, setSiteId] = useState(
|
||||
sites.some(s => s.id === defaultSiteId) ? defaultSiteId : (sites.length === 1 ? sites[0].id : '')
|
||||
truckSite && sites.some(s => s.id === truckSite)
|
||||
? truckSite
|
||||
: sites.some(s => s.id === defaultSiteId) ? defaultSiteId : (sites.length === 1 ? sites[0].id : '')
|
||||
)
|
||||
const [zoneId, setZoneId] = useState('')
|
||||
const effectiveZoneToken = resolveZoneToken({ zoneToken, sites, zoneId })
|
||||
const effectiveSiteId = zoneToken ? siteIdForToken(sites, zoneToken) : siteId
|
||||
const truckOptions = useMemo(() => trucksForSite(trucks, effectiveSiteId), [trucks, effectiveSiteId])
|
||||
|
||||
const [form, setForm] = useState({
|
||||
incident_type: (initialTruckId ? 'transport' : '') as IncidentType | '',
|
||||
@@ -69,6 +75,10 @@ export function ReportForm({ zoneToken, sites, defaultSiteId, trucks, initialTru
|
||||
asset_involved: false,
|
||||
truck_id: initialTruckId ?? '',
|
||||
})
|
||||
useEffect(() => {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setForm(f => (f.truck_id && !truckOptions.some(tk => tk.id === f.truck_id) ? { ...f, truck_id: '' } : f))
|
||||
}, [truckOptions])
|
||||
const [typeDetails, setTypeDetails] = useState<Record<string, string | boolean>>({})
|
||||
|
||||
const setDetail = (key: string, value: string | boolean) =>
|
||||
@@ -326,7 +336,7 @@ export function ReportForm({ zoneToken, sites, defaultSiteId, trucks, initialTru
|
||||
onChange={e => setForm(f => ({ ...f, truck_id: e.target.value }))}
|
||||
>
|
||||
<option value="">{t.truckPlaceholder}</option>
|
||||
{trucks.map(tk => (
|
||||
{truckOptions.map(tk => (
|
||||
<option key={tk.id} value={tk.id}>
|
||||
{tk.truck_no}{tk.carrier ? ` — ${tk.carrier}` : ''}
|
||||
</option>
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Apply by hand on the server DB with the owner's go-ahead. Not run by deploy.
|
||||
BEGIN;
|
||||
ALTER TABLE trucks ADD COLUMN IF NOT EXISTS site_id UUID REFERENCES sites(id);
|
||||
CREATE INDEX IF NOT EXISTS trucks_site_id_idx ON trucks(site_id);
|
||||
COMMIT;
|
||||
@@ -101,6 +101,9 @@ CREATE TABLE trucks (
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
ALTER TABLE trucks ADD COLUMN IF NOT EXISTS site_id UUID REFERENCES sites(id);
|
||||
CREATE INDEX IF NOT EXISTS trucks_site_id_idx ON trucks(site_id);
|
||||
|
||||
-- incidents: final column set includes all columns added in later migrations
|
||||
CREATE TABLE incidents (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
|
||||
@@ -0,0 +1,886 @@
|
||||
# Truck to Site Link Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Let admin link a truck to one site (with edit), and make the Report an Incident truck dropdown show only trucks for the selected site plus unassigned trucks.
|
||||
|
||||
**Architecture:** Nullable `trucks.site_id` column (hand-applied SQL). `/api/admin/trucks` POST and PATCH accept `site_id` and PATCH becomes a partial edit (truck_no, carrier, site_id, active). The Trucks admin tab gets a Site select on add, a site label per row and an Edit modal. The report form filters trucks with a pure helper `trucksForSite`.
|
||||
|
||||
**Tech Stack:** Next.js 16 App Router, Drizzle ORM + `pg`, vitest + Testing Library.
|
||||
|
||||
Spec: `docs/superpowers/specs/2026-10-15-truck-site-link-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- A truck links to **one** site, optional. Existing trucks stay unassigned.
|
||||
- A truck with no site shows for **every** site on the report form.
|
||||
- `POST /api/incidents` is NOT changed and does not reject a truck/site mismatch.
|
||||
- Schema change is hand-applied: write `db/ops/2026-10-15-trucks-site-id.sql`, edit `db/schema.sql` and `lib/db/schema.ts`. Do NOT run any SQL against any database. No RLS change.
|
||||
- Every DB mutation writes `audit_log` in the same transaction (existing pattern with `writeAuditLog`).
|
||||
- Admin routes use `requireAdmin()` and `asAdmin`.
|
||||
- UI uses existing tokens and classes (`bg-surface`, `border-divider`, `text-accent-700`, ...). No hard-coded hex, no `bg-white`, no 2px borders. `npm run check:design` must print `design gates: clean`.
|
||||
- Baseline: 7 pre-existing failing vitest tests. Do not fix or count them. After code changes run `graphify update .`.
|
||||
- Never commit `.env*`. Do not commit the unrelated dirty files (`design-system/ims-admin/MASTER.md` deletion, `*.zip`, `artifacts/`, `scripts/create-agent-*.js`, `.superpowers/sdd/progress.md`). Stage only the files named in each task.
|
||||
- Work on branch `feat/truck-site`.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Schema, SQL and site/truck helpers
|
||||
|
||||
**Files:**
|
||||
- Create: `db/ops/2026-10-15-trucks-site-id.sql`
|
||||
- Modify: `db/schema.sql` (after the `CREATE TABLE trucks (...)` block, line ~96-102)
|
||||
- Modify: `lib/db/schema.ts` (`trucks` table, line ~102)
|
||||
- Create: `lib/report/trucks.ts`
|
||||
- Create: `lib/admin/truck-input.ts`
|
||||
- Modify: `lib/report/zones.ts` (add `siteIdForToken`)
|
||||
- Test: `tests/lib/report/trucks.test.ts`, `tests/lib/admin/truck-input.test.ts`, `tests/lib/report/zones.test.ts` (append)
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `trucksForSite<T extends { site_id: string | null }>(trucks: T[], siteId: string): T[]`; `siteForTruck(trucks: { id: string; site_id: string | null }[], truckId: string | null | undefined): string | null`; `parseSiteId(raw: unknown): { ok: true; value: string | null | undefined } | { ok: false }`; `siteIdForToken(sites: SiteOption[], token: string | null): string` (returns `''` when none); `trucks.siteId` Drizzle column.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests**
|
||||
|
||||
`tests/lib/report/trucks.test.ts`:
|
||||
```ts
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { trucksForSite, siteForTruck } from '@/lib/report/trucks'
|
||||
|
||||
const trucks = [
|
||||
{ id: 't1', site_id: 'A' },
|
||||
{ id: 't2', site_id: 'B' },
|
||||
{ id: 't3', site_id: null },
|
||||
]
|
||||
|
||||
describe('trucksForSite', () => {
|
||||
it('returns matching and unassigned trucks', () => {
|
||||
expect(trucksForSite(trucks, 'A').map(t => t.id)).toEqual(['t1', 't3'])
|
||||
expect(trucksForSite(trucks, 'B').map(t => t.id)).toEqual(['t2', 't3'])
|
||||
})
|
||||
it('returns all trucks when no site is selected', () => {
|
||||
expect(trucksForSite(trucks, '').map(t => t.id)).toEqual(['t1', 't2', 't3'])
|
||||
})
|
||||
it('returns only unassigned trucks for a site with none linked', () => {
|
||||
expect(trucksForSite(trucks, 'C').map(t => t.id)).toEqual(['t3'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('siteForTruck', () => {
|
||||
it('returns the truck site', () => {
|
||||
expect(siteForTruck(trucks, 't2')).toBe('B')
|
||||
})
|
||||
it('returns null for unassigned, unknown or missing truck', () => {
|
||||
expect(siteForTruck(trucks, 't3')).toBeNull()
|
||||
expect(siteForTruck(trucks, 'nope')).toBeNull()
|
||||
expect(siteForTruck(trucks, null)).toBeNull()
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
`tests/lib/admin/truck-input.test.ts`:
|
||||
```ts
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSiteId } from '@/lib/admin/truck-input'
|
||||
|
||||
const UUID = '3f2b8c1e-9d4a-4e6f-8a1b-2c3d4e5f6a7b'
|
||||
|
||||
describe('parseSiteId', () => {
|
||||
it('treats undefined as not provided', () => {
|
||||
expect(parseSiteId(undefined)).toEqual({ ok: true, value: undefined })
|
||||
})
|
||||
it('treats null and empty string as clear', () => {
|
||||
expect(parseSiteId(null)).toEqual({ ok: true, value: null })
|
||||
expect(parseSiteId('')).toEqual({ ok: true, value: null })
|
||||
})
|
||||
it('accepts a uuid', () => {
|
||||
expect(parseSiteId(UUID)).toEqual({ ok: true, value: UUID })
|
||||
})
|
||||
it('rejects anything else', () => {
|
||||
expect(parseSiteId('abc')).toEqual({ ok: false })
|
||||
expect(parseSiteId(12)).toEqual({ ok: false })
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
Append to `tests/lib/report/zones.test.ts` (add `siteIdForToken` to its existing import from `@/lib/report/zones`):
|
||||
```ts
|
||||
describe('siteIdForToken', () => {
|
||||
const sites = [
|
||||
{ id: 'A', name: 'Site A', zones: [{ id: 'z1', name: 'Dock', qr_code_token: 'tok-1' }] },
|
||||
{ id: 'B', name: 'Site B', zones: [{ id: 'z2', name: 'Yard', qr_code_token: 'tok-2' }] },
|
||||
]
|
||||
it('finds the site that owns the token', () => {
|
||||
expect(siteIdForToken(sites, 'tok-2')).toBe('B')
|
||||
})
|
||||
it('returns empty string for null or unknown token', () => {
|
||||
expect(siteIdForToken(sites, null)).toBe('')
|
||||
expect(siteIdForToken(sites, 'nope')).toBe('')
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests to verify they fail**
|
||||
|
||||
Run: `npx vitest run tests/lib/report/trucks.test.ts tests/lib/admin/truck-input.test.ts tests/lib/report/zones.test.ts`
|
||||
Expected: FAIL (modules / export not found).
|
||||
|
||||
- [ ] **Step 3: Write the helpers**
|
||||
|
||||
`lib/report/trucks.ts`:
|
||||
```ts
|
||||
export function trucksForSite<T extends { site_id: string | null }>(trucks: T[], siteId: string): T[] {
|
||||
if (!siteId) return trucks
|
||||
return trucks.filter(t => t.site_id === null || t.site_id === siteId)
|
||||
}
|
||||
|
||||
export function siteForTruck(
|
||||
trucks: { id: string; site_id: string | null }[],
|
||||
truckId: string | null | undefined,
|
||||
): string | null {
|
||||
if (!truckId) return null
|
||||
return trucks.find(t => t.id === truckId)?.site_id ?? null
|
||||
}
|
||||
```
|
||||
|
||||
`lib/admin/truck-input.ts`:
|
||||
```ts
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
||||
|
||||
export type SiteIdInput = { ok: true; value: string | null | undefined } | { ok: false }
|
||||
|
||||
// undefined = field not sent, null/'' = clear the link, uuid string = set it.
|
||||
export function parseSiteId(raw: unknown): SiteIdInput {
|
||||
if (raw === undefined) return { ok: true, value: undefined }
|
||||
if (raw === null || raw === '') return { ok: true, value: null }
|
||||
if (typeof raw === 'string' && UUID_RE.test(raw)) return { ok: true, value: raw }
|
||||
return { ok: false }
|
||||
}
|
||||
```
|
||||
|
||||
Append to `lib/report/zones.ts`:
|
||||
```ts
|
||||
export function siteIdForToken(sites: SiteOption[], token: string | null): string {
|
||||
if (!token) return ''
|
||||
return sites.find(s => s.zones.some(z => z.qr_code_token === token))?.id ?? ''
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Schema and SQL**
|
||||
|
||||
`db/ops/2026-10-15-trucks-site-id.sql`:
|
||||
```sql
|
||||
-- Apply by hand on the server DB with the owner's go-ahead. Not run by deploy.
|
||||
BEGIN;
|
||||
ALTER TABLE trucks ADD COLUMN IF NOT EXISTS site_id UUID REFERENCES sites(id);
|
||||
CREATE INDEX IF NOT EXISTS trucks_site_id_idx ON trucks(site_id);
|
||||
COMMIT;
|
||||
```
|
||||
|
||||
`db/schema.sql`: immediately after the `CREATE TABLE trucks (...);` block add
|
||||
```sql
|
||||
ALTER TABLE trucks ADD COLUMN IF NOT EXISTS site_id UUID REFERENCES sites(id);
|
||||
CREATE INDEX IF NOT EXISTS trucks_site_id_idx ON trucks(site_id);
|
||||
```
|
||||
|
||||
`lib/db/schema.ts`: in `trucks` add after `carrier`:
|
||||
```ts
|
||||
siteId: uuid('site_id').references(() => sites.id),
|
||||
```
|
||||
(`sites` is declared above `trucks`, so no `AnyPgColumn` needed.)
|
||||
|
||||
- [ ] **Step 5: Run tests and typecheck**
|
||||
|
||||
Run: `npx vitest run tests/lib/report/trucks.test.ts tests/lib/admin/truck-input.test.ts tests/lib/report/zones.test.ts && npx tsc --noEmit`
|
||||
Expected: all PASS, tsc clean.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add db/ops/2026-10-15-trucks-site-id.sql db/schema.sql lib/db/schema.ts lib/report/trucks.ts lib/report/zones.ts lib/admin/truck-input.ts tests/lib/report/trucks.test.ts tests/lib/report/zones.test.ts tests/lib/admin/truck-input.test.ts
|
||||
git commit -m "feat(trucks): site_id column and site/truck helpers"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Truck API accepts site_id and edits
|
||||
|
||||
**Files:**
|
||||
- Modify: `app/api/admin/trucks/route.ts` (POST and PATCH; DELETE unchanged)
|
||||
- Test: `tests/api/admin-trucks.test.ts` (create)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `parseSiteId` from `@/lib/admin/truck-input`; `trucks.siteId`.
|
||||
- Produces: `POST /api/admin/trucks {truck_no, carrier?, site_id?}`: 201 `{id}`, 422 invalid/unknown/inactive site, 400 duplicate. `PATCH /api/admin/trucks {id, active?, truck_no?, carrier?, site_id?}`: 200 `{ok:true}`, 422 for missing id, empty change set, empty `truck_no`, or bad/unknown/inactive site, 409 duplicate truck number, 500 other.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests**
|
||||
|
||||
`tests/api/admin-trucks.test.ts`:
|
||||
```ts
|
||||
// @vitest-environment node
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const { selectQueue, setSpy, insertSpy, audit, txError } = vi.hoisted(() => ({
|
||||
selectQueue: [] as unknown[][],
|
||||
setSpy: vi.fn(),
|
||||
insertSpy: vi.fn(),
|
||||
audit: vi.fn(),
|
||||
txError: { code: null as string | null },
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-admin', () => ({
|
||||
requireAdmin: async () => ({ session: { sub: 'admin-1', role: 'admin' } }),
|
||||
}))
|
||||
vi.mock('@/lib/db/audit', () => ({ writeAuditLog: audit }))
|
||||
vi.mock('@/lib/db/with-user', () => {
|
||||
const tx = {
|
||||
execute: async () => undefined,
|
||||
insert: () => ({
|
||||
values: (v: unknown) => {
|
||||
insertSpy(v)
|
||||
return { returning: async () => [{ id: 'truck-new' }] }
|
||||
},
|
||||
}),
|
||||
update: () => ({
|
||||
set: (v: unknown) => {
|
||||
setSpy(v)
|
||||
return {
|
||||
where: async () => {
|
||||
if (txError.code) throw Object.assign(new Error('db'), { code: txError.code })
|
||||
},
|
||||
}
|
||||
},
|
||||
}),
|
||||
}
|
||||
const db = {
|
||||
select: () => ({ from: () => ({ where: () => ({ limit: async () => selectQueue.shift() ?? [] }) }) }),
|
||||
transaction: async (fn: (t: unknown) => unknown) => fn(tx),
|
||||
}
|
||||
return { asAdmin: async (fn: (d: unknown) => unknown) => fn(db) }
|
||||
})
|
||||
|
||||
import { POST, PATCH } from '@/app/api/admin/trucks/route'
|
||||
|
||||
const SITE = '3f2b8c1e-9d4a-4e6f-8a1b-2c3d4e5f6a7b'
|
||||
const req = (method: string, body: unknown) =>
|
||||
new Request('http://localhost/api/admin/trucks', {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
}) as never
|
||||
|
||||
beforeEach(() => {
|
||||
selectQueue.length = 0
|
||||
setSpy.mockClear()
|
||||
insertSpy.mockClear()
|
||||
audit.mockClear()
|
||||
txError.code = null
|
||||
})
|
||||
|
||||
describe('POST /api/admin/trucks', () => {
|
||||
it('creates a truck with no site', async () => {
|
||||
const res = await POST(req('POST', { truck_no: 'WXY 1' }))
|
||||
expect(res.status).toBe(201)
|
||||
expect(insertSpy).toHaveBeenCalledWith({ truckNo: 'WXY 1', carrier: null, siteId: null })
|
||||
})
|
||||
it('creates a truck linked to an active site and audits it', async () => {
|
||||
selectQueue.push([{ id: SITE }])
|
||||
const res = await POST(req('POST', { truck_no: 'WXY 2', site_id: SITE }))
|
||||
expect(res.status).toBe(201)
|
||||
expect(insertSpy).toHaveBeenCalledWith({ truckNo: 'WXY 2', carrier: null, siteId: SITE })
|
||||
expect(audit).toHaveBeenCalledTimes(1)
|
||||
expect(audit.mock.calls[0][4]).toMatchObject({ site_id: SITE })
|
||||
})
|
||||
it('422 for a malformed site_id', async () => {
|
||||
const res = await POST(req('POST', { truck_no: 'WXY 3', site_id: 'abc' }))
|
||||
expect(res.status).toBe(422)
|
||||
expect(insertSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
it('422 for an unknown or inactive site', async () => {
|
||||
selectQueue.push([])
|
||||
const res = await POST(req('POST', { truck_no: 'WXY 4', site_id: SITE }))
|
||||
expect(res.status).toBe(422)
|
||||
expect(insertSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/admin/trucks', () => {
|
||||
it('sets site_id and audits with the previous row', async () => {
|
||||
selectQueue.push([{ id: 't1', siteId: null }], [{ id: SITE }])
|
||||
const res = await PATCH(req('PATCH', { id: 't1', site_id: SITE }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(setSpy).toHaveBeenCalledWith({ siteId: SITE })
|
||||
expect(audit).toHaveBeenCalledTimes(1)
|
||||
expect(audit.mock.calls[0][4]).toEqual({ siteId: SITE })
|
||||
expect(audit.mock.calls[0][5]).toEqual({ id: 't1', siteId: null })
|
||||
})
|
||||
it('clears the site with null', async () => {
|
||||
selectQueue.push([{ id: 't1', siteId: SITE }])
|
||||
const res = await PATCH(req('PATCH', { id: 't1', site_id: null }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(setSpy).toHaveBeenCalledWith({ siteId: null })
|
||||
})
|
||||
it('edits truck_no and carrier together', async () => {
|
||||
selectQueue.push([{ id: 't1' }])
|
||||
const res = await PATCH(req('PATCH', { id: 't1', truck_no: ' ABC 9 ', carrier: ' ' }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(setSpy).toHaveBeenCalledWith({ truckNo: 'ABC 9', carrier: null })
|
||||
})
|
||||
it('still toggles active', async () => {
|
||||
selectQueue.push([{ id: 't1' }])
|
||||
const res = await PATCH(req('PATCH', { id: 't1', active: false }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(setSpy).toHaveBeenCalledWith({ active: false })
|
||||
})
|
||||
it('422 when nothing to change', async () => {
|
||||
const res = await PATCH(req('PATCH', { id: 't1' }))
|
||||
expect(res.status).toBe(422)
|
||||
})
|
||||
it('422 for an empty truck_no', async () => {
|
||||
const res = await PATCH(req('PATCH', { id: 't1', truck_no: ' ' }))
|
||||
expect(res.status).toBe(422)
|
||||
expect(setSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
it('422 for a malformed or unknown site', async () => {
|
||||
expect((await PATCH(req('PATCH', { id: 't1', site_id: 'abc' }))).status).toBe(422)
|
||||
selectQueue.push([{ id: 't1' }], [])
|
||||
expect((await PATCH(req('PATCH', { id: 't1', site_id: SITE }))).status).toBe(422)
|
||||
expect(setSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
it('409 for a duplicate truck number', async () => {
|
||||
selectQueue.push([{ id: 't1' }])
|
||||
txError.code = '23505'
|
||||
const res = await PATCH(req('PATCH', { id: 't1', truck_no: 'DUP 1' }))
|
||||
expect(res.status).toBe(409)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify failure**
|
||||
|
||||
Run: `npx vitest run tests/api/admin-trucks.test.ts`
|
||||
Expected: FAIL (site_id ignored, PATCH only handles `active`).
|
||||
|
||||
- [ ] **Step 3: Implement**
|
||||
|
||||
In `app/api/admin/trucks/route.ts`:
|
||||
|
||||
Change imports to:
|
||||
```ts
|
||||
import { trucks, incidents, sites } from '@/lib/db/schema'
|
||||
import { parseSiteId } from '@/lib/admin/truck-input'
|
||||
import { and, eq, sql } from 'drizzle-orm'
|
||||
```
|
||||
|
||||
Add above `POST`:
|
||||
```ts
|
||||
async function activeSiteExists(id: string): Promise<boolean> {
|
||||
const [row] = await asAdmin(db =>
|
||||
db.select({ id: sites.id }).from(sites).where(and(eq(sites.id, id), eq(sites.active, true))).limit(1)
|
||||
)
|
||||
return !!row
|
||||
}
|
||||
```
|
||||
|
||||
Replace the whole `POST` function with:
|
||||
```ts
|
||||
export async function POST(request: NextRequest) {
|
||||
const { session } = await requireAdmin()
|
||||
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
const body: { truck_no?: string; carrier?: string; site_id?: unknown } = await request.json().catch(() => ({}))
|
||||
const truck_no = (body.truck_no ?? '').trim()
|
||||
if (!truck_no) return NextResponse.json({ error: 'truck_no required' }, { status: 422 })
|
||||
|
||||
const parsedSite = parseSiteId(body.site_id)
|
||||
if (!parsedSite.ok) return NextResponse.json({ error: 'site_id invalid' }, { status: 422 })
|
||||
const siteId = parsedSite.value ?? null
|
||||
if (siteId && !(await activeSiteExists(siteId)))
|
||||
return NextResponse.json({ error: 'Site not found or inactive' }, { status: 422 })
|
||||
|
||||
const carrier = (body.carrier ?? '').trim() || null
|
||||
|
||||
try {
|
||||
let truckId: string | undefined
|
||||
await asAdmin(async db => {
|
||||
await db.transaction(async tx => {
|
||||
await tx.execute(sql`SELECT set_config('app.user_id', ${session.sub}, true)`)
|
||||
const [truck] = await tx.insert(trucks).values({ truckNo: truck_no, carrier, siteId }).returning({ id: trucks.id })
|
||||
if (!truck) throw new Error('Insert failed')
|
||||
truckId = truck.id
|
||||
await writeAuditLog(tx, 'trucks', truck.id, 'INSERT', { truck_no, carrier, site_id: siteId })
|
||||
})
|
||||
})
|
||||
if (!truckId) return NextResponse.json({ error: 'Insert failed' }, { status: 400 })
|
||||
return NextResponse.json({ id: truckId }, { status: 201 })
|
||||
} catch (e) {
|
||||
const code = (e as { code?: string }).code
|
||||
return NextResponse.json(
|
||||
{ error: code === '23505' ? 'Truck number already exists' : 'Insert failed' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Replace the whole `PATCH` function with:
|
||||
```ts
|
||||
export async function PATCH(request: NextRequest) {
|
||||
const { session } = await requireAdmin()
|
||||
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
const body: {
|
||||
id?: string
|
||||
active?: boolean
|
||||
truck_no?: string
|
||||
carrier?: string | null
|
||||
site_id?: unknown
|
||||
} = await request.json().catch(() => ({}))
|
||||
if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 })
|
||||
|
||||
const set: { active?: boolean; truckNo?: string; carrier?: string | null; siteId?: string | null } = {}
|
||||
if (typeof body.active === 'boolean') set.active = body.active
|
||||
if (body.truck_no !== undefined) {
|
||||
const no = String(body.truck_no).trim()
|
||||
if (!no) return NextResponse.json({ error: 'truck_no required' }, { status: 422 })
|
||||
set.truckNo = no
|
||||
}
|
||||
if (body.carrier !== undefined) set.carrier = (body.carrier ?? '').trim() || null
|
||||
const parsedSite = parseSiteId(body.site_id)
|
||||
if (!parsedSite.ok) return NextResponse.json({ error: 'site_id invalid' }, { status: 422 })
|
||||
if (parsedSite.value !== undefined) set.siteId = parsedSite.value
|
||||
if (Object.keys(set).length === 0)
|
||||
return NextResponse.json({ error: 'nothing to update' }, { status: 422 })
|
||||
|
||||
const [before] = await asAdmin(db =>
|
||||
db.select().from(trucks).where(eq(trucks.id, body.id!)).limit(1)
|
||||
)
|
||||
if (set.siteId && !(await activeSiteExists(set.siteId)))
|
||||
return NextResponse.json({ error: 'Site not found or inactive' }, { status: 422 })
|
||||
|
||||
try {
|
||||
await asAdmin(async db => {
|
||||
await db.transaction(async tx => {
|
||||
await tx.execute(sql`SELECT set_config('app.user_id', ${session.sub}, true)`)
|
||||
await tx.update(trucks).set(set).where(eq(trucks.id, body.id!))
|
||||
await writeAuditLog(tx, 'trucks', body.id!, 'admin_update', set, before ?? null)
|
||||
})
|
||||
})
|
||||
} catch (e) {
|
||||
const code = (e as { code?: string }).code
|
||||
if (code === '23505') return NextResponse.json({ error: 'Truck number already exists' }, { status: 409 })
|
||||
return NextResponse.json({ error: 'Update failed' }, { status: 500 })
|
||||
}
|
||||
return NextResponse.json({ ok: true })
|
||||
}
|
||||
```
|
||||
|
||||
Note the test for "422 for a malformed or unknown site" in PATCH: the malformed case returns before any select; the unknown case consumes `[before]` then the site check.
|
||||
|
||||
- [ ] **Step 4: Run tests and typecheck**
|
||||
|
||||
Run: `npx vitest run tests/api/admin-trucks.test.ts && npx tsc --noEmit`
|
||||
Expected: all PASS, tsc clean.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add app/api/admin/trucks/route.ts tests/api/admin-trucks.test.ts
|
||||
git commit -m "feat(trucks): admin API accepts site_id and partial edits"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Admin Trucks tab UI (site select, label, edit modal)
|
||||
|
||||
**Files:**
|
||||
- Modify: `app/(protected)/admin/page.tsx` (truck query + props)
|
||||
- Modify: `components/admin/admin-panel.tsx`
|
||||
- Modify: `components/admin/truck-manager.tsx`
|
||||
- Test: `tests/components/admin/truck-manager.test.tsx` (create)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `PATCH /api/admin/trucks` and `POST /api/admin/trucks` from Task 2.
|
||||
- Produces: `Truck` gains `site_id: string | null`; new exported `TruckSite = { id: string; name: string; active: boolean }`; `TruckManager` props `{ trucks: Truck[]; sites: TruckSite[] }`; `AdminPanel` prop `truckSites: TruckSite[]`.
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
`tests/components/admin/truck-manager.test.tsx`:
|
||||
```tsx
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { TruckManager, type Truck, type TruckSite } from '@/components/admin/truck-manager'
|
||||
|
||||
const { refresh } = vi.hoisted(() => ({ refresh: vi.fn() }))
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh }) }))
|
||||
|
||||
const fetchMock = vi.fn()
|
||||
beforeEach(() => {
|
||||
refresh.mockClear()
|
||||
fetchMock.mockReset()
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ ok: true }) })
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
})
|
||||
|
||||
const sites: TruckSite[] = [
|
||||
{ id: 'site-a', name: 'Site A', active: true },
|
||||
{ id: 'site-b', name: 'Site B', active: true },
|
||||
{ id: 'site-old', name: 'Old Site', active: false },
|
||||
]
|
||||
const trucks: Truck[] = [
|
||||
{ id: 't1', truck_no: 'WXY 1', carrier: null, site_id: 'site-a', active: true },
|
||||
{ id: 't2', truck_no: 'WXY 2', carrier: 'Setia', site_id: null, active: true },
|
||||
]
|
||||
|
||||
describe('TruckManager site link', () => {
|
||||
it('shows the site name or Unassigned on each row', () => {
|
||||
render(<TruckManager trucks={trucks} sites={sites} />)
|
||||
expect(screen.getByText('Site A')).toBeTruthy()
|
||||
expect(screen.getByText('Unassigned')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('edits the site of a truck via PATCH', async () => {
|
||||
render(<TruckManager trucks={trucks} sites={sites} />)
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[1])
|
||||
fireEvent.change(screen.getByLabelText('Site'), { target: { value: 'site-b' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() => expect(fetchMock).toHaveBeenCalled())
|
||||
const [url, init] = fetchMock.mock.calls[0]
|
||||
expect(url).toBe('/api/admin/trucks')
|
||||
expect(init.method).toBe('PATCH')
|
||||
expect(JSON.parse(init.body)).toEqual({ id: 't2', truck_no: 'WXY 2', carrier: 'Setia', site_id: 'site-b' })
|
||||
await waitFor(() => expect(refresh).toHaveBeenCalled())
|
||||
})
|
||||
|
||||
it('clears the site with the No site option', async () => {
|
||||
render(<TruckManager trucks={trucks} sites={sites} />)
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[0])
|
||||
fireEvent.change(screen.getByLabelText('Site'), { target: { value: '' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() => expect(fetchMock).toHaveBeenCalled())
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body).site_id).toBeNull()
|
||||
})
|
||||
|
||||
it('does not offer inactive sites unless already linked', () => {
|
||||
render(<TruckManager trucks={trucks} sites={sites} />)
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[0])
|
||||
const select = screen.getByLabelText('Site') as HTMLSelectElement
|
||||
const labels = Array.from(select.options).map(o => o.textContent)
|
||||
expect(labels).toEqual(['No site', 'Site A', 'Site B'])
|
||||
})
|
||||
|
||||
it('sends site_id when adding a truck', async () => {
|
||||
render(<TruckManager trucks={trucks} sites={sites} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add Truck/ }))
|
||||
fireEvent.change(screen.getByLabelText(/Truck Number/), { target: { value: 'NEW 1' } })
|
||||
fireEvent.change(screen.getByLabelText('Site'), { target: { value: 'site-b' } })
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Add Truck' }).pop()!)
|
||||
await waitFor(() => expect(fetchMock).toHaveBeenCalled())
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ truck_no: 'NEW 1', carrier: null, site_id: 'site-b' })
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify failure**
|
||||
|
||||
Run: `npx vitest run tests/components/admin/truck-manager.test.tsx`
|
||||
Expected: FAIL (no `sites` prop, no Edit button).
|
||||
|
||||
- [ ] **Step 3: Implement `components/admin/truck-manager.tsx`**
|
||||
|
||||
3a. Replace the type/props block at the top:
|
||||
```ts
|
||||
export type Truck = {
|
||||
id: string
|
||||
truck_no: string
|
||||
carrier: string | null
|
||||
site_id: string | null
|
||||
active: boolean
|
||||
}
|
||||
|
||||
export type TruckSite = { id: string; name: string; active: boolean }
|
||||
|
||||
interface Props {
|
||||
trucks: Truck[]
|
||||
sites: TruckSite[]
|
||||
}
|
||||
```
|
||||
and the signature `export function TruckManager({ trucks, sites }: Props) {`.
|
||||
|
||||
3b. After the existing `const [confirmDelete, ...]` state add:
|
||||
```ts
|
||||
const [siteId, setSiteId] = useState('')
|
||||
const [editing, setEditing] = useState<Truck | null>(null)
|
||||
const [editNo, setEditNo] = useState('')
|
||||
const [editCarrier, setEditCarrier] = useState('')
|
||||
const [editSiteId, setEditSiteId] = useState('')
|
||||
|
||||
const siteName = (id: string | null) => sites.find(s => s.id === id)?.name ?? null
|
||||
const siteChoices = (currentId: string) => sites.filter(s => s.active || s.id === currentId)
|
||||
|
||||
const openEdit = (tk: Truck) => {
|
||||
setEditing(tk)
|
||||
setEditNo(tk.truck_no)
|
||||
setEditCarrier(tk.carrier ?? '')
|
||||
setEditSiteId(tk.site_id ?? '')
|
||||
setError(null)
|
||||
}
|
||||
```
|
||||
|
||||
3c. In `handleAdd` change the body to `JSON.stringify({ truck_no: no, carrier: carrier.trim() || null, site_id: siteId || null })` and after `setCarrier('')` add `setSiteId('')`.
|
||||
|
||||
3d. After `handleDelete` add:
|
||||
```ts
|
||||
const handleSaveEdit = async () => {
|
||||
if (!editing) return
|
||||
const no = editNo.trim()
|
||||
if (!no) return
|
||||
const ok = await send('PATCH', {
|
||||
id: editing.id,
|
||||
truck_no: no,
|
||||
carrier: editCarrier.trim() || null,
|
||||
site_id: editSiteId || null,
|
||||
})
|
||||
if (ok) setEditing(null)
|
||||
}
|
||||
```
|
||||
|
||||
3e. In the row, replace the left block
|
||||
```tsx
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm font-semibold text-gray-900">{tk.truck_no}</span>
|
||||
{tk.carrier && <span className="text-xs text-gray-400">{tk.carrier}</span>}
|
||||
</div>
|
||||
```
|
||||
with
|
||||
```tsx
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm font-semibold text-gray-900">{tk.truck_no}</span>
|
||||
{tk.carrier && <span className="text-xs text-gray-400">{tk.carrier}</span>}
|
||||
<span className={`text-xs px-2 py-0.5 ${tk.site_id ? 'bg-neutral-100 text-ink' : 'bg-gray-100 text-gray-500'}`}>
|
||||
{siteName(tk.site_id) ?? 'Unassigned'}
|
||||
</span>
|
||||
</div>
|
||||
```
|
||||
and, in the right-hand actions, add before the "Report link" anchor:
|
||||
```tsx
|
||||
<button disabled={busyId === tk.id} onClick={() => openEdit(tk)}
|
||||
className="text-xs text-accent-700 hover:underline cursor-pointer disabled:opacity-50">
|
||||
Edit
|
||||
</button>
|
||||
```
|
||||
|
||||
3f. In the Add modal, update both reset handlers (`onClose` and Cancel) to also call `setSiteId('')`, and add inside the `space-y-4` div after the carrier field:
|
||||
```tsx
|
||||
<div>
|
||||
<label className={lbl} htmlFor="add-truck-site">Site</label>
|
||||
<select id="add-truck-site" value={siteId} onChange={e => setSiteId(e.target.value)} className={inp}>
|
||||
<option value="">No site</option>
|
||||
{siteChoices('').map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
```
|
||||
|
||||
3g. Add an Edit modal before the Delete Confirm modal:
|
||||
```tsx
|
||||
{/* Edit Truck Modal */}
|
||||
<Modal open={!!editing} onClose={() => { setEditing(null); setError(null) }}
|
||||
title="Edit Truck" width="sm"
|
||||
footer={
|
||||
<>
|
||||
<button onClick={() => { setEditing(null); setError(null) }}
|
||||
className="px-4 py-2 text-sm font-medium border border-divider text-gray-700 hover:bg-gray-50 cursor-pointer transition-colors">
|
||||
Cancel
|
||||
</button>
|
||||
<button disabled={busyId === editing?.id || !editNo.trim()} onClick={handleSaveEdit}
|
||||
className="px-4 py-2 bg-accent text-white text-sm font-semibold hover:bg-accent-600 disabled:opacity-50 cursor-pointer transition-colors">
|
||||
{busyId === editing?.id ? 'Saving…' : 'Save'}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{error && <p className="text-xs text-red-600 bg-red-50 px-3 py-2 mb-3">{error}</p>}
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className={lbl} htmlFor="edit-truck-no">Truck Number *</label>
|
||||
<input id="edit-truck-no" type="text" value={editNo} onChange={e => setEditNo(e.target.value)} className={inp} />
|
||||
</div>
|
||||
<div>
|
||||
<label className={lbl} htmlFor="edit-truck-carrier">Carrier (optional)</label>
|
||||
<input id="edit-truck-carrier" type="text" value={editCarrier} onChange={e => setEditCarrier(e.target.value)} className={inp} />
|
||||
</div>
|
||||
<div>
|
||||
<label className={lbl} htmlFor="edit-truck-site">Site</label>
|
||||
<select id="edit-truck-site" value={editSiteId} onChange={e => setEditSiteId(e.target.value)} className={inp}>
|
||||
<option value="">No site</option>
|
||||
{siteChoices(editing?.site_id ?? '').map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
```
|
||||
|
||||
Note: the delete-confirm modal and the row `Delete`/`Active` buttons stay unchanged. When only one modal is open at a time, `getByLabelText('Site')` is unambiguous.
|
||||
|
||||
3h. `components/admin/admin-panel.tsx`: import `TruckSite`, add prop `truckSites: TruckSite[]` to `Props`, destructure it, and render `<TruckManager trucks={trucks} sites={truckSites} />`.
|
||||
|
||||
3i. `app/(protected)/admin/page.tsx`: add `siteId: trucks.siteId` to the trucks select (the `id: trucks.id, truckNo: ...` object), map `site_id: t.siteId ?? null` in `truckList`, build
|
||||
```ts
|
||||
const truckSites = siteRows.map(s => ({ id: s.id, name: s.name, active: s.active }))
|
||||
```
|
||||
and pass `truckSites={truckSites}` to `<AdminPanel .../>` (find the existing `<AdminPanel` usage in that file and add the prop).
|
||||
|
||||
- [ ] **Step 4: Run tests, typecheck, design gate**
|
||||
|
||||
Run: `npx vitest run tests/components/admin/truck-manager.test.tsx && npx tsc --noEmit && npm run check:design`
|
||||
Expected: tests PASS, tsc clean, `design gates: clean`.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add components/admin/truck-manager.tsx components/admin/admin-panel.tsx "app/(protected)/admin/page.tsx" tests/components/admin/truck-manager.test.tsx
|
||||
git commit -m "feat(trucks): site select, site label and edit modal in admin"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Report form filters trucks by site
|
||||
|
||||
**Files:**
|
||||
- Modify: `app/report/page.tsx` (truck query adds `siteId`, list adds `site_id`)
|
||||
- Modify: `components/incidents/report-form.tsx`
|
||||
- Test: `tests/components/incidents/report-form-trucks.test.tsx` (create)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `trucksForSite`, `siteForTruck` from `@/lib/report/trucks`; `siteIdForToken` from `@/lib/report/zones` (Task 1).
|
||||
- Produces: `ReportForm` prop `trucks: Array<{ id; truck_no; carrier; site_id: string | null }>`.
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
`tests/components/incidents/report-form-trucks.test.tsx`:
|
||||
```tsx
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent, within } from '@testing-library/react'
|
||||
import { ReportForm } from '@/components/incidents/report-form'
|
||||
import { I18nProvider } from '@/lib/i18n/context'
|
||||
import en from '@/messages/en.json'
|
||||
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }) }))
|
||||
|
||||
const sites = [
|
||||
{ id: 'site-a', name: 'Site A', zones: [{ id: 'z1', name: 'Dock', qr_code_token: 'tok-a' }] },
|
||||
{ id: 'site-b', name: 'Site B', zones: [{ id: 'z2', name: 'Yard', qr_code_token: 'tok-b' }] },
|
||||
]
|
||||
const trucks = [
|
||||
{ id: 't1', truck_no: 'AAA 1', carrier: null, site_id: 'site-a' },
|
||||
{ id: 't2', truck_no: 'BBB 2', carrier: null, site_id: 'site-b' },
|
||||
{ id: 't3', truck_no: 'FREE 3', carrier: null, site_id: null },
|
||||
]
|
||||
|
||||
function renderForm(props: Partial<React.ComponentProps<typeof ReportForm>> = {}) {
|
||||
return render(
|
||||
<I18nProvider messages={en}>
|
||||
<ReportForm
|
||||
zoneToken={null}
|
||||
zoneName={null}
|
||||
siteName={null}
|
||||
sites={sites}
|
||||
defaultSiteId=""
|
||||
trucks={trucks}
|
||||
initialTruckId="t1"
|
||||
{...props}
|
||||
/>
|
||||
</I18nProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
const selectWith = (text: string) =>
|
||||
screen.getAllByRole('combobox').find(s => within(s).queryByText(text)) as HTMLSelectElement
|
||||
|
||||
const truckNos = () =>
|
||||
Array.from(selectWith(en.ReportForm.truckPlaceholder).options).map(o => o.textContent)
|
||||
|
||||
describe('ReportForm truck filter', () => {
|
||||
it('defaults the site to the preselected truck site and filters trucks', () => {
|
||||
renderForm()
|
||||
expect(selectWith(en.ReportForm.sitePlaceholder).value).toBe('site-a')
|
||||
expect(truckNos()).toEqual([en.ReportForm.truckPlaceholder, 'AAA 1', 'FREE 3'])
|
||||
})
|
||||
|
||||
it('changing the site refilters and clears a truck that no longer fits', () => {
|
||||
renderForm()
|
||||
expect(selectWith(en.ReportForm.truckPlaceholder).value).toBe('t1')
|
||||
fireEvent.change(selectWith(en.ReportForm.sitePlaceholder), { target: { value: 'site-b' } })
|
||||
expect(truckNos()).toEqual([en.ReportForm.truckPlaceholder, 'BBB 2', 'FREE 3'])
|
||||
expect(selectWith(en.ReportForm.truckPlaceholder).value).toBe('')
|
||||
})
|
||||
|
||||
it('uses the QR zone site when a zone token is present', () => {
|
||||
renderForm({ zoneToken: 'tok-b', zoneName: 'Yard', siteName: 'Site B', initialTruckId: null })
|
||||
// transport is not preselected without a truck, so pick it to reveal the truck select
|
||||
fireEvent.change(screen.getAllByRole('combobox').find(s => within(s).queryByText(en.IncidentType.transport))!, {
|
||||
target: { value: 'transport' },
|
||||
})
|
||||
expect(truckNos()).toEqual([en.ReportForm.truckPlaceholder, 'BBB 2', 'FREE 3'])
|
||||
})
|
||||
})
|
||||
```
|
||||
If the incident-type control is not a `<select>`, adapt only the third test's interaction (look at how the type picker renders in `report-form.tsx`) and keep its assertion; report the adaptation.
|
||||
|
||||
- [ ] **Step 2: Run to verify failure**
|
||||
|
||||
Run: `npx vitest run tests/components/incidents/report-form-trucks.test.tsx`
|
||||
Expected: FAIL (all trucks listed, site not defaulted from truck).
|
||||
|
||||
- [ ] **Step 3: Implement**
|
||||
|
||||
`app/report/page.tsx`: add `siteId: trucks.siteId,` to the truck select, and in `truckList` add `site_id: t.siteId ?? null,`.
|
||||
|
||||
`components/incidents/report-form.tsx`:
|
||||
|
||||
3a. Imports: change the React import to `import { useState, useEffect, useMemo } from 'react'`; change the zones import to
|
||||
```ts
|
||||
import { zonesForSite, resolveZoneToken, siteIdForToken, type SiteOption } from '@/lib/report/zones'
|
||||
import { trucksForSite, siteForTruck } from '@/lib/report/trucks'
|
||||
```
|
||||
|
||||
3b. In `Props` change the trucks type to
|
||||
`trucks: Array<{ id: string; truck_no: string; carrier: string | null; site_id: string | null }>`.
|
||||
|
||||
3c. Replace the `const [siteId, setSiteId] = useState(...)` block with:
|
||||
```ts
|
||||
const truckSite = !zoneToken ? siteForTruck(trucks, initialTruckId) : null
|
||||
const [siteId, setSiteId] = useState(
|
||||
truckSite && sites.some(s => s.id === truckSite)
|
||||
? truckSite
|
||||
: sites.some(s => s.id === defaultSiteId) ? defaultSiteId : (sites.length === 1 ? sites[0].id : '')
|
||||
)
|
||||
```
|
||||
|
||||
3d. After the `effectiveZoneToken` line add:
|
||||
```ts
|
||||
const effectiveSiteId = zoneToken ? siteIdForToken(sites, zoneToken) : siteId
|
||||
const truckOptions = useMemo(() => trucksForSite(trucks, effectiveSiteId), [trucks, effectiveSiteId])
|
||||
```
|
||||
|
||||
3e. After the `form` state declaration (it must come after `useState` for `form`) add:
|
||||
```ts
|
||||
useEffect(() => {
|
||||
setForm(f => (f.truck_id && !truckOptions.some(tk => tk.id === f.truck_id) ? { ...f, truck_id: '' } : f))
|
||||
}, [truckOptions])
|
||||
```
|
||||
(If the repo lint rule `react-hooks/set-state-in-effect` complains, add the same `// eslint-disable-next-line react-hooks/set-state-in-effect` comment used in this file above the `setForm` line.)
|
||||
|
||||
3f. In the Truck `<select>`, replace `{trucks.map(tk => (` with `{truckOptions.map(tk => (`.
|
||||
|
||||
- [ ] **Step 4: Run tests, typecheck, design gate, full suite**
|
||||
|
||||
Run: `npx vitest run tests/components/incidents/report-form-trucks.test.tsx && npx tsc --noEmit && npm run check:design && npx vitest run`
|
||||
Expected: new tests PASS, tsc clean, `design gates: clean`, full suite shows only the 7 pre-existing failures.
|
||||
|
||||
- [ ] **Step 5: graphify and commit**
|
||||
|
||||
```bash
|
||||
graphify update .
|
||||
git add app/report/page.tsx components/incidents/report-form.tsx tests/components/incidents/report-form-trucks.test.tsx
|
||||
git commit -m "feat(report): filter truck list by selected site"
|
||||
```
|
||||
@@ -0,0 +1,43 @@
|
||||
# Link trucks to a site
|
||||
|
||||
Date: 2026-10-15. Status: draft for review.
|
||||
|
||||
## Problem
|
||||
Trucks are a flat list. The Report an Incident form shows every active truck regardless of site. Admin cannot say which site a truck belongs to.
|
||||
|
||||
## Decisions
|
||||
- A truck links to **one** site (optional).
|
||||
- The report form **filters** the Truck dropdown by the selected site.
|
||||
- A truck with no site (all existing trucks) shows for **every** site until an admin assigns one.
|
||||
|
||||
## 1. Schema (manual, needs owner go-ahead)
|
||||
```sql
|
||||
ALTER TABLE trucks ADD COLUMN IF NOT EXISTS site_id UUID REFERENCES sites(id);
|
||||
CREATE INDEX IF NOT EXISTS trucks_site_id_idx ON trucks(site_id);
|
||||
```
|
||||
- Add `db/ops/2026-10-15-trucks-site-id.sql` (wrapped in BEGIN/COMMIT), update `db/schema.sql` and `lib/db/schema.ts` (`siteId: uuid('site_id').references(() => sites.id)`).
|
||||
- No RLS change: `trucks_read` (all) and `trucks_admin_all` already cover the column.
|
||||
|
||||
## 2. Admin, Trucks tab
|
||||
- `app/(protected)/admin/page.tsx` selects `trucks.siteId`; `TruckManager` receives `site_id` per truck and the list of active sites.
|
||||
- Add form: optional Site select. Each row shows the site name, or "Unassigned". Edit modal: Site select with a "No site" option.
|
||||
- `POST /api/admin/trucks` and `PATCH /api/admin/trucks` accept `site_id` (uuid or null). Non-null must reference an existing active site, otherwise 422. Audit log entry stays in the same transaction and records old and new `site_id`.
|
||||
|
||||
## 3. Report form
|
||||
- `app/report/page.tsx` passes `site_id` with each truck.
|
||||
- New pure helper `trucksForSite(trucks, siteId)` in `lib/report/trucks.ts`: returns trucks where `site_id` is null or equals `siteId`; with no `siteId`, returns all.
|
||||
- The site comes from the QR zone when present, otherwise from the Site select. When the site changes and the selected truck no longer fits, the selection clears.
|
||||
- `?truck_id=` still pre-selects the truck. If no zone is given, the truck's `site_id` (when set) becomes the default site.
|
||||
- `POST /api/incidents` is unchanged and does not reject a truck/site mismatch (UI filter only).
|
||||
|
||||
## Testing
|
||||
- `trucksForSite` unit tests (null site, matching, other site, no site selected).
|
||||
- API tests for `site_id` on create and edit: invalid site 422, valid site saved with audit row, null clears.
|
||||
- Component test: truck dropdown filters on site change and clears an invalid selection.
|
||||
- `npm run check:design` must print `design gates: clean`.
|
||||
|
||||
## Out of scope
|
||||
Several sites per truck, bulk assignment, filtering the Incidents list by truck site.
|
||||
|
||||
## Deploy
|
||||
Apply the SQL by hand first (additive, nullable, safe for the old build), then deploy per CLAUDE.md.
|
||||
@@ -0,0 +1,11 @@
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
||||
|
||||
export type SiteIdInput = { ok: true; value: string | null | undefined } | { ok: false }
|
||||
|
||||
// undefined = field not sent, null/'' = clear the link, uuid string = set it.
|
||||
export function parseSiteId(raw: unknown): SiteIdInput {
|
||||
if (raw === undefined) return { ok: true, value: undefined }
|
||||
if (raw === null || raw === '') return { ok: true, value: null }
|
||||
if (typeof raw === 'string' && UUID_RE.test(raw)) return { ok: true, value: raw }
|
||||
return { ok: false }
|
||||
}
|
||||
@@ -103,6 +103,7 @@ export const trucks = pgTable('trucks', {
|
||||
id: uuid('id').primaryKey().defaultRandom(),
|
||||
truckNo: text('truck_no').notNull().unique(),
|
||||
carrier: text('carrier'),
|
||||
siteId: uuid('site_id').references(() => sites.id),
|
||||
active: boolean('active').notNull().default(true),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
})
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
export function trucksForSite<T extends { site_id: string | null }>(trucks: T[], siteId: string): T[] {
|
||||
if (!siteId) return trucks
|
||||
return trucks.filter(t => t.site_id === null || t.site_id === siteId)
|
||||
}
|
||||
|
||||
export function siteForTruck(
|
||||
trucks: { id: string; site_id: string | null }[],
|
||||
truckId: string | null | undefined,
|
||||
): string | null {
|
||||
if (!truckId) return null
|
||||
return trucks.find(t => t.id === truckId)?.site_id ?? null
|
||||
}
|
||||
@@ -31,3 +31,8 @@ export function resolveZoneToken(args: {
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function siteIdForToken(sites: SiteOption[], token: string | null): string {
|
||||
if (!token) return ''
|
||||
return sites.find(s => s.zones.some(z => z.qr_code_token === token))?.id ?? ''
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
// @vitest-environment node
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const { selectQueue, setSpy, insertSpy, audit, txError } = vi.hoisted(() => ({
|
||||
selectQueue: [] as unknown[][],
|
||||
setSpy: vi.fn(),
|
||||
insertSpy: vi.fn(),
|
||||
audit: vi.fn(),
|
||||
txError: { code: null as string | null },
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-admin', () => ({
|
||||
requireAdmin: async () => ({ session: { sub: 'admin-1', role: 'admin' } }),
|
||||
}))
|
||||
vi.mock('@/lib/db/audit', () => ({ writeAuditLog: audit }))
|
||||
vi.mock('@/lib/db/with-user', () => {
|
||||
const tx = {
|
||||
execute: async () => undefined,
|
||||
insert: () => ({
|
||||
values: (v: unknown) => {
|
||||
insertSpy(v)
|
||||
return { returning: async () => [{ id: 'truck-new' }] }
|
||||
},
|
||||
}),
|
||||
update: () => ({
|
||||
set: (v: unknown) => {
|
||||
setSpy(v)
|
||||
return {
|
||||
where: async () => {
|
||||
if (txError.code) throw Object.assign(new Error('db'), { code: txError.code })
|
||||
},
|
||||
}
|
||||
},
|
||||
}),
|
||||
}
|
||||
const db = {
|
||||
select: () => ({ from: () => ({ where: () => ({ limit: async () => selectQueue.shift() ?? [] }) }) }),
|
||||
transaction: async (fn: (t: unknown) => unknown) => fn(tx),
|
||||
}
|
||||
return { asAdmin: async (fn: (d: unknown) => unknown) => fn(db) }
|
||||
})
|
||||
|
||||
import { POST, PATCH } from '@/app/api/admin/trucks/route'
|
||||
|
||||
const SITE = '3f2b8c1e-9d4a-4e6f-8a1b-2c3d4e5f6a7b'
|
||||
const req = (method: string, body: unknown) =>
|
||||
new Request('http://localhost/api/admin/trucks', {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
}) as never
|
||||
|
||||
beforeEach(() => {
|
||||
selectQueue.length = 0
|
||||
setSpy.mockClear()
|
||||
insertSpy.mockClear()
|
||||
audit.mockClear()
|
||||
txError.code = null
|
||||
})
|
||||
|
||||
describe('POST /api/admin/trucks', () => {
|
||||
it('creates a truck with no site', async () => {
|
||||
const res = await POST(req('POST', { truck_no: 'WXY 1' }))
|
||||
expect(res.status).toBe(201)
|
||||
expect(insertSpy).toHaveBeenCalledWith({ truckNo: 'WXY 1', carrier: null, siteId: null })
|
||||
})
|
||||
it('creates a truck linked to an active site and audits it', async () => {
|
||||
selectQueue.push([{ id: SITE }])
|
||||
const res = await POST(req('POST', { truck_no: 'WXY 2', site_id: SITE }))
|
||||
expect(res.status).toBe(201)
|
||||
expect(insertSpy).toHaveBeenCalledWith({ truckNo: 'WXY 2', carrier: null, siteId: SITE })
|
||||
expect(audit).toHaveBeenCalledTimes(1)
|
||||
expect(audit.mock.calls[0][4]).toMatchObject({ site_id: SITE })
|
||||
})
|
||||
it('422 for a malformed site_id', async () => {
|
||||
const res = await POST(req('POST', { truck_no: 'WXY 3', site_id: 'abc' }))
|
||||
expect(res.status).toBe(422)
|
||||
expect(insertSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
it('422 for an unknown or inactive site', async () => {
|
||||
selectQueue.push([])
|
||||
const res = await POST(req('POST', { truck_no: 'WXY 4', site_id: SITE }))
|
||||
expect(res.status).toBe(422)
|
||||
expect(insertSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/admin/trucks', () => {
|
||||
it('sets site_id and audits with the previous row', async () => {
|
||||
selectQueue.push([{ id: 't1', siteId: null }], [{ id: SITE }])
|
||||
const res = await PATCH(req('PATCH', { id: 't1', site_id: SITE }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(setSpy).toHaveBeenCalledWith({ siteId: SITE })
|
||||
expect(audit).toHaveBeenCalledTimes(1)
|
||||
expect(audit.mock.calls[0][4]).toEqual({ siteId: SITE })
|
||||
expect(audit.mock.calls[0][5]).toEqual({ id: 't1', siteId: null })
|
||||
})
|
||||
it('clears the site with null', async () => {
|
||||
selectQueue.push([{ id: 't1', siteId: SITE }])
|
||||
const res = await PATCH(req('PATCH', { id: 't1', site_id: null }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(setSpy).toHaveBeenCalledWith({ siteId: null })
|
||||
})
|
||||
it('edits truck_no and carrier together', async () => {
|
||||
selectQueue.push([{ id: 't1' }])
|
||||
const res = await PATCH(req('PATCH', { id: 't1', truck_no: ' ABC 9 ', carrier: ' ' }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(setSpy).toHaveBeenCalledWith({ truckNo: 'ABC 9', carrier: null })
|
||||
})
|
||||
it('still toggles active', async () => {
|
||||
selectQueue.push([{ id: 't1' }])
|
||||
const res = await PATCH(req('PATCH', { id: 't1', active: false }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(setSpy).toHaveBeenCalledWith({ active: false })
|
||||
})
|
||||
it('422 when nothing to change', async () => {
|
||||
const res = await PATCH(req('PATCH', { id: 't1' }))
|
||||
expect(res.status).toBe(422)
|
||||
})
|
||||
it('422 for an empty truck_no', async () => {
|
||||
const res = await PATCH(req('PATCH', { id: 't1', truck_no: ' ' }))
|
||||
expect(res.status).toBe(422)
|
||||
expect(setSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
it('422 for a malformed or unknown site', async () => {
|
||||
expect((await PATCH(req('PATCH', { id: 't1', site_id: 'abc' }))).status).toBe(422)
|
||||
selectQueue.push([{ id: 't1' }], [])
|
||||
expect((await PATCH(req('PATCH', { id: 't1', site_id: SITE }))).status).toBe(422)
|
||||
expect(setSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
it('skips the active-site check when the site is unchanged', async () => {
|
||||
selectQueue.push([{ id: 't1', siteId: SITE }])
|
||||
const res = await PATCH(req('PATCH', { id: 't1', truck_no: 'NEW 1', site_id: SITE }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(setSpy).toHaveBeenCalledWith({ truckNo: 'NEW 1', siteId: SITE })
|
||||
})
|
||||
it('422 when moving a site-less truck to an inactive site', async () => {
|
||||
selectQueue.push([{ id: 't1', siteId: null }], [])
|
||||
const res = await PATCH(req('PATCH', { id: 't1', site_id: SITE }))
|
||||
expect(res.status).toBe(422)
|
||||
expect(setSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
it('409 for a duplicate truck number', async () => {
|
||||
selectQueue.push([{ id: 't1' }])
|
||||
txError.code = '23505'
|
||||
const res = await PATCH(req('PATCH', { id: 't1', truck_no: 'DUP 1' }))
|
||||
expect(res.status).toBe(409)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { TruckManager, type Truck, type TruckSite } from '@/components/admin/truck-manager'
|
||||
|
||||
const { refresh } = vi.hoisted(() => ({ refresh: vi.fn() }))
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh }) }))
|
||||
|
||||
const fetchMock = vi.fn()
|
||||
beforeEach(() => {
|
||||
refresh.mockClear()
|
||||
fetchMock.mockReset()
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ ok: true }) })
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
})
|
||||
|
||||
const sites: TruckSite[] = [
|
||||
{ id: 'site-a', name: 'Site A', active: true },
|
||||
{ id: 'site-b', name: 'Site B', active: true },
|
||||
{ id: 'site-old', name: 'Old Site', active: false },
|
||||
]
|
||||
const trucks: Truck[] = [
|
||||
{ id: 't1', truck_no: 'WXY 1', carrier: null, site_id: 'site-a', active: true },
|
||||
{ id: 't2', truck_no: 'WXY 2', carrier: 'Setia', site_id: null, active: true },
|
||||
]
|
||||
|
||||
describe('TruckManager site link', () => {
|
||||
it('shows the site name or Unassigned on each row', () => {
|
||||
render(<TruckManager trucks={trucks} sites={sites} />)
|
||||
expect(screen.getByText('Site A')).toBeTruthy()
|
||||
expect(screen.getByText('Unassigned')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('edits the site of a truck via PATCH', async () => {
|
||||
render(<TruckManager trucks={trucks} sites={sites} />)
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[1])
|
||||
fireEvent.change(screen.getByLabelText('Site'), { target: { value: 'site-b' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() => expect(fetchMock).toHaveBeenCalled())
|
||||
const [url, init] = fetchMock.mock.calls[0]
|
||||
expect(url).toBe('/api/admin/trucks')
|
||||
expect(init.method).toBe('PATCH')
|
||||
expect(JSON.parse(init.body)).toEqual({ id: 't2', truck_no: 'WXY 2', carrier: 'Setia', site_id: 'site-b' })
|
||||
await waitFor(() => expect(refresh).toHaveBeenCalled())
|
||||
})
|
||||
|
||||
it('clears the site with the No site option', async () => {
|
||||
render(<TruckManager trucks={trucks} sites={sites} />)
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[0])
|
||||
fireEvent.change(screen.getByLabelText('Site'), { target: { value: '' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() => expect(fetchMock).toHaveBeenCalled())
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body).site_id).toBeNull()
|
||||
})
|
||||
|
||||
it('does not offer inactive sites unless already linked', () => {
|
||||
render(<TruckManager trucks={trucks} sites={sites} />)
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[0])
|
||||
const select = screen.getByLabelText('Site') as HTMLSelectElement
|
||||
const labels = Array.from(select.options).map(o => o.textContent)
|
||||
expect(labels).toEqual(['No site', 'Site A', 'Site B'])
|
||||
})
|
||||
|
||||
it('keeps the inactive site selectable for a truck already linked to it', () => {
|
||||
const oldTrucks: Truck[] = [
|
||||
{ id: 't9', truck_no: 'OLD 9', carrier: null, site_id: 'site-old', active: true },
|
||||
]
|
||||
render(<TruckManager trucks={oldTrucks} sites={sites} />)
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[0])
|
||||
const select = screen.getByLabelText('Site') as HTMLSelectElement
|
||||
const labels = Array.from(select.options).map(o => o.textContent)
|
||||
expect(labels).toEqual(['No site', 'Site A', 'Site B', 'Old Site'])
|
||||
})
|
||||
|
||||
it('sends site_id when adding a truck', async () => {
|
||||
render(<TruckManager trucks={trucks} sites={sites} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add Truck/ }))
|
||||
fireEvent.change(screen.getByLabelText(/Truck Number/), { target: { value: 'NEW 1' } })
|
||||
fireEvent.change(screen.getByLabelText('Site'), { target: { value: 'site-b' } })
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Add Truck' }).pop()!)
|
||||
await waitFor(() => expect(fetchMock).toHaveBeenCalled())
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ truck_no: 'NEW 1', carrier: null, site_id: 'site-b' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent, within } from '@testing-library/react'
|
||||
import { ReportForm } from '@/components/incidents/report-form'
|
||||
import { I18nProvider } from '@/lib/i18n/context'
|
||||
import en from '@/messages/en.json'
|
||||
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }) }))
|
||||
|
||||
const sites = [
|
||||
{ id: 'site-a', name: 'Site A', zones: [{ id: 'z1', name: 'Dock', qr_code_token: 'tok-a' }] },
|
||||
{ id: 'site-b', name: 'Site B', zones: [{ id: 'z2', name: 'Yard', qr_code_token: 'tok-b' }] },
|
||||
]
|
||||
const trucks = [
|
||||
{ id: 't1', truck_no: 'AAA 1', carrier: null, site_id: 'site-a' },
|
||||
{ id: 't2', truck_no: 'BBB 2', carrier: null, site_id: 'site-b' },
|
||||
{ id: 't3', truck_no: 'FREE 3', carrier: null, site_id: null },
|
||||
]
|
||||
|
||||
function renderForm(props: Partial<React.ComponentProps<typeof ReportForm>> = {}) {
|
||||
return render(
|
||||
<I18nProvider messages={en}>
|
||||
<ReportForm
|
||||
zoneToken={null}
|
||||
zoneName={null}
|
||||
siteName={null}
|
||||
sites={sites}
|
||||
defaultSiteId=""
|
||||
trucks={trucks}
|
||||
initialTruckId="t1"
|
||||
{...props}
|
||||
/>
|
||||
</I18nProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
const selectWith = (text: string) =>
|
||||
screen.getAllByRole('combobox').find(s => within(s).queryByText(text)) as HTMLSelectElement
|
||||
|
||||
const truckNos = () =>
|
||||
Array.from(selectWith(en.ReportForm.truckPlaceholder).options).map(o => o.textContent)
|
||||
|
||||
describe('ReportForm truck filter', () => {
|
||||
it('defaults the site to the preselected truck site and filters trucks', () => {
|
||||
renderForm()
|
||||
expect(selectWith(en.ReportForm.sitePlaceholder).value).toBe('site-a')
|
||||
expect(truckNos()).toEqual([en.ReportForm.truckPlaceholder, 'AAA 1', 'FREE 3'])
|
||||
})
|
||||
|
||||
it('changing the site refilters and clears a truck that no longer fits', () => {
|
||||
renderForm()
|
||||
expect(selectWith(en.ReportForm.truckPlaceholder).value).toBe('t1')
|
||||
fireEvent.change(selectWith(en.ReportForm.sitePlaceholder), { target: { value: 'site-b' } })
|
||||
expect(truckNos()).toEqual([en.ReportForm.truckPlaceholder, 'BBB 2', 'FREE 3'])
|
||||
expect(selectWith(en.ReportForm.truckPlaceholder).value).toBe('')
|
||||
})
|
||||
|
||||
it('uses the QR zone site when a zone token is present', () => {
|
||||
renderForm({ zoneToken: 'tok-b', zoneName: 'Yard', siteName: 'Site B', initialTruckId: null })
|
||||
fireEvent.change(screen.getAllByRole('combobox').find(s => within(s).queryByText(en.IncidentType.transport))!, {
|
||||
target: { value: 'transport' },
|
||||
})
|
||||
expect(truckNos()).toEqual([en.ReportForm.truckPlaceholder, 'BBB 2', 'FREE 3'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseSiteId } from '@/lib/admin/truck-input'
|
||||
|
||||
const UUID = '3f2b8c1e-9d4a-4e6f-8a1b-2c3d4e5f6a7b'
|
||||
|
||||
describe('parseSiteId', () => {
|
||||
it('treats undefined as not provided', () => {
|
||||
expect(parseSiteId(undefined)).toEqual({ ok: true, value: undefined })
|
||||
})
|
||||
it('treats null and empty string as clear', () => {
|
||||
expect(parseSiteId(null)).toEqual({ ok: true, value: null })
|
||||
expect(parseSiteId('')).toEqual({ ok: true, value: null })
|
||||
})
|
||||
it('accepts a uuid', () => {
|
||||
expect(parseSiteId(UUID)).toEqual({ ok: true, value: UUID })
|
||||
})
|
||||
it('rejects anything else', () => {
|
||||
expect(parseSiteId('abc')).toEqual({ ok: false })
|
||||
expect(parseSiteId(12)).toEqual({ ok: false })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { trucksForSite, siteForTruck } from '@/lib/report/trucks'
|
||||
|
||||
const trucks = [
|
||||
{ id: 't1', site_id: 'A' },
|
||||
{ id: 't2', site_id: 'B' },
|
||||
{ id: 't3', site_id: null },
|
||||
]
|
||||
|
||||
describe('trucksForSite', () => {
|
||||
it('returns matching and unassigned trucks', () => {
|
||||
expect(trucksForSite(trucks, 'A').map(t => t.id)).toEqual(['t1', 't3'])
|
||||
expect(trucksForSite(trucks, 'B').map(t => t.id)).toEqual(['t2', 't3'])
|
||||
})
|
||||
it('returns all trucks when no site is selected', () => {
|
||||
expect(trucksForSite(trucks, '').map(t => t.id)).toEqual(['t1', 't2', 't3'])
|
||||
})
|
||||
it('returns only unassigned trucks for a site with none linked', () => {
|
||||
expect(trucksForSite(trucks, 'C').map(t => t.id)).toEqual(['t3'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('siteForTruck', () => {
|
||||
it('returns the truck site', () => {
|
||||
expect(siteForTruck(trucks, 't2')).toBe('B')
|
||||
})
|
||||
it('returns null for unassigned, unknown or missing truck', () => {
|
||||
expect(siteForTruck(trucks, 't3')).toBeNull()
|
||||
expect(siteForTruck(trucks, 'nope')).toBeNull()
|
||||
expect(siteForTruck(trucks, null)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { groupSites, zonesForSite, resolveZoneToken, type ZoneRow } from '@/lib/report/zones'
|
||||
import { groupSites, zonesForSite, resolveZoneToken, siteIdForToken, type ZoneRow } from '@/lib/report/zones'
|
||||
|
||||
const rows: ZoneRow[] = [
|
||||
{ siteId: 's1', siteName: 'SC1', zoneId: 'z1', zoneName: 'Dock A', token: 'tok-a' },
|
||||
@@ -44,3 +44,17 @@ describe('resolveZoneToken', () => {
|
||||
expect(resolveZoneToken({ zoneToken: null, sites, zoneId: 'zz' })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('siteIdForToken', () => {
|
||||
const sites = [
|
||||
{ id: 'A', name: 'Site A', zones: [{ id: 'z1', name: 'Dock', qr_code_token: 'tok-1' }] },
|
||||
{ id: 'B', name: 'Site B', zones: [{ id: 'z2', name: 'Yard', qr_code_token: 'tok-2' }] },
|
||||
]
|
||||
it('finds the site that owns the token', () => {
|
||||
expect(siteIdForToken(sites, 'tok-2')).toBe('B')
|
||||
})
|
||||
it('returns empty string for null or unknown token', () => {
|
||||
expect(siteIdForToken(sites, null)).toBe('')
|
||||
expect(siteIdForToken(sites, 'nope')).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user