Analyse page: income, net and assets views; narrow-screen layout (#6)
## Summary
Step 4 of the analytics plan, items 2, 4 and 5: **income, net and assets views** on the Analyse page (replacing the old Vermögen chart page) and a **narrow-screen layout** pass.
### Views
A switch at the top selects **Ausgaben | Einnahmen | Netto | Vermögen**, stored in the URL as `view=`. Switching starts the drill-down from the top, because the subclasses differ per view.
- **Einnahmen:** works like Ausgaben. Bookings *from* an income account count positive, bookings *to* one (corrections) negative.
- **Netto:** income minus expenses. Income subclasses are positive and expense subclasses negative.
- The bar chart stacks income up and expenses down, with a black line for the net result per period; the tooltip total is left out there.
- Categories are ordered by size, so the big expense groups aren't folded into "Andere".
- The fourth tile shows the **savings rate** (net / income).
- No treemap, since areas can't show negative amounts.
- **Vermögen:** month-end balances of the asset accounts (class 1) in CHF. It is a stock, not a flow:
- A month, quarter or year shows the balance at its end, and the total is the balance at the end of the range.
- Tiles show that balance, the change since the start of the range (with the opening balance), and the comparison with the same month a year earlier.
- The year table shows year-end balances; the drill-down ends at the account.
- The year comparison shows month-end balances, without the cumulative switch.
- Foreign-currency balances are computed like the balance sheet (`ViewService`): kept in the account currency and converted with `IFxConverter`, which is asked once per currency.
- **Colours follow the view:** more expenses are red; more income, surplus or assets green. The CSS classes are now `worse` / `better` instead of `up` / `down`.
### Code
- `ExpenseAnalysis` → **`AccountingAnalysis`** with `AnalyticsView` (Expenses, Income, Net, Assets), and `GetExpenseAnalysisAsync` → `GetAnalysisAsync`. The running year's last month now comes from all bookings, not just expenses.
- `AnalyticsResult.Opening` gives the balance at the start of the range for Vermögen.
- `charts.js`: the stacked bar chart takes an optional `totalLine`.
### Removed
- The **Vermögen** chart page (`/Assets`) and its menu entry. Plotly is now only used by the booking-text charts on the Transactions page.
### Narrow screens
At 400 px the page was wider than the screen.
- **App-wide:** the side menu took half the screen. It now starts collapsed to icons below 700 px (`wwwroot/js/viewport.js`); the ☰ toggle still opens it. The header dropdowns are narrower, and the app name hides below 520 px.
- **Analyse page:** button groups wrap, the tiles sit two per row, and in the year table the name column is narrower and pinned while the years scroll, with the full name as a tooltip.
## Test plan
- [x] `dotnet build`: no warnings
- [x] `dotnet test`: 88/88 pass, including 7 new `AccountingAnalysisTestShould` tests (income signs, net ordering, month-end balances with opening, balance at period end, FX conversion asked once, comparison at the same month, assets drill-down ends at the account)
- [x] Against a copy of the real data, all matching the app's own reports:
- Einnahmen 2026 = 109'865.13 ("Total Einkünfte" in the profit-and-loss report)
- Netto 2026 = 32'859.06 (= 109'865.13 − 77'006.07)
- Vermögen end of Oct 2026 = 263'994.98 ("Total Aktiven" in the Bilanz)
- [x] Headless Chrome at 400, 820 and 1500 px: no horizontal overflow; menu collapsed at 400 px and expanded at 820 / 1500 px; pinned table column scrolls correctly; all charts render without console errors
## Note on the data (not a code issue)
The Vermögen view shows each year as its books say. In the real data, some closing balances don't match the next year's opening balances. These are probably bookings added to a year after the next one was opened:
- End of 2024 → 2025: Bargeld CHF (+40.75)
- End of 2025 → 2026: Bargeld CHF (+98.50), TKB Privatkonto (+200.00), account 1042 (2'030.40 at the end of 2025, missing in 2026), Durchlaufskonto (−7.29)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Reviewed-on: #6
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
This commit is contained in:
parent
00921b8dac
commit
9138f08287
17 changed files with 934 additions and 451 deletions
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -12,6 +12,21 @@ namespace Schaad.Accounting.Datasets.Analytics
|
|||
Year
|
||||
}
|
||||
|
||||
public enum AnalyticsView
|
||||
{
|
||||
/// <summary>Net expenses (class 4): bookings to an expense account minus refunds.</summary>
|
||||
Expenses,
|
||||
|
||||
/// <summary>Net income (class 3): bookings from an income account minus corrections.</summary>
|
||||
Income,
|
||||
|
||||
/// <summary>Income minus expenses: income subclasses positive, expense subclasses negative.</summary>
|
||||
Net,
|
||||
|
||||
/// <summary>Month-end balances of the asset accounts (class 1), in CHF. A stock, not a flow.</summary>
|
||||
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
|
|||
/// <summary>
|
||||
/// The last year of the range against the year before, over the same months
|
||||
/// (January to <see cref="Months"/>), so an unfinished year compares fairly.
|
||||
/// For <see cref="AnalyticsView.Assets"/> it compares the balances at the end of those months.
|
||||
/// </summary>
|
||||
public record YearComparison(int Year, int Months, decimal Current, decimal Previous)
|
||||
{
|
||||
|
|
@ -61,14 +77,16 @@ namespace Schaad.Accounting.Datasets.Analytics
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="AnalyticsView.Assets"/>. Months after the last month with data are
|
||||
/// null. <see cref="Total"/> is the year's sum, or its last balance.
|
||||
/// </summary>
|
||||
public record YearProfile(int Year, IReadOnlyList<decimal?> Months, decimal Total);
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="AnalyticsView.Assets"/>: 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.
|
||||
/// </summary>
|
||||
public record YearCell(int Year, decimal Value, decimal? ChangePercent);
|
||||
|
||||
|
|
@ -84,6 +102,10 @@ namespace Schaad.Accounting.Datasets.Analytics
|
|||
/// </summary>
|
||||
public record CompositionItem(AnalyticsNode Parent, string ParentName, AnalyticsNode? Child, string? ChildName, decimal Value);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Total"/> is the sum over the range, or for <see cref="AnalyticsView.Assets"/> the
|
||||
/// balance at its end; <see cref="Opening"/> is then the balance at its start (null otherwise).
|
||||
/// </summary>
|
||||
public record AnalyticsResult(
|
||||
IReadOnlyList<AnalyticsBreadcrumb> Breadcrumb,
|
||||
IReadOnlyList<DateOnly> Periods,
|
||||
|
|
@ -94,5 +116,6 @@ namespace Schaad.Accounting.Datasets.Analytics
|
|||
YearComparison? Comparison,
|
||||
IReadOnlyList<YearProfile> YearProfiles,
|
||||
IReadOnlyList<CategoryYears> CategoryYears,
|
||||
IReadOnlyList<CompositionItem> Composition);
|
||||
IReadOnlyList<CompositionItem> Composition,
|
||||
decimal? Opening = null);
|
||||
}
|
||||
|
|
|
|||
442
Schaad.Accounting.Services/AccountingAnalysis.cs
Normal file
442
Schaad.Accounting.Services/AccountingAnalysis.cs
Normal file
|
|
@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
///
|
||||
/// <list type="bullet">
|
||||
/// <item>Expenses: a booking to an expense account counts positive, a booking from one
|
||||
/// (refund, correction) negative.</item>
|
||||
/// <item>Income: a booking from an income account counts positive, a booking to one negative.</item>
|
||||
/// <item>Net: income positive, expenses negative.</item>
|
||||
/// <item>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.</item>
|
||||
/// </list>
|
||||
///
|
||||
/// 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 AccountingAnalysis
|
||||
{
|
||||
private const string NoTextName = "(ohne Text)";
|
||||
|
||||
private static readonly Dictionary<AnalyticsView, string> 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<AnalyticsView, List<Fact>> 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<int, string> accountNames = new();
|
||||
private readonly Dictionary<int, string> subClassNames = new();
|
||||
private readonly DateOnly? lastMonth;
|
||||
|
||||
public IReadOnlyList<int> Years { get; }
|
||||
|
||||
/// <param name="chfRate">CHF value of one unit of a currency; asked once per currency.</param>
|
||||
public AccountingAnalysis(IEnumerable<YearData> years, Func<string, decimal>? 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<string, decimal>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Same as the balance sheet (ViewService): amounts of a foreign-currency account are kept
|
||||
/// in its currency and only the balance is converted.
|
||||
/// </summary>
|
||||
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<Account, decimal> 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Booking texts mean nothing for balances, so the assets drill-down ends at the account.
|
||||
/// </summary>
|
||||
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<Fact> 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<YearProfile> GetYearProfiles(List<Fact> nodeFacts, DateOnly start, DateOnly end, bool isStock)
|
||||
{
|
||||
var profiles = new List<YearProfile>();
|
||||
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<CategoryYears> GetCategoryYears(
|
||||
List<Fact> nodeFacts, AnalyticsNode node, AnalyticsView view, List<AnalyticsCategory> 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<Fact>();
|
||||
var cells = new List<YearCell>();
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Amounts from January to <paramref name="lastMonthOfYear"/>, or the balance at its end.
|
||||
/// </summary>
|
||||
private static decimal SumYear(List<Fact> 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<CompositionItem> GetComposition(
|
||||
List<Fact> inRange, AnalyticsNode node, AnalyticsView view, List<AnalyticsCategory> categories,
|
||||
DateOnly end, bool isStock)
|
||||
{
|
||||
var facts = isStock ? inRange.Where(f => f.Month == end).ToList() : inRange;
|
||||
var items = new List<CompositionItem>();
|
||||
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<AnalyticsBreadcrumb> GetBreadcrumb(AnalyticsNode node, AnalyticsView view)
|
||||
{
|
||||
var path = new List<AnalyticsBreadcrumb> { 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<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)
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Last month of the period containing <paramref name="month"/>, but not after the range end.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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<ExpenseAnalysis> GetExpenseAnalysisAsync()
|
||||
public async Task<AccountingAnalysis> GetAnalysisAsync()
|
||||
{
|
||||
var mandator = settingsService.GetMandator();
|
||||
var years = new List<YearData>();
|
||||
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
{
|
||||
/// <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)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -6,8 +6,8 @@ namespace Schaad.Accounting.Interfaces
|
|||
public interface IAnalyticsService
|
||||
{
|
||||
/// <summary>
|
||||
/// Expenses of the currently selected mandator over all its years.
|
||||
/// All years of the currently selected mandator, ready for in-memory queries.
|
||||
/// </summary>
|
||||
Task<ExpenseAnalysis> GetExpenseAnalysisAsync();
|
||||
Task<AccountingAnalysis> GetAnalysisAsync();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<string>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
|
@ -17,7 +17,6 @@
|
|||
</FluentNavGroup>
|
||||
<FluentNavGroup Title="Charts" Icon="@(new Size32.ChartMultiple())">
|
||||
<FluentNavLink Href="analytics" Icon="@(new Size20.DataHistogram())" IconColor="Color.Accent">Analyse</FluentNavLink>
|
||||
<FluentNavLink Href="Assets" Icon="@(new Size32.DataPie())" IconColor="Color.Accent">Vermögen</FluentNavLink>
|
||||
</FluentNavGroup>
|
||||
<FluentNavGroup Title="Reports" Icon="@(new Size32.DocumentPrint())">
|
||||
<FluentNavLink Href="ProfitLossReport" Icon="@(new Size32.DataTrending())" IconColor="Color.Accent">Erfolgsrechnung</FluentNavLink>
|
||||
|
|
@ -30,5 +29,33 @@
|
|||
</div>
|
||||
|
||||
@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<IJSObjectReference>("import", "./js/viewport.js");
|
||||
if (await viewport.InvokeAsync<int>("width") < CollapseBelowWidth)
|
||||
{
|
||||
expanded = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
catch (JSDisconnectedException)
|
||||
{
|
||||
// Circuit gone before the first render finished; nothing to adjust.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,16 +1,16 @@
|
|||
@rendermode InteractiveServer
|
||||
|
||||
AccountingNext
|
||||
<span class="brand">AccountingNext</span>
|
||||
|
||||
<FluentStack Orientation="Orientation.Horizontal" HorizontalAlignment="HorizontalAlignment.Right">
|
||||
<FluentSelect TOption="int"
|
||||
<FluentSelect TOption="int" Width="100px" aria-label="Jahr"
|
||||
Items=@years
|
||||
OptionText="@(i => i.ToString())"
|
||||
OptionValue="@(i => i.ToString())"
|
||||
@bind-SelectedOption="@selectedYear"
|
||||
ValueChanged="YearChanged"/>
|
||||
|
||||
<FluentSelect TOption="string"
|
||||
<FluentSelect TOption="string" Width="180px" aria-label="Mandant"
|
||||
Items=@mandators
|
||||
OptionText="@(i => i.ToString())"
|
||||
OptionValue="@(i => i.ToString())"
|
||||
|
|
|
|||
10
Schaad.Accounting.UI/Components/MyHeader.razor.css
Normal file
10
Schaad.Accounting.UI/Components/MyHeader.razor.css
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
.brand {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* On a phone the year and mandator matter more than the app name. */
|
||||
@media (max-width: 520px) {
|
||||
.brand {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
|
@ -18,20 +18,14 @@
|
|||
|
||||
<div class="analytics">
|
||||
<div class="toolbar">
|
||||
<FluentBreadcrumb>
|
||||
@for (var i = 0; i < result.Breadcrumb.Count; i++)
|
||||
<div class="segmented views" role="group" aria-label="Ansicht">
|
||||
@foreach (var v in Views)
|
||||
{
|
||||
var crumb = result.Breadcrumb[i];
|
||||
if (i < result.Breadcrumb.Count - 1)
|
||||
{
|
||||
<FluentBreadcrumbItem Href="@NodeUrl(crumb.Node)">@crumb.Name</FluentBreadcrumbItem>
|
||||
<FluentButton Appearance="@(v == view ? Appearance.Accent : Appearance.Neutral)"
|
||||
aria-pressed="@(v == view ? "true" : "false")"
|
||||
OnClick="@(() => SetView(v))">@ViewName(v)</FluentButton>
|
||||
}
|
||||
else
|
||||
{
|
||||
<FluentBreadcrumbItem>@crumb.Name</FluentBreadcrumbItem>
|
||||
}
|
||||
}
|
||||
</FluentBreadcrumb>
|
||||
</div>
|
||||
|
||||
<div class="filters">
|
||||
<FluentSelect TOption="int" Label="Von" Width="110px"
|
||||
|
|
@ -60,21 +54,53 @@
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<FluentBreadcrumb>
|
||||
@for (var i = 0; i < result.Breadcrumb.Count; i++)
|
||||
{
|
||||
var crumb = result.Breadcrumb[i];
|
||||
if (i < result.Breadcrumb.Count - 1)
|
||||
{
|
||||
<FluentBreadcrumbItem Href="@NodeUrl(crumb.Node)">@crumb.Name</FluentBreadcrumbItem>
|
||||
}
|
||||
else
|
||||
{
|
||||
<FluentBreadcrumbItem>@crumb.Name</FluentBreadcrumbItem>
|
||||
}
|
||||
}
|
||||
</FluentBreadcrumb>
|
||||
|
||||
<div class="kpis">
|
||||
@if (IsAssets)
|
||||
{
|
||||
<FluentCard class="kpi">
|
||||
<div class="kpi-label">Total @RangeLabel</div>
|
||||
<div class="kpi-label">Stand Ende @EndLabel</div>
|
||||
<div class="kpi-value">@Chf(result.Total)</div>
|
||||
<div class="kpi-sub ellipsis" title="@CurrentName">@CurrentName</div>
|
||||
</FluentCard>
|
||||
<FluentCard class="kpi">
|
||||
<div class="kpi-label">Veränderung seit Anfang @fromYear</div>
|
||||
@{ var change = result.Total - (result.Opening ?? 0); }
|
||||
<div class="kpi-value @ChangeClass(change)">@((change > 0 ? "+" : "") + Chf(change))</div>
|
||||
<div class="kpi-sub">Anfangsbestand @Chf(result.Opening ?? 0)</div>
|
||||
</FluentCard>
|
||||
}
|
||||
else
|
||||
{
|
||||
<FluentCard class="kpi">
|
||||
<div class="kpi-label">@(IsNet ? "Überschuss" : "Total") @RangeLabel</div>
|
||||
<div class="kpi-value @(IsNet ? ChangeClass(result.Total) : "")">@Chf(result.Total)</div>
|
||||
<div class="kpi-sub ellipsis" title="@CurrentName">@CurrentName</div>
|
||||
</FluentCard>
|
||||
<FluentCard class="kpi">
|
||||
<div class="kpi-label">Ø pro Monat</div>
|
||||
<div class="kpi-value">@Chf(result.AveragePerMonth)</div>
|
||||
<div class="kpi-sub">über @result.Months Monate</div>
|
||||
</FluentCard>
|
||||
}
|
||||
<FluentCard class="kpi">
|
||||
@if (result.Comparison is { } comparison)
|
||||
{
|
||||
<div class="kpi-label">@ComparisonLabel(comparison)</div>
|
||||
<div class="kpi-label">@(IsAssets ? $"Ende {EndLabel} vs. Vorjahr" : ComparisonLabel(comparison))</div>
|
||||
<div class="kpi-value @ChangeClass(comparison.ChangePercent)">@ChangeLabel(comparison)</div>
|
||||
<div class="kpi-sub">@Chf(comparison.Current) statt @Chf(comparison.Previous)</div>
|
||||
}
|
||||
|
|
@ -86,24 +112,33 @@
|
|||
}
|
||||
</FluentCard>
|
||||
<FluentCard class="kpi">
|
||||
@if (IsNet && node.Level == AnalyticsLevel.All)
|
||||
{
|
||||
<div class="kpi-label">Sparquote</div>
|
||||
<div class="kpi-value">@(NetIncome == 0 ? "–" : Percent(result.Total / NetIncome))</div>
|
||||
<div class="kpi-sub">Einnahmen @Whole(NetIncome), Ausgaben @Whole(NetExpenses)</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="kpi-label">Grösster Posten</div>
|
||||
@if (result.Categories.Count > 0)
|
||||
{
|
||||
var top = result.Categories[0];
|
||||
<div class="kpi-value kpi-name" title="@top.Name">@top.Name</div>
|
||||
<div class="kpi-sub">@Chf(top.Total), @Percent(top.Share)</div>
|
||||
<div class="kpi-sub">@Chf(top.Total)@(IsNet ? "" : ", " + Percent(top.Share))</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="kpi-value">–</div>
|
||||
<div class="kpi-sub">keine Ausgaben im Zeitraum</div>
|
||||
<div class="kpi-sub">keine Daten im Zeitraum</div>
|
||||
}
|
||||
}
|
||||
</FluentCard>
|
||||
</div>
|
||||
|
||||
<div class="main">
|
||||
<FluentCard class="chart-card">
|
||||
<div class="card-title">@CurrentName im Verlauf</div>
|
||||
<div class="card-title">@CurrentName im Verlauf@(IsAssets ? " (Stand Ende Periode)" : "")</div>
|
||||
@if (result.Categories.Count > 0)
|
||||
{
|
||||
<ChartJsChart Kind="stackedBar" Data="@barData" OnClick="@OnBarClick"
|
||||
|
|
@ -115,12 +150,12 @@
|
|||
}
|
||||
else
|
||||
{
|
||||
<div class="empty">Keine Ausgaben im gewählten Zeitraum.</div>
|
||||
<div class="empty">Keine Daten im gewählten Zeitraum.</div>
|
||||
}
|
||||
</FluentCard>
|
||||
|
||||
<FluentCard class="list-card">
|
||||
<div class="card-title">@ChildLevelName</div>
|
||||
<div class="card-title">@ChildLevelName@(IsAssets ? $" (Ende {EndLabel})" : "")</div>
|
||||
<table class="categories">
|
||||
<tbody>
|
||||
@for (var i = 0; i < result.Categories.Count; i++)
|
||||
|
|
@ -137,11 +172,17 @@
|
|||
{
|
||||
@category.Name
|
||||
}
|
||||
@if (IsNet == false)
|
||||
{
|
||||
<div class="share-bar"><div style="width: @ShareWidth(category.Share); background: @ColorFor(i)"></div></div>
|
||||
}
|
||||
</td>
|
||||
<td class="amount">
|
||||
@Chf(category.Total)
|
||||
@if (IsNet == false)
|
||||
{
|
||||
<div class="share">@Percent(category.Share)</div>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
|
|
@ -154,12 +195,16 @@
|
|||
{
|
||||
<div class="pair">
|
||||
<FluentCard class="chart-card">
|
||||
<div class="card-title">Zusammensetzung @RangeLabel</div>
|
||||
@if (result.Composition.Count > 0)
|
||||
<div class="card-title">Zusammensetzung @(IsAssets ? $"Ende {EndLabel}" : RangeLabel)</div>
|
||||
@if (IsNet)
|
||||
{
|
||||
<div class="empty">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.</div>
|
||||
}
|
||||
else if (result.Composition.Count > 0)
|
||||
{
|
||||
<ChartJsChart Kind="treemap" Data="@treemapData" OnClick="@OnTreemapClick" Height="380px"
|
||||
AriaLabel="@($"Zusammensetzung {CurrentName} {RangeLabel} als Flächen")"/>
|
||||
<div class="hint">Fläche entspricht dem Betrag; Rückerstattungen (negative Beträge) sind nicht enthalten.@(CanDrillDown ? " Klick auf eine Fläche zeigt die Details." : "")</div>
|
||||
<div class="hint">@(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." : "")</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
@ -169,7 +214,9 @@
|
|||
|
||||
<FluentCard class="chart-card">
|
||||
<div class="card-header">
|
||||
<div class="card-title">Jahresvergleich</div>
|
||||
<div class="card-title">Jahresvergleich@(IsAssets ? " (Stand Ende Monat)" : "")</div>
|
||||
@if (IsAssets == false)
|
||||
{
|
||||
<div class="segmented small" role="group" aria-label="Darstellung">
|
||||
<FluentButton Appearance="@(cumulative ? Appearance.Neutral : Appearance.Accent)"
|
||||
aria-pressed="@(cumulative ? "false" : "true")"
|
||||
|
|
@ -178,9 +225,10 @@
|
|||
aria-pressed="@(cumulative ? "true" : "false")"
|
||||
OnClick="@(() => SetCumulative(true))">Kumuliert</FluentButton>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<ChartJsChart Kind="line" Data="@lineData" Height="380px"
|
||||
AriaLabel="@($"{CurrentName} pro Monat, eine Linie pro Jahr, {(cumulative ? "kumuliert" : "monatlich")}")"/>
|
||||
AriaLabel="@($"{CurrentName} pro Monat, eine Linie pro Jahr{(IsAssets ? ", Stand Ende Monat" : cumulative ? ", kumuliert" : ", monatlich")}")"/>
|
||||
</FluentCard>
|
||||
</div>
|
||||
|
||||
|
|
@ -195,14 +243,14 @@
|
|||
{
|
||||
<th scope="col">@YearHeader(profile.Year)</th>
|
||||
}
|
||||
<th scope="col" class="total">Total</th>
|
||||
<th scope="col" class="total">@(IsAssets ? "Ende" : "Total")</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var row in result.CategoryYears)
|
||||
{
|
||||
<tr @key="row.Node">
|
||||
<th scope="row" class="name">
|
||||
<th scope="row" class="name" title="@row.Name">
|
||||
@if (row.CanDrillDown)
|
||||
{
|
||||
<a href="@NodeUrl(row.Node)">@row.Name</a>
|
||||
|
|
@ -242,7 +290,7 @@
|
|||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
<div class="hint">Beträge in CHF; Farbe = Ø pro Monat, damit ein laufendes Jahr vergleichbar bleibt; Prozent = Veränderung zum Vorjahr.@(lastYearMonths < 12 ? " " + PartialYearNote : "")</div>
|
||||
<div class="hint">@TableNote@(lastYearMonths < 12 ? " " + PartialYearNote : "")</div>
|
||||
</FluentCard>
|
||||
}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -8,16 +8,17 @@ using Schaad.Accounting.UI.Components.Pages.Charts;
|
|||
namespace Schaad.Accounting.UI.Components.Pages.Analytics;
|
||||
|
||||
/// <summary>
|
||||
/// Expenses of the selected mandator over all years, with drill-down
|
||||
/// all → subclass → account → booking-text group. Every filter and the drill-down position
|
||||
/// live in the URL, so back/forward and bookmarks work; the data is loaded once and every
|
||||
/// change is an in-memory query.
|
||||
/// Expenses, income, net result or assets of the selected mandator over all years, with
|
||||
/// drill-down all → subclass → account → booking-text group (assets: down to the account).
|
||||
/// Every filter and the drill-down position live in the URL, so back/forward and bookmarks work;
|
||||
/// the data is loaded once and every change is an in-memory query.
|
||||
/// </summary>
|
||||
public partial class Analytics : ComponentBase
|
||||
{
|
||||
private static readonly CultureInfo Swiss = new("de-CH");
|
||||
private static readonly CultureInfo SwissNumbers = CreateSwissNumbers();
|
||||
private static readonly AnalyticsPeriod[] Periods = [AnalyticsPeriod.Month, AnalyticsPeriod.Quarter, AnalyticsPeriod.Year];
|
||||
private static readonly AnalyticsView[] Views = [AnalyticsView.Expenses, AnalyticsView.Income, AnalyticsView.Net, AnalyticsView.Assets];
|
||||
private static readonly string[] MonthNames = ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"];
|
||||
|
||||
// Year-comparison lines: the latest year in the accent colour, the one before in orange,
|
||||
|
|
@ -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<AnalyticsView>(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<string, object?>
|
||||
{
|
||||
["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<AnalyticsPeriod>(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()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +0,0 @@
|
|||
@page "/Assets"
|
||||
@rendermode InteractiveServer
|
||||
|
||||
<PageTitle>Vermögen</PageTitle>
|
||||
|
||||
<FluentCard Style="padding: 16px; max-width: 900px;">
|
||||
@if (config is not null && layout is not null && data is not null)
|
||||
{
|
||||
<PlotlyChart style="height: 560px; min-height: 420px" @bind-Config="config" @bind-Layout="layout" @bind-Data="data" @ref="chart" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<Loading/>
|
||||
}
|
||||
</FluentCard>
|
||||
|
|
@ -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<ITrace>? 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<ITrace> { ChartTheme.BuildDonutTrace(ChartFormatting.FoldTail(totals)) };
|
||||
|
||||
await base.OnInitializedAsync();
|
||||
}
|
||||
}
|
||||
|
|
@ -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`
|
||||
: '';
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
|
|||
4
Schaad.Accounting.UI/wwwroot/js/viewport.js
Normal file
4
Schaad.Accounting.UI/wwwroot/js/viewport.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
// Viewport helpers for Blazor components that need the window size on first render.
|
||||
export function width() {
|
||||
return window.innerWidth;
|
||||
}
|
||||
Loading…
Reference in a new issue