## 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>
145 lines
5.4 KiB
C#
145 lines
5.4 KiB
C#
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using System.Text.Json;
|
|
using Microsoft.Extensions.Logging;
|
|
using Schaad.Accounting.Interfaces;
|
|
|
|
namespace Schaad.Accounting.Repositories
|
|
{
|
|
public abstract class BaseRepository
|
|
{
|
|
// One semaphore per absolute file path so concurrent SaveAsync+SaveAsync and
|
|
// SaveAsync+LoadAsync are serialized and can't observe a half-written file.
|
|
private static readonly ConcurrentDictionary<string, SemaphoreSlim> FileLocks =
|
|
new(StringComparer.OrdinalIgnoreCase);
|
|
|
|
protected readonly ISettingsService settingsService;
|
|
protected readonly RepositoryCache cache;
|
|
protected readonly ILogger logger;
|
|
|
|
protected BaseRepository(ISettingsService settingsService, RepositoryCache cache, ILogger logger)
|
|
{
|
|
this.settingsService = settingsService;
|
|
this.cache = cache;
|
|
this.logger = logger;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Copies fileName from last year's directory to the current year's directory when the
|
|
/// current year doesn't have it yet. Kept synchronous because it runs from repository
|
|
/// constructors; File.Copy has no async equivalent in .NET 9 either way.
|
|
/// </summary>
|
|
protected void EnsureFileExists(string fileName)
|
|
{
|
|
string filePath = Path.Combine(settingsService.GetDbPath(), fileName);
|
|
var semaphore = GetLock(filePath);
|
|
semaphore.Wait();
|
|
try
|
|
{
|
|
if (File.Exists(filePath) == false)
|
|
{
|
|
var lastYearFile = Path.Combine(settingsService.GetLastYearDbPath(), fileName);
|
|
if (File.Exists(lastYearFile))
|
|
{
|
|
File.Copy(lastYearFile, filePath);
|
|
}
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
semaphore.Release();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Load a list, cached per scope. First call reads the JSON file; subsequent calls in
|
|
/// the same scope return the cached list. <see cref="SaveAsync"/> invalidates the entry.
|
|
/// </summary>
|
|
protected Task<List<T>> LoadListAsync<T>(string fileName)
|
|
=> LoadListAsync<T>(settingsService.GetDbPath(), fileName);
|
|
|
|
/// <summary>
|
|
/// Same as <see cref="LoadListAsync{T}(string)"/> for a file in any data directory (e.g.
|
|
/// another year). Shares the cache, which is keyed by absolute path, so a save in the
|
|
/// current year also invalidates readers of that year.
|
|
/// </summary>
|
|
protected Task<List<T>> LoadListAsync<T>(string directory, string fileName)
|
|
{
|
|
var filePath = Path.Combine(directory, fileName);
|
|
return cache.GetOrLoadAsync(filePath, async () => await LoadFileAsync<List<T>>(filePath) ?? new List<T>());
|
|
}
|
|
|
|
/// <summary>
|
|
/// Save an object to a JSON file. Writes to a .tmp sibling and then atomically
|
|
/// renames it, so a crash mid-write leaves the previous file intact. Invalidates
|
|
/// the corresponding cache entry.
|
|
/// </summary>
|
|
protected async Task SaveAsync<T>(T obj, string fileName)
|
|
{
|
|
var filePath = Path.Combine(settingsService.GetDbPath(), fileName);
|
|
var tmpPath = filePath + ".tmp";
|
|
|
|
var semaphore = GetLock(filePath);
|
|
await semaphore.WaitAsync();
|
|
try
|
|
{
|
|
try
|
|
{
|
|
await File.WriteAllBytesAsync(tmpPath, JsonSerializer.SerializeToUtf8Bytes(obj, JsonStorage.Options));
|
|
|
|
// File.Move has no async form in .NET 9.
|
|
File.Move(tmpPath, filePath, overwrite: true);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "Failed to save {FilePath}", filePath);
|
|
if (File.Exists(tmpPath))
|
|
{
|
|
try { File.Delete(tmpPath); } catch { /* best effort */ }
|
|
}
|
|
throw;
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
semaphore.Release();
|
|
}
|
|
|
|
cache.Invalidate(filePath);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Load an object from a JSON file (uncached; used for one-off reads such as file
|
|
/// existence bootstrapping). Prefer <see cref="LoadListAsync{T}"/> for repository reads.
|
|
/// </summary>
|
|
protected Task<T> LoadAsync<T>(string fileName)
|
|
=> LoadFileAsync<T>(Path.Combine(settingsService.GetDbPath(), fileName));
|
|
|
|
private static async Task<T> LoadFileAsync<T>(string filePath)
|
|
{
|
|
var semaphore = GetLock(filePath);
|
|
await semaphore.WaitAsync();
|
|
try
|
|
{
|
|
if (File.Exists(filePath) == false)
|
|
{
|
|
return default(T);
|
|
}
|
|
|
|
await using var stream = File.OpenRead(filePath);
|
|
return await JsonSerializer.DeserializeAsync<T>(stream, JsonStorage.Options);
|
|
}
|
|
finally
|
|
{
|
|
semaphore.Release();
|
|
}
|
|
}
|
|
|
|
private static SemaphoreSlim GetLock(string filePath)
|
|
=> FileLocks.GetOrAdd(filePath, _ => new SemaphoreSlim(1, 1));
|
|
}
|
|
}
|