AccountingNext/Schaad.Accounting.Services/ExpenseAnalysis.cs
Claudio Schaad 2bc32e9746 Add Analyse page: expenses over all years with drill-down (#4)
## Summary
A new **Analyse** page (Charts → Analyse, `/analytics`) shows the current mandator's **expenses over all years**, with drill-down **all expenses → subclass → account → booking text** (first word, like the existing charts). This covers steps 1 and 2 of the analytics plan; more views (composition, year comparison, heatmap, table) follow in later PRs.

The page **replaces the old "Ausgaben" and "Zeitverlauf" charts**, which are removed (see below). "Vermögen" stays until the Analyse page covers assets.

### Page
- **Filters:** from/to year, "Alle Jahre", Monat / Quartal / Jahr. The default is monthly for a single year and quarterly for several.
- **Breadcrumb** to jump back up the drill-down.
- **Tiles:** total, average per month, change versus the previous year over the same months (e.g. 2026 vs. 2025, Jan–Okt; more spending red, less green), largest item with its share.
- **Stacked bar chart** (Chart.js) with sorted tooltips including a total. Clicking a segment drills down. Beyond 7 categories the tail is grouped as "Andere", like the other charts.
- **Category list** with amount, share and share bar, in the chart's colours. Entries are links that drill down.
- **URL state** (`?from=&to=&period=&sub=&acc=&text=`): back/forward and bookmarks work. Data is loaded once per visit; every change is an in-memory query.

### Data
- `MultiYearRepository` (`IMultiYearRepository`) reads Accounts / SubClasses / Transactions of any mandator and year. It is read-only (never creates folders or copies files) and shares the per-session cache with the other repositories, so a save in the current year is reflected immediately.
- `ExpenseAnalysis` flattens all years into one row per month / account / booking-text group:
  - **Net amounts:** bookings to an expense account count positive, bookings from one (refunds, corrections) negative; moves between expense accounts cancel out at the higher levels.
  - **Accounts are keyed by number** across years and shown with the latest name.
  - **Bookings count in the year of the books they are in**, like 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.
  - The running year stops at the last month with data; the year-over-year comparison uses the same months of both years.
- `TransactionDataset.GetTextGroup` gets a static overload so the grouping can be used without a transaction view.
- `BaseRepository` can load a cached list from any directory.

### Chart.js
- Chart.js **4.5.1** (MIT) is vendored in `wwwroot/lib/chartjs` with its licence, checked against the npm registry checksum. There is no CDN dependency, so the app works offline.
- `wwwroot/js/charts.js` loads it only when the page opens and styles it like `ChartTheme` (palette, font, de-CH numbers with `'`). `StackedBarChart.razor` creates the chart once and then updates it in place.
- Plotly stays for "Vermögen" and the booking-text charts on the Transactions page.

### Removed
- The pages **Ausgaben** (`/spendings`, donut) and **Zeitverlauf** (`/SpendingsOverTime`, stacked bars) and their menu entries. Bookmarks to them now show "not found".
- `ChartService.GetExpensesPerMonthAsync` with its two helpers and its 6 tests; nothing else used them. `ChartService` now only serves the booking-text charts.

## Test plan
- [x] `dotnet build --no-incremental`: no warnings
- [x] `dotnet test`: 75/75 pass (6 tests removed with `GetExpensesPerMonthAsync`), including 15 new `ExpenseAnalysisTestShould` tests (subclass totals, refunds, non-expense bookings, transfers, account renames across years, booking-text level, breadcrumb, book-year attribution, running year, quarters/years, year range, year-over-year comparison, no previous year, no data) and 4 `MultiYearRepositoryTestShould` tests
- [x] Against a copy of the real data: every year's total matches an independent Python recomputation from the JSON files, and the 2026 total (77'006.07) equals "Total Ausgaben" in the profit-and-loss report
- [x] In headless Chrome: chart renders, clicking a bar drills to the subclass, a list entry drills to the account, browser back returns, and the period buttons switch. No console errors.
- [ ] Narrow-screen layout checked by hand (only covered by CSS so far)

## Known limitations
- A partial last period (e.g. Q4 26 with only October) is not marked as incomplete yet.

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

Reviewed-on: #4
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
2026-10-22 14:02:08 +00:00

207 lines
8.9 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));
}
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)
};
}
}