OpenDataVisualizer/CLAUDE.md
Claudio Schaad e729ea3403 Add Thurgau traffic visualizer with animated map
ASP.NET Core 10 API and React client that visualize the canton of
Thurgau's hourly traffic counts by vehicle class (data.tg.ch, CC0).

- Background refresh from data.tg.ch every 6 h into a per-day JSON
  cache, so history grows beyond the source's two-week window
- Road geometry per station direction from swisstopo swissTLM3D,
  oriented by geocoding the direction's target town; roundabout arms
  follow the road outward only
- Leaflet map with canvas animation: dots drive along the road in
  both directions, density by hourly count, colour by vehicle class,
  right-hand traffic; play/pause, time slider and day selection
- Station panel with per-class counts and Chart.js charts (hourly,
  weekday/weekend profile, daily totals, class mix)
- swisstopo base map switcher (grey, colour, aerial)
- Dockerfile and docker-compose with a data volume
- xUnit tests for mapping, cache, geometry, geocoding and analysis

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 20:33:58 +01:00

78 lines
5.9 KiB
Markdown

# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Commands
```bash
# Backend (ASP.NET Core 10) — API + static client at http://localhost:5080
dotnet build
dotnet run --project Schaad.OpenData.Server --launch-profile http
# Tests (xUnit + NSubstitute + Shouldly)
dotnet test
dotnet test --filter "FullyQualifiedName~RoadPathBuilderTestShould"
# Client (Vite + React + TypeScript), run from client/
npm install
npm run dev # http://localhost:5173, proxies /api to :5080
npm run build # tsc + vite build into Schaad.OpenData.Server/wwwroot
npm run typecheck
npm run format # prettier
# Docker
docker compose up --build # http://localhost:8080, data in volume opendatavisualizer-data
```
There is no lint step besides `tsc` (strict, no unused locals/parameters). `dotnet build` with the server running fails on locked DLLs; build or test only `Schaad.OpenData.Tests` in that case.
## Architecture
Visualizes open data from opendata.swiss. The first (and so far only) dataset is the canton of Thurgau's hourly traffic counts by vehicle class (`dbu-tba-1` on data.tg.ch, CC0): 64 counting stations, each with exactly two directions, 10 vehicle classes (SWISS10).
| Project | Role |
|---|---|
| `Schaad.OpenData.Traffic` | Fetching, JSON cache, road geometry, analysis — everything except HTTP hosting |
| `Schaad.OpenData.Server` | Minimal API (`/api/traffic/*` in `Traffic/TrafficEndpoints.cs`), serves the built client from `wwwroot` with SPA fallback |
| `Schaad.OpenData.Tests` | Tests for the Traffic library |
| `client/` | React SPA: Leaflet map with animated traffic, Chart.js station charts |
### Data flow
```
TrafficRefreshService (BackgroundService, checks every 15 min)
→ TrafficRefresher
→ ThurgauTrafficClient data.tg.ch JSON export (only the last ~14 days are available there)
→ TrafficSnapshot.Merge imported days replace cached days, older days are kept
→ TrafficCacheStorage {DataPath}/traffic/thurgau/{stations.json, meta.json, counts/yyyy-MM-dd.json, geometry-vN.json}
→ StationGeometryService road path per station direction (once per station)
→ TrafficDataStore immutable TrafficSnapshot swapped atomically, read by the endpoints
→ TrafficAnalysis shapes the snapshot for the API (DayView for the map, StationSummary for charts)
```
The cache accumulates history beyond the source's two-week window; refreshes only fetch from the last cached day minus one (`where=datum >= …`). `RefreshInterval` and `DataPath` are configured under `Traffic` in `appsettings.json` (`Traffic__DataPath=/app/data` in Docker). Yearly archives back to 2011 exist as `https://ogdtg.ch/verkehrsdaten/fahrzeugklassen/{year}_fzkl_data.csv.gz` but are not imported yet.
### Road geometry (for the direction animation)
The source has one point per station and directions as text (`nach X`, `von X`, or just `X`). `StationGeometryService` turns that into a road polyline per direction, oriented in driving direction:
1. `SwisstopoClient.GetRoadSegmentsAsync` loads swissTLM3D road segments around the station (api3.geo.admin.ch identify, paged by 200). `verkehrsbedeutung != 999998` marks main roads, `objektart <= 11` drivable roads (higher values are paths and lane markings).
2. `RoadPathBuilder.BuildRoadPath` snaps to a main road within 60 m (else the nearest drivable road), stitches connected segments (≤ 60° turn, penalty for changing road class) and trims to ±300 m.
3. Stations named `… Kreisel …` sit on a roundabout arm: `BuildArmPath` follows every road segment within 80 m outward (600 m) and keeps the one that gets furthest toward the target town (a roundabout ring loops back and loses); it falls back to `BuildRoadPath`.
4. `SwisstopoClient.FindPlaceAsync` geocodes the target town (SearchServer, municipalities + gazetteer, label must contain the name with ä→ae etc., nearest candidate wins — "Landquart" is also a place in Arbon). Names with `/` are split, since the SearchServer returns 503 for slashes.
5. `RoadPathBuilder.Orient` points each direction toward (`nach`) or away from (`von`) its target; the two directions of a station are always opposite.
When the geometry algorithm changes, bump `GeometryFileName` in `TrafficCacheStorage` so all stations are rebuilt.
### Client
- `traffic/flowAnimator.ts` owns the animation clock (time of day in hours, play/pause, speed) and draws on a canvas above Leaflet's overlay pane. Dots spawn per direction at a rate proportional to the interpolated hourly count, colored and sized by vehicle group, offset to the right of the driving direction. It reports the time to React at ~10 Hz via `onTick`; React components only get the integer hour, so markers and charts don't re-render every frame.
- The vehicle class order in `traffic/vehicleClasses.ts` must match the `VehicleClass` enum / `VehicleCounts.ToArray()` order; count arrays in the API are positional.
- UI language is German (de-CH). Base maps are swisstopo WMTS layers (grey `pixelkarte-grau` as default, colour `pixelkarte-farbe`, aerial `swissimage`), switchable via Leaflet's layer control; the choice is stored in localStorage (`odv.baseMap`).
## Conventions
- C#: `var`, primary constructors, file-scoped namespaces, one type per file, no comments, `DateOnly` for dates, central package versions in `Directory.Packages.props`, shared settings in `Directory.Build.props`.
- Classes that tests need to mock (`SwisstopoClient`, `StationGeometryService`, `ThurgauTrafficClient`, `TrafficCacheStorage`) use `virtual` methods instead of single-implementation interfaces.
- Tests: one `<Subject>TestShould` class per subject, method names `DoThisWhenThat`, Shouldly assertions (no `Assert.*`). HTTP clients are tested with a stub `HttpMessageHandler`, storage with a temp directory cleaned up in `Dispose`.
- TypeScript: Prettier config in `client/.prettierrc.json` (single quotes, width 100).