Compare commits
4 commits
0fdecc9e67
...
0e5fbf859f
| Author | SHA1 | Date | |
|---|---|---|---|
| 0e5fbf859f | |||
| 3c7df6c8bb | |||
| 76d006b515 | |||
| c47016cd6d |
13 changed files with 51 additions and 696 deletions
5
Directory.Build.props
Normal file
5
Directory.Build.props
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Project>
|
||||||
19
Directory.Packages.props
Normal file
19
Directory.Packages.props
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageVersion Include="coverlet.collector" Version="10.1.0" />
|
||||||
|
<PackageVersion Include="FreeSpire.PDF" Version="12.4.0" />
|
||||||
|
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.13" />
|
||||||
|
<PackageVersion Include="Microsoft.FluentUI.AspNetCore.Components" Version="4.14.5" />
|
||||||
|
<PackageVersion Include="Microsoft.FluentUI.AspNetCore.Components.Emoji" Version="4.14.5" />
|
||||||
|
<PackageVersion Include="Microsoft.FluentUI.AspNetCore.Components.Icons" Version="4.14.5" />
|
||||||
|
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
||||||
|
<PackageVersion Include="NSubstitute" Version="6.2.0" />
|
||||||
|
<PackageVersion Include="Plotly.Blazor" Version="7.2.0" />
|
||||||
|
<PackageVersion Include="Shouldly" Version="4.3.0" />
|
||||||
|
<PackageVersion Include="xunit" Version="2.9.3" />
|
||||||
|
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
|
|
@ -1,114 +0,0 @@
|
||||||
# AccountingNext — Technical Improvement Plan
|
|
||||||
|
|
||||||
Analysis and phased plan produced 2026-07-02. See conversation history for full context.
|
|
||||||
|
|
||||||
## Findings
|
|
||||||
|
|
||||||
### 1. Correctness bugs (must fix)
|
|
||||||
|
|
||||||
- **Shared mutable state across users.** `SettingsService` is registered as `Singleton` (`Schaad.Accounting.UI/Extensions.cs:21`) but holds mutable `year`/`mandator` fields (`Schaad.Accounting.Services/SettingsService.cs:13-14`). Any user switching year/mandator changes it for *all* connected Blazor Server users.
|
|
||||||
- **`TrySetYear` rollback is broken.** `SettingsService.cs:33` captures `var oldYear = year;` — that's the *parameter*, not `this.year`. The "rollback" restores the same value that just failed.
|
|
||||||
- **`ChartService` mutates a shared service.** `GetAccountExpensesPerMonth(accountId, year)` (`ChartService.cs:87`) calls `settingsService.TrySetYear(year)` then `SetYear(DateTime.Now.Year)` to reload prior-year data. Global mutation on a singleton — guaranteed to race in production.
|
|
||||||
- **`DummyFxService` has a typo.** `DummyFxService.cs:13` — `currencies.Contains(fromCurrency) && currencies.Contains(fromCurrency)` (both sides check `fromCurrency`). Also it silently returns the raw amount for supported currencies, so all "CHF conversions" are no-ops.
|
|
||||||
- **`TransactionRepository.GetTransaction` mutates the entity.** `TransactionRepository.cs:67-81` divides `Value` by `FxRate` on read, and `SaveTransaction` multiplies by `FxRate` on write. Also silently NREs when the id is not found (line 73 dereferences `transaction`).
|
|
||||||
- **`ViewService.GetTransactionViewList(accountId)` mutates transactions.** `ViewService.cs:172` flips `t.Value *= -1` on the loaded transaction. `FileService.GetTransactionListCsv` does the same (`FileService.cs:137`). These are the shared objects returned by the repository — later reads see wrong signs.
|
|
||||||
- **DI double-registration.** `Extensions.cs` registers `IChartService`, `IViewService`, `IFileService`, statement services, and `IFxService` in both `AddRepositories` and `AddServices`. Also `AddServices` registers `PdfParsingService` as its own key (`services.AddSingleton<PdfParsingService, PdfParsingService>()`) instead of `IPdfParsingService`.
|
|
||||||
- **Magic numbers instead of `ClassIds`.** `ProfitLossReport.razor.cs:25-26` uses `.Class == 3` / `.Class == 4`.
|
|
||||||
- **`ClassIds` doc/code mismatch.** `CLAUDE.md` states `Activa=1000, Passiva=2000, …`, but `ClassIds.cs` defines them as `1,2,3,4` (matches `Account.Class = Number / 1000`).
|
|
||||||
- **Non-atomic XML writes, no locking.** `BaseRepository.Save` writes directly to the target path. Interrupted writes corrupt data. Two concurrent saves interleave. No temp-file+rename, no `FileShare` lock.
|
|
||||||
- **`AccountRepository.EnsureFileExisits` calls `SaveAccount` in a loop.** Each call re-loads and re-serializes the whole account list.
|
|
||||||
- **`ProfitLossReport` / `BalanceSheetReport`** compute totals by re-summing balances that `ViewService` already computes — but with subtle differences. Two sources of truth for the same number.
|
|
||||||
|
|
||||||
### 2. Reliability / maintainability
|
|
||||||
|
|
||||||
- **No async I/O.** Every XML read/write is synchronous, blocking the SignalR hub thread in Blazor Server.
|
|
||||||
- **No caching.** A single page render calls `GetAccountList()` and `GetTransactionList()` many times. Every one is a fresh file read + XML deserialization.
|
|
||||||
- **O(N·M) lookups.** `ViewService.cs:138-139` — `accountList.Single(...)` inside a `Select` over all transactions. Should be a dictionary keyed by id.
|
|
||||||
- **No logging.** `ILogger` is not used anywhere.
|
|
||||||
- **No error surface.** Repositories throw or return `null`; UI dereferences with `!`.
|
|
||||||
- **Anemic domain model + `Copy` methods.** `Account.Copy`, `Transaction.Copy`, `SubClass.Copy` etc. are hand-rolled property copies used to merge edits into loaded entities.
|
|
||||||
- **Vendor coupling in the Domain project.** `Schaad.Accounting.Common` references `Schaad.Finance.Api.dll`. `IChartService`, `IFileService`, and `IViewService` live in `Common` and depend on `Schaad.Finance.Api` types.
|
|
||||||
- **Duplicated formatting logic.** `ToFormattedString(decimal)` exists in `Extensions.cs` and again in `FileService.cs`.
|
|
||||||
- **Culture setup in `Program.cs`** runs *after* `MapRazorComponents` and just sets `DefaultThreadCurrentCulture` globally. Should be `RequestLocalizationOptions` middleware.
|
|
||||||
- **Constructors doing I/O.** `AccountRepository`, `SubclassRepository`, `SplitPredefinitonRepository`, `BookingRuleRepository` call `EnsureFileExisits` in the constructor.
|
|
||||||
- **Typos leak into public API.** `EnsureFileExisits`, `SplitPredefinitonRepository`.
|
|
||||||
- **Dead / redundant code.** `AccountRepository.EnsureFileExisits` uses `new` to hide the base method; its `file.IndexOf("Accounts") > -1` guard is redundant. `Home.razor.cs:50` uses a `loaded` flag though `OnInitializedAsync` already runs once per instance. Commented-out `//var subclasses = subclassRepository.GetSubClassList();` in `ChartService`.
|
|
||||||
- **Legacy nuget packages.** All three library projects reference `System.Text.RegularExpressions 4.3.1`, `System.Xml.XmlSerializer 4.3.0`, `System.ComponentModel.Annotations 5.0.0` — legacy .NET Standard packages, redundant on `net9.0`.
|
|
||||||
- **`Common.csproj`** has `<Folder Include="Interfaces\Extensions\" />` for a folder that does not exist.
|
|
||||||
- **`ClassIds`** should be `static class`; currently instantiable.
|
|
||||||
|
|
||||||
### 3. Testability
|
|
||||||
|
|
||||||
- Zero tests, zero test project.
|
|
||||||
- Business rules (balance calculation, FX conversion, bank-transaction matching, CSV export, split logic) are entangled with mutable singletons and side effects on returned entities.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Phased plan
|
|
||||||
|
|
||||||
### Phase 1 — Stop the bleeding (correctness, low churn)
|
|
||||||
|
|
||||||
1. ~~Change `ISettingsService` registration from `Singleton` to `Scoped`.~~ **Deferred.** `MyHeader.YearChanged` uses `NavigateTo(..., forceLoad: true)` after mutating settings, which tears down the SignalR circuit — a Scoped instance would be recreated with default values on the new circuit. Proper fix: persist the year/mandator selection to a cookie or query string, then Scoped becomes safe. Tracked as a new Phase 2 item.
|
|
||||||
2. Fix `TrySetYear` (capture `this.year` before overwriting). Defer the `ChartService` prior-year-loading pattern to Phase 3.
|
|
||||||
3. Fix `DummyFxService` typo (or delete the class and replace with a real `IFxService` implementation from `Schaad.Finance.Api`).
|
|
||||||
4. Remove mutation-on-read in `TransactionRepository.GetTransaction`, `ViewService.GetTransactionViewList(accountId)`, and `FileService.GetTransactionListCsv`.
|
|
||||||
5. Add a not-found guard to `TransactionRepository.GetTransaction`.
|
|
||||||
6. De-duplicate the DI registrations. One `AddAccounting()` extension called once in `Program.cs`.
|
|
||||||
7. Replace `.Class == 3/4` magic numbers with `ClassIds.*`. Update CLAUDE.md's incorrect ClassIds section.
|
|
||||||
8. Make XML writes atomic: write to `foo.xml.tmp` then `File.Move(..., overwrite: true)`. Wrap Load/Save in a per-file `SemaphoreSlim` (or a simple `lock`).
|
|
||||||
|
|
||||||
### Phase 2 — Structural cleanup
|
|
||||||
|
|
||||||
9. **Introduce a per-request unit of work / cache.** A scoped `IAccountingContext` that loads each XML file at most once per request and holds the deserialized lists.
|
|
||||||
10. Replace `Copy(target)` methods with a single merge-in-place pattern (or `record with`).
|
|
||||||
11. Extract shared formatting to a single `Formatting` helper.
|
|
||||||
12. Move `IFileService`, `IChartService`, `IViewService` out of `Common` (they depend on `Schaad.Finance.Api`). Common should have no vendor dependency.
|
|
||||||
13. Fix typos (`EnsureFileExists`, `SplitPredefinitionRepository`).
|
|
||||||
14. Move file existence bootstrapping out of constructors into a startup step (`IHostedService` or lazy first-use).
|
|
||||||
15. Fix `AccountRepository.EnsureFileExists` to compute the start-balance updates in memory and save once.
|
|
||||||
16. Remove legacy NuGet packages. Remove the stale `Interfaces\Extensions\` folder entry.
|
|
||||||
17. Set culture via `RequestLocalizationOptions` middleware.
|
|
||||||
18. Add `ILogger<T>` to services and repositories.
|
|
||||||
18b. Persist selected year and mandator across page reloads (cookie, query string, or `ProtectedLocalStorage`). Prerequisite for making `ISettingsService` `Scoped` (Phase 1 item 1, deferred).
|
|
||||||
|
|
||||||
### Phase 3 — Async & performance
|
|
||||||
|
|
||||||
19. Convert repository interfaces to async.
|
|
||||||
20. Cache the current view's data behind the scoped unit-of-work; invalidate on save.
|
|
||||||
21. Precompute `accountsById` and `subclassNameByNumber` dictionaries once per request.
|
|
||||||
22. Clean up `ChartService` prior-year loading pattern: introduce an explicit "load year data" helper instead of mutating `ISettingsService`.
|
|
||||||
|
|
||||||
### Phase 4 — Testability & safety net
|
|
||||||
|
|
||||||
23. Add a `Schaad.Accounting.Tests` xUnit project.
|
|
||||||
24. First tests: `ViewService.GetBalanceView`, `MatchBankTransactionByBookingRule` / `SameAccountsLastMonth`, `TransactionRepository` FX round-trip, `FileService.GetTransactionListCsv`.
|
|
||||||
25. Abstract the XML store (`IEntityStore<T>`) so tests use an in-memory store.
|
|
||||||
|
|
||||||
### Phase 5 — Nice-to-haves
|
|
||||||
|
|
||||||
26. Replace hand-written XML models with `record` types + source-generated serializers.
|
|
||||||
27. Inject Fixer.io key via `IOptions<FxSettings>` instead of threading through method params.
|
|
||||||
28. Prune unused Fluent UI packages.
|
|
||||||
29. Add a health/backup admin page.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## PR breakdown
|
|
||||||
|
|
||||||
- **PR A** — Phase 1 items 1–7 + CLAUDE.md fix.
|
|
||||||
- **PR B** — Phase 1 item 8 (atomic writes + lock).
|
|
||||||
- **PR C** — Phase 2 mechanical cleanup: items 11, 13, 15, 16, 17.
|
|
||||||
- **PR D** — Phase 2 item 9: per-request unit of work / cache. Split off from PR C because it is invasive enough to warrant its own review.
|
|
||||||
- **PR E** — Phase 3 item 22: ChartService cleanup. Promoted ahead of async because it fixes an active correctness bug — `GetAccountExpensesPerMonth(accountId, year)` was mutating `ISettingsService` on the singleton to hop years, with the year parameter always hardcoded to `DateTime.Now.Year`, so the Spendings-over-time chart discarded the user's header year selection.
|
|
||||||
- **PR F** — Phase 3 item 21: precomputed dictionaries in `ViewService` to eliminate O(N·M) `Single(...)` scans and per-account transaction filtering.
|
|
||||||
- **Item 19 (async I/O)** — landed as PR P after being explicitly requested. See PR P entry below.
|
|
||||||
- **PR G** — Phase 4 items 23 + 24: `Schaad.Accounting.Tests` xUnit + NSubstitute + Shouldly project. Adopts the `xxxTestShould.DoThisWhenThat` naming convention with Shouldly assertions (no xUnit `Assert.*`). Covers `ViewService`, `TransactionRepository`, `Formatting`, `RepositoryCache`, `AccountRepository`, `ChartService`, and `FileService.GetTransactionListCsv` — 38 tests locking in the earlier PRs' behavior. Note: originally shipped as three separate commits (initial project, expanded coverage, Shouldly + naming conversion) and later squashed into one commit at the user's request.
|
|
||||||
- **PR H** — Phase 2 item 18 (first slice): add `ILogger<FileService>` to `FileService.ImportAccountStatementFile` so bank-statement imports emit `Information` for the file being processed and each account's import count, `Warning` when an account is skipped because it belongs to a different mandator, and `Error` when the vendor parser reports a failure. Rest of the logging (BaseRepository save failures, MatchOpenBankTransactions summary) tracked as a follow-up because it requires threading loggers through all seven repositories.
|
|
||||||
- **PR I** — Phase 2 item 12: move the service interfaces (`IViewService`, `IFileService`, `IChartService`) from `Schaad.Accounting.Common` into `Schaad.Accounting.Services/Interfaces/`. Namespaces are unchanged (`Schaad.Accounting.Interfaces`), so no consumer needs a `using` update. Drops the `Schaad.Finance.Api` `<Reference>` from `Common.csproj` — Common is now vendor-free and matches its documented role as the "shared models, DTOs, interfaces" layer.
|
|
||||||
- **PR J** — Phase 2 item 18 (second slice): thread `ILogger<T>` through `BaseRepository` and every concrete repository so `BaseRepository.Save`'s catch block logs the failing file path and exception before rethrowing (previously the exception's origin was silently swallowed and only the stack trace at the callsite survived). Pulls `Microsoft.Extensions.Logging.Abstractions` into the Db project. `TransactionRepositoryTestShould` and `AccountRepositoryTestShould` use `NullLogger<T>.Instance`. Remaining item 18 work (MatchOpenBankTransactions match-count summary in `ViewService`) still open.
|
|
||||||
- **PR K** — Phase 5 item 27: introduce `IFxConverter.ConvertToChf(amount, fromCurrency)` and its `FxConverter` implementation. The vendor `IFxService` and the FixerIo API key are now hidden inside `FxConverter`; callers stop threading the API key through every method call. `ViewService` drops both `IFxService` and `ISettingsService` from its constructor and takes `IFxConverter` instead. Simplifies `GetAccountViewList` (no more per-call `settingsService.GetSettings()` reads) and `GetBalanceSheetView`. Two-test `FxConverterTestShould` locks in the target-currency and API-key routing.
|
|
||||||
- **PR L** — Phase 2 item 10: drop the hand-rolled `Copy(target)` methods from `Account`, `BookingRule`, `BookingText`, `SubClass`, and `SplitPredefinition`; keep only a `Transaction.Clone()` for defensive-copy needs in `GetTransaction` / `ViewService.WithDisplaySign`. Every `SaveXxx` now uses `FindIndex` → in-place replace (or `Add` for new entries), moving the two "hidden" defaults (`Account.Currency = "CHF"` when unset, `Transaction.BookingDate = ValueDate` when unset) into the corresponding `SaveXxx` method where they belong. Fixes a pre-existing bug: `Transaction.Copy` never copied `RelatedParty`, so update-saves silently dropped it. Added `PreserveRelatedPartyWhenRoundTrippingTransaction` and `DefaultBookingDateToValueDateWhenBookingDateIsUnset` as regression tests. 42 tests total.
|
|
||||||
- **PR M** — Phase 2 item 18 (final slice): add `ILogger<ViewService>` and log a match-count summary from `MatchOpenBankTransactions` (`"Matched {Matched} of {Total} open bank transactions"`). Completes item 18 — statement imports (PR H), repository save failures (PR J), and match runs now all emit structured logs. Also removes a dead `ISettingsService` injection from `Home.razor.cs` (declared with `[Inject]` but never used anywhere in the file).
|
|
||||||
- **PR N** — Small polish pass covering three long-noted rough edges from the original analysis: `ClassIds` becomes a `static class` (was instantiable); `Home.razor.cs` loses the redundant `loaded` guard in `OnInitializedAsync` (Blazor already runs that lifecycle hook once per component instance); the hardcoded `mandator = "Claudio Schaad"` in `SettingsService` moves to a `DefaultMandator` field on `SettingsDataset`, plumbed through `appsettings.Development.json`.
|
|
||||||
- **PR O** — Phase 5 item 26 (partial): convert `BalanceDataset` and `BalanceSheetDataset` to positional records. Both were constructor-initialised value carriers with read-only usage. The rest of item 26 was descoped: the XML-serialised domain models (`Account`, `Transaction`, ...) need mutable public setters for `XmlSerializer`, and value-equality on mutable data is a footgun (hash changes on mutation); source-generated XML serialisers do not exist without switching file formats. `DataSerie` was already a record; `MessageDataset` has a real mutation method (`Add`) and stays a class; `AccountDataset` / `TransactionDataset` / `BookingRuleDataset` inherit from the mutable domain models and can't cleanly become records without a bigger refactor.
|
|
||||||
- **PR P** — Phase 3 item 19: full async I/O top to bottom. `BaseRepository.LoadAsync/SaveAsync/LoadListAsync` return `Task<T>`; the per-file `lock (obj)` becomes `SemaphoreSlim` so it can be `await`-ed. `Save` serialises to a `MemoryStream` synchronously (XmlSerializer has no async form) then writes bytes with `File.WriteAllBytesAsync`; `File.Move` (atomic rename) has no async counterpart in .NET 9 and stays sync. Every repository interface + implementation, every service interface + implementation (except the vendor-owned `IFxService`), every Razor page/dialog `OnInitializedAsync`, and every test-file assertion becomes `async` / `await`. 51 files touched in one atomic diff — the codebase does not compile in intermediate states. `AccountRepository.EnsureAccountsFile` keeps two `.GetAwaiter().GetResult()` bridges because it runs from the constructor (constructors can't be async). The observed async payoff is one `File.ReadAllBytesAsync` and one `File.WriteAllBytesAsync` per Load/Save; after PR D each XML file is deserialised at most once per SignalR circuit, so on this single-user local Blazor Server app this is architectural-hygiene work, not a measurable perf win.
|
|
||||||
354
MCP_DESIGN.md
354
MCP_DESIGN.md
|
|
@ -1,354 +0,0 @@
|
||||||
# MCP server design
|
|
||||||
|
|
||||||
Design produced 2026-07-03 in conversation with Claude. Read alongside `IMPROVEMENT_PLAN.md`.
|
|
||||||
|
|
||||||
## Goals
|
|
||||||
|
|
||||||
- Let Claude answer questions like *"how much did I spend on groceries in Q1?"*, *"what's my current balance in CHF?"*, *"which recurring debits changed vs. last year?"*.
|
|
||||||
- **Read-only.** No `Save*`, `Delete*`, `Backup`, or `Import*` tools ever exposed.
|
|
||||||
- Reuse the async `ViewService` / repository stack already in the codebase. No parallel data layer.
|
|
||||||
- Local stdio transport. No HTTP, no auth surface. The MCP server process runs on your machine, but any field a tool returns is forwarded by the MCP client to whichever model it's paired with. See [Privacy modes](#privacy-modes) below for what that actually means in practice.
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
### Transport
|
|
||||||
|
|
||||||
- **Stdio JSON-RPC** via the official `ModelContextProtocol` .NET SDK (Microsoft org's MCP package). Console app, `Microsoft.Extensions.Hosting`-based, `[McpServerToolType]` + `[McpServerTool]` attributes.
|
|
||||||
- No custom framing/serialization — the SDK handles it.
|
|
||||||
|
|
||||||
### Project layout
|
|
||||||
|
|
||||||
```
|
|
||||||
Schaad.Accounting.Mcp/
|
|
||||||
├── Schaad.Accounting.Mcp.csproj - net9.0 console
|
|
||||||
├── Program.cs - host + DI + McpServer.CreateStdioServer
|
|
||||||
├── Context/
|
|
||||||
│ └── AccountingScope.cs - year/mandator switching (see below)
|
|
||||||
├── Dtos/
|
|
||||||
│ ├── AccountDto.cs - flat records for LLM consumption
|
|
||||||
│ ├── TransactionDto.cs
|
|
||||||
│ └── ...
|
|
||||||
└── Tools/
|
|
||||||
├── ContextTools.cs - list_mandators, list_years
|
|
||||||
├── AccountTools.cs - list_accounts, get_account
|
|
||||||
├── BalanceTools.cs - get_balance_summary, get_income_statement
|
|
||||||
├── TransactionTools.cs - get_transactions, search_transactions
|
|
||||||
└── AnalysisTools.cs - get_expenses_by_category, compare_years
|
|
||||||
```
|
|
||||||
|
|
||||||
### DI wiring
|
|
||||||
|
|
||||||
The composition root `AddAccounting()` currently lives in `Schaad.Accounting.UI/Extensions.cs`. Two options:
|
|
||||||
|
|
||||||
1. **Extract** to a new tiny `Schaad.Accounting.Composition` project that references Db + Services. UI and Mcp both reference it.
|
|
||||||
2. **Duplicate** the ~15-line registration block in `Mcp/Program.cs`.
|
|
||||||
|
|
||||||
Recommend **(1)** — with two composition roots, every subsequent DI change would otherwise need to touch both.
|
|
||||||
|
|
||||||
`Mcp/Program.cs` is then:
|
|
||||||
|
|
||||||
```csharp
|
|
||||||
var builder = Host.CreateApplicationBuilder(args);
|
|
||||||
builder.Services.Configure<SettingsDataset>(builder.Configuration.GetSection("Settings"));
|
|
||||||
builder.Services.AddSingleton(sp => sp.GetRequiredService<IOptions<SettingsDataset>>().Value);
|
|
||||||
builder.Services.AddAccounting();
|
|
||||||
|
|
||||||
builder.Services
|
|
||||||
.AddMcpServer()
|
|
||||||
.WithStdioServerTransport()
|
|
||||||
.WithToolsFromAssembly();
|
|
||||||
|
|
||||||
await builder.Build().RunAsync();
|
|
||||||
```
|
|
||||||
|
|
||||||
## Handling year/mandator
|
|
||||||
|
|
||||||
`SettingsService` is `Singleton` and holds `year` + `mandator`. The UI mutates them via `MyHeader` + `forceLoad`. There is no equivalent in stdio MCP.
|
|
||||||
|
|
||||||
**Approach: every tool takes optional `year` and `mandator`; wrap execution in a scope that stashes & restores.**
|
|
||||||
|
|
||||||
```csharp
|
|
||||||
public sealed class AccountingScope : IDisposable
|
|
||||||
{
|
|
||||||
private readonly ISettingsService settings;
|
|
||||||
private readonly int oldYear;
|
|
||||||
private readonly string oldMandator;
|
|
||||||
|
|
||||||
public AccountingScope(ISettingsService settings, int? year, string? mandator)
|
|
||||||
{
|
|
||||||
this.settings = settings;
|
|
||||||
oldYear = settings.GetYear();
|
|
||||||
oldMandator = settings.GetMandator();
|
|
||||||
if (year.HasValue) settings.SetYear(year.Value);
|
|
||||||
if (mandator is not null) settings.SetMandator(mandator);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
settings.SetYear(oldYear);
|
|
||||||
settings.SetMandator(oldMandator);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Every tool wraps its body:
|
|
||||||
|
|
||||||
```csharp
|
|
||||||
[McpServerTool, Description("...")]
|
|
||||||
public async Task<...> ListAccountsAsync(int? year = null, string? mandator = null, ...)
|
|
||||||
{
|
|
||||||
using var _ = new AccountingScope(settingsService, year, mandator);
|
|
||||||
// RepositoryCache is Scoped; resolve a fresh IServiceScope so scoped services
|
|
||||||
// don't hold references to entries from an earlier (year, mandator).
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Concurrency**: stdio MCP calls are serial (one JSON-RPC message at a time), so the Singleton mutation window is safe. If we ever move to HTTP transport with concurrent calls, this design breaks — flag that in code.
|
|
||||||
|
|
||||||
**Cache freshness**: `RepositoryCache` is `Scoped` and keyed by absolute file path (which includes `dbPath` → year+mandator). When the scope changes year/mandator, the cache keys naturally change too, so stale data is not returned. But we should still resolve a fresh `IServiceScope` per tool call:
|
|
||||||
|
|
||||||
```csharp
|
|
||||||
public class ToolExecutor
|
|
||||||
{
|
|
||||||
private readonly IServiceScopeFactory scopeFactory;
|
|
||||||
private readonly ISettingsService settings;
|
|
||||||
|
|
||||||
public async Task<T> Run<T>(int? year, string? mandator, Func<IServiceProvider, Task<T>> body)
|
|
||||||
{
|
|
||||||
using var _ = new AccountingScope(settings, year, mandator);
|
|
||||||
using var scope = scopeFactory.CreateScope();
|
|
||||||
return await body(scope.ServiceProvider);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Each tool class takes `ToolExecutor` and wraps its body.
|
|
||||||
|
|
||||||
## Tool catalog
|
|
||||||
|
|
||||||
Naming: `snake_case`. All optional args default sensibly. All amounts are `decimal`, CHF-normalized where a currency isn't specified. All dates are ISO 8601 (`yyyy-MM-dd`).
|
|
||||||
|
|
||||||
### `list_mandators`
|
|
||||||
|
|
||||||
> List the mandators (client accounting sets) that have data.
|
|
||||||
|
|
||||||
- **Input:** `{ year?: int }`
|
|
||||||
- **Output:** `{ mandators: string[] }`
|
|
||||||
|
|
||||||
### `list_years`
|
|
||||||
|
|
||||||
> List the years for which the given mandator has data.
|
|
||||||
|
|
||||||
- **Input:** `{ mandator?: string }`
|
|
||||||
- **Output:** `{ years: int[] }`
|
|
||||||
|
|
||||||
### `list_accounts`
|
|
||||||
|
|
||||||
> List all accounts with their current-year balance in both account currency and CHF. Use before `get_transactions` to look up account IDs.
|
|
||||||
|
|
||||||
- **Input:** `{ year?, mandator?, class?: "activa"|"passiva"|"income"|"expenses" }`
|
|
||||||
- **Output:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"accounts": [
|
|
||||||
{ "id": "...", "number": 1010, "name": "Checking", "currency": "CHF",
|
|
||||||
"class": "activa", "subclassName": "Umlaufvermögen",
|
|
||||||
"balance": 12345.67, "balanceChf": 12345.67 }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### `get_balance_summary`
|
|
||||||
|
|
||||||
> Total activa vs. total passiva, plus equity (activa − passiva). CHF.
|
|
||||||
|
|
||||||
- **Input:** `{ year?, mandator? }`
|
|
||||||
- **Output:** `{ totalActivaChf, totalPassivaChf, equityChf }`
|
|
||||||
|
|
||||||
### `get_income_statement`
|
|
||||||
|
|
||||||
> Income statement (Erfolgsrechnung) for the year: profit, loss, net, and the account list per side.
|
|
||||||
|
|
||||||
- **Input:** `{ year?, mandator? }`
|
|
||||||
- **Output:** `{ profitChf, lossChf, netChf, incomeAccounts: [...], expenseAccounts: [...] }`
|
|
||||||
|
|
||||||
### `get_transactions`
|
|
||||||
|
|
||||||
> Fetch transactions with filters. Prefer narrow filters — this is the main workhorse. Truncated at `limit` (default 200, max 1000).
|
|
||||||
|
|
||||||
- **Input:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"year": 2026,
|
|
||||||
"mandator": null,
|
|
||||||
"accountId": null,
|
|
||||||
"fromDate": "2026-01-01",
|
|
||||||
"toDate": "2026-03-31",
|
|
||||||
"textSearch": "coop",
|
|
||||||
"minAmount": 100,
|
|
||||||
"maxAmount": null,
|
|
||||||
"limit": 200
|
|
||||||
}
|
|
||||||
```
|
|
||||||
- **Output:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"transactions": [
|
|
||||||
{ "id": "...", "date": "2026-02-14", "bookingDate": "2026-02-14",
|
|
||||||
"text": "Coop City", "value": 87.30, "currency": "CHF",
|
|
||||||
"originAccountId": "chk", "originAccountName": "Checking",
|
|
||||||
"targetAccountId": "groc", "targetAccountName": "Groceries",
|
|
||||||
"relatedParty": "Coop Genossenschaft" }
|
|
||||||
],
|
|
||||||
"total": 47,
|
|
||||||
"truncated": false
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Backed by `ITransactionRepository.GetTransactionListAsync()` + in-memory filter — datasets are small enough that we don't need repo-level query pushdown.
|
|
||||||
|
|
||||||
### `get_expenses_by_category`
|
|
||||||
|
|
||||||
> Expenses grouped by subclass or account. Sorted descending by CHF total.
|
|
||||||
|
|
||||||
- **Input:** `{ year?, mandator?, groupBy?: "subclass" | "account" }`
|
|
||||||
- **Output:** `{ categories: [{ name, totalChf, transactionCount }] }`
|
|
||||||
|
|
||||||
### `compare_years`
|
|
||||||
|
|
||||||
> Side-by-side comparison for equivalent categories across years. Useful for *"how did my spending change YoY"*.
|
|
||||||
|
|
||||||
- **Input:** `{ years: int[], mandator?, side: "income" | "expenses" | "both" }`
|
|
||||||
- **Output:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"comparison": [
|
|
||||||
{ "year": 2025, "totalIncomeChf": ..., "totalExpensesChf": ...,
|
|
||||||
"byCategory": { "Groceries": 4800.50, "Rent": 24000, ... } },
|
|
||||||
{ "year": 2026, ... }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Output shape conventions
|
|
||||||
|
|
||||||
- **Flat records**: no nested navigation properties. Account name inlined next to id so the LLM doesn't need a follow-up call.
|
|
||||||
- **CHF-normalized**: any total is always in CHF. Per-transaction values keep the account currency plus the CHF equivalent when accounts differ.
|
|
||||||
- **No booleans for "successful"** — either the tool returns data or it errors. MCP has native error surfacing.
|
|
||||||
- **Cap collection sizes**: `get_transactions` truncates at `limit`; the LLM decides whether to narrow the filter.
|
|
||||||
|
|
||||||
## Read-only enforcement
|
|
||||||
|
|
||||||
- Repository / service **interfaces** still expose write methods (they're used from the UI). What's exposed is controlled by simply not authoring a `[McpServerTool]` for those verbs.
|
|
||||||
- To make this explicit, the `Tools/` folder contains **only read operations**, and typed errors (or similar) are the only way the LLM sees "no such account".
|
|
||||||
- **Do NOT expose `SetYear` / `SetMandator` as tools.** Year/mandator switching happens implicitly per-call via `AccountingScope`. Otherwise the LLM could clobber the UI's session state.
|
|
||||||
|
|
||||||
## Packaging & Claude Desktop
|
|
||||||
|
|
||||||
Build once:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
dotnet publish Schaad.Accounting.Mcp/ -c Release -o D:/AccountingMcp
|
|
||||||
```
|
|
||||||
|
|
||||||
Claude Desktop `claude_desktop_config.json`:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"mcpServers": {
|
|
||||||
"schaad-accounting": {
|
|
||||||
"command": "D:/AccountingMcp/Schaad.Accounting.Mcp.exe",
|
|
||||||
"env": {
|
|
||||||
"Settings__DataPath": "D:/Developer/AccountingData/",
|
|
||||||
"Settings__DefaultMandator": "Claudio Schaad"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`FixerIoApiKey` doesn't need to be set — MCP tools only ever need CHF conversions of stored CHF values, and `DummyFxService` is the current implementation.
|
|
||||||
|
|
||||||
## Security
|
|
||||||
|
|
||||||
- **Local stdio only.** No listening port. Anything running as your user can already read the XML files; MCP doesn't widen the local-attack blast radius.
|
|
||||||
- **`DataPath` only from environment / config.** Never accept `set_data_path` or similar. The LLM must not be able to point the server at arbitrary directories.
|
|
||||||
- **No write tools** — repeated deliberately because it's the single biggest risk mitigation.
|
|
||||||
- No secrets in tool outputs. The `FixerIoApiKey` is not returned by any tool.
|
|
||||||
- Data exposure to the model provider is a separate axis from local security. See [Privacy modes](#privacy-modes) below.
|
|
||||||
|
|
||||||
## Privacy modes
|
|
||||||
|
|
||||||
**The data-flow reality.** When Claude Desktop calls an MCP tool, the invocation and result are relayed through the Anthropic API so the model can reason over them. "Local stdio" only means the *server process* runs on your PC — the JSON payload it emits still crosses the network on its way to the model. Other MCP clients (Cursor, Zed, any hosted-model client) work the same way.
|
|
||||||
|
|
||||||
To make the trade-off explicit, the server supports three privacy modes via a `Mcp:Privacy` config key.
|
|
||||||
|
|
||||||
### `Full` (default)
|
|
||||||
|
|
||||||
Every tool from the catalog is registered. Tool results include per-transaction detail: text, related party, amount, dates, source/target account names. Most useful for open-ended questions, most exposing — a single `get_transactions` call can send hundreds of rows of counterparty/amount data to the model provider.
|
|
||||||
|
|
||||||
**Use when:** you're comfortable with the model provider's data-use policy on your account, and you want maximum answer quality.
|
|
||||||
|
|
||||||
### `Aggregate`
|
|
||||||
|
|
||||||
Only aggregate tools are registered:
|
|
||||||
|
|
||||||
- `list_accounts` — trimmed: name, currency, class, `balanceChf`. **No account IDs, no bank account numbers, no start balance.**
|
|
||||||
- `get_balance_summary`
|
|
||||||
- `get_income_statement` — trimmed: totals per class, no per-account rows.
|
|
||||||
- `get_expenses_by_category` — grouped by subclass name.
|
|
||||||
- `compare_years` — same as `Full`.
|
|
||||||
|
|
||||||
Withheld: `get_transactions` (entirely), per-account balance rows, related-party names, individual dates and texts.
|
|
||||||
|
|
||||||
**Use when:** you want spending/income insight without exposing individual counterparties or transaction narratives. Trades power for privacy — Claude can answer *"how did my grocery spending change YoY?"* but not *"what was that odd 850 CHF withdrawal in March?"*.
|
|
||||||
|
|
||||||
### `Local`
|
|
||||||
|
|
||||||
Same tool catalog as `Full`, but intended to be paired with a **local** MCP client — e.g. an Ollama- or LM-Studio-backed client that runs the model on your own machine. The MCP server itself doesn't and can't enforce this; the choice happens in which client you point at the server binary. Nothing crosses the network. Answer quality is lower than Claude, sometimes considerably.
|
|
||||||
|
|
||||||
**Use when:** you don't want any financial data leaving your PC at all.
|
|
||||||
|
|
||||||
### Configuring the mode
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"mcpServers": {
|
|
||||||
"schaad-accounting": {
|
|
||||||
"command": "D:/AccountingMcp/Schaad.Accounting.Mcp.exe",
|
|
||||||
"env": {
|
|
||||||
"Settings__DataPath": "D:/Developer/AccountingData/",
|
|
||||||
"Settings__DefaultMandator": "Claudio Schaad",
|
|
||||||
"Mcp__Privacy": "Aggregate"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`Program.cs` reads `Mcp:Privacy` at startup and decides which `[McpServerToolType]` classes to register with the SDK. Modes are enforced by *registration*, not by runtime filtering — a tool that's not registered simply doesn't exist from the model's point of view, so the model can't accidentally call it.
|
|
||||||
|
|
||||||
For belt-and-braces defence-in-depth, the sensitive-output DTOs (`TransactionDto`, per-account rows) can also live in a separate namespace whose types are only ever *constructed* by tools that are registered under `Full`; that way an accidentally shipped aggregate build won't compile against them.
|
|
||||||
|
|
||||||
## Out of scope for v1
|
|
||||||
|
|
||||||
- **Resources**: expose the chart of accounts as an MCP `Resource` so the LLM reads structure once instead of via `list_accounts` on every conversation.
|
|
||||||
- **Prompts**: prebuilt Claude prompts (*"Monatlicher Kassenbericht"*, *"Erklär mir das Q3-Wachstum"*).
|
|
||||||
- **Bank-transaction matching preview**: expose the `MatchOpenBankTransactions` output as a read-only tool so Claude can review the auto-matcher's guesses.
|
|
||||||
- **Budgets / alerts**: not modelled in the app yet, so no data to expose.
|
|
||||||
|
|
||||||
## Rough implementation size
|
|
||||||
|
|
||||||
- New project + csproj + Program.cs: ~40 LOC
|
|
||||||
- `AccountingScope` + `ToolExecutor`: ~40 LOC
|
|
||||||
- 8 tools with DTOs: ~350 LOC (mostly declarative attribute schemas + `Select` projections)
|
|
||||||
- Extract `AddAccounting()` to `Composition` project: ~30 LOC (mostly moving)
|
|
||||||
- **Total: ~450 LOC**, plus config/docs.
|
|
||||||
|
|
||||||
## Suggested PR sequencing
|
|
||||||
|
|
||||||
- **PR Q** — Extract `AddAccounting()` from `Schaad.Accounting.UI/Extensions.cs` to a new `Schaad.Accounting.Composition` project referenced by UI and Mcp. Mechanical, low risk.
|
|
||||||
- **PR R** — Add the `Schaad.Accounting.Mcp` project with `Program.cs`, `AccountingScope`, `ToolExecutor`, and the first two tools (`list_mandators`, `list_accounts`). Enough to wire Claude Desktop and iterate on the actual conversation feel before adding analytics tools.
|
|
||||||
- **PR S** — Balance + income statement tools (`get_balance_summary`, `get_income_statement`).
|
|
||||||
- **PR T** — `get_transactions` (the workhorse) with filter validation and truncation.
|
|
||||||
- **PR U** — Analytics (`get_expenses_by_category`, `compare_years`).
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
|
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
|
||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
|
||||||
<RootNamespace>Schaad.Accounting</RootNamespace>
|
<RootNamespace>Schaad.Accounting</RootNamespace>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
</Project>
|
</Project>
|
||||||
|
|
@ -1,14 +1,10 @@
|
||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Schaad.Accounting.Common\Schaad.Accounting.Common.csproj" />
|
<ProjectReference Include="..\Schaad.Accounting.Common\Schaad.Accounting.Common.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.9" />
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,8 @@
|
||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="FreeSpire.PDF" Version="10.2.0" />
|
<PackageReference Include="FreeSpire.PDF" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.9" />
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Schaad.Accounting.Common\Schaad.Accounting.Common.csproj" />
|
<ProjectReference Include="..\Schaad.Accounting.Common\Schaad.Accounting.Common.csproj" />
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,24 @@
|
||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<IsPackable>false</IsPackable>
|
<IsPackable>false</IsPackable>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="coverlet.collector" Version="6.0.2" />
|
<PackageReference Include="coverlet.collector">
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
<PackageReference Include="NSubstitute" Version="5.3.0" />
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<PackageReference Include="Shouldly" Version="4.3.0" />
|
</PackageReference>
|
||||||
<PackageReference Include="xunit" Version="2.9.2" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
|
<PackageReference Include="NSubstitute" />
|
||||||
|
<PackageReference Include="Shouldly" />
|
||||||
|
<PackageReference Include="xunit" />
|
||||||
|
<PackageReference Include="xunit.runner.visualstudio">
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
</PackageReference>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|
|
||||||
|
|
@ -32,7 +32,7 @@ public partial class BookingRuleDialog : ComponentBase
|
||||||
|
|
||||||
private async Task SaveAsync()
|
private async Task SaveAsync()
|
||||||
{
|
{
|
||||||
if (editContext.Validate())
|
if (editContext is not null && editContext.Validate())
|
||||||
{
|
{
|
||||||
await bookingRuleRepository.SaveBookingRuleAsync(Content);
|
await bookingRuleRepository.SaveBookingRuleAsync(Content);
|
||||||
await Dialog.CloseAsync(Content);
|
await Dialog.CloseAsync(Content);
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ namespace Schaad.Accounting.UI
|
||||||
// Singleton because MyHeader triggers a full page reload (forceLoad: true) after
|
// Singleton because MyHeader triggers a full page reload (forceLoad: true) after
|
||||||
// changing year/mandator; a Scoped instance would be recreated on the new circuit
|
// changing year/mandator; a Scoped instance would be recreated on the new circuit
|
||||||
// and lose the selection. TODO: persist selection to a cookie/query string so this
|
// and lose the selection. TODO: persist selection to a cookie/query string so this
|
||||||
// can safely become Scoped (see IMPROVEMENT_PLAN.md).
|
// can safely become Scoped.
|
||||||
services.AddSingleton<ISettingsService, SettingsService>();
|
services.AddSingleton<ISettingsService, SettingsService>();
|
||||||
|
|
||||||
services.AddScoped<RepositoryCache>();
|
services.AddScoped<RepositoryCache>();
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
@ -22,10 +21,10 @@
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.FluentUI.AspNetCore.Components" Version="4.11.8" />
|
<PackageReference Include="Microsoft.FluentUI.AspNetCore.Components" />
|
||||||
<PackageReference Include="Microsoft.FluentUI.AspNetCore.Components.Emoji" Version="4.11.8" />
|
<PackageReference Include="Microsoft.FluentUI.AspNetCore.Components.Emoji" />
|
||||||
<PackageReference Include="Microsoft.FluentUI.AspNetCore.Components.Icons" Version="4.11.8" />
|
<PackageReference Include="Microsoft.FluentUI.AspNetCore.Components.Icons" />
|
||||||
<PackageReference Include="Plotly.Blazor" Version="6.0.1" />
|
<PackageReference Include="Plotly.Blazor" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|
|
||||||
|
|
@ -1,202 +0,0 @@
|
||||||
# UI improvement plan
|
|
||||||
|
|
||||||
Analysis produced 2026-07-03. Focused on Blazor UI concerns; the `IMPROVEMENT_PLAN.md` covered service/repository layers.
|
|
||||||
|
|
||||||
## 1. Real bugs
|
|
||||||
|
|
||||||
### 1.1 `TransactionDialog.SaveAsync` will NRE if the date picker is cleared
|
|
||||||
|
|
||||||
`TransactionDialog.razor.cs:37-40`:
|
|
||||||
|
|
||||||
```csharp
|
|
||||||
if (editContext.Validate())
|
|
||||||
{
|
|
||||||
Content.ValueDate = SelectedValue!.Value; // SelectedValue is DateTime?
|
|
||||||
Content.BookingDate = SelectedValue!.Value;
|
|
||||||
...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`SelectedValue!.Value` throws `InvalidOperationException` if the user opened the dialog, cleared the date, and hit Speichern.
|
|
||||||
|
|
||||||
### 1.2 `TransactionSplitDialog` only validates the first split row
|
|
||||||
|
|
||||||
`TransactionSplitDialog.razor.cs:50` builds an `EditContext` around the *first* transaction only. When the user adds a split row, subsequent rows have no `EditContext` — `editContext.Validate()` in `SaveAsync` returns true for the first row and completely ignores the rest. Empty text / wrong account on split rows never fails validation.
|
|
||||||
|
|
||||||
### 1.3 `AccountSelector` doesn't react to `Accounts` arriving late
|
|
||||||
|
|
||||||
`AccountSelector.razor.cs:17-20`:
|
|
||||||
|
|
||||||
```csharp
|
|
||||||
protected override void OnInitialized()
|
|
||||||
{
|
|
||||||
SelectedAccount = Accounts.FirstOrDefault(account => account.Id == AccountId);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
`OnInitialized` fires once. If the parent's `Accounts` list is empty at that point (the async path introduced in PR P) and hydrates later, `SelectedAccount` stays `null` and the typeahead shows no preselection. Should be `OnParametersSet`.
|
|
||||||
|
|
||||||
### 1.4 The whole "year/mandator via `forceLoad`" architecture
|
|
||||||
|
|
||||||
`MyHeader.YearChanged` calls `NavigateTo(..., forceLoad: true)`. `Home.SplitBankTransactionAsync` and `Home.ReloadPage()` do the same after any successful split. `SettingsService` is `Singleton` (documented in `Extensions.cs`) *because* the state has to survive that reload.
|
|
||||||
|
|
||||||
Symptoms:
|
|
||||||
|
|
||||||
- **Full HTTP round-trip** on every year/mandator switch, every split save. Tears down the SignalR circuit, blows away the scoped `RepositoryCache`, re-runs every repo constructor.
|
|
||||||
- **No URL-bookmarkable state** — you can't send yourself a link to "2023 / Mandator X".
|
|
||||||
- **Multi-user hazard** (already documented — single-user in practice, but the design is fragile if that ever changes).
|
|
||||||
- **Client-side state loss** — filters, scroll positions, half-typed inputs.
|
|
||||||
|
|
||||||
## 2. First-render null trap (partially patched, still fragile)
|
|
||||||
|
|
||||||
PR P's follow-up added `@if (accounts is null) { <p>Lädt…</p> return; }` sprinkled across ~11 pages/dialogs. Works but:
|
|
||||||
|
|
||||||
- Every page rolls its own guard. Sometimes it's `@if (balance is null)`, sometimes `@if (accounts is null || transactions is null)`, sometimes `@if (config is not null && layout is not null && data is not null) { <PlotlyChart .../> }`.
|
|
||||||
- No shared skeleton visual — just `<p>Lädt…</p>`. Feels unfinished.
|
|
||||||
- Collection fields are initialised to `[]` in some pages and left nullable in others. Two idioms in the same codebase.
|
|
||||||
|
|
||||||
A shared `<LoadingWhen Data="@x" />` wrapper with a consistent skeleton visual would centralize this.
|
|
||||||
|
|
||||||
## 3. `Home.razor` is doing too much
|
|
||||||
|
|
||||||
100 lines of markup + 190-line codebehind for four unrelated concerns on the landing page:
|
|
||||||
|
|
||||||
1. **Statement upload** — `FluentInputFile`, progress bar, cancel button.
|
|
||||||
2. **XML/zip file processing** — `OnCompletedAsync`, unzip, iterate.
|
|
||||||
3. **Auto-matched bank transactions table** — hand-crafted `<table>`, `<input list="texts">` for autocomplete, per-row book / split buttons.
|
|
||||||
4. **Booking / split flow** — `BookBankTransactionAsync`, `SplitBankTransactionAsync`.
|
|
||||||
|
|
||||||
Split into `<StatementImport />` and `<PendingBookings />`; Home stacks them.
|
|
||||||
|
|
||||||
## 4. Reports vs. list pages use different visual languages
|
|
||||||
|
|
||||||
- **List pages** (Accounts, BookingRules, BookingTexts, Transactions, BankTransactions): `<FluentDataGrid>` with `<PropertyColumn>` / `<TemplateColumn>`, pagination, sortable headers.
|
|
||||||
- **Reports** (BalanceReport, BalanceSheetReport, DetailReport, ProfitLossReport): hand-rolled `<table class="report">` with `@if (account.Balance == 0) { continue; }` inside `<tr>` and hand-crafted section headers.
|
|
||||||
|
|
||||||
Two different visual languages. Report format is domain-appropriate (they're printed accounting statements, not grids), but the hand-rolled markup means:
|
|
||||||
|
|
||||||
- Adding a column means editing 4 report `.razor` files.
|
|
||||||
- The `@if ... { continue; }` pattern inside `<tr>` reads oddly.
|
|
||||||
- No component reuse across reports.
|
|
||||||
|
|
||||||
Extract `<ReportSection Title="…">`, `<ReportAccountRow Account="@x" ShowBalance />`, `<ReportTotalRow Label="…" Value="…" />`.
|
|
||||||
|
|
||||||
## 5. No error boundaries, no expected-error UX
|
|
||||||
|
|
||||||
If any component throws, users get `blazor-error-ui` at the bottom of `MainLayout.razor` — a fixed div with *"An unhandled error has occurred. Reload."* No route back except manual reload. `Error.razor` is the default template that tells the user to enable Development mode.
|
|
||||||
|
|
||||||
For expected failures (save failed because file locked, unknown id on delete):
|
|
||||||
|
|
||||||
- Wrap each page/section in `<ErrorBoundary>` with a friendly retry.
|
|
||||||
- Route repository/service exceptions through `IMessageService` / `IToastService` (both already registered) instead of letting them bubble.
|
|
||||||
|
|
||||||
## 6. Feedback after mutations is invisible
|
|
||||||
|
|
||||||
`Accounts.EditAsync` closes the dialog and re-fetches the list. No confirmation, no "Saved" toast. If the list is long and the user's edit isn't visible in the current page, they have no signal the save worked.
|
|
||||||
|
|
||||||
Same in `BookingRules`, `BookingTexts`, `Classes`, `Transactions`.
|
|
||||||
|
|
||||||
Add `toastService.ShowSuccess("Konto gespeichert")` etc.
|
|
||||||
|
|
||||||
## 7. Confirmation dialogs show unformatted values
|
|
||||||
|
|
||||||
`Transactions.DeleteAsync`:
|
|
||||||
|
|
||||||
```csharp
|
|
||||||
$"Transaction '{transaction.Text}' mit Betrag {transaction.Value} wirklich löschen?"
|
|
||||||
```
|
|
||||||
|
|
||||||
`transaction.Value` is a raw decimal — no currency, no thousands separator. Reads *"...mit Betrag 1234.567 wirklich löschen?"*. Should use `.ToFormattedString()` and append the currency.
|
|
||||||
|
|
||||||
Same in `Accounts.DeleteAsync`, `BookingRules.DeleteAsync`, `BookingTexts.DeleteAsync`, `Classes.DeleteAsync`.
|
|
||||||
|
|
||||||
## 8. No search / filter on list pages
|
|
||||||
|
|
||||||
None of the FluentDataGrid pages have search or filter controls — only pagination.
|
|
||||||
|
|
||||||
- BookingRules can grow to hundreds of entries.
|
|
||||||
- BookingTexts likewise.
|
|
||||||
- BankTransactions runs into thousands over a year.
|
|
||||||
|
|
||||||
`<FluentSearch>` bound to a `filter` field, filter the `IQueryable` before passing to the grid.
|
|
||||||
|
|
||||||
## 9. Dialogs are fixed-height
|
|
||||||
|
|
||||||
`DialogParameters { Height = "500px" }` on every dialog. Content shorter than 500px wastes space; content longer scrolls inside. Should be `Height = "auto"`.
|
|
||||||
|
|
||||||
Also every dialog uses the same header icon (`Icons.Regular.Size24.WindowApps` — a generic "window" glyph). No visual distinction between dialog types.
|
|
||||||
|
|
||||||
## 10. `AccountSelector` uses `Autofocus="true"`
|
|
||||||
|
|
||||||
Fine for the split-dialog flow. In the Home booking table it means every keystroke-navigated row grabs focus from wherever the user was. Should be an opt-in parameter, off by default.
|
|
||||||
|
|
||||||
## 11. Header year/mandator has no confirm on change
|
|
||||||
|
|
||||||
`MyHeader.YearChanged` immediately does a `forceLoad`. If the user accidentally clicks 2018 in the dropdown, whatever they were doing (unsaved dialog, half-typed booking) is gone. Fixed once (1.4) is fixed.
|
|
||||||
|
|
||||||
## 12. Minor rough edges
|
|
||||||
|
|
||||||
- `Home.razor.cs` field name `IsCanceled` describes an intent, not a state — `cancelRequested` would be clearer.
|
|
||||||
- `Home.razor:35` shows a smiley emoji when no pending bookings.
|
|
||||||
- `Home.razor:67` uses `<input list="texts">` + `<datalist>` for text autocomplete — native HTML, inconsistent with `FluentAutocomplete` used in `AccountSelector`.
|
|
||||||
- Print CSS in `app.css` only hides `.hidePrint`. No `@page`, no `page-break-inside: avoid` on report rows. Long reports fragment across pages randomly.
|
|
||||||
- No accessible label on the delete/edit icon buttons (screen readers say "Button, button").
|
|
||||||
- The header ` $"{title} {mandator} {year}"` in `Report.cs` reads like *"Bilanz Claudio Schaad 2026"* — no separator, no branding.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Suggested phased plan
|
|
||||||
|
|
||||||
Sequenced by value / risk. Each is one PR unless noted.
|
|
||||||
|
|
||||||
### Phase 1 — Correctness bugs (low risk, high value)
|
|
||||||
|
|
||||||
- **U-1** Fix `AccountSelector` to use `OnParametersSet` instead of `OnInitialized` so the preselection tracks late-arriving `Accounts`.
|
|
||||||
- **U-2** Guard `TransactionDialog.SaveAsync` against `SelectedValue == null`; disable Save when the date is empty.
|
|
||||||
- **U-3** Fix `TransactionSplitDialog` validation to cover every row (per-row `EditContext`, or one `EditContext` over a wrapper).
|
|
||||||
|
|
||||||
### Phase 2 — The forceLoad/singleton trap (biggest single improvement)
|
|
||||||
|
|
||||||
Split into two PRs on delivery because the header path touches ~15 pages.
|
|
||||||
|
|
||||||
- **U-4a** Fix `Home.ReloadPage()` — the single non-settings `forceLoad` in the app. `SplitBankTransactionAsync` and `OnCompletedAsync` (statement import) now call a shared `LoadDataAsync()` that re-runs the auto-matcher, re-fetches accounts and booking texts in place, and keeps the SignalR circuit + scoped `RepositoryCache` alive. No cross-cutting scaffolding needed.
|
|
||||||
- **U-4b** Persist year and mandator (cookie + URL query params), make `SettingsService` `Scoped`, add an event or `LocationChanged` subscription so every page refreshes on year/mandator change, and drop `MyHeader`'s `forceLoad`. This is the big one — it touches every routable page.
|
|
||||||
|
|
||||||
### Phase 3 — Loading and error UX consistency
|
|
||||||
|
|
||||||
- **U-5** Shared `<LoadingWhen Data="@x">` component with a consistent skeleton visual. Adopt across every page currently using ad-hoc `@if (x is null) { <p>Lädt…</p> return; }`.
|
|
||||||
- **U-6a** Wrap `MainLayout`'s `@Body` in `<ErrorBoundary>` with a friendly retry UI. Reset on any `NavigationManager.LocationChanged` so the error state doesn't stick after the user clicks "Zur Startseite".
|
|
||||||
- **U-6b** Route expected `SaveTransactionAsync` / `DeleteAccountAsync` / etc. exceptions to `IMessageService` — try/catch in each of the ~15 event handlers with a shared error-formatting helper.
|
|
||||||
|
|
||||||
### Phase 4 — Feedback + polish for mutations
|
|
||||||
|
|
||||||
- **U-7** `IToastService.ShowSuccess(...)` after every successful save/delete across Accounts, BookingRules, BookingTexts, Classes, Transactions.
|
|
||||||
- **U-8** Format the raw decimal in Transactions' delete confirmation via `ToFormattedString()`, and fix the "Transaction" → "Transaktion" typo. Turned out to be a one-file change — the other four CRUD pages don't put values into confirmations.
|
|
||||||
- **U-9** Add `<FluentSearch>` filter to Accounts, BookingRules, BookingTexts, BankTransactions.
|
|
||||||
|
|
||||||
### Phase 5 — Home page split
|
|
||||||
|
|
||||||
- **U-10** Extract `<StatementImport />` and `<PendingBookings />` components. Home stacks them.
|
|
||||||
- **U-11** ~~Replace the Home `<input list="texts">` + `<datalist>` with `FluentAutocomplete`.~~ **Won't do.** Two attempts, both broke the UI:
|
|
||||||
- Attempt 1 (`ceef2c1`, reverted in `2522274`): `FluentCombobox` with `Autocomplete=Both`, a computed-getter `Items` source (fresh `IEnumerable` per access), and inline `@(t => t)` delegates. Suspected root cause: per-render parameter churn triggering re-init inside every row's Combobox, flooding the SignalR circuit.
|
|
||||||
- Attempt 2 (branch `refactor/pr-u11b-retry`, never merged): all three suspected causes fixed — `sortedBookingTexts` materialised into a real field populated in `LoadDataAsync`, `OptionText`/`OptionValue` extracted to `static readonly Func<string, string>`, `Autocomplete` downgraded to `List`. Same UI lockup.
|
|
||||||
|
|
||||||
Conclusion: `FluentCombobox` in Fluent UI Blazor 4.11.8 is not usable inside a per-row `@foreach` on a Blazor Server page with more than a handful of rows, independent of parameter stability. The native `<input list>` + `<datalist>` stays. If someone wants Fluent styling later, options that avoid the per-row Fluent component are: (a) a lightly-styled `<input>` wrapped in Fluent's CSS classes; (b) rendering the suggestions as a single shared component with a `TextChanged` callback that updates the row's `Text` field.
|
|
||||||
|
|
||||||
### Phase 6 — Report componentization
|
|
||||||
|
|
||||||
- **U-12** Extract `<ReportSection>`, `<ReportAccountRow>`, `<ReportSectionHeader>`, `<ReportTotalRow>`, `<ReportFooter>`. Apply to the four report pages. Shared print CSS + `page-break-inside: avoid` on rows.
|
|
||||||
|
|
||||||
### Phase 7 — Nice-to-haves (optional)
|
|
||||||
|
|
||||||
- Accessibility: `aria-label` on icon-only buttons, focus management after dialog close, skip-to-content link.
|
|
||||||
- Dark mode toggle (Fluent supports theme override).
|
|
||||||
- Keyboard: `Ctrl+S` in dialogs, `Del` on selected row in grids.
|
|
||||||
- Header format: nicer separator + optional subtitle.
|
|
||||||
- `AccountSelector`'s `Autofocus` becomes opt-in.
|
|
||||||
|
|
||||||
## What was explicitly *not* flagged
|
|
||||||
|
|
||||||
- The `de-CH` culture hardcode. Correct choice for the target user; localizing is a lot of work for zero user value.
|
|
||||||
- The `InteractiveServer` render mode. Correct for this app.
|
|
||||||
- The Fluent UI dependency.
|
|
||||||
6
global.json
Normal file
6
global.json
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
{
|
||||||
|
"sdk": {
|
||||||
|
"version": "10.0.100",
|
||||||
|
"rollForward": "latestFeature"
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue