Add "Wasser" page for the water bills #11

Merged
clayschaad merged 1 commit from water-bills into main 2026-10-30 20:19:07 +00:00
21 changed files with 779 additions and 56 deletions

View file

@ -47,13 +47,14 @@ 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}/{mandator}/water.json water 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.
`electricity.json` and `water.json` are the data files 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
@ -61,10 +62,11 @@ When a new year is opened, the previous year's data is copied as the starting po
- **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}/`; for `electricity.json` it reads/writes the mandator folder instead of the year folder
- **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` and `water.json` it reads/writes the mandator folder instead of the year folder
- **Texte bereinigen** page (`TextCleanup`) — edits only the `Text` of one account's bookings in the selected year (inline, search/replace via `TextReplacement`, bulk set); saves through `RawDataRepository.SaveTransactionTextsAsync`
- **AnalyticsService** — loads all years of the current mandator (via `MultiYearRepository`) into an `AccountingAnalysis` (expenses, income, net, assets) for the Analyse page; queries run in memory
- **Strom** page (`Electricity`, `/electricity`) — grid and dialog (FluentDataGrid/`ElectricityBillDialog`) over `IElectricityBillRepository`'s `ElectricityBill` records (one yearly NeoVac bill each: kWh/CHF for grid and PV, side costs; `TotalKwh`, `PvShare`, `TotalChf`, `ChfPerKwh` are computed); three Chart.js charts via `ChartJsChart` (stacked kWh, CHF/kWh lines, total CHF), grouped by a toggle per bill (default), calendar year or half-year (`ElectricityPeriod.FromBills`; a bill reaching over several periods is spread evenly over its months and the page shows a note)
- **Strom** page (`Electricity`, `/electricity`) — grid and dialog (FluentDataGrid/`ElectricityBillDialog`) over `IElectricityBillRepository`'s `ElectricityBill` records (one yearly NeoVac bill each: kWh/CHF for grid and PV, side costs; `TotalKwh`, `PvShare`, `TotalChf`, `ChfPerKwh` are computed); three Chart.js charts via `ChartJsChart` (stacked kWh, CHF/kWh lines, total CHF), grouped by a toggle per bill (default), calendar year or half-year (`BillPeriod<T>.FromBills` over `IPeriodBill<T>`; a bill reaching over several periods is spread evenly over its months and the page shows a note)
- **Wasser** page (`Water`, `/water`) — same layout as Strom over `IWaterBillRepository`'s `WaterBill` records (warm/cold water m³ and CHF, base costs; `TotalM3`, `WarmWaterShare`, `TotalChf` are computed); two charts (stacked m³, total CHF) with the same period toggle
### UI structure

View file

@ -28,7 +28,7 @@ namespace Schaad.Accounting.Interfaces
/// <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).
/// year (e.g. the electricity and water bills, whose period doesn't align with calendar years).
/// </summary>
string GetMandatorPath();

View file

@ -0,0 +1,17 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using Schaad.Accounting.Models;
namespace Schaad.Accounting.Interfaces
{
public interface IWaterBillRepository
{
Task<List<WaterBill>> GetWaterBillListAsync();
Task SaveWaterBillAsync(WaterBill bill);
Task<WaterBill> GetWaterBillAsync(string id);
Task DeleteWaterBillAsync(string id);
}
}

View file

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

View file

@ -9,7 +9,7 @@ namespace Schaad.Accounting.Models
/// 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 class ElectricityBill : IPeriodBill<ElectricityBill>
{
public string Id { get; set; }
@ -65,5 +65,14 @@ namespace Schaad.Accounting.Models
[JsonIgnore]
[Display(Name = "CHF/kWh PV")]
public decimal? PvChfPerKwh => PvKwh == 0 ? null : PvChf / PvKwh;
public void AddShare(ElectricityBill other, decimal share)
{
GridKwh += other.GridKwh * share;
PvKwh += other.PvKwh * share;
GridChf += other.GridChf * share;
PvChf += other.PvChf * share;
SideCostsChf += other.SideCostsChf * share;
}
}
}

View file

