feat: Phase 2 — leadership 大屏 (/overview) + district normalization + drawer a11y
Phase 2 of the UX modernization. Three conflict-free workstreams. Leadership 驾驶舱 (/overview): - Wuhan 13-district Leaflet choropleth (public/wuhan_districts.geojson, keyed on name, darker=higher per 高风险高亮), legend, hover/click-zoom - 全部/门诊/住院 Segmented toggle drives choropleth + Top-5 district bar - literal "数据截至2023-12" as-of badge (D3 honesty); raw spinner → LoadingState - decompose OverviewDashboard 501→273; 6 components + 2 helpers under components/overview/ District normalization (backend data boundary): - case_loader.normalize_district + load_cases_by_district_daily collapse the 26 dirty labels (武昌/武昌区…) → 13 canonical; analysis/grid/insights repointed (fixes a grid-merge row-drop bug as a bonus); in-memory, schema unchanged Shell a11y (code-review carryover): - drawer is now a proper modal: ESC, body scroll-lock, focus-in + focus-trap cycle + focus-restore, role=dialog/aria-modal/aria-label, hamburger aria-expanded - SideNav expanded state lifted to AppShell so rail+drawer stay in sync - RouteErrorBoundary around <Outlet/> keeps shell chrome on page/chunk failure Gates: tsc 0 · vitest 64 · e2e 19/19 (17 user-flows + 2 overview) · build ok · backend pytest 6 new + 48 regression green Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -12,6 +12,7 @@ import pandas as pd
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from config import DATA_DIR, RISK_HIGH, PROJECT_ROOT, WUHAN_BOUNDS, LAT_STEP, LON_STEP
|
||||
from data.case_loader import load_cases_by_district_daily
|
||||
from utils.date_helpers import get_latest_date
|
||||
from utils.geojson import parse_geojson_file, load_districts
|
||||
from utils.geo import point_in_polygon
|
||||
@@ -179,18 +180,16 @@ def _district_avg_aqi() -> dict:
|
||||
def _district_total_cases() -> dict:
|
||||
"""Real total recorded cases per district from cases_by_district_daily.
|
||||
|
||||
District labels in the case file are inconsistent ("武昌" vs "武昌区"),
|
||||
so names are normalized by stripping the "区" suffix and summed, then
|
||||
keyed by the canonical mapping name (with "区"). Returns {district: cases}.
|
||||
District labels are normalized to the canonical 13 区-suffixed names at the
|
||||
data-access boundary (data.case_loader), so this is a plain per-district
|
||||
sum. Returns {district: cases}.
|
||||
"""
|
||||
path = PROJECT_ROOT / "processed" / "cases_by_district_daily.parquet"
|
||||
if not path.exists():
|
||||
try:
|
||||
df = load_cases_by_district_daily()
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
df = pd.read_parquet(path, columns=["district", "total_cases"])
|
||||
df = df.copy()
|
||||
df["base"] = df["district"].str.replace("区", "", regex=False)
|
||||
by_base = df.groupby("base")["total_cases"].sum()
|
||||
return {f"{base}区": int(v) for base, v in by_base.items()}
|
||||
by_district = df.groupby("district")["total_cases"].sum()
|
||||
return {str(d): int(v) for d, v in by_district.items()}
|
||||
|
||||
|
||||
@lru_cache(maxsize=8)
|
||||
|
||||
@@ -21,6 +21,7 @@ from models import (
|
||||
MultiDayPredictionRequest,
|
||||
MultiDayPredictionResponse,
|
||||
)
|
||||
from data.case_loader import load_cases_by_district_daily
|
||||
|
||||
router = APIRouter(prefix="/api", tags=["grid"])
|
||||
|
||||
@@ -43,14 +44,13 @@ def _compute_historical_aggregation(
|
||||
) -> HistoricalAggregationResponse:
|
||||
"""Run the full pandas aggregation pipeline (called in thread pool)."""
|
||||
try:
|
||||
cases_df = _load_parquet(PROJECT_ROOT / "processed" / "cases_by_district_daily.parquet")
|
||||
cases_df = load_cases_by_district_daily()
|
||||
except FileNotFoundError:
|
||||
return HistoricalAggregationResponse(
|
||||
aggregations=[], total_records=0,
|
||||
date_range=(start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")),
|
||||
timestamp=datetime.now().isoformat(),
|
||||
)
|
||||
cases_df = cases_df.copy()
|
||||
cases_df['date'] = pd.to_datetime(cases_df['date'])
|
||||
|
||||
filtered_cases = cases_df[
|
||||
@@ -196,7 +196,7 @@ def _grids_geojson_body(date: str, district: Optional[str], risk_level: Optional
|
||||
if district:
|
||||
merged = merged[merged['district_name'].str.contains(district.replace('区', ''), na=False, regex=False)]
|
||||
|
||||
cases_df = _load_parquet(PROJECT_ROOT / "processed" / "cases_by_district_daily.parquet").copy()
|
||||
cases_df = load_cases_by_district_daily()
|
||||
cases_df['date'] = pd.to_datetime(cases_df['date']).dt.strftime('%Y-%m-%d')
|
||||
cases_df = cases_df[cases_df['date'] == date]
|
||||
|
||||
@@ -364,7 +364,7 @@ def _compute_grid_history(grid_id: str, days: int) -> dict:
|
||||
|
||||
district = grid_info.iloc[0]['district_name']
|
||||
|
||||
cases_df = _load_parquet(PROJECT_ROOT / "processed" / "cases_by_district_daily.parquet")
|
||||
cases_df = load_cases_by_district_daily()
|
||||
cases_df['date'] = pd.to_datetime(cases_df['date'])
|
||||
|
||||
end_date = datetime.now()
|
||||
|
||||
@@ -11,6 +11,7 @@ from pydantic import BaseModel, Field
|
||||
from typing import Dict, List, Literal
|
||||
|
||||
from config import DATA_DIR, RISK_HIGH, PROJECT_ROOT
|
||||
from data.case_loader import load_cases_by_district_daily
|
||||
from models import (
|
||||
InsightsResponse,
|
||||
InsightTrend,
|
||||
@@ -491,22 +492,22 @@ async def get_insights_cards():
|
||||
|
||||
cases_path = PROJECT_ROOT / "processed" / "cases_by_district_daily.parquet"
|
||||
if cases_path.exists():
|
||||
cases_df = _cached_parquet(str(cases_path))
|
||||
# Districts already normalized to the canonical 13 区-suffixed names.
|
||||
cases_df = load_cases_by_district_daily()
|
||||
cases_df["date"] = pd.to_datetime(cases_df["date"])
|
||||
latest_case_date = cases_df["date"].max()
|
||||
latest_cases = cases_df[cases_df["date"] == latest_case_date].copy()
|
||||
latest_cases["base_district"] = latest_cases["district"].str.replace("区", "")
|
||||
district_daily = latest_cases.groupby("base_district")["total_cases"].sum().sort_values(ascending=False)
|
||||
latest_cases = cases_df[cases_df["date"] == latest_case_date]
|
||||
district_daily = latest_cases.groupby("district")["total_cases"].sum().sort_values(ascending=False)
|
||||
total_daily = int(district_daily.sum())
|
||||
top_name = district_daily.index[0]
|
||||
top_val = int(district_daily.iloc[0])
|
||||
num_districts = len(district_daily)
|
||||
|
||||
week_ago = latest_case_date - pd.Timedelta(days=6)
|
||||
week_cases = cases_df[cases_df["date"] >= week_ago].copy()
|
||||
week_cases["base_district"] = week_cases["district"].str.replace("区", "")
|
||||
week_cases = cases_df[cases_df["date"] >= week_ago]
|
||||
daily_totals = week_cases.groupby("date")["total_cases"].sum()
|
||||
avg_daily = int(daily_totals.mean())
|
||||
week_district = week_cases.groupby("base_district")["total_cases"].sum().sort_values(ascending=False)
|
||||
week_district = week_cases.groupby("district")["total_cases"].sum().sort_values(ascending=False)
|
||||
week_top_val = int(week_district.iloc[0])
|
||||
|
||||
date_str = latest_case_date.strftime("%m月%d日")
|
||||
@@ -515,8 +516,8 @@ async def get_insights_cards():
|
||||
title=f"日病例统计 ({date_str})",
|
||||
description=(
|
||||
f"最近统计日({date_str})全市{num_districts}个区共记录{total_daily}例儿童呼吸道疾病病例,"
|
||||
f"{top_name}区{top_val}例为当日最高。近7日日均{avg_daily}例,"
|
||||
f"{week_district.index[0]}区累计{week_top_val}例居首。"
|
||||
f"{top_name}{top_val}例为当日最高。近7日日均{avg_daily}例,"
|
||||
f"{week_district.index[0]}累计{week_top_val}例居首。"
|
||||
),
|
||||
type="warning",
|
||||
metric="日病例",
|
||||
|
||||
Reference in New Issue
Block a user