AccountingNext/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.cs
Claudio Schaad 2bc32e9746 Add Analyse page: expenses over all years with drill-down (#4)
## 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>
2026-10-22 14:02:08 +00:00

212 lines
7.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Globalization;
using Microsoft.AspNetCore.Components;
using Schaad.Accounting.Datasets.Analytics;
using Schaad.Accounting.Interfaces;
using Schaad.Accounting.Services;
using Schaad.Accounting.UI.Components.Pages.Charts;
namespace Schaad.Accounting.UI.Components.Pages.Analytics;
/// <summary>
/// Expenses of the selected mandator over all years, with drill-down
/// all → subclass → account → booking-text group. Every filter and the drill-down position
/// live in the URL, so back/forward and bookmarks work; the data is loaded once and every
/// change is an in-memory query.
/// </summary>
public partial class Analytics : ComponentBase
{
private static readonly CultureInfo Swiss = new("de-CH");
private static readonly AnalyticsPeriod[] Periods = [AnalyticsPeriod.Month, AnalyticsPeriod.Quarter, AnalyticsPeriod.Year];
[Inject]
private IAnalyticsService analyticsService { get; set; } = null!;
[Inject]
private ISettingsService settingsService { get; set; } = null!;
[Inject]
private NavigationManager navigation { get; set; } = null!;
[SupplyParameterFromQuery(Name = "from")]
public int? From { get; set; }
[SupplyParameterFromQuery(Name = "to")]
public int? To { get; set; }
[SupplyParameterFromQuery(Name = "period")]
public string? Period { get; set; }
[SupplyParameterFromQuery(Name = "sub")]
public int? Sub { get; set; }
[SupplyParameterFromQuery(Name = "acc")]
public int? Acc { get; set; }
[SupplyParameterFromQuery(Name = "text")]
public string? Text { get; set; }
private string mandator = "";
private ExpenseAnalysis? analysis;
private AnalyticsResult? result;
private AnalyticsNode node = AnalyticsNode.All;
private int fromYear;
private int toYear;
private AnalyticsPeriod period;
private IReadOnlyList<string> chartLabels = [];
private IReadOnlyList<ChartSeries> chartSeries = [];
// Category behind each chart series; null for the folded "Andere" series.
private List<AnalyticsCategory?> seriesCategories = [];
private int coloredCount;
protected override async Task OnInitializedAsync()
{
mandator = settingsService.GetMandator();
analysis = await analyticsService.GetExpenseAnalysisAsync();
}
protected override void OnParametersSet()
{
if (analysis is null || analysis.Years.Count == 0)
{
return;
}
var years = analysis.Years;
fromYear = Math.Clamp(From ?? years[0], years[0], years[^1]);
toYear = Math.Clamp(To ?? years[^1], years[0], years[^1]);
if (fromYear > toYear)
{
(fromYear, toYear) = (toYear, fromYear);
}
period = ParsePeriod(Period) ?? (fromYear == toYear ? AnalyticsPeriod.Month : AnalyticsPeriod.Quarter);
node = Acc is { } account ? new AnalyticsNode(account / 100, account, Text)
: Sub is { } subClass ? new AnalyticsNode(subClass)
: AnalyticsNode.All;
result = analysis.Query(new AnalyticsQuery(fromYear, toYear, period, node));
BuildChart(result);
}
private void BuildChart(AnalyticsResult data)
{
chartLabels = data.Periods.Select(PeriodLabel).ToList();
// Same folding as the other charts: past MaxCategories, the tail becomes "Andere".
var categories = data.Categories;
coloredCount = categories.Count > ChartTheme.MaxCategories ? ChartTheme.MaxCategories - 1 : categories.Count;
var series = new List<ChartSeries>();
seriesCategories = [];
for (var i = 0; i < coloredCount; i++)
{
var category = categories[i];
series.Add(new ChartSeries(category.Name, ChartTheme.ColorAt(i), category.Values, category.CanDrillDown));
seriesCategories.Add(category);
}
if (coloredCount < categories.Count)
{
var other = new decimal[data.Periods.Count];
foreach (var category in categories.Skip(coloredCount))
{
for (var p = 0; p < other.Length; p++)
{
other[p] += category.Values[p];
}
}
series.Add(new ChartSeries(ChartTheme.OtherLabel, ChartTheme.OtherColor, other, Clickable: false));
seriesCategories.Add(null);
}
chartSeries = series;
}
private void OnSeriesClick(int seriesIndex)
{
if (seriesCategories.ElementAtOrDefault(seriesIndex) is { CanDrillDown: true } category)
{
navigation.NavigateTo(NodeUrl(category.Node));
}
}
private void OnFromChanged(int year)
{
if (year != fromYear)
{
navigation.NavigateTo(Url(node, year, year > toYear ? year : To, Period));
}
}
private void OnToChanged(int year)
{
if (year != toYear)
{
navigation.NavigateTo(Url(node, year < fromYear ? year : From, year, Period));
}
}
private void ShowAllYears() => navigation.NavigateTo(Url(node, null, null, Period));
private void SetPeriod(AnalyticsPeriod value) => navigation.NavigateTo(Url(node, From, To, value.ToString().ToLowerInvariant()));
private string NodeUrl(AnalyticsNode target) => Url(target, From, To, Period);
private string Url(AnalyticsNode target, int? from, int? to, string? periodValue)
=> navigation.GetUriWithQueryParameters(new Dictionary<string, object?>
{
["from"] = from,
["to"] = to,
["period"] = periodValue,
["sub"] = target.SubClass,
["acc"] = target.Account,
["text"] = target.Text
});
private static AnalyticsPeriod? ParsePeriod(string? value)
=> Enum.TryParse<AnalyticsPeriod>(value, ignoreCase: true, out var parsed) ? parsed : null;
private string PeriodLabel(DateOnly start) => period switch
{
AnalyticsPeriod.Month => ChartFormatting.MonthLabel(start),
AnalyticsPeriod.Quarter => $"Q{(start.Month - 1) / 3 + 1} {start.Year % 100:00}",
_ => start.Year.ToString()
};
private static string PeriodName(AnalyticsPeriod value) => value switch
{
AnalyticsPeriod.Month => "Monat",
AnalyticsPeriod.Quarter => "Quartal",
_ => "Jahr"
};
private string RangeLabel => fromYear == toYear ? fromYear.ToString() : $"{fromYear}–{toYear}";
private string CurrentName => result!.Breadcrumb[^1].Name;
private string ChildLevelName => node.Level switch
{
AnalyticsLevel.All => "Subklassen",
AnalyticsLevel.SubClass => "Konten",
_ => "Buchungstexte"
};
private string ColorFor(int index) => index < coloredCount ? ChartTheme.ColorAt(index) : ChartTheme.OtherColor;
private static string Chf(decimal value) => ChartFormatting.Chf(value);
private static string Percent(decimal share) => (share * 100).ToString("0.0", Swiss) + " %";
private static string ShareWidth(decimal share) => Math.Clamp(share * 100, 0, 100).ToString("0.##", CultureInfo.InvariantCulture) + "%";
private static string ComparisonLabel(YearComparison comparison)
=> comparison.Months == 12
? $"{comparison.Year} vs. {comparison.Year - 1}"
: $"{comparison.Year} vs. {comparison.Year - 1}, Jan–{Swiss.DateTimeFormat.GetAbbreviatedMonthName(comparison.Months).TrimEnd('.')}";
private static string ChangeLabel(YearComparison comparison)
=> comparison.ChangePercent is { } change ? (change > 0 ? "+" : "") + change.ToString("0.0", Swiss) + " %" : "–";
// For expenses, more is worse.
private static string ChangeClass(YearComparison comparison)
=> comparison.ChangePercent switch { > 0 => "up", < 0 => "down", _ => "" };
}