Add Analyse page: expenses over all years with drill-down #4

Merged
clayschaad merged 2 commits from analytics into main 2026-10-22 14:02:09 +00:00
30 changed files with 1552 additions and 336 deletions

View file

@ -56,8 +56,9 @@ When a new year is opened, the previous year's data is copied as the starting po
- **ViewService** — aggregates account balances, applies FX rates, builds datasets for the UI - **ViewService** — aggregates account balances, applies FX rates, builds datasets for the UI
- **FileService** — imports bank statements (MT940, CAMT053 via external `Schaad.Finance.dll`), parses PDFs, manages backups - **FileService** — imports bank statements (MT940, CAMT053 via external `Schaad.Finance.dll`), parses PDFs, manages backups
- **ChartService** — produces data for Plotly charts (assets, spendings over time) - **ChartService** — produces data for the Plotly booking-text charts on the transactions page
- **SettingsService** — manages the active year, mandator, and file paths - **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
### UI structure ### UI structure
@ -66,7 +67,8 @@ Pages live in `Schaad.Accounting.UI/Components/Pages/`. Each page typically has
### Key external dependencies ### Key external dependencies
- `Microsoft.FluentUI.AspNetCore.Components` — UI components (FluentDataGrid, FluentDialog, etc.) - `Microsoft.FluentUI.AspNetCore.Components` — UI components (FluentDataGrid, FluentDialog, etc.)
- `Plotly.Blazor` — charts - `Plotly.Blazor` — charts on the older chart pages
- Chart.js 4 — charts on the Analyse page; vendored in `wwwroot/lib/chartjs` (no CDN), wrapped by `wwwroot/js/charts.js` and `StackedBarChart.razor`
- `FreeSpire.PDF` — PDF parsing for bank statement imports - `FreeSpire.PDF` — PDF parsing for bank statement imports
- `Schaad.Finance.dll` / `Schaad.Finance.Api.dll` — proprietary DLLs for MT940/CAMT053 parsing and FX rate lookups (FixerIo API key in `appsettings.Development.json`) - `Schaad.Finance.dll` / `Schaad.Finance.Api.dll` — proprietary DLLs for MT940/CAMT053 parsing and FX rate lookups (FixerIo API key in `appsettings.Development.json`)

View file

@ -0,0 +1,71 @@
#nullable enable
using System;
using System.Collections.Generic;
namespace Schaad.Accounting.Datasets.Analytics
{
public enum AnalyticsPeriod
{
Month,
Quarter,
Year
}
public enum AnalyticsLevel
{
All,
SubClass,
Account,
Text
}
/// <summary>
/// A position in the drill-down: all expenses → subclass → account → booking-text group.
/// Deeper nodes carry their parents (an account node also has its subclass).
/// </summary>
public record AnalyticsNode(int? SubClass = null, int? Account = null, string? Text = null)
{
public static readonly AnalyticsNode All = new();
public AnalyticsLevel Level =>
Text != null ? AnalyticsLevel.Text
: Account != null ? AnalyticsLevel.Account
: SubClass != null ? AnalyticsLevel.SubClass
: AnalyticsLevel.All;
}
public record AnalyticsQuery(int FromYear, int ToYear, AnalyticsPeriod Period, AnalyticsNode Node);
public record AnalyticsBreadcrumb(AnalyticsNode Node, string Name);
/// <summary>
/// One child of the queried node, with its value per period (aligned with
/// <see cref="AnalyticsResult.Periods"/>).
/// </summary>
public record AnalyticsCategory(
AnalyticsNode Node,
string Name,
IReadOnlyList<decimal> Values,
decimal Total,
decimal Share,
bool CanDrillDown);
/// <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.
/// </summary>
public record YearComparison(int Year, int Months, decimal Current, decimal Previous)
{
public decimal? ChangePercent => Previous == 0 ? null : (Current - Previous) / Math.Abs(Previous) * 100;
}
public record AnalyticsResult(
IReadOnlyList<AnalyticsBreadcrumb> Breadcrumb,
IReadOnlyList<DateOnly> Periods,
IReadOnlyList<AnalyticsCategory> Categories,
decimal Total,
int Months,
decimal AveragePerMonth,
YearComparison? Comparison);
}

View file

@ -0,0 +1,14 @@
using System.Collections.Generic;
using Schaad.Accounting.Models;
namespace Schaad.Accounting.Datasets.Analytics
{
/// <summary>
/// The raw data of one mandator/year, as stored on disk.
/// </summary>
public record YearData(
int Year,
IReadOnlyList<Account> Accounts,
IReadOnlyList<SubClass> SubClasses,
IReadOnlyList<Transaction> Transactions);
}

View file

@ -48,15 +48,16 @@ namespace Schaad.Accounting.Datasets
/// First word of <see cref="Text"/>, used to group related bookings (e.g. "Narbonne Car" /// First word of <see cref="Text"/>, used to group related bookings (e.g. "Narbonne Car"
/// and "Narbonne Food" both group under "Narbonne"). /// and "Narbonne Food" both group under "Narbonne").
/// </summary> /// </summary>
public string GetTextGroup() public string GetTextGroup() => GetTextGroup(Text);
{
if (string.IsNullOrEmpty(Text))
{
return Text;
}
var spaceIndex = Text.IndexOf(' '); public static string GetTextGroup(string text)
return spaceIndex < 0 ? Text : Text[..spaceIndex]; {
if (string.IsNullOrEmpty(text))
{
return text;
}
var spaceIndex = text.IndexOf(' ');
return spaceIndex < 0 ? text : text[..spaceIndex];
} }
} }
} }

View file

@ -0,0 +1,19 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Schaad.Accounting.Datasets.Analytics;
namespace Schaad.Accounting.Interfaces
{
/// <summary>
/// Read-only access to any year of a mandator, independent of the year selected in the header.
/// </summary>
public interface IMultiYearRepository
{
/// <summary>
/// Years that have a data folder for the mandator, ascending.
/// </summary>
IReadOnlyList<int> GetYears(string mandator);
Task<YearData> GetYearDataAsync(string mandator, int year);
}
}

View file

