Add "Strom" page for the yearly NeoVac electricity bills (#9)

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-27 18:40:53 +00:00 committed by clayschaad
parent c9a25481f2
commit a6e479094e
25 changed files with 990 additions and 23 deletions

View file

@ -46,21 +46,25 @@ Data is multi-mandator and multi-year. The layout below `DataPath` (configured i
``` ```
{DataPath}/{mandator}/{year}/*.json data files {DataPath}/{mandator}/{year}/*.json data files
{DataPath}/{mandator}/electricity.json electricity bills (not per year, see below)
{DataPath}/uploads/{mandator}/{year}/ imported bank statements (+ creditCard/) {DataPath}/uploads/{mandator}/{year}/ imported bank statements (+ creditCard/)
{DataPath}/backup/{mandator}/{year}/ backup zips {DataPath}/backup/{mandator}/{year}/ backup zips
``` ```
When a new year is opened, the previous year's data is copied as the starting point. When a new year is opened, the previous year's data is copied as the starting point.
`electricity.json` is the one data file kept per mandator instead of per year (`ISettingsService.GetMandatorPath()`), because the NeoVac billing period runs 1 July–30 June and doesn't align with calendar years.
### Key services ### Key services
- **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 the Plotly booking-text charts on the transactions page - **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
- **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}/` - **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` - **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 - **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
### UI structure ### UI structure

View file

@ -1,5 +1,5 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<TargetFramework>net9.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
</Project> </Project>

View file

@ -0,0 +1,17 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Schaad.Accounting.Models;
namespace Schaad.Accounting.Interfaces
{
public interface IElectricityBillRepository
{
Task<List<ElectricityBill>> GetElectricityBillListAsync();
Task SaveElectricityBillAsync(ElectricityBill bill);
Task<ElectricityBill> GetElectricityBillAsync(string id);
Task DeleteElectricityBillAsync(string id);
}
}

View file

@ -26,6 +26,12 @@ namespace Schaad.Accounting.Interfaces
string GetLastYearDbPath(); string GetLastYearDbPath();
/// <summary>
/// The mandator's folder, above the per-year folders. For data that is not kept per
/// year (e.g. the electricity bills, whose period doesn't align with calendar years).
/// </summary>
string GetMandatorPath();
SettingsDataset GetSettings(); SettingsDataset GetSettings();
} }
} }

View file

@ -0,0 +1,69 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
namespace Schaad.Accounting.Models
{
/// <summary>
/// One yearly NeoVac electricity bill for the apartment. The billing period runs
/// 1 July – 30 June, so these are not stored per calendar year like the other data files
/// (see ElectricityBillRepository in Schaad.Accounting.Db).
/// </summary>
public class ElectricityBill
{
public string Id { get; set; }
[Display(Name = "Von")]
[Required]
public DateOnly PeriodFrom { get; set; }
[Display(Name = "Bis")]
[Required]
public DateOnly PeriodTo { get; set; }
[Display(Name = "Netzbezug")]
public decimal GridKwh { get; set; }
[Display(Name = "PV-Produktion")]
public decimal PvKwh { get; set; }
[Display(Name = "Netzbezug")]
public decimal GridChf { get; set; }
[Display(Name = "PV")]
public decimal PvChf { get; set; }
[Display(Name = "Nebenkosten")]
public decimal SideCostsChf { get; set; }
/// <summary>Grid draw plus own PV consumption, in kWh.</summary>
[JsonIgnore]
[Display(Name = "Total")]
public decimal TotalKwh => GridKwh + PvKwh;
/// <summary>Share of the consumption covered by PV, 0..1.</summary>
[JsonIgnore]
[Display(Name = "PV-Anteil")]
public decimal PvShare => TotalKwh == 0 ? 0 : PvKwh / TotalKwh;
/// <summary>Grid, PV and side costs added up.</summary>
[JsonIgnore]
[Display(Name = "Total")]
public decimal TotalChf => GridChf + PvChf + SideCostsChf;
/// <summary>Average price per kWh over the whole period.</summary>
[JsonIgnore]
[Display(Name = "CHF/kWh")]
public decimal ChfPerKwh => TotalKwh == 0 ? 0 : TotalChf / TotalKwh;
/// <summary>Price per kWh of grid electricity; null if there was no grid draw.</summary>
[JsonIgnore]
[Display(Name = "CHF/kWh Netz")]
public decimal? GridChfPerKwh => GridKwh == 0 ? null : GridChf / GridKwh;
/// <summary>Price per kWh of PV electricity; null if there was no PV consumption.</summary>
[JsonIgnore]
[Display(Name = "CHF/kWh PV")]
public decimal? PvChfPerKwh => PvKwh == 0 ? null : PvChf / PvKwh;
}
}

View file

@ -0,0 +1,73 @@
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

@ -78,9 +78,16 @@ namespace Schaad.Accounting.Repositories
/// renames it, so a crash mid-write leaves the previous file intact. Invalidates /// renames it, so a crash mid-write leaves the previous file intact. Invalidates
/// the corresponding cache entry. /// the corresponding cache entry.
/// </summary> /// </summary>
protected async Task SaveAsync<T>(T obj, string fileName) protected Task SaveAsync<T>(T obj, string fileName)
=> SaveAsync(obj, settingsService.GetDbPath(), fileName);
/// <summary>
/// Same as <see cref="SaveAsync{T}(T,string)"/> for a file in any data directory (e.g.
/// the mandator's folder instead of a year below it).
/// </summary>
protected async Task SaveAsync<T>(T obj, string directory, string fileName)
{ {
var filePath = Path.Combine(settingsService.GetDbPath(), fileName); var filePath = Path.Combine(directory, fileName);
var tmpPath = filePath + ".tmp"; var tmpPath = filePath + ".tmp";
var semaphore = GetLock(filePath); var semaphore = GetLock(filePath);

View file

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Schaad.Accounting.Interfaces;
using Schaad.Accounting.Models;
namespace Schaad.Accounting.Repositories
{
/// <summary>
/// Electricity bills of the current mandator, stored once per mandator (not per year like
/// the other data files) because the billing period runs 1 July – 30 June.
/// </summary>
public class ElectricityBillRepository : BaseRepository, IElectricityBillRepository
{
private const string ELECTRICITY = "electricity.json";
public ElectricityBillRepository(ISettingsService settingsService, RepositoryCache cache, ILogger<ElectricityBillRepository> logger)
: base(settingsService, cache, logger)
{
}
public Task<List<ElectricityBill>> GetElectricityBillListAsync()
=> LoadListAsync<ElectricityBill>(settingsService.GetMandatorPath(), ELECTRICITY);
public async Task SaveElectricityBillAsync(ElectricityBill bill)
{
var bills = await GetElectricityBillListAsync();
var idx = bills.FindIndex(b => b.Id == bill.Id);
if (idx >= 0)
{
bills[idx] = bill;
}
else
{
bill.Id = Guid.NewGuid().ToString();
bills.Add(bill);
}
await SaveAsync(bills, settingsService.GetMandatorPath(), ELECTRICITY);
}
public async Task<ElectricityBill> GetElectricityBillAsync(string id)
{
var bills = await GetElectricityBillListAsync();
return bills.FirstOrDefault(b => b.Id == id);
}
public async Task DeleteElectricityBillAsync(string id)
{
var bills = await GetElectricityBillListAsync();
bills.RemoveAll(b => b.Id == id);
await SaveAsync(bills, settingsService.GetMandatorPath(), ELECTRICITY);
}
}
}

View file

@ -25,6 +25,7 @@ namespace Schaad.Accounting.Repositories
{ {
private const string ACCOUNTS = "Accounts.json"; private const string ACCOUNTS = "Accounts.json";
private const string TRANSACTIONS = "Transactions.json"; private const string TRANSACTIONS = "Transactions.json";
private const string ELECTRICITY = "electricity.json";
private const int MaxErrors = 20; private const int MaxErrors = 20;
// Like the normal options, but property names that don't exist (typos) are errors instead // Like the normal options, but property names that don't exist (typos) are errors instead
@ -47,7 +48,8 @@ namespace Schaad.Accounting.Repositories
"BookingRules.json", "BookingRules.json",
"BookingTexts.json", "BookingTexts.json",
"SplitPredefinitions.json", "SplitPredefinitions.json",
"SubClasses.json" "SubClasses.json",
ELECTRICITY
]; ];
public async Task<RawDataFile> LoadAsync(string fileName) public async Task<RawDataFile> LoadAsync(string fileName)
@ -66,6 +68,7 @@ namespace Schaad.Accounting.Repositories
"BookingTexts.json" => SaveAsync<BookingText>(fileName, text, loadedHash), "BookingTexts.json" => SaveAsync<BookingText>(fileName, text, loadedHash),
"SplitPredefinitions.json" => SaveAsync<SplitPredefinition>(fileName, text, loadedHash), "SplitPredefinitions.json" => SaveAsync<SplitPredefinition>(fileName, text, loadedHash),
"SubClasses.json" => SaveAsync<SubClass>(fileName, text, loadedHash), "SubClasses.json" => SaveAsync<SubClass>(fileName, text, loadedHash),
ELECTRICITY => SaveAsync<ElectricityBill>(fileName, text, loadedHash),
_ => throw new ArgumentException($"Unknown data file '{fileName}'", nameof(fileName)) _ => throw new ArgumentException($"Unknown data file '{fileName}'", nameof(fileName))
}; };
@ -106,7 +109,7 @@ namespace Schaad.Accounting.Repositories
} }
var backupPath = await BackupAsync(current); var backupPath = await BackupAsync(current);
await SaveAsync(items, fileName); await SaveAsync(items, DirectoryOf(fileName), fileName);
logger.LogInformation("Saved {FilePath} from the JSON editor; previous version in {BackupPath}", current.Path, backupPath); logger.LogInformation("Saved {FilePath} from the JSON editor; previous version in {BackupPath}", current.Path, backupPath);
return new RawDataSaveResult([], await LoadAsync(fileName), backupPath); return new RawDataSaveResult([], await LoadAsync(fileName), backupPath);
@ -233,9 +236,14 @@ namespace Schaad.Accounting.Repositories
{ {
throw new ArgumentException($"Unknown data file '{fileName}'", nameof(fileName)); throw new ArgumentException($"Unknown data file '{fileName}'", nameof(fileName));
} }
return Path.Combine(settingsService.GetDbPath(), fileName); return Path.Combine(DirectoryOf(fileName), fileName);
} }
// electricity.json lives at the mandator level, not per year (its period runs 1 July –
// 30 June, so it doesn't align with calendar years).
private string DirectoryOf(string fileName)
=> fileName == ELECTRICITY ? settingsService.GetMandatorPath() : settingsService.GetDbPath();
private static string Hash(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes)); private static string Hash(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes));
private static string Describe(JsonException ex) private static string Describe(JsonException ex)

View file

@ -94,6 +94,11 @@ namespace Schaad.Accounting.Services
return EnsureDirectory(Path.Combine(GetSettings().DataPath, mandator, (year - 1).ToString())); return EnsureDirectory(Path.Combine(GetSettings().DataPath, mandator, (year - 1).ToString()));
} }
public string GetMandatorPath()
{
return EnsureDirectory(Path.Combine(GetSettings().DataPath, mandator));
}
public SettingsDataset GetSettings() public SettingsDataset GetSettings()
{ {
return settingsDataset; return settingsDataset;

View file

@ -0,0 +1,93 @@
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Schaad.Accounting.Interfaces;
using Schaad.Accounting.Models;
using Schaad.Accounting.Repositories;
using Shouldly;
namespace Schaad.Accounting.Tests;
public class ElectricityBillRepositoryTestShould : IDisposable
{
private readonly string mandatorDir;
private readonly ISettingsService settingsService;
private readonly ElectricityBillRepository sut;
public ElectricityBillRepositoryTestShould()
{
mandatorDir = Path.Combine(Path.GetTempPath(), "AccountingNext-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(mandatorDir);
settingsService = Substitute.For<ISettingsService>();
settingsService.GetMandatorPath().Returns(mandatorDir);
sut = new ElectricityBillRepository(settingsService, new RepositoryCache(), NullLogger<ElectricityBillRepository>.Instance);
}
public void Dispose()
{
if (Directory.Exists(mandatorDir))
{
Directory.Delete(mandatorDir, recursive: true);
}
}
[Fact]
public async Task ReturnEmptyListWhenFileDoesNotExistYet()
{
(await sut.GetElectricityBillListAsync()).ShouldBeEmpty();
}
[Fact]
public async Task AssignNewIdWhenSavingBillWithoutId()
{
var bill = new ElectricityBill
{
PeriodFrom = new DateOnly(2023, 7, 1),
PeriodTo = new DateOnly(2024, 6, 30),
GridKwh = 3419.432m,
PvKwh = 1936.328m,
GridChf = 1009.55m,
PvChf = 544.10m,
SideCostsChf = 134.30m
};
await sut.SaveElectricityBillAsync(bill);
var stored = (await sut.GetElectricityBillListAsync()).Single();
stored.Id.ShouldNotBeNullOrEmpty();
stored.TotalChf.ShouldBe(1687.95m);
}
[Fact]
public async Task UpdateInPlaceWhenSavingBillWithExistingId()
{
await sut.SaveElectricityBillAsync(new ElectricityBill { PeriodFrom = new DateOnly(2023, 7, 1), PeriodTo = new DateOnly(2024, 6, 30), GridKwh = 1000m });
var id = (await sut.GetElectricityBillListAsync()).Single().Id;
await sut.SaveElectricityBillAsync(new ElectricityBill { Id = id, PeriodFrom = new DateOnly(2023, 7, 1), PeriodTo = new DateOnly(2024, 6, 30), GridKwh = 1300m });
var bills = await sut.GetElectricityBillListAsync();
bills.Count.ShouldBe(1);
bills[0].GridKwh.ShouldBe(1300m);
}
[Fact]
public async Task RemoveBillWhenDeletingById()
{
await sut.SaveElectricityBillAsync(new ElectricityBill { PeriodFrom = new DateOnly(2023, 7, 1), PeriodTo = new DateOnly(2024, 6, 30) });
var id = (await sut.GetElectricityBillListAsync()).Single().Id;
await sut.DeleteElectricityBillAsync(id);
(await sut.GetElectricityBillListAsync()).ShouldBeEmpty();
}
[Fact]
public async Task StoreFileDirectlyInMandatorFolderWithoutYearSubfolder()
{
await sut.SaveElectricityBillAsync(new ElectricityBill { PeriodFrom = new DateOnly(2023, 7, 1), PeriodTo = new DateOnly(2024, 6, 30) });
File.Exists(Path.Combine(mandatorDir, "electricity.json")).ShouldBeTrue();
}
}

View file

@ -0,0 +1,87 @@
using Schaad.Accounting.Models;
using Shouldly;
namespace Schaad.Accounting.Tests;
public class ElectricityBillTestShould
{
[Fact]
public void AddGridAndPvWhenCalculatingTotalKwh()
{
var bill = new ElectricityBill { GridKwh = 3419.432m, PvKwh = 1936.328m };
bill.TotalKwh.ShouldBe(5355.76m);
}
[Fact]
public void DividePvByTotalWhenCalculatingPvShare()
{
var bill = new ElectricityBill { GridKwh = 600m, PvKwh = 400m };
bill.PvShare.ShouldBe(0.4m);
}
[Fact]
public void ReturnZeroPvShareWhenThereIsNoConsumption()
{
var bill = new ElectricityBill { GridKwh = 0m, PvKwh = 0m };
bill.PvShare.ShouldBe(0m);
}
[Fact]
public void AddGridPvAndSideCostsWhenCalculatingTotalChf()
{
var bill = new ElectricityBill { GridChf = 1009.55m, PvChf = 544.10m, SideCostsChf = 134.30m };
bill.TotalChf.ShouldBe(1687.95m);
}
[Fact]
public void DivideTotalChfByTotalKwhWhenCalculatingChfPerKwh()
{
var bill = new ElectricityBill { GridKwh = 600m, PvKwh = 400m, GridChf = 60m, PvChf = 40m };
bill.ChfPerKwh.ShouldBe(0.1m);
}
[Fact]
public void ReturnZeroChfPerKwhWhenThereIsNoConsumption()
{
var bill = new ElectricityBill { GridKwh = 0m, PvKwh = 0m, GridChf = 0m, PvChf = 0m, SideCostsChf = 50m };
bill.ChfPerKwh.ShouldBe(0m);
}
[Fact]
public void DivideGridChfByGridKwhWhenCalculatingGridChfPerKwh()
{
var bill = new ElectricityBill { GridKwh = 600m, GridChf = 180m };
bill.GridChfPerKwh.ShouldBe(0.3m);
}
[Fact]
public void ReturnNullGridChfPerKwhWhenThereWasNoGridDraw()
{
var bill = new ElectricityBill { GridKwh = 0m, GridChf = 0m };
bill.GridChfPerKwh.ShouldBeNull();
}
[Fact]
public void DividePvChfByPvKwhWhenCalculatingPvChfPerKwh()
{
var bill = new ElectricityBill { PvKwh = 400m, PvChf = 100m };
bill.PvChfPerKwh.ShouldBe(0.25m);
}
[Fact]
public void ReturnNullPvChfPerKwhWhenThereWasNoPvConsumption()
{
var bill = new ElectricityBill { PvKwh = 0m, PvChf = 0m };
bill.PvChfPerKwh.ShouldBeNull();
}
}

View file

@ -0,0 +1,79 @@
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

@ -24,6 +24,7 @@ public class RawDataRepositoryTestShould : IDisposable
private readonly string dataPath; private readonly string dataPath;
private readonly string dbDir; private readonly string dbDir;
private readonly string mandatorDir;
private readonly RepositoryCache cache = new(); private readonly RepositoryCache cache = new();
private readonly ISettingsService settingsService; private readonly ISettingsService settingsService;
private readonly RawDataRepository sut; private readonly RawDataRepository sut;
@ -31,7 +32,8 @@ public class RawDataRepositoryTestShould : IDisposable
public RawDataRepositoryTestShould() public RawDataRepositoryTestShould()
{ {
dataPath = Path.Combine(Path.GetTempPath(), "AccountingNext-tests-" + Guid.NewGuid().ToString("N")); dataPath = Path.Combine(Path.GetTempPath(), "AccountingNext-tests-" + Guid.NewGuid().ToString("N"));
dbDir = Path.Combine(dataPath, "Mandator", "2026"); mandatorDir = Path.Combine(dataPath, "Mandator");
dbDir = Path.Combine(mandatorDir, "2026");
Directory.CreateDirectory(dbDir); Directory.CreateDirectory(dbDir);
File.WriteAllText(Path.Combine(dbDir, "Accounts.json"), Accounts); File.WriteAllText(Path.Combine(dbDir, "Accounts.json"), Accounts);
File.WriteAllText(Path.Combine(dbDir, "Transactions.json"), Transactions); File.WriteAllText(Path.Combine(dbDir, "Transactions.json"), Transactions);
@ -39,6 +41,7 @@ public class RawDataRepositoryTestShould : IDisposable
settingsService = Substitute.For<ISettingsService>(); settingsService = Substitute.For<ISettingsService>();
settingsService.GetDbPath().Returns(dbDir); settingsService.GetDbPath().Returns(dbDir);
settingsService.GetLastYearDbPath().Returns(Path.Combine(dataPath, "no-such-dir")); settingsService.GetLastYearDbPath().Returns(Path.Combine(dataPath, "no-such-dir"));
settingsService.GetMandatorPath().Returns(mandatorDir);
settingsService.GetSettings().Returns(new SettingsDataset { DataPath = dataPath }); settingsService.GetSettings().Returns(new SettingsDataset { DataPath = dataPath });
settingsService.GetMandator().Returns("Mandator"); settingsService.GetMandator().Returns("Mandator");
settingsService.GetYear().Returns(2026); settingsService.GetYear().Returns(2026);
@ -169,6 +172,24 @@ public class RawDataRepositoryTestShould : IDisposable
File.ReadAllText(Path.Combine(dbDir, "Transactions.json")).ShouldContain("13"); File.ReadAllText(Path.Combine(dbDir, "Transactions.json")).ShouldContain("13");
} }
[Fact]
public async Task ReadAndWriteElectricityFileInMandatorFolderNotYearFolderWhenEditing()
{
File.WriteAllText(Path.Combine(mandatorDir, "electricity.json"), """
[ { "Id": "e1", "PeriodFrom": "2023-07-01", "PeriodTo": "2024-06-30", "GridKwh": 100 } ]
""");
var loaded = await sut.LoadAsync("electricity.json");
loaded.Text.ShouldContain("\"GridKwh\": 100");
var result = await sut.SaveAsync("electricity.json", loaded.Text.Replace("100", "150"), loaded.Hash);
result.Errors.ShouldBeEmpty();
result.Saved.ShouldBeTrue();
File.Exists(Path.Combine(mandatorDir, "electricity.json")).ShouldBeTrue();
File.ReadAllText(Path.Combine(mandatorDir, "electricity.json")).ShouldContain("150");
File.Exists(Path.Combine(dbDir, "electricity.json")).ShouldBeFalse();
}
[Fact] [Fact]
public async Task RejectUnknownFileNameWhenLoading() public async Task RejectUnknownFileNameWhenLoading()
{ {

View file

@ -33,6 +33,12 @@ public class SettingsServiceTestShould : IDisposable
sut.GetLastYearDbPath().ShouldBe(Path.Combine(dataPath, "Mandator", "2024")); sut.GetLastYearDbPath().ShouldBe(Path.Combine(dataPath, "Mandator", "2024"));
} }
[Fact]
public void ReturnMandatorFolderWithoutYearWhenGettingMandatorPath()
{
sut.GetMandatorPath().ShouldBe(Path.Combine(dataPath, "Mandator"));
}
[Fact] [Fact]
public void ReturnFoldersBelowRootUploadsWhenGettingUploadPaths() public void ReturnFoldersBelowRootUploadsWhenGettingUploadPaths()
{ {

View file

@ -9,6 +9,7 @@
<FluentNavLink Href="/" Match="NavLinkMatch.All" Icon="@(new Size20.Home())" IconColor="Color.Accent">Home</FluentNavLink> <FluentNavLink Href="/" Match="NavLinkMatch.All" Icon="@(new Size20.Home())" IconColor="Color.Accent">Home</FluentNavLink>
<FluentNavLink Href="transactions" Icon="@(new Size20.NumberSymbolSquare())" IconColor="Color.Accent">Transaktionen</FluentNavLink> <FluentNavLink Href="transactions" Icon="@(new Size20.NumberSymbolSquare())" IconColor="Color.Accent">Transaktionen</FluentNavLink>
<FluentNavLink Href="banktransactions" Icon="@(new Size20.BuildingBank())" IconColor="Color.Accent">Bank Transaktionen</FluentNavLink> <FluentNavLink Href="banktransactions" Icon="@(new Size20.BuildingBank())" IconColor="Color.Accent">Bank Transaktionen</FluentNavLink>
<FluentNavLink Href="electricity" Icon="@(new Size20.Flash())" IconColor="Color.Accent">Strom</FluentNavLink>
<FluentNavGroup Title="Stammdaten" Icon="@(new Size32.BookDatabase())"> <FluentNavGroup Title="Stammdaten" Icon="@(new Size32.BookDatabase())">
<FluentNavLink Href="bookingrules" Icon="@(new Size20.Check())" IconColor="Color.Accent">Buchungsregeln</FluentNavLink> <FluentNavLink Href="bookingrules" Icon="@(new Size20.Check())" IconColor="Color.Accent">Buchungsregeln</FluentNavLink>
<FluentNavLink Href="bookingtexts" Icon="@(new Size32.Text())" IconColor="Color.Accent">Buchungstexte</FluentNavLink> <FluentNavLink Href="bookingtexts" Icon="@(new Size32.Text())" IconColor="Color.Accent">Buchungstexte</FluentNavLink>

View file

@ -0,0 +1,64 @@
@implements IDialogContentComponent<Schaad.Accounting.Models.ElectricityBill>
@rendermode InteractiveServer
<FluentDialogHeader ShowDismiss="true">
<FluentStack VerticalAlignment="VerticalAlignment.Center">
<FluentIcon Value="@(new Icons.Regular.Size24.WindowApps())" />
<FluentLabel Typo="Typography.PaneHeader">
@Dialog.Instance.Parameters.Title
</FluentLabel>
</FluentStack>
</FluentDialogHeader>
<FluentDialogBody>
<EditForm EditContext="@editContext">
<DataAnnotationsValidator />
<FluentStack Orientation="Orientation.Horizontal">
<FluentDatePicker @bind-Value="@periodFrom" Label="Von" Style="width: 170px;" />
<FluentDatePicker @bind-Value="@periodTo" Label="Bis" Style="width: 170px;" />
</FluentStack>
<FluentStack Orientation="Orientation.Horizontal">
<FluentNumberField @bind-Value="@Content.GridKwh" Label="Netzbezug (kWh)" Style="width: 170px;" />
<FluentNumberField @bind-Value="@Content.PvKwh" Label="PV-Produktion (kWh)" Style="width: 170px;" />
</FluentStack>
<FluentStack Orientation="Orientation.Horizontal">
<FluentNumberField @bind-Value="@Content.GridChf" Label="Netzbezug (CHF)" Style="width: 170px;" />
<FluentNumberField @bind-Value="@Content.PvChf" Label="PV (CHF)" Style="width: 170px;" />
</FluentStack>
<FluentStack Orientation="Orientation.Horizontal">
<FluentNumberField @bind-Value="@Content.SideCostsChf" Label="Nebenkosten (CHF)" Style="width: 170px;" />
</FluentStack>
<div>
<FluentValidationSummary />
</div>
</EditForm>
<div style="margin-top: 12px; font-size: 13px; color: #52514e;">
Total <strong>@Chf(Content.TotalChf)</strong>
</div>
<FluentButton Appearance="Appearance.Lightweight" Style="margin-top: 12px; padding: 0; font-size: 13px;" OnClick="ShowGuideAsync">
Woher kommen die Werte? (NeoVac-Abrechnung)
</FluentButton>
</FluentDialogBody>
<FluentDialogFooter>
<FluentButton Appearance="Appearance.Neutral"
OnClick="@CancelAsync">
Abbrechen
</FluentButton>
<FluentButton Appearance="Appearance.Accent"
Disabled="@(periodFrom is null || periodTo is null)"
OnClick="@SaveAsync">
Speichern
</FluentButton>
</FluentDialogFooter>
@code {
// Shown in its own dialog (see ShowGuideAsync) instead of expanding inline: this dialog has a
// fixed Height, and FluentDialogBody doesn't resize to fit growing content.
private RenderFragment GuideImage =>
@<img src="/images/electricity-bill-guide.svg"
alt="Beispiel-Abrechnung mit Markierungen, welcher Wert in welches Feld gehört"
style="width: 100%; height: auto; display: block;" />;
}

View file

@ -0,0 +1,78 @@
using System.Globalization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.FluentUI.AspNetCore.Components;
using Schaad.Accounting.Interfaces;
using Schaad.Accounting.Models;
namespace Schaad.Accounting.UI.Components.Pages.Dialogs;
public partial class ElectricityBillDialog : ComponentBase
{
private static readonly CultureInfo SwissNumbers = CreateSwissNumbers();
private EditContext editContext = null!;
// FluentDatePicker needs DateTime?; the model stores DateOnly (see ElectricityBill).
private DateTime? periodFrom;
private DateTime? periodTo;
[CascadingParameter]
public FluentDialog Dialog { get; set; } = null!;
[Parameter]
public ElectricityBill Content { get; set; } = null!;
[Inject]
private IElectricityBillRepository electricityBillRepository { get; set; } = null!;
[Inject]
private IDialogService dialogService { get; set; } = null!;
protected override void OnInitialized()
{
periodFrom = Content.PeriodFrom == default ? null : Content.PeriodFrom.ToDateTime(TimeOnly.MinValue);
periodTo = Content.PeriodTo == default ? null : Content.PeriodTo.ToDateTime(TimeOnly.MinValue);
editContext = new EditContext(Content);
}
private async Task SaveAsync()
{
if (periodFrom is null || periodTo is null)
{
return;
}
Content.PeriodFrom = DateOnly.FromDateTime(periodFrom.Value);
Content.PeriodTo = DateOnly.FromDateTime(periodTo.Value);
if (editContext.Validate())
{
await electricityBillRepository.SaveElectricityBillAsync(Content);
await Dialog.CloseAsync(Content);
}
}
private async Task CancelAsync()
{
await Dialog.CancelAsync();
}
private async Task ShowGuideAsync()
{
await dialogService.ShowDialogAsync(GuideImage, new DialogParameters()
{
Width = "680px",
Title = "Woher kommen die Werte?",
PreventDismissOnOverlayClick = true,
PreventScroll = true,
});
}
private static string Chf(decimal value) => value.ToString("#,0.00", SwissNumbers) + " CHF";
private static CultureInfo CreateSwissNumbers()
{
var culture = new CultureInfo("de-CH");
culture.NumberFormat.NumberGroupSeparator = "'";
return culture;
}
}

View file

@ -0,0 +1,58 @@
@page "/electricity"
@rendermode InteractiveServer
@using Schaad.Accounting.UI.Components.Pages.Analytics
<PageTitle>Strom</PageTitle>
<div class="electricity">
<FluentStack Orientation="Orientation.Horizontal" VerticalAlignment="VerticalAlignment.Center">
<FluentButton IconStart="@(new Icons.Regular.Size16.Add())" Appearance="Appearance.Neutral" OnClick="AddAsync">Neue Abrechnung hinzufügen</FluentButton>
</FluentStack>
@if (source.Count == 0)
{
<FluentMessageBar Intent="MessageIntent.Info" AllowDismiss="false">Noch keine Abrechnungen erfasst.</FluentMessageBar>
}
else
{
<div class="pair">
<FluentCard class="chart-card">
<div class="card-title">Verbrauch pro Halbjahr</div>
<ChartJsChart Kind="stackedBar" Data="@barData" Height="360px"
AriaLabel="Netzbezug und PV-Produktion pro Halbjahr, 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" />
</FluentCard>
</div>
<FluentCard class="chart-card">
<div class="card-title">Gesamtkosten pro Halbjahr</div>
<ChartJsChart Kind="line" Data="@costData" Height="320px"
AriaLabel="Gesamtkosten pro Halbjahr" />
</FluentCard>
}
<div class="table-scroll">
<FluentDataGrid Items="@source.AsQueryable()" RowSize="DataGridRowSize.Medium">
<PropertyColumn Title="Von" Property="@(p => p.PeriodFrom)" Format="dd.MM.yyyy" Sortable="true" IsDefaultSortColumn="true" InitialSortDirection="SortDirection.Descending" />
<PropertyColumn Title="Bis" Property="@(p => p.PeriodTo)" Format="dd.MM.yyyy" Sortable="true" />
<PropertyColumn Title="Netz kWh" Property="@(p => p.GridKwh)" Format="#,0.0" Align="Align.End" />
<PropertyColumn Title="PV kWh" Property="@(p => p.PvKwh)" Format="#,0.0" Align="Align.End" />
<PropertyColumn Title="Total kWh" Property="@(p => p.TotalKwh)" Format="#,0.0" Align="Align.End" />
<PropertyColumn Title="PV-Anteil" Property="@(p => p.PvShare)" Format="P1" Align="Align.End" />
<PropertyColumn Title="Netz CHF" Property="@(p => p.GridChf)" Format="C2" Align="Align.End" />
<PropertyColumn Title="PV CHF" Property="@(p => p.PvChf)" Format="C2" Align="Align.End" />
<PropertyColumn Title="Nebenkosten" Property="@(p => p.SideCostsChf)" Format="C2" Align="Align.End" />
<PropertyColumn Title="Total CHF" Property="@(p => p.TotalChf)" Format="C2" Align="Align.End" />
<TemplateColumn Align="Align.Center" Width="50px">
<FluentButton IconEnd="@(new Icons.Regular.Size16.Delete())" Appearance="Appearance.Neutral" title="Löschen" aria-label="Löschen" OnClick="@(() => DeleteAsync(context.Id))" />
</TemplateColumn>
<TemplateColumn Align="Align.Center" Width="50px">
<FluentButton IconEnd="@(new Icons.Regular.Size16.Edit())" Appearance="Appearance.Neutral" title="Bearbeiten" aria-label="Bearbeiten" OnClick="@(() => EditAsync(context.Id))" />
</TemplateColumn>
</FluentDataGrid>
</div>
</div>

View file

@ -0,0 +1,138 @@
using Microsoft.AspNetCore.Components;
using Microsoft.FluentUI.AspNetCore.Components;
using Schaad.Accounting.Interfaces;
using Schaad.Accounting.Models;
using Schaad.Accounting.UI.Components.Pages.Charts;
using Schaad.Accounting.UI.Components.Pages.Dialogs;
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.
/// </summary>
public partial class Electricity : ComponentBase
{
[Inject]
private IElectricityBillRepository electricityBillRepository { get; set; } = null!;
[Inject]
private IDialogService dialogService { get; set; } = null!;
[Inject]
private IToastService toastService { get; set; } = null!;
private IReadOnlyList<ElectricityBill> source = [];
private object barData = new();
private object lineData = new();
private object costData = new();
protected override async Task OnInitializedAsync()
{
await LoadAsync();
}
private async Task LoadAsync()
{
source = (await electricityBillRepository.GetElectricityBillListAsync())
.OrderBy(b => b.PeriodFrom)
.ToList();
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();
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 }
},
unit = "kWh"
};
lineData = new
{
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 }
},
unit = "CHF/kWh",
axisDecimals = 2
};
costData = new
{
labels,
series = new object[]
{
new { name = "Total", color = ChartTheme.ColorAt(2), values = halves.Select(h => h.Bill?.TotalChf).ToList(), width = 2 }
},
unit = "CHF"
};
}
private async Task AddAsync()
{
var data = new ElectricityBill();
var dialog = await dialogService.ShowDialogAsync<ElectricityBillDialog>(data, new DialogParameters()
{
Width = "560px",
Height = "460px",
Title = "Abrechnung hinzufügen",
PreventDismissOnOverlayClick = true,
PreventScroll = true,
});
var result = await dialog.Result;
if (!result.Cancelled && result.Data != null)
{
await LoadAsync();
toastService.ShowToast(ToastIntent.Success, "Abrechnung gespeichert", 3000);
}
}
private async Task EditAsync(string id)
{
var data = await electricityBillRepository.GetElectricityBillAsync(id);
var dialog = await dialogService.ShowDialogAsync<ElectricityBillDialog>(data, new DialogParameters()
{
Width = "560px",
Height = "460px",
Title = "Abrechnung bearbeiten",
PreventDismissOnOverlayClick = true,
PreventScroll = true,
});
var result = await dialog.Result;
if (!result.Cancelled && result.Data != null)
{
await LoadAsync();
toastService.ShowToast(ToastIntent.Success, "Abrechnung gespeichert", 3000);
}
}
private async Task DeleteAsync(string id)
{
var bill = source.First(b => b.Id == id);
var dialog = await dialogService.ShowConfirmationAsync($"Abrechnung {FullLabel(bill)} wirklich löschen?", "Ja", "Nein", "Abrechnung löschen");
var result = await dialog.Result;
if (!result.Cancelled)
{
await electricityBillRepository.DeleteElectricityBillAsync(id);
await LoadAsync();
toastService.ShowToast(ToastIntent.Success, "Abrechnung gelöscht", 3000);
}
}
private static string FullLabel(ElectricityBill bill) => $"{bill.PeriodFrom:dd.MM.yyyy} – {bill.PeriodTo:dd.MM.yyyy}";
}

View file

@ -0,0 +1,32 @@
.electricity {
display: flex;
flex-direction: column;
gap: 16px;
}
.table-scroll {
overflow-x: auto;
}
.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);
}
}
::deep .chart-card {
padding: 16px;
min-width: 0;
}
.card-title {
font-weight: 600;
font-size: 15px;
margin-bottom: 12px;
}

View file

@ -21,6 +21,7 @@ namespace Schaad.Accounting.UI
services.AddScoped<IBankTransactionRepository, BankTransactionRepository>(); services.AddScoped<IBankTransactionRepository, BankTransactionRepository>();
services.AddScoped<IBookingRuleRepository, BookingRuleRepository>(); services.AddScoped<IBookingRuleRepository, BookingRuleRepository>();
services.AddScoped<IBookingTextRepository, BookingTextRepository>(); services.AddScoped<IBookingTextRepository, BookingTextRepository>();
services.AddScoped<IElectricityBillRepository, ElectricityBillRepository>();
services.AddScoped<ISplitPredefinitionRepository, SplitPredefinitionRepository>(); services.AddScoped<ISplitPredefinitionRepository, SplitPredefinitionRepository>();
services.AddScoped<ISubclassRepository, SubclassRepository>(); services.AddScoped<ISubclassRepository, SubclassRepository>();
services.AddScoped<ITransactionRepository, TransactionRepository>(); services.AddScoped<ITransactionRepository, TransactionRepository>();

View file

@ -6,7 +6,8 @@
} }
}, },
"Settings": { "Settings": {
"DataPath": "D:\\Developer\\AccountingData\\", "DataPath_": "/home/schaad/Documents/Developer/Data/Accounting/",
"DataPath": "D:\\Developer\\AccountingData",
"FixerIoApiKey": "ee23142f1120bb1223b0e76f98abfa97", "FixerIoApiKey": "ee23142f1120bb1223b0e76f98abfa97",
"DefaultMandator": "Claudio Schaad" "DefaultMandator": "Claudio Schaad"
} }

View file

@ -0,0 +1,52 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 532" role="img" aria-labelledby="guide-title">
<title id="guide-title">Beispiel-Abrechnung: Wo stehen die Werte?</title>
<rect x="8" y="8" width="624" height="516" rx="10" fill="#fcfcfb" stroke="#e1e0d9" />
<text x="24" y="38" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="16" font-weight="bold" fill="#0b0b0b">Beispiel: Wo stehen die Werte auf der Abrechnung?</text>
<text x="24" y="58" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12" fill="#52514e">Platzhalterwerte – der Aufbau entspricht dem Abschnitt „Ihre Abrechnung vom …“ der NeoVac-Abrechnung.</text>
<line x1="24" y1="72" x2="616" y2="72" stroke="#e1e0d9" stroke-width="1" />
<!-- Von / Bis -->
<text x="24" y="114" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13" fill="#0b0b0b">Abrechnungsperiode</text>
<rect x="380" y="94" width="232" height="22" rx="4" fill="none" stroke="#e87ba4" stroke-width="2" />
<text x="604" y="110" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13" font-weight="bold" fill="#0b0b0b">01.07.2025 – 30.06.2026</text>
<text x="604" y="128" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="11" font-weight="bold" fill="#e87ba4">→ Von / Bis</text>
<!-- Netzbezug kWh -->
<text x="24" y="180" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13" fill="#0b0b0b">Netzstrom – Ihr Anteil</text>
<rect x="380" y="160" width="232" height="22" rx="4" fill="none" stroke="#2a78d6" stroke-width="2" />
<text x="604" y="176" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13" font-weight="bold" fill="#0b0b0b">1'200.000 kWh</text>
<text x="604" y="194" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="11" font-weight="bold" fill="#2a78d6">→ Netzbezug (kWh)</text>
<!-- Netzbezug CHF -->
<text x="24" y="246" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13" fill="#0b0b0b">Netzstrom – Betrag (CHF)</text>
<rect x="380" y="226" width="232" height="22" rx="4" fill="none" stroke="#2a78d6" stroke-width="2" />
<text x="604" y="242" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13" font-weight="bold" fill="#0b0b0b">350.00</text>
<text x="604" y="260" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="11" font-weight="bold" fill="#2a78d6">→ Netzbezug (CHF)</text>
<!-- PV kWh -->
<text x="24" y="312" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13" fill="#0b0b0b">ZEV Photovoltaikstrom – Ihr Anteil</text>
<rect x="380" y="292" width="232" height="22" rx="4" fill="none" stroke="#eb6834" stroke-width="2" />
<text x="604" y="308" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13" font-weight="bold" fill="#0b0b0b">900.000 kWh</text>
<text x="604" y="326" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="11" font-weight="bold" fill="#eb6834">→ PV-Produktion (kWh)</text>
<!-- PV CHF -->
<text x="24" y="378" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13" fill="#0b0b0b">ZEV Photovoltaikstrom – Betrag (CHF)</text>
<rect x="380" y="358" width="232" height="22" rx="4" fill="none" stroke="#eb6834" stroke-width="2" />
<text x="604" y="374" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13" font-weight="bold" fill="#0b0b0b">250.00</text>
<text x="604" y="392" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="11" font-weight="bold" fill="#eb6834">→ PV (CHF)</text>
<!-- Nebenkosten CHF -->
<text x="24" y="444" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13" fill="#0b0b0b">ZEV Stromnebenkosten – Betrag (CHF)</text>
<rect x="380" y="424" width="232" height="22" rx="4" fill="none" stroke="#1baf7a" stroke-width="2" />
<text x="604" y="440" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13" font-weight="bold" fill="#0b0b0b">80.00</text>
<text x="604" y="458" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="11" font-weight="bold" fill="#1baf7a">→ Nebenkosten (CHF)</text>
<line x1="24" y1="480" x2="616" y2="480" stroke="#e1e0d9" stroke-width="1" />
<!-- Computed, informational only -->
<text x="24" y="506" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12" fill="#898781">Stromkosten (wird berechnet)</text>
<text x="604" y="506" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12" fill="#898781">680.00</text>
</svg>

After

Width:  |  Height:  |  Size: 4.8 KiB

View file

@ -36,9 +36,18 @@ const theme = {
// de-CH uses a typographic apostrophe; the rest of the app (Formatting.cs) uses a plain one. // 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 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 formatChf = value => amount.format(value).replace(/’/g, "'");
const formatAxis = value => axisAmount.format(value).replace(/’/g, "'");
// Axis ticks default to whole numbers (CHF amounts in the hundreds/thousands); series with small
// values (e.g. CHF/kWh, well under 1) pass data.axisDecimals to avoid every tick rounding to "0".
const axisAmountFormatters = new Map();
function axisAmount(decimals) {
if (!axisAmountFormatters.has(decimals)) {
axisAmountFormatters.set(decimals, new Intl.NumberFormat('de-CH', { minimumFractionDigits: decimals, maximumFractionDigits: decimals }));
}
return axisAmountFormatters.get(decimals);
}
const formatAxis = (value, decimals = 0) => axisAmount(decimals).format(value).replace(/’/g, "'");
// Treemap tile helpers: level 0 tiles are parents (their group value is the parent id); level 1 // 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. // tiles keep the original tree items, which carry the parent id.
@ -68,12 +77,14 @@ const legend = {
labels: { usePointStyle: true, pointStyle: 'rectRounded', boxWidth: 10, color: theme.muted, font: { size: 12 } } labels: { usePointStyle: true, pointStyle: 'rectRounded', boxWidth: 10, color: theme.muted, font: { size: 12 } }
}; };
const amountAxis = { // unit/decimals default to CHF/0, so existing callers that don't pass data.unit/axisDecimals
// keep their current axis.
const amountAxis = (unit = 'CHF', decimals = 0) => ({
grid: { color: theme.grid }, grid: { color: theme.grid },
border: { display: false }, border: { display: false },
title: { display: true, text: 'CHF', color: theme.muted }, title: { display: true, text: unit, color: theme.muted },
ticks: { color: theme.muted, callback: value => formatAxis(value) } ticks: { color: theme.muted, callback: value => formatAxis(value, decimals) }
}; });
const categoryAxis = { grid: { display: false }, ticks: { color: theme.muted } }; const categoryAxis = { grid: { display: false }, ticks: { color: theme.muted } };
@ -110,7 +121,7 @@ const kinds = {
order: -1 order: -1
}] : [])] }] : [])]
}), }),
options: () => ({ options: state => ({
interaction: { mode: 'index', intersect: false }, interaction: { mode: 'index', intersect: false },
plugins: { plugins: {
legend, legend,
@ -119,17 +130,17 @@ const kinds = {
filter: item => item.parsed.y !== 0, filter: item => item.parsed.y !== 0,
itemSort: (a, b) => b.parsed.y - a.parsed.y, itemSort: (a, b) => b.parsed.y - a.parsed.y,
callbacks: { callbacks: {
label: item => ` ${item.dataset.label}: ${formatChf(item.parsed.y)} CHF`, label: item => ` ${item.dataset.label}: ${formatChf(item.parsed.y)} ${state().unit ?? 'CHF'}`,
footer: items => { footer: items => {
const bars = items.filter(i => i.dataset.type !== 'line'); const bars = items.filter(i => i.dataset.type !== 'line');
return bars.length === items.length return bars.length === items.length
? `Total: ${formatChf(bars.reduce((sum, i) => sum + i.parsed.y, 0))} CHF` ? `Total: ${formatChf(bars.reduce((sum, i) => sum + i.parsed.y, 0))} ${state().unit ?? 'CHF'}`
: ''; : '';
} }
} }
} }
}, },
scales: { x: { ...categoryAxis, stacked: true }, y: { ...amountAxis, stacked: true } } scales: { x: { ...categoryAxis, stacked: true }, y: { ...amountAxis(state().unit ?? 'CHF', state().axisDecimals ?? 0), stacked: true } }
}), }),
hit: (chart, event) => { hit: (chart, event) => {
const hit = chart.getElementsAtEventForMode(event, 'nearest', { intersect: true }, false)[0]; const hit = chart.getElementsAtEventForMode(event, 'nearest', { intersect: true }, false)[0];
@ -154,7 +165,7 @@ const kinds = {
spanGaps: false spanGaps: false
})) }))
}), }),
options: () => ({ options: state => ({
interaction: { mode: 'index', intersect: false }, interaction: { mode: 'index', intersect: false },
plugins: { plugins: {
legend: { ...legend, labels: { ...legend.labels, pointStyle: 'line' } }, legend: { ...legend, labels: { ...legend.labels, pointStyle: 'line' } },
@ -162,10 +173,10 @@ const kinds = {
...tooltip, ...tooltip,
filter: item => item.parsed.y !== null, filter: item => item.parsed.y !== null,
itemSort: (a, b) => b.parsed.y - a.parsed.y, itemSort: (a, b) => b.parsed.y - a.parsed.y,
callbacks: { label: item => ` ${item.dataset.label}: ${formatChf(item.parsed.y)} CHF` } callbacks: { label: item => ` ${item.dataset.label}: ${formatChf(item.parsed.y)} ${state().unit ?? 'CHF'}` }
} }
}, },
scales: { x: categoryAxis, y: amountAxis } scales: { x: categoryAxis, y: amountAxis(state().unit ?? 'CHF', state().axisDecimals ?? 0) }
}), }),
hit: () => null hit: () => null
}, },