@ -0,0 +1,18 @@
using System;
namespace Schaad.Accounting.Models
{
/// <summary>
/// A bill over a period (e.g. the yearly NeoVac electricity or water bill), so it can be
/// grouped into calendar periods by <see cref="BillPeriod{T}"/>.
/// </summary>
public interface IPeriodBill<in T>
{
DateOnly PeriodFrom { get; set; }
DateOnly PeriodTo { get; set; }
/// <summary>Adds <paramref name="share"/> (0..1) of the other bill's values to this one.</summary>
void AddShare(T other, decimal share);
}
}

View file

@ -0,0 +1,63 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
namespace Schaad.Accounting.Models
{
/// <summary>
/// One water bill for the apartment. Like the electricity bills, these are stored once per
/// mandator instead of per calendar year, because the billing period (e.g. 1 July – 30 June)
/// doesn't align with calendar years (see WaterBillRepository in Schaad.Accounting.Db).
/// </summary>
public class WaterBill : IPeriodBill<WaterBill>
{
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 = "Warmwasser")]
public decimal WarmWaterM3 { get; set; }
[Display(Name = "Kaltwasser")]
public decimal ColdWaterM3 { get; set; }
[Display(Name = "Warmwasser")]
public decimal WarmWaterChf { get; set; }
[Display(Name = "Kaltwasser")]
public decimal ColdWaterChf { get; set; }
[Display(Name = "Grundkosten")]
public decimal BaseCostsChf { get; set; }
/// <summary>Warm plus cold water, in m³.</summary>
[JsonIgnore]
[Display(Name = "Total")]
public decimal TotalM3 => WarmWaterM3 + ColdWaterM3;
/// <summary>Share of the consumption that was warm water, 0..1.</summary>
[JsonIgnore]
[Display(Name = "Warmwasser-Anteil")]
public decimal WarmWaterShare => TotalM3 == 0 ? 0 : WarmWaterM3 / TotalM3;
/// <summary>Warm water, cold water and base costs added up.</summary>
[JsonIgnore]
[Display(Name = "Total")]
public decimal TotalChf => WarmWaterChf + ColdWaterChf + BaseCostsChf;
public void AddShare(WaterBill other, decimal share)
{
WarmWaterM3 += other.WarmWaterM3 * share;
ColdWaterM3 += other.ColdWaterM3 * share;
WarmWaterChf += other.WarmWaterChf * share;
ColdWaterChf += other.ColdWaterChf * share;
BaseCostsChf += other.BaseCostsChf * share;
}
}
}

View file

@ -26,6 +26,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 string WATER = "water.json";
private const int MaxErrors = 20;
// Like the normal options, but property names that don't exist (typos) are errors instead
@ -49,7 +50,8 @@ namespace Schaad.Accounting.Repositories
"BookingTexts.json",
"SplitPredefinitions.json",
"SubClasses.json",
ELECTRICITY
ELECTRICITY,
WATER
];
public async Task<RawDataFile> LoadAsync(string fileName)
@ -69,6 +71,7 @@ namespace Schaad.Accounting.Repositories
"SplitPredefinitions.json" => SaveAsync<SplitPredefinition>(fileName, text, loadedHash),
"SubClasses.json" => SaveAsync<SubClass>(fileName, text, loadedHash),
ELECTRICITY => SaveAsync<ElectricityBill>(fileName, text, loadedHash),
WATER => SaveAsync<WaterBill>(fileName, text, loadedHash),
_ => throw new ArgumentException($"Unknown data file '{fileName}'", nameof(fileName))
};
@ -239,10 +242,10 @@ namespace Schaad.Accounting.Repositories
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).
// electricity.json and water.json live at the mandator level, not per year (their 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();
=> fileName is ELECTRICITY or WATER ? settingsService.GetMandatorPath() : settingsService.GetDbPath();
private static string Hash(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes));

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>
/// Water bills of the current mandator, stored once per mandator (not per year like the
/// other data files) because the billing period doesn't align with calendar years.
/// </summary>
public class WaterBillRepository : BaseRepository, IWaterBillRepository
{
private const string WATER = "water.json";
public WaterBillRepository(ISettingsService settingsService, RepositoryCache cache, ILogger<WaterBillRepository> logger)
: base(settingsService, cache, logger)
{
}
public Task<List<WaterBill>> GetWaterBillListAsync()
=> LoadListAsync<WaterBill>(settingsService.GetMandatorPath(), WATER);
public async Task SaveWaterBillAsync(WaterBill bill)
{
var bills = await GetWaterBillListAsync();
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(), WATER);
}
public async Task<WaterBill> GetWaterBillAsync(string id)
{
var bills = await GetWaterBillListAsync();
return bills.FirstOrDefault(b => b.Id == id);
}
public async Task DeleteWaterBillAsync(string id)
{
var bills = await GetWaterBillListAsync();
bills.RemoveAll(b => b.Id == id);
await SaveAsync(bills, settingsService.GetMandatorPath(), WATER);
}
}
}