@ -60,9 +60,17 @@ namespace Schaad.Accounting.Repositories
/// the same scope return the cached list. <see cref="SaveAsync"/> invalidates the entry. /// the same scope return the cached list. <see cref="SaveAsync"/> invalidates the entry.
/// </summary> /// </summary>
protected Task<List<T>> LoadListAsync<T>(string fileName) protected Task<List<T>> LoadListAsync<T>(string fileName)
=> LoadListAsync<T>(settingsService.GetDbPath(), fileName);
/// <summary>
/// Same as <see cref="LoadListAsync{T}(string)"/> for a file in any data directory (e.g.
/// another year). Shares the cache, which is keyed by absolute path, so a save in the
/// current year also invalidates readers of that year.
/// </summary>
protected Task<List<T>> LoadListAsync<T>(string directory, string fileName)
{ {
var filePath = Path.Combine(settingsService.GetDbPath(), fileName); var filePath = Path.Combine(directory, fileName);
return cache.GetOrLoadAsync(filePath, async () => await LoadAsync<List<T>>(fileName) ?? new List<T>()); return cache.GetOrLoadAsync(filePath, async () => await LoadFileAsync<List<T>>(filePath) ?? new List<T>());
} }
/// <summary> /// <summary>
@ -108,10 +116,11 @@ namespace Schaad.Accounting.Repositories
/// Load an object from a JSON file (uncached; used for one-off reads such as file /// Load an object from a JSON file (uncached; used for one-off reads such as file
/// existence bootstrapping). Prefer <see cref="LoadListAsync{T}"/> for repository reads. /// existence bootstrapping). Prefer <see cref="LoadListAsync{T}"/> for repository reads.
/// </summary> /// </summary>
protected async Task<T> LoadAsync<T>(string fileName) protected Task<T> LoadAsync<T>(string fileName)
{ => LoadFileAsync<T>(Path.Combine(settingsService.GetDbPath(), fileName));
var filePath = Path.Combine(settingsService.GetDbPath(), fileName);
private static async Task<T> LoadFileAsync<T>(string filePath)
{
var semaphore = GetLock(filePath); var semaphore = GetLock(filePath);
await semaphore.WaitAsync(); await semaphore.WaitAsync();
try try

View file

@ -0,0 +1,51 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Schaad.Accounting.Datasets.Analytics;
using Schaad.Accounting.Interfaces;
using Schaad.Accounting.Models;
namespace Schaad.Accounting.Repositories
{
public class MultiYearRepository : BaseRepository, IMultiYearRepository
{
private const string ACCOUNTS = "Accounts.json";
private const string SUBCLASSES = "SubClasses.json";
private const string TRANSACTIONS = "Transactions.json";
public MultiYearRepository(ISettingsService settingsService, RepositoryCache cache, ILogger<MultiYearRepository> logger)
: base(settingsService, cache, logger)
{
}
public IReadOnlyList<int> GetYears(string mandator)
{
var mandatorPath = Path.Combine(settingsService.GetSettings().DataPath, mandator);
if (Directory.Exists(mandatorPath) == false)
{
return [];
}
// Empty year folders exist (GetLastYearDbPath creates them); only years with accounts count.
return Directory.GetDirectories(mandatorPath)
.Select(Path.GetFileName)
.Where(name => int.TryParse(name, out _) && File.Exists(Path.Combine(mandatorPath, name, ACCOUNTS)))
.Select(int.Parse)
.Order()
.ToList();
}
public async Task<YearData> GetYearDataAsync(string mandator, int year)
{
// Read-only: never creates folders or copies last year's files, unlike GetDbPath/EnsureFileExists.
var directory = Path.Combine(settingsService.GetSettings().DataPath, mandator, year.ToString());
return new YearData(
year,
await LoadListAsync<Account>(directory, ACCOUNTS),
await LoadListAsync<SubClass>(directory, SUBCLASSES),
await LoadListAsync<Transaction>(directory, TRANSACTIONS));
}
}
}

View file

@ -0,0 +1,30 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Schaad.Accounting.Datasets.Analytics;
using Schaad.Accounting.Interfaces;
namespace Schaad.Accounting.Services
{
public class AnalyticsService : IAnalyticsService
{
private readonly ISettingsService settingsService;
private readonly IMultiYearRepository multiYearRepository;
public AnalyticsService(ISettingsService settingsService, IMultiYearRepository multiYearRepository)
{
this.settingsService = settingsService;
this.multiYearRepository = multiYearRepository;
}
public async Task<ExpenseAnalysis> GetExpenseAnalysisAsync()
{
var mandator = settingsService.GetMandator();
var years = new List<YearData>();
foreach (var year in multiYearRepository.GetYears(mandator))
{
years.Add(await multiYearRepository.GetYearDataAsync(mandator, year));
}
return new ExpenseAnalysis(years);
}
}
}

View file

@ -19,82 +19,6 @@ namespace Schaad.Accounting.Services
this.viewService = viewService; this.viewService = viewService;
} }
public async Task<IReadOnlyList<DataSerie>> GetExpensesPerMonthAsync()
{
var expenseTransactions = (await viewService.GetTransactionViewListAsync())
.Where(t => t.TargetAccount.Class == ClassIds.Expenses)
.ToList();
var distinctSubClasses = expenseTransactions
.Select(t => t.TargetAccount.SubClass)
.Distinct()
.Count();
return distinctSubClasses > 1
? await GetSubClassExpensesPerMonthAsync(expenseTransactions)
: await GetAccountExpensesPerMonthAsync();
}
private async Task<List<DataSerie>> GetSubClassExpensesPerMonthAsync(List<TransactionDataset> expenseTransactions)
{
var year = settingsService.GetYear();
var maxMonth = expenseTransactions
.OrderByDescending(t => t.ValueDate)
.FirstOrDefault()?.ValueDate.Month ?? 12;
var subClassNameByNumber = (await viewService.GetAccountViewListAsync())
.GroupBy(a => a.SubClass)
.ToDictionary(g => g.Key, g => g.First().SubClassName);
var list = new List<DataSerie>();
foreach (var grp in expenseTransactions.GroupBy(t => t.TargetAccount.SubClass))
{
var groupedByMonth = grp
.GroupBy(t => t.ValueDate.Month)
.ToDictionary(g => g.Key, g => g.Sum(t => t.GetValue(t.TargetAccount.IsFxAccount)));
EnsureEntryForEveryMonth(groupedByMonth, maxMonth);
list.Add(new DataSerie(
Id: grp.Key.ToString(),
Name: subClassNameByNumber[grp.Key],
X: groupedByMonth.OrderBy(g => g.Key).Select(g => new DateOnly(year, g.Key, 1)).ToList(),
Y: groupedByMonth.OrderBy(g => g.Key).Select(g => g.Value).ToList()
));
}
return list;
}
private async Task<List<DataSerie>> GetAccountExpensesPerMonthAsync()
{
var year = settingsService.GetYear();
var allTransactions = await viewService.GetTransactionViewListAsync();
var expenseAccounts = (await viewService.GetAccountViewListAsync()).Where(a => a.Class == ClassIds.Expenses);
var list = new List<DataSerie>();
foreach (var account in expenseAccounts)
{
var transactions = allTransactions.Where(t => t.TargetAccountId == account.Id).ToList();
if (transactions.Count == 0)
{
continue;
}
var maxMonth = transactions.Max(t => t.ValueDate.Month);
var groupedByMonth = transactions
.GroupBy(t => t.ValueDate.Month)
.ToDictionary(g => g.Key, g => g.Sum(t => t.GetValue(account.IsFxAccount)));
EnsureEntryForEveryMonth(groupedByMonth, maxMonth);
list.Add(new DataSerie(
Id: account.Id,
Name: account.Name,
X: groupedByMonth.OrderBy(g => g.Key).Select(g => new DateOnly(year, g.Key, 1)).ToList(),
Y: groupedByMonth.OrderBy(g => g.Key).Select(g => g.Value).ToList()
));
}
return list;
}
public async Task<IReadOnlyList<DataSerie>> GetBookingTextExpensesPerMonthAsync(string accountId) public async Task<IReadOnlyList<DataSerie>> GetBookingTextExpensesPerMonthAsync(string accountId)
{ {
var account = await viewService.GetAccountViewAsync(accountId); var account = await viewService.GetAccountViewAsync(accountId);

View file

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

View file

@ -0,0 +1,13 @@
using System.Threading.Tasks;
using Schaad.Accounting.Services;
namespace Schaad.Accounting.Interfaces
{
public interface IAnalyticsService
{
/// <summary>
/// Expenses of the currently selected mandator over all its years.
/// </summary>
Task<ExpenseAnalysis> GetExpenseAnalysisAsync();
}
}

View file

@ -6,8 +6,6 @@ namespace Schaad.Accounting.Interfaces
{ {
public interface IChartService public interface IChartService
{ {
Task<IReadOnlyList<DataSerie>> GetExpensesPerMonthAsync();
Task<IReadOnlyList<DataSerie>> GetBookingTextExpensesPerMonthAsync(string accountId); Task<IReadOnlyList<DataSerie>> GetBookingTextExpensesPerMonthAsync(string accountId);
Task<IReadOnlyList<CategoryTotal>> GetBookingTextTotalsAsync(string accountId); Task<IReadOnlyList<CategoryTotal>> GetBookingTextTotalsAsync(string accountId);

View file

@ -20,93 +20,6 @@ public class ChartServiceTestShould
private ChartService BuildService() => new(settingsService, viewService); private ChartService BuildService() => new(settingsService, viewService);
[Fact]
public async Task HonourSelectedYearWhenBuildingMonthlySeries()
{
settingsService.GetYear().Returns(2023);
var groceries = MakeAccount("groc", 4200);
var checking = MakeAccount("chk", 1010);
viewService.GetAccountViewListAsync().Returns(new List<AccountDataset> { AsDataset(groceries), AsDataset(checking) });
viewService.GetTransactionViewListAsync().Returns(new List<TransactionDataset>
{
MakeTransaction(checking, groceries, value: 50m, valueDate: new DateTime(2023, 4, 5))
});
var series = await BuildService().GetExpensesPerMonthAsync();
series.Count.ShouldBe(1);
series[0].X.ShouldAllBe(x => ((DateOnly)x).Year == 2023);
settingsService.DidNotReceive().SetYear(Arg.Any<int>());
settingsService.DidNotReceive().TrySetYear(Arg.Any<int>());
}
[Fact]
public async Task GroupExpensesByAccountWhenAllExpensesShareOneSubClass()
{
var mannenbach = MakeAccount("m1", 4000);
var mannenbach2 = MakeAccount("m2", 4001);
var checking = MakeAccount("chk", 1010);
viewService.GetAccountViewListAsync().Returns(new List<AccountDataset>
{
AsDataset(mannenbach), AsDataset(mannenbach2), AsDataset(checking)
});
viewService.GetTransactionViewListAsync().Returns(new List<TransactionDataset>
{
MakeTransaction(checking, mannenbach, value: 10m, valueDate: new DateTime(2026, 1, 1)),
MakeTransaction(checking, mannenbach2, value: 20m, valueDate: new DateTime(2026, 1, 1))
});
var series = await BuildService().GetExpensesPerMonthAsync();
series.Count.ShouldBe(2);
series.ShouldContain(s => s.Id == "m1");
series.ShouldContain(s => s.Id == "m2");
}
[Fact]
public async Task GroupExpensesBySubClassWhenMultipleSubClassesAreUsed()
{
var groceries = MakeAccount("groc", 4200);
var utilities = MakeAccount("util", 4300);
var checking = MakeAccount("chk", 1010);
viewService.GetAccountViewListAsync().Returns(new List<AccountDataset>
{
AsDataset(groceries, subClassName: "Groceries"), AsDataset(utilities, subClassName: "Utilities"), AsDataset(checking)
});
viewService.GetTransactionViewListAsync().Returns(new List<TransactionDataset>
{
MakeTransaction(checking, groceries, value: 50m, valueDate: new DateTime(2026, 1, 1)),
MakeTransaction(checking, utilities, value: 30m, valueDate: new DateTime(2026, 2, 1))
});
var series = await BuildService().GetExpensesPerMonthAsync();
series.Count.ShouldBe(2);
series.ShouldContain(s => s.Id == "42" && s.Name == "Groceries");
series.ShouldContain(s => s.Id == "43" && s.Name == "Utilities");
}
[Fact]
public async Task SkipAccountsWithoutTransactionsWhenBuildingSeries()
{
var groceries = MakeAccount("groc", 4000);
var utilities = MakeAccount("util", 4001);
var checking = MakeAccount("chk", 1010);
viewService.GetAccountViewListAsync().Returns(new List<AccountDataset>
{
AsDataset(groceries), AsDataset(utilities), AsDataset(checking)
});
viewService.GetTransactionViewListAsync().Returns(new List<TransactionDataset>
{
MakeTransaction(checking, groceries, value: 50m, valueDate: new DateTime(2026, 1, 1))
});
var series = await BuildService().GetExpensesPerMonthAsync();
series.Count.ShouldBe(1);
series[0].Id.ShouldBe("groc");
}
private static Account MakeAccount(string id, int number, string currency = "CHF") => new() private static Account MakeAccount(string id, int number, string currency = "CHF") => new()
{ {
Id = id, Id = id,
@ -133,43 +46,6 @@ public class ChartServiceTestShould
}, },
origin, target); origin, target);
[Fact]
public async Task ConvertFxAccountValuesWhenBuildingAccountSeries()
{
var usSubscription = MakeAccount("us", 4000, currency: "USD");
var checking = MakeAccount("chk", 1010);
viewService.GetAccountViewListAsync().Returns(new List<AccountDataset> { AsDataset(usSubscription), AsDataset(checking) });
viewService.GetTransactionViewListAsync().Returns(new List<TransactionDataset>
{
MakeTransaction(checking, usSubscription, value: 100m, valueDate: new DateTime(2026, 1, 1), fxRate: 0.5m)
});
var series = await BuildService().GetExpensesPerMonthAsync();
series.Single().Y.Single().ShouldBe(200m);
}
[Fact]
public async Task ConvertFxAccountValuesWhenBuildingSubClassSeries()
{
var usSubscription = MakeAccount("us", 4200, currency: "USD");
var utilities = MakeAccount("util", 4300);
var checking = MakeAccount("chk", 1010);
viewService.GetAccountViewListAsync().Returns(new List<AccountDataset>
{
AsDataset(usSubscription), AsDataset(utilities), AsDataset(checking)
});
viewService.GetTransactionViewListAsync().Returns(new List<TransactionDataset>
{
MakeTransaction(checking, usSubscription, value: 100m, valueDate: new DateTime(2026, 1, 1), fxRate: 0.5m),
MakeTransaction(checking, utilities, value: 30m, valueDate: new DateTime(2026, 2, 1))
});
var series = await BuildService().GetExpensesPerMonthAsync();
series.Single(s => s.Id == "42").Y[0].ShouldBe(200m);
}
[Fact] [Fact]
public async Task GroupBookingTextExpensesByTextWhenBuildingMonthlySeriesForAccount() public async Task GroupBookingTextExpensesByTextWhenBuildingMonthlySeriesForAccount()
{ {

View file

@ -0,0 +1,255 @@
using Schaad.Accounting.Datasets.Analytics;
using Schaad.Accounting.Models;
using Schaad.Accounting.Services;
using Shouldly;
namespace Schaad.Accounting.Tests;
public class ExpenseAnalysisTestShould
{
private static readonly Account Bank = new() { Id = "bank", Number = 1020, Name = "Bank" };
private static readonly Account Salary = new() { Id = "salary", Number = 3000, Name = "Lohn" };
private static readonly Account Food = new() { Id = "food", Number = 4000, Name = "Lebensmittel" };
private static readonly Account Restaurant = new() { Id = "restaurant", Number = 4010, Name = "Restaurant" };
private static readonly Account Rent = new() { Id = "rent", Number = 4100, Name = "Miete" };
private static readonly SubClass[] SubClasses =
[
new() { Number = 40, Name = "Verpflegung" },
new() { Number = 41, Name = "Wohnen" }
];
private static Transaction Booking(string date, Account from, Account to, decimal value, string text = "Text") => new()
{
ValueDate = DateTime.Parse(date),
OriginAccountId = from.Id,
TargetAccountId = to.Id,
Value = value,
Text = text
};
private static YearData Year(int year, params Transaction[] transactions)
=> new(year, [Bank, Salary, Food, Restaurant, Rent], SubClasses, transactions);
private static AnalyticsQuery Query(int from, int to, AnalyticsNode? node = null, AnalyticsPeriod period = AnalyticsPeriod.Month)
=> new(from, to, period, node ?? AnalyticsNode.All);
[Fact]
public void SumExpensesPerSubClassWhenQueryingAll()
{
var sut = new ExpenseAnalysis([Year(2025,
Booking("2025-01-10", Bank, Food, 100),
Booking("2025-01-20", Bank, Restaurant, 50),
Booking("2025-02-01", Bank, Rent, 1000))]);
var result = sut.Query(Query(2025, 2025));
result.Total.ShouldBe(1150);
result.Categories.Select(c => (c.Name, c.Total)).ShouldBe([("Wohnen", 1000m), ("Verpflegung", 150m)]);
result.Categories[0].Node.ShouldBe(new AnalyticsNode(SubClass: 41));
result.Categories[0].Share.ShouldBe(1000m / 1150m);
}
[Fact]
public void SubtractRefundsWhenSummingExpenses()
{
var sut = new ExpenseAnalysis([Year(2025,
Booking("2025-01-10", Bank, Food, 100),
Booking("2025-01-15", Food, Bank, 30))]);
var result = sut.Query(Query(2025, 2025));
result.Total.ShouldBe(70);
}
[Fact]
public void IgnoreBookingsWithoutExpenseAccountWhenQuerying()
{
var sut = new ExpenseAnalysis([Year(2025,
Booking("2025-01-25", Salary, Bank, 5000),
Booking("2025-01-26", Bank, Food, 100))]);
var result = sut.Query(Query(2025, 2025));
result.Total.ShouldBe(100);
}
[Fact]
public void CancelTransfersWithinSubClassWhenQueryingAll()
{
// Reclassifying 20 from food to restaurant changes neither the total nor the subclass.
var sut = new ExpenseAnalysis([Year(2025,
Booking("2025-01-10", Bank, Food, 100),
Booking("2025-01-11", Food, Restaurant, 20))]);
var all = sut.Query(Query(2025, 2025));
var subClass = sut.Query(Query(2025, 2025, new AnalyticsNode(SubClass: 40)));
all.Total.ShouldBe(100);
all.Categories.Single().Total.ShouldBe(100);
subClass.Categories.Select(c => (c.Name, c.Total)).ShouldBe([("Lebensmittel", 80m), ("Restaurant", 20m)]);
}
[Fact]
public void GroupAccountsByNumberWithLatestNameWhenAccountChangedOverYears()
{
var oldRent = new Account { Id = "rent-old-id", Number = 4100, Name = "Miete alt" };
var sut = new ExpenseAnalysis(
[
new YearData(2024, [Bank, oldRent], SubClasses, [Booking("2024-03-01", Bank, oldRent, 900)]),
Year(2025, Booking("2025-03-01", Bank, Rent, 1000))
]);
var result = sut.Query(Query(2024, 2025, new AnalyticsNode(SubClass: 41)));
result.Categories.Single().Name.ShouldBe("Miete");
result.Categories.Single().Total.ShouldBe(1900);
}
[Fact]
public void ShowBookingTextGroupsWhenDrillingIntoAccount()
{
var sut = new ExpenseAnalysis([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"))]);
var result = sut.Query(Query(2025, 2025, new AnalyticsNode(SubClass: 40, Account: 4000)));
result.Categories.Select(c => (c.Name, c.Total)).ShouldBe([("Migros", 140m), ("Coop", 30m)]);
result.Categories[0].Node.ShouldBe(new AnalyticsNode(40, 4000, "Migros"));
result.Categories.ShouldAllBe(c => c.CanDrillDown == false);
}
[Fact]
public void ReturnItselfAsOnlyCategoryWhenQueryingBookingTextGroup()
{
var node = new AnalyticsNode(40, 4000, "Migros");
var sut = new ExpenseAnalysis([Year(2025,
Booking("2025-01-10", Bank, Food, 100, "Migros"),
Booking("2025-01-12", Bank, Food, 30, "Coop"))]);
var result = sut.Query(Query(2025, 2025, node));
result.Categories.Single().Node.ShouldBe(node);
result.Total.ShouldBe(100);
}
[Fact]
public void BuildBreadcrumbWithNamesWhenQueryingBookingTextGroup()
{
var sut = new ExpenseAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100, "Migros"))]);
var result = sut.Query(Query(2025, 2025, new AnalyticsNode(40, 4000, "Migros")));
result.Breadcrumb.Select(b => b.Name).ShouldBe(["Ausgaben", "Verpflegung", "Lebensmittel", "Migros"]);
result.Breadcrumb[2].Node.ShouldBe(new AnalyticsNode(40, 4000));
}
[Fact]
public void CountBookingsInTheirBookYearWhenDatedOutsideIt()
{
var sut = new ExpenseAnalysis(
[
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))
]);
var result = sut.Query(Query(2024, 2025, period: AnalyticsPeriod.Month));
result.Total.ShouldBe(60);
var values = result.Categories.Single().Values;
values[0].ShouldBe(10); // Jan 2024
values[11].ShouldBe(20); // Dec 2024
values[14].ShouldBe(30); // Mar 2025
}
[Fact]
public void StopAtLastMonthWithDataWhenRangeIncludesRunningYear()
{
var sut = new ExpenseAnalysis([Year(2026,
Booking("2026-01-10", Bank, Food, 100),
Booking("2026-03-10", Bank, Food, 200))]);
var result = sut.Query(Query(2026, 2026));
result.Periods.ShouldBe([new DateOnly(2026, 1, 1), new DateOnly(2026, 2, 1), new DateOnly(2026, 3, 1)]);
result.Categories.Single().Values.ShouldBe([100m, 0m, 200m]);
result.Months.ShouldBe(3);
result.AveragePerMonth.ShouldBe(100);
}
[Fact]
public void SumIntoQuartersAndYearsWhenPeriodIsCoarser()
{
var sut = new ExpenseAnalysis(
[
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))
]);
var quarters = sut.Query(Query(2024, 2025, period: AnalyticsPeriod.Quarter));
var years = sut.Query(Query(2024, 2025, period: AnalyticsPeriod.Year));
quarters.Periods.Count.ShouldBe(8);
quarters.Categories.Single().Values.ShouldBe([10m, 0m, 0m, 20m, 0m, 30m, 0m, 40m]);
years.Periods.ShouldBe([new DateOnly(2024, 1, 1), new DateOnly(2025, 1, 1)]);
years.Categories.Single().Values.ShouldBe([30m, 70m]);
}
[Fact]
public void LeaveOutYearsOutsideRangeWhenQuerying()
{
var sut = new ExpenseAnalysis(
[
Year(2024, Booking("2024-02-10", Bank, Food, 10)),
Year(2025, Booking("2025-02-10", Bank, Food, 30))
]);
var result = sut.Query(Query(2025, 2025));
result.Total.ShouldBe(30);
result.Months.ShouldBe(2);
}
[Fact]
public void CompareSameMonthsOfPreviousYearWhenYearIsRunning()
{
var sut = new ExpenseAnalysis(
[
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))
]);
// Range is 2026 only, but the comparison still looks at 2025.
var comparison = sut.Query(Query(2026, 2026)).Comparison;
comparison.ShouldNotBeNull();
comparison.Year.ShouldBe(2026);
comparison.Months.ShouldBe(2);
comparison.Current.ShouldBe(200);
comparison.Previous.ShouldBe(100);
comparison.ChangePercent.ShouldBe(100);
}
[Fact]
public void ReturnNoComparisonWhenPreviousYearHasNoData()
{
var sut = new ExpenseAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100))]);
sut.Query(Query(2025, 2025)).Comparison.ShouldBeNull();
}
[Fact]
public void ReturnEmptyResultWhenThereIsNoData()
{
var sut = new ExpenseAnalysis([]);
var result = sut.Query(Query(2025, 2025));
sut.Years.ShouldBeEmpty();
result.Total.ShouldBe(0);
result.Categories.ShouldBeEmpty();
result.Periods.Count.ShouldBe(12);
}
}

