Add "Strom" page for the yearly NeoVac electricity bill

A new page (/electricity) to record one electricity bill per billing
period (1 July-30 June) with a grid, add/edit dialog, and two Chart.js
charts (kWh split grid/PV per period, CHF/kWh as a line).

- ElectricityBill (Common): Grid/PV kWh and CHF, side costs, advance
  payment; computed TotalKwh, PvShare, TotalChf, Balance, ChfPerKwh.
- Stored once per mandator at {DataPath}/{mandator}/electricity.json
  instead of per year, since the billing period doesn't align with
  calendar years (new ISettingsService.GetMandatorPath(),
  BaseRepository gets a directory-aware SaveAsync overload).
- electricity.json is also editable through the JSON editor
  (RawDataRepository).
- charts.js: stackedBar/line charts can now show a unit other than
  CHF (defaults to CHF, so the Analyse page is unaffected).
- The add/edit dialog links to an annotated example (SVG, placeholder
  data) showing which value on the real NeoVac bill goes into which
  field; opens in its own dialog since the main dialog has a fixed
  height.
- Tests for the computed properties and the new repositories.

Also bumps the TargetFramework to net10.0 and updates the local
DataPath in appsettings.Development.json.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Claudio Schaad 2026-10-25 20:30:40 +01:00
parent c9a25481f2
commit 7d7bd6073c
23 changed files with 826 additions and 20 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}/electricity.json electricity bills (not per year, see below)
{DataPath}/uploads/{mandator}/{year}/ imported bank statements (+ creditCard/)
{DataPath}/backup/{mandator}/{year}/ backup zips
```
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
- **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
- **ChartService** — produces data for the Plotly booking-text charts on the transactions page
- **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`
- **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, advance payment; `TotalKwh`, `PvShare`, `TotalChf`, `Balance`, `ChfPerKwh` are computed); two Chart.js charts via `ChartJsChart` (stacked kWh per period, CHF/kWh line)
### UI structure

View file

@ -1,5 +1,5 @@
<Project>
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
</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();
/// <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();
}
}

View file

@ -0,0 +1,67 @@
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; }
[Display(Name = "Akonto")]
public decimal AdvanceChf { 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, before the advance payment.</summary>
[JsonIgnore]
[Display(Name = "Total")]
public decimal TotalChf => GridChf + PvChf + SideCostsChf;
/// <summary>What is still owed (positive) or was overpaid (negative) after the advance.</summary>
[JsonIgnore]
[Display(Name = "Saldo")]
public decimal Balance => TotalChf - AdvanceChf;
/// <summary>Average price per kWh over the whole period.</summary>
[JsonIgnore]
[Display(Name = "CHF/kWh")]
public decimal ChfPerKwh => TotalKwh == 0 ? 0 : TotalChf / TotalKwh;
}
}

View file

@ -78,9 +78,16 @@ namespace Schaad.Accounting.Repositories
/// renames it, so a crash mid-write leaves the previous file intact. Invalidates
/// the corresponding cache entry.
/// </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 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 TRANSACTIONS = "Transactions.json";
private const string ELECTRICITY = "electricity.json";
private const int MaxErrors = 20;
// 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",
"BookingTexts.json",
"SplitPredefinitions.json",
"SubClasses.json"
"SubClasses.json",
ELECTRICITY
];
public async Task<RawDataFile> LoadAsync(string fileName)
@ -66,6 +68,7 @@ namespace Schaad.Accounting.Repositories
"BookingTexts.json" => SaveAsync<BookingText>(fileName, text, loadedHash),
"SplitPredefinitions.json" => SaveAsync<SplitPredefinition>(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))
};
@ -106,7 +109,7 @@ namespace Schaad.Accounting.Repositories
}
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);
return new RawDataSaveResult([], await LoadAsync(fileName), backupPath);
@ -233,9 +236,14 @@ namespace Schaad.Accounting.Repositories
{
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 Describe(JsonException ex)

View file

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

View file

@ -0,0 +1,94 @@
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,
AdvanceChf = 1212.00m
};
await sut.SaveElectricityBillAsync(bill);
var stored = (await sut.GetElectricityBillListAsync()).Single();
stored.Id.ShouldNotBeNullOrEmpty();
stored.Balance.ShouldBe(475.95m);
}
[Fact]
public async Task UpdateInPlaceWhenSavingBillWithExistingId()
{
await sut.SaveElectricityBillAsync(new ElectricityBill { PeriodFrom = new DateOnly(2023, 7, 1), PeriodTo = new DateOnly(2024, 6, 30), AdvanceChf = 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), AdvanceChf = 1300m });
var bills = await sut.GetElectricityBillListAsync();
bills.Count.ShouldBe(1);
bills[0].AdvanceChf.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,72 @@
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 CalculateBalanceWhenAdvanceIsSubtractedFromTotal()
{
var bill = new ElectricityBill
{
GridKwh = 3419.432m,
PvKwh = 1936.328m,
GridChf = 1009.55m,
PvChf = 544.10m,
SideCostsChf = 134.30m,
AdvanceChf = 1212.00m
};
bill.TotalChf.ShouldBe(1687.95m);
bill.Balance.ShouldBe(475.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);
}
}

