AccountingNext/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.cs
Claudio Schaad 00921b8dac Analyse page: composition, year comparison and year table; fix year filter loop (#5)
## 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>
2026-10-22 14:21:32 +00:00

354 lines
13 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 CultureInfo SwissNumbers = CreateSwissNumbers();
private static readonly AnalyticsPeriod[] Periods = [AnalyticsPeriod.Month, AnalyticsPeriod.Quarter, AnalyticsPeriod.Year];
private static readonly string[] MonthNames = ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"];
// Year-comparison lines: the latest year in the accent colour, the one before in orange,
// older ones in fading grey.
private static readonly string[] OlderYearColors = ["#898781", "#a9a8a3", "#c4c3be", "#d6d5d0"];
[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 object barData = new();
// Category behind each bar series; null for the folded "Andere" series.
private List<AnalyticsCategory?> seriesCategories = [];
private int coloredCount;
private object treemapData = new();
// Treemap click key ("p3" or "p3|c7") → drill-down target.
private Dictionary<string, AnalyticsNode> treemapNodes = [];
private object lineData = new();
private bool cumulative = true;
// Heat shading of the year table: a cell's monthly average relative to the largest one.
private decimal maxMonthlyAverage;
private int lastYearMonths = 12;
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));
BuildBarChart(result);
BuildTreemap(result);
BuildLineChart(result);
BuildYearTable(result);
}
private void BuildBarChart(AnalyticsResult data)
{
// 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<object>();
seriesCategories = [];
for (var i = 0; i < coloredCount; i++)
{
var category = categories[i];
series.Add(new { name = category.Name, color = ChartTheme.ColorAt(i), values = category.Values, clickable = 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 { name = ChartTheme.OtherLabel, color = ChartTheme.OtherColor, values = other, clickable = false });
seriesCategories.Add(null);
}
barData = new { labels = data.Periods.Select(PeriodLabel).ToList(), series };
}
private void BuildTreemap(AnalyticsResult data)
{
// Parent ids follow the category order, so a parent has the same colour as in the bar
// chart and the list.
var parents = data.Categories
.Select((category, i) => (category.Node, Id: $"p{i}", Color: ColorFor(i)))
.ToDictionary(x => x.Node);
var names = new Dictionary<string, string>();
var colors = new Dictionary<string, string>();
var items = new List<object>();
treemapNodes = [];
foreach (var item in data.Composition)
{
var parent = parents[item.Parent];
names[parent.Id] = item.ParentName;
colors[parent.Id] = parent.Color;
if (item.Parent.Level != AnalyticsLevel.Text)
{
treemapNodes[parent.Id] = item.Parent;
}
string? childId = null;
if (item.Child is { } child)
{
childId = $"c{items.Count}";
names[childId] = item.ChildName!;
treemapNodes[$"{parent.Id}|{childId}"] = child;
}
items.Add(new { p = parent.Id, c = childId, value = item.Value });
}
treemapData = new { items, names, colors, clickable = treemapNodes.Keys.ToList() };
}
private void BuildLineChart(AnalyticsResult data)
{
var profiles = data.YearProfiles;
var series = profiles.Select((profile, i) =>
{
var age = profiles.Count - 1 - i;
var color = age switch
{
0 => ChartTheme.Categorical[0],
1 => ChartTheme.Categorical[1],
_ => OlderYearColors[Math.Min(age - 2, OlderYearColors.Length - 1)]
};
var values = cumulative ? RunningTotal(profile.Months) : profile.Months;
return new { name = profile.Year.ToString(), color, values, width = age == 0 ? 3 : 2 };
}).ToList();
lineData = new { labels = MonthNames, series };
}
private static IReadOnlyList<decimal?> RunningTotal(IReadOnlyList<decimal?> months)
{
var sum = 0m;
return months.Select(m => m is { } value ? sum += value : (decimal?)null).ToList();
}
private void SetCumulative(bool value)
{
cumulative = value;
BuildLineChart(result!);
}
private void BuildYearTable(AnalyticsResult data)
{
lastYearMonths = data.YearProfiles[^1].Months.Count(m => m is not null);
maxMonthlyAverage = data.CategoryYears
.SelectMany(row => row.Cells)
.Select(cell => cell.Value / MonthsOf(cell.Year))
.DefaultIfEmpty(0)
.Max();
}
private int MonthsOf(int year) => year == toYear ? Math.Max(lastYearMonths, 1) : 12;
private void OnBarClick(string key)
{
if (int.TryParse(key, out var index) && seriesCategories.ElementAtOrDefault(index) is { CanDrillDown: true } category)
{
navigation.NavigateTo(NodeUrl(category.Node));
}
}
private void OnTreemapClick(string key)
{
if (treemapNodes.TryGetValue(key, out var target))
{
navigation.NavigateTo(NodeUrl(target));
}
}
// FluentSelect reports its selection again whenever it re-renders. The new year only reaches
// OnParametersSet once the navigation completes, so it is taken over right away; otherwise
// every re-render starts another navigation to the same URL, cancelling the previous one,
// and the page never updates.
private void OnFromChanged(int year)
{
if (year == fromYear)
{
return;
}
var url = Url(node, year, year > toYear ? year : To, Period);
fromYear = year;
toYear = Math.Max(toYear, year);
navigation.NavigateTo(url);
}
private void OnToChanged(int year)
{
if (year == toYear)
{
return;
}
var url = Url(node, year < fromYear ? year : From, year, Period);
toYear = year;
fromYear = Math.Min(fromYear, year);
navigation.NavigateTo(url);
}
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 bool CanDrillDown => result!.Categories.Any(c => c.CanDrillDown);
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 Whole(decimal value) => value.ToString("#,0", SwissNumbers);
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 string YearHeader(int year) => year == toYear && lastYearMonths < 12 ? $"{year}*" : year.ToString();
private string PartialYearNote
=> $"* {toYear}: Januar–{Swiss.DateTimeFormat.GetMonthName(lastYearMonths)}; Veränderung gegenüber denselben Monaten im Vorjahr.";
private string HeatColor(YearCell cell)
{
if (maxMonthlyAverage <= 0 || cell.Value <= 0)
{
return "transparent";
}
var intensity = Math.Min(cell.Value / MonthsOf(cell.Year) / maxMonthlyAverage, 1);
// Capped so dark text stays readable on the strongest cells.
return $"rgba(42, 120, 214, {(0.06m + intensity * 0.5m).ToString("0.###", CultureInfo.InvariantCulture)})";
}
private static string ChangeText(decimal? change)
=> change is { } c ? (c > 0 ? "+" : "") + c.ToString("0", Swiss) + " %" : "";
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(decimal? change) => change switch { > 0 => "up", < 0 => "down", _ => "" };
private static CultureInfo CreateSwissNumbers()
{
var culture = new CultureInfo("de-CH");
culture.NumberFormat.NumberGroupSeparator = "'";
return culture;
}
}