View file

@ -0,0 +1,84 @@
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Schaad.Accounting.Datasets;
using Schaad.Accounting.Interfaces;
using Schaad.Accounting.Repositories;
using Shouldly;
namespace Schaad.Accounting.Tests;
public class MultiYearRepositoryTestShould : IDisposable
{
private readonly string dataPath;
private readonly ISettingsService settingsService;
private readonly MultiYearRepository sut;
public MultiYearRepositoryTestShould()
{
dataPath = Path.Combine(Path.GetTempPath(), "AccountingNext-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dataPath);
settingsService = Substitute.For<ISettingsService>();
settingsService.GetSettings().Returns(new SettingsDataset { DataPath = dataPath });
sut = new MultiYearRepository(settingsService, new RepositoryCache(), NullLogger<MultiYearRepository>.Instance);
}
public void Dispose()
{
if (Directory.Exists(dataPath))
{
Directory.Delete(dataPath, recursive: true);
}
}
private void WriteFile(string mandator, int year, string fileName, string json)
{
var dir = Path.Combine(dataPath, mandator, year.ToString());
Directory.CreateDirectory(dir);
File.WriteAllText(Path.Combine(dir, fileName), json);
}
[Fact]
public void ListOnlyYearsWithAccountsWhenGettingYears()
{
WriteFile("Mandator", 2025, "Accounts.json", "[]");
WriteFile("Mandator", 2023, "Accounts.json", "[]");
Directory.CreateDirectory(Path.Combine(dataPath, "Mandator", "2026"));
WriteFile("Other", 2024, "Accounts.json", "[]");
sut.GetYears("Mandator").ShouldBe([2023, 2025]);
}
[Fact]
public void ReturnNoYearsWhenMandatorDoesNotExist()
{
sut.GetYears("Unknown").ShouldBeEmpty();
}
[Fact]
public async Task ReadRequestedYearWhenLoadingYearData()
{
WriteFile("Mandator", 2024, "Accounts.json", """[{ "Id": "a1", "Number": 4000, "Name": "Food" }]""");
WriteFile("Mandator", 2024, "SubClasses.json", """[{ "Number": 40, "Name": "Verpflegung" }]""");
WriteFile("Mandator", 2024, "Transactions.json", """[{ "Id": "t1", "Value": 12.5, "TargetAccountId": "a1" }]""");
var data = await sut.GetYearDataAsync("Mandator", 2024);
data.Year.ShouldBe(2024);
data.Accounts.Single().Name.ShouldBe("Food");
data.SubClasses.Single().Name.ShouldBe("Verpflegung");
data.Transactions.Single().Value.ShouldBe(12.5m);
settingsService.DidNotReceive().GetDbPath();
}
[Fact]
public async Task ReturnEmptyListsWithoutCreatingFoldersWhenFilesAreMissing()
{
var data = await sut.GetYearDataAsync("Mandator", 2020);
data.Accounts.ShouldBeEmpty();
data.Transactions.ShouldBeEmpty();
Directory.Exists(Path.Combine(dataPath, "Mandator")).ShouldBeFalse();
}
}

View file

@ -16,8 +16,7 @@
<FluentNavLink Href="Accounts" Icon="@(new Size20.PersonAccounts())" IconColor="Color.Accent">Konten</FluentNavLink> <FluentNavLink Href="Accounts" Icon="@(new Size20.PersonAccounts())" IconColor="Color.Accent">Konten</FluentNavLink>
</FluentNavGroup> </FluentNavGroup>
<FluentNavGroup Title="Charts" Icon="@(new Size32.ChartMultiple())"> <FluentNavGroup Title="Charts" Icon="@(new Size32.ChartMultiple())">
<FluentNavLink Href="spendings" Icon="@(new Size32.DataPie())" IconColor="Color.Accent">Ausgaben</FluentNavLink> <FluentNavLink Href="analytics" Icon="@(new Size20.DataHistogram())" IconColor="Color.Accent">Analyse</FluentNavLink>
<FluentNavLink Href="SpendingsOverTime" Icon="@(new Size32.DataArea())" IconColor="Color.Accent">Zeitverlauf</FluentNavLink>
<FluentNavLink Href="Assets" Icon="@(new Size32.DataPie())" IconColor="Color.Accent">Vermögen</FluentNavLink> <FluentNavLink Href="Assets" Icon="@(new Size32.DataPie())" IconColor="Color.Accent">Vermögen</FluentNavLink>
</FluentNavGroup> </FluentNavGroup>
<FluentNavGroup Title="Reports" Icon="@(new Size32.DocumentPrint())"> <FluentNavGroup Title="Reports" Icon="@(new Size32.DocumentPrint())">

View file

@ -0,0 +1,152 @@
@page "/analytics"
@rendermode InteractiveServer
@using Schaad.Accounting.Datasets.Analytics
<PageTitle>Analyse</PageTitle>
@if (analysis is null)
{
<Loading/>
return;
}
@if (analysis.Years.Count == 0 || result is null)
{
<FluentMessageBar Intent="MessageIntent.Info" AllowDismiss="false">Für @mandator gibt es noch keine Daten.</FluentMessageBar>
return;
}
<div class="analytics">
<div class="toolbar">
<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="filters">
<FluentSelect TOption="int" Label="Von" Width="110px"
Items="@analysis.Years"
OptionText="@(y => y.ToString())"
OptionValue="@(y => y.ToString())"
SelectedOption="@fromYear"
SelectedOptionChanged="@OnFromChanged"/>
<FluentSelect TOption="int" Label="Bis" Width="110px"
Items="@analysis.Years"
OptionText="@(y => y.ToString())"
OptionValue="@(y => y.ToString())"
SelectedOption="@toYear"
SelectedOptionChanged="@OnToChanged"/>
<FluentButton Appearance="Appearance.Lightweight" OnClick="ShowAllYears"
Disabled="@(fromYear == analysis.Years[0] && toYear == analysis.Years[^1])">Alle Jahre</FluentButton>
<div class="segmented" role="group" aria-label="Zeitraster">
@foreach (var p in Periods)
{
<FluentButton Appearance="@(p == period ? Appearance.Accent : Appearance.Neutral)"
aria-pressed="@(p == period ? "true" : "false")"
OnClick="@(() => SetPeriod(p))">@PeriodName(p)</FluentButton>
}
</div>
</div>
</div>
<div class="kpis">
<FluentCard class="kpi">
<div class="kpi-label">Total @RangeLabel</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">Ø 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-value @ChangeClass(comparison)">@ChangeLabel(comparison)</div>
<div class="kpi-sub">@Chf(comparison.Current) statt @Chf(comparison.Previous)</div>
}
else
{
<div class="kpi-label">Vergleich zum Vorjahr</div>
<div class="kpi-value">–</div>
<div class="kpi-sub">keine Daten für @(toYear - 1)</div>
}
</FluentCard>
<FluentCard class="kpi">
<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>
}
else
{
<div class="kpi-value">–</div>
<div class="kpi-sub">keine Ausgaben im Zeitraum</div>
}
</FluentCard>
</div>
<div class="main">
<FluentCard class="chart-card">
<div class="card-title">@CurrentName im Verlauf</div>
@if (result.Categories.Count > 0)
{
<StackedBarChart Labels="@chartLabels" Series="@chartSeries" OnSeriesClick="@OnSeriesClick"
AriaLabel="@($"{CurrentName} {RangeLabel} nach {ChildLevelName}, gestapelte Balken")"/>
@if (node.Level != AnalyticsLevel.Text)
{
<div class="hint">Klick auf einen Balken oder einen Eintrag rechts zeigt die Details.</div>
}
}
else
{
<div class="empty">Keine Ausgaben im gewählten Zeitraum.</div>
}
</FluentCard>
<FluentCard class="list-card">
<div class="card-title">@ChildLevelName</div>
<table class="categories">
<tbody>
@for (var i = 0; i < result.Categories.Count; i++)
{
var category = result.Categories[i];
<tr @key="category.Node">
<td class="swatch-cell"><span class="swatch" style="background: @ColorFor(i)"></span></td>
<td class="name">
@if (category.CanDrillDown)
{
<a href="@NodeUrl(category.Node)">@category.Name</a>
}
else
{
@category.Name
}
<div class="share-bar"><div style="width: @ShareWidth(category.Share); background: @ColorFor(i)"></div></div>
</td>
<td class="amount">
@Chf(category.Total)
<div class="share">@Percent(category.Share)</div>
</td>
</tr>
}
</tbody>
</table>
</FluentCard>
</div>
</div>

