From 2a9d32d1d0585d2ac73da4f6fd6f954451f9a0a2 Mon Sep 17 00:00:00 2001 From: weeihan Date: Thu, 15 Oct 2026 11:17:15 +0800 Subject: [PATCH 1/7] docs: spec for linking trucks to a site Co-Authored-By: Claude Sonnet 5.5 --- .../2026-10-15-truck-site-link-design.md | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 docs/superpowers/specs/2026-10-15-truck-site-link-design.md diff --git a/docs/superpowers/specs/2026-10-15-truck-site-link-design.md b/docs/superpowers/specs/2026-10-15-truck-site-link-design.md new file mode 100644 index 0000000..c403f7a --- /dev/null +++ b/docs/superpowers/specs/2026-10-15-truck-site-link-design.md @@ -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. From fd7a55337fdd8cc862e0d80c8f7c0731739da974 Mon Sep 17 00:00:00 2001 From: weeihan Date: Thu, 15 Oct 2026 11:25:16 +0800 Subject: [PATCH 2/7] docs: implementation plan for truck-to-site link Co-Authored-By: Claude Sonnet 5.5 --- .../plans/2026-10-15-truck-site-link.md | 886 ++++++++++++++++++ 1 file changed, 886 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-15-truck-site-link.md diff --git a/docs/superpowers/plans/2026-10-15-truck-site-link.md b/docs/superpowers/plans/2026-10-15-truck-site-link.md new file mode 100644 index 0000000..73474f8 --- /dev/null +++ b/docs/superpowers/plans/2026-10-15-truck-site-link.md @@ -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(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" +``` From 867b725262f14db14819f0d29516cd86cbbfb30e Mon Sep 17 00:00:00 2001 From: weeihan Date: Thu, 15 Oct 2026 11:44:37 +0800 Subject: [PATCH 3/7] feat(trucks): site_id column and site/truck helpers Co-Authored-By: Claude Sonnet 5.5 --- db/ops/2026-10-15-trucks-site-id.sql | 5 +++++ db/schema.sql | 3 +++ lib/admin/truck-input.ts | 11 ++++++++++ lib/db/schema.ts | 1 + lib/report/trucks.ts | 12 +++++++++++ lib/report/zones.ts | 5 +++++ tests/lib/admin/truck-input.test.ts | 21 ++++++++++++++++++ tests/lib/report/trucks.test.ts | 32 ++++++++++++++++++++++++++++ tests/lib/report/zones.test.ts | 16 +++++++++++++- 9 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 db/ops/2026-10-15-trucks-site-id.sql create mode 100644 lib/admin/truck-input.ts create mode 100644 lib/report/trucks.ts create mode 100644 tests/lib/admin/truck-input.test.ts create mode 100644 tests/lib/report/trucks.test.ts diff --git a/db/ops/2026-10-15-trucks-site-id.sql b/db/ops/2026-10-15-trucks-site-id.sql new file mode 100644 index 0000000..b0b5938 --- /dev/null +++ b/db/ops/2026-10-15-trucks-site-id.sql @@ -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; diff --git a/db/schema.sql b/db/schema.sql index eb02d0f..8391254 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -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(), diff --git a/lib/admin/truck-input.ts b/lib/admin/truck-input.ts new file mode 100644 index 0000000..e7d0a62 --- /dev/null +++ b/lib/admin/truck-input.ts @@ -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 } +} diff --git a/lib/db/schema.ts b/lib/db/schema.ts index 319800a..445437a 100644 --- a/lib/db/schema.ts +++ b/lib/db/schema.ts @@ -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(), }) diff --git a/lib/report/trucks.ts b/lib/report/trucks.ts new file mode 100644 index 0000000..caffcae --- /dev/null +++ b/lib/report/trucks.ts @@ -0,0 +1,12 @@ +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 +} diff --git a/lib/report/zones.ts b/lib/report/zones.ts index ec9ac51..e6f2e40 100644 --- a/lib/report/zones.ts +++ b/lib/report/zones.ts @@ -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 ?? '' +} diff --git a/tests/lib/admin/truck-input.test.ts b/tests/lib/admin/truck-input.test.ts new file mode 100644 index 0000000..6bf8505 --- /dev/null +++ b/tests/lib/admin/truck-input.test.ts @@ -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 }) + }) +}) diff --git a/tests/lib/report/trucks.test.ts b/tests/lib/report/trucks.test.ts new file mode 100644 index 0000000..7b9e609 --- /dev/null +++ b/tests/lib/report/trucks.test.ts @@ -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() + }) +}) diff --git a/tests/lib/report/zones.test.ts b/tests/lib/report/zones.test.ts index 5d43e09..173aa40 100644 --- a/tests/lib/report/zones.test.ts +++ b/tests/lib/report/zones.test.ts @@ -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('') + }) +}) From f3f3aec59fef513141065ec3ab5acb715ab11d57 Mon Sep 17 00:00:00 2001 From: weeihan Date: Thu, 15 Oct 2026 11:46:31 +0800 Subject: [PATCH 4/7] feat(trucks): admin API accepts site_id and partial edits Co-Authored-By: Claude Sonnet 5.5 --- app/api/admin/trucks/route.ts | 59 +++++++++++--- tests/api/admin-trucks.test.ts | 137 +++++++++++++++++++++++++++++++++ 2 files changed, 187 insertions(+), 9 deletions(-) create mode 100644 tests/api/admin-trucks.test.ts diff --git a/app/api/admin/trucks/route.ts b/app/api/admin/trucks/route.ts index 5469683..a8d3129 100644 --- a/app/api/admin/trucks/route.ts +++ b/app/api/admin/trucks/route.ts @@ -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 { + 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 && !(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 }) diff --git a/tests/api/admin-trucks.test.ts b/tests/api/admin-trucks.test.ts new file mode 100644 index 0000000..b063801 --- /dev/null +++ b/tests/api/admin-trucks.test.ts @@ -0,0 +1,137 @@ +// @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) + }) +}) From 149704898dc00d68a7348360feb3c84a5520d60c Mon Sep 17 00:00:00 2001 From: weeihan Date: Thu, 15 Oct 2026 11:48:15 +0800 Subject: [PATCH 5/7] feat(trucks): site select, site label and edit modal in admin Co-Authored-By: Claude Sonnet 5.5 --- app/(protected)/admin/page.tsx | 7 +- components/admin/admin-panel.tsx | 7 +- components/admin/truck-manager.tsx | 92 ++++++++++++++++++- tests/components/admin/truck-manager.test.tsx | 72 +++++++++++++++ 4 files changed, 169 insertions(+), 9 deletions(-) create mode 100644 tests/components/admin/truck-manager.test.tsx diff --git a/app/(protected)/admin/page.tsx b/app/(protected)/admin/page.tsx index b850db3..e4b3881 100644 --- a/app/(protected)/admin/page.tsx +++ b/app/(protected)/admin/page.tsx @@ -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} /> ) diff --git a/components/admin/admin-panel.tsx b/components/admin/admin-panel.tsx index 6aa4747..2b88df6 100644 --- a/components/admin/admin-panel.tsx +++ b/components/admin/admin-panel.tsx @@ -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('users') const tabs: { id: Tab; label: string; count: number }[] = [ @@ -45,7 +46,7 @@ export function AdminPanel({ users, sites, siteOptions, trucks }: Props) { {tab === 'users' && } {tab === 'sites' && } - {tab === 'trucks' && } + {tab === 'trucks' && } ) } diff --git a/components/admin/truck-manager.tsx b/components/admin/truck-manager.tsx index 0c8ce3d..7112f13 100644 --- a/components/admin/truck-manager.tsx +++ b/components/admin/truck-manager.tsx @@ -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(null) const [showAdd, setShowAdd] = useState(false) const [confirmDelete, setConfirmDelete] = useState(null) + 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) + } 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 (
@@ -106,8 +140,15 @@ export function TruckManager({ trucks }: Props) {
{tk.truck_no} {tk.carrier && {tk.carrier}} + + {siteName(tk.site_id) ?? 'Unassigned'} +
+ Report link @@ -134,11 +175,11 @@ export function TruckManager({ trucks }: Props) {
{/* Add Truck Modal */} - { setShowAdd(false); setTruckNo(''); setCarrier(''); setError(null) }} + { setShowAdd(false); setTruckNo(''); setCarrier(''); setSiteId(''); setError(null) }} title="Add Truck" width="sm" footer={ <> - @@ -165,6 +206,49 @@ export function TruckManager({ trucks }: Props) { onKeyDown={e => e.key === 'Enter' && handleAdd()} className={inp} />
+
+ + +
+
+ + + {/* 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} /> +
+
+ + +
diff --git a/tests/components/admin/truck-manager.test.tsx b/tests/components/admin/truck-manager.test.tsx new file mode 100644 index 0000000..b94f85f --- /dev/null +++ b/tests/components/admin/truck-manager.test.tsx @@ -0,0 +1,72 @@ +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' }) + }) +}) From 5f1d7a6ed4ed998b90961b6e4021cb91ed31ee55 Mon Sep 17 00:00:00 2001 From: weeihan Date: Thu, 15 Oct 2026 11:50:00 +0800 Subject: [PATCH 6/7] feat(report): filter truck list by selected site Co-Authored-By: Claude Sonnet 5.5 --- app/report/page.tsx | 2 + components/incidents/report-form.tsx | 20 ++++-- .../incidents/report-form-trucks.test.tsx | 64 +++++++++++++++++++ 3 files changed, 81 insertions(+), 5 deletions(-) create mode 100644 tests/components/incidents/report-form-trucks.test.tsx diff --git a/app/report/page.tsx b/app/report/page.tsx index f3c0f67..bd23bf4 100644 --- a/app/report/page.tsx +++ b/app/report/page.tsx @@ -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 => diff --git a/components/incidents/report-form.tsx b/components/incidents/report-form.tsx index fe64adb..f75116f 100644 --- a/components/incidents/report-form.tsx +++ b/components/incidents/report-form.tsx @@ -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>({}) 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 }))} > - {trucks.map(tk => ( + {truckOptions.map(tk => ( diff --git a/tests/components/incidents/report-form-trucks.test.tsx b/tests/components/incidents/report-form-trucks.test.tsx new file mode 100644 index 0000000..2ca356e --- /dev/null +++ b/tests/components/incidents/report-form-trucks.test.tsx @@ -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> = {}) { + 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 }) + 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']) + }) +}) From 17c32ecd045ecb7a24b0975cb69912ead35ace16 Mon Sep 17 00:00:00 2001 From: weeihan Date: Thu, 15 Oct 2026 11:53:32 +0800 Subject: [PATCH 7/7] fix(trucks): skip active-site check when PATCH leaves site unchanged Co-Authored-By: Claude Sonnet 5.5 --- app/api/admin/trucks/route.ts | 2 +- tests/api/admin-trucks.test.ts | 12 ++++++++++++ tests/components/admin/truck-manager.test.tsx | 11 +++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/app/api/admin/trucks/route.ts b/app/api/admin/trucks/route.ts index a8d3129..74d9280 100644 --- a/app/api/admin/trucks/route.ts +++ b/app/api/admin/trucks/route.ts @@ -83,7 +83,7 @@ export async function PATCH(request: NextRequest) { const [before] = await asAdmin(db => db.select().from(trucks).where(eq(trucks.id, body.id!)).limit(1) ) - if (set.siteId && !(await activeSiteExists(set.siteId))) + if (set.siteId && set.siteId !== before?.siteId && !(await activeSiteExists(set.siteId))) return NextResponse.json({ error: 'Site not found or inactive' }, { status: 422 }) try { diff --git a/tests/api/admin-trucks.test.ts b/tests/api/admin-trucks.test.ts index b063801..2a976b8 100644 --- a/tests/api/admin-trucks.test.ts +++ b/tests/api/admin-trucks.test.ts @@ -128,6 +128,18 @@ describe('PATCH /api/admin/trucks', () => { 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' diff --git a/tests/components/admin/truck-manager.test.tsx b/tests/components/admin/truck-manager.test.tsx index b94f85f..b843f3e 100644 --- a/tests/components/admin/truck-manager.test.tsx +++ b/tests/components/admin/truck-manager.test.tsx @@ -60,6 +60,17 @@ describe('TruckManager site link', () => { 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() + 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() fireEvent.click(screen.getByRole('button', { name: /Add Truck/ }))