View file

@ -24,6 +24,7 @@ public class RawDataRepositoryTestShould : IDisposable
private readonly string dataPath;
private readonly string dbDir;
private readonly string mandatorDir;
private readonly RepositoryCache cache = new();
private readonly ISettingsService settingsService;
private readonly RawDataRepository sut;
@ -31,7 +32,8 @@ public class RawDataRepositoryTestShould : IDisposable
public RawDataRepositoryTestShould()
{
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);
File.WriteAllText(Path.Combine(dbDir, "Accounts.json"), Accounts);
File.WriteAllText(Path.Combine(dbDir, "Transactions.json"), Transactions);
@ -39,6 +41,7 @@ public class RawDataRepositoryTestShould : IDisposable
settingsService = Substitute.For<ISettingsService>();
settingsService.GetDbPath().Returns(dbDir);
settingsService.GetLastYearDbPath().Returns(Path.Combine(dataPath, "no-such-dir"));
settingsService.GetMandatorPath().Returns(mandatorDir);
settingsService.GetSettings().Returns(new SettingsDataset { DataPath = dataPath });
settingsService.GetMandator().Returns("Mandator");
settingsService.GetYear().Returns(2026);
@ -169,6 +172,24 @@ public class RawDataRepositoryTestShould : IDisposable
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]
public async Task RejectUnknownFileNameWhenLoading()
{

View file

@ -33,6 +33,12 @@ public class SettingsServiceTestShould : IDisposable
sut.GetLastYearDbPath().ShouldBe(Path.Combine(dataPath, "Mandator", "2024"));
}
[Fact]
public void ReturnMandatorFolderWithoutYearWhenGettingMandatorPath()
{
sut.GetMandatorPath().ShouldBe(Path.Combine(dataPath, "Mandator"));
}
[Fact]
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="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="electricity" Icon="@(new Size20.Flash())" IconColor="Color.Accent">Strom</FluentNavLink>
<FluentNavGroup Title="Stammdaten" Icon="@(new Size32.BookDatabase())">
<FluentNavLink Href="bookingrules" Icon="@(new Size20.Check())" IconColor="Color.Accent">Buchungsregeln</FluentNavLink>
<FluentNavLink Href="bookingtexts" Icon="@(new Size32.Text())" IconColor="Color.Accent">Buchungstexte</FluentNavLink>

View file

@ -0,0 +1,66 @@
@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;" />
<FluentNumberField @bind-Value="@Content.AdvanceChf" Label="Akonto (CHF)" Style="width: 170px;" />
</FluentStack>
<div>
<FluentValidationSummary />
</div>
</EditForm>
<div style="margin-top: 12px; font-size: 13px; color: #52514e;">
Total @Chf(Content.TotalChf), Akonto @Chf(Content.AdvanceChf) → Saldo <strong>@Chf(Content.Balance)</strong>
(@(Content.Balance >= 0 ? "Nachzahlung" : "Gutschrift"))
</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,57 @@
@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>
<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" />
<PropertyColumn Title="Akonto" Property="@(p => p.AdvanceChf)" Format="C2" Align="Align.End" />
<TemplateColumn Title="Saldo" Align="Align.End">
<span class="@(context.Balance >= 0 ? "due" : "credit")">@Chf(context.Balance)</span>
</TemplateColumn>
<PropertyColumn Title="CHF/kWh" Property="@(p => p.ChfPerKwh)" Format="0.000" 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>
@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 Periode</div>
<ChartJsChart Kind="stackedBar" Data="@barData" Height="360px"
AriaLabel="Netzbezug und PV-Produktion pro Abrechnungsperiode, 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 über die Abrechnungsperioden" />
</FluentCard>
</div>
}
</div>

View file

