feat(db): phase 4 group 2 — admin routes to Drizzle

Convert app/api/admin/sites, trucks, users from Supabase PostgREST to
Drizzle ORM. All data ops use asAdmin(); all audit writes use
withUser(session.sub, tx => writeAuditLog(tx, ...)). Zero supabase
imports remain in the three files.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-07-23 16:44:39 +08:00
co-authored by Claude Sonnet 4.6
parent 25f923f530
commit d234ebf916
3 changed files with 179 additions and 168 deletions
+47 -53
View File
@@ -2,57 +2,56 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { requireAdmin } from '@/lib/auth/require-admin'
import { createClient } from '@/lib/supabase/server'
import { asAdmin, withUser } from '@/lib/db/with-user'
import { trucks, incidents } from '@/lib/db/schema'
import { writeAuditLog } from '@/lib/db/audit'
import { eq, sql } from 'drizzle-orm'
export async function POST(request: NextRequest) {
const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const body: { truck_no?: string; carrier?: string } = await request.json().catch(() => ({}))
const truck_no = (body.truck_no ?? '').trim()
if (!truck_no) return NextResponse.json({ error: 'truck_no required' }, { status: 422 })
const { data: truck, error } = await supabase
.from('trucks')
.insert({ truck_no, carrier: (body.carrier ?? '').trim() || null })
.select('id')
.single()
if (error || !truck)
try {
const [truck] = await asAdmin(db =>
db.insert(trucks).values({ truckNo: truck_no, carrier: (body.carrier ?? '').trim() || null }).returning({ id: trucks.id })
)
if (!truck) return NextResponse.json({ error: 'Insert failed' }, { status: 400 })
await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'trucks', truck.id, 'INSERT', { truck_no, carrier: (body.carrier ?? '').trim() || null })
})
return NextResponse.json({ id: truck.id }, { status: 201 })
} catch (e) {
const code = (e as { code?: string }).code
return NextResponse.json(
{ error: error?.code === '23505' ? 'Truck number already exists' : 'Insert failed' },
{ error: code === '23505' ? 'Truck number already exists' : 'Insert failed' },
{ status: 400 },
)
await supabase.rpc('write_audit_log', {
p_table_name: 'trucks',
p_record_id: truck.id,
p_action: 'INSERT',
p_new_value: { truck_no, carrier: (body.carrier ?? '').trim() || null },
})
return NextResponse.json({ id: truck.id }, { status: 201 })
}
}
export async function PATCH(request: NextRequest) {
const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const body: { id?: string; active?: boolean } = await request.json().catch(() => ({}))
if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 })
const { data: before } = await supabase.from('trucks').select('*').eq('id', body.id).single()
const { error } = await supabase.from('trucks').update({ active: body.active }).eq('id', body.id)
if (error) return NextResponse.json({ error: 'Update failed' }, { status: 500 })
await supabase.rpc('write_audit_log', {
p_table_name: 'trucks',
p_record_id: body.id,
p_action: 'admin_update',
p_old_value: before,
p_new_value: { active: body.active },
const [before] = await asAdmin(db =>
db.select().from(trucks).where(eq(trucks.id, body.id!)).limit(1)
)
try {
await asAdmin(db =>
db.update(trucks).set({ active: body.active }).where(eq(trucks.id, body.id!))
)
} catch {
return NextResponse.json({ error: 'Update failed' }, { status: 500 })
}
await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'trucks', body.id!, 'admin_update', { active: body.active }, before ?? null)
})
return NextResponse.json({ ok: true })
}
@@ -60,39 +59,34 @@ export async function PATCH(request: NextRequest) {
export async function DELETE(request: NextRequest) {
const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const body: { id?: string } = await request.json().catch(() => ({}))
if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 })
const { count } = await supabase
.from('incidents')
.select('id', { count: 'exact', head: true })
.eq('truck_id', body.id)
if ((count ?? 0) > 0)
const [countRow] = await asAdmin(db =>
db.select({ cnt: sql<number>`count(*)` }).from(incidents).where(eq(incidents.truckId, body.id!))
)
const incidentCount = Number(countRow?.cnt ?? 0)
if (incidentCount > 0)
return NextResponse.json(
{ error: `Cannot delete — ${count} incident(s) reference this truck. Deactivate it instead.` },
{ error: `Cannot delete — ${incidentCount} incident(s) reference this truck. Deactivate it instead.` },
{ status: 409 },
)
const { data: before } = await supabase.from('trucks').select('*').eq('id', body.id).single()
const { error } = await supabase.from('trucks').delete().eq('id', body.id)
if (error)
const [before] = await asAdmin(db =>
db.select().from(trucks).where(eq(trucks.id, body.id!)).limit(1)
)
try {
await asAdmin(db => db.delete(trucks).where(eq(trucks.id, body.id!)))
} catch (e) {
const code = (e as { code?: string }).code
return NextResponse.json(
{
error:
error.code === '23503'
? 'Cannot delete — this truck is still referenced elsewhere. Deactivate it instead.'
: 'Delete failed',
},
{ status: error.code === '23503' ? 409 : 500 },
{ error: code === '23503' ? 'Cannot delete — truck still referenced. Deactivate instead.' : 'Delete failed' },
{ status: code === '23503' ? 409 : 500 },
)
await supabase.rpc('write_audit_log', {
p_table_name: 'trucks',
p_record_id: body.id,
p_action: 'DELETE',
p_old_value: before,
}
await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'trucks', body.id!, 'DELETE', null, before ?? null)
})
return NextResponse.json({ ok: true })
}