New Schaad.OpenData.Watercraft library that discovers the yearly "immatrikulierte Wasserfahrzeuge" datasets (2021–2025) on data.tg.ch, caches them and aggregates boats per harbour location by type, propulsion, fuel, emission group and use, with length/power bins. API under /api/watercraft, new page /schifffahrt/thurgau with donut markers per location, year playback, toggleable categories and a location/canton panel. Swisstopo base layers moved to map/baseLayers.ts for both maps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9.2 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Commands
# 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. Two datasets so far, both from the canton of Thurgau on data.tg.ch:
- hourly traffic counts by vehicle class (
dbu-tba-1, CC0): 64 counting stations, each with exactly two directions, 10 vehicle classes (SWISS10) - registered watercraft (one dataset per year,
djs-kpo-5/8/7/9/10for 2021–2025, CC BY 4.0): ~7000 boats, one row per boat with location (harbour village orohne festen Standort), type, propulsion, fuel, emission group, length and power
| Project | Role |
|---|---|
Schaad.OpenData.Traffic |
Fetching, JSON cache, road geometry, analysis — everything except HTTP hosting |
Schaad.OpenData.Watercraft |
Watercraft: catalog lookup, JSON cache, aggregation per location |
Schaad.OpenData.Server |
Minimal API (/api/traffic/* in Traffic/TrafficEndpoints.cs, /api/watercraft/* in Watercraft/WatercraftEndpoints.cs), serves the built client from wwwroot with SPA fallback |
Schaad.OpenData.Tests |
Tests for the Traffic and Watercraft libraries |
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 and Watercraft in appsettings.json (Traffic__DataPath=/app/data and Watercraft__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:
SwisstopoClient.GetRoadSegmentsAsyncloads swissTLM3D road segments around the station (api3.geo.admin.ch identify, paged by 200) with their street name.verkehrsbedeutung != 999998marks main roads;objektart12–19 are paths and lane markings (15/16 seen in practice), everything else is a road — note that 20 is a regular road type.RoadPathBuilder.BuildRoadPathsnaps 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.- Stations named
… Kreisel …sit on a roundabout arm. The roundabout centre is the average position of all stations sharing the name part before-(e.g. the fourWEINFELDEN Kreisel Weststations), and the arm target is a point 3 km outward from that centre through the station (StationGeometryService.OutwardTarget), so no geocoding is needed.BuildArmPathfollows every segment within 80 m outward for 600 m, preferring segments named like the station's address (the arm's street), and keeps the arm that gets furthest outward; a ring loops back and is rejected. A roundabout with a single station falls back to the geocoded target. - Otherwise
SwisstopoClient.FindPlaceAsyncgeocodes 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. Directions can benach/zur/zum/Richtung X(toward) orvon/vom X(from); targets likeUmfahrung,Zentrumor street names cannot be geocoded. RoadPathBuilder.Orientpoints each direction toward or away from 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.
Watercraft
WatercraftRefreshService (BackgroundService, checks every 30 min, refreshes daily)
→ WatercraftRefresher
→ ThurgauWatercraftClient.FindDatasetsAsync catalog search, keeps titles "Bestand der bei der Schifffahrtskontrolle … {year}"
→ ThurgauWatercraftClient.FetchAsync only for years that are new or whose dataset id / modified date changed
→ WatercraftCacheStorage {DataPath}/watercraft/thurgau/{meta.json, years/{year}.json}
→ WatercraftDataStore
→ WatercraftAnalysis categories per dimension (ordered by frequency over all years, so client colors stay stable), per location and canton: counts per category, length/power bins, medians, licence-required count (> 6 kW or > 15 m² sail)
The source has no coordinates. WatercraftLocations maps each location name to a point on the shore (village point from the swisstopo gazetteer snapped to the nearest Bodensee/Untersee shoreline and pushed 150 m into the lake, or onto the Rhine). An unknown name gets no position and is listed beside the map instead of on it. Missing values become categories (Ohne Motor, Keine Angabe, Ohne besondere Verwendung), which the client draws in grey.
Client
- Routing with
react-router-dom:/is the start page (pages/HomePage.tsx) with one large tile per map, each map has its own page (/verkehr/thurgau→pages/TrafficThurgauPage.tsx,/schifffahrt/thurgau?jahr=2023→pages/WatercraftThurgauPage.tsx). Tiles come from the registry insrc/maps.ts; a new map needs an entry there (with a preview image inpublic/previews/) and a route inApp.tsx. Deep links work because the server falls back toindex.html. traffic/flowAnimator.tsowns 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 viaonTick; React components only get the integer hour, so markers and charts don't re-render every frame.- The vehicle class order in
traffic/vehicleClasses.tsmust match theVehicleClassenum /VehicleCounts.ToArray()order; count arrays in the API are positional. - Watercraft page:
components/watercraft/WatercraftMap.tsxdraws one SVG donut per location (area ∝ boats, segments by the selected dimension); markers are created once and resized in place, so year changes animate via CSS.watercraft/categories.tsfolds categories into at most six coloured groups plus greyÜbrigeand grey "absent" groups; legend chips hide groups, which shrinks the donuts. The panel shows the canton or the selected location for the selected year plus a stacked trend over all years. - UI language is German (de-CH). Base maps (shared in
map/baseLayers.ts) are swisstopo WMTS layers (greypixelkarte-grauas default, colourpixelkarte-farbe, aerialswissimage), 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,DateOnlyfor dates, central package versions inDirectory.Packages.props, shared settings inDirectory.Build.props. - Classes that tests need to mock (
SwisstopoClient,StationGeometryService,ThurgauTrafficClient,TrafficCacheStorage,ThurgauWatercraftClient,WatercraftCacheStorage) usevirtualmethods instead of single-implementation interfaces. - Tests: one
<Subject>TestShouldclass per subject, method namesDoThisWhenThat, Shouldly assertions (noAssert.*). HTTP clients are tested with a stubHttpMessageHandler, storage with a temp directory cleaned up inDispose. - TypeScript: Prettier config in
client/.prettierrc.json(single quotes, width 100).