AccountingNext/Schaad.Accounting.Db/Repositories/BaseRepository.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

152 lines
5.8 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Schaad.Accounting.Interfaces;
namespace Schaad.Accounting.Repositories
{
public abstract class BaseRepository
{
// One semaphore per absolute file path so concurrent SaveAsync+SaveAsync and
// SaveAsync+LoadAsync are serialized and can't observe a half-written file.
private static readonly ConcurrentDictionary<string, SemaphoreSlim> FileLocks =
new(StringComparer.OrdinalIgnoreCase);
protected readonly ISettingsService settingsService;
protected readonly RepositoryCache cache;
protected readonly ILogger logger;
protected BaseRepository(ISettingsService settingsService, RepositoryCache cache, ILogger logger)
{
this.settingsService = settingsService;
this.cache = cache;
this.logger = logger;
}
/// <summary>
/// Copies fileName from last year's directory to the current year's directory when the
/// current year doesn't have it yet. Kept synchronous because it runs from repository
/// constructors; File.Copy has no async equivalent in .NET 9 either way.
/// </summary>
protected void EnsureFileExists(string fileName)
{
string filePath = Path.Combine(settingsService.GetDbPath(), fileName);
var semaphore = GetLock(filePath);
semaphore.Wait();
try
{
if (File.Exists(filePath) == false)
{
var lastYearFile = Path.Combine(settingsService.GetLastYearDbPath(), fileName);
if (File.Exists(lastYearFile))
{
File.Copy(lastYearFile, filePath);
}
}
}
finally
{
semaphore.Release();
}
}
/// <summary>
/// Load a list, cached per scope. First call reads the JSON file; subsequent calls in
/// the same scope return the cached list. <see cref="SaveAsync"/> invalidates the entry.
/// </summary>
protected Task<List<T>> LoadListAsync<T>(string fileName)
=> LoadListAsync<T>(settingsService.GetDbPath(), fileName);
/// <summary>
/// Same as <see cref="LoadListAsync{T}(string)"/> for a file in any data directory (e.g.
/// another year). Shares the cache, which is keyed by absolute path, so a save in the
/// current year also invalidates readers of that year.
/// </summary>
protected Task<List<T>> LoadListAsync<T>(string directory, string fileName)
{
var filePath = Path.Combine(directory, fileName);
return cache.GetOrLoadAsync(filePath, async () => await LoadFileAsync<List<T>>(filePath) ?? new List<T>());
}
/// <summary>
/// Save an object to a JSON file. Writes to a .tmp sibling and then atomically
/// renames it, so a crash mid-write leaves the previous file intact. Invalidates
/// the corresponding cache entry.
/// </summary>
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(directory, fileName);
var tmpPath = filePath + ".tmp";
var semaphore = GetLock(filePath);
await semaphore.WaitAsync();
try
{
try
{
await File.WriteAllBytesAsync(tmpPath, JsonSerializer.SerializeToUtf8Bytes(obj, JsonStorage.Options));
// File.Move has no async form in .NET 9.
File.Move(tmpPath, filePath, overwrite: true);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to save {FilePath}", filePath);
if (File.Exists(tmpPath))
{
try { File.Delete(tmpPath); } catch { /* best effort */ }
}
throw;
}
}
finally
{
semaphore.Release();
}
cache.Invalidate(filePath);
}
/// <summary>
/// Load an object from a JSON file (uncached; used for one-off reads such as file
/// existence bootstrapping). Prefer <see cref="LoadListAsync{T}"/> for repository reads.
/// </summary>
protected Task<T> LoadAsync<T>(string fileName)
=> LoadFileAsync<T>(Path.Combine(settingsService.GetDbPath(), fileName));
private static async Task<T> LoadFileAsync<T>(string filePath)
{
var semaphore = GetLock(filePath);
await semaphore.WaitAsync();
try
{
if (File.Exists(filePath) == false)
{
return default(T);
}
await using var stream = File.OpenRead(filePath);
return await JsonSerializer.DeserializeAsync<T>(stream, JsonStorage.Options);
}
finally
{
semaphore.Release();
}
}
private static SemaphoreSlim GetLock(string filePath)
=> FileLocks.GetOrAdd(filePath, _ => new SemaphoreSlim(1, 1));
}
}