From 9138f082870b97edb8b5c83f4876a49d10f2fc36 Mon Sep 17 00:00:00 2001 From: Claudio Schaad Date: Thu, 22 Oct 2026 16:42:43 +0000 Subject: [PATCH] Analyse page: income, net and assets views; narrow-screen layout (#6) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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: https://git.schaad.solutions/clayschaad/AccountingNext/pulls/6 Co-authored-by: Claudio Schaad Co-committed-by: Claudio Schaad --- CLAUDE.md | 2 +- .../Datasets/Analytics/AnalyticsModels.cs | 35 +- .../AccountingAnalysis.cs | 442 ++++++++++++++++++ .../AnalyticsService.cs | 8 +- Schaad.Accounting.Services/ExpenseAnalysis.cs | 283 ----------- .../Interfaces/IAnalyticsService.cs | 4 +- ...uld.cs => AccountingAnalysisTestShould.cs} | 171 ++++++- .../Components/Layout/NavMenu.razor | 29 +- .../Components/MyHeader.razor | 6 +- .../Components/MyHeader.razor.css | 10 + .../Pages/Analytics/Analytics.razor | 150 ++++-- .../Pages/Analytics/Analytics.razor.cs | 117 ++++- .../Pages/Analytics/Analytics.razor.css | 49 +- .../Components/Pages/Charts/Assets.razor | 15 - .../Components/Pages/Charts/Assets.razor.cs | 34 -- Schaad.Accounting.UI/wwwroot/js/charts.js | 26 +- Schaad.Accounting.UI/wwwroot/js/viewport.js | 4 + 17 files changed, 934 insertions(+), 451 deletions(-) create mode 100644 Schaad.Accounting.Services/AccountingAnalysis.cs delete mode 100644 Schaad.Accounting.Services/ExpenseAnalysis.cs rename Schaad.Accounting.Tests/{ExpenseAnalysisTestShould.cs => AccountingAnalysisTestShould.cs} (63%) create mode 100644 Schaad.Accounting.UI/Components/MyHeader.razor.css delete mode 100644 Schaad.Accounting.UI/Components/Pages/Charts/Assets.razor delete mode 100644 Schaad.Accounting.UI/Components/Pages/Charts/Assets.razor.cs create mode 100644 Schaad.Accounting.UI/wwwroot/js/viewport.js diff --git a/CLAUDE.md b/CLAUDE.md index ce7cbe0..18d0bf2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,7 +58,7 @@ When a new year is opened, the previous year's data is copied as the starting po - **FileService** — imports bank statements (MT940, CAMT053 via external `Schaad.Finance.dll`), parses PDFs, manages backups - **ChartService** — produces data for the Plotly booking-text charts on the transactions page - **SettingsService** — manages the active year, mandator, and file paths -- **AnalyticsService** — loads all years of the current mandator (via `MultiYearRepository`) into an `ExpenseAnalysis` for the Analyse page; queries run in memory +- **AnalyticsService** — loads all years of the current mandator (via `MultiYearRepository`) into an `AccountingAnalysis` (expenses, income, net, assets) for the Analyse page; queries run in memory ### UI structure diff --git a/Schaad.Accounting.Common/Datasets/Analytics/AnalyticsModels.cs b/Schaad.Accounting.Common/Datasets/Analytics/AnalyticsModels.cs index 786f19a..63d9e1a 100644 --- a/Schaad.Accounting.Common/Datasets/Analytics/AnalyticsModels.cs +++ b/Schaad.Accounting.Common/Datasets/Analytics/AnalyticsModels.cs @@ -12,6 +12,21 @@ namespace Schaad.Accounting.Datasets.Analytics Year } + public enum AnalyticsView + { + /// Net expenses (class 4): bookings to an expense account minus refunds. + Expenses, + + /// Net income (class 3): bookings from an income account minus corrections. + Income, + + /// Income minus expenses: income subclasses positive, expense subclasses negative. + Net, + + /// Month-end balances of the asset accounts (class 1), in CHF. A stock, not a flow. + Assets + } + public enum AnalyticsLevel { All, @@ -35,7 +50,7 @@ namespace Schaad.Accounting.Datasets.Analytics : AnalyticsLevel.All; } - public record AnalyticsQuery(int FromYear, int ToYear, AnalyticsPeriod Period, AnalyticsNode Node); + public record AnalyticsQuery(int FromYear, int ToYear, AnalyticsPeriod Period, AnalyticsNode Node, AnalyticsView View = AnalyticsView.Expenses); public record AnalyticsBreadcrumb(AnalyticsNode Node, string Name); @@ -54,6 +69,7 @@ namespace Schaad.Accounting.Datasets.Analytics /// /// The last year of the range against the year before, over the same months /// (January to ), so an unfinished year compares fairly. + /// For it compares the balances at the end of those months. /// public record YearComparison(int Year, int Months, decimal Current, decimal Previous) { @@ -61,14 +77,16 @@ namespace Schaad.Accounting.Datasets.Analytics } /// - /// Monthly values of the queried node in one year (index 0 = January). Months after the last - /// month with data are null. + /// Monthly values of the queried node in one year (index 0 = January): sums, or month-end + /// balances for . Months after the last month with data are + /// null. is the year's sum, or its last balance. /// public record YearProfile(int Year, IReadOnlyList Months, decimal Total); /// - /// A category's value in one year. For the running year only the months with data count, and - /// the change compares the same months of the previous year. + /// A category's value in one year (for : its balance at the end + /// of the year). For the running year only the months with data count, and the change compares + /// the same months of the previous year. /// public record YearCell(int Year, decimal Value, decimal? ChangePercent); @@ -84,6 +102,10 @@ namespace Schaad.Accounting.Datasets.Analytics /// public record CompositionItem(AnalyticsNode Parent, string ParentName, AnalyticsNode? Child, string? ChildName, decimal Value); + /// + /// is the sum over the range, or for the + /// balance at its end; is then the balance at its start (null otherwise). + /// public record AnalyticsResult( IReadOnlyList Breadcrumb, IReadOnlyList Periods, @@ -94,5 +116,6 @@ namespace Schaad.Accounting.Datasets.Analytics YearComparison? Comparison, IReadOnlyList YearProfiles, IReadOnlyList CategoryYears, - IReadOnlyList Composition); + IReadOnlyList Composition, + decimal? Opening = null); } diff --git a/Schaad.Accounting.Services/AccountingAnalysis.cs b/Schaad.Accounting.Services/AccountingAnalysis.cs new file mode 100644 index 0000000..9cf086d --- /dev/null +++ b/Schaad.Accounting.Services/AccountingAnalysis.cs @@ -0,0 +1,442 @@ +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using Schaad.Accounting.Datasets; +using Schaad.Accounting.Datasets.Analytics; +using Schaad.Accounting.Models; + +namespace Schaad.Accounting.Services +{ + /// + /// The bookings of one mandator over all years, flattened into one row per + /// (month, account, booking-text group) and view, so every query is an in-memory group-by. + /// + /// + /// Expenses: a booking to an expense account counts positive, a booking from one + /// (refund, correction) negative. + /// Income: a booking from an income account counts positive, a booking to one negative. + /// Net: income positive, expenses negative. + /// Assets: one row per asset account and month with its balance at the end of that month + /// (opening balance of the year plus the bookings so far), in CHF. Rows are balances, not + /// amounts: a period takes its last month instead of the sum. + /// + /// + /// 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. + /// + public class AccountingAnalysis + { + private const string NoTextName = "(ohne Text)"; + + private static readonly Dictionary RootNames = new() + { + [AnalyticsView.Expenses] = "Ausgaben", + [AnalyticsView.Income] = "Einnahmen", + [AnalyticsView.Net] = "Netto", + [AnalyticsView.Assets] = "Vermögen" + }; + + private record Fact(DateOnly Month, int Account, string Text, decimal Amount); + + private readonly Dictionary> factsByView = new() + { + [AnalyticsView.Expenses] = new(), + [AnalyticsView.Income] = new(), + [AnalyticsView.Net] = new(), + [AnalyticsView.Assets] = new() + }; + // Opening balance (CHF) per year and asset account. + private readonly Dictionary<(int Year, int Account), decimal> openings = new(); + private readonly Dictionary accountNames = new(); + private readonly Dictionary subClassNames = new(); + private readonly DateOnly? lastMonth; + + public IReadOnlyList Years { get; } + + /// CHF value of one unit of a currency; asked once per currency. + public AccountingAnalysis(IEnumerable years, Func? chfRate = null) + { + var ordered = years.OrderBy(y => y.Year).ToList(); + Years = ordered.Select(y => y.Year).ToList(); + + var bookMonths = ordered + .SelectMany(y => y.Transactions.Select(t => BookMonth(t.ValueDate, y.Year))) + .ToList(); + lastMonth = bookMonths.Count > 0 ? bookMonths.Max() : null; + + var rates = new Dictionary(); + decimal RateOf(Account account) + { + if (account.IsFxAccount == false || chfRate is null) + { + return 1; + } + if (rates.TryGetValue(account.Currency, out var rate) == false) + { + rate = rates[account.Currency] = chfRate(account.Currency); + } + return rate; + } + + 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); + // Asset flows per account and month, in the account's currency. + var assetFlows = new Dictionary<(int Account, int Month), decimal>(); + + foreach (var transaction in year.Transactions) + { + var month = BookMonth(transaction.ValueDate, year.Year); + var text = TransactionDataset.GetTextGroup(transaction.Text) ?? ""; + accountsById.TryGetValue(transaction.TargetAccountId ?? "", out var target); + accountsById.TryGetValue(transaction.OriginAccountId ?? "", out var origin); + + if (target?.Class == ClassIds.Expenses) + { + AddFlow(AnalyticsView.Expenses, new Fact(month, target.Number, text, transaction.Value)); + } + if (origin?.Class == ClassIds.Expenses) + { + AddFlow(AnalyticsView.Expenses, new Fact(month, origin.Number, text, -transaction.Value)); + } + if (origin?.Class == ClassIds.Income) + { + AddFlow(AnalyticsView.Income, new Fact(month, origin.Number, text, transaction.Value)); + } + if (target?.Class == ClassIds.Income) + { + AddFlow(AnalyticsView.Income, new Fact(month, target.Number, text, -transaction.Value)); + } + + if (target?.Class == ClassIds.Activa) + { + AddAssetFlow(assetFlows, target, month.Month, InAccountCurrency(transaction, target)); + } + if (origin?.Class == ClassIds.Activa) + { + AddAssetFlow(assetFlows, origin, month.Month, -InAccountCurrency(transaction, origin)); + } + } + + AddBalances(year, assetFlows, RateOf); + } + } + + private void AddFlow(AnalyticsView view, Fact fact) + { + factsByView[view].Add(fact); + factsByView[AnalyticsView.Net].Add(view == AnalyticsView.Expenses ? fact with { Amount = -fact.Amount } : fact); + } + + private static void AddAssetFlow(Dictionary<(int, int), decimal> flows, Account account, int month, decimal amount) + { + flows[(account.Number, month)] = flows.GetValueOrDefault((account.Number, month)) + amount; + } + + /// + /// Same as the balance sheet (ViewService): amounts of a foreign-currency account are kept + /// in its currency and only the balance is converted. + /// + private static decimal InAccountCurrency(Transaction transaction, Account account) + => account.IsFxAccount && transaction.FxRate is { } rate && rate != 0 + ? Math.Round(transaction.Value / rate, 2) + : transaction.Value; + + private void AddBalances(YearData year, Dictionary<(int Account, int Month), decimal> flows, Func rateOf) + { + var lastMonthOfYear = lastMonth is { } last && last.Year == year.Year ? last.Month : 12; + foreach (var account in year.Accounts.Where(a => a.Class == ClassIds.Activa)) + { + var rate = rateOf(account); + openings[(year.Year, account.Number)] = account.StartBalance * rate; + + var balance = account.StartBalance; + for (var month = 1; month <= lastMonthOfYear; month++) + { + balance += flows.GetValueOrDefault((account.Number, month)); + factsByView[AnalyticsView.Assets].Add(new Fact(new DateOnly(year.Year, month, 1), account.Number, "", balance * rate)); + } + } + } + + /// + /// 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. + /// + 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 view = query.View; + var isStock = view == AnalyticsView.Assets; + var node = Normalize(query.Node, view); + + 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 = factsByView[view].Where(f => IsInNode(f, 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); + + // A balance counts at the end of its period (or of the range), an amount in its period. + bool CountsIn(Fact fact) => isStock == false || fact.Month == PeriodEnd(fact.Month, query.Period, end); + var total = inRange.Where(f => isStock == false || f.Month == end).Sum(f => f.Amount); + + var categories = inRange + .GroupBy(f => ChildOf(f, node, view)) + .Select(g => + { + var values = new decimal[periods.Count]; + foreach (var fact in g.Where(CountsIn)) + { + values[periodIndex[PeriodStart(fact.Month, query.Period)]] += fact.Amount; + } + var categoryTotal = isStock ? g.Where(f => f.Month == end).Sum(f => f.Amount) : values.Sum(); + return new AnalyticsCategory( + g.Key, + NameOf(g.Key, view), + values, + categoryTotal, + total == 0 ? 0 : categoryTotal / total, + CanDrillDown: g.Key.Level < LeafLevel(view)); + }) + // Accounts whose bookings cancel out completely are noise, not a category. + .Where(c => c.Values.Any(v => v != 0)) + // Net mixes income (positive) and expenses (negative); by size, the big expenses + // stay among the first categories instead of being folded away last. + .OrderByDescending(c => view == AnalyticsView.Net ? Math.Abs(c.Total) : c.Total) + .ToList(); + + decimal? opening = isStock + ? openings.Where(o => o.Key.Year == start.Year && IsInNode(new Fact(start, o.Key.Account, "", 0), node)).Sum(o => o.Value) + : null; + + return new AnalyticsResult( + GetBreadcrumb(node, view), + periods, + categories, + total, + months, + isStock || months == 0 ? 0 : total / months, + GetComparison(nodeFacts, end, isStock), + GetYearProfiles(nodeFacts, start, end, isStock), + GetCategoryYears(nodeFacts, node, view, categories, start, end, isStock), + GetComposition(inRange, node, view, categories, end, isStock), + opening); + } + + /// + /// Booking texts mean nothing for balances, so the assets drill-down ends at the account. + /// + private static AnalyticsLevel LeafLevel(AnalyticsView view) + => view == AnalyticsView.Assets ? AnalyticsLevel.Account : AnalyticsLevel.Text; + + private static AnalyticsNode Normalize(AnalyticsNode node, AnalyticsView view) + => view == AnalyticsView.Assets && node.Text != null ? node with { Text = null } : node; + + private YearComparison? GetComparison(List nodeFacts, DateOnly end, bool isStock) + { + var year = end.Year; + if (Years.Contains(year - 1) == false) + { + return null; + } + + var current = SumYear(nodeFacts, year, end.Month, isStock); + var previous = SumYear(nodeFacts, year - 1, end.Month, isStock); + return new YearComparison(year, end.Month, current, previous); + } + + private static List GetYearProfiles(List nodeFacts, DateOnly start, DateOnly end, bool isStock) + { + var profiles = new List(); + for (var year = start.Year; year <= end.Year; year++) + { + var lastMonthOfYear = year == end.Year ? end.Month : 12; + var months = new decimal?[12]; + for (var month = 1; month <= lastMonthOfYear; month++) + { + months[month - 1] = 0; + } + foreach (var fact in nodeFacts.Where(f => f.Month.Year == year && f.Month.Month <= lastMonthOfYear)) + { + months[fact.Month.Month - 1] += fact.Amount; + } + var yearTotal = isStock ? months[lastMonthOfYear - 1] ?? 0 : months.Sum() ?? 0; + profiles.Add(new YearProfile(year, months, yearTotal)); + } + return profiles; + } + + private List GetCategoryYears( + List nodeFacts, AnalyticsNode node, AnalyticsView view, List categories, + DateOnly start, DateOnly end, bool isStock) + { + // Not limited to the range: the first year's change needs the year before. + var factsByChild = nodeFacts.GroupBy(f => ChildOf(f, node, view)).ToDictionary(g => g.Key, g => g.ToList()); + + return categories.Select(category => + { + var childFacts = factsByChild.GetValueOrDefault(category.Node) ?? new List(); + var cells = new List(); + for (var year = start.Year; year <= end.Year; year++) + { + var lastMonthOfYear = year == end.Year ? end.Month : 12; + var value = SumYear(childFacts, year, lastMonthOfYear, isStock); + decimal? change = null; + if (Years.Contains(year - 1)) + { + var previous = SumYear(childFacts, year - 1, lastMonthOfYear, isStock); + 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(); + } + + /// + /// Amounts from January to , or the balance at its end. + /// + private static decimal SumYear(List facts, int year, int lastMonthOfYear, bool isStock) + => isStock + ? facts.Where(f => f.Month.Year == year && f.Month.Month == lastMonthOfYear).Sum(f => f.Amount) + : facts.Where(f => f.Month.Year == year && f.Month.Month <= lastMonthOfYear).Sum(f => f.Amount); + + private List GetComposition( + List inRange, AnalyticsNode node, AnalyticsView view, List categories, + DateOnly end, bool isStock) + { + var facts = isStock ? inRange.Where(f => f.Month == end).ToList() : inRange; + var items = new List(); + foreach (var category in categories.Where(c => c.Total > 0)) + { + if (category.Node.Level == LeafLevel(view)) + { + items.Add(new CompositionItem(category.Node, category.Name, null, null, category.Total)); + continue; + } + + var children = facts + .Where(f => ChildOf(f, node, view) == category.Node) + .GroupBy(f => ChildOf(f, category.Node, view)) + .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, view), child.Value)); + } + } + return items; + } + + 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, AnalyticsView view) + { + // The lowest level is its own only child. + if (node.Level >= LeafLevel(view)) + { + return node; + } + return node.Level switch + { + AnalyticsLevel.All => new AnalyticsNode(SubClass: fact.Account / 100), + AnalyticsLevel.SubClass => new AnalyticsNode(SubClass: fact.Account / 100, Account: fact.Account), + _ => new AnalyticsNode(SubClass: fact.Account / 100, Account: fact.Account, Text: fact.Text) + }; + } + + private string NameOf(AnalyticsNode node, AnalyticsView view) => node.Level switch + { + AnalyticsLevel.All => RootNames[view], + 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 GetBreadcrumb(AnalyticsNode node, AnalyticsView view) + { + var path = new List { new(AnalyticsNode.All, RootNames[view]) }; + if (node.SubClass is { } subClass) + { + path.Add(new(new AnalyticsNode(subClass), NameOf(new AnalyticsNode(subClass), view))); + } + if (node.Account is { } account) + { + path.Add(new(new AnalyticsNode(account / 100, account), NameOf(new AnalyticsNode(account / 100, account), view))); + } + if (node.Text is not null) + { + path.Add(new(node, NameOf(node, view))); + } + return path; + } + + private static List GetPeriods(DateOnly start, DateOnly end, AnalyticsPeriod period) + { + var step = period switch { AnalyticsPeriod.Month => 1, AnalyticsPeriod.Quarter => 3, _ => 12 }; + var periods = new List(); + 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) + }; + + /// + /// Last month of the period containing , but not after the range end. + /// + private static DateOnly PeriodEnd(DateOnly month, AnalyticsPeriod period, DateOnly rangeEnd) + { + var periodEnd = period switch + { + AnalyticsPeriod.Month => month, + AnalyticsPeriod.Quarter => PeriodStart(month, period).AddMonths(2), + _ => new DateOnly(month.Year, 12, 1) + }; + return periodEnd > rangeEnd ? rangeEnd : periodEnd; + } + } +} diff --git a/Schaad.Accounting.Services/AnalyticsService.cs b/Schaad.Accounting.Services/AnalyticsService.cs index d67838f..c7dde6f 100644 --- a/Schaad.Accounting.Services/AnalyticsService.cs +++ b/Schaad.Accounting.Services/AnalyticsService.cs @@ -9,14 +9,16 @@ namespace Schaad.Accounting.Services { private readonly ISettingsService settingsService; private readonly IMultiYearRepository multiYearRepository; + private readonly IFxConverter fxConverter; - public AnalyticsService(ISettingsService settingsService, IMultiYearRepository multiYearRepository) + public AnalyticsService(ISettingsService settingsService, IMultiYearRepository multiYearRepository, IFxConverter fxConverter) { this.settingsService = settingsService; this.multiYearRepository = multiYearRepository; + this.fxConverter = fxConverter; } - public async Task GetExpenseAnalysisAsync() + public async Task GetAnalysisAsync() { var mandator = settingsService.GetMandator(); var years = new List(); @@ -24,7 +26,7 @@ namespace Schaad.Accounting.Services { years.Add(await multiYearRepository.GetYearDataAsync(mandator, year)); } - return new ExpenseAnalysis(years); + return new AccountingAnalysis(years, currency => fxConverter.ConvertToChf(1, currency)); } } } diff --git a/Schaad.Accounting.Services/ExpenseAnalysis.cs b/Schaad.Accounting.Services/ExpenseAnalysis.cs deleted file mode 100644 index fe30121..0000000 --- a/Schaad.Accounting.Services/ExpenseAnalysis.cs +++ /dev/null @@ -1,283 +0,0 @@ -#nullable enable - -using System; -using System.Collections.Generic; -using System.Linq; -using Schaad.Accounting.Datasets; -using Schaad.Accounting.Datasets.Analytics; - -namespace Schaad.Accounting.Services -{ - /// - /// 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. - /// - 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 facts = new(); - private readonly Dictionary accountNames = new(); - private readonly Dictionary subClassNames = new(); - private readonly DateOnly? lastMonth; - - public IReadOnlyList Years { get; } - - public ExpenseAnalysis(IEnumerable 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; - } - - /// - /// 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. - /// - 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 GetYearProfiles(List nodeFacts, DateOnly start, DateOnly end) - { - var profiles = new List(); - 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 GetCategoryYears(List nodeFacts, AnalyticsNode node, List 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(); - var cells = new List(); - 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 facts, int year, int lastMonth) - => facts.Where(f => f.Month.Year == year && f.Month.Month <= lastMonth).Sum(f => f.Amount); - - private List GetComposition(List inRange, AnalyticsNode node, List categories) - { - var items = new List(); - 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 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 GetBreadcrumb(AnalyticsNode node) - { - var path = new List { 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 GetPeriods(DateOnly start, DateOnly end, AnalyticsPeriod period) - { - var step = period switch { AnalyticsPeriod.Month => 1, AnalyticsPeriod.Quarter => 3, _ => 12 }; - var periods = new List(); - 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) - }; - } -} diff --git a/Schaad.Accounting.Services/Interfaces/IAnalyticsService.cs b/Schaad.Accounting.Services/Interfaces/IAnalyticsService.cs index a7b2b8b..f604c02 100644 --- a/Schaad.Accounting.Services/Interfaces/IAnalyticsService.cs +++ b/Schaad.Accounting.Services/Interfaces/IAnalyticsService.cs @@ -6,8 +6,8 @@ namespace Schaad.Accounting.Interfaces public interface IAnalyticsService { /// - /// Expenses of the currently selected mandator over all its years. + /// All years of the currently selected mandator, ready for in-memory queries. /// - Task GetExpenseAnalysisAsync(); + Task GetAnalysisAsync(); } } diff --git a/Schaad.Accounting.Tests/ExpenseAnalysisTestShould.cs b/Schaad.Accounting.Tests/AccountingAnalysisTestShould.cs similarity index 63% rename from Schaad.Accounting.Tests/ExpenseAnalysisTestShould.cs rename to Schaad.Accounting.Tests/AccountingAnalysisTestShould.cs index 1a2a751..d6c19fa 100644 --- a/Schaad.Accounting.Tests/ExpenseAnalysisTestShould.cs +++ b/Schaad.Accounting.Tests/AccountingAnalysisTestShould.cs @@ -5,7 +5,7 @@ using Shouldly; namespace Schaad.Accounting.Tests; -public class ExpenseAnalysisTestShould +public class AccountingAnalysisTestShould { private static readonly Account Bank = new() { Id = "bank", Number = 1020, Name = "Bank" }; private static readonly Account Salary = new() { Id = "salary", Number = 3000, Name = "Lohn" }; @@ -15,6 +15,8 @@ public class ExpenseAnalysisTestShould private static readonly SubClass[] SubClasses = [ + new() { Number = 10, Name = "Bargeld, Konten" }, + new() { Number = 30, Name = "Lohn" }, new() { Number = 40, Name = "Verpflegung" }, new() { Number = 41, Name = "Wohnen" } ]; @@ -37,7 +39,7 @@ public class ExpenseAnalysisTestShould [Fact] public void SumExpensesPerSubClassWhenQueryingAll() { - var sut = new ExpenseAnalysis([Year(2025, + var sut = new AccountingAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100), Booking("2025-01-20", Bank, Restaurant, 50), Booking("2025-02-01", Bank, Rent, 1000))]); @@ -53,7 +55,7 @@ public class ExpenseAnalysisTestShould [Fact] public void SubtractRefundsWhenSummingExpenses() { - var sut = new ExpenseAnalysis([Year(2025, + var sut = new AccountingAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100), Booking("2025-01-15", Food, Bank, 30))]); @@ -65,7 +67,7 @@ public class ExpenseAnalysisTestShould [Fact] public void IgnoreBookingsWithoutExpenseAccountWhenQuerying() { - var sut = new ExpenseAnalysis([Year(2025, + var sut = new AccountingAnalysis([Year(2025, Booking("2025-01-25", Salary, Bank, 5000), Booking("2025-01-26", Bank, Food, 100))]); @@ -78,7 +80,7 @@ public class ExpenseAnalysisTestShould public void CancelTransfersWithinSubClassWhenQueryingAll() { // Reclassifying 20 from food to restaurant changes neither the total nor the subclass. - var sut = new ExpenseAnalysis([Year(2025, + var sut = new AccountingAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100), Booking("2025-01-11", Food, Restaurant, 20))]); @@ -94,7 +96,7 @@ public class ExpenseAnalysisTestShould public void GroupAccountsByNumberWithLatestNameWhenAccountChangedOverYears() { var oldRent = new Account { Id = "rent-old-id", Number = 4100, Name = "Miete alt" }; - var sut = new ExpenseAnalysis( + var sut = new AccountingAnalysis( [ new YearData(2024, [Bank, oldRent], SubClasses, [Booking("2024-03-01", Bank, oldRent, 900)]), Year(2025, Booking("2025-03-01", Bank, Rent, 1000)) @@ -109,7 +111,7 @@ public class ExpenseAnalysisTestShould [Fact] public void ShowBookingTextGroupsWhenDrillingIntoAccount() { - var sut = new ExpenseAnalysis([Year(2025, + var sut = new AccountingAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100, "Migros Zürich"), Booking("2025-01-11", Bank, Food, 40, "Migros Bern"), Booking("2025-01-12", Bank, Food, 30, "Coop"))]); @@ -125,7 +127,7 @@ public class ExpenseAnalysisTestShould public void ReturnItselfAsOnlyCategoryWhenQueryingBookingTextGroup() { var node = new AnalyticsNode(40, 4000, "Migros"); - var sut = new ExpenseAnalysis([Year(2025, + var sut = new AccountingAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100, "Migros"), Booking("2025-01-12", Bank, Food, 30, "Coop"))]); @@ -138,7 +140,7 @@ public class ExpenseAnalysisTestShould [Fact] public void BuildBreadcrumbWithNamesWhenQueryingBookingTextGroup() { - var sut = new ExpenseAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100, "Migros"))]); + var sut = new AccountingAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100, "Migros"))]); var result = sut.Query(Query(2025, 2025, new AnalyticsNode(40, 4000, "Migros"))); @@ -149,7 +151,7 @@ public class ExpenseAnalysisTestShould [Fact] public void CountBookingsInTheirBookYearWhenDatedOutsideIt() { - var sut = new ExpenseAnalysis( + var sut = new AccountingAnalysis( [ Year(2024, Booking("2023-12-29", Bank, Food, 10), Booking("2025-01-02", Bank, Food, 20)), Year(2025, Booking("2025-03-10", Bank, Food, 30)) @@ -167,7 +169,7 @@ public class ExpenseAnalysisTestShould [Fact] public void StopAtLastMonthWithDataWhenRangeIncludesRunningYear() { - var sut = new ExpenseAnalysis([Year(2026, + var sut = new AccountingAnalysis([Year(2026, Booking("2026-01-10", Bank, Food, 100), Booking("2026-03-10", Bank, Food, 200))]); @@ -182,7 +184,7 @@ public class ExpenseAnalysisTestShould [Fact] public void SumIntoQuartersAndYearsWhenPeriodIsCoarser() { - var sut = new ExpenseAnalysis( + var sut = new AccountingAnalysis( [ Year(2024, Booking("2024-02-10", Bank, Food, 10), Booking("2024-11-10", Bank, Food, 20)), Year(2025, Booking("2025-05-10", Bank, Food, 30), Booking("2025-12-10", Bank, Food, 40)) @@ -200,7 +202,7 @@ public class ExpenseAnalysisTestShould [Fact] public void LeaveOutYearsOutsideRangeWhenQuerying() { - var sut = new ExpenseAnalysis( + var sut = new AccountingAnalysis( [ Year(2024, Booking("2024-02-10", Bank, Food, 10)), Year(2025, Booking("2025-02-10", Bank, Food, 30)) @@ -215,7 +217,7 @@ public class ExpenseAnalysisTestShould [Fact] public void CompareSameMonthsOfPreviousYearWhenYearIsRunning() { - var sut = new ExpenseAnalysis( + var sut = new AccountingAnalysis( [ Year(2025, Booking("2025-01-10", Bank, Food, 100), Booking("2025-09-10", Bank, Food, 500)), Year(2026, Booking("2026-01-10", Bank, Food, 150), Booking("2026-02-10", Bank, Food, 50)) @@ -235,7 +237,7 @@ public class ExpenseAnalysisTestShould [Fact] public void ReturnNoComparisonWhenPreviousYearHasNoData() { - var sut = new ExpenseAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100))]); + var sut = new AccountingAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100))]); sut.Query(Query(2025, 2025)).Comparison.ShouldBeNull(); } @@ -243,7 +245,7 @@ public class ExpenseAnalysisTestShould [Fact] public void ReturnEmptyResultWhenThereIsNoData() { - var sut = new ExpenseAnalysis([]); + var sut = new AccountingAnalysis([]); var result = sut.Query(Query(2025, 2025)); @@ -256,7 +258,7 @@ public class ExpenseAnalysisTestShould [Fact] public void LeaveMonthsWithoutDataEmptyWhenBuildingYearProfiles() { - var sut = new ExpenseAnalysis( + var sut = new AccountingAnalysis( [ Year(2025, Booking("2025-01-10", Bank, Food, 100), Booking("2025-12-10", Bank, Food, 50)), Year(2026, Booking("2026-02-10", Bank, Food, 70)) @@ -277,7 +279,7 @@ public class ExpenseAnalysisTestShould [Fact] public void CompareSameMonthsWithPreviousYearWhenBuildingCategoryYears() { - var sut = new ExpenseAnalysis( + var sut = new AccountingAnalysis( [ Year(2024, Booking("2024-01-10", Bank, Food, 100), Booking("2024-06-10", Bank, Rent, 400)), Year(2025, Booking("2025-01-10", Bank, Food, 150), Booking("2025-06-10", Bank, Rent, 500), Booking("2025-11-10", Bank, Rent, 999)), @@ -300,7 +302,7 @@ public class ExpenseAnalysisTestShould [Fact] public void ReturnNoChangeWhenYearBeforeHasNoData() { - var sut = new ExpenseAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100))]); + var sut = new AccountingAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100))]); sut.Query(Query(2025, 2025)).CategoryYears.Single().Cells.Single().ChangePercent.ShouldBeNull(); } @@ -308,7 +310,7 @@ public class ExpenseAnalysisTestShould [Fact] public void NestAccountsInSubClassesWhenBuildingComposition() { - var sut = new ExpenseAnalysis([Year(2025, + var sut = new AccountingAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100), Booking("2025-01-11", Bank, Restaurant, 40), Booking("2025-01-12", Bank, Rent, 1000))]); @@ -327,7 +329,7 @@ public class ExpenseAnalysisTestShould [Fact] public void UseSingleLevelWhenBuildingCompositionForAccount() { - var sut = new ExpenseAnalysis([Year(2025, + var sut = new AccountingAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100, "Migros"), Booking("2025-01-11", Bank, Food, 30, "Coop"))]); @@ -339,7 +341,7 @@ public class ExpenseAnalysisTestShould [Fact] public void LeaveOutNegativeAmountsWhenBuildingComposition() { - var sut = new ExpenseAnalysis([Year(2025, + var sut = new AccountingAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100), Booking("2025-01-11", Restaurant, Bank, 40))]); @@ -347,4 +349,129 @@ public class ExpenseAnalysisTestShould items.Single().ParentName.ShouldBe("Lebensmittel"); } + + private static AnalyticsQuery ViewQuery(AnalyticsView view, int from, int to, AnalyticsNode? node = null, AnalyticsPeriod period = AnalyticsPeriod.Month) + => new(from, to, period, node ?? AnalyticsNode.All, view); + + [Fact] + public void CountBookingsFromIncomeAccountsWhenViewIsIncome() + { + var sut = new AccountingAnalysis([Year(2025, + Booking("2025-01-25", Salary, Bank, 5000), + Booking("2025-02-01", Bank, Salary, 200), + Booking("2025-02-10", Bank, Food, 100))]); + + var result = sut.Query(ViewQuery(AnalyticsView.Income, 2025, 2025)); + + result.Total.ShouldBe(4800); + result.Breadcrumb.Single().Name.ShouldBe("Einnahmen"); + result.Categories.Single().Node.ShouldBe(new AnalyticsNode(SubClass: 30)); + } + + [Fact] + public void SubtractExpensesFromIncomeWhenViewIsNet() + { + var sut = new AccountingAnalysis([Year(2025, + Booking("2025-01-25", Salary, Bank, 5000), + Booking("2025-01-26", Bank, Food, 100), + Booking("2025-02-01", Bank, Rent, 1000))]); + + var result = sut.Query(ViewQuery(AnalyticsView.Net, 2025, 2025)); + + result.Total.ShouldBe(3900); + // Ordered by size, so big expenses aren't folded into "Andere". + result.Categories.Select(c => (c.Name, c.Total)).ShouldBe([("Lohn", 5000m), ("Wohnen", -1000m), ("Verpflegung", -100m)]); + result.Categories[2].Values.ShouldBe([-100m, 0m]); + } + + private static readonly Account Savings = new() { Id = "savings", Number = 1030, Name = "Sparkonto", StartBalance = 1000 }; + private static readonly Account Euro = new() { Id = "euro", Number = 1001, Name = "Bargeld EUR", Currency = "EUR", StartBalance = 100 }; + + private static YearData AssetYear(int year, decimal savingsStart, params Transaction[] transactions) + => new(year, + [Bank, Salary, Food, new Account { Id = Savings.Id, Number = Savings.Number, Name = Savings.Name, StartBalance = savingsStart }, Euro], + SubClasses, + transactions); + + [Fact] + public void ReturnMonthEndBalancesWhenViewIsAssets() + { + var sut = new AccountingAnalysis([AssetYear(2025, 1000, + Booking("2025-01-25", Salary, Savings, 500), + Booking("2025-03-10", Savings, Food, 200))]); + + var result = sut.Query(new AnalyticsQuery(2025, 2025, AnalyticsPeriod.Month, new AnalyticsNode(SubClass: 10), AnalyticsView.Assets)); + + var savings = result.Categories.Single(c => c.Name == "Sparkonto"); + savings.Values.ShouldBe([1500m, 1500m, 1300m]); + savings.Total.ShouldBe(1300); + savings.CanDrillDown.ShouldBeFalse(); + result.Opening.ShouldBe(1100); // 1000 savings + 100 EUR at a rate of 1 + } + + [Fact] + public void TakeBalanceAtPeriodEndWhenSummingAssetsByQuarter() + { + var sut = new AccountingAnalysis([AssetYear(2025, 1000, + Booking("2025-01-25", Salary, Savings, 500), + Booking("2025-05-10", Savings, Food, 200), + Booking("2025-07-10", Salary, Bank, 1))]); + + var result = sut.Query(new AnalyticsQuery(2025, 2025, AnalyticsPeriod.Quarter, new AnalyticsNode(10, 1030), AnalyticsView.Assets)); + + // Q1 ends with 1500, Q2 with 1300; Q3 is cut off at July, the last month with data. + result.Categories.Single().Values.ShouldBe([1500m, 1300m, 1300m]); + result.Total.ShouldBe(1300); + } + + private static Transaction WithFxRate(Transaction transaction, decimal fxRate) + { + transaction.FxRate = fxRate; + return transaction; + } + + [Fact] + public void ConvertForeignBalancesOnceWhenViewIsAssets() + { + var asked = new List(); + var sut = new AccountingAnalysis( + [AssetYear(2025, 0, WithFxRate(Booking("2025-02-01", Bank, Euro, 93, "Wechsel"), 0.93m))], + currency => { asked.Add(currency); return 0.9m; }); + + var result = sut.Query(new AnalyticsQuery(2025, 2025, AnalyticsPeriod.Month, new AnalyticsNode(10, 1001), AnalyticsView.Assets)); + + // 100 EUR opening + 93 CHF booked at 0.93 = 200 EUR, at 0.9 CHF per EUR. + result.Total.ShouldBe(180); + asked.ShouldBe(["EUR"]); + } + + [Fact] + public void CompareBalancesAtSameMonthWhenViewIsAssets() + { + var sut = new AccountingAnalysis( + [ + AssetYear(2025, 1000, Booking("2025-02-10", Salary, Savings, 100), Booking("2025-11-10", Salary, Savings, 900)), + AssetYear(2026, 2000, Booking("2026-02-10", Salary, Savings, 300)) + ]); + + var result = sut.Query(new AnalyticsQuery(2025, 2026, AnalyticsPeriod.Year, new AnalyticsNode(10, 1030), AnalyticsView.Assets)); + + result.Comparison.ShouldNotBeNull(); + result.Comparison.Current.ShouldBe(2300); // Feb 2026 + result.Comparison.Previous.ShouldBe(1100); // Feb 2025, not Dec + result.YearProfiles.Select(p => p.Total).ShouldBe([2000m, 2300m]); + result.CategoryYears.Single().Cells.Select(c => c.Value).ShouldBe([2000m, 2300m]); + } + + [Fact] + public void StopAtAccountWhenDrillingIntoAssets() + { + var sut = new AccountingAnalysis([AssetYear(2025, 1000, Booking("2025-01-25", Salary, Savings, 500, "Lohn Januar"))]); + + var result = sut.Query(new AnalyticsQuery(2025, 2025, AnalyticsPeriod.Month, new AnalyticsNode(10, 1030, "Lohn"), AnalyticsView.Assets)); + + result.Breadcrumb.Select(b => b.Name).ShouldBe(["Vermögen", "Bargeld, Konten", "Sparkonto"]); + result.Categories.Single().Node.ShouldBe(new AnalyticsNode(10, 1030)); + result.Composition.Single().Child.ShouldBeNull(); + } } diff --git a/Schaad.Accounting.UI/Components/Layout/NavMenu.razor b/Schaad.Accounting.UI/Components/Layout/NavMenu.razor index eb6a1e8..0a8359d 100644 --- a/Schaad.Accounting.UI/Components/Layout/NavMenu.razor +++ b/Schaad.Accounting.UI/Components/Layout/NavMenu.razor @@ -17,7 +17,6 @@ Analyse - Vermögen Erfolgsrechnung @@ -30,5 +29,33 @@ @code { + // Below this width the expanded menu would take half the screen, so it starts collapsed + // (icons only); the toggle still opens it. + private const int CollapseBelowWidth = 700; + private bool expanded = true; + + [Inject] + private IJSRuntime js { get; set; } = null!; + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (firstRender == false) + { + return; + } + try + { + await using var viewport = await js.InvokeAsync("import", "./js/viewport.js"); + if (await viewport.InvokeAsync("width") < CollapseBelowWidth) + { + expanded = false; + StateHasChanged(); + } + } + catch (JSDisconnectedException) + { + // Circuit gone before the first render finished; nothing to adjust. + } + } } \ No newline at end of file diff --git a/Schaad.Accounting.UI/Components/MyHeader.razor b/Schaad.Accounting.UI/Components/MyHeader.razor index 6ea08f6..32cb00d 100644 --- a/Schaad.Accounting.UI/Components/MyHeader.razor +++ b/Schaad.Accounting.UI/Components/MyHeader.razor @@ -1,16 +1,16 @@ @rendermode InteractiveServer -AccountingNext +AccountingNext - -
- - @for (var i = 0; i < result.Breadcrumb.Count; i++) +
+ @foreach (var v in Views) { - var crumb = result.Breadcrumb[i]; - if (i < result.Breadcrumb.Count - 1) - { - @crumb.Name - } - else - { - @crumb.Name - } + @ViewName(v) } - +
+ + @for (var i = 0; i < result.Breadcrumb.Count; i++) + { + var crumb = result.Breadcrumb[i]; + if (i < result.Breadcrumb.Count - 1) + { + @crumb.Name + } + else + { + @crumb.Name + } + } + +
- -
Total @RangeLabel
-
@Chf(result.Total)
-
@CurrentName
-
- -
Ø pro Monat
-
@Chf(result.AveragePerMonth)
-
über @result.Months Monate
-
+ @if (IsAssets) + { + +
Stand Ende @EndLabel
+
@Chf(result.Total)
+
@CurrentName
+
+ +
Veränderung seit Anfang @fromYear
+ @{ var change = result.Total - (result.Opening ?? 0); } +
@((change > 0 ? "+" : "") + Chf(change))
+
Anfangsbestand @Chf(result.Opening ?? 0)
+
+ } + else + { + +
@(IsNet ? "Überschuss" : "Total") @RangeLabel
+
@Chf(result.Total)
+
@CurrentName
+
+ +
Ø pro Monat
+
@Chf(result.AveragePerMonth)
+
über @result.Months Monate
+
+ } @if (result.Comparison is { } comparison) { -
@ComparisonLabel(comparison)
+
@(IsAssets ? $"Ende {EndLabel} vs. Vorjahr" : ComparisonLabel(comparison))
@ChangeLabel(comparison)
@Chf(comparison.Current) statt @Chf(comparison.Previous)
} @@ -86,24 +112,33 @@ }
-
Grösster Posten
- @if (result.Categories.Count > 0) + @if (IsNet && node.Level == AnalyticsLevel.All) { - var top = result.Categories[0]; -
@top.Name
-
@Chf(top.Total), @Percent(top.Share)
+
Sparquote
+
@(NetIncome == 0 ? "–" : Percent(result.Total / NetIncome))
+
Einnahmen @Whole(NetIncome), Ausgaben @Whole(NetExpenses)
} else { -
–
-
keine Ausgaben im Zeitraum
+
Grösster Posten
+ @if (result.Categories.Count > 0) + { + var top = result.Categories[0]; +
@top.Name
+
@Chf(top.Total)@(IsNet ? "" : ", " + Percent(top.Share))
+ } + else + { +
–
+
keine Daten im Zeitraum
+ } }
-
@CurrentName im Verlauf
+
@CurrentName im Verlauf@(IsAssets ? " (Stand Ende Periode)" : "")
@if (result.Categories.Count > 0) { Keine Ausgaben im gewählten Zeitraum.
+
Keine Daten im gewählten Zeitraum.
} -
@ChildLevelName
+
@ChildLevelName@(IsAssets ? $" (Ende {EndLabel})" : "")
@for (var i = 0; i < result.Categories.Count; i++) @@ -137,11 +172,17 @@ { @category.Name } - + @if (IsNet == false) + { + + } } @@ -154,12 +195,16 @@ {
-
Zusammensetzung @RangeLabel
- @if (result.Composition.Count > 0) +
Zusammensetzung @(IsAssets ? $"Ende {EndLabel}" : RangeLabel)
+ @if (IsNet) + { +
Für Netto nicht verfügbar: Ausgaben sind negativ und lassen sich nicht als Fläche zeigen. Die Ansichten Einnahmen und Ausgaben zeigen die Zusammensetzung.
+ } + else if (result.Composition.Count > 0) { -
Fläche entspricht dem Betrag; Rückerstattungen (negative Beträge) sind nicht enthalten.@(CanDrillDown ? " Klick auf eine Fläche zeigt die Details." : "")
+
@(IsAssets ? "Fläche entspricht dem Saldo; negative Saldi sind nicht enthalten." : "Fläche entspricht dem Betrag; Rückerstattungen (negative Beträge) sind nicht enthalten.")@(CanDrillDown ? " Klick auf eine Fläche zeigt die Details." : "")
} else { @@ -169,18 +214,21 @@
-
Jahresvergleich
-
- Monatlich - Kumuliert -
+
Jahresvergleich@(IsAssets ? " (Stand Ende Monat)" : "")
+ @if (IsAssets == false) + { +
+ Monatlich + Kumuliert +
+ }
+ AriaLabel="@($"{CurrentName} pro Monat, eine Linie pro Jahr{(IsAssets ? ", Stand Ende Monat" : cumulative ? ", kumuliert" : ", monatlich")}")"/>
@@ -195,14 +243,14 @@ { } - + @foreach (var row in result.CategoryYears) { -
@Chf(category.Total) - + @if (IsNet == false) + { + + }
@YearHeader(profile.Year)Total@(IsAssets ? "Ende" : "Total")
+ @if (row.CanDrillDown) { @row.Name @@ -242,7 +290,7 @@
-
Beträge in CHF; Farbe = Ø pro Monat, damit ein laufendes Jahr vergleichbar bleibt; Prozent = Veränderung zum Vorjahr.@(lastYearMonths < 12 ? " " + PartialYearNote : "")
+
@TableNote@(lastYearMonths < 12 ? " " + PartialYearNote : "")
} diff --git a/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.cs b/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.cs index 6a200f2..be7807c 100644 --- a/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.cs +++ b/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.cs @@ -8,16 +8,17 @@ using Schaad.Accounting.UI.Components.Pages.Charts; namespace Schaad.Accounting.UI.Components.Pages.Analytics; /// -/// 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. +/// 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. /// 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, @@ -33,6 +34,9 @@ public partial class Analytics : ComponentBase [Inject] private NavigationManager navigation { get; set; } = null!; + [SupplyParameterFromQuery(Name = "view")] + public string? View { get; set; } + [SupplyParameterFromQuery(Name = "from")] public int? From { get; set; } @@ -52,8 +56,9 @@ public partial class Analytics : ComponentBase public string? Text { get; set; } private string mandator = ""; - private ExpenseAnalysis? analysis; + private AccountingAnalysis? analysis; private AnalyticsResult? result; + private AnalyticsView view; private AnalyticsNode node = AnalyticsNode.All; private int fromYear; private int toYear; @@ -71,14 +76,14 @@ public partial class Analytics : ComponentBase 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; + // 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.GetExpenseAnalysisAsync(); + analysis = await analyticsService.GetAnalysisAsync(); } protected override void OnParametersSet() @@ -96,18 +101,23 @@ public partial class Analytics : ComponentBase (fromYear, toYear) = (toYear, fromYear); } period = ParsePeriod(Period) ?? (fromYear == toYear ? AnalyticsPeriod.Month : AnalyticsPeriod.Quarter); + view = Enum.TryParse(View, ignoreCase: true, out var parsedView) ? parsedView : AnalyticsView.Expenses; - node = Acc is { } account ? new AnalyticsNode(account / 100, account, Text) + 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)); + 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". @@ -135,7 +145,15 @@ public partial class Analytics : ComponentBase 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 }; + + // 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) @@ -155,7 +173,7 @@ public partial class Analytics : ComponentBase var parent = parents[item.Parent]; names[parent.Id] = item.ParentName; colors[parent.Id] = parent.Color; - if (item.Parent.Level != AnalyticsLevel.Text) + if (data.Categories.First(c => c.Node == item.Parent).CanDrillDown) { treemapNodes[parent.Id] = item.Parent; } @@ -184,7 +202,8 @@ public partial class Analytics : ComponentBase 1 => ChartTheme.Categorical[1], _ => OlderYearColors[Math.Min(age - 2, OlderYearColors.Length - 1)] }; - var values = cumulative ? RunningTotal(profile.Months) : profile.Months; + // 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 }; @@ -205,13 +224,21 @@ public partial class Analytics : ComponentBase private void BuildYearTable(AnalyticsResult data) { lastYearMonths = data.YearProfiles[^1].Months.Count(m => m is not null); - maxMonthlyAverage = data.CategoryYears + maxHeat = data.CategoryYears .SelectMany(row => row.Cells) - .Select(cell => cell.Value / MonthsOf(cell.Year)) + .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) @@ -262,11 +289,19 @@ public partial class Analytics : ComponentBase 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 { + ["view"] = viewValue, ["from"] = from, ["to"] = to, ["period"] = periodValue, @@ -275,6 +310,9 @@ public partial class Analytics : ComponentBase ["text"] = target.Text }); + private static string? ViewValue(AnalyticsView value) + => value == AnalyticsView.Expenses ? null : value.ToString().ToLowerInvariant(); + private static AnalyticsPeriod? ParsePeriod(string? value) => Enum.TryParse(value, ignoreCase: true, out var parsed) ? parsed : null; @@ -292,19 +330,35 @@ public partial class Analytics : ComponentBase _ => "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); @@ -317,18 +371,29 @@ public partial class Analytics : ComponentBase 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 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) { - if (maxMonthlyAverage <= 0 || cell.Value <= 0) + var value = HeatValue(cell); + if (maxHeat <= 0 || value <= 0) { return "transparent"; } - var intensity = Math.Min(cell.Value / MonthsOf(cell.Year) / maxMonthlyAverage, 1); + 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 $"rgba(42, 120, 214, {(0.06m + intensity * 0.5m).ToString("0.###", CultureInfo.InvariantCulture)})"; + 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) @@ -342,8 +407,16 @@ public partial class Analytics : ComponentBase 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", _ => "" }; + // 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() { diff --git a/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.css b/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.css index fd42d3e..db84fda 100644 --- a/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.css +++ b/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.css @@ -45,6 +45,9 @@ .kpi-value { font-size: 24px; + /* Fluent sets a fixed 20px line height; at 24px the descenders (g, p, y) would stick out of + the box and get cut where the text is truncated with an ellipsis. */ + line-height: 1.3; font-weight: 600; margin: 4px 0 2px; font-variant-numeric: tabular-nums; @@ -57,11 +60,11 @@ white-space: nowrap; } -.kpi-value.up { +.kpi-value.worse { color: #c50f1f; } -.kpi-value.down { +.kpi-value.better { color: #107c10; } @@ -264,10 +267,48 @@ min-height: 14px; } -.change.up { +.change.worse { color: #c50f1f; } -.change.down { +.change.better { color: #107c10; } + +.segmented.views { + margin-left: 0; +} + +/* Narrow screens: button groups and the category list wrap instead of widening the page. */ +.segmented { + flex-wrap: wrap; +} + +.categories .name { + overflow-wrap: anywhere; +} + +@media (max-width: 600px) { + .segmented { + margin-left: 0; + } + + .kpis { + grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); + } + + .kpi-value { + font-size: 20px; + } +} + +/* Year table on a phone: a narrow name column that stays in place while the years scroll. */ +@media (max-width: 600px) { + .years .name { + max-width: 120px; + position: sticky; + left: 0; + z-index: 1; + background: #ffffff; + } +} diff --git a/Schaad.Accounting.UI/Components/Pages/Charts/Assets.razor b/Schaad.Accounting.UI/Components/Pages/Charts/Assets.razor deleted file mode 100644 index dabb4d9..0000000 --- a/Schaad.Accounting.UI/Components/Pages/Charts/Assets.razor +++ /dev/null @@ -1,15 +0,0 @@ -@page "/Assets" -@rendermode InteractiveServer - -Vermögen - - - @if (config is not null && layout is not null && data is not null) - { - - } - else - { - - } - diff --git a/Schaad.Accounting.UI/Components/Pages/Charts/Assets.razor.cs b/Schaad.Accounting.UI/Components/Pages/Charts/Assets.razor.cs deleted file mode 100644 index 112eb91..0000000 --- a/Schaad.Accounting.UI/Components/Pages/Charts/Assets.razor.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Microsoft.AspNetCore.Components; -using Plotly.Blazor; -using Plotly.Blazor.Traces; -using Schaad.Accounting.Datasets.Charts; -using Schaad.Accounting.Interfaces; - -namespace Schaad.Accounting.UI.Components.Pages.Charts; - -public partial class Assets : ComponentBase -{ - private PlotlyChart chart = null!; - private Config? config; - private Plotly.Blazor.Layout? layout; - private IList? data; - - [Inject] - private IViewService viewService { get; set; } = null!; - - protected override async Task OnInitializedAsync() - { - config = ChartTheme.BaseConfig(); - layout = ChartTheme.BaseLayout("Vermögen nach Konto"); - - var accounts = (await viewService.GetAccountViewListAsync()).Where(a => a.Class == ClassIds.Activa); - var totals = accounts - .Where(a => a.BalanceCHF > 0) - .Select(a => new CategoryTotal(a.Name, a.BalanceCHF)) - .ToList(); - - data = new List { ChartTheme.BuildDonutTrace(ChartFormatting.FoldTail(totals)) }; - - await base.OnInitializedAsync(); - } -} diff --git a/Schaad.Accounting.UI/wwwroot/js/charts.js b/Schaad.Accounting.UI/wwwroot/js/charts.js index c3dfd8d..6800571 100644 --- a/Schaad.Accounting.UI/wwwroot/js/charts.js +++ b/Schaad.Accounting.UI/wwwroot/js/charts.js @@ -80,12 +80,14 @@ const categoryAxis = { grid: { display: false }, ticks: { color: theme.muted } } // Each kind turns the data sent from Blazor into Chart.js data, and builds its options once. // Options read the current data through state(), so update() only has to swap the data. const kinds = { - // data: { labels, series: [{ name, color, values, clickable }] }; click key = series index + // data: { labels, series: [{ name, color, values, clickable }], totalLine?: { name, values } }; + // click key = series index. The optional line (e.g. the net result) is its own stack, so it + // shows its value instead of stacking onto the bars. stackedBar: { type: 'bar', data: data => ({ labels: data.labels, - datasets: data.series.map(s => ({ + datasets: [...data.series.map(s => ({ label: s.name, data: s.values, backgroundColor: s.color, @@ -95,7 +97,18 @@ const kinds = { borderRadius: 3, stack: 'total', clickable: s.clickable - })) + })), ...(data.totalLine ? [{ + type: 'line', + label: data.totalLine.name, + data: data.totalLine.values, + stack: 'line', + borderColor: theme.ink, + backgroundColor: theme.ink, + borderWidth: 2, + pointRadius: 2, + tension: 0.25, + order: -1 + }] : [])] }), options: () => ({ interaction: { mode: 'index', intersect: false }, @@ -107,7 +120,12 @@ const kinds = { itemSort: (a, b) => b.parsed.y - a.parsed.y, callbacks: { label: item => ` ${item.dataset.label}: ${formatChf(item.parsed.y)} CHF`, - footer: items => `Total: ${formatChf(items.reduce((sum, i) => sum + i.parsed.y, 0))} CHF` + footer: items => { + const bars = items.filter(i => i.dataset.type !== 'line'); + return bars.length === items.length + ? `Total: ${formatChf(bars.reduce((sum, i) => sum + i.parsed.y, 0))} CHF` + : ''; + } } } }, diff --git a/Schaad.Accounting.UI/wwwroot/js/viewport.js b/Schaad.Accounting.UI/wwwroot/js/viewport.js new file mode 100644 index 0000000..d60ff98 --- /dev/null +++ b/Schaad.Accounting.UI/wwwroot/js/viewport.js @@ -0,0 +1,4 @@ +// Viewport helpers for Blazor components that need the window size on first render. +export function width() { + return window.innerWidth; +}