AccountingNext/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.cs
Claudio Schaad afa07f8156 Analyse page: composition, year comparison and year table; fix year filter loop
Step 3 of the analytics plan:
- Zusammensetzung: treemap (chartjs-chart-treemap 4.2.2, vendored) with the
  queried node's children and, nested, their children; clicking a tile drills
  down to that level
- Jahresvergleich: one line per year over Jan-Dec, monthly or cumulative
- Jahre im Vergleich: category x year table, cells shaded by monthly average
  (so the running year compares fairly), change vs. the same months of the
  previous year, clickable rows; replaces both heatmap and table from the plan
- ExpenseAnalysis returns year profiles, the category x year table and the
  two-level composition; StackedBarChart becomes a generic ChartJsChart
- Click hints only show when something can be drilled into; the treemap
  cursor only changes over clickable tiles; zero cells show "-"

Fix: choosing a year in Von/Bis started an endless navigation loop (FluentSelect
re-reports its value on every re-render, before the new URL has been applied),
so the page stopped updating. The handlers now take over the year immediately.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:20:24 +02: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;
}
}