AccountingNext/Schaad.Accounting.Db/Repositories/BaseRepository.cs
Claudio Schaad 6ab5ac133e Store data as JSON in a {mandator}/{year} layout, with startup migration (#2)
## Summary
- Repositories read and write **JSON instead of XML**. The JSON is human readable: indented, umlauts written as-is, property names as in the C# models (`BankTransactionText`), null values left out, computed properties (`Class`, `SubClass`, `IsFxAccount`, `ReadOnly`) not stored. Shared settings live in `JsonStorage`.
- **New data folder layout**, defined in `DataFolders`:
  ```
  {DataPath}/{mandator}/{year}/*.json          data files (no Data subfolder)
  {DataPath}/uploads/{mandator}/{year}/        imported bank statements (+ creditCard/)
  {DataPath}/backup/{mandator}/{year}/         backup zips and the original XML files
  ```
  `SettingsService` builds the new paths. `GetYearMandatorPath` / `GetLastYearMandatorPath` are removed because they now equal the data paths. The mandator dropdown lists mandators that have a folder for the selected year.
- New **`DataMigrator`** runs at startup, before the app serves requests, in two phases:
  1. **Restructure:** moves the old `{year}/{mandator}/Data`, `{year}/{mandator}/uploads` and `{year}/backup/{mandator}` folders into the new layout, unchanged.
  2. **Convert:** turns the seven known XML data files in each `{mandator}/{year}` folder into JSON, checks that the JSON reads back to the same data, then moves the XML to `backup/{mandator}/{year}/xml-{timestamp}/`. Bank-statement XMLs are moved but never converted.
- **Safety:** nothing is ever overwritten. If a file already exists at the target, the source is dropped only when both are identical; otherwise it is an error. Any error stops startup (conversion is skipped if a move failed), so the app never runs on a half-migrated folder. Old folders are removed only once empty; unexpected leftovers are logged and kept. Both phases can safely run again.
- `CLAUDE.md` updated for JSON storage and the new layout.

## Upgrade notes
- **Make a full copy of the data folder before the first start** of this version.
- **Don't run an older (XML) version** on a migrated data folder. It would find no data and start new XML files in the old layout.
- The backup zip now contains only the data files of the current mandator/year. Uploads live in their own folder.
- Empty folders from the old layout are not carried over; the app recreates them when needed.

## Test plan
- [x] `dotnet build`: no warnings
- [x] `dotnet test`: 77/77 pass, including 15 `DataMigratorTestShould` tests (old-layout data, uploads with subfolders and year backups moved; XML converted in old and new layout; readable JSON; values round-trip through the repositories; unknown XMLs not converted; rerun does nothing; stray files kept; crash recovery for moves and conversions; conflicting files; corrupt XML) and 4 `SettingsServiceTestShould` tests for the new paths and mandator list
- [x] Ran the app against a copy of the real data folder: 136 files moved, 82 XML files converted, no old year folders left, Accounts / Balance report / Transactions pages render
- [x] Checked every one of the 137 original files against a checksum manifest: uploads and other files byte-identical at their new location, every XML backup identical to the original, and JSON vs. XML compared field by field (11,807 records, 101,564 fields, 0 differences). 8 dates with a UTC offset in the XML are written as the same instant in local time, which is what the old app also had in memory after reading them.
- [ ] Start once on the real data folder and check the pages

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reviewed-on: #2
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
2026-10-22 12:00:17 +00:00

136 lines
4.9 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)
{
var filePath = Path.Combine(settingsService.GetDbPath(), fileName);
return cache.GetOrLoadAsync(filePath, async () => await LoadAsync<List<T>>(fileName) ?? 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 async Task SaveAsync<T>(T obj, string fileName)
{
var filePath = Path.Combine(settingsService.GetDbPath(), 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 async Task<T> LoadAsync<T>(string fileName)
{
var filePath = Path.Combine(settingsService.GetDbPath(), fileName);
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));
}
}