36 KiB
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/incidentsis 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, editdb/schema.sqlandlib/db/schema.ts. Do NOT run any SQL against any database. No RLS change. - Every DB mutation writes
audit_login the same transaction (existing pattern withwriteAuditLog). - Admin routes use
requireAdmin()andasAdmin. - UI uses existing tokens and classes (
bg-surface,border-divider,text-accent-700, ...). No hard-coded hex, nobg-white, no 2px borders.npm run check:designmust printdesign 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.mddeletion,*.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 theCREATE TABLE trucks (...)block, line ~96-102) - Modify:
lib/db/schema.ts(truckstable, line ~102) - Create:
lib/report/trucks.ts - Create:
lib/admin/truck-input.ts - Modify:
lib/report/zones.ts(addsiteIdForToken) - 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.siteIdDrizzle column. -
Step 1: Write the failing tests
tests/lib/report/trucks.test.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:
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):
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:
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:
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:
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:
-- 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
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:
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
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:
parseSiteIdfrom@/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, emptytruck_no, or bad/unknown/inactive site, 409 duplicate truck number, 500 other. -
Step 1: Write the failing tests
tests/api/admin-trucks.test.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:
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:
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:
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:
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
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/trucksandPOST /api/admin/trucksfrom Task 2. -
Produces:
Truckgainssite_id: string | null; new exportedTruckSite = { id: string; name: string; active: boolean };TruckManagerprops{ trucks: Truck[]; sites: TruckSite[] };AdminPanelproptruckSites: TruckSite[]. -
Step 1: Write the failing test
tests/components/admin/truck-manager.test.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:
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:
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:
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
<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
<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:
<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:
<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:
{/* 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
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
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 addssiteId, list addssite_id) - Modify:
components/incidents/report-form.tsx - Test:
tests/components/incidents/report-form-trucks.test.tsx(create)
Interfaces:
-
Consumes:
trucksForSite,siteForTruckfrom@/lib/report/trucks;siteIdForTokenfrom@/lib/report/zones(Task 1). -
Produces:
ReportFormproptrucks: Array<{ id; truck_no; carrier; site_id: string | null }>. -
Step 1: Write the failing test
tests/components/incidents/report-form-trucks.test.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
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:
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:
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:
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
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"