View file

@ -0,0 +1,212 @@
using System.Globalization;
using Microsoft.AspNetCore.Components;
using Schaad.Accounting.Datasets.Analytics;
using Schaad.Accounting.Interfaces;
using Schaad.Accounting.Services;
using Schaad.Accounting.UI.Components.Pages.Charts;
namespace Schaad.Accounting.UI.Components.Pages.Analytics;
/// <summary>
/// Expenses 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.
/// </summary>
public partial class Analytics : ComponentBase
{
private static readonly CultureInfo Swiss = new("de-CH");
private static readonly AnalyticsPeriod[] Periods = [AnalyticsPeriod.Month, AnalyticsPeriod.Quarter, AnalyticsPeriod.Year];
[Inject]
private IAnalyticsService analyticsService { get; set; } = null!;
[Inject]
private ISettingsService settingsService { get; set; } = null!;
[Inject]
private NavigationManager navigation { get; set; } = null!;
[SupplyParameterFromQuery(Name = "from")]
public int? From { get; set; }
[SupplyParameterFromQuery(Name = "to")]
public int? To { get; set; }
[SupplyParameterFromQuery(Name = "period")]
public string? Period { get; set; }
[SupplyParameterFromQuery(Name = "sub")]
public int? Sub { get; set; }
[SupplyParameterFromQuery(Name = "acc")]
public int? Acc { get; set; }
[SupplyParameterFromQuery(Name = "text")]
public string? Text { get; set; }
private string mandator = "";
private ExpenseAnalysis? analysis;
private AnalyticsResult? result;
private AnalyticsNode node = AnalyticsNode.All;
private int fromYear;
private int toYear;
private AnalyticsPeriod period;
private IReadOnlyList<string> chartLabels = [];
private IReadOnlyList<ChartSeries> chartSeries = [];
// Category behind each chart series; null for the folded "Andere" series.
private List<AnalyticsCategory?> seriesCategories = [];
private int coloredCount;
protected override async Task OnInitializedAsync()
{
mandator = settingsService.GetMandator();
analysis = await analyticsService.GetExpenseAnalysisAsync();
}
protected override void OnParametersSet()
{
if (analysis is null || analysis.Years.Count == 0)
{
return;
}
var years = analysis.Years;
fromYear = Math.Clamp(From ?? years[0], years[0], years[^1]);
toYear = Math.Clamp(To ?? years[^1], years[0], years[^1]);
if (fromYear > toYear)
{
(fromYear, toYear) = (toYear, fromYear);
}
period = ParsePeriod(Period) ?? (fromYear == toYear ? AnalyticsPeriod.Month : AnalyticsPeriod.Quarter);
node = Acc is { } account ? new AnalyticsNode(account / 100, account, Text)
: Sub is { } subClass ? new AnalyticsNode(subClass)
: AnalyticsNode.All;
result = analysis.Query(new AnalyticsQuery(fromYear, toYear, period, node));
BuildChart(result);
}
private void BuildChart(AnalyticsResult data)
{
chartLabels = data.Periods.Select(PeriodLabel).ToList();
// Same folding as the other charts: past MaxCategories, the tail becomes "Andere".
var categories = data.Categories;
coloredCount = categories.Count > ChartTheme.MaxCategories ? ChartTheme.MaxCategories - 1 : categories.Count;
var series = new List<ChartSeries>();
seriesCategories = [];
for (var i = 0; i < coloredCount; i++)
{
var category = categories[i];
series.Add(new ChartSeries(category.Name, ChartTheme.ColorAt(i), category.Values, category.CanDrillDown));
seriesCategories.Add(category);
}
if (coloredCount < categories.Count)
{
var other = new decimal[data.Periods.Count];
foreach (var category in categories.Skip(coloredCount))
{
for (var p = 0; p < other.Length; p++)
{
other[p] += category.Values[p];
}
}
series.Add(new ChartSeries(ChartTheme.OtherLabel, ChartTheme.OtherColor, other, Clickable: false));
seriesCategories.Add(null);
}
chartSeries = series;
}
private void OnSeriesClick(int seriesIndex)
{
if (seriesCategories.ElementAtOrDefault(seriesIndex) is { CanDrillDown: true } category)
{
navigation.NavigateTo(NodeUrl(category.Node));
}
}
private void OnFromChanged(int year)
{
if (year != fromYear)
{
navigation.NavigateTo(Url(node, year, year > toYear ? year : To, Period));
}
}
private void OnToChanged(int year)
{
if (year != toYear)
{
navigation.NavigateTo(Url(node, year < fromYear ? year : From, year, Period));
}
}
private void ShowAllYears() => navigation.NavigateTo(Url(node, null, null, Period));
private void SetPeriod(AnalyticsPeriod value) => navigation.NavigateTo(Url(node, From, To, value.ToString().ToLowerInvariant()));
private string NodeUrl(AnalyticsNode target) => Url(target, From, To, Period);
private string Url(AnalyticsNode target, int? from, int? to, string? periodValue)
=> navigation.GetUriWithQueryParameters(new Dictionary<string, object?>
{
["from"] = from,
["to"] = to,
["period"] = periodValue,
["sub"] = target.SubClass,
["acc"] = target.Account,
["text"] = target.Text
});
private static AnalyticsPeriod? ParsePeriod(string? value)
=> Enum.TryParse<AnalyticsPeriod>(value, ignoreCase: true, out var parsed) ? parsed : null;
private string PeriodLabel(DateOnly start) => period switch
{
AnalyticsPeriod.Month => ChartFormatting.MonthLabel(start),
AnalyticsPeriod.Quarter => $"Q{(start.Month - 1) / 3 + 1} {start.Year % 100:00}",
_ => start.Year.ToString()
};
private static string PeriodName(AnalyticsPeriod value) => value switch
{
AnalyticsPeriod.Month => "Monat",
AnalyticsPeriod.Quarter => "Quartal",
_ => "Jahr"
};
private string RangeLabel => fromYear == toYear ? fromYear.ToString() : $"{fromYear}–{toYear}";
private string CurrentName => result!.Breadcrumb[^1].Name;
private string ChildLevelName => node.Level switch
{
AnalyticsLevel.All => "Subklassen",
AnalyticsLevel.SubClass => "Konten",
_ => "Buchungstexte"
};
private string ColorFor(int index) => index < coloredCount ? ChartTheme.ColorAt(index) : ChartTheme.OtherColor;
private static string Chf(decimal value) => ChartFormatting.Chf(value);
private static string Percent(decimal share) => (share * 100).ToString("0.0", Swiss) + " %";
private static string ShareWidth(decimal share) => Math.Clamp(share * 100, 0, 100).ToString("0.##", CultureInfo.InvariantCulture) + "%";
private static string ComparisonLabel(YearComparison comparison)
=> comparison.Months == 12
? $"{comparison.Year} vs. {comparison.Year - 1}"
: $"{comparison.Year} vs. {comparison.Year - 1}, Jan–{Swiss.DateTimeFormat.GetAbbreviatedMonthName(comparison.Months).TrimEnd('.')}";
private static string ChangeLabel(YearComparison comparison)
=> comparison.ChangePercent is { } change ? (change > 0 ? "+" : "") + change.ToString("0.0", Swiss) + " %" : "–";
// For expenses, more is worse.
private static string ChangeClass(YearComparison comparison)
=> comparison.ChangePercent switch { > 0 => "up", < 0 => "down", _ => "" };
}

