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
+90 -12
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,21 +109,78 @@ 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">
<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
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>
<a
href={`/ims/report?zone=${z.qr_code_token}`}
target="_blank"
className="text-xs text-blue-600 hover:underline"
>
Report link / QR target
</a>
<div className="flex items-center gap-3">
<a
href={`/ims/report?zone=${z.qr_code_token}`}
target="_blank"
className="text-xs text-blue-600 hover:underline"
>
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>
+60 -13
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,25 +115,46 @@ 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>
<a
href={`/ims/report?truck_id=${tk.id}`}
target="_blank"
className="text-xs text-blue-600 hover:underline"
>
Report link / QR target
</a>
<div className="flex items-center gap-3">
<a
href={`/ims/report?truck_id=${tk.id}`}
target="_blank"
className="text-xs text-blue-600 hover:underline"
>
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)