From f3f3aec59fef513141065ec3ab5acb715ab11d57 Mon Sep 17 00:00:00 2001 From: weeihan Date: Thu, 15 Oct 2026 11:46:31 +0800 Subject: [PATCH] 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) + }) +})