View file

@ -3,7 +3,7 @@ using Shouldly;
namespace Schaad.Accounting.Tests;
public class ElectricityPeriodTestShould
public class BillPeriodTestShould
{
[Fact]
public void KeepEachBillUnchangedWhenGroupingPerBill()
@ -11,7 +11,7 @@ public class ElectricityPeriodTestShould
var later = YearlyBill(2024);
var first = YearlyBill(2023);
var periods = ElectricityPeriod.FromBills([later, first], ElectricityPeriodKind.Bill);
var periods = BillPeriod<ElectricityBill>.FromBills([later, first], BillPeriodKind.Bill);
periods.Select(p => p.Bill).ShouldBe([first, later]);
periods.ShouldAllBe(p => !p.IsSplit);
@ -20,7 +20,7 @@ public class ElectricityPeriodTestShould
[Fact]
public void LabelBillAsBillingYearWhenItCoversAWholeYear()
{
var periods = ElectricityPeriod.FromBills([YearlyBill(2023)], ElectricityPeriodKind.Bill);
var periods = BillPeriod<ElectricityBill>.FromBills([YearlyBill(2023)], BillPeriodKind.Bill);
periods[0].Label.ShouldBe("23/24");
}
@ -30,7 +30,7 @@ public class ElectricityPeriodTestShould
{
var bill = Bill(new DateOnly(2024, 1, 1), new DateOnly(2024, 6, 30));
var periods = ElectricityPeriod.FromBills([bill], ElectricityPeriodKind.Bill);
var periods = BillPeriod<ElectricityBill>.FromBills([bill], BillPeriodKind.Bill);
periods[0].Label.ShouldBe("01.01.24–30.06.24");
}
@ -45,7 +45,7 @@ public class ElectricityPeriodTestShould
bill.PvChf = 400m;
bill.SideCostsChf = 100m;
var halves = ElectricityPeriod.FromBills([bill], ElectricityPeriodKind.HalfYear);
var halves = BillPeriod<ElectricityBill>.FromBills([bill], BillPeriodKind.HalfYear);
halves.Count.ShouldBe(2);
halves[0].From.ShouldBe(new DateOnly(2023, 7, 1));
@ -69,13 +69,24 @@ public class ElectricityPeriodTestShould
var second = YearlyBill(2024);
second.GridKwh = 5000m;
var years = ElectricityPeriod.FromBills([first, second], ElectricityPeriodKind.Year);
var years = BillPeriod<ElectricityBill>.FromBills([first, second], BillPeriodKind.Year);
years.Select(y => y.Label).ShouldBe(["2023", "2024", "2025"]);
years.Select(y => y.Bill.GridKwh).ShouldBe([1500m, 4000m, 2500m]);
years.ShouldAllBe(y => y.IsSplit);
}
[Fact]
public void SplitWaterBillIntoTwoHalvesWhenPeriodRunsJulyToJune()
{
var bill = new WaterBill { PeriodFrom = new DateOnly(2023, 7, 1), PeriodTo = new DateOnly(2024, 6, 30), WarmWaterM3 = 10m, ColdWaterM3 = 30m, BaseCostsChf = 200m };
var halves = BillPeriod<WaterBill>.FromBills([bill], BillPeriodKind.HalfYear);
halves.Select(h => h.Label).ShouldBe(["H2 23", "H1 24"]);
halves.ShouldAllBe(h => h.Bill.WarmWaterM3 == 5m && h.Bill.ColdWaterM3 == 15m && h.Bill.BaseCostsChf == 100m);
}
[Fact]
public void KeepPricePerKwhOfTheBillWhenSplittingIt()
{
@ -83,7 +94,7 @@ public class ElectricityPeriodTestShould
bill.GridKwh = 3000m;
bill.GridChf = 900m;
var halves = ElectricityPeriod.FromBills([bill], ElectricityPeriodKind.HalfYear);
var halves = BillPeriod<ElectricityBill>.FromBills([bill], BillPeriodKind.HalfYear);
halves.ShouldAllBe(h => h.Bill.GridChfPerKwh == 0.3m);
}
@ -96,7 +107,7 @@ public class ElectricityPeriodTestShould
var second = Bill(new DateOnly(2024, 4, 1), new DateOnly(2024, 6, 30));
second.GridKwh = 200m;
var halves = ElectricityPeriod.FromBills([first, second], ElectricityPeriodKind.HalfYear);
var halves = BillPeriod<ElectricityBill>.FromBills([first, second], BillPeriodKind.HalfYear);
halves.Count.ShouldBe(1);
halves[0].Bill.GridKwh.ShouldBe(300m);
@ -109,7 +120,7 @@ public class ElectricityPeriodTestShould
var first = YearlyBill(2022);
var later = YearlyBill(2024);
var halves = ElectricityPeriod.FromBills([later, first], ElectricityPeriodKind.HalfYear);
var halves = BillPeriod<ElectricityBill>.FromBills([later, first], BillPeriodKind.HalfYear);
halves.Select(h => h.Label).ShouldBe(["H2 22", "H1 23", "H2 23", "H1 24", "H2 24", "H1 25"]);
halves[2].Bill.ShouldBeNull();
@ -117,12 +128,12 @@ public class ElectricityPeriodTestShould
}
[Theory]
[InlineData(ElectricityPeriodKind.Bill)]
[InlineData(ElectricityPeriodKind.Year)]
[InlineData(ElectricityPeriodKind.HalfYear)]
public void ReturnEmptyListWhenThereAreNoBills(ElectricityPeriodKind kind)
[InlineData(BillPeriodKind.Bill)]
[InlineData(BillPeriodKind.Year)]
[InlineData(BillPeriodKind.HalfYear)]
public void ReturnEmptyListWhenThereAreNoBills(BillPeriodKind kind)
{
ElectricityPeriod.FromBills([], kind).ShouldBeEmpty();
BillPeriod<ElectricityBill>.FromBills([], kind).ShouldBeEmpty();
}
private static ElectricityBill YearlyBill(int startYear) => Bill(new DateOnly(startYear, 7, 1), new DateOnly(startYear + 1, 6, 30));