View file

@ -0,0 +1,163 @@
.analytics {
display: flex;
flex-direction: column;
gap: 16px;
}
.toolbar {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
}
.filters {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: 8px;
}
.segmented {
display: flex;
gap: 2px;
margin-left: 8px;
}
.kpis {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 12px;
}
::deep .kpi {
padding: 14px 16px;
min-width: 0;
}
.kpi-label {
color: #52514e;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.kpi-value {
font-size: 24px;
font-weight: 600;
margin: 4px 0 2px;
font-variant-numeric: tabular-nums;
}
.kpi-name,
.ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.kpi-value.up {
color: #c50f1f;
}
.kpi-value.down {
color: #107c10;
}
.kpi-sub {
color: #52514e;
font-size: 12px;
}
.main {
display: grid;
grid-template-columns: minmax(0, 2.2fr) minmax(260px, 1fr);
gap: 12px;
align-items: start;
}
@media (max-width: 1100px) {
.main {
grid-template-columns: minmax(0, 1fr);
}
}
::deep .chart-card,
::deep .list-card {
padding: 16px;
min-width: 0;
}
.card-title {
font-weight: 600;
font-size: 15px;
margin-bottom: 12px;
}
.hint,
.empty {
color: #52514e;
font-size: 12px;
margin-top: 8px;
}
.categories {
width: 100%;
border-collapse: collapse;
}
.categories td {
padding: 6px 4px;
border-bottom: 1px solid #e1e0d9;
vertical-align: top;
}
.categories tr:last-child td {
border-bottom: none;
}
.swatch-cell {
width: 14px;
}
.swatch {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 3px;
margin-top: 4px;
}
.name a {
color: inherit;
text-decoration: none;
}
.name a:hover,
.name a:focus-visible {
text-decoration: underline;
}
.share-bar {
height: 4px;
background: #f0efea;
border-radius: 2px;
margin-top: 4px;
}
.share-bar > div {
height: 100%;
border-radius: 2px;
}
.amount {
text-align: right;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.share {
color: #52514e;
font-size: 12px;
}

View file

@ -0,0 +1,6 @@
@* Chart.js stacked bar chart (wwwroot/js/charts.js). Created once; later parameter changes are
pushed as an in-place update so the chart animates instead of being rebuilt. *@
<div class="chart-box" style="height: @Height">
<canvas @ref="canvas" role="img" aria-label="@AriaLabel"></canvas>
</div>

View file

@ -0,0 +1,94 @@
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
namespace Schaad.Accounting.UI.Components.Pages.Analytics;
public record ChartSeries(string Name, string Color, IReadOnlyList<decimal> Values, bool Clickable);
public partial class StackedBarChart : ComponentBase, IAsyncDisposable
{
private ElementReference canvas;
private IJSObjectReference? module;
private IJSObjectReference? chart;
private Task? creating;
private DotNetObjectReference<StackedBarChart>? selfReference;
private IReadOnlyList<string>? renderedLabels;
private IReadOnlyList<ChartSeries>? renderedSeries;
[Inject]
private IJSRuntime js { get; set; } = null!;
[Parameter, EditorRequired]
public IReadOnlyList<string> Labels { get; set; } = [];
[Parameter, EditorRequired]
public IReadOnlyList<ChartSeries> Series { get; set; } = [];
/// <summary>Called with the index into <see cref="Series"/> when a clickable segment is clicked.</summary>
[Parameter]
public EventCallback<int> OnSeriesClick { get; set; }
[Parameter]
public string Height { get; set; } = "420px";
[Parameter]
public string AriaLabel { get; set; } = "";
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (ReferenceEquals(Labels, renderedLabels) && ReferenceEquals(Series, renderedSeries))
{
return;
}
renderedLabels = Labels;
renderedSeries = Series;
var data = new
{
labels = Labels,
series = Series.Select(s => new { name = s.Name, color = s.Color, values = s.Values, clickable = s.Clickable })
};
if (creating is null)
{
creating = CreateAsync(data);
await creating;
return;
}
// New data may arrive while the first (async) creation is still running.
await creating;
await chart!.InvokeVoidAsync("update", data);
}
private async Task CreateAsync(object data)
{
module = await js.InvokeAsync<IJSObjectReference>("import", "./js/charts.js");
selfReference = DotNetObjectReference.Create(this);
chart = await module.InvokeAsync<IJSObjectReference>("createStackedBar", canvas, data, selfReference);
}
[JSInvokable]
public Task OnSeriesClicked(int seriesIndex) => OnSeriesClick.InvokeAsync(seriesIndex);
public async ValueTask DisposeAsync()
{
try
{
if (chart is not null)
{
await chart.InvokeVoidAsync("destroy");
await chart.DisposeAsync();
}
if (module is not null)
{
await module.DisposeAsync();
}
}
catch (JSDisconnectedException)
{
// Circuit already gone; the browser side is gone with it.
}
selfReference?.Dispose();
}
}