@ -0,0 +1,138 @@
using System.Globalization;
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 two charts:
/// consumption split grid/PV per period, and the resulting price per kWh.
/// </summary>
public partial class Electricity : ComponentBase
{
private static readonly CultureInfo SwissNumbers = CreateSwissNumbers();
[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();
protected override async Task OnInitializedAsync()
{
await LoadAsync();
}
private async Task LoadAsync()
{
source = (await electricityBillRepository.GetElectricityBillListAsync())
.OrderBy(b => b.PeriodFrom)
.ToList();
BuildCharts();
}
private void BuildCharts()
{
var labels = source.Select(ChartLabel).ToList();
barData = new
{
labels,
series = new object[]
{
new { name = "Netz", color = ChartTheme.ColorAt(0), values = source.Select(b => b.GridKwh).ToList(), clickable = false },
new { name = "PV", color = ChartTheme.ColorAt(1), values = source.Select(b => b.PvKwh).ToList(), clickable = false }
},
unit = "kWh"
};
lineData = new
{
labels,
series = new object[]
{
new { name = "CHF/kWh", color = ChartTheme.ColorAt(0), values = source.Select(b => b.ChfPerKwh).ToList(), width = 2 }
},
unit = "CHF/kWh"
};
}
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);
}
}
// Short label for the chart axis, e.g. "23/24".
private static string ChartLabel(ElectricityBill bill) => $"{bill.PeriodFrom:yy}/{bill.PeriodTo:yy}";
private static string FullLabel(ElectricityBill bill) => $"{bill.PeriodFrom:dd.MM.yyyy} – {bill.PeriodTo:dd.MM.yyyy}";
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,40 @@
.electricity {
display: flex;
flex-direction: column;
gap: 16px;
}
.table-scroll {
overflow-x: auto;
}
.due {
color: #c50f1f;
}
.credit {
color: #107c10;
}
.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<IBookingRuleRepository, BookingRuleRepository>();
services.AddScoped<IBookingTextRepository, BookingTextRepository>();
services.AddScoped<IElectricityBillRepository, ElectricityBillRepository>();
services.AddScoped<ISplitPredefinitionRepository, SplitPredefinitionRepository>();
services.AddScoped<ISubclassRepository, SubclassRepository>();
services.AddScoped<ITransactionRepository, TransactionRepository>();

View file

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

View file

@ -0,0 +1,61 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 620" 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="604" 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>
<!-- Akonto CHF -->
<text x="24" y="510" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13" fill="#0b0b0b">Akontozahlungen Strom</text>
<rect x="380" y="490" width="232" height="22" rx="4" fill="none" stroke="#eda100" stroke-width="2" />
<text x="604" y="506" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="13" font-weight="bold" fill="#0b0b0b">-600.00</text>
<text x="604" y="524" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="11" font-weight="bold" fill="#eda100">→ Akonto (CHF), ohne Minus eingeben</text>
<line x1="24" y1="546" x2="616" y2="546" stroke="#e1e0d9" stroke-width="1" />
<!-- Computed, informational only -->
<text x="24" y="572" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12" fill="#898781">Stromkosten (wird berechnet)</text>
<text x="604" y="572" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12" fill="#898781">680.00</text>
<text x="24" y="594" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12" fill="#898781">Saldo (wird berechnet)</text>
<text x="604" y="594" text-anchor="end" font-family="'Helvetica Neue', Helvetica, Arial, sans-serif" font-size="12" fill="#898781">80.00</text>
</svg>

After

Width:  |  Height:  |  Size: 5.7 KiB

View file

@ -68,12 +68,13 @@ const legend = {
labels: { usePointStyle: true, pointStyle: 'rectRounded', boxWidth: 10, color: theme.muted, font: { size: 12 } }
};
const amountAxis = {
// unit defaults to CHF, so existing callers that don't pass data.unit keep their current axis.
const amountAxis = (unit = 'CHF') => ({
grid: { color: theme.grid },
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) }
};
});
const categoryAxis = { grid: { display: false }, ticks: { color: theme.muted } };
@ -110,7 +111,7 @@ const kinds = {
order: -1
}] : [])]
}),
options: () => ({
options: state => ({
interaction: { mode: 'index', intersect: false },
plugins: {
legend,
@ -119,17 +120,17 @@ const kinds = {
filter: item => item.parsed.y !== 0,
itemSort: (a, b) => b.parsed.y - a.parsed.y,
callbacks: {
label: item => ` ${item.dataset.label}: ${formatChf(item.parsed.y)} CHF`,
label: item => ` ${item.dataset.label}: ${formatChf(item.parsed.y)} ${state().unit ?? 'CHF'}`,
footer: items => {
const bars = items.filter(i => i.dataset.type !== 'line');
return bars.length === items.length
? `Total: ${formatChf(bars.reduce((sum, i) => sum + i.parsed.y, 0))} CHF`
? `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'), stacked: true } }
}),
hit: (chart, event) => {
const hit = chart.getElementsAtEventForMode(event, 'nearest', { intersect: true }, false)[0];
@ -154,7 +155,7 @@ const kinds = {
spanGaps: false
}))
}),
options: () => ({
options: state => ({
interaction: { mode: 'index', intersect: false },
plugins: {
legend: { ...legend, labels: { ...legend.labels, pointStyle: 'line' } },
@ -162,10 +163,10 @@ const kinds = {
...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` }
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') }
}),
hit: () => null
},