AccountingNext/CLAUDE.md
Claudio Schaad 255c133b85 Add JSON editor for the data files (#7)
## Summary
A new page **Stammdaten → JSON-Editor** (`/json-editor`) for viewing and editing the data files of the year and mandator selected in the header, as plain JSON.

### Editor
- **Files:** opens `Transactions.json` by default; the dropdown offers the other six data files. The file is part of the URL (`?file=`).
- **Monaco** (the VS Code editor) via **BlazorMonaco 3.5.0** (MIT). Its files ship inside the NuGet package, so there is no CDN. `wwwroot/js/monaco.js` loads it only when the page opens, instead of three script tags on every page.
- **Features:**
  - JSON highlighting, line numbers, folding, minimap, and live syntax error markers
  - **Suchen / Ersetzen** buttons, or Ctrl+F / Ctrl+H, with case, whole-word and regex options
  - **Formatieren** tidies the indentation
- **Status line:** mandator / year / file, size, and an "Ungespeicherte Änderungen" marker. Undoing all edits clears it again.

### Saving (`RawDataRepository`)
Only validated text is saved, because a broken file would break every page that reads it:
- **Strict JSON:** unknown property names are errors (e.g. `"Vlaue"`), reported with line, column and path. Clicking an error jumps to the line.
- **IDs:** every entry needs an `Id`, and IDs must be unique.
- **Account references:**
  - `Transactions.json` may only reference accounts in `Accounts.json`;
  - `Accounts.json` may not drop accounts that transactions still use.
- **No silent overwrite:** saving is refused if the file changed on disk since it was loaded (SHA-256 of the content).
- **Backup:** the previous version is copied to `backup/{mandator}/{year}/json-{timestamp}/`.
- **Saved through `BaseRepository.SaveAsync`:** an atomic write that refreshes the cached data, so other pages see the change immediately. The file is written in the normal format; unchanged parts stay byte-identical.

### Infrastructure
- **Hub message size** raised to 8 MB (`Program.cs`): the editor sends whole files from the browser (`Transactions.json` is several hundred KB), and the default is 32 KB per message.
- **Unsaved changes:** `wwwroot/js/unsaved-guard.js` asks before leaving via a link, and the browser's own prompt covers reload, closing the tab and switching year or mandator. Blazor's `NavigationLock` can't do this here: pages are interactive one by one, so routing between them is static enhanced navigation, which doesn't consult interactive components. Switching files or "Neu laden" inside the page uses a Fluent confirmation dialog.

## Test plan
- [x] `dotnet build`: no warnings
- [x] `dotnet test`: 98/98 pass, including 10 new `RawDataRepositoryTestShould` tests:
  - loading
  - save with backup
  - cached data refreshed after saving
  - invalid JSON with line and column
  - unknown property
  - unknown account
  - missing and duplicate IDs
  - removing an account that is still used
  - refusing when the file changed since loading
  - unknown file name rejected
- [x] Headless Chrome on a copy of the real data:
  - editor loads the 433 KB / 9'023-line `Transactions.json` with JSON highlighting; Ersetzen opens the replace widget
  - replacing 88 occurrences and saving: the file on disk equals the original plus exactly those replacements, and a backup is written
  - a typo is rejected, the file stays untouched, and the error jumps to the line
  - leaving with changes: "Abbrechen" stays, "OK" leaves, no prompt without changes, reload asks after real typing

## Notes
- Monaco's own UI texts (Find, Replace, …) are English.
- Not part of this PR: every menu link throws a harmless console error (`navmenu-toggle` is null). The Fluent nav template expects a toggle element that this app doesn't render.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reviewed-on: #7
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
2026-10-22 17:55:20 +00:00

5 KiB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Commands

# Build
dotnet build

# Run (dev server at http://localhost:5225)
cd Schaad.Accounting.UI && dotnet run

# Test
dotnet test

# Publish
dotnet publish -c Release

Tests live in Schaad.Accounting.Tests (xUnit + NSubstitute + Shouldly). There is no lint command.

Architecture

AccountingNext is a Swiss personal accounting app built with ASP.NET Core 9 + Blazor (interactive server-side rendering) and Microsoft Fluent UI. Data is stored as human-readable JSON files on disk (System.Text.Json, settings in JsonStorage) — no database.

Projects

Project Role
Schaad.Accounting.UI Blazor web app — pages, dialogs, layout
Schaad.Accounting.Services Business logic — balances, FX conversion, file import, charts
Schaad.Accounting.Db Repository layer — JSON serialization/deserialization
Schaad.Accounting.Common Shared models, DTOs, interfaces

Data flow

Blazor Pages/Dialogs (UI)
  → Services (ViewService, FileService, ChartService)
  → Repositories (AccountRepository, TransactionRepository, …)
  → JSON files: {DataPath}/{mandator}/{year}/*.json

Data is multi-mandator and multi-year. The layout below DataPath (configured in appsettings.Development.json) is defined in DataFolders:

{DataPath}/{mandator}/{year}/*.json          data files
{DataPath}/uploads/{mandator}/{year}/        imported bank statements (+ creditCard/)
{DataPath}/backup/{mandator}/{year}/         backup zips

When a new year is opened, the previous year's data is copied as the starting point.

Key services

  • ViewService — aggregates account balances, applies FX rates, builds datasets for the UI
  • FileService — imports bank statements (MT940, CAMT053 via external Schaad.Finance.dll), parses PDFs, manages backups
  • ChartService — produces data for the Plotly booking-text charts on the transactions page
  • SettingsService — manages the active year, mandator, and file paths
  • RawDataRepository — plain-text load/save of the data files for the JSON editor page; validates (strict JSON, unique Ids, account references), refuses if the file changed since loading, and backs up the old version to backup/{mandator}/{year}/json-{timestamp}/
  • AnalyticsService — loads all years of the current mandator (via MultiYearRepository) into an AccountingAnalysis (expenses, income, net, assets) for the Analyse page; queries run in memory

UI structure

Pages live in Schaad.Accounting.UI/Components/Pages/. Each page typically has a companion Dialogs/ subfolder with Fluent UI dialog components for CRUD operations. The app is hardcoded to the de-CH culture.

Key external dependencies

  • Microsoft.FluentUI.AspNetCore.Components — UI components (FluentDataGrid, FluentDialog, etc.)
  • Plotly.Blazor — charts on the older chart pages
  • BlazorMonaco — Monaco editor for the JSON editor page; loaded on demand by wwwroot/js/monaco.js instead of script tags in App.razor
  • Chart.js 4 + chartjs-chart-treemap — charts on the Analyse page; vendored in wwwroot/lib/ (no CDN), wrapped by wwwroot/js/charts.js and ChartJsChart.razor
  • FreeSpire.PDF — PDF parsing for bank statement imports
  • Schaad.Finance.dll / Schaad.Finance.Api.dll — proprietary DLLs for MT940/CAMT053 parsing and FX rate lookups (FixerIo API key in appsettings.Development.json)

Domain constants

ClassIds in Schaad.Accounting.Common defines the Swiss accounting chart-of-accounts classes: Activa=1, Passiva=2, Income=3, Expenses=4. These are the leading digit of an account number (accounts are 4-digit; Account.Class = Number / 1000).

Testing conventions

Tests live in Schaad.Accounting.Tests and use xUnit + NSubstitute (mocks) + Shouldly (assertions).

  • File and class name: <Subject>TestShould — one file per subject under test. Examples: ViewServiceTestShould.cs, TransactionRepositoryTestShould.cs, FormattingTestShould.cs.
  • Test method name: DoThisWhenThat — describes the behavior first, then the condition. Read together the class + method form a sentence:
    • ViewServiceTestShould.SumActivaAndPassivaTotalsSeparatelyWhenGettingBalanceView
    • TransactionRepositoryTestShould.ReturnNullWhenGettingUnknownTransactionId
  • Assertions: use Shouldly (value.ShouldBe(expected), list.ShouldBeEmpty(), x.ShouldBeNull(), list.ShouldContain(...), first.ShouldBeSameAs(second), etc.). Do not use xUnit Assert.*.

Example:

public class FormattingTestShould
{
    [Fact]
    public void RoundToTwoDecimalsWhenValueHasMorePrecision()
    {
        1.234m.ToFormattedString().ShouldBe("1.23");
    }
}

Repository tests that hit real file I/O use a temp directory via Path.GetTempPath() and clean up in IDisposable.Dispose. Pure service tests use NSubstitute mocks for every dependency and don't touch the filesystem.