Repositories now read and write indented, human-readable JSON
(System.Text.Json, shared settings in JsonStorage). File names and folders
are unchanged apart from the extension.
XmlToJsonMigrator runs at startup before the app serves requests. It converts
the known Data/*.xml files under every year/mandator, verifies the JSON reads
back to the same data, and moves the XML to
{year}/backup/{mandator}/xml-{timestamp}/. Bank-statement XMLs in uploads/ are
never touched. Any failure stops startup and leaves that file's XML in place.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
164 lines
6.7 KiB
C#
164 lines
6.7 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>
|
|
/// One-time startup migration from the old XML data files to JSON. Looks at every
|
|
/// {DataPath}/{year}/{mandator}/Data folder, converts each known XML data file to its JSON
|
|
/// counterpart, verifies the JSON file reads back to the same data, and only then moves the
|
|
/// XML file to {DataPath}/{year}/backup/{mandator}/xml-{timestamp}/.
|
|
/// </summary>
|
|
public class XmlToJsonMigrator
|
|
{
|
|
private const string BackupFolder = "backup";
|
|
|
|
// Only these files are data files; bank statement XMLs live elsewhere (uploads/) and
|
|
// are never touched.
|
|
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<XmlToJsonMigrator> logger;
|
|
|
|
public XmlToJsonMigrator(ILogger<XmlToJsonMigrator> logger)
|
|
{
|
|
this.logger = logger;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Converts all XML data files below dataPath. Returns the number of converted files.
|
|
/// Throws if any file could not be converted, so the app doesn't start on a half-migrated
|
|
/// data folder; files that failed keep their XML in place.
|
|
/// </summary>
|
|
public async Task<int> MigrateAsync(string dataPath)
|
|
{
|
|
if (Directory.Exists(dataPath) == false)
|
|
{
|
|
return 0;
|
|
}
|
|
|
|
var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
|
|
var converted = 0;
|
|
var errors = new List<Exception>();
|
|
|
|
foreach (var yearDir in Directory.GetDirectories(dataPath).Where(d => int.TryParse(Path.GetFileName(d), out _)))
|
|
{
|
|
var mandatorDirs = Directory.GetDirectories(yearDir)
|
|
.Where(d => !Path.GetFileName(d).Equals(BackupFolder, StringComparison.OrdinalIgnoreCase));
|
|
|
|
foreach (var mandatorDir in mandatorDirs)
|
|
{
|
|
var dataDir = Path.Combine(mandatorDir, "Data");
|
|
if (Directory.Exists(dataDir) == false)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var backupDir = Path.Combine(yearDir, BackupFolder, Path.GetFileName(mandatorDir), "xml-" + timestamp);
|
|
|
|
foreach (var xmlPath in Directory.GetFiles(dataDir, "*.xml"))
|
|
{
|
|
if (DataFiles.TryGetValue(Path.GetFileNameWithoutExtension(xmlPath), out var type) == false)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
try
|
|
{
|
|
await ConvertAsync(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));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (converted > 0)
|
|
{
|
|
logger.LogInformation("Converted {Count} XML data files to JSON", converted);
|
|
}
|
|
|
|
if (errors.Count > 0)
|
|
{
|
|
throw new AggregateException("XML to JSON migration failed; see inner exceptions. Fix the files and restart.", errors);
|
|
}
|
|
|
|
return converted;
|
|
}
|
|
|
|
private async Task ConvertAsync(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;
|
|
}
|
|
}
|
|
}
|