Strom page: toggle charts between bill, calendar year and half-year (#10)

Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
This commit is contained in:
Claudio Schaad 2026-10-30 19:07:54 +00:00 committed by clayschaad
parent a6e479094e
commit dee1e0dde0
8 changed files with 329 additions and 169 deletions

View file

@ -64,7 +64,7 @@ When a new year is opened, the previous year's data is copied as the starting po
- **RawDataRepository** — plain-text load/save of the data files for the JSON editor page; validates (strict JSON, unique Ids, account references), refuses if the file changed since loading, and backs up the old version to `backup/{mandator}/{year}/json-{timestamp}/`; for `electricity.json` it reads/writes the mandator folder instead of the year folder
- **Texte bereinigen** page (`TextCleanup`) — edits only the `Text` of one account's bookings in the selected year (inline, search/replace via `TextReplacement`, bulk set); saves through `RawDataRepository.SaveTransactionTextsAsync`
- **AnalyticsService** — loads all years of the current mandator (via `MultiYearRepository`) into an `AccountingAnalysis` (expenses, income, net, assets) for the Analyse page; queries run in memory
- **Strom** page (`Electricity`, `/electricity`) — grid and dialog (FluentDataGrid/`ElectricityBillDialog`) over `IElectricityBillRepository`'s `ElectricityBill` records (one yearly NeoVac bill each: kWh/CHF for grid and PV, side costs; `TotalKwh`, `PvShare`, `TotalChf`, `ChfPerKwh` are computed); three Chart.js charts via `ChartJsChart`, one value per calendar half-year (`ElectricityHalfYear` spreads each bill evenly over its months): stacked kWh, CHF/kWh lines, total CHF
- **Strom** page (`Electricity`, `/electricity`) — grid and dialog (FluentDataGrid/`ElectricityBillDialog`) over `IElectricityBillRepository`'s `ElectricityBill` records (one yearly NeoVac bill each: kWh/CHF for grid and PV, side costs; `TotalKwh`, `PvShare`, `TotalChf`, `ChfPerKwh` are computed); three Chart.js charts via `ChartJsChart` (stacked kWh, CHF/kWh lines, total CHF), grouped by a toggle per bill (default), calendar year or half-year (`ElectricityPeriod.FromBills`; a bill reaching over several periods is spread evenly over its months and the page shows a note)
### UI structure

View file

@ -1,73 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Schaad.Accounting.Models
{
/// <summary>
/// One calendar half-year (January–June or July–December) of electricity bills, for the
/// charts on the Strom page. <see cref="Bill"/> holds the bill values that fall into this
/// half-year, or is null if no bill covers it.
/// </summary>
public class ElectricityHalfYear
{
public DateOnly From { get; init; }
public ElectricityBill Bill { get; init; }
/// <summary>Short label for a chart axis, e.g. "H2 23".</summary>
public string Label => $"H{(From.Month <= 6 ? 1 : 2)} {From:yy}";
/// <summary>
/// Splits the bills into calendar half-years, from the first to the last covered one
/// (half-years in between that no bill covers are included with a null Bill). A bill's
/// values are spread evenly over the months of its period, so a yearly bill (1 July –
/// 30 June) contributes exactly half to each of its two half-years.
/// </summary>
public static List<ElectricityHalfYear> FromBills(IEnumerable<ElectricityBill> bills)
{
var sums = new SortedDictionary<DateOnly, ElectricityBill>();
foreach (var bill in bills)
{
var months = MonthIndex(bill.PeriodTo) - MonthIndex(bill.PeriodFrom) + 1;
if (months <= 0)
{
continue;
}
var monthsPerHalf = Enumerable.Range(0, months)
.Select(m => HalfYearStart(bill.PeriodFrom.AddMonths(m)))
.GroupBy(start => start);
foreach (var half in monthsPerHalf)
{
var share = (decimal)half.Count() / months;
if (!sums.TryGetValue(half.Key, out var sum))
{
sum = new ElectricityBill { PeriodFrom = half.Key, PeriodTo = half.Key.AddMonths(6).AddDays(-1) };
sums[half.Key] = sum;
}
sum.GridKwh += bill.GridKwh * share;
sum.PvKwh += bill.PvKwh * share;
sum.GridChf += bill.GridChf * share;
sum.PvChf += bill.PvChf * share;
sum.SideCostsChf += bill.SideCostsChf * share;
}
}
var result = new List<ElectricityHalfYear>();
if (sums.Count == 0)
{
return result;
}
for (var start = sums.Keys.First(); start <= sums.Keys.Last(); start = start.AddMonths(6))
{
result.Add(new ElectricityHalfYear { From = start, Bill = sums.GetValueOrDefault(start) });
}
return result;
}
private static int MonthIndex(DateOnly date) => date.Year * 12 + date.Month - 1;
private static DateOnly HalfYearStart(DateOnly date) => new(date.Year, date.Month <= 6 ? 1 : 7, 1);
}
}

View file

@ -0,0 +1,125 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Schaad.Accounting.Models
{
/// <summary>How the electricity bills are grouped for the charts on the Strom page.</summary>
public enum ElectricityPeriodKind
{
/// <summary>One entry per bill, exactly as entered.</summary>
Bill,
/// <summary>One entry per calendar year.</summary>
Year,
/// <summary>One entry per calendar half-year (January–June or July–December).</summary>
HalfYear
}
/// <summary>
/// One period of electricity bills, for the charts on the Strom page. <see cref="Bill"/> holds
/// the bill values that fall into this period, or is null if no bill covers it.
/// </summary>
public class ElectricityPeriod
{
public ElectricityPeriodKind Kind { get; init; }
public DateOnly From { get; init; }
public DateOnly To { get; init; }
public ElectricityBill Bill { get; init; }
/// <summary>
/// True if the values were (partly) spread from a bill whose period reaches beyond this one,
/// i.e. they are estimated rather than billed.
/// </summary>
public bool IsSplit { get; init; }
/// <summary>Short label for a chart axis, e.g. "23/24", "2024" or "H2 23".</summary>
public string Label => Kind switch
{
ElectricityPeriodKind.Year => From.Year.ToString(),
ElectricityPeriodKind.HalfYear => $"H{(From.Month <= 6 ? 1 : 2)} {From:yy}",
_ => IsWholeBillingYear ? $"{From:yy}/{To:yy}" : $"{From:dd.MM.yy}–{To:dd.MM.yy}"
};
private bool IsWholeBillingYear => From.Day == 1 && To == From.AddYears(1).AddDays(-1);
/// <summary>
/// Groups the bills by <paramref name="kind"/>. With <see cref="ElectricityPeriodKind.Bill"/>
/// each bill is its own period. Otherwise the result runs from the first to the last covered
/// calendar period (periods in between that no bill covers are included with a null Bill),
/// and a bill's values are spread evenly over the months of its period, so a yearly bill
/// (1 July – 30 June) contributes exactly half to each of its two half-years or calendar years.
/// </summary>
public static List<ElectricityPeriod> FromBills(IEnumerable<ElectricityBill> bills, ElectricityPeriodKind kind)
{
if (kind == ElectricityPeriodKind.Bill)
{
return bills
.OrderBy(b => b.PeriodFrom)
.Select(b => new ElectricityPeriod { Kind = kind, From = b.PeriodFrom, To = b.PeriodTo, Bill = b })
.ToList();
}
var length = kind == ElectricityPeriodKind.Year ? 12 : 6;
var sums = new SortedDictionary<DateOnly, ElectricityBill>();
var split = new HashSet<DateOnly>();
foreach (var bill in bills)
{
var months = MonthIndex(bill.PeriodTo) - MonthIndex(bill.PeriodFrom) + 1;
if (months <= 0)
{
continue;
}
var monthsPerPeriod = Enumerable.Range(0, months)
.Select(m => PeriodStart(bill.PeriodFrom.AddMonths(m), length))
.GroupBy(start => start)
.ToList();
foreach (var period in monthsPerPeriod)
{
var share = (decimal)period.Count() / months;
if (!sums.TryGetValue(period.Key, out var sum))
{
sum = new ElectricityBill { PeriodFrom = period.Key, PeriodTo = period.Key.AddMonths(length).AddDays(-1) };
sums[period.Key] = sum;
}
if (monthsPerPeriod.Count > 1)
{
split.Add(period.Key);
}
sum.GridKwh += bill.GridKwh * share;
sum.PvKwh += bill.PvKwh * share;
sum.GridChf += bill.GridChf * share;
sum.PvChf += bill.PvChf * share;
sum.SideCostsChf += bill.SideCostsChf * share;
}
}
var result = new List<ElectricityPeriod>();
if (sums.Count == 0)
{
return result;
}
for (var start = sums.Keys.First(); start <= sums.Keys.Last(); start = start.AddMonths(length))
{
result.Add(new ElectricityPeriod
{
Kind = kind,
From = start,
To = start.AddMonths(length).AddDays(-1),
Bill = sums.GetValueOrDefault(start),
IsSplit = split.Contains(start)
});
}
return result;
}
private static int MonthIndex(DateOnly date) => date.Year * 12 + date.Month - 1;
private static DateOnly PeriodStart(DateOnly date, int length) => new(date.Year, (date.Month - 1) / length * length + 1, 1);
}
}

View file

@ -1,79 +0,0 @@
using Schaad.Accounting.Models;
using Shouldly;
namespace Schaad.Accounting.Tests;
public class ElectricityHalfYearTestShould
{
[Fact]
public void SplitYearlyBillIntoTwoHalvesWhenPeriodRunsJulyToJune()
{
var bill = Bill(new DateOnly(2023, 7, 1), new DateOnly(2024, 6, 30));
bill.GridKwh = 3000m;
bill.PvKwh = 2000m;
bill.GridChf = 900m;
bill.PvChf = 400m;
bill.SideCostsChf = 100m;
var halves = ElectricityHalfYear.FromBills([bill]);
halves.Count.ShouldBe(2);
halves[0].From.ShouldBe(new DateOnly(2023, 7, 1));
halves[1].From.ShouldBe(new DateOnly(2024, 1, 1));
foreach (var half in halves)
{
half.Bill.GridKwh.ShouldBe(1500m);
half.Bill.PvKwh.ShouldBe(1000m);
half.Bill.GridChf.ShouldBe(450m);
half.Bill.PvChf.ShouldBe(200m);
half.Bill.SideCostsChf.ShouldBe(50m);
}
}
[Fact]
public void KeepPricePerKwhOfTheBillWhenSplittingIt()
{
var bill = Bill(new DateOnly(2023, 7, 1), new DateOnly(2024, 6, 30));
bill.GridKwh = 3000m;
bill.GridChf = 900m;
var halves = ElectricityHalfYear.FromBills([bill]);
halves.ShouldAllBe(h => h.Bill.GridChfPerKwh == 0.3m);
}
[Fact]
public void AddUpBillsWhenTheyShareAHalfYear()
{
var first = Bill(new DateOnly(2024, 1, 1), new DateOnly(2024, 3, 31));
first.GridKwh = 100m;
var second = Bill(new DateOnly(2024, 4, 1), new DateOnly(2024, 6, 30));
second.GridKwh = 200m;
var halves = ElectricityHalfYear.FromBills([first, second]);
halves.Count.ShouldBe(1);
halves[0].Bill.GridKwh.ShouldBe(300m);
}
[Fact]
public void IncludeEmptyHalfYearWhenNoBillCoversIt()
{
var first = Bill(new DateOnly(2022, 7, 1), new DateOnly(2023, 6, 30));
var later = Bill(new DateOnly(2024, 7, 1), new DateOnly(2025, 6, 30));
var halves = ElectricityHalfYear.FromBills([later, first]);
halves.Select(h => h.Label).ShouldBe(["H2 22", "H1 23", "H2 23", "H1 24", "H2 24", "H1 25"]);
halves[2].Bill.ShouldBeNull();
halves[3].Bill.ShouldBeNull();
}
[Fact]
public void ReturnEmptyListWhenThereAreNoBills()
{
ElectricityHalfYear.FromBills([]).ShouldBeEmpty();
}
private static ElectricityBill Bill(DateOnly from, DateOnly to) => new() { PeriodFrom = from, PeriodTo = to };
}

View file

@ -0,0 +1,131 @@
using Schaad.Accounting.Models;
using Shouldly;
namespace Schaad.Accounting.Tests;
public class ElectricityPeriodTestShould
{
[Fact]
public void KeepEachBillUnchangedWhenGroupingPerBill()
{
var later = YearlyBill(2024);
var first = YearlyBill(2023);
var periods = ElectricityPeriod.FromBills([later, first], ElectricityPeriodKind.Bill);
periods.Select(p => p.Bill).ShouldBe([first, later]);
periods.ShouldAllBe(p => !p.IsSplit);
}
[Fact]
public void LabelBillAsBillingYearWhenItCoversAWholeYear()
{
var periods = ElectricityPeriod.FromBills([YearlyBill(2023)], ElectricityPeriodKind.Bill);
periods[0].Label.ShouldBe("23/24");
}
[Fact]
public void LabelBillWithDatesWhenItIsNotAWholeYear()
{
var bill = Bill(new DateOnly(2024, 1, 1), new DateOnly(2024, 6, 30));
var periods = ElectricityPeriod.FromBills([bill], ElectricityPeriodKind.Bill);
periods[0].Label.ShouldBe("01.01.24–30.06.24");
}
[Fact]
public void SplitYearlyBillIntoTwoHalvesWhenPeriodRunsJulyToJune()
{
var bill = YearlyBill(2023);
bill.GridKwh = 3000m;
bill.PvKwh = 2000m;
bill.GridChf = 900m;
bill.PvChf = 400m;
bill.SideCostsChf = 100m;
var halves = ElectricityPeriod.FromBills([bill], ElectricityPeriodKind.HalfYear);
halves.Count.ShouldBe(2);
halves[0].From.ShouldBe(new DateOnly(2023, 7, 1));
halves[1].From.ShouldBe(new DateOnly(2024, 1, 1));
foreach (var half in halves)
{
half.IsSplit.ShouldBeTrue();
half.Bill.GridKwh.ShouldBe(1500m);
half.Bill.PvKwh.ShouldBe(1000m);
half.Bill.GridChf.ShouldBe(450m);
half.Bill.PvChf.ShouldBe(200m);
half.Bill.SideCostsChf.ShouldBe(50m);
}
}
[Fact]
public void SplitYearlyBillIntoTwoCalendarYearsWhenPeriodRunsJulyToJune()
{
var first = YearlyBill(2023);
first.GridKwh = 3000m;
var second = YearlyBill(2024);
second.GridKwh = 5000m;
var years = ElectricityPeriod.FromBills([first, second], ElectricityPeriodKind.Year);
years.Select(y => y.Label).ShouldBe(["2023", "2024", "2025"]);
years.Select(y => y.Bill.GridKwh).ShouldBe([1500m, 4000m, 2500m]);
years.ShouldAllBe(y => y.IsSplit);
}
[Fact]
public void KeepPricePerKwhOfTheBillWhenSplittingIt()
{
var bill = YearlyBill(2023);
bill.GridKwh = 3000m;
bill.GridChf = 900m;
var halves = ElectricityPeriod.FromBills([bill], ElectricityPeriodKind.HalfYear);
halves.ShouldAllBe(h => h.Bill.GridChfPerKwh == 0.3m);
}
[Fact]
public void AddUpBillsWithoutSplittingWhenTheyShareAPeriod()
{
var first = Bill(new DateOnly(2024, 1, 1), new DateOnly(2024, 3, 31));
first.GridKwh = 100m;
var second = Bill(new DateOnly(2024, 4, 1), new DateOnly(2024, 6, 30));
second.GridKwh = 200m;
var halves = ElectricityPeriod.FromBills([first, second], ElectricityPeriodKind.HalfYear);
halves.Count.ShouldBe(1);
halves[0].Bill.GridKwh.ShouldBe(300m);
halves[0].IsSplit.ShouldBeFalse();
}
[Fact]
public void IncludeEmptyHalfYearWhenNoBillCoversIt()
{
var first = YearlyBill(2022);
var later = YearlyBill(2024);
var halves = ElectricityPeriod.FromBills([later, first], ElectricityPeriodKind.HalfYear);
halves.Select(h => h.Label).ShouldBe(["H2 22", "H1 23", "H2 23", "H1 24", "H2 24", "H1 25"]);
halves[2].Bill.ShouldBeNull();
halves[3].Bill.ShouldBeNull();
}
[Theory]
[InlineData(ElectricityPeriodKind.Bill)]
[InlineData(ElectricityPeriodKind.Year)]
[InlineData(ElectricityPeriodKind.HalfYear)]
public void ReturnEmptyListWhenThereAreNoBills(ElectricityPeriodKind kind)
{
ElectricityPeriod.FromBills([], kind).ShouldBeEmpty();
}
private static ElectricityBill YearlyBill(int startYear) => Bill(new DateOnly(startYear, 7, 1), new DateOnly(startYear + 1, 6, 30));
private static ElectricityBill Bill(DateOnly from, DateOnly to) => new() { PeriodFrom = from, PeriodTo = to };
}

View file

@ -15,23 +15,38 @@
}
else
{
<FluentStack Orientation="Orientation.Horizontal" VerticalAlignment="VerticalAlignment.Center" Wrap="true">
<div class="segmented" role="group" aria-label="Zeitraum">
@foreach (var kind in PeriodKinds)
{
<FluentButton Appearance="@(kind == periodKind ? Appearance.Accent : Appearance.Neutral)"
aria-pressed="@(kind == periodKind ? "true" : "false")"
OnClick="@(() => SetPeriodKind(kind))">@PeriodKindName(kind)</FluentButton>
}
</div>
@if (isSplit)
{
<span class="split-note">Werte anteilig auf die Monate der Abrechnungsperiode verteilt</span>
}
</FluentStack>
<div class="pair">
<FluentCard class="chart-card">
<div class="card-title">Verbrauch pro Halbjahr</div>
<div class="card-title">Verbrauch @PerPeriod</div>
<ChartJsChart Kind="stackedBar" Data="@barData" Height="360px"
AriaLabel="Netzbezug und PV-Produktion pro Halbjahr, gestapelte Balken in kWh" />
AriaLabel="@($"Netzbezug und PV-Produktion {PerPeriod}, gestapelte Balken in kWh")" />
</FluentCard>
<FluentCard class="chart-card">
<div class="card-title">Preis pro kWh</div>
<ChartJsChart Kind="line" Data="@lineData" Height="360px"
AriaLabel="Preis pro kWh für Netz, PV und Total pro Halbjahr" />
AriaLabel="@($"Preis pro kWh für Netz, PV und Total {PerPeriod}")" />
</FluentCard>
</div>
<FluentCard class="chart-card">
<div class="card-title">Gesamtkosten pro Halbjahr</div>
<div class="card-title">Gesamtkosten @PerPeriod</div>
<ChartJsChart Kind="line" Data="@costData" Height="320px"
AriaLabel="Gesamtkosten pro Halbjahr" />
AriaLabel="@($"Gesamtkosten {PerPeriod}")" />
</FluentCard>
}