View file

@ -0,0 +1,4 @@
.chart-box {
position: relative;
width: 100%;
}

View file

@ -1,15 +0,0 @@
@page "/spendings"
@rendermode InteractiveServer
<PageTitle>Ausgaben</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>

View file

@ -1,35 +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 Spendings : 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("Ausgaben nach Kategorie");
var accounts = (await viewService.GetAccountViewListAsync()).Where(a => a.Class == ClassIds.Expenses);
var totals = accounts
.GroupBy(a => a.SubClass)
.Select(g => new CategoryTotal(g.First().SubClassName, g.Sum(a => a.Balance)))
.Where(t => t.Value != 0)
.ToList();
data = new List<ITrace> { ChartTheme.BuildDonutTrace(ChartFormatting.FoldTail(totals)) };
await base.OnInitializedAsync();
}
}

View file

@ -1,15 +0,0 @@
@page "/SpendingsOverTime"
@rendermode InteractiveServer
<PageTitle>Ausgaben im Verlauf</PageTitle>
<FluentCard Style="padding: 16px;">
@if (config is not null && layout is not null)
{
<PlotlyChart style="height: 560px; min-height: 420px" @bind-Config="config" @bind-Layout="layout" @bind-Data="data" @ref="chart" />
}
else
{
<Loading/>
}
</FluentCard>

