Analyse page: composition, year comparison and year table; fix year filter loop
Step 3 of the analytics plan: - Zusammensetzung: treemap (chartjs-chart-treemap 4.2.2, vendored) with the queried node's children and, nested, their children; clicking a tile drills down to that level - Jahresvergleich: one line per year over Jan-Dec, monthly or cumulative - Jahre im Vergleich: category x year table, cells shaded by monthly average (so the running year compares fairly), change vs. the same months of the previous year, clickable rows; replaces both heatmap and table from the plan - ExpenseAnalysis returns year profiles, the category x year table and the two-level composition; StackedBarChart becomes a generic ChartJsChart - Click hints only show when something can be drilled into; the treemap cursor only changes over clickable tiles; zero cells show "-" Fix: choosing a year in Von/Bis started an endless navigation loop (FluentSelect re-reports its value on every re-render, before the new URL has been applied), so the page stopped updating. The handlers now take over the year immediately. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2bc32e9746
commit
afa07f8156
14 changed files with 828 additions and 123 deletions
|
|
@ -68,7 +68,7 @@ Pages live in `Schaad.Accounting.UI/Components/Pages/`. Each page typically has
|
|||
|
||||
- `Microsoft.FluentUI.AspNetCore.Components` — UI components (FluentDataGrid, FluentDialog, etc.)
|
||||
- `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`
|
||||
- Chart.js 4 + `chartjs-chart-treemap` — charts on the Analyse page; vendored in `wwwroot/lib/` (no CDN), wrapped by `wwwroot/js/charts.js` and `ChartJsChart.razor`
|
||||
- `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`)
|
||||
|
||||
|
|
|
|||
|
|
@ -60,6 +60,30 @@ namespace Schaad.Accounting.Datasets.Analytics
|
|||
public decimal? ChangePercent => Previous == 0 ? null : (Current - Previous) / Math.Abs(Previous) * 100;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Monthly values of the queried node in one year (index 0 = January). Months after the last
|
||||
/// month with data are null.
|
||||
/// </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.
|
||||
/// </summary>
|
||||
public record YearCell(int Year, decimal Value, decimal? ChangePercent);
|
||||
|
||||
/// <summary>
|
||||
/// One row of the category × year table, in the same order as <see cref="AnalyticsResult.Categories"/>.
|
||||
/// </summary>
|
||||
public record CategoryYears(AnalyticsNode Node, string Name, bool CanDrillDown, IReadOnlyList<YearCell> Cells, decimal Total);
|
||||
|
||||
/// <summary>
|
||||
/// A treemap tile: a child of the queried node and, one level deeper, one of its children.
|
||||
/// <see cref="Child"/> is null when the child has no deeper level (booking-text groups).
|
||||
/// Only positive amounts are included; an area can't show a refund.
|
||||
/// </summary>
|
||||
public record CompositionItem(AnalyticsNode Parent, string ParentName, AnalyticsNode? Child, string? ChildName, decimal Value);
|
||||
|
||||
public record AnalyticsResult(
|
||||
IReadOnlyList<AnalyticsBreadcrumb> Breadcrumb,
|
||||
IReadOnlyList<DateOnly> Periods,
|
||||
|
|
@ -67,5 +91,8 @@ namespace Schaad.Accounting.Datasets.Analytics
|
|||
decimal Total,
|
||||
int Months,
|
||||
decimal AveragePerMonth,
|
||||
YearComparison? Comparison);
|
||||
YearComparison? Comparison,
|
||||
IReadOnlyList<YearProfile> YearProfiles,
|
||||
IReadOnlyList<CategoryYears> CategoryYears,
|
||||
IReadOnlyList<CompositionItem> Composition);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -128,7 +128,83 @@ namespace Schaad.Accounting.Services
|
|||
total,
|
||||
months,
|
||||
months == 0 ? 0 : total / months,
|
||||
GetComparison(nodeFacts, end));
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -252,4 +252,99 @@ public class ExpenseAnalysisTestShould
|
|||
result.Categories.ShouldBeEmpty();
|
||||
result.Periods.Count.ShouldBe(12);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LeaveMonthsWithoutDataEmptyWhenBuildingYearProfiles()
|
||||
{
|
||||
var sut = new ExpenseAnalysis(
|
||||
[
|
||||
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))
|
||||
]);
|
||||
|
||||
var profiles = sut.Query(Query(2025, 2026)).YearProfiles;
|
||||
|
||||
profiles.Select(p => p.Year).ShouldBe([2025, 2026]);
|
||||
profiles[0].Months.Count.ShouldBe(12);
|
||||
profiles[0].Months[0].ShouldBe(100);
|
||||
profiles[0].Months[1].ShouldBe(0);
|
||||
profiles[0].Total.ShouldBe(150);
|
||||
profiles[1].Months[0].ShouldBe(0);
|
||||
profiles[1].Months[1].ShouldBe(70);
|
||||
profiles[1].Months[2].ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CompareSameMonthsWithPreviousYearWhenBuildingCategoryYears()
|
||||
{
|
||||
var sut = new ExpenseAnalysis(
|
||||
[
|
||||
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)),
|
||||
Year(2026, Booking("2026-01-10", Bank, Food, 120), Booking("2026-02-10", Bank, Rent, 300))
|
||||
]);
|
||||
|
||||
// Range starts in 2025, so 2025's change still compares with 2024.
|
||||
var rows = sut.Query(Query(2025, 2026)).CategoryYears;
|
||||
|
||||
var food = rows.Single(r => r.Name == "Verpflegung");
|
||||
food.Cells.Select(c => (c.Year, c.Value)).ShouldBe([(2025, 150m), (2026, 120m)]);
|
||||
food.Cells[0].ChangePercent.ShouldBe(50);
|
||||
food.Cells[1].ChangePercent.ShouldBe(-20); // Jan–Feb 2026 vs. Jan–Feb 2025
|
||||
var rent = rows.Single(r => r.Name == "Wohnen");
|
||||
rent.Cells[1].Value.ShouldBe(300);
|
||||
rent.Cells[1].ChangePercent.ShouldBeNull(); // nothing in Jan–Feb 2025
|
||||
rows.Select(r => r.Node).ShouldBe(sut.Query(Query(2025, 2026)).Categories.Select(c => c.Node));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReturnNoChangeWhenYearBeforeHasNoData()
|
||||
{
|
||||
var sut = new ExpenseAnalysis([Year(2025, Booking("2025-01-10", Bank, Food, 100))]);
|
||||
|
||||
sut.Query(Query(2025, 2025)).CategoryYears.Single().Cells.Single().ChangePercent.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NestAccountsInSubClassesWhenBuildingComposition()
|
||||
{
|
||||
var sut = new ExpenseAnalysis([Year(2025,
|
||||
Booking("2025-01-10", Bank, Food, 100),
|
||||
Booking("2025-01-11", Bank, Restaurant, 40),
|
||||
Booking("2025-01-12", Bank, Rent, 1000))]);
|
||||
|
||||
var items = sut.Query(Query(2025, 2025)).Composition;
|
||||
|
||||
items.Select(i => (i.ParentName, i.ChildName, i.Value)).ShouldBe(
|
||||
[
|
||||
("Wohnen", "Miete", 1000m),
|
||||
("Verpflegung", "Lebensmittel", 100m),
|
||||
("Verpflegung", "Restaurant", 40m)
|
||||
]);
|
||||
items[1].Child.ShouldBe(new AnalyticsNode(40, 4000));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UseSingleLevelWhenBuildingCompositionForAccount()
|
||||
{
|
||||
var sut = new ExpenseAnalysis([Year(2025,
|
||||
Booking("2025-01-10", Bank, Food, 100, "Migros"),
|
||||
Booking("2025-01-11", Bank, Food, 30, "Coop"))]);
|
||||
|
||||
var items = sut.Query(Query(2025, 2025, new AnalyticsNode(40, 4000))).Composition;
|
||||
|
||||
items.Select(i => (i.ParentName, i.Child, i.Value)).ShouldBe([("Migros", (AnalyticsNode?)null, 100m), ("Coop", null, 30m)]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LeaveOutNegativeAmountsWhenBuildingComposition()
|
||||
{
|
||||
var sut = new ExpenseAnalysis([Year(2025,
|
||||
Booking("2025-01-10", Bank, Food, 100),
|
||||
Booking("2025-01-11", Restaurant, Bank, 40))]);
|
||||
|
||||
var items = sut.Query(Query(2025, 2025, new AnalyticsNode(SubClass: 40))).Composition;
|
||||
|
||||
items.Single().ParentName.ShouldBe("Lebensmittel");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -75,7 +75,7 @@
|
|||
@if (result.Comparison is { } comparison)
|
||||
{
|
||||
<div class="kpi-label">@ComparisonLabel(comparison)</div>
|
||||
<div class="kpi-value @ChangeClass(comparison)">@ChangeLabel(comparison)</div>
|
||||
<div class="kpi-value @ChangeClass(comparison.ChangePercent)">@ChangeLabel(comparison)</div>
|
||||
<div class="kpi-sub">@Chf(comparison.Current) statt @Chf(comparison.Previous)</div>
|
||||
}
|
||||
else
|
||||
|
|
@ -106,9 +106,9 @@
|
|||
<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)
|
||||
<ChartJsChart Kind="stackedBar" Data="@barData" OnClick="@OnBarClick"
|
||||
AriaLabel="@($"{CurrentName} {RangeLabel} nach {ChildLevelName}, gestapelte Balken")"/>
|
||||
@if (CanDrillDown)
|
||||
{
|
||||
<div class="hint">Klick auf einen Balken oder einen Eintrag rechts zeigt die Details.</div>
|
||||
}
|
||||
|
|
@ -149,4 +149,100 @@
|
|||
</table>
|
||||
</FluentCard>
|
||||
</div>
|
||||
|
||||
@if (result.Categories.Count > 0)
|
||||
{
|
||||
<div class="pair">
|
||||
<FluentCard class="chart-card">
|
||||
<div class="card-title">Zusammensetzung @RangeLabel</div>
|
||||
@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>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="empty">Keine positiven Beträge im gewählten Zeitraum.</div>
|
||||
}
|
||||
</FluentCard>
|
||||
|
||||
<FluentCard class="chart-card">
|
||||
<div class="card-header">
|
||||
<div class="card-title">Jahresvergleich</div>
|
||||
<div class="segmented small" role="group" aria-label="Darstellung">
|
||||
<FluentButton Appearance="@(cumulative ? Appearance.Neutral : Appearance.Accent)"
|
||||
aria-pressed="@(cumulative ? "false" : "true")"
|
||||
OnClick="@(() => SetCumulative(false))">Monatlich</FluentButton>
|
||||
<FluentButton Appearance="@(cumulative ? Appearance.Accent : Appearance.Neutral)"
|
||||
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")}")"/>
|
||||
</FluentCard>
|
||||
</div>
|
||||
|
||||
<FluentCard class="table-card">
|
||||
<div class="card-title">Jahre im Vergleich</div>
|
||||
<div class="table-scroll">
|
||||
<table class="years">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col" class="name">@ChildLevelName</th>
|
||||
@foreach (var profile in result.YearProfiles)
|
||||
{
|
||||
<th scope="col">@YearHeader(profile.Year)</th>
|
||||
}
|
||||
<th scope="col" class="total">Total</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var row in result.CategoryYears)
|
||||
{
|
||||
<tr @key="row.Node">
|
||||
<th scope="row" class="name">
|
||||
@if (row.CanDrillDown)
|
||||
{
|
||||
<a href="@NodeUrl(row.Node)">@row.Name</a>
|
||||
}
|
||||
else
|
||||
{
|
||||
@row.Name
|
||||
}
|
||||
</th>
|
||||
@foreach (var cell in row.Cells)
|
||||
{
|
||||
@if (cell.Value == 0)
|
||||
{
|
||||
<td class="zero">–</td>
|
||||
}
|
||||
else
|
||||
{
|
||||
<td style="background: @HeatColor(cell)">
|
||||
@Whole(cell.Value)
|
||||
<div class="change @ChangeClass(cell.ChangePercent)">@ChangeText(cell.ChangePercent)</div>
|
||||
</td>
|
||||
}
|
||||
}
|
||||
<td class="total">@Whole(row.Total)</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<th scope="row" class="name">Total</th>
|
||||
@foreach (var profile in result.YearProfiles)
|
||||
{
|
||||
<td>@Whole(profile.Total)</td>
|
||||
}
|
||||
<td class="total">@Whole(result.Total)</td>
|
||||
</tr>
|
||||
</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>
|
||||
</FluentCard>
|
||||
}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -16,7 +16,13 @@ namespace Schaad.Accounting.UI.Components.Pages.Analytics;
|
|||
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 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,
|
||||
// older ones in fading grey.
|
||||
private static readonly string[] OlderYearColors = ["#898781", "#a9a8a3", "#c4c3be", "#d6d5d0"];
|
||||
|
||||
[Inject]
|
||||
private IAnalyticsService analyticsService { get; set; } = null!;
|
||||
|
|
@ -53,12 +59,22 @@ public partial class Analytics : ComponentBase
|
|||
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 object barData = new();
|
||||
// Category behind each bar series; null for the folded "Andere" series.
|
||||
private List<AnalyticsCategory?> seriesCategories = [];
|
||||
private int coloredCount;
|
||||
|
||||
private object treemapData = new();
|
||||
// Treemap click key ("p3" or "p3|c7") → drill-down target.
|
||||
private Dictionary<string, AnalyticsNode> treemapNodes = [];
|
||||
|
||||
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;
|
||||
private int lastYearMonths = 12;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
mandator = settingsService.GetMandator();
|
||||
|
|
@ -86,23 +102,24 @@ public partial class Analytics : ComponentBase
|
|||
: AnalyticsNode.All;
|
||||
|
||||
result = analysis.Query(new AnalyticsQuery(fromYear, toYear, period, node));
|
||||
BuildChart(result);
|
||||
BuildBarChart(result);
|
||||
BuildTreemap(result);
|
||||
BuildLineChart(result);
|
||||
BuildYearTable(result);
|
||||
}
|
||||
|
||||
private void BuildChart(AnalyticsResult data)
|
||||
private void BuildBarChart(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>();
|
||||
var series = new List<object>();
|
||||
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));
|
||||
series.Add(new { name = category.Name, color = ChartTheme.ColorAt(i), values = category.Values, clickable = category.CanDrillDown });
|
||||
seriesCategories.Add(category);
|
||||
}
|
||||
if (coloredCount < categories.Count)
|
||||
|
|
@ -115,34 +132,130 @@ public partial class Analytics : ComponentBase
|
|||
other[p] += category.Values[p];
|
||||
}
|
||||
}
|
||||
series.Add(new ChartSeries(ChartTheme.OtherLabel, ChartTheme.OtherColor, other, Clickable: false));
|
||||
series.Add(new { name = ChartTheme.OtherLabel, color = ChartTheme.OtherColor, values = other, clickable = false });
|
||||
seriesCategories.Add(null);
|
||||
}
|
||||
chartSeries = series;
|
||||
barData = new { labels = data.Periods.Select(PeriodLabel).ToList(), series };
|
||||
}
|
||||
|
||||
private void OnSeriesClick(int seriesIndex)
|
||||
private void BuildTreemap(AnalyticsResult data)
|
||||
{
|
||||
if (seriesCategories.ElementAtOrDefault(seriesIndex) is { CanDrillDown: true } category)
|
||||
// Parent ids follow the category order, so a parent has the same colour as in the bar
|
||||
// chart and the list.
|
||||
var parents = data.Categories
|
||||
.Select((category, i) => (category.Node, Id: $"p{i}", Color: ColorFor(i)))
|
||||
.ToDictionary(x => x.Node);
|
||||
var names = new Dictionary<string, string>();
|
||||
var colors = new Dictionary<string, string>();
|
||||
var items = new List<object>();
|
||||
treemapNodes = [];
|
||||
|
||||
foreach (var item in data.Composition)
|
||||
{
|
||||
var parent = parents[item.Parent];
|
||||
names[parent.Id] = item.ParentName;
|
||||
colors[parent.Id] = parent.Color;
|
||||
if (item.Parent.Level != AnalyticsLevel.Text)
|
||||
{
|
||||
treemapNodes[parent.Id] = item.Parent;
|
||||
}
|
||||
|
||||
string? childId = null;
|
||||
if (item.Child is { } child)
|
||||
{
|
||||
childId = $"c{items.Count}";
|
||||
names[childId] = item.ChildName!;
|
||||
treemapNodes[$"{parent.Id}|{childId}"] = child;
|
||||
}
|
||||
items.Add(new { p = parent.Id, c = childId, value = item.Value });
|
||||
}
|
||||
treemapData = new { items, names, colors, clickable = treemapNodes.Keys.ToList() };
|
||||
}
|
||||
|
||||
private void BuildLineChart(AnalyticsResult data)
|
||||
{
|
||||
var profiles = data.YearProfiles;
|
||||
var series = profiles.Select((profile, i) =>
|
||||
{
|
||||
var age = profiles.Count - 1 - i;
|
||||
var color = age switch
|
||||
{
|
||||
0 => ChartTheme.Categorical[0],
|
||||
1 => ChartTheme.Categorical[1],
|
||||
_ => OlderYearColors[Math.Min(age - 2, OlderYearColors.Length - 1)]
|
||||
};
|
||||
var values = cumulative ? RunningTotal(profile.Months) : profile.Months;
|
||||
return new { name = profile.Year.ToString(), color, values, width = age == 0 ? 3 : 2 };
|
||||
}).ToList();
|
||||
lineData = new { labels = MonthNames, series };
|
||||
}
|
||||
|
||||
private static IReadOnlyList<decimal?> RunningTotal(IReadOnlyList<decimal?> months)
|
||||
{
|
||||
var sum = 0m;
|
||||
return months.Select(m => m is { } value ? sum += value : (decimal?)null).ToList();
|
||||
}
|
||||
|
||||
private void SetCumulative(bool value)
|
||||
{
|
||||
cumulative = value;
|
||||
BuildLineChart(result!);
|
||||
}
|
||||
|
||||
private void BuildYearTable(AnalyticsResult data)
|
||||
{
|
||||
lastYearMonths = data.YearProfiles[^1].Months.Count(m => m is not null);
|
||||
maxMonthlyAverage = data.CategoryYears
|
||||
.SelectMany(row => row.Cells)
|
||||
.Select(cell => cell.Value / MonthsOf(cell.Year))
|
||||
.DefaultIfEmpty(0)
|
||||
.Max();
|
||||
}
|
||||
|
||||
private int MonthsOf(int year) => year == toYear ? Math.Max(lastYearMonths, 1) : 12;
|
||||
|
||||
private void OnBarClick(string key)
|
||||
{
|
||||
if (int.TryParse(key, out var index) && seriesCategories.ElementAtOrDefault(index) is { CanDrillDown: true } category)
|
||||
{
|
||||
navigation.NavigateTo(NodeUrl(category.Node));
|
||||
}
|
||||
}
|
||||
|
||||
private void OnTreemapClick(string key)
|
||||
{
|
||||
if (treemapNodes.TryGetValue(key, out var target))
|
||||
{
|
||||
navigation.NavigateTo(NodeUrl(target));
|
||||
}
|
||||
}
|
||||
|
||||
// FluentSelect reports its selection again whenever it re-renders. The new year only reaches
|
||||
// OnParametersSet once the navigation completes, so it is taken over right away; otherwise
|
||||
// every re-render starts another navigation to the same URL, cancelling the previous one,
|
||||
// and the page never updates.
|
||||
private void OnFromChanged(int year)
|
||||
{
|
||||
if (year != fromYear)
|
||||
if (year == fromYear)
|
||||
{
|
||||
navigation.NavigateTo(Url(node, year, year > toYear ? year : To, Period));
|
||||
return;
|
||||
}
|
||||
var url = Url(node, year, year > toYear ? year : To, Period);
|
||||
fromYear = year;
|
||||
toYear = Math.Max(toYear, year);
|
||||
navigation.NavigateTo(url);
|
||||
}
|
||||
|
||||
private void OnToChanged(int year)
|
||||
{
|
||||
if (year != toYear)
|
||||
if (year == toYear)
|
||||
{
|
||||
navigation.NavigateTo(Url(node, year < fromYear ? year : From, year, Period));
|
||||
return;
|
||||
}
|
||||
var url = Url(node, year < fromYear ? year : From, year, Period);
|
||||
toYear = year;
|
||||
fromYear = Math.Min(fromYear, year);
|
||||
navigation.NavigateTo(url);
|
||||
}
|
||||
|
||||
private void ShowAllYears() => navigation.NavigateTo(Url(node, null, null, Period));
|
||||
|
|
@ -179,6 +292,8 @@ public partial class Analytics : ComponentBase
|
|||
_ => "Jahr"
|
||||
};
|
||||
|
||||
private bool CanDrillDown => result!.Categories.Any(c => c.CanDrillDown);
|
||||
|
||||
private string RangeLabel => fromYear == toYear ? fromYear.ToString() : $"{fromYear}–{toYear}";
|
||||
|
||||
private string CurrentName => result!.Breadcrumb[^1].Name;
|
||||
|
|
@ -194,10 +309,31 @@ public partial class Analytics : ComponentBase
|
|||
|
||||
private static string Chf(decimal value) => ChartFormatting.Chf(value);
|
||||
|
||||
private static string Whole(decimal value) => value.ToString("#,0", SwissNumbers);
|
||||
|
||||
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 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 HeatColor(YearCell cell)
|
||||
{
|
||||
if (maxMonthlyAverage <= 0 || cell.Value <= 0)
|
||||
{
|
||||
return "transparent";
|
||||
}
|
||||
var intensity = Math.Min(cell.Value / MonthsOf(cell.Year) / maxMonthlyAverage, 1);
|
||||
// Capped so dark text stays readable on the strongest cells.
|
||||
return $"rgba(42, 120, 214, {(0.06m + intensity * 0.5m).ToString("0.###", CultureInfo.InvariantCulture)})";
|
||||
}
|
||||
|
||||
private static string ChangeText(decimal? change)
|
||||
=> change is { } c ? (c > 0 ? "+" : "") + c.ToString("0", Swiss) + " %" : "";
|
||||
|
||||
private static string ComparisonLabel(YearComparison comparison)
|
||||
=> comparison.Months == 12
|
||||
? $"{comparison.Year} vs. {comparison.Year - 1}"
|
||||
|
|
@ -207,6 +343,12 @@ public partial class Analytics : ComponentBase
|
|||
=> 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", _ => "" };
|
||||
private static string ChangeClass(decimal? change) => change switch { > 0 => "up", < 0 => "down", _ => "" };
|
||||
|
||||
private static CultureInfo CreateSwissNumbers()
|
||||
{
|
||||
var culture = new CultureInfo("de-CH");
|
||||
culture.NumberFormat.NumberGroupSeparator = "'";
|
||||
return culture;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -161,3 +161,113 @@
|
|||
color: #52514e;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.pair {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.pair {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.card-header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.card-header .card-title {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.segmented.small {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
::deep .table-card {
|
||||
padding: 16px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.table-scroll {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.years {
|
||||
width: 100%;
|
||||
border-collapse: separate;
|
||||
border-spacing: 2px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.years th,
|
||||
.years td {
|
||||
padding: 6px 8px;
|
||||
text-align: right;
|
||||
white-space: nowrap;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.years thead th {
|
||||
color: #52514e;
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.years .name {
|
||||
text-align: left;
|
||||
font-weight: normal;
|
||||
max-width: 280px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.years thead .name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.years .name a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.years .name a:hover,
|
||||
.years .name a:focus-visible {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.years .total {
|
||||
font-weight: 600;
|
||||
border-left: 1px solid #e1e0d9;
|
||||
}
|
||||
|
||||
.years tfoot th,
|
||||
.years tfoot td {
|
||||
font-weight: 600;
|
||||
border-top: 1px solid #e1e0d9;
|
||||
}
|
||||
|
||||
.years .zero {
|
||||
color: #c4c3be;
|
||||
}
|
||||
|
||||
.change {
|
||||
font-size: 11px;
|
||||
color: #52514e;
|
||||
min-height: 14px;
|
||||
}
|
||||
|
||||
.change.up {
|
||||
color: #c50f1f;
|
||||
}
|
||||
|
||||
.change.down {
|
||||
color: #107c10;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,6 @@
|
|||
@* Chart.js chart (wwwroot/js/charts.js). Created once; a new Data object is 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>
|
||||
|
|
@ -3,30 +3,29 @@ 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
|
||||
public partial class ChartJsChart : 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;
|
||||
private DotNetObjectReference<ChartJsChart>? selfReference;
|
||||
private object? renderedData;
|
||||
|
||||
[Inject]
|
||||
private IJSRuntime js { get; set; } = null!;
|
||||
|
||||
/// <summary>"stackedBar", "line" or "treemap"; see charts.js for the data each one takes.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public IReadOnlyList<string> Labels { get; set; } = [];
|
||||
public string Kind { get; set; } = "";
|
||||
|
||||
/// <summary>Serialized to JSON for charts.js. Pass a new object to update the chart.</summary>
|
||||
[Parameter, EditorRequired]
|
||||
public IReadOnlyList<ChartSeries> Series { get; set; } = [];
|
||||
public object Data { get; set; } = null!;
|
||||
|
||||
/// <summary>Called with the index into <see cref="Series"/> when a clickable segment is clicked.</summary>
|
||||
/// <summary>Called with the clicked element's key (see charts.js) when a clickable element is clicked.</summary>
|
||||
[Parameter]
|
||||
public EventCallback<int> OnSeriesClick { get; set; }
|
||||
public EventCallback<string> OnClick { get; set; }
|
||||
|
||||
[Parameter]
|
||||
public string Height { get; set; } = "420px";
|
||||
|
|
@ -36,18 +35,11 @@ public partial class StackedBarChart : ComponentBase, IAsyncDisposable
|
|||
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (ReferenceEquals(Labels, renderedLabels) && ReferenceEquals(Series, renderedSeries))
|
||||
if (ReferenceEquals(Data, renderedData))
|
||||
{
|
||||
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 })
|
||||
};
|
||||
var data = renderedData = Data;
|
||||
|
||||
if (creating is null)
|
||||
{
|
||||
|
|
@ -65,11 +57,11 @@ public partial class StackedBarChart : ComponentBase, IAsyncDisposable
|
|||
{
|
||||
module = await js.InvokeAsync<IJSObjectReference>("import", "./js/charts.js");
|
||||
selfReference = DotNetObjectReference.Create(this);
|
||||
chart = await module.InvokeAsync<IJSObjectReference>("createStackedBar", canvas, data, selfReference);
|
||||
chart = await module.InvokeAsync<IJSObjectReference>("createChart", canvas, Kind, data, selfReference);
|
||||
}
|
||||
|
||||
[JSInvokable]
|
||||
public Task OnSeriesClicked(int seriesIndex) => OnSeriesClick.InvokeAsync(seriesIndex);
|
||||
public Task OnChartClicked(string key) => OnClick.InvokeAsync(key);
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
@* 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>
|
||||
|
|
@ -1,20 +1,28 @@
|
|||
// 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.
|
||||
// Thin Chart.js wrapper for Blazor (see ChartJsChart.razor). Chart.js and the treemap plugin are
|
||||
// loaded on first use from wwwroot/lib, so pages without charts don't pay for them.
|
||||
|
||||
let chartJsLoading;
|
||||
const scripts = new Map();
|
||||
|
||||
function loadChartJs() {
|
||||
if (window.Chart) {
|
||||
return Promise.resolve();
|
||||
function loadScript(src) {
|
||||
if (!scripts.has(src)) {
|
||||
scripts.set(src, new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = src;
|
||||
script.onload = resolve;
|
||||
script.onerror = () => reject(new Error(`${src} could not be loaded`));
|
||||
document.head.appendChild(script);
|
||||
}));
|
||||
}
|
||||
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;
|
||||
return scripts.get(src);
|
||||
}
|
||||
|
||||
async function loadChartJs(kind) {
|
||||
await loadScript('lib/chartjs/chart.umd.min.js');
|
||||
if (kind === 'treemap') {
|
||||
// Registers itself with the global Chart.
|
||||
await loadScript('lib/chartjs-chart-treemap/chartjs-chart-treemap.min.js');
|
||||
}
|
||||
window.Chart.defaults.font.family = theme.font;
|
||||
}
|
||||
|
||||
// Same look as ChartTheme.cs.
|
||||
|
|
@ -32,54 +40,69 @@ 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
|
||||
}));
|
||||
// Treemap tile helpers: level 0 tiles are parents (their group value is the parent id); level 1
|
||||
// tiles keep the original tree items, which carry the parent id.
|
||||
const parentOf = raw => raw.l === 0 ? raw.g : raw._data.children[0].p;
|
||||
const isParentGroup = (raw, items) => raw.l === 0 && items.some(i => i.c);
|
||||
|
||||
function withAlpha(hex, alpha) {
|
||||
const n = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${n >> 16}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 tooltip = {
|
||||
backgroundColor: '#ffffff',
|
||||
borderColor: theme.grid,
|
||||
borderWidth: 1,
|
||||
titleColor: theme.ink,
|
||||
bodyColor: theme.ink,
|
||||
footerColor: theme.ink,
|
||||
titleFont: { weight: 'bold' },
|
||||
footerFont: { weight: 'bold' },
|
||||
padding: 10,
|
||||
usePointStyle: true
|
||||
};
|
||||
|
||||
const chart = new window.Chart(canvas, {
|
||||
const legend = {
|
||||
position: 'bottom',
|
||||
labels: { usePointStyle: true, pointStyle: 'rectRounded', boxWidth: 10, color: theme.muted, font: { size: 12 } }
|
||||
};
|
||||
|
||||
const amountAxis = {
|
||||
grid: { color: theme.grid },
|
||||
border: { display: false },
|
||||
title: { display: true, text: 'CHF', color: theme.muted },
|
||||
ticks: { color: theme.muted, callback: value => formatAxis(value) }
|
||||
};
|
||||
|
||||
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
|
||||
stackedBar: {
|
||||
type: 'bar',
|
||||
data: { labels: data.labels, datasets: toDatasets(data.series) },
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
animation: { duration: 250 },
|
||||
data: data => ({
|
||||
labels: data.labels,
|
||||
datasets: data.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
|
||||
}))
|
||||
}),
|
||||
options: () => ({
|
||||
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 } }
|
||||
},
|
||||
legend,
|
||||
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,
|
||||
...tooltip,
|
||||
filter: item => item.parsed.y !== 0,
|
||||
itemSort: (a, b) => b.parsed.y - a.parsed.y,
|
||||
callbacks: {
|
||||
|
|
@ -88,33 +111,148 @@ export async function createStackedBar(canvas, data, dotNetRef) {
|
|||
}
|
||||
}
|
||||
},
|
||||
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) }
|
||||
scales: { x: { ...categoryAxis, stacked: true }, y: { ...amountAxis, stacked: true } }
|
||||
}),
|
||||
hit: (chart, event) => {
|
||||
const hit = chart.getElementsAtEventForMode(event, 'nearest', { intersect: true }, false)[0];
|
||||
return hit && chart.data.datasets[hit.datasetIndex].clickable ? String(hit.datasetIndex) : null;
|
||||
}
|
||||
},
|
||||
|
||||
// data: { labels, series: [{ name, color, values (null = no data), width }] }; not clickable
|
||||
line: {
|
||||
type: 'line',
|
||||
data: data => ({
|
||||
labels: data.labels,
|
||||
datasets: data.series.map(s => ({
|
||||
label: s.name,
|
||||
data: s.values,
|
||||
borderColor: s.color,
|
||||
backgroundColor: s.color,
|
||||
borderWidth: s.width,
|
||||
pointRadius: s.width > 2 ? 3 : 2,
|
||||
pointHoverRadius: 5,
|
||||
tension: 0.25,
|
||||
spanGaps: false
|
||||
}))
|
||||
}),
|
||||
options: () => ({
|
||||
interaction: { mode: 'index', intersect: false },
|
||||
plugins: {
|
||||
legend: { ...legend, labels: { ...legend.labels, pointStyle: 'line' } },
|
||||
tooltip: {
|
||||
...tooltip,
|
||||
filter: item => item.parsed.y !== null,
|
||||
itemSort: (a, b) => b.parsed.y - a.parsed.y,
|
||||
callbacks: { label: item => ` ${item.dataset.label}: ${formatChf(item.parsed.y)} CHF` }
|
||||
}
|
||||
},
|
||||
scales: { x: categoryAxis, y: amountAxis }
|
||||
}),
|
||||
hit: () => null
|
||||
},
|
||||
|
||||
// data: { items: [{ p, c, value }], names: { id: name }, colors: { p: color }, clickable: [key] }
|
||||
// p = parent id, c = child id (null for a single level); click key = "p" or "p|c"
|
||||
treemap: {
|
||||
type: 'treemap',
|
||||
data: data => ({
|
||||
datasets: [{
|
||||
tree: data.items,
|
||||
key: 'value',
|
||||
groups: data.items.some(i => i.c) ? ['p', 'c'] : ['p'],
|
||||
spacing: 1,
|
||||
borderWidth: 0,
|
||||
borderRadius: 3,
|
||||
backgroundColor: ctx => {
|
||||
if (ctx.type !== 'data') {
|
||||
return 'transparent';
|
||||
}
|
||||
const color = data.colors[parentOf(ctx.raw)] ?? '#898781';
|
||||
return withAlpha(color, isParentGroup(ctx.raw, data.items) ? 0.25 : 0.9);
|
||||
},
|
||||
captions: {
|
||||
display: true,
|
||||
color: theme.ink,
|
||||
font: { weight: 'bold', size: 12 },
|
||||
formatter: ctx => `${data.names[ctx.raw.g]} ${formatAxis(ctx.raw.v)}`
|
||||
},
|
||||
labels: {
|
||||
display: true,
|
||||
color: '#ffffff',
|
||||
font: [{ size: 12, weight: 'bold' }, { size: 11 }],
|
||||
overflow: 'hidden',
|
||||
formatter: ctx => [data.names[ctx.raw.g], `${formatAxis(ctx.raw.v)} CHF`]
|
||||
}
|
||||
}]
|
||||
}),
|
||||
options: state => ({
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
...tooltip,
|
||||
displayColors: false,
|
||||
callbacks: {
|
||||
title: items => {
|
||||
const raw = items[0].raw;
|
||||
const names = state().names;
|
||||
return raw.l === 0 ? names[raw.g] : `${names[parentOf(raw)]} › ${names[raw.g]}`;
|
||||
},
|
||||
label: item => `${formatChf(item.raw.v)} CHF`
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
hit: (chart, event) => {
|
||||
// Deepest tile under the pointer: an account inside a subclass wins over the subclass.
|
||||
const hits = chart.getElementsAtEventForMode(event, 'point', { intersect: true }, false);
|
||||
const data = chart.data.datasets[0].data;
|
||||
const raw = hits.map(h => data[h.index]).sort((a, b) => b.l - a.l)[0];
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
const key = raw.l === 0 ? raw.g : `${parentOf(raw)}|${raw.g}`;
|
||||
return chart.$clickable?.includes(key) ? key : null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a chart of the given kind on the canvas and returns a handle with update/destroy.
|
||||
* Clicking a clickable element calls dotNetRef.OnChartClicked(key); see the kinds above for keys.
|
||||
*/
|
||||
export async function createChart(canvas, kind, data, dotNetRef) {
|
||||
await loadChartJs(kind);
|
||||
const spec = kinds[kind];
|
||||
let current = data;
|
||||
|
||||
const chart = new window.Chart(canvas, {
|
||||
type: spec.type,
|
||||
data: spec.data(current),
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
animation: { duration: 250 },
|
||||
...spec.options(() => current),
|
||||
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';
|
||||
event.native.target.style.cursor = spec.hit(chart, event) !== null ? '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);
|
||||
const key = spec.hit(chart, event);
|
||||
if (key !== null) {
|
||||
dotNetRef.invokeMethodAsync('OnChartClicked', key);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
chart.$clickable = current.clickable;
|
||||
|
||||
return {
|
||||
update(newData) {
|
||||
chart.data.labels = newData.labels;
|
||||
chart.data.datasets = toDatasets(newData.series);
|
||||
current = newData;
|
||||
chart.$clickable = current.clickable;
|
||||
chart.data = spec.data(current);
|
||||
chart.update();
|
||||
},
|
||||
destroy() {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2019-2021 Jukka Kurkela
|
||||
|
||||
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.
|
||||
8
Schaad.Accounting.UI/wwwroot/lib/chartjs-chart-treemap/chartjs-chart-treemap.min.js
vendored
Normal file
8
Schaad.Accounting.UI/wwwroot/lib/chartjs-chart-treemap/chartjs-chart-treemap.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
Loading…
Reference in a new issue