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
+67 -69
View File
@@ -2,12 +2,14 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
import { requireAdmin } from '@/lib/auth/require-admin' import { requireAdmin } from '@/lib/auth/require-admin'
import { createClient } from '@/lib/supabase/server' import { asAdmin, withUser } from '@/lib/db/with-user'
import { sites, zones, incidents } from '@/lib/db/schema'
import { writeAuditLog } from '@/lib/db/audit'
import { eq, sql } from 'drizzle-orm'
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
const { session } = await requireAdmin() const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const body: { kind?: 'site' | 'zone'; name?: string; address?: string; site_id?: string } = const body: { kind?: 'site' | 'zone'; name?: string; address?: string; site_id?: string } =
await request.json().catch(() => ({})) await request.json().catch(() => ({}))
@@ -16,58 +18,57 @@ export async function POST(request: NextRequest) {
if (body.kind === 'zone') { if (body.kind === 'zone') {
if (!body.site_id) return NextResponse.json({ error: 'site_id required for zone' }, { status: 422 }) if (!body.site_id) return NextResponse.json({ error: 'site_id required for zone' }, { status: 422 })
const { data: zone, error } = await supabase const qrCodeToken = crypto.randomUUID()
.from('zones') try {
.insert({ site_id: body.site_id, name }) const [zone] = await asAdmin(db =>
.select('id, qr_code_token') db.insert(zones).values({ siteId: body.site_id!, name, qrCodeToken }).returning({ id: zones.id, qrCodeToken: zones.qrCodeToken })
.single() )
if (error || !zone) return NextResponse.json({ error: 'Insert failed' }, { status: 500 }) if (!zone) return NextResponse.json({ error: 'Insert failed' }, { status: 500 })
await withUser(session.sub, async tx => {
await supabase.rpc('write_audit_log', { await writeAuditLog(tx, 'zones', zone.id, 'INSERT', { name, site_id: body.site_id })
p_table_name: 'zones', })
p_record_id: zone.id, return NextResponse.json({ id: zone.id, qr_code_token: zone.qrCodeToken }, { status: 201 })
p_action: 'INSERT', } catch {
p_new_value: { name, site_id: body.site_id }, return NextResponse.json({ error: 'Insert failed' }, { status: 500 })
}) }
return NextResponse.json({ id: zone.id, qr_code_token: zone.qr_code_token }, { status: 201 })
} }
const { data: site, error } = await supabase try {
.from('sites') const [site] = await asAdmin(db =>
.insert({ name, address: body.address ?? null }) db.insert(sites).values({ name, address: body.address ?? null }).returning({ id: sites.id })
.select('id') )
.single() if (!site) return NextResponse.json({ error: 'Insert failed' }, { status: 500 })
if (error || !site) return NextResponse.json({ error: 'Insert failed' }, { status: 500 }) await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'sites', site.id, 'INSERT', { name, address: body.address ?? null })
await supabase.rpc('write_audit_log', { })
p_table_name: 'sites', return NextResponse.json({ id: site.id }, { status: 201 })
p_record_id: site.id, } catch {
p_action: 'INSERT', return NextResponse.json({ error: 'Insert failed' }, { status: 500 })
p_new_value: { name, address: body.address ?? null }, }
})
return NextResponse.json({ id: site.id }, { status: 201 })
} }
export async function PATCH(request: NextRequest) { export async function PATCH(request: NextRequest) {
const { session } = await requireAdmin() const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const body: { kind?: 'site' | 'zone'; id?: string; active?: boolean } = const body: { kind?: 'site' | 'zone'; id?: string; active?: boolean } =
await request.json().catch(() => ({})) await request.json().catch(() => ({}))
if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 }) if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 })
const table = body.kind === 'zone' ? 'zones' : 'sites'
const { data: before } = await supabase.from(table).select('*').eq('id', body.id).single() const table = body.kind === 'zone' ? zones : sites
const { error } = await supabase.from(table).update({ active: body.active }).eq('id', body.id) const [before] = await asAdmin(db =>
if (error) return NextResponse.json({ error: 'Update failed' }, { status: 500 }) db.select().from(table).where(eq(table.id, body.id!)).limit(1)
)
await supabase.rpc('write_audit_log', { try {
p_table_name: table, await asAdmin(db =>
p_record_id: body.id, db.update(table).set({ active: body.active }).where(eq(table.id, body.id!))
p_action: 'admin_update', )
p_old_value: before, } catch {
p_new_value: { active: body.active }, return NextResponse.json({ error: 'Update failed' }, { status: 500 })
}
const tableName = body.kind === 'zone' ? 'zones' : 'sites'
await withUser(session.sub, async tx => {
await writeAuditLog(tx, tableName, body.id!, 'admin_update', { active: body.active }, before ?? null)
}) })
return NextResponse.json({ ok: true }) return NextResponse.json({ ok: true })
} }
@@ -75,42 +76,39 @@ export async function PATCH(request: NextRequest) {
export async function DELETE(request: NextRequest) { export async function DELETE(request: NextRequest) {
const { session } = await requireAdmin() const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const body: { kind?: 'site' | 'zone'; id?: string } = await request.json().catch(() => ({})) const body: { kind?: 'site' | 'zone'; id?: string } = await request.json().catch(() => ({}))
if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 }) if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 })
const table = body.kind === 'zone' ? 'zones' : 'sites'
const col = body.kind === 'zone' ? 'zone_id' : 'site_id'
// Count referencing incidents for a clear, actionable error message const tableName = body.kind === 'zone' ? 'zones' : 'sites'
const { count } = await supabase const [countRow] = await asAdmin(db =>
.from('incidents') db.select({ cnt: sql<number>`count(*)` })
.select('id', { count: 'exact', head: true }) .from(incidents)
.eq(col, body.id) .where(body.kind === 'zone' ? eq(incidents.zoneId, body.id!) : eq(incidents.siteId, body.id!))
if ((count ?? 0) > 0) )
const incidentCount = Number(countRow?.cnt ?? 0)
if (incidentCount > 0)
return NextResponse.json( return NextResponse.json(
{ error: `Cannot delete — ${count} incident(s) reference this. Deactivate it instead.` }, { error: `Cannot delete — ${incidentCount} incident(s) reference this. Deactivate it instead.` },
{ status: 409 }, { status: 409 },
) )
const { data: before } = await supabase.from(table).select('*').eq('id', body.id).single() const [before] = await asAdmin(db =>
const { error } = await supabase.from(table).delete().eq('id', body.id) db.select().from(body.kind === 'zone' ? zones : sites).where(eq((body.kind === 'zone' ? zones : sites).id, body.id!)).limit(1)
if (error) )
return NextResponse.json( try {
{ await asAdmin(db =>
error: db.delete(body.kind === 'zone' ? zones : sites).where(eq((body.kind === 'zone' ? zones : sites).id, body.id!))
error.code === '23503'
? 'Cannot delete — this is still referenced elsewhere. Deactivate it instead.'
: 'Delete failed',
},
{ status: error.code === '23503' ? 409 : 500 },
) )
} catch (e) {
await supabase.rpc('write_audit_log', { const code = (e as { code?: string }).code
p_table_name: table, return NextResponse.json(
p_record_id: body.id, { error: code === '23503' ? 'Cannot delete — still referenced elsewhere. Deactivate instead.' : 'Delete failed' },
p_action: 'DELETE', { status: code === '23503' ? 409 : 500 },
p_old_value: before, )
}
await withUser(session.sub, async tx => {
await writeAuditLog(tx, tableName, body.id!, 'DELETE', null, before ?? null)
}) })
return NextResponse.json({ ok: true }) return NextResponse.json({ ok: true })
} }
+47 -53
View File
@@ -2,57 +2,56 @@ export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
import { requireAdmin } from '@/lib/auth/require-admin' 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) { export async function POST(request: NextRequest) {
const { session } = await requireAdmin() const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) 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 body: { truck_no?: string; carrier?: string } = await request.json().catch(() => ({}))
const truck_no = (body.truck_no ?? '').trim() const truck_no = (body.truck_no ?? '').trim()
if (!truck_no) return NextResponse.json({ error: 'truck_no required' }, { status: 422 }) if (!truck_no) return NextResponse.json({ error: 'truck_no required' }, { status: 422 })
const { data: truck, error } = await supabase try {
.from('trucks') const [truck] = await asAdmin(db =>
.insert({ truck_no, carrier: (body.carrier ?? '').trim() || null }) db.insert(trucks).values({ truckNo: truck_no, carrier: (body.carrier ?? '').trim() || null }).returning({ id: trucks.id })
.select('id') )
.single() if (!truck) return NextResponse.json({ error: 'Insert failed' }, { status: 400 })
await withUser(session.sub, async tx => {
if (error || !truck) 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( return NextResponse.json(
{ error: error?.code === '23505' ? 'Truck number already exists' : 'Insert failed' }, { error: code === '23505' ? 'Truck number already exists' : 'Insert failed' },
{ status: 400 }, { 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) { export async function PATCH(request: NextRequest) {
const { session } = await requireAdmin() const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const body: { id?: string; active?: boolean } = await request.json().catch(() => ({})) const body: { id?: string; active?: boolean } = await request.json().catch(() => ({}))
if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 }) 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 [before] = await asAdmin(db =>
const { error } = await supabase.from('trucks').update({ active: body.active }).eq('id', body.id) db.select().from(trucks).where(eq(trucks.id, body.id!)).limit(1)
if (error) return NextResponse.json({ error: 'Update failed' }, { status: 500 }) )
try {
await supabase.rpc('write_audit_log', { await asAdmin(db =>
p_table_name: 'trucks', db.update(trucks).set({ active: body.active }).where(eq(trucks.id, body.id!))
p_record_id: body.id, )
p_action: 'admin_update', } catch {
p_old_value: before, return NextResponse.json({ error: 'Update failed' }, { status: 500 })
p_new_value: { active: body.active }, }
await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'trucks', body.id!, 'admin_update', { active: body.active }, before ?? null)
}) })
return NextResponse.json({ ok: true }) return NextResponse.json({ ok: true })
} }
@@ -60,39 +59,34 @@ export async function PATCH(request: NextRequest) {
export async function DELETE(request: NextRequest) { export async function DELETE(request: NextRequest) {
const { session } = await requireAdmin() const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const body: { id?: string } = await request.json().catch(() => ({})) const body: { id?: string } = await request.json().catch(() => ({}))
if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 }) if (!body.id) return NextResponse.json({ error: 'id required' }, { status: 422 })
const { count } = await supabase const [countRow] = await asAdmin(db =>
.from('incidents') db.select({ cnt: sql<number>`count(*)` }).from(incidents).where(eq(incidents.truckId, body.id!))
.select('id', { count: 'exact', head: true }) )
.eq('truck_id', body.id) const incidentCount = Number(countRow?.cnt ?? 0)
if ((count ?? 0) > 0) if (incidentCount > 0)
return NextResponse.json( 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 }, { status: 409 },
) )
const { data: before } = await supabase.from('trucks').select('*').eq('id', body.id).single() const [before] = await asAdmin(db =>
const { error } = await supabase.from('trucks').delete().eq('id', body.id) db.select().from(trucks).where(eq(trucks.id, body.id!)).limit(1)
if (error) )
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( return NextResponse.json(
{ { error: code === '23503' ? 'Cannot delete — truck still referenced. Deactivate instead.' : 'Delete failed' },
error: { status: code === '23503' ? 409 : 500 },
error.code === '23503'
? 'Cannot delete — this truck is still referenced elsewhere. Deactivate it instead.'
: 'Delete failed',
},
{ status: error.code === '23503' ? 409 : 500 },
) )
}
await supabase.rpc('write_audit_log', { await withUser(session.sub, async tx => {
p_table_name: 'trucks', await writeAuditLog(tx, 'trucks', body.id!, 'DELETE', null, before ?? null)
p_record_id: body.id,
p_action: 'DELETE',
p_old_value: before,
}) })
return NextResponse.json({ ok: true }) return NextResponse.json({ ok: true })
} }
+65 -46
View File
@@ -1,26 +1,45 @@
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { isValidRole } from '@/lib/auth/roles' import { isValidRole } from '@/lib/auth/roles'
import { requireAdmin } from '@/lib/auth/require-admin' import { requireAdmin } from '@/lib/auth/require-admin'
import { hashPassword } from '@/lib/auth/password' import { hashPassword } from '@/lib/auth/password'
import { asAdmin } from '@/lib/db/with-user' import { asAdmin, withUser } from '@/lib/db/with-user'
import { users } from '@/lib/db/schema' import { users } from '@/lib/db/schema'
import { eq } from 'drizzle-orm' import { writeAuditLog } from '@/lib/db/audit'
import { desc, eq } from 'drizzle-orm'
export async function GET() { export async function GET() {
const { session } = await requireAdmin() const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient() const data = await asAdmin(db =>
const { data, error } = await supabase db.select({
.from('users') id: users.id,
.select('id, name, email, phone, role, department, site_id, active, created_at') name: users.name,
.order('created_at', { ascending: false }) email: users.email,
phone: users.phone,
if (error) return NextResponse.json({ error: 'Fetch failed' }, { status: 500 }) role: users.role,
return NextResponse.json(data ?? []) department: users.department,
siteId: users.siteId,
active: users.active,
createdAt: users.createdAt,
})
.from(users)
.orderBy(desc(users.createdAt))
)
// Return snake_case to preserve existing frontend contract
return NextResponse.json(data.map(u => ({
id: u.id,
name: u.name,
email: u.email,
phone: u.phone,
role: u.role,
department: u.department,
site_id: u.siteId,
active: u.active,
created_at: u.createdAt,
})))
} }
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
@@ -57,12 +76,10 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: 'User creation failed' }, { status: 500 }) return NextResponse.json({ error: 'User creation failed' }, { status: 500 })
} }
const supabase = await createClient() await withUser(session.sub, async tx => {
await supabase.rpc('write_audit_log', { await writeAuditLog(tx, 'users', created.id, 'created', {
p_table_name: 'users', email, role: body.role ?? 'reporter', site_id: body.site_id ?? null,
p_record_id: created.id, })
p_action: 'created',
p_new_value: { email, role: body.role ?? 'reporter', site_id: body.site_id ?? null },
}) })
return NextResponse.json({ id: created.id }, { status: 201 }) return NextResponse.json({ id: created.id }, { status: 201 })
@@ -72,8 +89,6 @@ export async function PATCH(request: NextRequest) {
const { session } = await requireAdmin() const { session } = await requireAdmin()
if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) if (!session) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const body: { const body: {
id?: string id?: string
role?: string role?: string
@@ -90,29 +105,34 @@ export async function PATCH(request: NextRequest) {
if (body.id === session.sub && body.role !== undefined && body.role !== 'admin') if (body.id === session.sub && body.role !== undefined && body.role !== 'admin')
return NextResponse.json({ error: 'Cannot demote your own account' }, { status: 422 }) return NextResponse.json({ error: 'Cannot demote your own account' }, { status: 422 })
const update: Record<string, unknown> = {} const drizzleUpdate: Partial<{ role: typeof users.$inferInsert['role']; siteId: string | null; active: boolean; department: string | null }> = {}
if (body.role !== undefined) update.role = body.role if (body.role !== undefined) drizzleUpdate.role = body.role as typeof users.$inferInsert['role']
if (body.site_id !== undefined) update.site_id = body.site_id if (body.site_id !== undefined) drizzleUpdate.siteId = body.site_id
if (body.active !== undefined) update.active = body.active if (body.active !== undefined) drizzleUpdate.active = body.active
if (body.department !== undefined) update.department = body.department if (body.department !== undefined) drizzleUpdate.department = body.department
if (Object.keys(update).length === 0) if (Object.keys(drizzleUpdate).length === 0)
return NextResponse.json({ error: 'Nothing to update' }, { status: 422 }) return NextResponse.json({ error: 'Nothing to update' }, { status: 422 })
const { data: before } = await supabase const [before] = await asAdmin(db =>
.from('users').select('role, site_id, active, department').eq('id', body.id).single() db.select({ role: users.role, siteId: users.siteId, active: users.active, department: users.department })
.from(users)
.where(eq(users.id, body.id!))
.limit(1)
)
if (!before) return NextResponse.json({ error: 'User not found' }, { status: 404 }) if (!before) return NextResponse.json({ error: 'User not found' }, { status: 404 })
const { error } = await supabase.from('users').update(update).eq('id', body.id) try {
if (error) return NextResponse.json({ error: 'Update failed' }, { status: 500 }) await asAdmin(db => db.update(users).set(drizzleUpdate).where(eq(users.id, body.id!)))
} catch {
await supabase.rpc('write_audit_log', { return NextResponse.json({ error: 'Update failed' }, { status: 500 })
p_table_name: 'users', }
p_record_id: body.id, await withUser(session.sub, async tx => {
p_action: 'admin_update', await writeAuditLog(
p_old_value: before ?? null, tx, 'users', body.id!, 'admin_update',
p_new_value: update, drizzleUpdate,
{ role: before.role, site_id: before.siteId, active: before.active, department: before.department },
)
}) })
return NextResponse.json({ ok: true }) return NextResponse.json({ ok: true })
} }
@@ -126,11 +146,11 @@ export async function DELETE(request: NextRequest) {
if (id === session.sub) if (id === session.sub)
return NextResponse.json({ error: 'Cannot delete your own account' }, { status: 422 }) return NextResponse.json({ error: 'Cannot delete your own account' }, { status: 422 })
const supabase = await createClient()
// fetch user info for audit before deletion // fetch user info for audit before deletion
const { data: target } = await supabase const [target] = await asAdmin(db =>
.from('users').select('email, name, role').eq('id', id).single() db.select({ email: users.email, name: users.name, role: users.role })
.from(users).where(eq(users.id, id)).limit(1)
)
// Delete user directly from DB // Delete user directly from DB
const [deleted] = await asAdmin(db => const [deleted] = await asAdmin(db =>
@@ -142,11 +162,10 @@ export async function DELETE(request: NextRequest) {
} }
if (target) { if (target) {
await supabase.rpc('write_audit_log', { await withUser(session.sub, async tx => {
p_table_name: 'users', await writeAuditLog(tx, 'users', id, 'deleted', {
p_record_id: id, email: target.email, name: target.name, role: target.role,
p_action: 'deleted', })
p_new_value: { email: target.email, name: target.name, role: target.role },
}) })
} }