View file

@ -1,52 +0,0 @@
using Microsoft.AspNetCore.Components;
using Plotly.Blazor;
using Plotly.Blazor.LayoutLib;
using Plotly.Blazor.Traces;
using Schaad.Accounting.Interfaces;
namespace Schaad.Accounting.UI.Components.Pages.Charts;
public partial class SpendingsOverTime : ComponentBase
{
private PlotlyChart chart = null!;
private Config? config;
private Plotly.Blazor.Layout? layout;
private IList<ITrace> data = new List<ITrace>();
[Inject]
private IChartService chartService { get; set; } = null!;
protected override async Task OnInitializedAsync()
{
config = ChartTheme.BaseConfig();
layout = ChartTheme.BaseLayout("Ausgaben im Verlauf");
layout.BarMode = BarModeEnum.Stack;
layout.BarCornerRadius = 4;
layout.HoverMode = HoverModeEnum.XUnified;
layout.XAxis = new List<XAxis>
{
new()
{
Type = Plotly.Blazor.LayoutLib.XAxisLib.TypeEnum.Category,
GridColor = ChartTheme.GridColor,
LineColor = ChartTheme.GridColor
}
};
layout.YAxis = new List<YAxis>
{
new()
{
Title = new Plotly.Blazor.LayoutLib.YAxisLib.Title { Text = "CHF" },
GridColor = ChartTheme.GridColor,
ZeroLineColor = ChartTheme.GridColor,
SeparateThousands = true
}
};
var dataSeries = await chartService.GetExpensesPerMonthAsync();
data = ChartTheme.BuildStackedBarTraces(ChartFormatting.FoldTail(dataSeries));
await base.OnInitializedAsync();
}
}

