feat: transport incidents with truck number support
- DB: trucks table + incidents.truck_id FK + transport enum value - Validation: transport type requires truck_id - Create API: validates truck exists/active, persists truck_id - Report form: truck dropdown shown when type=transport (required) - Admin: TruckManager CRUD + /api/admin/trucks route - Detail: trucks join surfaced in incident-detail + detail page query - Inbox (HSE + supervisor): truck filter, transport in TYPE_OPTIONS, fixed stale enum values (dropped dangerous_occurrence/mhe_asset/occupational_disease) - List: transport label + truck number badge in rows - i18n: transport + truckLabel/truckPlaceholder in en/ms/zh Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CPf5Rc8QPx6V8KLEEgfKEQ
This commit is contained in:
@@ -5,6 +5,7 @@ import { redirect } from 'next/navigation'
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { UserManager, type AdminUser, type SiteOption } from '@/components/admin/user-manager'
|
||||
import { SiteZoneManager, type SiteWithZones } from '@/components/admin/site-zone-manager'
|
||||
import { TruckManager, type Truck } from '@/components/admin/truck-manager'
|
||||
|
||||
export default async function AdminHome() {
|
||||
const supabase = await createClient()
|
||||
@@ -15,7 +16,7 @@ export default async function AdminHome() {
|
||||
.from('users').select('role').eq('id', user.id).single()
|
||||
if (!profile || profile.role !== 'admin') redirect('/login')
|
||||
|
||||
const [{ data: users }, { data: sites }] = await Promise.all([
|
||||
const [{ data: users }, { data: sites }, { data: trucks }] = await Promise.all([
|
||||
supabase
|
||||
.from('users')
|
||||
.select('id, name, email, role, department, site_id, active')
|
||||
@@ -24,6 +25,10 @@ export default async function AdminHome() {
|
||||
.from('sites')
|
||||
.select('id, name, address, zones (id, name, qr_code_token)')
|
||||
.order('name'),
|
||||
supabase
|
||||
.from('trucks')
|
||||
.select('id, truck_no, carrier, active')
|
||||
.order('truck_no'),
|
||||
])
|
||||
|
||||
const siteOptions: SiteOption[] = (sites ?? []).map(s => ({ id: s.id, name: s.name }))
|
||||
@@ -41,6 +46,7 @@ export default async function AdminHome() {
|
||||
</div>
|
||||
<UserManager users={(users ?? []) as AdminUser[]} sites={siteOptions} />
|
||||
<SiteZoneManager sites={(sites ?? []) as unknown as SiteWithZones[]} />
|
||||
<TruckManager trucks={(trucks ?? []) as Truck[]} />
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ export default async function HseIncidentDetailPage({ params }: Props) {
|
||||
reported_at, closed_at,
|
||||
sites (id, name),
|
||||
zones (id, name),
|
||||
trucks (id, truck_no, carrier),
|
||||
reporter:users!reported_by (id, name, email),
|
||||
evidence_files (id, stage, file_url, file_type, uploaded_at)
|
||||
`)
|
||||
|
||||
@@ -3,14 +3,14 @@ export const dynamic = 'force-dynamic'
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { IncidentList, type Incident } from '@/components/incidents/incident-list'
|
||||
import { Pagination } from '@/components/incidents/pagination'
|
||||
import { IncidentFilters, type SiteOption } from '@/components/incidents/incident-filters'
|
||||
import { IncidentFilters, type SiteOption, type TruckOption } from '@/components/incidents/incident-filters'
|
||||
|
||||
const PAGE_SIZE = 25
|
||||
|
||||
export default async function HseInboxPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ page?: string; q?: string; status?: string; type?: string; site_id?: string }>
|
||||
searchParams: Promise<{ page?: string; q?: string; status?: string; type?: string; site_id?: string; truck_id?: string }>
|
||||
}) {
|
||||
const supabase = await createClient()
|
||||
const params = await searchParams
|
||||
@@ -23,6 +23,7 @@ export default async function HseInboxPage({
|
||||
id, reference_no, incident_type, status, severity, reported_at,
|
||||
sites (name),
|
||||
zones (name),
|
||||
trucks (truck_no),
|
||||
reporter:users!reported_by (name)
|
||||
`, { count: 'exact' })
|
||||
.order('reported_at', { ascending: false })
|
||||
@@ -33,13 +34,16 @@ export default async function HseInboxPage({
|
||||
if (params.status) query = query.eq('status', params.status)
|
||||
if (params.type) query = query.eq('incident_type', params.type)
|
||||
if (params.site_id) query = query.eq('site_id', params.site_id)
|
||||
if (params.truck_id) query = query.eq('truck_id', params.truck_id)
|
||||
|
||||
const [{ data: incidents, count }, { data: sites }] = await Promise.all([
|
||||
const [{ data: incidents, count }, { data: sites }, { data: trucks }] = await Promise.all([
|
||||
query.range(from, from + PAGE_SIZE - 1),
|
||||
supabase.from('sites').select('id, name').order('name'),
|
||||
supabase.from('trucks').select('id, truck_no').eq('active', true).order('truck_no'),
|
||||
])
|
||||
|
||||
const siteOptions: SiteOption[] = (sites ?? []).map(s => ({ id: s.id, name: s.name }))
|
||||
const truckOptions: TruckOption[] = (trucks ?? []).map(tk => ({ id: tk.id, truck_no: tk.truck_no }))
|
||||
|
||||
return (
|
||||
<main className="max-w-4xl mx-auto px-4 py-6">
|
||||
@@ -47,7 +51,7 @@ export default async function HseInboxPage({
|
||||
<h1 className="text-2xl font-bold text-gray-900">Incident Inbox</h1>
|
||||
<span className="text-sm text-gray-500">{count ?? incidents?.length ?? 0} incidents</span>
|
||||
</div>
|
||||
<IncidentFilters sites={siteOptions} />
|
||||
<IncidentFilters sites={siteOptions} trucks={truckOptions} />
|
||||
<IncidentList incidents={(incidents ?? []) as unknown as Incident[]} basePath="/hse" />
|
||||
<Pagination page={page} pageSize={PAGE_SIZE} total={count ?? 0} href="/hse/incidents" />
|
||||
</main>
|
||||
|
||||
@@ -3,14 +3,14 @@ export const dynamic = 'force-dynamic'
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { IncidentList, type Incident } from '@/components/incidents/incident-list'
|
||||
import { Pagination } from '@/components/incidents/pagination'
|
||||
import { IncidentFilters, type SiteOption } from '@/components/incidents/incident-filters'
|
||||
import { IncidentFilters, type SiteOption, type TruckOption } from '@/components/incidents/incident-filters'
|
||||
|
||||
const PAGE_SIZE = 25
|
||||
|
||||
export default async function SupervisorInboxPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ page?: string; q?: string; status?: string; type?: string; site_id?: string }>
|
||||
searchParams: Promise<{ page?: string; q?: string; status?: string; type?: string; site_id?: string; truck_id?: string }>
|
||||
}) {
|
||||
const supabase = await createClient()
|
||||
const params = await searchParams
|
||||
@@ -23,6 +23,7 @@ export default async function SupervisorInboxPage({
|
||||
id, reference_no, incident_type, status, severity, reported_at,
|
||||
sites (name),
|
||||
zones (name),
|
||||
trucks (truck_no),
|
||||
reporter:users!reported_by (name)
|
||||
`, { count: 'exact' })
|
||||
.order('reported_at', { ascending: false })
|
||||
@@ -33,13 +34,16 @@ export default async function SupervisorInboxPage({
|
||||
if (params.status) query = query.eq('status', params.status)
|
||||
if (params.type) query = query.eq('incident_type', params.type)
|
||||
if (params.site_id) query = query.eq('site_id', params.site_id)
|
||||
if (params.truck_id) query = query.eq('truck_id', params.truck_id)
|
||||
|
||||
const [{ data: incidents, count }, { data: sites }] = await Promise.all([
|
||||
const [{ data: incidents, count }, { data: sites }, { data: trucks }] = await Promise.all([
|
||||
query.range(from, from + PAGE_SIZE - 1),
|
||||
supabase.from('sites').select('id, name').order('name'),
|
||||
supabase.from('trucks').select('id, truck_no').eq('active', true).order('truck_no'),
|
||||
])
|
||||
|
||||
const siteOptions: SiteOption[] = (sites ?? []).map(s => ({ id: s.id, name: s.name }))
|
||||
const truckOptions: TruckOption[] = (trucks ?? []).map(tk => ({ id: tk.id, truck_no: tk.truck_no }))
|
||||
|
||||
return (
|
||||
<main className="max-w-4xl mx-auto px-4 py-6">
|
||||
@@ -47,7 +51,7 @@ export default async function SupervisorInboxPage({
|
||||
<h1 className="text-2xl font-bold text-gray-900">Incident Inbox</h1>
|
||||
<span className="text-sm text-gray-500">{count ?? incidents?.length ?? 0} incidents</span>
|
||||
</div>
|
||||
<IncidentFilters sites={siteOptions} />
|
||||
<IncidentFilters sites={siteOptions} trucks={truckOptions} />
|
||||
<IncidentList incidents={(incidents ?? []) as unknown as Incident[]} basePath="/supervisor" />
|
||||
<Pagination page={page} pageSize={PAGE_SIZE} total={count ?? 0} href="/supervisor/incidents" />
|
||||
</main>
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { requireAdmin } from '@/lib/auth/require-admin'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { supabase, user } = await requireAdmin()
|
||||
if (!user) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
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)
|
||||
return NextResponse.json(
|
||||
{ error: 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 })
|
||||
}
|
||||
@@ -47,6 +47,7 @@ export async function POST(request: Request) {
|
||||
injury_involved: body.injury_involved === 'true' || body.injury_involved === true,
|
||||
asset_involved: body.asset_involved === 'true' || body.asset_involved === true,
|
||||
medical_status: body.medical_status as MedicalStatus | undefined || undefined,
|
||||
truck_id: (body.truck_id as string) || null,
|
||||
}
|
||||
|
||||
const validation = validateIncidentInput(input)
|
||||
@@ -54,6 +55,14 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Validation failed', details: validation.errors }, { status: 422 })
|
||||
}
|
||||
|
||||
let truckId: string | null = null
|
||||
if (input.incident_type === 'transport') {
|
||||
const { data: truck } = await supabase
|
||||
.from('trucks').select('id').eq('id', input.truck_id).eq('active', true).single()
|
||||
if (!truck) return NextResponse.json({ error: 'Validation failed', details: ['truck not found or inactive'] }, { status: 422 })
|
||||
truckId = truck.id
|
||||
}
|
||||
|
||||
let rawDetails: Record<string, unknown> | undefined
|
||||
if (typeof body.type_details === 'string' && body.type_details) {
|
||||
try {
|
||||
@@ -91,6 +100,7 @@ export async function POST(request: Request) {
|
||||
asset_involved: input.asset_involved,
|
||||
medical_status: input.injury_involved ? (input.medical_status ?? 'none') : null,
|
||||
type_details: detailsCheck.sanitized,
|
||||
truck_id: truckId,
|
||||
})
|
||||
.select('id, reference_no')
|
||||
.single()
|
||||
|
||||
+12
-1
@@ -32,6 +32,12 @@ export default async function ReportPage({ searchParams }: Props) {
|
||||
}
|
||||
}
|
||||
|
||||
const { data: trucks } = await supabase
|
||||
.from('trucks')
|
||||
.select('id, truck_no, carrier')
|
||||
.eq('active', true)
|
||||
.order('truck_no')
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-gray-50 py-6 px-4 max-w-lg mx-auto">
|
||||
<div className="mb-6">
|
||||
@@ -47,7 +53,12 @@ export default async function ReportPage({ searchParams }: Props) {
|
||||
<p className="text-sm text-amber-600 mt-1">No zone detected — zone will not be recorded</p>
|
||||
)}
|
||||
</div>
|
||||
<ReportForm zoneToken={zone ?? null} zoneName={zoneName} siteName={siteName} />
|
||||
<ReportForm
|
||||
zoneToken={zone ?? null}
|
||||
zoneName={zoneName}
|
||||
siteName={siteName}
|
||||
trucks={(trucks ?? []) as Array<{ id: string; truck_no: string; carrier: string | null }>}
|
||||
/>
|
||||
<OfflineSync />
|
||||
</main>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
|
||||
export type Truck = {
|
||||
id: string
|
||||
truck_no: string
|
||||
carrier: string | null
|
||||
active: boolean
|
||||
}
|
||||
|
||||
interface Props {
|
||||
trucks: Truck[]
|
||||
}
|
||||
|
||||
export function TruckManager({ trucks }: Props) {
|
||||
const router = useRouter()
|
||||
const [truckNo, setTruckNo] = useState('')
|
||||
const [carrier, setCarrier] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
async function handleAdd() {
|
||||
const no = truckNo.trim()
|
||||
if (!no) return
|
||||
setSubmitting(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetch('/ims/api/admin/trucks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ truck_no: no, carrier: carrier.trim() || null }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) {
|
||||
setError(data.error ?? 'Failed to add truck')
|
||||
return
|
||||
}
|
||||
setTruckNo('')
|
||||
setCarrier('')
|
||||
router.refresh()
|
||||
} catch {
|
||||
setError('Network error')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
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">
|
||||
<h2 className="text-sm font-semibold text-gray-900">Trucks</h2>
|
||||
</div>
|
||||
|
||||
<div className="px-5 py-4 space-y-3">
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Truck number (e.g. WXY 1234)"
|
||||
className="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
value={truckNo}
|
||||
onChange={e => setTruckNo(e.target.value)}
|
||||
onKeyDown={e => e.key === 'Enter' && handleAdd()}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Carrier (optional)"
|
||||
className="flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
value={carrier}
|
||||
onChange={e => setCarrier(e.target.value)}
|
||||
onKeyDown={e => e.key === 'Enter' && handleAdd()}
|
||||
/>
|
||||
<button
|
||||
onClick={handleAdd}
|
||||
disabled={submitting || !truckNo.trim()}
|
||||
className="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{submitting ? 'Adding…' : 'Add'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-xs text-red-600">{error}</p>
|
||||
)}
|
||||
|
||||
{trucks.length === 0 ? (
|
||||
<p className="text-sm text-gray-400 py-2">No trucks yet.</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-gray-100">
|
||||
{trucks.map(tk => (
|
||||
<li key={tk.id} className="flex items-center gap-3 py-2">
|
||||
<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="ml-auto text-xs font-medium px-2 py-0.5 rounded-full bg-gray-100 text-gray-500">
|
||||
Inactive
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -8,6 +8,7 @@ const TYPE_LABELS: Record<string, string> = {
|
||||
environmental: 'Environmental',
|
||||
security: 'Security',
|
||||
fire: 'Fire / Emergency',
|
||||
transport: 'Transport / Vehicle',
|
||||
}
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
@@ -42,6 +43,7 @@ export type Incident = {
|
||||
type_details?: Record<string, string | boolean> | null
|
||||
sites: { id: string; name: string } | null
|
||||
zones: { id: string; name: string } | null
|
||||
trucks: { id: string; truck_no: string; carrier: string | null } | null
|
||||
reporter: { id: string; name: string; email: string } | null
|
||||
evidence_files: Array<{
|
||||
id: string
|
||||
@@ -86,6 +88,12 @@ export function IncidentDetail({ incident }: Props) {
|
||||
<dl className="grid grid-cols-2 gap-4 sm:grid-cols-3">
|
||||
<Field label="Site" value={incident.sites?.name} />
|
||||
<Field label="Zone" value={incident.zones?.name} />
|
||||
{incident.trucks && (
|
||||
<Field
|
||||
label="Truck"
|
||||
value={`${incident.trucks.truck_no}${incident.trucks.carrier ? ` — ${incident.trucks.carrier}` : ''}`}
|
||||
/>
|
||||
)}
|
||||
<Field label="Reported by" value={incident.reporter?.name} />
|
||||
<Field label="Reported at" value={new Date(incident.reported_at).toLocaleString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })} />
|
||||
<Field label="Severity" value={incident.severity ? `Level ${incident.severity}` : 'Not yet assigned'} />
|
||||
|
||||
@@ -17,21 +17,23 @@ const TYPE_OPTIONS = [
|
||||
{ value: '', label: 'All Types' },
|
||||
{ value: 'injury', label: 'Injury' },
|
||||
{ value: 'near_miss', label: 'Near Miss' },
|
||||
{ value: 'dangerous_occurrence', label: 'Dangerous Occurrence' },
|
||||
{ value: 'occupational_disease', label: 'Occupational Disease' },
|
||||
{ value: 'hazard', label: 'Hazard' },
|
||||
{ value: 'asset_damage', label: 'Asset Damage' },
|
||||
{ value: 'environmental', label: 'Environmental' },
|
||||
{ value: 'mhe_asset', label: 'MHE / Asset' },
|
||||
{ value: 'security', label: 'Security' },
|
||||
{ value: 'fire', label: 'Fire' },
|
||||
{ value: 'transport', label: 'Transport' },
|
||||
]
|
||||
|
||||
export interface SiteOption { id: string; name: string }
|
||||
export interface TruckOption { id: string; truck_no: string }
|
||||
|
||||
interface FiltersProps {
|
||||
sites: SiteOption[]
|
||||
trucks: TruckOption[]
|
||||
}
|
||||
|
||||
function FiltersInner({ sites }: FiltersProps) {
|
||||
function FiltersInner({ sites, trucks }: FiltersProps) {
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
const searchParams = useSearchParams()
|
||||
@@ -58,7 +60,7 @@ function FiltersInner({ sites }: FiltersProps) {
|
||||
}, [updateParam])
|
||||
|
||||
const hasFilters = searchParams.get('q') || searchParams.get('status') ||
|
||||
searchParams.get('type') || searchParams.get('site_id')
|
||||
searchParams.get('type') || searchParams.get('site_id') || searchParams.get('truck_id')
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2 mb-4">
|
||||
@@ -102,6 +104,16 @@ function FiltersInner({ sites }: FiltersProps) {
|
||||
{sites.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
|
||||
</select>
|
||||
)}
|
||||
{trucks.length > 0 && (
|
||||
<select
|
||||
value={searchParams.get('truck_id') ?? ''}
|
||||
onChange={e => updateParam('truck_id', e.target.value)}
|
||||
className="text-sm border border-gray-300 rounded-lg px-2 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
|
||||
>
|
||||
<option value="">All Trucks</option>
|
||||
{trucks.map(tk => <option key={tk.id} value={tk.id}>{tk.truck_no}</option>)}
|
||||
</select>
|
||||
)}
|
||||
{hasFilters && (
|
||||
<button
|
||||
onClick={() => {
|
||||
@@ -117,10 +129,10 @@ function FiltersInner({ sites }: FiltersProps) {
|
||||
)
|
||||
}
|
||||
|
||||
export function IncidentFilters({ sites }: FiltersProps) {
|
||||
export function IncidentFilters({ sites, trucks }: FiltersProps) {
|
||||
return (
|
||||
<Suspense fallback={<div className="h-10 mb-4" />}>
|
||||
<FiltersInner sites={sites} />
|
||||
<FiltersInner sites={sites} trucks={trucks} />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ const TYPE_LABELS: Record<string, string> = {
|
||||
environmental: 'Environmental',
|
||||
security: 'Security',
|
||||
fire: 'Fire / Emergency',
|
||||
transport: 'Transport / Vehicle',
|
||||
}
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
@@ -31,6 +32,7 @@ export type Incident = {
|
||||
reported_at: string
|
||||
sites: { name: string } | null
|
||||
zones: { name: string } | null
|
||||
trucks: { truck_no: string } | null
|
||||
reporter: { name: string } | null
|
||||
}
|
||||
|
||||
@@ -113,6 +115,9 @@ export function IncidentList({ incidents, basePath }: Props) {
|
||||
{TYPE_LABELS[inc.incident_type] ?? inc.incident_type}
|
||||
{inc.zones?.name && ` · ${inc.zones.name}`}
|
||||
{inc.sites?.name && ` · ${inc.sites.name}`}
|
||||
{inc.trucks?.truck_no && (
|
||||
<span className="ml-1 text-xs text-gray-400">· {inc.trucks.truck_no}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-4 text-right">
|
||||
|
||||
@@ -10,9 +10,10 @@ interface Props {
|
||||
zoneToken: string | null
|
||||
zoneName: string | null
|
||||
siteName: string | null
|
||||
trucks: Array<{ id: string; truck_no: string; carrier: string | null }>
|
||||
}
|
||||
|
||||
export function ReportForm({ zoneToken }: Props) {
|
||||
export function ReportForm({ zoneToken, trucks }: Props) {
|
||||
const router = useRouter()
|
||||
const t = useTranslations('ReportForm')
|
||||
const itLabels = useTranslations('IncidentType')
|
||||
@@ -27,6 +28,7 @@ export function ReportForm({ zoneToken }: Props) {
|
||||
['environmental', itLabels.environmental],
|
||||
['security', itLabels.security],
|
||||
['fire', itLabels.fire],
|
||||
['transport', itLabels.transport],
|
||||
]
|
||||
|
||||
const MEDICAL_STATUS_OPTIONS: [MedicalStatus, string][] = [
|
||||
@@ -55,6 +57,7 @@ export function ReportForm({ zoneToken }: Props) {
|
||||
injury_involved: false,
|
||||
medical_status: '' as MedicalStatus | '',
|
||||
asset_involved: false,
|
||||
truck_id: '',
|
||||
})
|
||||
const [typeDetails, setTypeDetails] = useState<Record<string, string | boolean>>({})
|
||||
|
||||
@@ -116,6 +119,7 @@ export function ReportForm({ zoneToken }: Props) {
|
||||
asset_involved: form.asset_involved,
|
||||
medical_status: form.medical_status || undefined,
|
||||
type_details: Object.keys(typeDetails).length > 0 ? typeDetails : undefined,
|
||||
truck_id: form.truck_id || undefined,
|
||||
created_at: new Date().toISOString(),
|
||||
})
|
||||
setSavedOffline(true)
|
||||
@@ -168,6 +172,7 @@ export function ReportForm({ zoneToken }: Props) {
|
||||
if (Object.keys(typeDetails).length > 0) {
|
||||
fd.append('type_details', JSON.stringify(typeDetails))
|
||||
}
|
||||
if (form.truck_id) fd.append('truck_id', form.truck_id)
|
||||
files.forEach(f => fd.append('files', f))
|
||||
|
||||
const res = await fetch('/ims/api/incidents', { method: 'POST', body: fd })
|
||||
@@ -217,7 +222,7 @@ export function ReportForm({ zoneToken }: Props) {
|
||||
className="w-full border border-gray-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
value={form.incident_type}
|
||||
onChange={e => {
|
||||
setForm(f => ({ ...f, incident_type: e.target.value as IncidentType }))
|
||||
setForm(f => ({ ...f, incident_type: e.target.value as IncidentType, truck_id: '' }))
|
||||
setTypeDetails({})
|
||||
}}
|
||||
>
|
||||
@@ -254,6 +259,27 @@ export function ReportForm({ zoneToken }: Props) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{form.incident_type === 'transport' && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
{t.truckLabel} <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<select
|
||||
required
|
||||
className="w-full border border-gray-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
value={form.truck_id}
|
||||
onChange={e => setForm(f => ({ ...f, truck_id: e.target.value }))}
|
||||
>
|
||||
<option value="">{t.truckPlaceholder}</option>
|
||||
{trucks.map(tk => (
|
||||
<option key={tk.id} value={tk.id}>
|
||||
{tk.truck_no}{tk.carrier ? ` — ${tk.carrier}` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
{t.descriptionLabel} <span className="text-red-500">*</span>
|
||||
@@ -344,7 +370,7 @@ export function ReportForm({ zoneToken }: Props) {
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting || !form.incident_type}
|
||||
disabled={submitting || !form.incident_type || (form.incident_type === 'transport' && !form.truck_id)}
|
||||
className="w-full bg-blue-600 text-white py-3 rounded-lg font-medium text-sm
|
||||
hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
|
||||
@@ -9,6 +9,7 @@ export interface PendingReport {
|
||||
asset_involved: boolean
|
||||
medical_status?: string
|
||||
type_details?: Record<string, string | boolean>
|
||||
truck_id?: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
|
||||
+5
-2
@@ -16,7 +16,9 @@
|
||||
"qualityScoreLabel": "Report quality — {score}/10",
|
||||
"errorGeneric": "Something went wrong. Please try again.",
|
||||
"savedOffline": "Report saved. It will be submitted automatically when you're back online.",
|
||||
"offlineBanner": "You're offline. Your report will be saved and submitted when you reconnect."
|
||||
"offlineBanner": "You're offline. Your report will be saved and submitted when you reconnect.",
|
||||
"truckLabel": "Truck",
|
||||
"truckPlaceholder": "Select truck…"
|
||||
},
|
||||
"IncidentType": {
|
||||
"injury": "Injury / Medical",
|
||||
@@ -25,7 +27,8 @@
|
||||
"asset_damage": "Asset / Equipment Damage",
|
||||
"environmental": "Environmental Incident",
|
||||
"security": "Security Incident",
|
||||
"fire": "Fire / Emergency"
|
||||
"fire": "Fire / Emergency",
|
||||
"transport": "Transport / Vehicle"
|
||||
},
|
||||
"MedicalStatus": {
|
||||
"none": "No treatment needed",
|
||||
|
||||
+5
-2
@@ -16,7 +16,9 @@
|
||||
"qualityScoreLabel": "Kualiti laporan — {score}/10",
|
||||
"errorGeneric": "Berlaku ralat. Sila cuba lagi.",
|
||||
"savedOffline": "Laporan disimpan. Ia akan dihantar secara automatik apabila anda dalam talian semula.",
|
||||
"offlineBanner": "Anda tiada sambungan. Laporan anda akan disimpan dan dihantar apabila disambungkan semula."
|
||||
"offlineBanner": "Anda tiada sambungan. Laporan anda akan disimpan dan dihantar apabila disambungkan semula.",
|
||||
"truckLabel": "Trak",
|
||||
"truckPlaceholder": "Pilih trak…"
|
||||
},
|
||||
"IncidentType": {
|
||||
"injury": "Kecederaan / Perubatan",
|
||||
@@ -25,7 +27,8 @@
|
||||
"asset_damage": "Kerosakan Aset / Peralatan",
|
||||
"environmental": "Insiden Alam Sekitar",
|
||||
"security": "Insiden Keselamatan",
|
||||
"fire": "Kebakaran / Kecemasan"
|
||||
"fire": "Kebakaran / Kecemasan",
|
||||
"transport": "Pengangkutan / Kenderaan"
|
||||
},
|
||||
"MedicalStatus": {
|
||||
"none": "Tiada rawatan diperlukan",
|
||||
|
||||
+5
-2
@@ -16,7 +16,9 @@
|
||||
"qualityScoreLabel": "报告质量 — {score}/10",
|
||||
"errorGeneric": "出现错误,请重试。",
|
||||
"savedOffline": "报告已保存。当您重新联网时将自动提交。",
|
||||
"offlineBanner": "您处于离线状态。您的报告将在重新联网时自动提交。"
|
||||
"offlineBanner": "您处于离线状态。您的报告将在重新联网时自动提交。",
|
||||
"truckLabel": "货车",
|
||||
"truckPlaceholder": "选择货车…"
|
||||
},
|
||||
"IncidentType": {
|
||||
"injury": "受伤/医疗",
|
||||
@@ -25,7 +27,8 @@
|
||||
"asset_damage": "资产/设备损坏",
|
||||
"environmental": "环境事故",
|
||||
"security": "安全事故",
|
||||
"fire": "火灾/紧急情况"
|
||||
"fire": "火灾/紧急情况",
|
||||
"transport": "运输 / 车辆"
|
||||
},
|
||||
"MedicalStatus": {
|
||||
"none": "无需治疗",
|
||||
|
||||
Reference in New Issue
Block a user