## Summary
Step 3 of the analytics plan: three more views on the **Analyse** page, plus a **fix for a bug in `main`** where changing the year filter stopped the page from updating.
### Fix: year filter navigation loop
Choosing a year in "Von" or "Bis" started an endless navigation loop: one click caused about 2,700 navigations in 3 seconds. The page never updated, and because the browser then throttled navigation, the Monat / Quartal / Jahr buttons stopped working too.
**Cause:** `FluentSelect` reports its selected value again on every re-render. The handler compared it with the year on the page, which only changes once a navigation has finished, so every re-render started another navigation to the same URL and cancelled the previous one.
**Fix:** `OnFromChanged` / `OnToChanged` take over the chosen year immediately, so a repeated report of the same value does nothing. The bug came in with #4.
### New views
- **Zusammensetzung (treemap):** the children of the current level as areas, with their own children nested inside (e.g. subclass → accounts, account → booking texts). The colours are the same as in the bar chart and list. Clicking an area drills into it; clicking a nested tile goes straight to that deeper level. Refunds (negative amounts) are left out, since an area can't be negative.
- **Jahresvergleich:** one line per year over Jan–Dez, switchable between *Monatlich* and *Kumuliert* (default). The latest year is a thick blue line, the year before orange, and older years fading grey. The running year stops at the last month with data.
- **Jahre im Vergleich:** categories × years, with a total column and a total row.
- Cells are shaded by **monthly average**, so the running year compares fairly.
- Each cell shows the change versus the previous year over the **same months**: the running year is marked `2026*` with a footnote.
- Rows drill down when clicked, and zero cells show "–".
- This one view replaces both the heatmap and the table from the plan, which would have shown the same numbers twice.
### Other changes
- **Chart.js has no sunburst**, so the composition view is a treemap. It uses `chartjs-chart-treemap` **4.2.2** (MIT, by a Chart.js maintainer), vendored in `wwwroot/lib/chartjs-chart-treemap` with its licence and checked against the npm registry checksum. It is loaded only when the treemap is first used.
- **`ExpenseAnalysis`** also returns the year profiles, the category × year table and the two-level composition.
- **`StackedBarChart` became a generic `ChartJsChart`**: `Kind` = stackedBar / line / treemap, and new `Data` updates the chart in place. `charts.js` has one `createChart` entry point.
- **Click hints only appear when something can be drilled into.** At the account level they were shown before even though booking texts can't be opened (already the case in #4). The treemap only shows a hand cursor over clickable tiles.
## Test plan
- [x] `dotnet build`: no warnings
- [x] `dotnet test`: 81/81 pass, including 6 new `ExpenseAnalysisTestShould` tests (year profiles with empty future months, category × year values and same-months change, no previous year, nested composition, single-level composition for an account, negative amounts left out)
- [x] On a copy of the real data in headless Chrome: all three new charts render without console errors; table year totals match the verified per-year totals (2022: 190'724 … 2026: 77'006); the treemap for 2022 adds up to that year's total
- [x] Interactions: treemap area and nested-tile clicks, table row links, Monatlich/Kumuliert switch
- [x] Year filter fix: Von 2025 → Jahr → Bis 2025 → Quartal → Alle Jahre → back make exactly one navigation each, and charts, tiles and table update every time
- [ ] Narrow-screen layout checked by hand
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Reviewed-on: #5
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
## Summary
A new **Analyse** page (Charts → Analyse, `/analytics`) shows the current mandator's **expenses over all years**, with drill-down **all expenses → subclass → account → booking text** (first word, like the existing charts). This covers steps 1 and 2 of the analytics plan; more views (composition, year comparison, heatmap, table) follow in later PRs.
The page **replaces the old "Ausgaben" and "Zeitverlauf" charts**, which are removed (see below). "Vermögen" stays until the Analyse page covers assets.
### Page
- **Filters:** from/to year, "Alle Jahre", Monat / Quartal / Jahr. The default is monthly for a single year and quarterly for several.
- **Breadcrumb** to jump back up the drill-down.
- **Tiles:** total, average per month, change versus the previous year over the same months (e.g. 2026 vs. 2025, Jan–Okt; more spending red, less green), largest item with its share.
- **Stacked bar chart** (Chart.js) with sorted tooltips including a total. Clicking a segment drills down. Beyond 7 categories the tail is grouped as "Andere", like the other charts.
- **Category list** with amount, share and share bar, in the chart's colours. Entries are links that drill down.
- **URL state** (`?from=&to=&period=&sub=&acc=&text=`): back/forward and bookmarks work. Data is loaded once per visit; every change is an in-memory query.
### Data
- `MultiYearRepository` (`IMultiYearRepository`) reads Accounts / SubClasses / Transactions of any mandator and year. It is read-only (never creates folders or copies files) and shares the per-session cache with the other repositories, so a save in the current year is reflected immediately.
- `ExpenseAnalysis` flattens all years into one row per month / account / booking-text group:
- **Net amounts:** bookings to an expense account count positive, bookings from one (refunds, corrections) negative; moves between expense accounts cancel out at the higher levels.
- **Accounts are keyed by number** across years and shown with the latest name.
- **Bookings count in the year of the books they are in**, like the annual reports. The few bookings dated outside that year (late-December payments booked in the next year) go to its first or last month.
- The running year stops at the last month with data; the year-over-year comparison uses the same months of both years.
- `TransactionDataset.GetTextGroup` gets a static overload so the grouping can be used without a transaction view.
- `BaseRepository` can load a cached list from any directory.
### Chart.js
- Chart.js **4.5.1** (MIT) is vendored in `wwwroot/lib/chartjs` with its licence, checked against the npm registry checksum. There is no CDN dependency, so the app works offline.
- `wwwroot/js/charts.js` loads it only when the page opens and styles it like `ChartTheme` (palette, font, de-CH numbers with `'`). `StackedBarChart.razor` creates the chart once and then updates it in place.
- Plotly stays for "Vermögen" and the booking-text charts on the Transactions page.
### Removed
- The pages **Ausgaben** (`/spendings`, donut) and **Zeitverlauf** (`/SpendingsOverTime`, stacked bars) and their menu entries. Bookmarks to them now show "not found".
- `ChartService.GetExpensesPerMonthAsync` with its two helpers and its 6 tests; nothing else used them. `ChartService` now only serves the booking-text charts.
## Test plan
- [x] `dotnet build --no-incremental`: no warnings
- [x] `dotnet test`: 75/75 pass (6 tests removed with `GetExpensesPerMonthAsync`), including 15 new `ExpenseAnalysisTestShould` tests (subclass totals, refunds, non-expense bookings, transfers, account renames across years, booking-text level, breadcrumb, book-year attribution, running year, quarters/years, year range, year-over-year comparison, no previous year, no data) and 4 `MultiYearRepositoryTestShould` tests
- [x] Against a copy of the real data: every year's total matches an independent Python recomputation from the JSON files, and the 2026 total (77'006.07) equals "Total Ausgaben" in the profit-and-loss report
- [x] In headless Chrome: chart renders, clicking a bar drills to the subclass, a list entry drills to the account, browser back returns, and the period buttons switch. No console errors.
- [ ] Narrow-screen layout checked by hand (only covered by CSS so far)
## Known limitations
- A partial last period (e.g. Q4 26 with only October) is not marked as incomplete yet.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Reviewed-on: #4
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
## Summary
All data folders are now migrated to JSON in the `{mandator}/{year}` layout, so the one-time migration from #2 is no longer needed.
- Remove `DataMigrator` and its 15 tests, its DI registration and the startup call in `Program.cs` (`Main` is back to a plain `app.Run()`).
- Remove the old-layout year-folder filter in `SettingsService.GetMandators` and the `DataFolders.IsYear` helper it used.
- Remove the migration notes from `CLAUDE.md` and code comments.
- Rename `.xml` paths to `.json` in a repository-cache test (cosmetic).
Bank-statement import (CAMT053 `.xml` in `StatementImport`) is unaffected.
**Note:** this version expects every data folder to be migrated already. An old-layout or XML data folder is no longer converted. The original XMLs remain in `backup/{mandator}/{year}/xml-<timestamp>/` and can be deleted manually.
## Test plan
- [x] `dotnet build --no-incremental`: no warnings
- [x] `dotnet test`: 62/62 pass
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Reviewed-on: #3
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
## Summary
- Repositories read and write **JSON instead of XML**. The JSON is human readable: indented, umlauts written as-is, property names as in the C# models (`BankTransactionText`), null values left out, computed properties (`Class`, `SubClass`, `IsFxAccount`, `ReadOnly`) not stored. Shared settings live in `JsonStorage`.
- **New data folder layout**, defined in `DataFolders`:
```
{DataPath}/{mandator}/{year}/*.json data files (no Data subfolder)
{DataPath}/uploads/{mandator}/{year}/ imported bank statements (+ creditCard/)
{DataPath}/backup/{mandator}/{year}/ backup zips and the original XML files
```
`SettingsService` builds the new paths. `GetYearMandatorPath` / `GetLastYearMandatorPath` are removed because they now equal the data paths. The mandator dropdown lists mandators that have a folder for the selected year.
- New **`DataMigrator`** runs at startup, before the app serves requests, in two phases:
1. **Restructure:** moves the old `{year}/{mandator}/Data`, `{year}/{mandator}/uploads` and `{year}/backup/{mandator}` folders into the new layout, unchanged.
2. **Convert:** turns the seven known XML data files in each `{mandator}/{year}` folder into JSON, checks that the JSON reads back to the same data, then moves the XML to `backup/{mandator}/{year}/xml-{timestamp}/`. Bank-statement XMLs are moved but never converted.
- **Safety:** nothing is ever overwritten. If a file already exists at the target, the source is dropped only when both are identical; otherwise it is an error. Any error stops startup (conversion is skipped if a move failed), so the app never runs on a half-migrated folder. Old folders are removed only once empty; unexpected leftovers are logged and kept. Both phases can safely run again.
- `CLAUDE.md` updated for JSON storage and the new layout.
## Upgrade notes
- **Make a full copy of the data folder before the first start** of this version.
- **Don't run an older (XML) version** on a migrated data folder. It would find no data and start new XML files in the old layout.
- The backup zip now contains only the data files of the current mandator/year. Uploads live in their own folder.
- Empty folders from the old layout are not carried over; the app recreates them when needed.
## Test plan
- [x] `dotnet build`: no warnings
- [x] `dotnet test`: 77/77 pass, including 15 `DataMigratorTestShould` tests (old-layout data, uploads with subfolders and year backups moved; XML converted in old and new layout; readable JSON; values round-trip through the repositories; unknown XMLs not converted; rerun does nothing; stray files kept; crash recovery for moves and conversions; conflicting files; corrupt XML) and 4 `SettingsServiceTestShould` tests for the new paths and mandator list
- [x] Ran the app against a copy of the real data folder: 136 files moved, 82 XML files converted, no old year folders left, Accounts / Balance report / Transactions pages render
- [x] Checked every one of the 137 original files against a checksum manifest: uploads and other files byte-identical at their new location, every XML backup identical to the original, and JSON vs. XML compared field by field (11,807 records, 101,564 fields, 0 differences). 8 dates with a UTC offset in the XML are written as the same instant in local time, which is what the old app also had in memory after reading them.
- [ ] Start once on the real data folder and check the pages
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Reviewed-on: #2
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
Bookings like "Narbonne Car" and "Narbonne Food" should roll up into
one series/slice instead of staying separate, so grouping now uses
the text up to the first space via TransactionDataset.GetTextGroup().
Adds two charts to the per-account transactions view: a stacked bar
chart of monthly totals and a pie chart of overall totals, both
grouped by booking text, so recurring bookings (rent, subscriptions,
etc.) are visible at a glance. Chart components are keyed on the
account id so switching accounts remounts them instead of reusing a
stale Plotly instance.
Every repository, service, Blazor page/dialog, and test now uses
async/await. Single atomic diff; the codebase does not compile in
intermediate states.
- BaseRepository: LoadListAsync/LoadAsync/SaveAsync return Task<T>;
per-file locks use SemaphoreSlim so waiters can await; Save
serialises to a MemoryStream sync (XmlSerializer has no async
form), then File.WriteAllBytesAsync + sync File.Move.
- RepositoryCache.GetOrLoadAsync takes a Func<Task<List<T>>>.
- All 7 repository interfaces + implementations async.
- All service interfaces + implementations async (except vendor
IFxService and stateless IFxConverter / SettingsService).
- Every Blazor OnInitializedAsync switches to await base.
- Test suite fully async, 42 tests pass.
AccountRepository.EnsureAccountsFile keeps two .GetAwaiter().GetResult()
bridges because it runs from the constructor.
Null-render guard follow-up (folded in):
Blazor now renders the component once with fields at their initial
values while OnInitializedAsync awaits — so fields declared `= null!`
are actually null on that first render and things like
`accounts.GroupBy(...)` throw ArgumentNullException. Fixed across
Transactions, BalanceReport, BalanceSheetReport, ProfitLossReport,
DetailReport, Assets, Spendings, SpendingsOverTime, TransactionDialog,
TransactionSplitDialog, and BookingRuleDialog:
- Collection fields initialise to [] so first-render loops are empty.
- Single-object data fields become nullable; the razor wraps
consumption in `@if (field is null) { <p>Lädt…</p> return; }`.
- <PlotlyChart> guarded behind a null check on config/layout/data so
Plotly.Blazor's @bind doesn't see nulls.
- Header/footer strings initialise to "" instead of null!.
Architectural hygiene on a single-user local Blazor Server app: the
observed win is one File.ReadAllBytesAsync and one
File.WriteAllBytesAsync per Load/Save, and after PR D each file is
loaded at most once per SignalR circuit.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Both were constructor-initialised value carriers with read-only
consumers. Positional record syntax replaces the class + property +
ctor boilerplate; ViewService callers updated to PascalCase named
args to match the record-generated parameter names.
Rest of item 26 descoped: XmlSerializer needs mutable public
setters (value-equality on mutable data is a footgun) and has no
source generator without changing file format. See
IMPROVEMENT_PLAN.md for the full rationale.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Three long-noted rough edges from the original analysis, each a
one-line touch:
- ClassIds becomes static class (was instantiable).
- Home.razor.cs drops the `loaded` bool guard (Blazor already runs
OnInitializedAsync exactly once per component instance).
- Move the "Claudio Schaad" mandator default out of SettingsService
into SettingsDataset.DefaultMandator, plumbed through
appsettings.Development.json.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Replace the hand-rolled model.Copy(target) pattern in every SaveXxx
with FindIndex -> in-place replace (or Add on new). Move the two
hidden defaults out of the deleted Copy bodies: Currency = "CHF"
default now lives in AccountRepository.SaveAccount; BookingDate =
ValueDate default now lives in TransactionRepository.SaveTransaction.
Delete Copy from Account, BookingRule, BookingText, SubClass, and
SplitPredefinition. Keep Transaction.Clone() (renamed from Copy, and
now includes RelatedParty) for the defensive copy in GetTransaction
and ViewService.WithDisplaySign.
Fixes a pre-existing bug where Transaction.Copy silently dropped
RelatedParty on every update save.
42 tests total, all passing.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
IViewService, IFileService, and IChartService move from
Schaad.Accounting.Common/Interfaces/ to
Schaad.Accounting.Services/Interfaces/. Namespaces are unchanged, so
no consumer needs a using update. Common's vendor <Reference
Include="Schaad.Finance.Api"> can be dropped, matching Common's
documented role as the shared models/DTOs/interfaces layer.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- Consolidate decimal.ToFormattedString into Schaad.Accounting.Formatting
- Rename EnsureFileExisits -> EnsureFileExists and
SplitPredefiniton* -> SplitPredefinition* (class, interface, files, DI reg)
- AccountRepository: single-save year-rollover start-balance seed
- Drop legacy .NET Standard packages redundant on net9.0 and the stale
Interfaces\Extensions\ folder entry
- Set culture via RequestLocalizationOptions middleware
- Plan: item 9 (unit of work) split off into a dedicated PR D
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>