View file

@ -24,8 +24,10 @@ namespace Schaad.Accounting.UI
services.AddScoped<ISplitPredefinitionRepository, SplitPredefinitionRepository>(); services.AddScoped<ISplitPredefinitionRepository, SplitPredefinitionRepository>();
services.AddScoped<ISubclassRepository, SubclassRepository>(); services.AddScoped<ISubclassRepository, SubclassRepository>();
services.AddScoped<ITransactionRepository, TransactionRepository>(); services.AddScoped<ITransactionRepository, TransactionRepository>();
services.AddScoped<IMultiYearRepository, MultiYearRepository>();
services.AddScoped<IChartService, ChartService>(); services.AddScoped<IChartService, ChartService>();
services.AddScoped<IAnalyticsService, AnalyticsService>();
services.AddScoped<IViewService, ViewService>(); services.AddScoped<IViewService, ViewService>();
services.AddScoped<IFileService, FileService>(); services.AddScoped<IFileService, FileService>();
services.AddScoped<IAccountStatementService, AccountStatementService>(); services.AddScoped<IAccountStatementService, AccountStatementService>();

View file

@ -0,0 +1,124 @@
// Thin Chart.js wrapper for Blazor (see StackedBarChart.razor). Chart.js is loaded on first use
// from wwwroot/lib/chartjs, so pages without charts don't pay for it.
let chartJsLoading;
function loadChartJs() {
if (window.Chart) {
return Promise.resolve();
}
chartJsLoading ??= new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = 'lib/chartjs/chart.umd.min.js';
script.onload = resolve;
script.onerror = () => reject(new Error('Chart.js could not be loaded'));
document.head.appendChild(script);
});
return chartJsLoading;
}
// Same look as ChartTheme.cs.
const theme = {
font: "'Helvetica Neue', Helvetica, Arial, sans-serif",
ink: '#0b0b0b',
muted: '#52514e',
grid: '#e1e0d9',
surface: '#fcfcfb'
};
// de-CH uses a typographic apostrophe; the rest of the app (Formatting.cs) uses a plain one.
const amount = new Intl.NumberFormat('de-CH', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const axisAmount = new Intl.NumberFormat('de-CH', { maximumFractionDigits: 0 });
const formatChf = value => amount.format(value).replace(/’/g, "'");
const formatAxis = value => axisAmount.format(value).replace(/’/g, "'");
function toDatasets(series) {
return series.map(s => ({
label: s.name,
data: s.values,
backgroundColor: s.color,
hoverBackgroundColor: s.color,
borderColor: theme.surface,
borderWidth: { top: 1 },
borderRadius: 3,
stack: 'total',
clickable: s.clickable
}));
}
/**
* Creates a stacked bar chart on the canvas and returns a handle with update/destroy.
* data: { labels: string[], series: { name, color, values: number[], clickable }[] }
* Clicking a bar segment of a clickable series calls dotNetRef.OnSeriesClicked(seriesIndex).
*/
export async function createStackedBar(canvas, data, dotNetRef) {
await loadChartJs();
window.Chart.defaults.font.family = theme.font;
const chart = new window.Chart(canvas, {
type: 'bar',
data: { labels: data.labels, datasets: toDatasets(data.series) },
options: {
responsive: true,
maintainAspectRatio: false,
animation: { duration: 250 },
interaction: { mode: 'index', intersect: false },
plugins: {
legend: {
position: 'bottom',
labels: { usePointStyle: true, pointStyle: 'rectRounded', boxWidth: 10, color: theme.muted, font: { family: theme.font, size: 12 } }
},
tooltip: {
backgroundColor: '#ffffff',
borderColor: theme.grid,
borderWidth: 1,
titleColor: theme.ink,
bodyColor: theme.ink,
footerColor: theme.ink,
titleFont: { family: theme.font, weight: 'bold' },
bodyFont: { family: theme.font },
footerFont: { family: theme.font, weight: 'bold' },
padding: 10,
usePointStyle: true,
filter: item => item.parsed.y !== 0,
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`
}
}
},
scales: {
x: { stacked: true, grid: { display: false }, ticks: { color: theme.muted, font: { family: theme.font } } },
y: {
stacked: true,
grid: { color: theme.grid },
border: { display: false },
title: { display: true, text: 'CHF', color: theme.muted, font: { family: theme.font } },
ticks: { color: theme.muted, font: { family: theme.font }, callback: value => formatAxis(value) }
}
},
onHover: (event, _, chart) => {
const hit = chart.getElementsAtEventForMode(event, 'nearest', { intersect: true }, false)[0];
event.native.target.style.cursor = hit && chart.data.datasets[hit.datasetIndex].clickable ? 'pointer' : 'default';
},
onClick: (event, _, chart) => {
const hit = chart.getElementsAtEventForMode(event, 'nearest', { intersect: true }, false)[0];
if (hit && chart.data.datasets[hit.datasetIndex].clickable) {
dotNetRef.invokeMethodAsync('OnSeriesClicked', hit.datasetIndex);
}
}
}
});
return {
update(newData) {
chart.data.labels = newData.labels;
chart.data.datasets = toDatasets(newData.series);
chart.update();
},
destroy() {
chart.destroy();
}
};
}

View file

@ -0,0 +1,9 @@
The MIT License (MIT)
Copyright (c) 2014-2024 Chart.js Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

File diff suppressed because one or more lines are too long