AccountingNext/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.cs
Claudio Schaad 9138f08287 Analyse page: income, net and assets views; narrow-screen layout (#6)
## Summary
Step 4 of the analytics plan, items 2, 4 and 5: **income, net and assets views** on the Analyse page (replacing the old Vermögen chart page) and a **narrow-screen layout** pass.

### Views
A switch at the top selects **Ausgaben | Einnahmen | Netto | Vermögen**, stored in the URL as `view=`. Switching starts the drill-down from the top, because the subclasses differ per view.

- **Einnahmen:** works like Ausgaben. Bookings *from* an income account count positive, bookings *to* one (corrections) negative.
- **Netto:** income minus expenses. Income subclasses are positive and expense subclasses negative.
  - The bar chart stacks income up and expenses down, with a black line for the net result per period; the tooltip total is left out there.
  - Categories are ordered by size, so the big expense groups aren't folded into "Andere".
  - The fourth tile shows the **savings rate** (net / income).
  - No treemap, since areas can't show negative amounts.
- **Vermögen:** month-end balances of the asset accounts (class 1) in CHF. It is a stock, not a flow:
  - A month, quarter or year shows the balance at its end, and the total is the balance at the end of the range.
  - Tiles show that balance, the change since the start of the range (with the opening balance), and the comparison with the same month a year earlier.
  - The year table shows year-end balances; the drill-down ends at the account.
  - The year comparison shows month-end balances, without the cumulative switch.
  - Foreign-currency balances are computed like the balance sheet (`ViewService`): kept in the account currency and converted with `IFxConverter`, which is asked once per currency.
- **Colours follow the view:** more expenses are red; more income, surplus or assets green. The CSS classes are now `worse` / `better` instead of `up` / `down`.

### Code
- `ExpenseAnalysis` → **`AccountingAnalysis`** with `AnalyticsView` (Expenses, Income, Net, Assets), and `GetExpenseAnalysisAsync` → `GetAnalysisAsync`. The running year's last month now comes from all bookings, not just expenses.
- `AnalyticsResult.Opening` gives the balance at the start of the range for Vermögen.
- `charts.js`: the stacked bar chart takes an optional `totalLine`.

### Removed
- The **Vermögen** chart page (`/Assets`) and its menu entry. Plotly is now only used by the booking-text charts on the Transactions page.

### Narrow screens
At 400 px the page was wider than the screen.

- **App-wide:** the side menu took half the screen. It now starts collapsed to icons below 700 px (`wwwroot/js/viewport.js`); the ☰ toggle still opens it. The header dropdowns are narrower, and the app name hides below 520 px.
- **Analyse page:** button groups wrap, the tiles sit two per row, and in the year table the name column is narrower and pinned while the years scroll, with the full name as a tooltip.

## Test plan
- [x] `dotnet build`: no warnings
- [x] `dotnet test`: 88/88 pass, including 7 new `AccountingAnalysisTestShould` tests (income signs, net ordering, month-end balances with opening, balance at period end, FX conversion asked once, comparison at the same month, assets drill-down ends at the account)
- [x] Against a copy of the real data, all matching the app's own reports:
  - Einnahmen 2026 = 109'865.13 ("Total Einkünfte" in the profit-and-loss report)
  - Netto 2026 = 32'859.06 (= 109'865.13 − 77'006.07)
  - Vermögen end of Oct 2026 = 263'994.98 ("Total Aktiven" in the Bilanz)
- [x] Headless Chrome at 400, 820 and 1500 px: no horizontal overflow; menu collapsed at 400 px and expanded at 820 / 1500 px; pinned table column scrolls correctly; all charts render without console errors

## Note on the data (not a code issue)
The Vermögen view shows each year as its books say. In the real data, some closing balances don't match the next year's opening balances. These are probably bookings added to a year after the next one was opened:
- End of 2024 → 2025: Bargeld CHF (+40.75)
- End of 2025 → 2026: Bargeld CHF (+98.50), TKB Privatkonto (+200.00), account 1042 (2'030.40 at the end of 2025, missing in 2026), Durchlaufskonto (−7.29)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reviewed-on: #6
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
2026-10-22 16:42:43 +00:00

427 lines
17 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, income, net result or assets of the selected mandator over all years, with
/// drill-down all → subclass → account → booking-text group (assets: down to the account).
/// 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 AnalyticsView[] Views = [AnalyticsView.Expenses, AnalyticsView.Income, AnalyticsView.Net, AnalyticsView.Assets];
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 = "view")]
public string? View { get; set; }
[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 AccountingAnalysis? analysis;
private AnalyticsResult? result;
private AnalyticsView view;
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 value (amounts: per month) relative to the largest one.
private decimal maxHeat;
private int lastYearMonths = 12;
protected override async Task OnInitializedAsync()
{
mandator = settingsService.GetMandator();
analysis = await analyticsService.GetAnalysisAsync();
}
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);
view = Enum.TryParse<AnalyticsView>(View, ignoreCase: true, out var parsedView) ? parsedView : AnalyticsView.Expenses;
node = Acc is { } account ? new AnalyticsNode(account / 100, account, IsAssets ? null : Text)
: Sub is { } subClass ? new AnalyticsNode(subClass)
: AnalyticsNode.All;
result = analysis.Query(new AnalyticsQuery(fromYear, toYear, period, node, view));
BuildBarChart(result);
BuildTreemap(result);
BuildLineChart(result);
BuildYearTable(result);
}
private bool IsAssets => view == AnalyticsView.Assets;
private bool IsNet => view == AnalyticsView.Net;
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);
}
// Net: income stacks up, expenses down; the line shows what is left.
object? totalLine = null;
if (IsNet)
{
var net = Enumerable.Range(0, data.Periods.Count).Select(p => categories.Sum(c => c.Values[p])).ToList();
totalLine = new { name = "Netto", values = net };
}
barData = new { labels = data.Periods.Select(PeriodLabel).ToList(), series, totalLine };
}
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 (data.Categories.First(c => c.Node == item.Parent).CanDrillDown)
{
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)]
};
// Balances already accumulate; only amounts can be summed up.
var values = cumulative && IsAssets == false ? 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);
maxHeat = data.CategoryYears
.SelectMany(row => row.Cells)
.Select(HeatValue)
.DefaultIfEmpty(0)
.Max();
}
// Amounts per month, so the running year compares fairly; balances as they are. Net shades
// both signs, so it compares magnitudes.
private decimal HeatValue(YearCell cell)
{
var value = IsAssets ? cell.Value : cell.Value / MonthsOf(cell.Year);
return IsNet ? Math.Abs(value) : value;
}
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()));
// Subclasses differ per view, so switching starts again at the top.
private void SetView(AnalyticsView value)
=> navigation.NavigateTo(Url(AnalyticsNode.All, From, To, Period, ViewValue(value)));
private string NodeUrl(AnalyticsNode target) => Url(target, From, To, Period);
private string Url(AnalyticsNode target, int? from, int? to, string? periodValue)
=> Url(target, from, to, periodValue, ViewValue(view));
private string Url(AnalyticsNode target, int? from, int? to, string? periodValue, string? viewValue)
=> navigation.GetUriWithQueryParameters(new Dictionary<string, object?>
{
["view"] = viewValue,
["from"] = from,
["to"] = to,
["period"] = periodValue,
["sub"] = target.SubClass,
["acc"] = target.Account,
["text"] = target.Text
});
private static string? ViewValue(AnalyticsView value)
=> value == AnalyticsView.Expenses ? null : value.ToString().ToLowerInvariant();
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 static string ViewName(AnalyticsView value) => value switch
{
AnalyticsView.Expenses => "Ausgaben",
AnalyticsView.Income => "Einnahmen",
AnalyticsView.Net => "Netto",
_ => "Vermögen"
};
private bool CanDrillDown => result!.Categories.Any(c => c.CanDrillDown);
private string RangeLabel => fromYear == toYear ? fromYear.ToString() : $"{fromYear}–{toYear}";
// Month the range ends with, e.g. "Okt 2026" (for balances).
private string EndLabel => $"{MonthNames[(toYear == analysis!.Years[^1] ? lastYearMonths : 12) - 1]} {toYear}";
private string CurrentName => result!.Breadcrumb[^1].Name;
private string ChildLevelName => node.Level switch
{
AnalyticsLevel.All => "Subklassen",
AnalyticsLevel.SubClass => "Konten",
_ when IsAssets => "Konto",
_ => "Buchungstexte"
};
private decimal NetIncome => result!.Categories.Where(c => c.Total > 0).Sum(c => c.Total);
private decimal NetExpenses => -result!.Categories.Where(c => c.Total < 0).Sum(c => c.Total);
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 => IsAssets
? $"* {toYear}: Saldo Ende {Swiss.DateTimeFormat.GetMonthName(lastYearMonths)}; Veränderung gegenüber demselben Monat im Vorjahr."
: $"* {toYear}: Januar–{Swiss.DateTimeFormat.GetMonthName(lastYearMonths)}; Veränderung gegenüber denselben Monaten im Vorjahr.";
private string TableNote => view switch
{
AnalyticsView.Assets => "Saldo am Jahresende in CHF; Farbe = Höhe des Saldos; Prozent = Veränderung zum Vorjahr.",
AnalyticsView.Net => "Beträge in CHF; grün = Überschuss, rot = Defizit, Farbe nach Ø pro Monat; Prozent = Veränderung zum Vorjahr.",
_ => "Beträge in CHF; Farbe = Ø pro Monat, damit ein laufendes Jahr vergleichbar bleibt; Prozent = Veränderung zum Vorjahr."
};
private string HeatColor(YearCell cell)
{
var value = HeatValue(cell);
if (maxHeat <= 0 || value <= 0)
{
return "transparent";
}
var alpha = (0.06m + Math.Min(value / maxHeat, 1) * 0.5m).ToString("0.###", CultureInfo.InvariantCulture);
// Capped so dark text stays readable on the strongest cells.
return IsNet
? cell.Value >= 0 ? $"rgba(16, 124, 16, {alpha})" : $"rgba(197, 15, 31, {alpha})"
: $"rgba(42, 120, 214, {alpha})";
}
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) + " %" : "–";
// Red = worse, green = better: more expenses are worse, more income, savings or assets better.
private string ChangeClass(decimal? change)
{
var sign = change switch { > 0 => 1, < 0 => -1, _ => 0 };
if (view != AnalyticsView.Expenses)
{
sign = -sign;
}
return sign switch { > 0 => "worse", < 0 => "better", _ => "" };
}
private static CultureInfo CreateSwissNumbers()
{
var culture = new CultureInfo("de-CH");
culture.NumberFormat.NumberGroupSeparator = "'";
return culture;
}
}