AccountingNext/Schaad.Accounting.Db/Repositories/RawDataRepository.cs
Claudio Schaad 7d7bd6073c 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>
2026-10-25 20:30:40 +01:00

270 lines
12 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Schaad.Accounting.Interfaces;
using Schaad.Accounting.Models;
namespace Schaad.Accounting.Repositories
{
/// <summary>
/// Plain-text access to the data files of the selected year and mandator for the JSON editor.
/// Saving goes through <see cref="BaseRepository.SaveAsync{T}"/> (atomic write, cache
/// invalidation), but only after the text has been checked, because a broken file would break
/// every page that reads it.
/// </summary>
public class RawDataRepository : BaseRepository, IRawDataRepository
{
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
// of being silently dropped on save.
private static readonly JsonSerializerOptions StrictOptions = new(JsonStorage.Options)
{
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow
};
public RawDataRepository(ISettingsService settingsService, RepositoryCache cache, ILogger<RawDataRepository> logger)
: base(settingsService, cache, logger)
{
}
public IReadOnlyList<string> FileNames { get; } =
[
TRANSACTIONS,
ACCOUNTS,
"BankTransactions.json",
"BookingRules.json",
"BookingTexts.json",
"SplitPredefinitions.json",
"SubClasses.json",
ELECTRICITY
];
public async Task<RawDataFile> LoadAsync(string fileName)
{
var path = PathOf(fileName);
var bytes = File.Exists(path) ? await File.ReadAllBytesAsync(path) : Array.Empty<byte>();
return new RawDataFile(fileName, path, Encoding.UTF8.GetString(bytes), Hash(bytes));
}
public Task<RawDataSaveResult> SaveAsync(string fileName, string text, string loadedHash) => fileName switch
{
TRANSACTIONS => SaveAsync<Transaction>(fileName, text, loadedHash),
ACCOUNTS => SaveAsync<Account>(fileName, text, loadedHash),
"BankTransactions.json" => SaveAsync<BankTransaction>(fileName, text, loadedHash),
"BookingRules.json" => SaveAsync<BookingRule>(fileName, text, loadedHash),
"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))
};
private async Task<RawDataSaveResult> SaveAsync<T>(string fileName, string text, string loadedHash)
{
List<T>? items;
try
{
items = JsonSerializer.Deserialize<List<T>>(text, StrictOptions);
}
catch (JsonException ex)
{
return Failed(Describe(ex));
}
if (items is null)
{
return Failed("Die Datei muss eine Liste enthalten: [ ... ]");
}
var errors = CheckIds(items);
if (items is List<Transaction> transactions)
{
errors.AddRange(await CheckAccountReferencesAsync(transactions));
}
if (items is List<Account> accounts)
{
errors.AddRange(await CheckAccountsStillUsedAsync(accounts));
}
if (errors.Count > 0)
{
return Failed(errors.ToArray());
}
var current = await LoadAsync(fileName);
if (current.Hash != loadedHash)
{
return Failed("Die Datei wurde seit dem Laden geändert (z.B. durch eine Buchung). Bitte neu laden; deine Änderungen gehen dabei verloren, also vorher kopieren.");
}
var backupPath = await BackupAsync(current);
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);
}
public async Task<TransactionSnapshot> LoadTransactionsAsync()
{
var file = await LoadAsync(TRANSACTIONS);
return new TransactionSnapshot(ParseTransactions(file), file.Hash);
}
private static List<Transaction> ParseTransactions(RawDataFile file)
=> file.Text.Length == 0
? new List<Transaction>()
: JsonSerializer.Deserialize<List<Transaction>>(file.Text, JsonStorage.Options) ?? new List<Transaction>();
public async Task<RawDataSaveResult> SaveTransactionTextsAsync(IReadOnlyDictionary<string, string> textById, string loadedHash)
{
// One read: the backup is exactly the version that was checked.
var file = await LoadAsync(TRANSACTIONS);
if (file.Hash != loadedHash)
{
return Failed("Die Buchungen wurden seit dem Laden geändert (z.B. durch eine neue Buchung). Bitte neu laden.");
}
var transactions = ParseTransactions(file);
var byId = transactions.Where(t => t.Id != null).ToDictionary(t => t.Id);
var errors = new List<string>();
foreach (var (id, text) in textById)
{
if (byId.TryGetValue(id, out var transaction) == false)
{
errors.Add($"Buchung \"{id}\" gibt es nicht mehr.");
}
else if (string.IsNullOrWhiteSpace(text))
{
errors.Add($"Buchung vom {transaction.ValueDate:dd.MM.yyyy} über {transaction.Value:0.00}: Der Text darf nicht leer sein.");
}
else
{
transaction.Text = text;
}
}
if (errors.Count > 0)
{
return Failed(Limit(errors).ToArray());
}
var backupPath = await BackupAsync(file);
await SaveAsync(transactions, TRANSACTIONS);
logger.LogInformation("Changed {Count} transaction texts in {FilePath}; previous version in {BackupPath}", textById.Count, file.Path, backupPath);
return new RawDataSaveResult([], await LoadAsync(TRANSACTIONS), backupPath);
}
private static List<string> CheckIds<T>(List<T> items)
{
var errors = new List<string>();
var idProperty = typeof(T).GetProperty("Id");
if (idProperty is null)
{
return errors;
}
var ids = items.Select(item => idProperty.GetValue(item) as string).ToList();
for (var i = 0; i < ids.Count; i++)
{
if (string.IsNullOrWhiteSpace(ids[i]))
{
errors.Add($"Eintrag {i + 1}: \"Id\" fehlt.");
}
}
foreach (var duplicate in ids.Where(id => !string.IsNullOrWhiteSpace(id)).GroupBy(id => id).Where(g => g.Count() > 1))
{
errors.Add($"Id \"{duplicate.Key}\" kommt {duplicate.Count()}-mal vor.");
}
return Limit(errors);
}
private async Task<List<string>> CheckAccountReferencesAsync(List<Transaction> transactions)
{
var accountIds = (await LoadListAsync<Account>(ACCOUNTS)).Select(a => a.Id).ToHashSet();
var errors = new List<string>();
for (var i = 0; i < transactions.Count; i++)
{
var t = transactions[i];
foreach (var (id, role) in new[] { (t.OriginAccountId, "OriginAccountId"), (t.TargetAccountId, "TargetAccountId") })
{
if (accountIds.Contains(id) == false)
{
errors.Add($"Buchung {i + 1} ({t.ValueDate:dd.MM.yyyy} \"{t.Text}\"): {role} \"{id}\" ist kein Konto in {ACCOUNTS}.");
}
}
}
return Limit(errors);
}
private async Task<List<string>> CheckAccountsStillUsedAsync(List<Account> accounts)
{
var accountIds = accounts.Select(a => a.Id).ToHashSet();
var transactions = await LoadListAsync<Transaction>(TRANSACTIONS);
return Limit(transactions
.SelectMany(t => new[] { t.OriginAccountId, t.TargetAccountId })
.Where(id => accountIds.Contains(id) == false)
.GroupBy(id => id)
.Select(g => $"Konto-Id \"{g.Key}\" fehlt, wird aber von {g.Count()} Buchungen in {TRANSACTIONS} verwendet.")
.ToList());
}
private async Task<string> BackupAsync(RawDataFile current)
{
var settings = settingsService.GetSettings();
var directory = Path.Combine(settings.DataPath, DataFolders.Backup, settingsService.GetMandator(),
settingsService.GetYear().ToString(), "json-" + DateTime.Now.ToString("yyyyMMddHHmmss"));
Directory.CreateDirectory(directory);
var backupPath = Path.Combine(directory, current.FileName);
await File.WriteAllTextAsync(backupPath, current.Text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
return backupPath;
}
private string PathOf(string fileName)
{
if (FileNames.Contains(fileName) == false)
{
throw new ArgumentException($"Unknown data file '{fileName}'", nameof(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)
{
// Message ends with " Path: ... | LineNumber: ... | BytePositionInLine: ...", which we
// show in our own words.
var message = ex.Message;
var cut = message.IndexOf(" Path:", StringComparison.Ordinal);
if (cut > 0)
{
message = message[..cut];
}
var position = ex.LineNumber is { } line ? $"Zeile {line + 1}, Spalte {(ex.BytePositionInLine ?? 0) + 1}" : "Unbekannte Stelle";
return $"{position} ({ex.Path}): {message}";
}
private static List<string> Limit(List<string> errors)
=> errors.Count <= MaxErrors
? errors
: errors.Take(MaxErrors).Append($"… und {errors.Count - MaxErrors} weitere.").ToList();
private static RawDataSaveResult Failed(params string[] errors) => new(errors, null, null);
}
}