## 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>
283 lines
12 KiB
C#
283 lines
12 KiB
C#
#nullable enable
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using Schaad.Accounting.Datasets;
|
|
using Schaad.Accounting.Datasets.Analytics;
|
|
|
|
namespace Schaad.Accounting.Services
|
|
{
|
|
/// <summary>
|
|
/// All expense bookings of one mandator over all years, flattened into one row per
|
|
/// (month, account, booking-text group) so every query is an in-memory group-by.
|
|
///
|
|
/// Amounts are net: a booking to an expense account counts positive, a booking from one
|
|
/// (refund, correction) negative. Bookings count in the year of the books they are in. Accounts are identified by number across years and
|
|
/// shown with the name from the latest year they appear in.
|
|
/// </summary>
|
|
public class ExpenseAnalysis
|
|
{
|
|
public const string AllName = "Ausgaben";
|
|
private const string NoTextName = "(ohne Text)";
|
|
|
|
private record Fact(DateOnly Month, int Account, string Text, decimal Amount);
|
|
|
|
private readonly List<Fact> facts = new();
|
|
private readonly Dictionary<int, string> accountNames = new();
|
|
private readonly Dictionary<int, string> subClassNames = new();
|
|
private readonly DateOnly? lastMonth;
|
|
|
|
public IReadOnlyList<int> Years { get; }
|
|
|
|
public ExpenseAnalysis(IEnumerable<YearData> years)
|
|
{
|
|
var ordered = years.OrderBy(y => y.Year).ToList();
|
|
Years = ordered.Select(y => y.Year).ToList();
|
|
|
|
foreach (var year in ordered)
|
|
{
|
|
// Later years overwrite earlier names, so the latest name wins.
|
|
foreach (var account in year.Accounts)
|
|
{
|
|
accountNames[account.Number] = account.Name;
|
|
}
|
|
foreach (var subClass in year.SubClasses)
|
|
{
|
|
subClassNames[subClass.Number] = subClass.Name;
|
|
}
|
|
|
|
var accountsById = year.Accounts.Where(a => a.Id != null).ToDictionary(a => a.Id);
|
|
foreach (var transaction in year.Transactions)
|
|
{
|
|
var month = BookMonth(transaction.ValueDate, year.Year);
|
|
var text = TransactionDataset.GetTextGroup(transaction.Text) ?? "";
|
|
|
|
if (accountsById.TryGetValue(transaction.TargetAccountId ?? "", out var target) && target.Class == ClassIds.Expenses)
|
|
{
|
|
facts.Add(new Fact(month, target.Number, text, transaction.Value));
|
|
}
|
|
if (accountsById.TryGetValue(transaction.OriginAccountId ?? "", out var origin) && origin.Class == ClassIds.Expenses)
|
|
{
|
|
facts.Add(new Fact(month, origin.Number, text, -transaction.Value));
|
|
}
|
|
}
|
|
}
|
|
|
|
lastMonth = facts.Count > 0 ? facts.Max(f => f.Month) : null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// A booking belongs to the year of the books it is in, like in 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.
|
|
/// </summary>
|
|
private static DateOnly BookMonth(DateTime valueDate, int bookYear)
|
|
{
|
|
var month = new DateOnly(valueDate.Year, valueDate.Month, 1);
|
|
var first = new DateOnly(bookYear, 1, 1);
|
|
var last = new DateOnly(bookYear, 12, 1);
|
|
return month < first ? first : month > last ? last : month;
|
|
}
|
|
|
|
public AnalyticsResult Query(AnalyticsQuery query)
|
|
{
|
|
var start = new DateOnly(query.FromYear, 1, 1);
|
|
var end = new DateOnly(query.ToYear, 12, 1);
|
|
if (lastMonth is { } last && last < end && last >= start)
|
|
{
|
|
// Don't count months that have no data yet (the running year).
|
|
end = last;
|
|
}
|
|
var months = (end.Year - start.Year) * 12 + end.Month - start.Month + 1;
|
|
|
|
var nodeFacts = facts.Where(f => IsInNode(f, query.Node)).ToList();
|
|
var inRange = nodeFacts.Where(f => f.Month >= start && f.Month <= end).ToList();
|
|
|
|
var periods = GetPeriods(start, end, query.Period);
|
|
var periodIndex = periods.Select((p, i) => (p, i)).ToDictionary(x => x.p, x => x.i);
|
|
|
|
var total = inRange.Sum(f => f.Amount);
|
|
var categories = inRange
|
|
.GroupBy(f => ChildOf(f, query.Node))
|
|
.Select(g =>
|
|
{
|
|
var values = new decimal[periods.Count];
|
|
foreach (var fact in g)
|
|
{
|
|
values[periodIndex[PeriodStart(fact.Month, query.Period)]] += fact.Amount;
|
|
}
|
|
var categoryTotal = values.Sum();
|
|
return new AnalyticsCategory(
|
|
g.Key,
|
|
NameOf(g.Key),
|
|
values,
|
|
categoryTotal,
|
|
total == 0 ? 0 : categoryTotal / total,
|
|
CanDrillDown: g.Key.Level != AnalyticsLevel.Text);
|
|
})
|
|
// Accounts whose bookings cancel out completely are noise, not a category.
|
|
.Where(c => c.Values.Any(v => v != 0))
|
|
.OrderByDescending(c => c.Total)
|
|
.ToList();
|
|
|
|
return new AnalyticsResult(
|
|
GetBreadcrumb(query.Node),
|
|
periods,
|
|
categories,
|
|
total,
|
|
months,
|
|
months == 0 ? 0 : total / months,
|
|
GetComparison(nodeFacts, end),
|
|
GetYearProfiles(nodeFacts, start, end),
|
|
GetCategoryYears(nodeFacts, query.Node, categories, start, end),
|
|
GetComposition(inRange, query.Node, categories));
|
|
}
|
|
|
|
private static List<YearProfile> GetYearProfiles(List<Fact> nodeFacts, DateOnly start, DateOnly end)
|
|
{
|
|
var profiles = new List<YearProfile>();
|
|
for (var year = start.Year; year <= end.Year; year++)
|
|
{
|
|
var lastMonth = year == end.Year ? end.Month : 12;
|
|
var months = new decimal?[12];
|
|
for (var month = 1; month <= lastMonth; month++)
|
|
{
|
|
months[month - 1] = 0;
|
|
}
|
|
foreach (var fact in nodeFacts.Where(f => f.Month.Year == year && f.Month.Month <= lastMonth))
|
|
{
|
|
months[fact.Month.Month - 1] += fact.Amount;
|
|
}
|
|
profiles.Add(new YearProfile(year, months, months.Sum() ?? 0));
|
|
}
|
|
return profiles;
|
|
}
|
|
|
|
private List<CategoryYears> GetCategoryYears(List<Fact> nodeFacts, AnalyticsNode node, List<AnalyticsCategory> categories, DateOnly start, DateOnly end)
|
|
{
|
|
// Not limited to the range: the first year's change needs the year before.
|
|
var factsByChild = nodeFacts.GroupBy(f => ChildOf(f, node)).ToDictionary(g => g.Key, g => g.ToList());
|
|
|
|
return categories.Select(category =>
|
|
{
|
|
var childFacts = factsByChild.GetValueOrDefault(category.Node) ?? new List<Fact>();
|
|
var cells = new List<YearCell>();
|
|
for (var year = start.Year; year <= end.Year; year++)
|
|
{
|
|
var lastMonth = year == end.Year ? end.Month : 12;
|
|
var value = SumYear(childFacts, year, lastMonth);
|
|
decimal? change = null;
|
|
if (Years.Contains(year - 1))
|
|
{
|
|
var previous = SumYear(childFacts, year - 1, lastMonth);
|
|
change = previous == 0 ? null : (value - previous) / Math.Abs(previous) * 100;
|
|
}
|
|
cells.Add(new YearCell(year, value, change));
|
|
}
|
|
return new CategoryYears(category.Node, category.Name, category.CanDrillDown, cells, category.Total);
|
|
}).ToList();
|
|
}
|
|
|
|
private static decimal SumYear(List<Fact> facts, int year, int lastMonth)
|
|
=> facts.Where(f => f.Month.Year == year && f.Month.Month <= lastMonth).Sum(f => f.Amount);
|
|
|
|
private List<CompositionItem> GetComposition(List<Fact> inRange, AnalyticsNode node, List<AnalyticsCategory> categories)
|
|
{
|
|
var items = new List<CompositionItem>();
|
|
foreach (var category in categories.Where(c => c.Total > 0))
|
|
{
|
|
if (category.Node.Level == AnalyticsLevel.Text)
|
|
{
|
|
items.Add(new CompositionItem(category.Node, category.Name, null, null, category.Total));
|
|
continue;
|
|
}
|
|
|
|
var children = inRange
|
|
.Where(f => ChildOf(f, node) == category.Node)
|
|
.GroupBy(f => ChildOf(f, category.Node))
|
|
.Select(g => (Node: g.Key, Value: g.Sum(f => f.Amount)))
|
|
.Where(c => c.Value > 0)
|
|
.OrderByDescending(c => c.Value);
|
|
foreach (var child in children)
|
|
{
|
|
items.Add(new CompositionItem(category.Node, category.Name, child.Node, NameOf(child.Node), child.Value));
|
|
}
|
|
}
|
|
return items;
|
|
}
|
|
|
|
private YearComparison? GetComparison(List<Fact> nodeFacts, DateOnly end)
|
|
{
|
|
var year = end.Year;
|
|
if (Years.Contains(year - 1) == false)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var current = nodeFacts.Where(f => f.Month.Year == year && f.Month.Month <= end.Month).Sum(f => f.Amount);
|
|
var previous = nodeFacts.Where(f => f.Month.Year == year - 1 && f.Month.Month <= end.Month).Sum(f => f.Amount);
|
|
return new YearComparison(year, end.Month, current, previous);
|
|
}
|
|
|
|
private static bool IsInNode(Fact fact, AnalyticsNode node) => node.Level switch
|
|
{
|
|
AnalyticsLevel.All => true,
|
|
AnalyticsLevel.SubClass => fact.Account / 100 == node.SubClass,
|
|
AnalyticsLevel.Account => fact.Account == node.Account,
|
|
_ => fact.Account == node.Account && fact.Text == node.Text
|
|
};
|
|
|
|
private static AnalyticsNode ChildOf(Fact fact, AnalyticsNode node) => node.Level switch
|
|
{
|
|
AnalyticsLevel.All => new AnalyticsNode(SubClass: fact.Account / 100),
|
|
AnalyticsLevel.SubClass => new AnalyticsNode(SubClass: fact.Account / 100, Account: fact.Account),
|
|
// A booking-text group is the lowest level; it is its own only child.
|
|
_ => new AnalyticsNode(SubClass: fact.Account / 100, Account: fact.Account, Text: fact.Text)
|
|
};
|
|
|
|
private string NameOf(AnalyticsNode node) => node.Level switch
|
|
{
|
|
AnalyticsLevel.All => AllName,
|
|
AnalyticsLevel.SubClass => subClassNames.GetValueOrDefault(node.SubClass!.Value, $"Subklasse {node.SubClass}"),
|
|
AnalyticsLevel.Account => accountNames.GetValueOrDefault(node.Account!.Value, $"Konto {node.Account}"),
|
|
_ => string.IsNullOrEmpty(node.Text) ? NoTextName : node.Text
|
|
};
|
|
|
|
private List<AnalyticsBreadcrumb> GetBreadcrumb(AnalyticsNode node)
|
|
{
|
|
var path = new List<AnalyticsBreadcrumb> { new(AnalyticsNode.All, AllName) };
|
|
if (node.SubClass is { } subClass)
|
|
{
|
|
path.Add(new(new AnalyticsNode(subClass), NameOf(new AnalyticsNode(subClass))));
|
|
}
|
|
if (node.Account is { } account)
|
|
{
|
|
path.Add(new(new AnalyticsNode(account / 100, account), NameOf(new AnalyticsNode(account / 100, account))));
|
|
}
|
|
if (node.Text is not null)
|
|
{
|
|
path.Add(new(node, NameOf(node)));
|
|
}
|
|
return path;
|
|
}
|
|
|
|
private static List<DateOnly> GetPeriods(DateOnly start, DateOnly end, AnalyticsPeriod period)
|
|
{
|
|
var step = period switch { AnalyticsPeriod.Month => 1, AnalyticsPeriod.Quarter => 3, _ => 12 };
|
|
var periods = new List<DateOnly>();
|
|
for (var p = PeriodStart(start, period); p <= end; p = p.AddMonths(step))
|
|
{
|
|
periods.Add(p);
|
|
}
|
|
return periods;
|
|
}
|
|
|
|
private static DateOnly PeriodStart(DateOnly month, AnalyticsPeriod period) => period switch
|
|
{
|
|
AnalyticsPeriod.Month => month,
|
|
AnalyticsPeriod.Quarter => new DateOnly(month.Year, (month.Month - 1) / 3 * 3 + 1, 1),
|
|
_ => new DateOnly(month.Year, 1, 1)
|
|
};
|
|
}
|
|
}
|