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 { /// /// 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}/. /// 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 DataFiles = new(StringComparer.OrdinalIgnoreCase) { ["Accounts"] = typeof(List), ["BankTransactions"] = typeof(List), ["BookingRules"] = typeof(List), ["BookingTexts"] = typeof(List), ["SplitPredefinitions"] = typeof(List), ["SubClasses"] = typeof(List), ["Transactions"] = typeof(List) }; private readonly ILogger logger; public XmlToJsonMigrator(ILogger logger) { this.logger = logger; } /// /// 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. /// public async Task MigrateAsync(string dataPath) { if (Directory.Exists(dataPath) == false) { return 0; } var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss"); var converted = 0; var errors = new List(); 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); } /// /// Never overwrite an existing backup: "Accounts.xml", then "Accounts (2).xml", ... /// 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; } } }