# 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(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(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 { 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() expect(screen.getByText('Site A')).toBeTruthy() expect(screen.getByText('Unassigned')).toBeTruthy() }) it('edits the site of a truck via PATCH', async () => { render() 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() 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() 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() 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(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
{tk.truck_no} {tk.carrier && {tk.carrier}}
``` with ```tsx
{tk.truck_no} {tk.carrier && {tk.carrier}} {siteName(tk.site_id) ?? 'Unassigned'}
``` and, in the right-hand actions, add before the "Report link" anchor: ```tsx ``` 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
``` 3g. Add an Edit modal before the Delete Confirm modal: ```tsx {/* Edit Truck Modal */} { setEditing(null); setError(null) }} title="Edit Truck" width="sm" footer={ <> } > {error &&

{error}

}
setEditNo(e.target.value)} className={inp} />
setEditCarrier(e.target.value)} className={inp} />
``` 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 ``. 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 `` (find the existing ``. - [ ] **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> = {}) { return render( , ) } 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 ``, 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" ```