View file

@ -190,6 +190,24 @@ public class RawDataRepositoryTestShould : IDisposable
File.Exists(Path.Combine(dbDir, "electricity.json")).ShouldBeFalse();
}
[Fact]
public async Task ReadAndWriteWaterFileInMandatorFolderNotYearFolderWhenEditing()
{
File.WriteAllText(Path.Combine(mandatorDir, "water.json"), """
[ { "Id": "w1", "PeriodFrom": "2023-07-01", "PeriodTo": "2024-06-30", "WarmWaterM3": 100 } ]
""");
var loaded = await sut.LoadAsync("water.json");
loaded.Text.ShouldContain("\"WarmWaterM3\": 100");
var result = await sut.SaveAsync("water.json", loaded.Text.Replace("100", "150"), loaded.Hash);
result.Errors.ShouldBeEmpty();
result.Saved.ShouldBeTrue();
File.Exists(Path.Combine(mandatorDir, "water.json")).ShouldBeTrue();
File.ReadAllText(Path.Combine(mandatorDir, "water.json")).ShouldContain("150");
File.Exists(Path.Combine(dbDir, "water.json")).ShouldBeFalse();
}
[Fact]
public async Task RejectUnknownFileNameWhenLoading()
{

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 WaterBillRepositoryTestShould : IDisposable
{
private readonly string mandatorDir;
private readonly ISettingsService settingsService;
private readonly WaterBillRepository sut;
public WaterBillRepositoryTestShould()
{
mandatorDir = Path.Combine(Path.GetTempPath(), "AccountingNext-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(mandatorDir);
settingsService = Substitute.For<ISettingsService>();
settingsService.GetMandatorPath().Returns(mandatorDir);
sut = new WaterBillRepository(settingsService, new RepositoryCache(), NullLogger<WaterBillRepository>.Instance);
}
public void Dispose()
{
if (Directory.Exists(mandatorDir))
{
Directory.Delete(mandatorDir, recursive: true);
}
}
[Fact]
public async Task ReturnEmptyListWhenFileDoesNotExistYet()
{
(await sut.GetWaterBillListAsync()).ShouldBeEmpty();
}
[Fact]
public async Task AssignNewIdWhenSavingBillWithoutId()
{
var bill = new WaterBill
{
PeriodFrom = new DateOnly(2023, 7, 1),
PeriodTo = new DateOnly(2024, 6, 30),
WarmWaterM3 = 12.345m,
ColdWaterM3 = 30.5m,
WarmWaterChf = 250.40m,
ColdWaterChf = 98.15m,
BaseCostsChf = 120m
};
await sut.SaveWaterBillAsync(bill);
var stored = (await sut.GetWaterBillListAsync()).Single();
stored.Id.ShouldNotBeNullOrEmpty();
stored.TotalM3.ShouldBe(42.845m);
stored.TotalChf.ShouldBe(468.55m);
}
[Fact]
public async Task UpdateInPlaceWhenSavingBillWithExistingId()
{
await sut.SaveWaterBillAsync(new WaterBill { PeriodFrom = new DateOnly(2023, 7, 1), PeriodTo = new DateOnly(2024, 6, 30), WarmWaterM3 = 10m });
var id = (await sut.GetWaterBillListAsync()).Single().Id;
await sut.SaveWaterBillAsync(new WaterBill { Id = id, PeriodFrom = new DateOnly(2023, 7, 1), PeriodTo = new DateOnly(2024, 6, 30), WarmWaterM3 = 13m });
var bills = await sut.GetWaterBillListAsync();
bills.Count.ShouldBe(1);
bills[0].WarmWaterM3.ShouldBe(13m);
}
[Fact]
public async Task RemoveBillWhenDeletingById()
{
await sut.SaveWaterBillAsync(new WaterBill { PeriodFrom = new DateOnly(2023, 7, 1), PeriodTo = new DateOnly(2024, 6, 30) });
var id = (await sut.GetWaterBillListAsync()).Single().Id;
await sut.DeleteWaterBillAsync(id);
(await sut.GetWaterBillListAsync()).ShouldBeEmpty();
}
[Fact]
public async Task StoreFileDirectlyInMandatorFolderWithoutYearSubfolder()
{
await sut.SaveWaterBillAsync(new WaterBill { PeriodFrom = new DateOnly(2023, 7, 1), PeriodTo = new DateOnly(2024, 6, 30) });
File.Exists(Path.Combine(mandatorDir, "water.json")).ShouldBeTrue();
}
}

View file

@ -0,0 +1,53 @@
using Schaad.Accounting.Models;
using Shouldly;
namespace Schaad.Accounting.Tests;
public class WaterBillTestShould
{
[Fact]
public void AddWarmAndColdWaterWhenCalculatingTotalM3()
{
var bill = new WaterBill { WarmWaterM3 = 12.345m, ColdWaterM3 = 30.5m };
bill.TotalM3.ShouldBe(42.845m);
}
[Fact]
public void DivideWarmWaterByTotalWhenCalculatingWarmWaterShare()
{
var bill = new WaterBill { WarmWaterM3 = 10m, ColdWaterM3 = 30m };
bill.WarmWaterShare.ShouldBe(0.25m);
}
[Fact]
public void ReturnZeroWarmWaterShareWhenThereIsNoConsumption()
{
var bill = new WaterBill { WarmWaterM3 = 0m, ColdWaterM3 = 0m };
bill.WarmWaterShare.ShouldBe(0m);
}
[Fact]
public void AddWarmColdAndBaseCostsWhenCalculatingTotalChf()
{
var bill = new WaterBill { WarmWaterChf = 250.40m, ColdWaterChf = 98.15m, BaseCostsChf = 120m };
bill.TotalChf.ShouldBe(468.55m);
}
[Fact]
public void AddShareOfAllValuesWhenAddingShareOfOtherBill()
{
var sum = new WaterBill { WarmWaterM3 = 1m, ColdWaterM3 = 2m, WarmWaterChf = 4m, ColdWaterChf = 5m, BaseCostsChf = 3m };
sum.AddShare(new WaterBill { WarmWaterM3 = 10m, ColdWaterM3 = 20m, WarmWaterChf = 40m, ColdWaterChf = 50m, BaseCostsChf = 300m }, 0.5m);
sum.WarmWaterM3.ShouldBe(6m);
sum.ColdWaterM3.ShouldBe(12m);
sum.WarmWaterChf.ShouldBe(24m);
sum.ColdWaterChf.ShouldBe(30m);
sum.BaseCostsChf.ShouldBe(153m);
}
}

View file

@ -10,6 +10,7 @@
<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>
<FluentNavLink Href="water" Icon="@(new Size20.Drop())" IconColor="Color.Accent">Wasser</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,51 @@
@implements IDialogContentComponent<Schaad.Accounting.Models.WaterBill>
@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.WarmWaterM3" Label="Warmwasser (m³)" Style="width: 170px;" />
<FluentNumberField @bind-Value="@Content.ColdWaterM3" Label="Kaltwasser (m³)" Style="width: 170px;" />
</FluentStack>
<FluentStack Orientation="Orientation.Horizontal">
<FluentNumberField @bind-Value="@Content.WarmWaterChf" Label="Warmwasser (CHF)" Style="width: 170px;" />
<FluentNumberField @bind-Value="@Content.ColdWaterChf" Label="Kaltwasser (CHF)" Style="width: 170px;" />
</FluentStack>
<FluentStack Orientation="Orientation.Horizontal">
<FluentNumberField @bind-Value="@Content.BaseCostsChf" Label="Grundkosten (CHF)" Style="width: 170px;" />
</FluentStack>
<div>
<FluentValidationSummary />
</div>
</EditForm>
<div style="margin-top: 12px; font-size: 13px; color: #52514e;">
Total <strong>@M3(Content.TotalM3)</strong> · <strong>@Chf(Content.TotalChf)</strong>
</div>
</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>

View file

@ -0,0 +1,66 @@
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 WaterBillDialog : ComponentBase
{
private static readonly CultureInfo SwissNumbers = CreateSwissNumbers();
private EditContext editContext = null!;
// FluentDatePicker needs DateTime?; the model stores DateOnly (see WaterBill).
private DateTime? periodFrom;
private DateTime? periodTo;
[CascadingParameter]
public FluentDialog Dialog { get; set; } = null!;
[Parameter]
public WaterBill Content { get; set; } = null!;
[Inject]
private IWaterBillRepository waterBillRepository { 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 waterBillRepository.SaveWaterBillAsync(Content);
await Dialog.CloseAsync(Content);
}
}
private async Task CancelAsync()
{
await Dialog.CancelAsync();
}
private static string M3(decimal value) => value.ToString("#,0.00", SwissNumbers) + " m³";
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

@ -11,7 +11,7 @@ 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
/// <see cref="IElectricityBillRepository"/>). Grid for entering/editing, plus charts per bill,
/// calendar year or half-year (see <see cref="ElectricityPeriod"/>): consumption grid/PV, price
/// calendar year or half-year (see <see cref="BillPeriod{T}"/>): consumption grid/PV, price
/// per kWh and total costs.
/// </summary>
public partial class Electricity : ComponentBase
@ -25,12 +25,12 @@ public partial class Electricity : ComponentBase
[Inject]
private IToastService toastService { get; set; } = null!;
private static readonly ElectricityPeriodKind[] PeriodKinds =
[ElectricityPeriodKind.Bill, ElectricityPeriodKind.Year, ElectricityPeriodKind.HalfYear];
private static readonly BillPeriodKind[] PeriodKinds =
[BillPeriodKind.Bill, BillPeriodKind.Year, BillPeriodKind.HalfYear];
private IReadOnlyList<ElectricityBill> source = [];
private ElectricityPeriodKind periodKind = ElectricityPeriodKind.Bill;
private BillPeriodKind periodKind = BillPeriodKind.Bill;
// True if a bill had to be spread over several periods of the selected kind.
private bool isSplit;
@ -52,7 +52,7 @@ public partial class Electricity : ComponentBase
BuildCharts();
}
private void SetPeriodKind(ElectricityPeriodKind kind)
private void SetPeriodKind(BillPeriodKind kind)
{
periodKind = kind;
BuildCharts();
@ -61,7 +61,7 @@ public partial class Electricity : ComponentBase
private void BuildCharts()
{
// A bill reaching over several periods is spread evenly over its months.
var periods = ElectricityPeriod.FromBills(source, periodKind);
var periods = BillPeriod<ElectricityBill>.FromBills(source, periodKind);
isSplit = periods.Any(p => p.IsSplit);
var labels = periods.Select(p => p.Label).ToList();
barData = new
@ -150,17 +150,17 @@ public partial class Electricity : ComponentBase
}
}
private static string PeriodKindName(ElectricityPeriodKind kind) => kind switch
private static string PeriodKindName(BillPeriodKind kind) => kind switch
{
ElectricityPeriodKind.Year => "Kalenderjahr",
ElectricityPeriodKind.HalfYear => "Halbjahr",
BillPeriodKind.Year => "Kalenderjahr",
BillPeriodKind.HalfYear => "Halbjahr",
_ => "Abrechnung"
};
private string PerPeriod => periodKind switch
{
ElectricityPeriodKind.Year => "pro Jahr",
ElectricityPeriodKind.HalfYear => "pro Halbjahr",
BillPeriodKind.Year => "pro Jahr",
BillPeriodKind.HalfYear => "pro Halbjahr",
_ => "pro Abrechnung"
};

View file

@ -0,0 +1,67 @@
@page "/water"
@rendermode InteractiveServer
@using Schaad.Accounting.UI.Components.Pages.Analytics
<PageTitle>Wasser</PageTitle>
<div class="water">
<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
{
<FluentStack Orientation="Orientation.Horizontal" VerticalAlignment="VerticalAlignment.Center" Wrap="true">
<div class="segmented" role="group" aria-label="Zeitraum">
@foreach (var kind in PeriodKinds)
{
<FluentButton Appearance="@(kind == periodKind ? Appearance.Accent : Appearance.Neutral)"
aria-pressed="@(kind == periodKind ? "true" : "false")"
OnClick="@(() => SetPeriodKind(kind))">@PeriodKindName(kind)</FluentButton>
}
</div>
@if (isSplit)
{
<span class="split-note">Werte anteilig auf die Monate der Abrechnungsperiode verteilt</span>
}
</FluentStack>
<div class="pair">
<FluentCard class="chart-card">
<div class="card-title">Verbrauch @PerPeriod</div>
<ChartJsChart Kind="stackedBar" Data="@barData" Height="360px"
AriaLabel="@($"Warm- und Kaltwasserverbrauch {PerPeriod}, gestapelte Balken in m³")" />
</FluentCard>
<FluentCard class="chart-card">
<div class="card-title">Gesamtkosten @PerPeriod</div>
<ChartJsChart Kind="line" Data="@costData" Height="360px"
AriaLabel="@($"Gesamtkosten {PerPeriod}")" />
</FluentCard>
</div>
}
<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="Warmwasser m³" Property="@(p => p.WarmWaterM3)" Format="#,0.00" Align="Align.End" />
<PropertyColumn Title="Kaltwasser m³" Property="@(p => p.ColdWaterM3)" Format="#,0.00" Align="Align.End" />
<PropertyColumn Title="Total m³" Property="@(p => p.TotalM3)" Format="#,0.00" Align="Align.End" />
<PropertyColumn Title="Warmwasser-Anteil" Property="@(p => p.WarmWaterShare)" Format="P1" Align="Align.End" />
<PropertyColumn Title="Warmwasser CHF" Property="@(p => p.WarmWaterChf)" Format="C2" Align="Align.End" />
<PropertyColumn Title="Kaltwasser CHF" Property="@(p => p.ColdWaterChf)" Format="C2" Align="Align.End" />
<PropertyColumn Title="Grundkosten" Property="@(p => p.BaseCostsChf)" 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,154 @@
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>
/// Water bills for the apartment, laid out like the Strom page (<see cref="Electricity"/>): the
/// bills are stored once per mandator, not per calendar year (see <see cref="IWaterBillRepository"/>).
/// Grid for entering/editing, plus charts per bill, calendar year or half-year (see
/// <see cref="BillPeriod{T}"/>): warm/cold water consumption and total costs.
/// </summary>
public partial class Water : ComponentBase
{
[Inject]
private IWaterBillRepository waterBillRepository { get; set; } = null!;
[Inject]
private IDialogService dialogService { get; set; } = null!;
[Inject]
private IToastService toastService { get; set; } = null!;
private static readonly BillPeriodKind[] PeriodKinds =
[BillPeriodKind.Bill, BillPeriodKind.Year, BillPeriodKind.HalfYear];
private IReadOnlyList<WaterBill> source = [];
private BillPeriodKind periodKind = BillPeriodKind.Bill;
// True if a bill had to be spread over several periods of the selected kind.
private bool isSplit;
private object barData = new();
private object costData = new();
protected override async Task OnInitializedAsync()
{
await LoadAsync();
}
private async Task LoadAsync()
{
source = (await waterBillRepository.GetWaterBillListAsync())
.OrderBy(b => b.PeriodFrom)
.ToList();
BuildCharts();
}
private void SetPeriodKind(BillPeriodKind kind)
{
periodKind = kind;
BuildCharts();
}
private void BuildCharts()
{
// A bill reaching over several periods is spread evenly over its months.
var periods = BillPeriod<WaterBill>.FromBills(source, periodKind);
isSplit = periods.Any(p => p.IsSplit);
var labels = periods.Select(p => p.Label).ToList();
barData = new
{
labels,
series = new object[]
{
new { name = "Warmwasser", color = ChartTheme.ColorAt(0), values = periods.Select(p => p.Bill?.WarmWaterM3).ToList(), clickable = false },
new { name = "Kaltwasser", color = ChartTheme.ColorAt(1), values = periods.Select(p => p.Bill?.ColdWaterM3).ToList(), clickable = false }
},
unit = "m³"
};
costData = new
{
labels,
series = new object[]
{
new { name = "Total", color = ChartTheme.ColorAt(2), values = periods.Select(p => p.Bill?.TotalChf).ToList(), width = 2 }
},
unit = "CHF"
};
}
private async Task AddAsync()
{
var data = new WaterBill();
var dialog = await dialogService.ShowDialogAsync<WaterBillDialog>(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 waterBillRepository.GetWaterBillAsync(id);
var dialog = await dialogService.ShowDialogAsync<WaterBillDialog>(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 waterBillRepository.DeleteWaterBillAsync(id);
await LoadAsync();
toastService.ShowToast(ToastIntent.Success, "Abrechnung gelöscht", 3000);
}
}
private static string PeriodKindName(BillPeriodKind kind) => kind switch
{
BillPeriodKind.Year => "Kalenderjahr",
BillPeriodKind.HalfYear => "Halbjahr",
_ => "Abrechnung"
};
private string PerPeriod => periodKind switch
{
BillPeriodKind.Year => "pro Jahr",
BillPeriodKind.HalfYear => "pro Halbjahr",
_ => "pro Abrechnung"
};
private static string FullLabel(WaterBill bill) => $"{bill.PeriodFrom:dd.MM.yyyy} – {bill.PeriodTo:dd.MM.yyyy}";
}

View file

@ -0,0 +1,43 @@
.water {
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;
}
.segmented {
display: flex;
flex-wrap: wrap;
gap: 2px;
}
.split-note {
font-size: 12px;
color: var(--neutral-foreground-hint);
}

View file

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