Initial commit: AARS backend + frontend + holiday/leave phase 1+2
This commit is contained in:
@@ -0,0 +1,291 @@
|
||||
import { useState, useEffect, useMemo, useRef } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend, LineChart, Line } from 'recharts'
|
||||
import { AlertTriangle, MapPin, Users, FileText, Calendar, TrendingUp, XCircle, CheckCircle2, Download, Search, ChevronUp, ChevronDown, Filter, X, Activity } from 'lucide-react'
|
||||
import api from '../../api'
|
||||
import toast from 'react-hot-toast'
|
||||
|
||||
const SEVERITY_COLORS = {
|
||||
'1': { bg: '#D1FAE5', fg: '#065F46', label: '低 Low' },
|
||||
'2': { bg: '#DBEAFE', fg: '#1E40AF', label: '中 Medium' },
|
||||
'3': { bg: '#FEF3C7', fg: '#92400E', label: '高 High' },
|
||||
'4': { bg: '#FED7AA', fg: '#9A3412', label: '嚴重 Severe' },
|
||||
'5': { bg: '#FEE2E2', fg: '#7F1D1D', label: '極嚴重 Critical' },
|
||||
}
|
||||
|
||||
export default function AccidentDashboard() {
|
||||
const [summary, setSummary] = useState(null)
|
||||
const [stats, setStats] = useState(null)
|
||||
const [records, setRecords] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [dateFrom, setDateFrom] = useState('')
|
||||
const [dateTo, setDateTo] = useState('')
|
||||
const dashboardRef = useRef(null)
|
||||
|
||||
const fmt = (d) => d.toISOString().slice(0, 10)
|
||||
const weekRange = (offsetWeeks) => {
|
||||
const now = new Date()
|
||||
const dow = now.getDay()
|
||||
const daysFromMonday = (dow + 6) % 7
|
||||
const start = new Date(now)
|
||||
start.setDate(now.getDate() - daysFromMonday + offsetWeeks * 7)
|
||||
const end = new Date(start)
|
||||
end.setDate(start.getDate() + 6)
|
||||
return [fmt(start), fmt(end)]
|
||||
}
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
const monthStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().slice(0, 10)
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [dateFrom, dateTo])
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const params = {}
|
||||
if (dateFrom) params.date_from = dateFrom
|
||||
if (dateTo) params.date_to = dateTo
|
||||
const [sumRes, statRes, recRes] = await Promise.all([
|
||||
api.get('/api/accident/dashboard/summary', { params }),
|
||||
api.get('/api/accident/dashboard/stats', { params }),
|
||||
api.get('/api/accident/records', { params: { ...params, per_page: 1000 } }).catch(() => ({ data: { records: [] } })),
|
||||
])
|
||||
setSummary(sumRes.data)
|
||||
setStats(statRes.data)
|
||||
setRecords(recRes.data.records || [])
|
||||
} catch (err) {
|
||||
toast.error('載入失敗')
|
||||
console.error(err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleExportExcel = async () => {
|
||||
try {
|
||||
const params = {}
|
||||
if (dateFrom) params.date_from = dateFrom
|
||||
if (dateTo) params.date_to = dateTo
|
||||
const response = await api.get('/api/accident/export/excel', { params, responseType: 'blob' })
|
||||
const url = window.URL.createObjectURL(new Blob([response.data]))
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
let suffix = ''
|
||||
if (dateFrom && dateTo) suffix = `_${dateFrom}_${dateTo}`
|
||||
else if (dateFrom) suffix = `_from_${dateFrom}`
|
||||
else if (dateTo) suffix = `_to_${dateTo}`
|
||||
link.setAttribute('download', `accident${suffix}.xlsx`)
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
toast.success('Excel 已下載')
|
||||
} catch (err) {
|
||||
toast.error('匯出失敗')
|
||||
}
|
||||
}
|
||||
|
||||
// Build donut chart data (severity distribution)
|
||||
const severityData = useMemo(() => {
|
||||
if (!summary?.severity_count) return []
|
||||
return Object.entries(summary.severity_count)
|
||||
.filter(([_, count]) => count > 0)
|
||||
.map(([sev, count]) => ({
|
||||
name: SEVERITY_COLORS[sev]?.label || `Sev ${sev}`,
|
||||
value: count,
|
||||
severity: sev,
|
||||
color: SEVERITY_COLORS[sev]?.fg || '#6B7280',
|
||||
}))
|
||||
}, [summary])
|
||||
|
||||
// Build line chart (monthly trend)
|
||||
const monthlyTrend = useMemo(() => {
|
||||
const byMonth = {}
|
||||
for (const r of records) {
|
||||
if (!r.date) continue
|
||||
const ym = r.date.substring(0, 7)
|
||||
byMonth[ym] = (byMonth[ym] || 0) + 1
|
||||
}
|
||||
return Object.entries(byMonth)
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([month, count]) => ({ month, count }))
|
||||
}, [records])
|
||||
|
||||
if (loading && !summary) {
|
||||
return <div className="p-12 text-center text-slate-500">載入中…</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6" ref={dashboardRef}>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-bold text-slate-900">意外事故 Dashboard</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<Link
|
||||
to="/accident/list"
|
||||
className="flex items-center gap-2 px-3 py-1.5 border border-slate-300 text-slate-700 rounded-md hover:bg-slate-50 text-sm"
|
||||
>
|
||||
<FileText size={16} />
|
||||
列表
|
||||
</Link>
|
||||
<button
|
||||
onClick={handleExportExcel}
|
||||
className="flex items-center gap-2 px-3 py-1.5 bg-green-600 text-white rounded-md hover:bg-green-700 text-sm"
|
||||
>
|
||||
<Download size={16} />
|
||||
匯出 Excel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Date Range Filter */}
|
||||
<div className="card p-4">
|
||||
<div className="flex flex-wrap gap-3 items-end">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-slate-500">日期範圍:</span>
|
||||
<input type="date" value={dateFrom} onChange={e => setDateFrom(e.target.value)} className="text-sm border border-slate-300 rounded-md px-3 py-2" />
|
||||
<span className="text-slate-400">-</span>
|
||||
<input type="date" value={dateTo} onChange={e => setDateTo(e.target.value)} className="text-sm border border-slate-300 rounded-md px-3 py-2" />
|
||||
</div>
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
<button onClick={() => { setDateFrom(today); setDateTo(today) }} className="text-xs px-3 py-2 border border-slate-300 rounded-md hover:bg-slate-50">今日</button>
|
||||
<button onClick={() => { const [w0, w1] = weekRange(0); setDateFrom(w0); setDateTo(w1) }} className="text-xs px-3 py-2 border border-slate-300 rounded-md hover:bg-slate-50">本週</button>
|
||||
<button onClick={() => { const [w0, w1] = weekRange(-1); setDateFrom(w0); setDateTo(w1) }} className="text-xs px-3 py-2 border border-slate-300 rounded-md hover:bg-slate-50">上週</button>
|
||||
<button onClick={() => { setDateFrom(monthStart); setDateTo(today) }} className="text-xs px-3 py-2 border border-slate-300 rounded-md hover:bg-slate-50">本月</button>
|
||||
<button onClick={() => { setDateFrom(''); setDateTo('') }} className="text-xs text-slate-500 hover:text-slate-700 px-2 py-2 border border-slate-300 rounded">清除</button>
|
||||
</div>
|
||||
</div>
|
||||
{(dateFrom || dateTo) && (
|
||||
<p className="text-xs text-slate-400 mt-2">顯示 {dateFrom || '開始'} ~ {dateTo || today} 的數據</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Stats Cards */}
|
||||
{summary && (
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<StatCard icon={AlertTriangle} color="bg-red-50 text-red-600" label="總記錄 Total" value={summary.total_records || 0} />
|
||||
<StatCard icon={Calendar} color="bg-blue-50 text-blue-600" label="本月" value={summary.this_month || 0} />
|
||||
<StatCard icon={MapPin} color="bg-purple-50 text-purple-600" label="地點 Locations" value={summary.unique_locations || 0} />
|
||||
<StatCard icon={TrendingUp} color="bg-green-50 text-green-600" label="日均" value={summary.avg_per_day || 0} />
|
||||
{Object.entries(summary.severity_count || {}).map(([sev, count]) => (
|
||||
<StatCard
|
||||
key={sev}
|
||||
icon={Activity}
|
||||
color=""
|
||||
label={`Severity ${sev}`}
|
||||
value={count}
|
||||
overrideColor={SEVERITY_COLORS[sev]?.fg}
|
||||
overrideBg={SEVERITY_COLORS[sev]?.bg}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Charts */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
{/* Severity Distribution */}
|
||||
<div className="card p-4">
|
||||
<h3 className="text-sm font-semibold text-slate-700 mb-3">嚴重程度分佈</h3>
|
||||
{severityData.length === 0 ? (
|
||||
<p className="text-sm text-slate-400 text-center py-12">暫無數據</p>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height={250}>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={severityData}
|
||||
dataKey="value"
|
||||
nameKey="name"
|
||||
cx="50%" cy="50%"
|
||||
outerRadius={80}
|
||||
label={(entry) => `${entry.name}: ${entry.value}`}
|
||||
>
|
||||
{severityData.map((entry, i) => (
|
||||
<Cell key={i} fill={entry.color} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Monthly Trend */}
|
||||
<div className="card p-4">
|
||||
<h3 className="text-sm font-semibold text-slate-700 mb-3">月度趨勢</h3>
|
||||
{monthlyTrend.length === 0 ? (
|
||||
<p className="text-sm text-slate-400 text-center py-12">暫無數據</p>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height={250}>
|
||||
<LineChart data={monthlyTrend}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="month" />
|
||||
<YAxis />
|
||||
<Tooltip />
|
||||
<Line type="monotone" dataKey="count" stroke="#2563EB" strokeWidth={2} dot={{ r: 4 }} />
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Leaderboards */}
|
||||
{stats && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<RankCard title="地點 (Top 5)" icon={MapPin} data={stats.by_location?.slice(0, 5) || []} field="count" />
|
||||
<RankCard title="員工 (Top 5)" icon={Users} data={stats.by_employee?.slice(0, 5) || []} field="count" />
|
||||
<RankCard title="部門 (Top 5)" icon={FileText} data={stats.by_department?.slice(0, 5) || []} field="count" />
|
||||
<RankCard title="負責人 (Top 5)" icon={CheckCircle2} data={stats.by_responsible?.slice(0, 5) || []} field="count" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function StatCard({ icon: Icon, color, label, value, overrideColor, overrideBg }) {
|
||||
return (
|
||||
<div
|
||||
className="card p-4"
|
||||
style={overrideBg ? { backgroundColor: overrideBg } : undefined}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-xs text-slate-500 mb-1">{label}</p>
|
||||
<p className="text-2xl font-bold" style={overrideColor ? { color: overrideColor } : undefined}>{value}</p>
|
||||
</div>
|
||||
{Icon && (
|
||||
<div className={`p-2 rounded-lg ${color}`}>
|
||||
<Icon size={20} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RankCard({ title, icon: Icon, data, field }) {
|
||||
return (
|
||||
<div className="card p-4">
|
||||
<h3 className="text-sm font-semibold text-slate-700 mb-3 flex items-center gap-2">
|
||||
<Icon size={16} /> {title}
|
||||
</h3>
|
||||
<div className="space-y-1">
|
||||
{data.length === 0 ? (
|
||||
<p className="text-sm text-slate-400 text-center py-4">暫無數據</p>
|
||||
) : data.map((s, i) => (
|
||||
<div key={s.name} className="py-1.5 border-b border-slate-100 last:border-0">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`w-5 h-5 rounded-full flex items-center justify-center text-xs font-bold ${i === 0 ? 'bg-yellow-100 text-yellow-700' : i === 1 ? 'bg-slate-100 text-slate-500' : i === 2 ? 'bg-orange-50 text-orange-400' : 'bg-slate-50 text-slate-400'}`}>{i + 1}</span>
|
||||
<span className="text-sm text-slate-700 truncate max-w-[160px]" title={s.name}>{s.name}</span>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<span className="text-sm font-bold text-slate-700">{s[field]}</span>
|
||||
<span className="text-xs text-slate-400 ml-2">avg {s.avg_severity || 0}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useParams, useNavigate, Link } from 'react-router-dom'
|
||||
import api from '../../api'
|
||||
import toast from 'react-hot-toast'
|
||||
import { ArrowLeft, FileText, AlertTriangle } from 'lucide-react'
|
||||
|
||||
const SEVERITY_COLORS = {
|
||||
'1': { bg: '#D1FAE5', fg: '#065F46', label: '低 Low' },
|
||||
'2': { bg: '#DBEAFE', fg: '#1E40AF', label: '中 Medium' },
|
||||
'3': { bg: '#FEF3C7', fg: '#92400E', label: '高 High' },
|
||||
'4': { bg: '#FED7AA', fg: '#9A3412', label: '嚴重 Severe' },
|
||||
'5': { bg: '#FEE2E2', fg: '#7F1D1D', label: '極嚴重 Critical' },
|
||||
}
|
||||
|
||||
const FIELDS = [
|
||||
{ key: 'date', label: '日期 Date' },
|
||||
{ key: 'time', label: '時間 Time' },
|
||||
{ key: 'severity', label: '嚴重程度 Severity', badge: true },
|
||||
{ key: 'location', label: '地點 Location' },
|
||||
{ key: 'employee_name', label: '員工/報告人 Employee' },
|
||||
{ key: 'department', label: '部門 Department' },
|
||||
{ key: 'description', label: '事件描述 Description' },
|
||||
{ key: 'medical_report', label: '醫療報告 Medical Report' },
|
||||
{ key: 'action_taken', label: '處理情況 Action Taken' },
|
||||
{ key: 'responsible_person', label: '負責人 Responsible Person' },
|
||||
{ key: 'created_at', label: '建立時間 Created At' },
|
||||
]
|
||||
|
||||
export default function AccidentDetail() {
|
||||
const { id } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const [record, setRecord] = useState(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(null)
|
||||
|
||||
useEffect(() => {
|
||||
const numericId = parseInt(id, 10)
|
||||
if (isNaN(numericId) || numericId <= 0) {
|
||||
navigate('/accident/list', { replace: true })
|
||||
return
|
||||
}
|
||||
fetchRecord(numericId)
|
||||
}, [id])
|
||||
|
||||
const fetchRecord = async (recordId) => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const { data } = await api.get(`/api/accident/${recordId}`)
|
||||
setRecord(data)
|
||||
} catch (err) {
|
||||
console.error('Error fetching record:', err)
|
||||
const detail = err.response?.data?.detail
|
||||
// FastAPI 422 returns detail as array of validation errors — stringify safely
|
||||
let msg = 'Failed to load record'
|
||||
if (typeof detail === 'string') {
|
||||
msg = detail
|
||||
} else if (Array.isArray(detail)) {
|
||||
msg = `Invalid request: ${detail.map(d => d.msg || JSON.stringify(d)).join('; ')}`
|
||||
} else if (detail && typeof detail === 'object') {
|
||||
msg = JSON.stringify(detail)
|
||||
} else if (err.response?.status === 404) {
|
||||
msg = 'Record not found'
|
||||
}
|
||||
setError(msg)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-slate-500">載入中...</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<Link
|
||||
to="/accident/list"
|
||||
className="flex items-center gap-2 text-slate-600 hover:text-slate-900"
|
||||
>
|
||||
<ArrowLeft size={20} />
|
||||
返回列表
|
||||
</Link>
|
||||
</div>
|
||||
<div className="card p-8 text-center">
|
||||
<AlertTriangle size={48} className="mx-auto text-red-400 mb-2" />
|
||||
<div className="text-red-500 mb-2">{error}</div>
|
||||
<button
|
||||
onClick={() => navigate('/accident/list')}
|
||||
className="mt-4 px-4 py-2 text-sm text-primary-600 hover:text-primary-700"
|
||||
>
|
||||
返回列表
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const sev = String(record.severity || '')
|
||||
const sevColor = SEVERITY_COLORS[sev] || { bg: '#F3F4F6', fg: '#374151', label: sev || '-' }
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 mb-4 sm:mb-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Link
|
||||
to="/accident/list"
|
||||
className="flex items-center gap-2 text-slate-600 hover:text-slate-900"
|
||||
>
|
||||
<ArrowLeft size={20} />
|
||||
返回
|
||||
</Link>
|
||||
<h1 className="text-xl sm:text-2xl font-bold text-slate-900">
|
||||
意外記錄 #{id}
|
||||
</h1>
|
||||
</div>
|
||||
<span
|
||||
className="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold"
|
||||
style={{ backgroundColor: sevColor.bg, color: sevColor.fg }}
|
||||
>
|
||||
Severity {sev} · {sevColor.label}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="card overflow-hidden">
|
||||
<div className="p-4 border-b border-slate-200 bg-slate-50">
|
||||
<div className="flex items-center gap-3">
|
||||
<FileText size={24} className="text-slate-400" />
|
||||
<div>
|
||||
<div className="font-medium text-slate-900">記錄詳情</div>
|
||||
<div className="text-sm text-slate-500">AARS 意外事故記錄</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="divide-y divide-slate-100">
|
||||
{FIELDS.map(({ key, label, badge }) => {
|
||||
const val = record[key]
|
||||
const display = val !== null && val !== undefined && val !== '' ? String(val) : '-'
|
||||
return (
|
||||
<div key={key} className="grid grid-cols-1 sm:grid-cols-12">
|
||||
<div className="sm:col-span-3 px-4 py-3 text-sm font-medium text-slate-500 bg-slate-50">
|
||||
{label}
|
||||
</div>
|
||||
<div className="sm:col-span-9 px-4 py-3 text-sm text-slate-900 break-words">
|
||||
{badge && sev !== '' ? (
|
||||
<span
|
||||
className="inline-flex items-center px-2 py-0.5 rounded text-xs font-bold"
|
||||
style={{ backgroundColor: sevColor.bg, color: sevColor.fg }}
|
||||
>
|
||||
{sev} · {sevColor.label}
|
||||
</span>
|
||||
) : (
|
||||
display
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
import { useState, useEffect, useMemo } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Link } from 'react-router-dom'
|
||||
import api from '../../api'
|
||||
import toast from 'react-hot-toast'
|
||||
import { Search, Eye, ChevronUp, ChevronDown, Filter, X, Settings2, RotateCcw } from 'lucide-react'
|
||||
|
||||
export default function AccidentList() {
|
||||
const navigate = useNavigate()
|
||||
const [records, setRecords] = useState([])
|
||||
const [excelHeaders, setExcelHeaders] = useState({}) // sql_col -> Excel chinese header
|
||||
const [columnOrder, setColumnOrder] = useState([]) // ordered SQL cols (Excel order)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [search, setSearch] = useState('')
|
||||
const [sortKey, setSortKey] = useState('date')
|
||||
const [sortDir, setSortDir] = useState('desc')
|
||||
const [filterKey, setFilterKey] = useState('')
|
||||
const [filterValue, setFilterValue] = useState('')
|
||||
|
||||
// Column visibility — localStorage persisted
|
||||
const STORAGE_KEY = 'aars.accident.visibleColumns.v1'
|
||||
const [visibleCols, setVisibleCols] = useState(() => {
|
||||
try {
|
||||
const s = localStorage.getItem(STORAGE_KEY)
|
||||
if (s) return JSON.parse(s)
|
||||
} catch {}
|
||||
return null // null = show all
|
||||
})
|
||||
const [showColumnSettings, setShowColumnSettings] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
fetchRecords()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (visibleCols !== null) {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(visibleCols))
|
||||
}
|
||||
}, [visibleCols])
|
||||
|
||||
const fetchRecords = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const { data } = await api.get('/api/accident/records?per_page=1000')
|
||||
setRecords(data.records || [])
|
||||
const eh = data.excel_headers || {}
|
||||
const co = data.column_order || []
|
||||
setExcelHeaders(eh)
|
||||
setColumnOrder(co)
|
||||
// Default sort
|
||||
if (data.records && data.records.length > 0 && !sortKey) {
|
||||
setSortKey('date')
|
||||
setSortDir('desc')
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error('Failed to load records')
|
||||
console.error(err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// The set of columns to display: filtered by visibleCols (if not null)
|
||||
const displayedCols = useMemo(() => {
|
||||
let cols = columnOrder.filter(c => c !== 'id')
|
||||
if (visibleCols !== null) {
|
||||
cols = cols.filter(c => visibleCols[c])
|
||||
}
|
||||
return cols
|
||||
}, [columnOrder, visibleCols])
|
||||
|
||||
// Helper: get display name for a SQL column (uses Excel header, trims trailing spaces)
|
||||
const displayName = (col) => {
|
||||
const h = excelHeaders[col]
|
||||
return (h ? String(h).trim() : col) || col
|
||||
}
|
||||
|
||||
// Filtered and sorted data
|
||||
const processedData = useMemo(() => {
|
||||
let result = [...records]
|
||||
if (filterKey && filterValue) {
|
||||
result = result.filter(r => {
|
||||
const val = String(r[filterKey] || '').toLowerCase()
|
||||
return val.includes(filterValue.toLowerCase())
|
||||
})
|
||||
}
|
||||
if (search) {
|
||||
const searchLower = search.toLowerCase()
|
||||
result = result.filter(r =>
|
||||
Object.values(r).some(v =>
|
||||
v && String(v).toLowerCase().includes(searchLower)
|
||||
)
|
||||
)
|
||||
}
|
||||
if (sortKey) {
|
||||
result.sort((a, b) => {
|
||||
const aVal = a[sortKey] || ''
|
||||
const bVal = b[sortKey] || ''
|
||||
const aNum = Number(aVal)
|
||||
const bNum = Number(bVal)
|
||||
let cmp = 0
|
||||
if (!isNaN(aNum) && !isNaN(bNum) && aVal !== '' && bVal !== '') {
|
||||
cmp = aNum - bNum
|
||||
} else {
|
||||
cmp = String(aVal).localeCompare(String(bVal))
|
||||
}
|
||||
return sortDir === 'asc' ? cmp : -cmp
|
||||
})
|
||||
}
|
||||
return result
|
||||
}, [records, search, sortKey, sortDir, filterKey, filterValue])
|
||||
|
||||
const handleSort = (key) => {
|
||||
if (sortKey === key) {
|
||||
setSortDir(sortDir === 'asc' ? 'desc' : 'asc')
|
||||
} else {
|
||||
setSortKey(key)
|
||||
setSortDir('asc')
|
||||
}
|
||||
}
|
||||
|
||||
const handleFilter = (key) => {
|
||||
setFilterKey(key)
|
||||
setFilterValue('')
|
||||
}
|
||||
|
||||
const clearFilter = () => {
|
||||
setFilterKey('')
|
||||
setFilterValue('')
|
||||
}
|
||||
|
||||
const getSortIcon = (key) => {
|
||||
if (sortKey !== key) return null
|
||||
return sortDir === 'asc' ? <ChevronUp size={14} /> : <ChevronDown size={14} />
|
||||
}
|
||||
|
||||
const toggleColumn = (col) => {
|
||||
const next = visibleCols ? { ...visibleCols } : {}
|
||||
// Initialize all columns to true first
|
||||
columnOrder.forEach(c => { if (next[c] === undefined) next[c] = true })
|
||||
next[col] = !next[col]
|
||||
setVisibleCols(next)
|
||||
}
|
||||
|
||||
const resetColumns = () => {
|
||||
setVisibleCols(null)
|
||||
localStorage.removeItem(STORAGE_KEY)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-lg sm:text-xl font-bold text-slate-900">意外記錄 Accident</h1>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setShowColumnSettings(!showColumnSettings)}
|
||||
className={`flex items-center gap-2 px-3 py-2 text-sm rounded-md border ${
|
||||
showColumnSettings
|
||||
? 'bg-slate-100 border-slate-400 text-slate-800'
|
||||
: 'border-slate-300 text-slate-600 hover:bg-slate-50'
|
||||
}`}
|
||||
>
|
||||
<Settings2 size={16} />
|
||||
欄位 ({displayedCols.length}/{columnOrder.filter(c => c !== 'id').length})
|
||||
</button>
|
||||
<Link
|
||||
to="/upload"
|
||||
className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white text-sm rounded-md hover:bg-red-700"
|
||||
>
|
||||
上傳 Excel
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Column Settings Panel */}
|
||||
{showColumnSettings && (
|
||||
<div className="card p-4 border-l-4 border-primary-500">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="text-sm font-semibold text-slate-700">
|
||||
選擇顯示嘅欄位 (來源: Excel)
|
||||
</div>
|
||||
<button
|
||||
onClick={resetColumns}
|
||||
className="flex items-center gap-1 text-xs text-slate-500 hover:text-slate-800"
|
||||
>
|
||||
<RotateCcw size={12} />
|
||||
重設全部顯示
|
||||
</button>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-2">
|
||||
{columnOrder.filter(c => c !== 'id').map(col => {
|
||||
const isVisible = visibleCols === null || (visibleCols[col] !== false)
|
||||
return (
|
||||
<label key={col} className="flex items-center gap-2 text-xs cursor-pointer hover:bg-slate-50 px-2 py-1 rounded">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isVisible}
|
||||
onChange={() => toggleColumn(col)}
|
||||
className="rounded"
|
||||
/>
|
||||
<span className="text-slate-700">{displayName(col)}</span>
|
||||
<span className="text-slate-400 text-[10px]">({col})</span>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Filters */}
|
||||
<div className="card p-3">
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<div className="relative flex-1 min-w-[200px]">
|
||||
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
|
||||
<input
|
||||
type="text"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="搜尋所有欄位..."
|
||||
className="w-full pl-9 pr-4 py-2 text-sm border border-slate-300 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Filter size={16} className="text-slate-400" />
|
||||
<select
|
||||
value={filterKey}
|
||||
onChange={(e) => handleFilter(e.target.value)}
|
||||
className="text-sm border border-slate-300 rounded-md px-2 py-2"
|
||||
>
|
||||
<option value="">篩選欄位</option>
|
||||
{displayedCols.map(h => (
|
||||
<option key={h} value={h}>{displayName(h)}</option>
|
||||
))}
|
||||
</select>
|
||||
{filterKey && (
|
||||
<>
|
||||
<input
|
||||
type="text"
|
||||
value={filterValue}
|
||||
onChange={(e) => setFilterValue(e.target.value)}
|
||||
placeholder="輸入篩選值..."
|
||||
className="text-sm border border-slate-300 rounded-md px-2 py-2 w-32"
|
||||
/>
|
||||
<button onClick={clearFilter} className="p-1 text-slate-400 hover:text-slate-600">
|
||||
<X size={16} />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-sm text-slate-500 py-2">
|
||||
{processedData.length} 筆記錄
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<div className="card overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-slate-100 border-b border-slate-200">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left text-xs font-semibold text-slate-600 w-12">#</th>
|
||||
{displayedCols.map(h => (
|
||||
<th
|
||||
key={h}
|
||||
className="px-3 py-2 text-left text-xs font-semibold text-slate-600 cursor-pointer hover:bg-slate-200 whitespace-nowrap"
|
||||
onClick={() => handleSort(h)}
|
||||
title={excelHeaders[h] || h}
|
||||
>
|
||||
<div className="flex items-center gap-1">
|
||||
{displayName(h)}
|
||||
{getSortIcon(h)}
|
||||
</div>
|
||||
</th>
|
||||
))}
|
||||
<th className="px-3 py-2 text-right text-xs font-semibold text-slate-600 w-16">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td colSpan={displayedCols.length + 2} className="px-3 py-6 text-center text-slate-400">
|
||||
載入中...
|
||||
</td>
|
||||
</tr>
|
||||
) : processedData.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={displayedCols.length + 2} className="px-3 py-6 text-center text-slate-400">
|
||||
沒有記錄
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
processedData.map((record) => (
|
||||
<tr
|
||||
key={record.id}
|
||||
className="hover:bg-slate-50 cursor-pointer"
|
||||
onClick={() => navigate(`/accident/${record.id}`)}
|
||||
>
|
||||
<td className="px-3 py-2 text-xs text-slate-400">{record.id}</td>
|
||||
{displayedCols.map(h => (
|
||||
<td key={h} className="px-3 py-2 text-slate-700 max-w-xs truncate" title={record[h]}>
|
||||
{record[h] !== null && record[h] !== undefined && record[h] !== '' ? String(record[h]) : '-'}
|
||||
</td>
|
||||
))}
|
||||
<td className="px-3 py-2 text-right" onClick={(e) => e.stopPropagation()}>
|
||||
<Link
|
||||
to={`/accident/${record.id}`}
|
||||
className="p-1 text-slate-400 hover:text-primary-600 inline-block"
|
||||
>
|
||||
<Eye size={16} />
|
||||
</Link>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user