New page /analytics shows the current mandator's expenses across all years, with drill-down all -> subclass -> account -> booking-text group, year range and month/quarter/year filters, KPI tiles, a stacked bar chart and a category list. Filters and drill-down position live in the URL. - MultiYearRepository reads any mandator/year (read-only, shared cache) - ExpenseAnalysis flattens all years and answers queries in memory: net amounts (refunds count negative), accounts keyed by number with the latest name, bookings counted in the year of their books, year-over-year comparison over the same months - Chart.js 4.5.1 vendored in wwwroot/lib/chartjs, wrapped by wwwroot/js/charts.js and StackedBarChart.razor Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
212 lines
7.7 KiB
C#
212 lines
7.7 KiB
C#
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", _ => "" };
|
||
}
|