feat: add reports center, admin drill-down, disease filter + bug fixes + perf optimization
Frontend features:
- 报表中心 (ReportsCenter): list/detail views, diagnosis breakdown chart, CSV export
- 多级行政下钻 (AdminBreadcrumb): 湖北省→武汉市→区→街道 hierarchical drill-down
- 按病种筛选 (DiseaseFilter): multi-select diagnosis filter on monitoring + reports pages
Backend:
- Add /forecast/{days} endpoint, diagnosis filter params on cases endpoints
- Add /streets aggregation endpoint, enrich reports with real case data
- Extract shared case_loader module
Bug fixes (14):
- Fix missing /risk/forecast route (404), historyApi pointing to non-existent router
- Fix min_risk filter silently ignored in insights/hotspots
- Fix type mismatches: CaseTrendResponse, CaseStatsResponse shapes
- Fix silent .catch(() => {}) swallowing errors, fetchAlerts not clearing stale state
- Fix lru_cache caching exceptions, generateReport used cachedGet for write op
- Fix missing useEffect deps in Insights, DistrictComparison, ReportsCenter
Performance (9):
- Zustand selectors across 9 components (eliminate re-render cascades)
- Fix districtCases.sort() mutating store state, inline IIFE → memo'd component
- CaseLocationMap: React.memo, race protection, correct deps
- AlertCard: stable callbacks, TimelinePlayer: useMemo, TopNav: clock isolation
- SideNav: modules array to module scope, DiseaseFilter: memoized filter
This commit is contained in:
@@ -29,7 +29,12 @@ const HORIZON_LABELS: Record<number, string> = {
|
||||
};
|
||||
|
||||
export function AlertsDashboard() {
|
||||
const { alerts, isLoading, error, clearError, fetchRiskMap, fetchAlerts } = useRiskStore();
|
||||
const alerts = useRiskStore((s) => s.alerts);
|
||||
const isLoading = useRiskStore((s) => s.isLoading);
|
||||
const error = useRiskStore((s) => s.error);
|
||||
const clearError = useRiskStore((s) => s.clearError);
|
||||
const fetchRiskMap = useRiskStore((s) => s.fetchRiskMap);
|
||||
const fetchAlerts = useRiskStore((s) => s.fetchAlerts);
|
||||
const [selectedHorizon, setSelectedHorizon] = useState<number | 'all'>('all');
|
||||
const [selectedPriority, setSelectedPriority] = useState<'all' | 'P1' | 'P2'>('all');
|
||||
const [sortBy, setSortBy] = useState<'risk' | 'time'>('risk');
|
||||
@@ -474,7 +479,8 @@ export function AlertsDashboard() {
|
||||
key={alert.alert_id}
|
||||
alert={alert}
|
||||
isSelected={selectedAlert === alert.alert_id}
|
||||
onClick={() => handleAlertCardClick(alert.alert_id)}
|
||||
alertId={alert.alert_id}
|
||||
onCardClick={handleAlertCardClick}
|
||||
/>
|
||||
))}
|
||||
{filteredAlerts.length > 50 && (
|
||||
@@ -579,19 +585,24 @@ export function AlertsDashboard() {
|
||||
interface AlertCardProps {
|
||||
alert: ExtendedAlert;
|
||||
isSelected?: boolean;
|
||||
onClick?: () => void;
|
||||
alertId: string;
|
||||
onCardClick: (id: string) => void;
|
||||
}
|
||||
|
||||
const AlertCard = React.memo(function AlertCard({ alert, isSelected, onClick }: AlertCardProps) {
|
||||
const AlertCard = React.memo(function AlertCard({ alert, isSelected, alertId, onCardClick }: AlertCardProps) {
|
||||
const isP1 = alert.priority === 'P1';
|
||||
const riskPercent = Math.round(alert.risk_value * 100);
|
||||
|
||||
const handleClick = useCallback(() => {
|
||||
onCardClick(alertId);
|
||||
}, [alertId, onCardClick]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`card overflow-hidden transition-colors cursor-pointer ${
|
||||
isSelected ? 'border-primary ring-1 ring-primary' : 'hover:border-primary'
|
||||
}`}
|
||||
onClick={onClick}
|
||||
onClick={handleClick}
|
||||
>
|
||||
<div className={`px-4 py-3 border-b ${isP1 ? 'bg-danger/5 border-danger/20' : 'bg-warning/5 border-warning/20'}`}>
|
||||
<div className="flex items-center justify-between">
|
||||
|
||||
@@ -22,12 +22,16 @@ const RISK_COLORS: Record<string, string> = {
|
||||
};
|
||||
|
||||
export function DistrictComparison() {
|
||||
const { districtData, isLoading, error, clearError, fetchDistricts } = useAnalysisStore();
|
||||
const districtData = useAnalysisStore((s) => s.districtData);
|
||||
const isLoading = useAnalysisStore((s) => s.isLoading);
|
||||
const error = useAnalysisStore((s) => s.error);
|
||||
const clearError = useAnalysisStore((s) => s.clearError);
|
||||
const fetchDistricts = useAnalysisStore((s) => s.fetchDistricts);
|
||||
const [metric, setMetric] = useState<'avg_aqi' | 'avg_risk' | 'high_risk_count'>('avg_aqi');
|
||||
|
||||
useEffect(() => {
|
||||
fetchDistricts();
|
||||
}, []);
|
||||
}, [fetchDistricts]);
|
||||
|
||||
const metricConfig = {
|
||||
avg_aqi: { label: '平均AQI', color: '#2563EB', unit: '' },
|
||||
|
||||
@@ -45,11 +45,15 @@ const TYPE_CONFIG = {
|
||||
};
|
||||
|
||||
export function Insights() {
|
||||
const { insights, isLoading, error, clearError, fetchInsights } = useAnalysisStore();
|
||||
const insights = useAnalysisStore((s) => s.insights);
|
||||
const isLoading = useAnalysisStore((s) => s.isLoading);
|
||||
const error = useAnalysisStore((s) => s.error);
|
||||
const clearError = useAnalysisStore((s) => s.clearError);
|
||||
const fetchInsights = useAnalysisStore((s) => s.fetchInsights);
|
||||
|
||||
useEffect(() => {
|
||||
fetchInsights();
|
||||
}, []);
|
||||
}, [fetchInsights]);
|
||||
|
||||
const stats = insights
|
||||
? [
|
||||
|
||||
@@ -1,28 +1,25 @@
|
||||
import { useEffect, useState, useMemo, useRef, useCallback } from 'react';
|
||||
import { useEffect, useState, useMemo, useRef, useCallback, memo } from 'react';
|
||||
import { Calendar, Activity, TrendingUp, TrendingDown, Stethoscope, Building2 } from 'lucide-react';
|
||||
import { useTimelineStore, useMonitoringStore } from '@/stores';
|
||||
import { gridApi } from '@/services/api';
|
||||
import { useDiseaseStore } from '@/stores/diseaseStore';
|
||||
import { useDrilldownStore } from '@/stores/drilldownStore';
|
||||
import { gridApi, caseApi } from '@/services/api';
|
||||
import { ErrorBanner } from '@/components/ErrorBanner';
|
||||
import { TimelinePlayer } from '@/components/TimelinePlayer';
|
||||
import { StatisticalCharts } from '@/components/StatisticalCharts';
|
||||
import { CaseLocationMap } from '@/components/CaseLocationMap';
|
||||
import { DiseaseFilter } from '@/components/DiseaseFilter';
|
||||
import { AdminBreadcrumb } from '@/components/AdminBreadcrumb';
|
||||
|
||||
interface MonitoringDashboardProps {
|
||||
defaultStartDate?: string;
|
||||
defaultEndDate?: string;
|
||||
}
|
||||
|
||||
const WUHAN_DISTRICTS = [
|
||||
'江岸区', '江汉区', '硚口区', '汉阳区', '武昌区',
|
||||
'青山区', '洪山区', '东西湖区', '汉南区', '蔡甸区',
|
||||
'江夏区', '黄陂区', '新洲区',
|
||||
];
|
||||
|
||||
export function MonitoringDashboard({
|
||||
defaultStartDate = '2022-12-01',
|
||||
defaultEndDate = '2024-12-30',
|
||||
}: MonitoringDashboardProps) {
|
||||
const [selectedDistrict, setSelectedDistrict] = useState<string | null>(null);
|
||||
const [chartData, setChartData] = useState<Array<{ date: string; cases: number; aqi?: number }>>([]);
|
||||
|
||||
const {
|
||||
@@ -35,13 +32,14 @@ export function MonitoringDashboard({
|
||||
setDateRange,
|
||||
} = useTimelineStore();
|
||||
|
||||
const {
|
||||
districtCases,
|
||||
error,
|
||||
clearError,
|
||||
fetchDistrictCases,
|
||||
isLoading,
|
||||
} = useMonitoringStore();
|
||||
const districtCases = useMonitoringStore((s) => s.districtCases);
|
||||
const error = useMonitoringStore((s) => s.error);
|
||||
const clearError = useMonitoringStore((s) => s.clearError);
|
||||
const fetchDistrictCases = useMonitoringStore((s) => s.fetchDistrictCases);
|
||||
const isLoading = useMonitoringStore((s) => s.isLoading);
|
||||
|
||||
const { selectedDistrict, selectedStreet } = useDrilldownStore();
|
||||
const { selectedDiagnoses } = useDiseaseStore();
|
||||
|
||||
useEffect(() => {
|
||||
setDateRange(defaultStartDate, defaultEndDate);
|
||||
@@ -54,25 +52,42 @@ export function MonitoringDashboard({
|
||||
const end = new Date(defaultEndDate);
|
||||
const start = new Date(defaultEndDate);
|
||||
start.setDate(start.getDate() - 90);
|
||||
gridApi.getHistoricalAggregated(
|
||||
start.toISOString().split('T')[0],
|
||||
end.toISOString().split('T')[0],
|
||||
'daily',
|
||||
district,
|
||||
).then((data) => {
|
||||
const rows = data.aggregations || [];
|
||||
const dailyCases: Record<string, number> = {};
|
||||
rows.forEach((item: { date: string; total_cases: number }) => {
|
||||
dailyCases[item.date] = (dailyCases[item.date] || 0) + item.total_cases;
|
||||
});
|
||||
setChartData(
|
||||
Object.entries(dailyCases)
|
||||
.map(([date, cases]) => ({ date, cases }))
|
||||
.sort((a, b) => a.date.localeCompare(b.date))
|
||||
);
|
||||
}).catch(() => {});
|
||||
fetchDistrictCases();
|
||||
}, [defaultEndDate, fetchDistrictCases]);
|
||||
const startStr = start.toISOString().split('T')[0];
|
||||
const endStr = end.toISOString().split('T')[0];
|
||||
|
||||
if (selectedDiagnoses.length > 0 && selectedDiagnoses.length <= 3) {
|
||||
// Use caseApi for diagnosis-filtered data
|
||||
caseApi.getTrend({
|
||||
start_date: startStr,
|
||||
end_date: endStr,
|
||||
group_by: 'day',
|
||||
diagnosis: selectedDiagnoses.join(','),
|
||||
}).then((data) => {
|
||||
const trend = data.trend || [];
|
||||
setChartData(
|
||||
trend.map((t: { date: string; total: number }) => ({ date: t.date, cases: t.total }))
|
||||
);
|
||||
}).catch((e) => { console.error('Failed to load chart data:', e); });
|
||||
} else {
|
||||
// Use gridApi for unfiltered data (or too many diagnoses selected)
|
||||
gridApi.getHistoricalAggregated(startStr, endStr, 'daily', district)
|
||||
.then((data) => {
|
||||
const rows = data.aggregations || [];
|
||||
const dailyCases: Record<string, number> = {};
|
||||
rows.forEach((item: { date: string; total_cases: number }) => {
|
||||
dailyCases[item.date] = (dailyCases[item.date] || 0) + item.total_cases;
|
||||
});
|
||||
setChartData(
|
||||
Object.entries(dailyCases)
|
||||
.map(([date, cases]) => ({ date, cases }))
|
||||
.sort((a, b) => a.date.localeCompare(b.date))
|
||||
);
|
||||
}).catch((e) => { console.error('Failed to load chart data:', e); });
|
||||
}
|
||||
|
||||
// Fetch districtCases with diagnosis filter
|
||||
fetchDistrictCases(selectedDiagnoses.length > 0 ? selectedDiagnoses.join(',') : undefined);
|
||||
}, [defaultEndDate, fetchDistrictCases, selectedDiagnoses]);
|
||||
|
||||
useEffect(() => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
@@ -189,19 +204,16 @@ export function MonitoringDashboard({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* District filter */}
|
||||
{/* Disease filter */}
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-gray-500">区域筛选:</span>
|
||||
<select
|
||||
value={selectedDistrict || ''}
|
||||
onChange={(e) => setSelectedDistrict(e.target.value || null)}
|
||||
className="px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
<option value="">全市</option>
|
||||
{WUHAN_DISTRICTS.map((d) => (
|
||||
<option key={d} value={d}>{d}</option>
|
||||
))}
|
||||
</select>
|
||||
<DiseaseFilter onFilterChange={() => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => {
|
||||
loadChartData(selectedDistrict || undefined);
|
||||
}, 300);
|
||||
}} />
|
||||
{/* District filter - AdminBreadcrumb for drill-down */}
|
||||
<AdminBreadcrumb />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -217,7 +229,7 @@ export function MonitoringDashboard({
|
||||
{/* Case Location Map */}
|
||||
<div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-4">病例分布地图</h3>
|
||||
<CaseLocationMap height="400px" />
|
||||
<CaseLocationMap height="400px" district={selectedDistrict} street={selectedStreet} />
|
||||
</div>
|
||||
|
||||
{/* Statistical Charts */}
|
||||
@@ -232,44 +244,7 @@ export function MonitoringDashboard({
|
||||
<div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
|
||||
<h3 className="text-lg font-semibold text-gray-900 mb-4">区县病例分布</h3>
|
||||
<div className="space-y-2">
|
||||
{(() => {
|
||||
const maxTotal = Math.max(...districtCases.map(d => d.total), 1);
|
||||
return districtCases
|
||||
.sort((a, b) => b.total - a.total)
|
||||
.map((d) => {
|
||||
const outPct = d.total > 0 ? (d.outpatient / d.total) * 100 : 0;
|
||||
const inPct = d.total > 0 ? (d.inpatient / d.total) * 100 : 0;
|
||||
const barWidth = (d.total / maxTotal) * 100;
|
||||
return (
|
||||
<div
|
||||
key={d.district}
|
||||
className={`flex items-center gap-3 p-2 rounded cursor-pointer transition-colors ${
|
||||
selectedDistrict === d.district ? 'bg-blue-50' : 'hover:bg-gray-50'
|
||||
}`}
|
||||
onClick={() => setSelectedDistrict(
|
||||
selectedDistrict === d.district ? null : d.district
|
||||
)}
|
||||
>
|
||||
<div className="w-16 text-sm text-gray-700 text-right shrink-0">{d.district}</div>
|
||||
<div className="flex-1 h-6 bg-gray-100 rounded overflow-hidden flex">
|
||||
<div
|
||||
className="bg-orange-400 h-full transition-all"
|
||||
style={{ width: `${barWidth * outPct / 100}%` }}
|
||||
title={`门诊: ${d.outpatient.toLocaleString()}`}
|
||||
/>
|
||||
<div
|
||||
className="bg-red-400 h-full transition-all"
|
||||
style={{ width: `${barWidth * inPct / 100}%` }}
|
||||
title={`住院: ${d.inpatient.toLocaleString()}`}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-20 text-right text-sm font-medium text-gray-900 shrink-0">
|
||||
{d.total.toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
})()}
|
||||
<DistrictBreakdown districtCases={districtCases} selectedDistrict={selectedDistrict} />
|
||||
</div>
|
||||
<div className="flex items-center gap-4 mt-3 pt-2 border-t border-gray-100">
|
||||
<div className="flex items-center gap-1.5 text-xs text-gray-500">
|
||||
@@ -297,4 +272,58 @@ export function MonitoringDashboard({
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
interface DistrictBreakdownProps {
|
||||
districtCases: Array<{ district: string; total: number; outpatient: number; inpatient: number }>;
|
||||
selectedDistrict: string | null;
|
||||
}
|
||||
|
||||
const DistrictBreakdown = memo(function DistrictBreakdown({ districtCases, selectedDistrict }: DistrictBreakdownProps) {
|
||||
const sortedCases = useMemo(() => [...districtCases].sort((a, b) => b.total - a.total), [districtCases]);
|
||||
const maxTotal = useMemo(() => sortedCases.length > 0 ? sortedCases[0].total : 1, [sortedCases]);
|
||||
|
||||
const handleDistrictClick = useCallback((district: string) => {
|
||||
if (selectedDistrict === district) {
|
||||
useDrilldownStore.getState().drillUp();
|
||||
} else {
|
||||
useDrilldownStore.getState().drillDown('district', district);
|
||||
}
|
||||
}, [selectedDistrict]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{sortedCases.map((d) => {
|
||||
const outPct = d.total > 0 ? (d.outpatient / d.total) * 100 : 0;
|
||||
const inPct = d.total > 0 ? (d.inpatient / d.total) * 100 : 0;
|
||||
const barWidth = (d.total / maxTotal) * 100;
|
||||
return (
|
||||
<div
|
||||
key={d.district}
|
||||
className={`flex items-center gap-3 p-2 rounded cursor-pointer transition-colors ${
|
||||
selectedDistrict === d.district ? 'bg-blue-50' : 'hover:bg-gray-50'
|
||||
}`}
|
||||
onClick={() => handleDistrictClick(d.district)}
|
||||
>
|
||||
<div className="w-16 text-sm text-gray-700 text-right shrink-0">{d.district}</div>
|
||||
<div className="flex-1 h-6 bg-gray-100 rounded overflow-hidden flex">
|
||||
<div
|
||||
className="bg-orange-400 h-full transition-all"
|
||||
style={{ width: `${barWidth * outPct / 100}%` }}
|
||||
title={`门诊: ${d.outpatient.toLocaleString()}`}
|
||||
/>
|
||||
<div
|
||||
className="bg-red-400 h-full transition-all"
|
||||
style={{ width: `${barWidth * inPct / 100}%` }}
|
||||
title={`住院: ${d.inpatient.toLocaleString()}`}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-20 text-right text-sm font-medium text-gray-900 shrink-0">
|
||||
{d.total.toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
});
|
||||
349
frontend/src/pages/ReportsCenter.tsx
Normal file
349
frontend/src/pages/ReportsCenter.tsx
Normal file
@@ -0,0 +1,349 @@
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
|
||||
import { FileText, Download, Activity, TrendingUp, TrendingDown, AlertTriangle, ChevronLeft, RefreshCw } from 'lucide-react';
|
||||
import { useReportsStore } from '@/stores/reportsStore';
|
||||
import { useDiseaseStore } from '@/stores/diseaseStore';
|
||||
import { ErrorBanner } from '@/components/ErrorBanner';
|
||||
import { DiseaseFilter } from '@/components/DiseaseFilter';
|
||||
import type { ReportResponse } from '@/types';
|
||||
|
||||
const TYPE_LABELS: Record<string, string> = {
|
||||
daily: '日报', weekly: '周报', monthly: '月报', custom: '自定义',
|
||||
};
|
||||
|
||||
const TYPE_COLORS: Record<string, string> = {
|
||||
daily: 'bg-blue-100 text-blue-700', weekly: 'bg-purple-100 text-purple-700',
|
||||
monthly: 'bg-green-100 text-green-700', custom: 'bg-gray-100 text-gray-700',
|
||||
};
|
||||
|
||||
const PRIORITY_COLORS: Record<string, string> = {
|
||||
high: 'bg-red-100 text-red-700 border-red-300',
|
||||
medium: 'bg-yellow-100 text-yellow-700 border-yellow-300',
|
||||
low: 'bg-gray-100 text-gray-600 border-gray-300',
|
||||
};
|
||||
|
||||
function downloadCSV(report: ReportResponse) {
|
||||
const BOM = '';
|
||||
const headers = ['报告ID', '标题', '类型', '报告日期', '周期开始', '周期结束', '总病例数', '平均风险',
|
||||
'峰值风险日期', '峰值风险值', '高风险区域数', '趋势方向', '诊断名称', '门诊病例', '住院病例', '诊断总病例'];
|
||||
|
||||
const { metadata, summary } = report;
|
||||
const breakdowns = report.diagnosis_breakdown || [];
|
||||
const typeLabel = TYPE_LABELS[metadata.type] || metadata.type;
|
||||
|
||||
let csv = BOM + headers.join(',') + '\n';
|
||||
|
||||
if (breakdowns.length === 0) {
|
||||
csv += [
|
||||
metadata.report_id, `"${metadata.title}"`, typeLabel, metadata.generated_at,
|
||||
metadata.period_start, metadata.period_end, summary.total_cases, summary.avg_risk,
|
||||
summary.peak_risk_date, summary.peak_risk_value, summary.high_risk_areas, summary.trend_direction,
|
||||
'', '', '', ''
|
||||
].join(',');
|
||||
} else {
|
||||
breakdowns.forEach((d) => {
|
||||
csv += [
|
||||
metadata.report_id, `"${metadata.title}"`, typeLabel, metadata.generated_at,
|
||||
metadata.period_start, metadata.period_end, summary.total_cases, summary.avg_risk,
|
||||
summary.peak_risk_date, summary.peak_risk_value, summary.high_risk_areas, summary.trend_direction,
|
||||
`"${d.diagnosis}"`, d.outpatient, d.inpatient, d.total
|
||||
].join(',') + '\n';
|
||||
});
|
||||
}
|
||||
|
||||
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `${report.metadata.report_id}.csv`;
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
function ReportList({ onSelect }: { onSelect: (id: string) => void }) {
|
||||
const reports = useReportsStore((s) => s.reports);
|
||||
const isLoading = useReportsStore((s) => s.isLoading);
|
||||
const error = useReportsStore((s) => s.error);
|
||||
const clearError = useReportsStore((s) => s.clearError);
|
||||
const fetchReportsList = useReportsStore((s) => s.fetchReportsList);
|
||||
const [filter, setFilter] = useState<string>('all');
|
||||
|
||||
useEffect(() => { fetchReportsList(filter === 'all' ? undefined : filter); }, [filter, fetchReportsList]);
|
||||
|
||||
const filters = [
|
||||
{ key: 'all', label: '全部' },
|
||||
{ key: 'daily', label: '日报' },
|
||||
{ key: 'weekly', label: '周报' },
|
||||
{ key: 'monthly', label: '月报' },
|
||||
];
|
||||
|
||||
if (error) return <ErrorBanner error={error} onRetry={() => { clearError(); fetchReportsList(filter === 'all' ? undefined : filter); }} onDismiss={clearError} />;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
{filters.map((f) => (
|
||||
<button
|
||||
key={f.key}
|
||||
onClick={() => setFilter(f.key)}
|
||||
className={`px-3 py-1 text-[12px] rounded transition-colors ${
|
||||
filter === f.key ? 'bg-primary text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
>{f.label}</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="text-center py-8 text-sm text-gray-500">加载中...</div>
|
||||
) : reports.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<FileText className="w-12 h-12 text-gray-300 mx-auto mb-3" />
|
||||
<p className="text-gray-500 text-sm">暂无报告</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-gray-50 border-b border-gray-200">
|
||||
<tr>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase">报告ID</th>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase">标题</th>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase">类型</th>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase">报告周期</th>
|
||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase">生成时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{reports.map((r) => (
|
||||
<tr
|
||||
key={r.report_id}
|
||||
onClick={() => onSelect(r.report_id)}
|
||||
className="border-b border-gray-100 hover:bg-blue-50 cursor-pointer transition-colors"
|
||||
>
|
||||
<td className="px-4 py-3 font-mono text-xs text-gray-900">{r.report_id}</td>
|
||||
<td className="px-4 py-3 text-gray-900">{r.title}</td>
|
||||
<td className="px-4 py-3">
|
||||
<span className={`px-2 py-0.5 rounded text-[11px] font-medium ${TYPE_COLORS[r.type] || 'bg-gray-100 text-gray-600'}`}>
|
||||
{TYPE_LABELS[r.type] || r.type}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-500 text-xs">
|
||||
{r.period_start} ~ {r.period_end}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-gray-500 text-xs">{r.generated_at?.slice(0, 10)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ReportDetail({ reportId, onBack }: { reportId: string; onBack: () => void }) {
|
||||
const currentReport = useReportsStore((s) => s.currentReport);
|
||||
const isLoading = useReportsStore((s) => s.isLoading);
|
||||
const error = useReportsStore((s) => s.error);
|
||||
const clearError = useReportsStore((s) => s.clearError);
|
||||
const fetchReport = useReportsStore((s) => s.fetchReport);
|
||||
const { selectedDiagnoses } = useDiseaseStore();
|
||||
|
||||
useEffect(() => { fetchReport(reportId); }, [reportId]);
|
||||
|
||||
if (error) return <ErrorBanner error={error} onRetry={() => { clearError(); fetchReport(reportId); }} onDismiss={clearError} />;
|
||||
if (isLoading || !currentReport) return <div className="text-center py-8 text-sm text-gray-500">加载报告...</div>;
|
||||
|
||||
const { metadata, summary, sections, recommendations, diagnosis_breakdown } = currentReport;
|
||||
|
||||
const filteredBreakdown = diagnosis_breakdown?.filter(
|
||||
d => selectedDiagnoses.length === 0 || selectedDiagnoses.includes(d.diagnosis)
|
||||
) || [];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button onClick={onBack} className="flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700 mb-4">
|
||||
<ChevronLeft className="w-4 h-4" /> 返回列表
|
||||
</button>
|
||||
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-gray-900">{metadata.title}</h2>
|
||||
<div className="flex items-center gap-2 mt-1 text-xs text-gray-500">
|
||||
<span className={`px-2 py-0.5 rounded font-medium ${TYPE_COLORS[metadata.type] || ''}`}>
|
||||
{TYPE_LABELS[metadata.type] || metadata.type}
|
||||
</span>
|
||||
<span>{metadata.period_start} ~ {metadata.period_end}</span>
|
||||
<span>生成: {metadata.generated_at?.slice(0, 10)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => downloadCSV(currentReport)}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-green-600 text-white rounded hover:bg-green-700 transition-colors"
|
||||
>
|
||||
<Download className="w-3.5 h-3.5" /> 导出CSV
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Summary cards */}
|
||||
<div className="grid grid-cols-5 gap-3 mb-6">
|
||||
{[
|
||||
{ label: '总病例数', value: summary.total_cases.toLocaleString(), icon: Activity, color: 'text-blue-600', bg: 'bg-blue-50' },
|
||||
{ label: '平均风险', value: (summary.avg_risk * 100).toFixed(1) + '%', icon: AlertTriangle, color: 'text-orange-600', bg: 'bg-orange-50' },
|
||||
{ label: '峰值风险', value: (summary.peak_risk_value * 100).toFixed(1) + '%', icon: TrendingUp, color: 'text-red-600', bg: 'bg-red-50' },
|
||||
{ label: '高风险区域', value: `${summary.high_risk_areas}个`, icon: TrendingUp, color: 'text-red-600', bg: 'bg-red-50' },
|
||||
{
|
||||
label: '趋势', value: summary.trend_direction === 'improving' ? '好转' : summary.trend_direction === 'worsening' ? '恶化' : '平稳',
|
||||
icon: summary.trend_direction === 'improving' ? TrendingDown : summary.trend_direction === 'worsening' ? TrendingUp : Activity,
|
||||
color: summary.trend_direction === 'improving' ? 'text-green-600' : summary.trend_direction === 'worsening' ? 'text-red-600' : 'text-gray-600',
|
||||
bg: summary.trend_direction === 'improving' ? 'bg-green-50' : summary.trend_direction === 'worsening' ? 'bg-red-50' : 'bg-gray-50',
|
||||
},
|
||||
].map((stat) => (
|
||||
<div key={stat.label} className="bg-white rounded-lg border border-gray-200 p-3">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<div className={`w-7 h-7 rounded ${stat.bg} flex items-center justify-center`}>
|
||||
<stat.icon className={`w-3.5 h-3.5 ${stat.color}`} />
|
||||
</div>
|
||||
<span className="text-[11px] text-gray-500">{stat.label}</span>
|
||||
</div>
|
||||
<div className="text-xl font-bold text-gray-900">{stat.value}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Sections and charts in 2-column layout */}
|
||||
<div className="grid grid-cols-2 gap-4 mb-6">
|
||||
{sections.map((section, idx) => (
|
||||
<div key={idx} className="bg-white rounded-lg border border-gray-200 p-4">
|
||||
<h3 className="text-sm font-semibold text-gray-900 mb-2">{section.title}</h3>
|
||||
<p className="text-xs text-gray-600 leading-relaxed">{section.content}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Diagnosis breakdown chart */}
|
||||
{filteredBreakdown.length > 0 ? (
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-4 mb-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="text-sm font-semibold text-gray-900">诊断分类统计</h3>
|
||||
<DiseaseFilter />
|
||||
</div>
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<BarChart data={filteredBreakdown} margin={{ top: 5, right: 20, left: 10, bottom: 5 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
|
||||
<XAxis dataKey="diagnosis" tick={{ fontSize: 11, fill: '#6b7280' }} />
|
||||
<YAxis tick={{ fontSize: 11, fill: '#6b7280' }} />
|
||||
<Tooltip contentStyle={{ fontSize: 12, borderRadius: 8, border: '1px solid #e5e7eb' }} />
|
||||
<Bar dataKey="outpatient" name="门诊" stackId="a" fill="#3b82f6" radius={[0, 0, 0, 0]} />
|
||||
<Bar dataKey="inpatient" name="住院" stackId="a" fill="#ef4444" radius={[4, 4, 0, 0]} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
<div className="flex items-center gap-4 mt-2 pt-2 border-t border-gray-100">
|
||||
<div className="flex items-center gap-1.5 text-xs text-gray-500"><span className="w-3 h-3 bg-blue-500 rounded-sm" />门诊</div>
|
||||
<div className="flex items-center gap-1.5 text-xs text-gray-500"><span className="w-3 h-3 bg-red-500 rounded-sm" />住院</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-4 mb-6 text-center">
|
||||
<p className="text-sm text-gray-400">暂无诊断分类数据</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Recommendations */}
|
||||
{recommendations.length > 0 && (
|
||||
<div className="bg-white rounded-lg border border-gray-200 p-4">
|
||||
<h3 className="text-sm font-semibold text-gray-900 mb-3">建议措施</h3>
|
||||
<div className="space-y-2">
|
||||
{recommendations.map((rec, idx) => (
|
||||
<div key={idx} className={`flex items-start gap-3 p-3 rounded border ${PRIORITY_COLORS[rec.priority] || ''}`}>
|
||||
<span className={`px-1.5 py-0.5 rounded text-[10px] font-bold shrink-0 ${
|
||||
rec.priority === 'high' ? 'bg-red-500 text-white' :
|
||||
rec.priority === 'medium' ? 'bg-yellow-500 text-white' : 'bg-gray-400 text-white'
|
||||
}`}>
|
||||
{rec.priority === 'high' ? '高' : rec.priority === 'medium' ? '中' : '低'}
|
||||
</span>
|
||||
<div>
|
||||
<div className="text-sm font-medium text-gray-900">{rec.title}</div>
|
||||
<div className="text-xs text-gray-600 mt-0.5">{rec.description}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ReportsCenter() {
|
||||
const [view, setView] = useState<'list' | 'detail'>('list');
|
||||
const [selectedReportId, setSelectedReportId] = useState<string | null>(null);
|
||||
const { error, clearError, fetchReportsList, generateReport } = useReportsStore();
|
||||
const [genType, setGenType] = useState<string>('daily');
|
||||
const [isGenerating, setIsGenerating] = useState(false);
|
||||
|
||||
const handleGenerate = useCallback(async () => {
|
||||
setIsGenerating(true);
|
||||
try {
|
||||
await generateReport(genType);
|
||||
setView('detail');
|
||||
} finally {
|
||||
setIsGenerating(false);
|
||||
}
|
||||
}, [genType, generateReport]);
|
||||
|
||||
const handleSelect = useCallback((id: string) => {
|
||||
setSelectedReportId(id);
|
||||
setView('detail');
|
||||
}, []);
|
||||
|
||||
const handleBack = useCallback(() => {
|
||||
setView('list');
|
||||
setSelectedReportId(null);
|
||||
fetchReportsList();
|
||||
}, [fetchReportsList]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
{error && view === 'list' && (
|
||||
<ErrorBanner error={error} onRetry={() => { clearError(); fetchReportsList(); }} onDismiss={clearError} />
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between mb-5">
|
||||
<div>
|
||||
<h1 className="font-display text-[18px] font-semibold mb-1 flex items-center gap-2">
|
||||
<FileText className="w-5 h-5 text-primary" />
|
||||
报表中心
|
||||
</h1>
|
||||
<p className="text-[12px] text-text-muted">健康风险评估报告管理与导出</p>
|
||||
</div>
|
||||
|
||||
{view === 'list' && (
|
||||
<div className="flex items-center gap-2">
|
||||
<select
|
||||
value={genType}
|
||||
onChange={(e) => setGenType(e.target.value)}
|
||||
className="px-3 py-1.5 border border-gray-300 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
<option value="daily">日报</option>
|
||||
<option value="weekly">周报</option>
|
||||
<option value="monthly">月报</option>
|
||||
</select>
|
||||
<button
|
||||
onClick={handleGenerate}
|
||||
disabled={isGenerating}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-primary text-white rounded hover:bg-primary-dark transition-colors disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-3.5 h-3.5 ${isGenerating ? 'animate-spin' : ''}`} />
|
||||
生成新报告
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{view === 'list' && <ReportList onSelect={handleSelect} />}
|
||||
{view === 'detail' && selectedReportId && (
|
||||
<ReportDetail reportId={selectedReportId} onBack={handleBack} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -32,7 +32,13 @@ const DAY_OPTIONS = [
|
||||
];
|
||||
|
||||
export function TrendAnalysis() {
|
||||
const { trendData, isLoading, error, clearError, selectedDays, setSelectedDays, fetchTrend } = useAnalysisStore();
|
||||
const trendData = useAnalysisStore((s) => s.trendData);
|
||||
const isLoading = useAnalysisStore((s) => s.isLoading);
|
||||
const error = useAnalysisStore((s) => s.error);
|
||||
const clearError = useAnalysisStore((s) => s.clearError);
|
||||
const selectedDays = useAnalysisStore((s) => s.selectedDays);
|
||||
const setSelectedDays = useAnalysisStore((s) => s.setSelectedDays);
|
||||
const fetchTrend = useAnalysisStore((s) => s.fetchTrend);
|
||||
const [selectedPollutants, setSelectedPollutants] = useState<string[]>(['aqi', 'pm25']);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
Reference in New Issue
Block a user