diff --git a/CLAUDE.md b/CLAUDE.md index 5349be2..c25b8da 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 diff --git a/Directory.Build.props b/Directory.Build.props index 67b2324..020f2b0 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,5 +1,5 @@ - net9.0 + net10.0 diff --git a/Schaad.Accounting.Common/Interfaces/IElectricityBillRepository.cs b/Schaad.Accounting.Common/Interfaces/IElectricityBillRepository.cs new file mode 100644 index 0000000..1b54b39 --- /dev/null +++ b/Schaad.Accounting.Common/Interfaces/IElectricityBillRepository.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Schaad.Accounting.Models; + +namespace Schaad.Accounting.Interfaces +{ + public interface IElectricityBillRepository + { + Task> GetElectricityBillListAsync(); + + Task SaveElectricityBillAsync(ElectricityBill bill); + + Task GetElectricityBillAsync(string id); + + Task DeleteElectricityBillAsync(string id); + } +} diff --git a/Schaad.Accounting.Common/Interfaces/ISettingsService.cs b/Schaad.Accounting.Common/Interfaces/ISettingsService.cs index 4e6c279..ec1f6d8 100644 --- a/Schaad.Accounting.Common/Interfaces/ISettingsService.cs +++ b/Schaad.Accounting.Common/Interfaces/ISettingsService.cs @@ -26,6 +26,12 @@ namespace Schaad.Accounting.Interfaces string GetLastYearDbPath(); + /// + /// 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). + /// + string GetMandatorPath(); + SettingsDataset GetSettings(); } } \ No newline at end of file diff --git a/Schaad.Accounting.Common/Models/ElectricityBill.cs b/Schaad.Accounting.Common/Models/ElectricityBill.cs new file mode 100644 index 0000000..6311756 --- /dev/null +++ b/Schaad.Accounting.Common/Models/ElectricityBill.cs @@ -0,0 +1,67 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.Text.Json.Serialization; + +namespace Schaad.Accounting.Models +{ + /// + /// 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). + /// + 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; } + + /// Grid draw plus own PV consumption, in kWh. + [JsonIgnore] + [Display(Name = "Total")] + public decimal TotalKwh => GridKwh + PvKwh; + + /// Share of the consumption covered by PV, 0..1. + [JsonIgnore] + [Display(Name = "PV-Anteil")] + public decimal PvShare => TotalKwh == 0 ? 0 : PvKwh / TotalKwh; + + /// Grid, PV and side costs added up, before the advance payment. + [JsonIgnore] + [Display(Name = "Total")] + public decimal TotalChf => GridChf + PvChf + SideCostsChf; + + /// What is still owed (positive) or was overpaid (negative) after the advance. + [JsonIgnore] + [Display(Name = "Saldo")] + public decimal Balance => TotalChf - AdvanceChf; + + /// Average price per kWh over the whole period. + [JsonIgnore] + [Display(Name = "CHF/kWh")] + public decimal ChfPerKwh => TotalKwh == 0 ? 0 : TotalChf / TotalKwh; + } +} diff --git a/Schaad.Accounting.Db/Repositories/BaseRepository.cs b/Schaad.Accounting.Db/Repositories/BaseRepository.cs index 019424a..843788b 100644 --- a/Schaad.Accounting.Db/Repositories/BaseRepository.cs +++ b/Schaad.Accounting.Db/Repositories/BaseRepository.cs @@ -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. /// - protected async Task SaveAsync(T obj, string fileName) + protected Task SaveAsync(T obj, string fileName) + => SaveAsync(obj, settingsService.GetDbPath(), fileName); + + /// + /// Same as for a file in any data directory (e.g. + /// the mandator's folder instead of a year below it). + /// + protected async Task SaveAsync(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); diff --git a/Schaad.Accounting.Db/Repositories/ElectricityBillRepository.cs b/Schaad.Accounting.Db/Repositories/ElectricityBillRepository.cs new file mode 100644 index 0000000..620d43a --- /dev/null +++ b/Schaad.Accounting.Db/Repositories/ElectricityBillRepository.cs @@ -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 +{ + /// + /// 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. + /// + public class ElectricityBillRepository : BaseRepository, IElectricityBillRepository + { + private const string ELECTRICITY = "electricity.json"; + + public ElectricityBillRepository(ISettingsService settingsService, RepositoryCache cache, ILogger logger) + : base(settingsService, cache, logger) + { + } + + public Task> GetElectricityBillListAsync() + => LoadListAsync(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 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); + } + } +} diff --git a/Schaad.Accounting.Db/Repositories/RawDataRepository.cs b/Schaad.Accounting.Db/Repositories/RawDataRepository.cs index 1cf4713..fa85658 100644 --- a/Schaad.Accounting.Db/Repositories/RawDataRepository.cs +++ b/Schaad.Accounting.Db/Repositories/RawDataRepository.cs @@ -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 LoadAsync(string fileName) @@ -66,6 +68,7 @@ namespace Schaad.Accounting.Repositories "BookingTexts.json" => SaveAsync(fileName, text, loadedHash), "SplitPredefinitions.json" => SaveAsync(fileName, text, loadedHash), "SubClasses.json" => SaveAsync(fileName, text, loadedHash), + ELECTRICITY => SaveAsync(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) diff --git a/Schaad.Accounting.Services/SettingsService.cs b/Schaad.Accounting.Services/SettingsService.cs index 82f3a3e..2157691 100644 --- a/Schaad.Accounting.Services/SettingsService.cs +++ b/Schaad.Accounting.Services/SettingsService.cs @@ -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; diff --git a/Schaad.Accounting.Tests/ElectricityBillRepositoryTestShould.cs b/Schaad.Accounting.Tests/ElectricityBillRepositoryTestShould.cs new file mode 100644 index 0000000..3b2e687 --- /dev/null +++ b/Schaad.Accounting.Tests/ElectricityBillRepositoryTestShould.cs @@ -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(); + settingsService.GetMandatorPath().Returns(mandatorDir); + + sut = new ElectricityBillRepository(settingsService, new RepositoryCache(), NullLogger.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(); + } +} diff --git a/Schaad.Accounting.Tests/ElectricityBillTestShould.cs b/Schaad.Accounting.Tests/ElectricityBillTestShould.cs new file mode 100644 index 0000000..b335ea9 --- /dev/null +++ b/Schaad.Accounting.Tests/ElectricityBillTestShould.cs @@ -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); + } +} diff --git a/Schaad.Accounting.Tests/RawDataRepositoryTestShould.cs b/Schaad.Accounting.Tests/RawDataRepositoryTestShould.cs index 2e917ac..6df8a7f 100644 --- a/Schaad.Accounting.Tests/RawDataRepositoryTestShould.cs +++ b/Schaad.Accounting.Tests/RawDataRepositoryTestShould.cs @@ -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(); 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() { diff --git a/Schaad.Accounting.Tests/SettingsServiceTestShould.cs b/Schaad.Accounting.Tests/SettingsServiceTestShould.cs index 568e348..f4fc335 100644 --- a/Schaad.Accounting.Tests/SettingsServiceTestShould.cs +++ b/Schaad.Accounting.Tests/SettingsServiceTestShould.cs @@ -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() { diff --git a/Schaad.Accounting.UI/Components/Layout/NavMenu.razor b/Schaad.Accounting.UI/Components/Layout/NavMenu.razor index 7bda4bb..6696f58 100644 --- a/Schaad.Accounting.UI/Components/Layout/NavMenu.razor +++ b/Schaad.Accounting.UI/Components/Layout/NavMenu.razor @@ -9,6 +9,7 @@ Home Transaktionen Bank Transaktionen + Strom Buchungsregeln Buchungstexte diff --git a/Schaad.Accounting.UI/Components/Pages/Dialogs/ElectricityBillDialog.razor b/Schaad.Accounting.UI/Components/Pages/Dialogs/ElectricityBillDialog.razor new file mode 100644 index 0000000..20dbb4d --- /dev/null +++ b/Schaad.Accounting.UI/Components/Pages/Dialogs/ElectricityBillDialog.razor @@ -0,0 +1,66 @@ +@implements IDialogContentComponent +@rendermode InteractiveServer + + + + + + @Dialog.Instance.Parameters.Title + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ +
+ Total @Chf(Content.TotalChf), Akonto @Chf(Content.AdvanceChf) → Saldo @Chf(Content.Balance) + (@(Content.Balance >= 0 ? "Nachzahlung" : "Gutschrift")) +
+ + + Woher kommen die Werte? (NeoVac-Abrechnung) + +
+ + + + Abbrechen + + + Speichern + + + +@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 => + @Beispiel-Abrechnung mit Markierungen, welcher Wert in welches Feld gehört; +} diff --git a/Schaad.Accounting.UI/Components/Pages/Dialogs/ElectricityBillDialog.razor.cs b/Schaad.Accounting.UI/Components/Pages/Dialogs/ElectricityBillDialog.razor.cs new file mode 100644 index 0000000..6ec5410 --- /dev/null +++ b/Schaad.Accounting.UI/Components/Pages/Dialogs/ElectricityBillDialog.razor.cs @@ -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; + } +} diff --git a/Schaad.Accounting.UI/Components/Pages/Electricity.razor b/Schaad.Accounting.UI/Components/Pages/Electricity.razor new file mode 100644 index 0000000..3f49484 --- /dev/null +++ b/Schaad.Accounting.UI/Components/Pages/Electricity.razor @@ -0,0 +1,57 @@ +@page "/electricity" +@rendermode InteractiveServer +@using Schaad.Accounting.UI.Components.Pages.Analytics + +Strom + +
+ + Neue Abrechnung hinzufügen + + +
+ + + + + + + + + + + + + + @Chf(context.Balance) + + + + + + + + + +
+ + @if (source.Count == 0) + { + Noch keine Abrechnungen erfasst. + } + else + { +
+ +
Verbrauch pro Periode
+ +
+ +
Preis pro kWh
+ +
+
+ } +
diff --git a/Schaad.Accounting.UI/Components/Pages/Electricity.razor.cs b/Schaad.Accounting.UI/Components/Pages/Electricity.razor.cs new file mode 100644 index 0000000..479ff26 --- /dev/null +++ b/Schaad.Accounting.UI/Components/Pages/Electricity.razor.cs @@ -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; + +/// +/// 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 +/// ). Grid for entering/editing, plus two charts: +/// consumption split grid/PV per period, and the resulting price per kWh. +/// +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 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(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(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; + } +} diff --git a/Schaad.Accounting.UI/Components/Pages/Electricity.razor.css b/Schaad.Accounting.UI/Components/Pages/Electricity.razor.css new file mode 100644 index 0000000..3b2b4a5 --- /dev/null +++ b/Schaad.Accounting.UI/Components/Pages/Electricity.razor.css @@ -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; +} diff --git a/Schaad.Accounting.UI/Extensions.cs b/Schaad.Accounting.UI/Extensions.cs index 16cc13d..697e699 100644 --- a/Schaad.Accounting.UI/Extensions.cs +++ b/Schaad.Accounting.UI/Extensions.cs @@ -21,6 +21,7 @@ namespace Schaad.Accounting.UI services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/Schaad.Accounting.UI/appsettings.Development.json b/Schaad.Accounting.UI/appsettings.Development.json index c513c03..5237f59 100644 --- a/Schaad.Accounting.UI/appsettings.Development.json +++ b/Schaad.Accounting.UI/appsettings.Development.json @@ -6,8 +6,8 @@ } }, "Settings": { - "DataPath": "D:\\Developer\\AccountingData\\", + "DataPath": "/home/schaad/Documents/Developer/Data/Accounting/", "FixerIoApiKey": "ee23142f1120bb1223b0e76f98abfa97", "DefaultMandator": "Claudio Schaad" } -} +} \ No newline at end of file diff --git a/Schaad.Accounting.UI/wwwroot/images/electricity-bill-guide.svg b/Schaad.Accounting.UI/wwwroot/images/electricity-bill-guide.svg new file mode 100644 index 0000000..1e3c619 --- /dev/null +++ b/Schaad.Accounting.UI/wwwroot/images/electricity-bill-guide.svg @@ -0,0 +1,61 @@ + + Beispiel-Abrechnung: Wo stehen die Werte? + + + + Beispiel: Wo stehen die Werte auf der Abrechnung? + Platzhalterwerte – der Aufbau entspricht dem Abschnitt „Ihre Abrechnung vom …“ der NeoVac-Abrechnung. + + + + + Abrechnungsperiode + + 01.07.2025 – 30.06.2026 + → Von / Bis + + + Netzstrom – Ihr Anteil + + 1'200.000 kWh + → Netzbezug (kWh) + + + Netzstrom – Betrag (CHF) + + 350.00 + → Netzbezug (CHF) + + + ZEV Photovoltaikstrom – Ihr Anteil + + 900.000 kWh + → PV-Produktion (kWh) + + + ZEV Photovoltaikstrom – Betrag (CHF) + + 250.00 + → PV (CHF) + + + ZEV Stromnebenkosten – Betrag (CHF) + + 80.00 + → Nebenkosten (CHF) + + + Akontozahlungen Strom + + -600.00 + → Akonto (CHF), ohne Minus eingeben + + + + + Stromkosten (wird berechnet) + 680.00 + + Saldo (wird berechnet) + 80.00 + diff --git a/Schaad.Accounting.UI/wwwroot/js/charts.js b/Schaad.Accounting.UI/wwwroot/js/charts.js index 6800571..0fa4ce8 100644 --- a/Schaad.Accounting.UI/wwwroot/js/charts.js +++ b/Schaad.Accounting.UI/wwwroot/js/charts.js @@ -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 },