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

280 lines
12 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Microsoft.Extensions.Logging;
using Schaad.Accounting.Models;
namespace Schaad.Accounting.Repositories
{
/// <summary>
/// Startup migration of the data folder, in two phases:
/// <list type="number">
/// <item>Restructure: move the old {year}/{mandator}/Data, {year}/{mandator}/uploads and
/// {year}/backup/{mandator} folders into the layout described in <see cref="DataFolders"/>.
/// Files are moved unchanged.</item>
/// <item>Convert: turn the known XML data files in each {mandator}/{year} folder into JSON,
/// verify the JSON reads back to the same data, then move the XML to
/// backup/{mandator}/{year}/xml-{timestamp}/.</item>
/// </list>
/// Both phases are idempotent. Nothing is ever overwritten; any problem is collected and thrown
/// at the end so the app does not start on a half-migrated folder.
/// </summary>
public class DataMigrator
{
// Only these files are data files; bank statement XMLs live in uploads/ and are never
// converted.
private static readonly Dictionary<string, Type> DataFiles = new(StringComparer.OrdinalIgnoreCase)
{
["Accounts"] = typeof(List<Account>),
["BankTransactions"] = typeof(List<BankTransaction>),
["BookingRules"] = typeof(List<BookingRule>),
["BookingTexts"] = typeof(List<BookingText>),
["SplitPredefinitions"] = typeof(List<SplitPredefinition>),
["SubClasses"] = typeof(List<SubClass>),
["Transactions"] = typeof(List<Transaction>)
};
private readonly ILogger<DataMigrator> logger;
public DataMigrator(ILogger<DataMigrator> logger)
{
this.logger = logger;
}
public record Result(int MovedFiles, int ConvertedFiles);
public async Task<Result> MigrateAsync(string dataPath)
{
if (Directory.Exists(dataPath) == false)
{
return new Result(0, 0);
}
var errors = new List<Exception>();
var moved = Restructure(dataPath, errors);
if (moved > 0)
{
logger.LogInformation("Moved {Count} files into the {{mandator}}/{{year}} folder layout", moved);
}
// Converting on top of a failed restructure could leave some files of a mandator/year
// converted and others still in the old place; fix the move first.
var converted = 0;
if (errors.Count == 0)
{
converted = await ConvertAsync(dataPath, errors);
if (converted > 0)
{
logger.LogInformation("Converted {Count} XML data files to JSON", converted);
}
}
if (errors.Count > 0)
{
throw new AggregateException("Data folder migration failed; see inner exceptions. Fix the files and restart.", errors);
}
return new Result(moved, converted);
}
private int Restructure(string dataPath, List<Exception> errors)
{
var moved = 0;
foreach (var yearDir in Directory.GetDirectories(dataPath).Where(d => DataFolders.IsYear(Path.GetFileName(d))))
{
var year = Path.GetFileName(yearDir);
foreach (var dir in Directory.GetDirectories(yearDir))
{
var name = Path.GetFileName(dir);
if (name.Equals(DataFolders.Backup, StringComparison.OrdinalIgnoreCase))
{
// {year}/backup/{mandator} -> backup/{mandator}/{year}
foreach (var mandatorBackupDir in Directory.GetDirectories(dir))
{
moved += MoveTree(mandatorBackupDir, Path.Combine(dataPath, DataFolders.Backup, Path.GetFileName(mandatorBackupDir), year), errors);
}
}
else
{
// {year}/{mandator}/Data -> {mandator}/{year}
// {year}/{mandator}/uploads -> uploads/{mandator}/{year}
moved += MoveTree(Path.Combine(dir, "Data"), Path.Combine(dataPath, name, year), errors);
moved += MoveTree(Path.Combine(dir, DataFolders.Uploads), Path.Combine(dataPath, DataFolders.Uploads, name, year), errors);
}
}
DeleteEmptyDirectories(yearDir);
if (Directory.Exists(yearDir))
{
logger.LogWarning("Old year folder {YearDir} still contains files that are not part of the known layout; left in place", yearDir);
}
}
return moved;
}
/// <summary>
/// Moves every file below source to the same relative path below target. A file whose
/// target already exists is dropped only if both are byte-identical; otherwise it is an
/// error and the source stays.
/// </summary>
private int MoveTree(string source, string target, List<Exception> errors)
{
if (Directory.Exists(source) == false)
{
return 0;
}
var moved = 0;
foreach (var file in Directory.GetFiles(source, "*", SearchOption.AllDirectories))
{
var targetFile = Path.Combine(target, Path.GetRelativePath(source, file));
try
{
if (File.Exists(targetFile))
{
if (File.ReadAllBytes(file).AsSpan().SequenceEqual(File.ReadAllBytes(targetFile)) == false)
{
throw new InvalidOperationException($"'{targetFile}' already exists with different content than '{file}'. Remove one of them.");
}
File.Delete(file);
}
else
{
Directory.CreateDirectory(Path.GetDirectoryName(targetFile)!);
File.Move(file, targetFile);
moved++;
}
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to move {File} to {Target}; the file was left in place", file, targetFile);
errors.Add(new InvalidOperationException($"Failed to move '{file}' to '{targetFile}'", ex));
}
}
DeleteEmptyDirectories(source);
return moved;
}
private async Task<int> ConvertAsync(string dataPath, List<Exception> errors)
{
var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
var converted = 0;
var mandatorDirs = Directory.GetDirectories(dataPath)
.Where(d => !DataFolders.IsReserved(Path.GetFileName(d)) && !DataFolders.IsYear(Path.GetFileName(d)));
foreach (var mandatorDir in mandatorDirs)
{
foreach (var yearDir in Directory.GetDirectories(mandatorDir).Where(d => DataFolders.IsYear(Path.GetFileName(d))))
{
var backupDir = Path.Combine(dataPath, DataFolders.Backup, Path.GetFileName(mandatorDir), Path.GetFileName(yearDir), "xml-" + timestamp);
foreach (var xmlPath in Directory.GetFiles(yearDir, "*.xml"))
{
if (DataFiles.TryGetValue(Path.GetFileNameWithoutExtension(xmlPath), out var type) == false)
{
continue;
}
try
{
await ConvertFileAsync(xmlPath, type, backupDir);
converted++;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to convert {XmlPath} to JSON; the XML file was left in place", xmlPath);
errors.Add(new InvalidOperationException($"Failed to convert '{xmlPath}' to JSON", ex));
}
}
}
}
return converted;
}
private async Task ConvertFileAsync(string xmlPath, Type type, string backupDir)
{
object data;
await using (var xmlStream = File.OpenRead(xmlPath))
{
data = new XmlSerializer(type).Deserialize(xmlStream);
}
var expected = JsonSerializer.SerializeToUtf8Bytes(data, type, JsonStorage.Options);
var jsonPath = Path.ChangeExtension(xmlPath, ".json");
if (File.Exists(jsonPath))
{
// Possible when a previous run wrote the JSON but crashed before moving the XML.
// Safe to finish only if the JSON holds exactly the XML's data.
var existing = await File.ReadAllBytesAsync(jsonPath);
if (expected.AsSpan().SequenceEqual(existing) == false)
{
throw new InvalidOperationException($"'{jsonPath}' already exists with different content than '{xmlPath}'. Remove one of them.");
}
}
else
{
var tmpPath = jsonPath + ".tmp";
await File.WriteAllBytesAsync(tmpPath, expected);
File.Move(tmpPath, jsonPath);
}
// Verify the written file reads back to the same data before giving up the XML.
await using (var jsonStream = File.OpenRead(jsonPath))
{
var roundTripped = await JsonSerializer.DeserializeAsync(jsonStream, type, JsonStorage.Options);
if (expected.AsSpan().SequenceEqual(JsonSerializer.SerializeToUtf8Bytes(roundTripped, type, JsonStorage.Options)) == false)
{
throw new InvalidOperationException($"'{jsonPath}' does not read back to the data in '{xmlPath}'.");
}
}
Directory.CreateDirectory(backupDir);
File.Move(xmlPath, GetFreeBackupPath(backupDir, Path.GetFileName(xmlPath)));
logger.LogInformation("Converted {XmlPath} to {JsonPath}", xmlPath, jsonPath);
}
/// <summary>
/// Never overwrite an existing backup: "Accounts.xml", then "Accounts (2).xml", ...
/// </summary>
private static string GetFreeBackupPath(string backupDir, string fileName)
{
var path = Path.Combine(backupDir, fileName);
for (var i = 2; File.Exists(path); i++)
{
path = Path.Combine(backupDir, $"{Path.GetFileNameWithoutExtension(fileName)} ({i}){Path.GetExtension(fileName)}");
}
return path;
}
/// <summary>
/// Removes dir and its subdirectories bottom-up, but only those that are empty.
/// </summary>
private static void DeleteEmptyDirectories(string dir)
{
if (Directory.Exists(dir) == false)
{
return;
}
foreach (var sub in Directory.GetDirectories(dir))
{
DeleteEmptyDirectories(sub);
}
if (Directory.EnumerateFileSystemEntries(dir).Any() == false)
{
Directory.Delete(dir);
}
}
}
}