feat: delete + deactivate for sites, zones, and trucks; harden incident API error handling

- zones: add active column (migration 20260713000005)
- sites/zones API: PATCH (toggle active) + DELETE (blocked when incidents reference it)
- trucks API: PATCH + DELETE with same pattern
- admin page: select active for sites + zones
- site-zone-manager + truck-manager: deactivate toggle + delete button per row with busyId
- incidents API: reject reports on deactivated zone/site; wrap handler in top-level try-catch so unhandled errors return JSON (not HTML)
- report-form: parse JSON separately so HTTP status code surfaces instead of generic "Something went wrong"

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CPf5Rc8QPx6V8KLEEgfKEQ
This commit is contained in:
2026-07-13 16:05:36 +08:00
co-authored by Claude Sonnet 4.6
parent 370b985375
commit 690485f74e
8 changed files with 307 additions and 30 deletions
+1 -1
View File
@@ -23,7 +23,7 @@ export default async function AdminHome() {
.order('created_at', { ascending: false }),
supabase
.from('sites')
.select('id, name, address, zones (id, name, qr_code_token)')
.select('id, name, address, active, zones (id, name, qr_code_token, active)')
.order('name'),
supabase
.from('trucks')
+65
View File
@@ -45,3 +45,68 @@ export async function POST(request: NextRequest) {
})
return NextResponse.json({ id: site.id }, { status: 201 })
}
export async function PATCH(request: NextRequest) {
const { supabase, user } = await requireAdmin()
if (!user) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const body: { kind?: 'site' | 'zone'; id?: string; active?: boolean } =
await request.json().catch(() => ({}))
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 { error } = await supabase.from(table).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: table,
p_record_id: body.id,
p_action: 'admin_update',
p_old_value: before,
p_new_value: { active: body.active },
})
return NextResponse.json({ ok: true })
}
export async function DELETE(request: NextRequest) {
const { supabase, user } = await requireAdmin()
if (!user) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const body: { kind?: 'site' | 'zone'; id?: string } = await request.json().catch(() => ({}))
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 { count } = await supabase
.from('incidents')
.select('id', { count: 'exact', head: true })
.eq(col, body.id)
if ((count ?? 0) > 0)
return NextResponse.json(
{ error: `Cannot delete — ${count} incident(s) reference this. Deactivate it instead.` },
{ status: 409 },
)
const { data: before } = await supabase.from(table).select('*').eq('id', body.id).single()
const { error } = await supabase.from(table).delete().eq('id', body.id)
if (error)
return NextResponse.json(
{
error:
error.code === '23503'
? 'Cannot delete — this is still referenced elsewhere. Deactivate it instead.'
: 'Delete failed',
},
{ status: error.code === '23503' ? 409 : 500 },
)
await supabase.rpc('write_audit_log', {
p_table_name: table,
p_record_id: body.id,
p_action: 'DELETE',
p_old_value: before,
})
return NextResponse.json({ ok: true })
}
+60
View File
@@ -32,3 +32,63 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ id: truck.id }, { status: 201 })
}
export async function PATCH(request: NextRequest) {
const { supabase, user } = await requireAdmin()
if (!user) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
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 },
})
return NextResponse.json({ ok: true })
}
export async function DELETE(request: NextRequest) {
const { supabase, user } = await requireAdmin()
if (!user) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
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)
return NextResponse.json(
{ error: `Cannot delete — ${count} 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)
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 },
)
await supabase.rpc('write_audit_log', {
p_table_name: 'trucks',
p_record_id: body.id,
p_action: 'DELETE',
p_old_value: before,
})
return NextResponse.json({ ok: true })
}
+13 -1
View File
@@ -10,6 +10,15 @@ import { getApiKey } from '@/lib/settings'
export const dynamic = 'force-dynamic'
export async function POST(request: Request) {
try {
return await handlePost(request)
} catch (err) {
console.error('Unhandled error in POST /api/incidents:', err)
return NextResponse.json({ error: 'Internal server error', details: [String(err)] }, { status: 500 })
}
}
async function handlePost(request: Request) {
const supabase = await createClient()
const { data, error: authError } = await supabase.auth.getUser()
if (authError || !data?.user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
@@ -80,13 +89,16 @@ export async function POST(request: Request) {
const { data: zone, error: zoneError } = await supabase
.from('zones')
.select('id, site_id')
.select('id, site_id, active, sites(active)')
.eq('qr_code_token', input.zone_token)
.single()
if (zoneError || !zone) {
return NextResponse.json({ error: 'Zone not found' }, { status: 404 })
}
if (zone.active === false || (zone.sites as { active?: boolean } | null)?.active === false) {
return NextResponse.json({ error: 'This location is no longer active for reporting.' }, { status: 409 })
}
const { data: incident, error: incidentError } = await supabase
.from('incidents')
+81 -3
View File
@@ -7,7 +7,8 @@ export type SiteWithZones = {
id: string
name: string
address: string | null
zones: Array<{ id: string; name: string; qr_code_token: string }>
active: boolean
zones: Array<{ id: string; name: string; qr_code_token: string; active: boolean }>
}
interface Props {
@@ -20,6 +21,7 @@ export function SiteZoneManager({ sites }: Props) {
const [zoneName, setZoneName] = useState('')
const [zoneSiteId, setZoneSiteId] = useState('')
const [busy, setBusy] = useState(false)
const [busyId, setBusyId] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
const post = async (payload: Record<string, unknown>) => {
@@ -40,6 +42,25 @@ export function SiteZoneManager({ sites }: Props) {
return true
}
const send = async (method: 'PATCH' | 'DELETE', payload: Record<string, unknown>) => {
const id = payload.id as string
setBusyId(id)
setError(null)
const res = await fetch('/ims/api/admin/sites', {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
setBusyId(null)
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setError(data.error ?? 'Action failed')
return false
}
router.refresh()
return true
}
return (
<div className="bg-white rounded-xl shadow-sm p-5">
<h2 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-4">Sites & Zones</h2>
@@ -88,14 +109,49 @@ export function SiteZoneManager({ sites }: Props) {
<div className="space-y-4">
{sites.map(site => (
<div key={site.id} className="border border-gray-100 rounded-lg p-3">
<div
key={site.id}
className={`border border-gray-100 rounded-lg p-3 transition-opacity ${!site.active ? 'opacity-50' : ''}`}
>
<div className="flex items-center justify-between gap-2">
<div>
<p className="text-sm font-semibold text-gray-900">{site.name}</p>
{site.address && <p className="text-xs text-gray-400">{site.address}</p>}
</div>
<div className="flex items-center gap-2 shrink-0">
<button
disabled={busyId === site.id}
onClick={() => send('PATCH', { kind: 'site', id: site.id, active: !site.active })}
className={`text-xs font-medium px-2 py-1 rounded-full border transition-colors disabled:opacity-50 ${
site.active
? 'border-green-300 text-green-700 hover:bg-green-50'
: 'border-gray-300 text-gray-500 hover:bg-gray-50'
}`}
>
{site.active ? 'Active' : 'Deactivated'}
</button>
<button
disabled={busyId === site.id}
onClick={async () => {
if (window.confirm(`Delete site "${site.name}"? This cannot be undone.`))
await send('DELETE', { kind: 'site', id: site.id })
}}
className="text-xs text-red-600 hover:underline disabled:opacity-50"
>
Delete
</button>
</div>
</div>
{site.zones.length > 0 ? (
<ul className="mt-2 space-y-1">
{site.zones.map(z => (
<li key={z.id} className="flex items-center justify-between text-sm text-gray-600">
<li
key={z.id}
className={`flex items-center justify-between text-sm text-gray-600 transition-opacity ${!z.active ? 'opacity-50' : ''}`}
>
<span>{z.name}</span>
<div className="flex items-center gap-3">
<a
href={`/ims/report?zone=${z.qr_code_token}`}
target="_blank"
@@ -103,6 +159,28 @@ export function SiteZoneManager({ sites }: Props) {
>
Report link / QR target
</a>
<button
disabled={busyId === z.id}
onClick={() => send('PATCH', { kind: 'zone', id: z.id, active: !z.active })}
className={`text-xs font-medium px-2 py-0.5 rounded-full border transition-colors disabled:opacity-50 ${
z.active
? 'border-green-300 text-green-700 hover:bg-green-50'
: 'border-gray-300 text-gray-500 hover:bg-gray-50'
}`}
>
{z.active ? 'Active' : 'Deactivated'}
</button>
<button
disabled={busyId === z.id}
onClick={async () => {
if (window.confirm(`Delete zone "${z.name}"? This cannot be undone.`))
await send('DELETE', { kind: 'zone', id: z.id })
}}
className="text-xs text-red-600 hover:underline disabled:opacity-50"
>
Delete
</button>
</div>
</li>
))}
</ul>
+53 -6
View File
@@ -19,6 +19,7 @@ export function TruckManager({ trucks }: Props) {
const [truckNo, setTruckNo] = useState('')
const [carrier, setCarrier] = useState('')
const [submitting, setSubmitting] = useState(false)
const [busyId, setBusyId] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
async function handleAdd() {
@@ -47,6 +48,31 @@ export function TruckManager({ trucks }: Props) {
}
}
const send = async (method: 'PATCH' | 'DELETE', payload: Record<string, unknown>) => {
const id = payload.id as string
setBusyId(id)
setError(null)
try {
const res = await fetch('/ims/api/admin/trucks', {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setError(data.error ?? 'Action failed')
return false
}
router.refresh()
return true
} catch {
setError('Network error')
return false
} finally {
setBusyId(null)
}
}
return (
<div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
<div className="px-5 py-4 border-b border-gray-100">
@@ -89,18 +115,17 @@ export function TruckManager({ trucks }: Props) {
) : (
<ul className="divide-y divide-gray-100">
{trucks.map(tk => (
<li key={tk.id} className="flex items-center justify-between py-2">
<li
key={tk.id}
className={`flex items-center justify-between py-2 transition-opacity ${!tk.active ? 'opacity-50' : ''}`}
>
<div className="flex items-center gap-3">
<span className="text-sm font-medium text-gray-900">{tk.truck_no}</span>
{tk.carrier && (
<span className="text-xs text-gray-500">{tk.carrier}</span>
)}
{!tk.active && (
<span className="text-xs font-medium px-2 py-0.5 rounded-full bg-gray-100 text-gray-500">
Inactive
</span>
)}
</div>
<div className="flex items-center gap-3">
<a
href={`/ims/report?truck_id=${tk.id}`}
target="_blank"
@@ -108,6 +133,28 @@ export function TruckManager({ trucks }: Props) {
>
Report link / QR target
</a>
<button
disabled={busyId === tk.id}
onClick={() => send('PATCH', { id: tk.id, active: !tk.active })}
className={`text-xs font-medium px-2 py-0.5 rounded-full border transition-colors disabled:opacity-50 ${
tk.active
? 'border-green-300 text-green-700 hover:bg-green-50'
: 'border-gray-300 text-gray-500 hover:bg-gray-50'
}`}
>
{tk.active ? 'Active' : 'Deactivated'}
</button>
<button
disabled={busyId === tk.id}
onClick={async () => {
if (window.confirm(`Delete truck "${tk.truck_no}"? This cannot be undone.`))
await send('DELETE', { id: tk.id })
}}
className="text-xs text-red-600 hover:underline disabled:opacity-50"
>
Delete
</button>
</div>
</li>
))}
</ul>
+14 -3
View File
@@ -177,15 +177,26 @@ export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
files.forEach(f => fd.append('files', f))
const res = await fetch('/ims/api/incidents', { method: 'POST', body: fd })
const data = await res.json()
// Parse JSON separately so a non-JSON response (HTML error page) surfaces the status code
let data: Record<string, unknown> = {}
try {
data = await res.json()
} catch {
console.error('Non-JSON response from /api/incidents', res.status, res.statusText)
setError(`${t.errorGeneric} (HTTP ${res.status})`)
return
}
if (!res.ok) {
setError(data.details ? data.details.join('. ') : data.error)
const msg = Array.isArray(data.details) ? (data.details as string[]).join('. ') : (data.error as string)
setError(msg ?? t.errorGeneric)
return
}
router.push(`/report/success?ref=${data.reference_no}`)
} catch {
} catch (err) {
console.error('Submit error:', err)
setError(t.errorGeneric)
} finally {
setSubmitting(false)
@@ -0,0 +1,4 @@
-- Add soft-delete support to zones (sites and trucks already have this column).
-- Leave zones_read as USING (true) so deactivated zones still render on historical incidents.
-- Deactivation is enforced for new reports in the create-incident API, not via RLS.
ALTER TABLE zones ADD COLUMN active BOOLEAN NOT NULL DEFAULT true;