View file

@ -10,8 +10,9 @@ namespace Schaad.Accounting.UI.Components.Pages;
/// <summary>
/// Yearly NeoVac electricity bills for the apartment (billing period 1 July – 30 June, so the
/// bills are stored once per mandator, not per calendar year; see
/// <see cref="IElectricityBillRepository"/>). Grid for entering/editing, plus charts per half-year
/// (see <see cref="ElectricityHalfYear"/>): consumption grid/PV, price per kWh and total costs.
/// <see cref="IElectricityBillRepository"/>). Grid for entering/editing, plus charts per bill,
/// calendar year or half-year (see <see cref="ElectricityPeriod"/>): consumption grid/PV, price
/// per kWh and total costs.
/// </summary>
public partial class Electricity : ComponentBase
{
@ -24,8 +25,16 @@ public partial class Electricity : ComponentBase
[Inject]
private IToastService toastService { get; set; } = null!;
private static readonly ElectricityPeriodKind[] PeriodKinds =
[ElectricityPeriodKind.Bill, ElectricityPeriodKind.Year, ElectricityPeriodKind.HalfYear];
private IReadOnlyList<ElectricityBill> source = [];
private ElectricityPeriodKind periodKind = ElectricityPeriodKind.Bill;
// True if a bill had to be spread over several periods of the selected kind.
private bool isSplit;
private object barData = new();
private object lineData = new();
private object costData = new();
@ -43,18 +52,25 @@ public partial class Electricity : ComponentBase
BuildCharts();
}
private void SetPeriodKind(ElectricityPeriodKind kind)
{
periodKind = kind;
BuildCharts();
}
private void BuildCharts()
{
// One entry per half-year; a yearly bill is split evenly into its two halves.
var halves = ElectricityHalfYear.FromBills(source);
var labels = halves.Select(h => h.Label).ToList();
// A bill reaching over several periods is spread evenly over its months.
var periods = ElectricityPeriod.FromBills(source, periodKind);
isSplit = periods.Any(p => p.IsSplit);
var labels = periods.Select(p => p.Label).ToList();
barData = new
{
labels,
series = new object[]
{
new { name = "Netz", color = ChartTheme.ColorAt(0), values = halves.Select(h => h.Bill?.GridKwh).ToList(), clickable = false },
new { name = "PV", color = ChartTheme.ColorAt(1), values = halves.Select(h => h.Bill?.PvKwh).ToList(), clickable = false }
new { name = "Netz", color = ChartTheme.ColorAt(0), values = periods.Select(p => p.Bill?.GridKwh).ToList(), clickable = false },
new { name = "PV", color = ChartTheme.ColorAt(1), values = periods.Select(p => p.Bill?.PvKwh).ToList(), clickable = false }
},
unit = "kWh"
};
@ -63,9 +79,9 @@ public partial class Electricity : ComponentBase
labels,
series = new object[]
{
new { name = "Netz", color = ChartTheme.ColorAt(0), values = halves.Select(h => h.Bill?.GridChfPerKwh).ToList(), width = 2 },
new { name = "PV", color = ChartTheme.ColorAt(1), values = halves.Select(h => h.Bill?.PvChfPerKwh).ToList(), width = 2 },
new { name = "Total", color = ChartTheme.OtherColor, values = halves.Select(h => h.Bill?.ChfPerKwh).ToList(), width = 2 }
new { name = "Netz", color = ChartTheme.ColorAt(0), values = periods.Select(p => p.Bill?.GridChfPerKwh).ToList(), width = 2 },
new { name = "PV", color = ChartTheme.ColorAt(1), values = periods.Select(p => p.Bill?.PvChfPerKwh).ToList(), width = 2 },
new { name = "Total", color = ChartTheme.OtherColor, values = periods.Select(p => p.Bill?.ChfPerKwh).ToList(), width = 2 }
},
unit = "CHF/kWh",
axisDecimals = 2
@ -75,7 +91,7 @@ public partial class Electricity : ComponentBase
labels,
series = new object[]
{
new { name = "Total", color = ChartTheme.ColorAt(2), values = halves.Select(h => h.Bill?.TotalChf).ToList(), width = 2 }
new { name = "Total", color = ChartTheme.ColorAt(2), values = periods.Select(p => p.Bill?.TotalChf).ToList(), width = 2 }
},
unit = "CHF"
};
@ -134,5 +150,19 @@ public partial class Electricity : ComponentBase
}
}
private static string PeriodKindName(ElectricityPeriodKind kind) => kind switch
{
ElectricityPeriodKind.Year => "Kalenderjahr",
ElectricityPeriodKind.HalfYear => "Halbjahr",
_ => "Abrechnung"
};
private string PerPeriod => periodKind switch
{
ElectricityPeriodKind.Year => "pro Jahr",
ElectricityPeriodKind.HalfYear => "pro Halbjahr",
_ => "pro Abrechnung"
};
private static string FullLabel(ElectricityBill bill) => $"{bill.PeriodFrom:dd.MM.yyyy} – {bill.PeriodTo:dd.MM.yyyy}";
}

View file

@ -30,3 +30,14 @@
font-size: 15px;
margin-bottom: 12px;
}
.segmented {
display: flex;
flex-wrap: wrap;
gap: 2px;
}
.split-note {
font-size: 12px;
color: var(--neutral-foreground-hint);
}