From 24bdfe60bcd00ec876646397074bd0854bddd643 Mon Sep 17 00:00:00 2001 From: Claudio Schaad Date: Thu, 22 Oct 2026 13:34:23 +0200 Subject: [PATCH 1/3] Store data as JSON instead of XML, with startup migration 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 --- CLAUDE.md | 10 +- Schaad.Accounting.Common/Models/Account.cs | 8 +- .../Models/Transaction.cs | 4 +- Schaad.Accounting.Db/JsonStorage.cs | 23 ++ .../Repositories/AccountRepository.cs | 2 +- .../Repositories/BankTransactionRepository.cs | 2 +- .../Repositories/BaseRepository.cs | 33 +-- .../Repositories/BookingRuleRepository.cs | 2 +- .../Repositories/BookingTextRepository.cs | 2 +- .../SplitPredefinitionRepository.cs | 2 +- .../Repositories/SubclassRepository.cs | 2 +- .../Repositories/TransactionRepository.cs | 2 +- Schaad.Accounting.Db/XmlToJsonMigrator.cs | 164 ++++++++++++++ .../XmlToJsonMigratorTestShould.cs | 209 ++++++++++++++++++ Schaad.Accounting.UI/Extensions.cs | 1 + Schaad.Accounting.UI/Program.cs | 10 +- 16 files changed, 432 insertions(+), 44 deletions(-) create mode 100644 Schaad.Accounting.Db/JsonStorage.cs create mode 100644 Schaad.Accounting.Db/XmlToJsonMigrator.cs create mode 100644 Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs diff --git a/CLAUDE.md b/CLAUDE.md index dc8e983..48f681a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,7 +22,7 @@ Tests live in `Schaad.Accounting.Tests` (xUnit + NSubstitute + Shouldly). There ## Architecture -**AccountingNext** is a Swiss personal accounting app built with ASP.NET Core 9 + Blazor (interactive server-side rendering) and Microsoft Fluent UI. Data is stored as XML files on disk — no database. +**AccountingNext** is a Swiss personal accounting app built with ASP.NET Core 9 + Blazor (interactive server-side rendering) and Microsoft Fluent UI. Data is stored as human-readable JSON files on disk (`System.Text.Json`, settings in `JsonStorage`) — no database. ### Projects @@ -30,7 +30,7 @@ Tests live in `Schaad.Accounting.Tests` (xUnit + NSubstitute + Shouldly). There |---|---| | `Schaad.Accounting.UI` | Blazor web app — pages, dialogs, layout | | `Schaad.Accounting.Services` | Business logic — balances, FX conversion, file import, charts | -| `Schaad.Accounting.Db` | Repository layer — XML serialization/deserialization | +| `Schaad.Accounting.Db` | Repository layer — JSON serialization/deserialization, XML-to-JSON startup migration | | `Schaad.Accounting.Common` | Shared models, DTOs, interfaces | ### Data flow @@ -39,11 +39,13 @@ Tests live in `Schaad.Accounting.Tests` (xUnit + NSubstitute + Shouldly). There Blazor Pages/Dialogs (UI) → Services (ViewService, FileService, ChartService) → Repositories (AccountRepository, TransactionRepository, …) - → XML files: {DataPath}/{year}/{mandator}/Data/*.xml + → JSON files: {DataPath}/{year}/{mandator}/Data/*.json ``` Data is multi-year and multi-mandator. Each combination has its own directory under `DataPath` (configured in `appsettings.Development.json`). When a new year is opened, the previous year's data is copied as the starting point. +The app used to store XML. On startup, `XmlToJsonMigrator` converts any remaining `Data/*.xml` files to JSON, verifies them, and moves the XML to `{DataPath}/{year}/backup/{mandator}/xml-{timestamp}/`. It throws (stopping startup) if a file can't be converted. Bank-statement XMLs in `uploads/` are never touched. + ### Key services - **ViewService** — aggregates account balances, applies FX rates, builds datasets for the UI @@ -89,4 +91,4 @@ public class FormattingTestShould } ``` -Repository tests that hit real XML I/O use a temp directory via `Path.GetTempPath()` and clean up in `IDisposable.Dispose`. Pure service tests use NSubstitute mocks for every dependency and don't touch the filesystem. +Repository tests that hit real file I/O use a temp directory via `Path.GetTempPath()` and clean up in `IDisposable.Dispose`. Pure service tests use NSubstitute mocks for every dependency and don't touch the filesystem. diff --git a/Schaad.Accounting.Common/Models/Account.cs b/Schaad.Accounting.Common/Models/Account.cs index 62460e3..7fce333 100644 --- a/Schaad.Accounting.Common/Models/Account.cs +++ b/Schaad.Accounting.Common/Models/Account.cs @@ -1,5 +1,5 @@ using System.ComponentModel.DataAnnotations; -using System.Xml.Serialization; +using System.Text.Json.Serialization; namespace Schaad.Accounting.Models { @@ -22,14 +22,14 @@ namespace Schaad.Accounting.Models [MaxLength(3)] public string Currency { get; set; } - [XmlIgnore] + [JsonIgnore] [Display(Name = "Klasse")] public int Class { get { return Number / 1000; } } - [XmlIgnore] + [JsonIgnore] [Display(Name = "Subklasse")] public int SubClass { @@ -54,7 +54,7 @@ namespace Schaad.Accounting.Models [Display(Name = "Letzter Banksaldo")] public decimal LastBankBalance { get; set; } - [XmlIgnore] + [JsonIgnore] public bool IsFxAccount { get { return string.IsNullOrEmpty(Currency) == false && Currency != "CHF"; } diff --git a/Schaad.Accounting.Common/Models/Transaction.cs b/Schaad.Accounting.Common/Models/Transaction.cs index e662b1a..e593ca9 100644 --- a/Schaad.Accounting.Common/Models/Transaction.cs +++ b/Schaad.Accounting.Common/Models/Transaction.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; -using System.Xml.Serialization; +using System.Text.Json.Serialization; namespace Schaad.Accounting.Models { @@ -44,7 +44,7 @@ namespace Schaad.Accounting.Models [Display(Name = "Währungskurs")] public decimal? FxRate { get; set; } - [XmlIgnore] + [JsonIgnore] public bool ReadOnly {get; set;} public Transaction() diff --git a/Schaad.Accounting.Db/JsonStorage.cs b/Schaad.Accounting.Db/JsonStorage.cs new file mode 100644 index 0000000..1a265f4 --- /dev/null +++ b/Schaad.Accounting.Db/JsonStorage.cs @@ -0,0 +1,23 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Schaad.Accounting.Repositories +{ + /// + /// Serializer settings shared by the repositories and the XML-to-JSON migration, so both + /// produce byte-identical files. + /// + public static class JsonStorage + { + public static readonly JsonSerializerOptions Options = new() + { + // Human readable: indented, and umlauts/quotes written as-is instead of \u escapes. + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + } +} diff --git a/Schaad.Accounting.Db/Repositories/AccountRepository.cs b/Schaad.Accounting.Db/Repositories/AccountRepository.cs index 33a59fa..1cb72e8 100644 --- a/Schaad.Accounting.Db/Repositories/AccountRepository.cs +++ b/Schaad.Accounting.Db/Repositories/AccountRepository.cs @@ -11,7 +11,7 @@ namespace Schaad.Accounting.Repositories { public class AccountRepository : BaseRepository, IAccountRepository { - private readonly string ACCOUNTS = "Accounts.xml"; + private readonly string ACCOUNTS = "Accounts.json"; public AccountRepository(ISettingsService settingsService, RepositoryCache cache, ILogger logger) : base(settingsService, cache, logger) diff --git a/Schaad.Accounting.Db/Repositories/BankTransactionRepository.cs b/Schaad.Accounting.Db/Repositories/BankTransactionRepository.cs index 8f6baa0..1d67981 100644 --- a/Schaad.Accounting.Db/Repositories/BankTransactionRepository.cs +++ b/Schaad.Accounting.Db/Repositories/BankTransactionRepository.cs @@ -10,7 +10,7 @@ namespace Schaad.Accounting.Repositories { public class BankTransactionRepository : BaseRepository, IBankTransactionRepository { - private readonly string BANK_TRANSACTIONS = "BankTransactions.xml"; + private readonly string BANK_TRANSACTIONS = "BankTransactions.json"; public BankTransactionRepository(ISettingsService settingsService, RepositoryCache cache, ILogger logger) : base(settingsService, cache, logger) diff --git a/Schaad.Accounting.Db/Repositories/BaseRepository.cs b/Schaad.Accounting.Db/Repositories/BaseRepository.cs index 59e62bc..7c6e712 100644 --- a/Schaad.Accounting.Db/Repositories/BaseRepository.cs +++ b/Schaad.Accounting.Db/Repositories/BaseRepository.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; -using System.Text; using System.Threading; using System.Threading.Tasks; -using System.Xml; -using System.Xml.Serialization; +using System.Text.Json; using Microsoft.Extensions.Logging; using Schaad.Accounting.Interfaces; @@ -58,7 +56,7 @@ namespace Schaad.Accounting.Repositories } /// - /// Load a list, cached per scope. First call reads the XML file; subsequent calls in + /// Load a list, cached per scope. First call reads the JSON file; subsequent calls in /// the same scope return the cached list. invalidates the entry. /// protected Task> LoadListAsync(string fileName) @@ -68,7 +66,7 @@ namespace Schaad.Accounting.Repositories } /// - /// Save an object to an xml file. Writes to a .tmp sibling and then atomically + /// 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. /// @@ -81,22 +79,9 @@ namespace Schaad.Accounting.Repositories await semaphore.WaitAsync(); try { - var settings = new XmlWriterSettings - { - Encoding = Encoding.UTF8, - Indent = true - }; - try { - // XmlSerializer is synchronous — serialize to memory, then write async. - using var memory = new MemoryStream(); - using (var writer = XmlWriter.Create(memory, settings)) - { - var serializer = new XmlSerializer(typeof(T)); - serializer.Serialize(writer, obj); - } - await File.WriteAllBytesAsync(tmpPath, memory.ToArray()); + await File.WriteAllBytesAsync(tmpPath, JsonSerializer.SerializeToUtf8Bytes(obj, JsonStorage.Options)); // File.Move has no async form in .NET 9. File.Move(tmpPath, filePath, overwrite: true); @@ -120,7 +105,7 @@ namespace Schaad.Accounting.Repositories } /// - /// Load an object from an xml file (uncached; used for one-off reads such as file + /// Load an object from a JSON file (uncached; used for one-off reads such as file /// existence bootstrapping). Prefer for repository reads. /// protected async Task LoadAsync(string fileName) @@ -136,10 +121,8 @@ namespace Schaad.Accounting.Repositories return default(T); } - var bytes = await File.ReadAllBytesAsync(filePath); - using var memory = new MemoryStream(bytes); - var serializer = new XmlSerializer(typeof(T)); - return (T)serializer.Deserialize(memory); + await using var stream = File.OpenRead(filePath); + return await JsonSerializer.DeserializeAsync(stream, JsonStorage.Options); } finally { diff --git a/Schaad.Accounting.Db/Repositories/BookingRuleRepository.cs b/Schaad.Accounting.Db/Repositories/BookingRuleRepository.cs index 5743677..ddcfd28 100644 --- a/Schaad.Accounting.Db/Repositories/BookingRuleRepository.cs +++ b/Schaad.Accounting.Db/Repositories/BookingRuleRepository.cs @@ -10,7 +10,7 @@ namespace Schaad.Accounting.Repositories { public class BookingRuleRepository : BaseRepository, IBookingRuleRepository { - private readonly string BOOKING_RULES = "BookingRules.xml"; + private readonly string BOOKING_RULES = "BookingRules.json"; public BookingRuleRepository(ISettingsService settingsService, RepositoryCache cache, ILogger logger) : base(settingsService, cache, logger) diff --git a/Schaad.Accounting.Db/Repositories/BookingTextRepository.cs b/Schaad.Accounting.Db/Repositories/BookingTextRepository.cs index 53969b9..a8c9ee7 100644 --- a/Schaad.Accounting.Db/Repositories/BookingTextRepository.cs +++ b/Schaad.Accounting.Db/Repositories/BookingTextRepository.cs @@ -10,7 +10,7 @@ namespace Schaad.Accounting.Repositories { public class BookingTextRepository : BaseRepository, IBookingTextRepository { - private readonly string BOOKING_TEXTS = "BookingTexts.xml"; + private readonly string BOOKING_TEXTS = "BookingTexts.json"; public BookingTextRepository(ISettingsService settingsService, RepositoryCache cache, ILogger logger) : base(settingsService, cache, logger) diff --git a/Schaad.Accounting.Db/Repositories/SplitPredefinitionRepository.cs b/Schaad.Accounting.Db/Repositories/SplitPredefinitionRepository.cs index b8f94ce..584d58f 100644 --- a/Schaad.Accounting.Db/Repositories/SplitPredefinitionRepository.cs +++ b/Schaad.Accounting.Db/Repositories/SplitPredefinitionRepository.cs @@ -10,7 +10,7 @@ namespace Schaad.Accounting.Repositories { public class SplitPredefinitionRepository : BaseRepository, ISplitPredefinitionRepository { - private readonly string SPLIT_PREDEFINITION = "SplitPredefinitions.xml"; + private readonly string SPLIT_PREDEFINITION = "SplitPredefinitions.json"; public SplitPredefinitionRepository(ISettingsService settingsService, RepositoryCache cache, ILogger logger) : base(settingsService, cache, logger) diff --git a/Schaad.Accounting.Db/Repositories/SubclassRepository.cs b/Schaad.Accounting.Db/Repositories/SubclassRepository.cs index b7f5878..7d44d90 100644 --- a/Schaad.Accounting.Db/Repositories/SubclassRepository.cs +++ b/Schaad.Accounting.Db/Repositories/SubclassRepository.cs @@ -11,7 +11,7 @@ namespace Schaad.Accounting.Repositories public class SubclassRepository : BaseRepository, ISubclassRepository { private readonly Dictionary classes = new Dictionary(); - private readonly string SUBCLASSES = "SubClasses.xml"; + private readonly string SUBCLASSES = "SubClasses.json"; public SubclassRepository(ISettingsService settingsService, RepositoryCache cache, ILogger logger) : base(settingsService, cache, logger) diff --git a/Schaad.Accounting.Db/Repositories/TransactionRepository.cs b/Schaad.Accounting.Db/Repositories/TransactionRepository.cs index 4472517..981ad5a 100644 --- a/Schaad.Accounting.Db/Repositories/TransactionRepository.cs +++ b/Schaad.Accounting.Db/Repositories/TransactionRepository.cs @@ -11,7 +11,7 @@ namespace Schaad.Accounting.Repositories public class TransactionRepository : BaseRepository, ITransactionRepository { private readonly IAccountRepository accountRepository; - private readonly string TRANSACTIONS = "Transactions.xml"; + private readonly string TRANSACTIONS = "Transactions.json"; public TransactionRepository(ISettingsService settingsService, RepositoryCache cache, IAccountRepository accountRepository, ILogger logger) : base(settingsService, cache, logger) diff --git a/Schaad.Accounting.Db/XmlToJsonMigrator.cs b/Schaad.Accounting.Db/XmlToJsonMigrator.cs new file mode 100644 index 0000000..2c7305e --- /dev/null +++ b/Schaad.Accounting.Db/XmlToJsonMigrator.cs @@ -0,0 +1,164 @@ +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; + } + } +} diff --git a/Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs b/Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs new file mode 100644 index 0000000..c2c41ea --- /dev/null +++ b/Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs @@ -0,0 +1,209 @@ +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using Schaad.Accounting.Interfaces; +using Schaad.Accounting.Repositories; +using Shouldly; + +namespace Schaad.Accounting.Tests; + +public class XmlToJsonMigratorTestShould : IDisposable +{ + // Shaped like a file written by the old XmlSerializer-based repository, including the + // BOM-less declaration, namespaces and an xsi:nil FxRate. + private const string TransactionsXml = """ + + + + t1 + 2026-01-30T00:00:00 + 2026-01-31T00:00:00 + Gebäudeversicherung + 114.20 + a1 + a2 + + + + t2 + 2026-02-01T00:00:00 + 2026-02-01T00:00:00 + EUR Zahlung + -50.5 + a2 + a1 + 0.9312 + + + """; + + private const string AccountsXml = """ + + + + a1 + 1020 + Bank + CHF + 1000.50 + 0 + + + """; + + private readonly string dataPath; + private readonly string dataDir; + private readonly XmlToJsonMigrator sut = new(NullLogger.Instance); + + public XmlToJsonMigratorTestShould() + { + dataPath = Path.Combine(Path.GetTempPath(), "AccountingNext-tests-" + Guid.NewGuid().ToString("N")); + dataDir = Path.Combine(dataPath, "2026", "Mandator", "Data"); + Directory.CreateDirectory(dataDir); + } + + public void Dispose() + { + if (Directory.Exists(dataPath)) + { + Directory.Delete(dataPath, recursive: true); + } + } + + [Fact] + public async Task WriteJsonAndMoveXmlToBackupWhenDataFolderHasXml() + { + File.WriteAllText(Path.Combine(dataDir, "Transactions.xml"), TransactionsXml); + + var converted = await sut.MigrateAsync(dataPath); + + converted.ShouldBe(1); + File.Exists(Path.Combine(dataDir, "Transactions.json")).ShouldBeTrue(); + File.Exists(Path.Combine(dataDir, "Transactions.xml")).ShouldBeFalse(); + var backup = Directory.GetFiles(Path.Combine(dataPath, "2026", "backup", "Mandator"), "Transactions.xml", SearchOption.AllDirectories); + backup.Length.ShouldBe(1); + File.ReadAllText(backup[0]).ShouldBe(TransactionsXml); + } + + [Fact] + public async Task WriteHumanReadableJsonWhenConvertingXml() + { + File.WriteAllText(Path.Combine(dataDir, "Transactions.xml"), TransactionsXml); + + await sut.MigrateAsync(dataPath); + + var json = File.ReadAllText(Path.Combine(dataDir, "Transactions.json")); + json.ShouldContain("\"text\": \"Gebäudeversicherung\""); + json.ShouldContain("\n \"id\": \"t1\""); + json.ShouldNotContain("\"fxRate\": null"); + json.ShouldNotContain("readOnly"); + } + + [Fact] + public async Task PreserveAllValuesWhenReadingMigratedDataThroughRepository() + { + File.WriteAllText(Path.Combine(dataDir, "Transactions.xml"), TransactionsXml); + File.WriteAllText(Path.Combine(dataDir, "Accounts.xml"), AccountsXml); + + await sut.MigrateAsync(dataPath); + + var settingsService = Substitute.For(); + settingsService.GetDbPath().Returns(dataDir); + settingsService.GetLastYearDbPath().Returns(Path.Combine(dataPath, "no-such-dir")); + var accountRepository = new AccountRepository(settingsService, new RepositoryCache(), NullLogger.Instance); + var transactionRepository = new TransactionRepository(settingsService, new RepositoryCache(), accountRepository, NullLogger.Instance); + var transactions = await transactionRepository.GetTransactionListAsync(); + var accounts = await accountRepository.GetAccountListAsync(); + + transactions.Count.ShouldBe(2); + transactions[0].Text.ShouldBe("Gebäudeversicherung"); + transactions[0].Value.ShouldBe(114.20m); + transactions[0].ValueDate.ShouldBe(new DateTime(2026, 1, 30)); + transactions[0].BookingDate.ShouldBe(new DateTime(2026, 1, 31)); + transactions[0].OriginAccountId.ShouldBe("a1"); + transactions[0].TargetAccountId.ShouldBe("a2"); + transactions[0].FxRate.ShouldBeNull(); + transactions[1].Value.ShouldBe(-50.5m); + transactions[1].FxRate.ShouldBe(0.9312m); + accounts.Single().Number.ShouldBe(1020); + accounts.Single().StartBalance.ShouldBe(1000.50m); + } + + [Fact] + public async Task LeaveUnknownXmlFilesUntouchedWhenMigrating() + { + var statement = Path.Combine(dataDir, "camt053.xml"); + var upload = Path.Combine(dataPath, "2026", "Mandator", "uploads", "Accounts.xml"); + Directory.CreateDirectory(Path.GetDirectoryName(upload)!); + File.WriteAllText(statement, ""); + File.WriteAllText(upload, ""); + + var converted = await sut.MigrateAsync(dataPath); + + converted.ShouldBe(0); + File.Exists(statement).ShouldBeTrue(); + File.Exists(upload).ShouldBeTrue(); + } + + [Fact] + public async Task SkipBackupFolderWhenScanningMandators() + { + var backupData = Path.Combine(dataPath, "2026", "backup", "Data"); + Directory.CreateDirectory(backupData); + File.WriteAllText(Path.Combine(backupData, "Accounts.xml"), AccountsXml); + + var converted = await sut.MigrateAsync(dataPath); + + converted.ShouldBe(0); + File.Exists(Path.Combine(backupData, "Accounts.xml")).ShouldBeTrue(); + } + + [Fact] + public async Task DoNothingWhenAllDataIsAlreadyJson() + { + File.WriteAllText(Path.Combine(dataDir, "Accounts.xml"), AccountsXml); + await sut.MigrateAsync(dataPath); + + var converted = await sut.MigrateAsync(dataPath); + + converted.ShouldBe(0); + } + + [Fact] + public async Task FinishMigrationWhenJsonAlreadyMatchesXml() + { + // Simulates a crash after the JSON was written but before the XML was moved. + File.WriteAllText(Path.Combine(dataDir, "Accounts.xml"), AccountsXml); + await sut.MigrateAsync(dataPath); + File.WriteAllText(Path.Combine(dataDir, "Accounts.xml"), AccountsXml); + + var converted = await sut.MigrateAsync(dataPath); + + converted.ShouldBe(1); + File.Exists(Path.Combine(dataDir, "Accounts.xml")).ShouldBeFalse(); + } + + [Fact] + public async Task ThrowAndKeepBothFilesWhenJsonExistsWithDifferentContent() + { + File.WriteAllText(Path.Combine(dataDir, "Accounts.xml"), AccountsXml); + File.WriteAllText(Path.Combine(dataDir, "Accounts.json"), "[]"); + + await Should.ThrowAsync(() => sut.MigrateAsync(dataPath)); + + File.Exists(Path.Combine(dataDir, "Accounts.xml")).ShouldBeTrue(); + File.ReadAllText(Path.Combine(dataDir, "Accounts.json")).ShouldBe("[]"); + } + + [Fact] + public async Task ConvertRemainingFilesAndThrowWhenOneXmlIsCorrupt() + { + File.WriteAllText(Path.Combine(dataDir, "Accounts.xml"), AccountsXml); + File.WriteAllText(Path.Combine(dataDir, "Transactions.xml"), ""); + + await Should.ThrowAsync(() => sut.MigrateAsync(dataPath)); + + File.Exists(Path.Combine(dataDir, "Accounts.json")).ShouldBeTrue(); + File.Exists(Path.Combine(dataDir, "Transactions.xml")).ShouldBeTrue(); + File.Exists(Path.Combine(dataDir, "Transactions.json")).ShouldBeFalse(); + } +} diff --git a/Schaad.Accounting.UI/Extensions.cs b/Schaad.Accounting.UI/Extensions.cs index 1bb2772..d9998b2 100644 --- a/Schaad.Accounting.UI/Extensions.cs +++ b/Schaad.Accounting.UI/Extensions.cs @@ -16,6 +16,7 @@ namespace Schaad.Accounting.UI // can safely become Scoped. services.AddSingleton(); + services.AddSingleton(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/Schaad.Accounting.UI/Program.cs b/Schaad.Accounting.UI/Program.cs index 5475d30..51b5740 100644 --- a/Schaad.Accounting.UI/Program.cs +++ b/Schaad.Accounting.UI/Program.cs @@ -2,6 +2,7 @@ using System.Globalization; using Microsoft.AspNetCore.Localization; using Microsoft.Extensions.Options; using Microsoft.FluentUI.AspNetCore.Components; +using Schaad.Accounting.Repositories; using Schaad.Accounting.Datasets; using Schaad.Accounting.UI.Components; @@ -9,7 +10,7 @@ namespace Schaad.Accounting.UI { public class Program { - public static void Main(string[] args) + public static async Task Main(string[] args) { var builder = WebApplication.CreateBuilder(args); @@ -29,6 +30,11 @@ namespace Schaad.Accounting.UI var app = builder.Build(); + // Convert any remaining XML data files to JSON before serving requests. Throws (and + // stops startup) if a file can't be converted, rather than running on partial data. + await app.Services.GetRequiredService() + .MigrateAsync(app.Services.GetRequiredService().DataPath); + // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { @@ -52,7 +58,7 @@ namespace Schaad.Accounting.UI app.MapRazorComponents() .AddInteractiveServerRenderMode(); - app.Run(); + await app.RunAsync(); } } } -- 2.39.5 From acf6753d077f9dca2d25ee1c9e275e6af837dab7 Mon Sep 17 00:00:00 2001 From: Claudio Schaad Date: Thu, 22 Oct 2026 13:44:24 +0200 Subject: [PATCH 2/3] Use PascalCase property names in JSON data files Property names now match the C# models (BankTransactionText instead of bankTransactionText). Reading stays case-insensitive. The migrator test now checks casing case-sensitively; Shouldly's ShouldContain ignores case by default, so it never actually checked it. Co-Authored-By: Claude Opus 5.5 --- Schaad.Accounting.Db/JsonStorage.cs | 1 - Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs | 8 ++++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/Schaad.Accounting.Db/JsonStorage.cs b/Schaad.Accounting.Db/JsonStorage.cs index 1a265f4..50b518e 100644 --- a/Schaad.Accounting.Db/JsonStorage.cs +++ b/Schaad.Accounting.Db/JsonStorage.cs @@ -15,7 +15,6 @@ namespace Schaad.Accounting.Repositories // Human readable: indented, and umlauts/quotes written as-is instead of \u escapes. WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; diff --git a/Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs b/Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs index c2c41ea..e910795 100644 --- a/Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs +++ b/Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs @@ -92,10 +92,10 @@ public class XmlToJsonMigratorTestShould : IDisposable await sut.MigrateAsync(dataPath); var json = File.ReadAllText(Path.Combine(dataDir, "Transactions.json")); - json.ShouldContain("\"text\": \"Gebäudeversicherung\""); - json.ShouldContain("\n \"id\": \"t1\""); - json.ShouldNotContain("\"fxRate\": null"); - json.ShouldNotContain("readOnly"); + json.ShouldContain("\"Text\": \"Gebäudeversicherung\"", Case.Sensitive); + json.ShouldContain("\n \"Id\": \"t1\"", Case.Sensitive); + json.ShouldNotContain("FxRate\": null", Case.Insensitive); + json.ShouldNotContain("ReadOnly", Case.Insensitive); } [Fact] -- 2.39.5 From cbc1cd3f1f5704e611574cfa178dafa3acd053d6 Mon Sep 17 00:00:00 2001 From: Claudio Schaad Date: Thu, 22 Oct 2026 13:57:58 +0200 Subject: [PATCH 3/3] Restructure data folder to {mandator}/{year}, uploads and backup at root New layout below DataPath (defined in DataFolders): {mandator}/{year}/*.json uploads/{mandator}/{year}/ backup/{mandator}/{year}/ XmlToJsonMigrator becomes DataMigrator with two phases: first move the old {year}/{mandator}/Data, uploads and {year}/backup folders into the new layout unchanged, then convert the XML data files to JSON. Nothing is overwritten; an identical file at the target is dropped, a different one stops startup. Old folders are removed only once empty. SettingsService builds the new paths; GetYearMandatorPath and GetLastYearMandatorPath are removed as they now equal the data paths. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 16 +- Schaad.Accounting.Common/DataFolders.cs | 30 ++ .../Interfaces/ISettingsService.cs | 6 +- Schaad.Accounting.Db/DataMigrator.cs | 280 ++++++++++++++++ Schaad.Accounting.Db/JsonStorage.cs | 2 +- Schaad.Accounting.Db/XmlToJsonMigrator.cs | 164 ---------- Schaad.Accounting.Services/FileService.cs | 4 +- Schaad.Accounting.Services/SettingsService.cs | 79 ++--- .../DataMigratorTestShould.cs | 299 ++++++++++++++++++ .../SettingsServiceTestShould.cs | 63 ++++ .../XmlToJsonMigratorTestShould.cs | 209 ------------ Schaad.Accounting.UI/Extensions.cs | 2 +- Schaad.Accounting.UI/Program.cs | 6 +- 13 files changed, 721 insertions(+), 439 deletions(-) create mode 100644 Schaad.Accounting.Common/DataFolders.cs create mode 100644 Schaad.Accounting.Db/DataMigrator.cs delete mode 100644 Schaad.Accounting.Db/XmlToJsonMigrator.cs create mode 100644 Schaad.Accounting.Tests/DataMigratorTestShould.cs create mode 100644 Schaad.Accounting.Tests/SettingsServiceTestShould.cs delete mode 100644 Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs diff --git a/CLAUDE.md b/CLAUDE.md index 48f681a..b7e5451 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,7 +30,7 @@ Tests live in `Schaad.Accounting.Tests` (xUnit + NSubstitute + Shouldly). There |---|---| | `Schaad.Accounting.UI` | Blazor web app — pages, dialogs, layout | | `Schaad.Accounting.Services` | Business logic — balances, FX conversion, file import, charts | -| `Schaad.Accounting.Db` | Repository layer — JSON serialization/deserialization, XML-to-JSON startup migration | +| `Schaad.Accounting.Db` | Repository layer — JSON serialization/deserialization, startup data migration | | `Schaad.Accounting.Common` | Shared models, DTOs, interfaces | ### Data flow @@ -39,12 +39,20 @@ Tests live in `Schaad.Accounting.Tests` (xUnit + NSubstitute + Shouldly). There Blazor Pages/Dialogs (UI) → Services (ViewService, FileService, ChartService) → Repositories (AccountRepository, TransactionRepository, …) - → JSON files: {DataPath}/{year}/{mandator}/Data/*.json + → JSON files: {DataPath}/{mandator}/{year}/*.json ``` -Data is multi-year and multi-mandator. Each combination has its own directory under `DataPath` (configured in `appsettings.Development.json`). When a new year is opened, the previous year's data is copied as the starting point. +Data is multi-mandator and multi-year. The layout below `DataPath` (configured in `appsettings.Development.json`) is defined in `DataFolders`: -The app used to store XML. On startup, `XmlToJsonMigrator` converts any remaining `Data/*.xml` files to JSON, verifies them, and moves the XML to `{DataPath}/{year}/backup/{mandator}/xml-{timestamp}/`. It throws (stopping startup) if a file can't be converted. Bank-statement XMLs in `uploads/` are never touched. +``` +{DataPath}/{mandator}/{year}/*.json data files +{DataPath}/uploads/{mandator}/{year}/ imported bank statements (+ creditCard/) +{DataPath}/backup/{mandator}/{year}/ backup zips and migrated XML files +``` + +When a new year is opened, the previous year's data is copied as the starting point. + +The app used to store XML in `{DataPath}/{year}/{mandator}/Data/`, with uploads and backups inside each year. On startup, `DataMigrator` moves any old-layout folders into the layout above, then converts remaining XML data files to JSON, verifies them, and moves the XML to `backup/{mandator}/{year}/xml-{timestamp}/`. It never overwrites files and throws (stopping startup) if anything fails. Bank-statement XMLs are moved but never converted. ### Key services diff --git a/Schaad.Accounting.Common/DataFolders.cs b/Schaad.Accounting.Common/DataFolders.cs new file mode 100644 index 0000000..7281212 --- /dev/null +++ b/Schaad.Accounting.Common/DataFolders.cs @@ -0,0 +1,30 @@ +namespace Schaad.Accounting +{ + /// + /// Folder layout below DataPath: + /// + /// {DataPath}/{mandator}/{year}/*.json data files + /// {DataPath}/uploads/{mandator}/{year}/ imported bank statements (+ creditCard/) + /// {DataPath}/backup/{mandator}/{year}/ backup zips and migrated XML files + /// + /// + public static class DataFolders + { + public const string Uploads = "uploads"; + public const string Backup = "backup"; + public const string CreditCard = "creditCard"; + + /// + /// True for the top-level folders that are not mandators. + /// + public static bool IsReserved(string folderName) + => folderName.Equals(Uploads, System.StringComparison.OrdinalIgnoreCase) + || folderName.Equals(Backup, System.StringComparison.OrdinalIgnoreCase); + + /// + /// Year folders are four-digit numbers. + /// + public static bool IsYear(string folderName) + => folderName.Length == 4 && int.TryParse(folderName, out _); + } +} diff --git a/Schaad.Accounting.Common/Interfaces/ISettingsService.cs b/Schaad.Accounting.Common/Interfaces/ISettingsService.cs index 150448d..4e6c279 100644 --- a/Schaad.Accounting.Common/Interfaces/ISettingsService.cs +++ b/Schaad.Accounting.Common/Interfaces/ISettingsService.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using Schaad.Accounting.Datasets; namespace Schaad.Accounting.Interfaces @@ -16,10 +16,6 @@ namespace Schaad.Accounting.Interfaces void SetMandator(string mandator); - string GetYearMandatorPath(); - - string GetLastYearMandatorPath(); - string GetBackupFilePath(); string GetUploadPath(); diff --git a/Schaad.Accounting.Db/DataMigrator.cs b/Schaad.Accounting.Db/DataMigrator.cs new file mode 100644 index 0000000..1100ab6 --- /dev/null +++ b/Schaad.Accounting.Db/DataMigrator.cs @@ -0,0 +1,280 @@ +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 +{ + /// + /// Startup migration of the data folder, in two phases: + /// + /// Restructure: move the old {year}/{mandator}/Data, {year}/{mandator}/uploads and + /// {year}/backup/{mandator} folders into the layout described in . + /// Files are moved unchanged. + /// 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}/. + /// + /// 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. + /// + public class DataMigrator + { + // Only these files are data files; bank statement XMLs live in uploads/ and are never + // converted. + 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 DataMigrator(ILogger logger) + { + this.logger = logger; + } + + public record Result(int MovedFiles, int ConvertedFiles); + + public async Task MigrateAsync(string dataPath) + { + if (Directory.Exists(dataPath) == false) + { + return new Result(0, 0); + } + + var errors = new List(); + + 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 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; + } + + /// + /// 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. + /// + private int MoveTree(string source, string target, List 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 ConvertAsync(string dataPath, List 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); + } + + /// + /// 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; + } + + /// + /// Removes dir and its subdirectories bottom-up, but only those that are empty. + /// + 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); + } + } + } +} diff --git a/Schaad.Accounting.Db/JsonStorage.cs b/Schaad.Accounting.Db/JsonStorage.cs index 50b518e..267a9fd 100644 --- a/Schaad.Accounting.Db/JsonStorage.cs +++ b/Schaad.Accounting.Db/JsonStorage.cs @@ -5,7 +5,7 @@ using System.Text.Json.Serialization; namespace Schaad.Accounting.Repositories { /// - /// Serializer settings shared by the repositories and the XML-to-JSON migration, so both + /// Serializer settings shared by the repositories and the data migration, so both /// produce byte-identical files. /// public static class JsonStorage diff --git a/Schaad.Accounting.Db/XmlToJsonMigrator.cs b/Schaad.Accounting.Db/XmlToJsonMigrator.cs deleted file mode 100644 index 2c7305e..0000000 --- a/Schaad.Accounting.Db/XmlToJsonMigrator.cs +++ /dev/null @@ -1,164 +0,0 @@ -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; - } - } -} diff --git a/Schaad.Accounting.Services/FileService.cs b/Schaad.Accounting.Services/FileService.cs index 14960ac..c2e4069 100644 --- a/Schaad.Accounting.Services/FileService.cs +++ b/Schaad.Accounting.Services/FileService.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.IO.Compression; using System.Linq; using System.Text; @@ -42,7 +42,7 @@ namespace Schaad.Accounting.Services public string Backup() { var outpath = settingsService.GetBackupFilePath(); - var sourcepath = settingsService.GetYearMandatorPath(); + var sourcepath = settingsService.GetDbPath(); ZipFile.CreateFromDirectory(sourcepath, outpath); return $"Backup '{outpath}' erfolgreich erstellt"; } diff --git a/Schaad.Accounting.Services/SettingsService.cs b/Schaad.Accounting.Services/SettingsService.cs index 5de9255..27c7b8e 100644 --- a/Schaad.Accounting.Services/SettingsService.cs +++ b/Schaad.Accounting.Services/SettingsService.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -46,10 +46,21 @@ namespace Schaad.Accounting.Services return mandator; } + /// + /// Mandators that have a folder for the given year. + /// public IReadOnlyList GetMandators(int year) { - var path = Path.Combine(GetSettings().DataPath, year.ToString()); - return Directory.GetDirectories(path).Select(Path.GetFileName).Where(d => !d.Equals("Backup", StringComparison.InvariantCultureIgnoreCase)).ToList(); + var dataPath = GetSettings().DataPath; + if (Directory.Exists(dataPath) == false) + { + return []; + } + return Directory.GetDirectories(dataPath) + .Where(d => Directory.Exists(Path.Combine(d, year.ToString()))) + .Select(Path.GetFileName) + .Where(name => !DataFolders.IsReserved(name) && !DataFolders.IsYear(name)) + .ToList(); } public void SetMandator(string mandator) @@ -57,76 +68,44 @@ namespace Schaad.Accounting.Services this.mandator = mandator; } - public string GetYearMandatorPath() - { - var path = Path.Combine(GetSettings().DataPath, year.ToString(), mandator); - if (Directory.Exists(path) == false) - { - Directory.CreateDirectory(path); - } - return path; - } - - public string GetLastYearMandatorPath() - { - var path = Path.Combine(GetSettings().DataPath, (year - 1).ToString(), mandator); - return path; - } - public string GetBackupFilePath() { - var backupPath = Path.Combine(GetSettings().DataPath, year.ToString(), "backup", mandator); - if (Directory.Exists(backupPath) == false) - { - Directory.CreateDirectory(backupPath); - } - var backupFilePath = Path.Combine(backupPath, DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip"); - return backupFilePath; + var backupPath = EnsureDirectory(Path.Combine(GetSettings().DataPath, DataFolders.Backup, mandator, year.ToString())); + return Path.Combine(backupPath, DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip"); } public string GetUploadPath() { - var uploadPath = Path.Combine(GetYearMandatorPath(), "uploads"); - if (Directory.Exists(uploadPath) == false) - { - Directory.CreateDirectory(uploadPath); - } - return uploadPath; + return EnsureDirectory(Path.Combine(GetSettings().DataPath, DataFolders.Uploads, mandator, year.ToString())); } public string GetCreditCardStatementPath() { - var path = Path.Combine(GetUploadPath(), "creditCard"); - if (Directory.Exists(path) == false) - { - Directory.CreateDirectory(path); - } - return path; + return EnsureDirectory(Path.Combine(GetUploadPath(), DataFolders.CreditCard)); } public string GetDbPath() { - var path = Path.Combine(GetYearMandatorPath(), "Data"); - if (Directory.Exists(path) == false) - { - Directory.CreateDirectory(path); - } - return path; + return EnsureDirectory(Path.Combine(GetSettings().DataPath, mandator, year.ToString())); } public string GetLastYearDbPath() { - var path = Path.Combine(GetLastYearMandatorPath(), "Data"); - if (Directory.Exists(path) == false) - { - Directory.CreateDirectory(path); - } - return path; + return EnsureDirectory(Path.Combine(GetSettings().DataPath, mandator, (year - 1).ToString())); } public SettingsDataset GetSettings() { return settingsDataset; } + + private static string EnsureDirectory(string path) + { + if (Directory.Exists(path) == false) + { + Directory.CreateDirectory(path); + } + return path; + } } } \ No newline at end of file diff --git a/Schaad.Accounting.Tests/DataMigratorTestShould.cs b/Schaad.Accounting.Tests/DataMigratorTestShould.cs new file mode 100644 index 0000000..b6911fa --- /dev/null +++ b/Schaad.Accounting.Tests/DataMigratorTestShould.cs @@ -0,0 +1,299 @@ +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using Schaad.Accounting.Interfaces; +using Schaad.Accounting.Repositories; +using Shouldly; + +namespace Schaad.Accounting.Tests; + +public class DataMigratorTestShould : IDisposable +{ + // Shaped like a file written by the old XmlSerializer-based repository, including the + // BOM-less declaration, namespaces and an xsi:nil FxRate. + private const string TransactionsXml = """ + + + + t1 + 2026-01-30T00:00:00 + 2026-01-31T00:00:00 + Gebäudeversicherung + 114.20 + a1 + a2 + + + + t2 + 2026-02-01T00:00:00 + 2026-02-01T00:00:00 + EUR Zahlung + -50.5 + a2 + a1 + 0.9312 + + + """; + + private const string AccountsXml = """ + + + + a1 + 1020 + Bank + CHF + 1000.50 + 0 + + + """; + + private readonly string dataPath; + // Old layout: {year}/{mandator}/Data + private readonly string oldDataDir; + // New layout: {mandator}/{year} + private readonly string newDataDir; + private readonly DataMigrator sut = new(NullLogger.Instance); + + public DataMigratorTestShould() + { + dataPath = Path.Combine(Path.GetTempPath(), "AccountingNext-tests-" + Guid.NewGuid().ToString("N")); + oldDataDir = Path.Combine(dataPath, "2026", "Mandator", "Data"); + newDataDir = Path.Combine(dataPath, "Mandator", "2026"); + Directory.CreateDirectory(dataPath); + } + + public void Dispose() + { + if (Directory.Exists(dataPath)) + { + Directory.Delete(dataPath, recursive: true); + } + } + + private static void WriteFile(string path, string content) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + } + + private string[] XmlBackups(string fileName) + => Directory.GetFiles(Path.Combine(dataPath, "backup", "Mandator", "2026"), fileName, SearchOption.AllDirectories); + + [Fact] + public async Task ConvertOldLayoutXmlToJsonInMandatorYearFolderWhenMigrating() + { + WriteFile(Path.Combine(oldDataDir, "Transactions.xml"), TransactionsXml); + + var result = await sut.MigrateAsync(dataPath); + + result.ShouldBe(new DataMigrator.Result(MovedFiles: 1, ConvertedFiles: 1)); + File.Exists(Path.Combine(newDataDir, "Transactions.json")).ShouldBeTrue(); + File.Exists(Path.Combine(newDataDir, "Transactions.xml")).ShouldBeFalse(); + Directory.Exists(Path.Combine(dataPath, "2026")).ShouldBeFalse(); + var backup = XmlBackups("Transactions.xml"); + backup.Length.ShouldBe(1); + File.ReadAllText(backup[0]).ShouldBe(TransactionsXml); + } + + [Fact] + public async Task MoveOldLayoutJsonUnchangedWhenMigrating() + { + WriteFile(Path.Combine(oldDataDir, "Accounts.json"), "[]"); + + var result = await sut.MigrateAsync(dataPath); + + result.ShouldBe(new DataMigrator.Result(MovedFiles: 1, ConvertedFiles: 0)); + File.ReadAllText(Path.Combine(newDataDir, "Accounts.json")).ShouldBe("[]"); + Directory.Exists(Path.Combine(dataPath, "2026")).ShouldBeFalse(); + } + + [Fact] + public async Task MoveUploadsWithSubfoldersToRootUploadsFolderWhenMigrating() + { + var oldUploads = Path.Combine(dataPath, "2025", "Mandator", "uploads"); + WriteFile(Path.Combine(oldUploads, "statement.c053.xml"), ""); + WriteFile(Path.Combine(oldUploads, "creditCard", "card.pdf"), "pdf"); + + await sut.MigrateAsync(dataPath); + + var newUploads = Path.Combine(dataPath, "uploads", "Mandator", "2025"); + File.ReadAllText(Path.Combine(newUploads, "statement.c053.xml")).ShouldBe(""); + File.ReadAllText(Path.Combine(newUploads, "creditCard", "card.pdf")).ShouldBe("pdf"); + Directory.Exists(Path.Combine(dataPath, "2025")).ShouldBeFalse(); + } + + [Fact] + public async Task MoveYearBackupsToRootBackupFolderWhenMigrating() + { + WriteFile(Path.Combine(dataPath, "2024", "backup", "Mandator", "20240101120000.zip"), "zip"); + + await sut.MigrateAsync(dataPath); + + File.ReadAllText(Path.Combine(dataPath, "backup", "Mandator", "2024", "20240101120000.zip")).ShouldBe("zip"); + Directory.Exists(Path.Combine(dataPath, "2024")).ShouldBeFalse(); + } + + [Fact] + public async Task ConvertXmlAlreadyInNewLayoutWhenMigrating() + { + WriteFile(Path.Combine(newDataDir, "Accounts.xml"), AccountsXml); + + var result = await sut.MigrateAsync(dataPath); + + result.ShouldBe(new DataMigrator.Result(MovedFiles: 0, ConvertedFiles: 1)); + File.Exists(Path.Combine(newDataDir, "Accounts.json")).ShouldBeTrue(); + XmlBackups("Accounts.xml").Length.ShouldBe(1); + } + + [Fact] + public async Task WriteHumanReadableJsonWhenConvertingXml() + { + WriteFile(Path.Combine(oldDataDir, "Transactions.xml"), TransactionsXml); + + await sut.MigrateAsync(dataPath); + + var json = File.ReadAllText(Path.Combine(newDataDir, "Transactions.json")); + json.ShouldContain("\"Text\": \"Gebäudeversicherung\"", Case.Sensitive); + json.ShouldContain("\n \"Id\": \"t1\"", Case.Sensitive); + json.ShouldNotContain("FxRate\": null", Case.Insensitive); + json.ShouldNotContain("ReadOnly", Case.Insensitive); + } + + [Fact] + public async Task PreserveAllValuesWhenReadingMigratedDataThroughRepository() + { + WriteFile(Path.Combine(oldDataDir, "Transactions.xml"), TransactionsXml); + WriteFile(Path.Combine(oldDataDir, "Accounts.xml"), AccountsXml); + + await sut.MigrateAsync(dataPath); + + var settingsService = Substitute.For(); + settingsService.GetDbPath().Returns(newDataDir); + settingsService.GetLastYearDbPath().Returns(Path.Combine(dataPath, "no-such-dir")); + var accountRepository = new AccountRepository(settingsService, new RepositoryCache(), NullLogger.Instance); + var transactionRepository = new TransactionRepository(settingsService, new RepositoryCache(), accountRepository, NullLogger.Instance); + var transactions = await transactionRepository.GetTransactionListAsync(); + var accounts = await accountRepository.GetAccountListAsync(); + + transactions.Count.ShouldBe(2); + transactions[0].Text.ShouldBe("Gebäudeversicherung"); + transactions[0].Value.ShouldBe(114.20m); + transactions[0].ValueDate.ShouldBe(new DateTime(2026, 1, 30)); + transactions[0].BookingDate.ShouldBe(new DateTime(2026, 1, 31)); + transactions[0].OriginAccountId.ShouldBe("a1"); + transactions[0].TargetAccountId.ShouldBe("a2"); + transactions[0].FxRate.ShouldBeNull(); + transactions[1].Value.ShouldBe(-50.5m); + transactions[1].FxRate.ShouldBe(0.9312m); + accounts.Single().Number.ShouldBe(1020); + accounts.Single().StartBalance.ShouldBe(1000.50m); + } + + [Fact] + public async Task LeaveUnknownXmlFilesUnconvertedWhenMigrating() + { + WriteFile(Path.Combine(newDataDir, "camt053.xml"), ""); + WriteFile(Path.Combine(dataPath, "uploads", "Mandator", "2026", "Accounts.xml"), ""); + + var result = await sut.MigrateAsync(dataPath); + + result.ConvertedFiles.ShouldBe(0); + File.Exists(Path.Combine(newDataDir, "camt053.xml")).ShouldBeTrue(); + File.Exists(Path.Combine(dataPath, "uploads", "Mandator", "2026", "Accounts.xml")).ShouldBeTrue(); + } + + [Fact] + public async Task DoNothingWhenAlreadyMigrated() + { + WriteFile(Path.Combine(oldDataDir, "Accounts.xml"), AccountsXml); + await sut.MigrateAsync(dataPath); + + var result = await sut.MigrateAsync(dataPath); + + result.ShouldBe(new DataMigrator.Result(0, 0)); + } + + [Fact] + public async Task KeepOldFolderWithUnexpectedFilesWhenMigrating() + { + WriteFile(Path.Combine(oldDataDir, "Accounts.json"), "[]"); + var stray = Path.Combine(dataPath, "2026", "Mandator", "notes.txt"); + WriteFile(stray, "keep me"); + + await sut.MigrateAsync(dataPath); + + File.Exists(Path.Combine(newDataDir, "Accounts.json")).ShouldBeTrue(); + File.ReadAllText(stray).ShouldBe("keep me"); + Directory.Exists(oldDataDir).ShouldBeFalse(); + } + + [Fact] + public async Task DropOldFileWhenIdenticalFileAlreadyMoved() + { + // Simulates a crash after a copy landed in the new layout but before the old one was removed. + WriteFile(Path.Combine(oldDataDir, "Accounts.json"), "[]"); + WriteFile(Path.Combine(newDataDir, "Accounts.json"), "[]"); + + await sut.MigrateAsync(dataPath); + + File.ReadAllText(Path.Combine(newDataDir, "Accounts.json")).ShouldBe("[]"); + Directory.Exists(Path.Combine(dataPath, "2026")).ShouldBeFalse(); + } + + [Fact] + public async Task ThrowAndSkipConversionWhenMoveTargetHasDifferentContent() + { + WriteFile(Path.Combine(oldDataDir, "Accounts.json"), "[]"); + WriteFile(Path.Combine(newDataDir, "Accounts.json"), "[{}]"); + WriteFile(Path.Combine(newDataDir, "Transactions.xml"), TransactionsXml); + + await Should.ThrowAsync(() => sut.MigrateAsync(dataPath)); + + File.ReadAllText(Path.Combine(oldDataDir, "Accounts.json")).ShouldBe("[]"); + File.ReadAllText(Path.Combine(newDataDir, "Accounts.json")).ShouldBe("[{}]"); + File.Exists(Path.Combine(newDataDir, "Transactions.xml")).ShouldBeTrue(); + } + + [Fact] + public async Task FinishConversionWhenJsonAlreadyMatchesXml() + { + // Simulates a crash after the JSON was written but before the XML was moved. + WriteFile(Path.Combine(newDataDir, "Accounts.xml"), AccountsXml); + await sut.MigrateAsync(dataPath); + WriteFile(Path.Combine(newDataDir, "Accounts.xml"), AccountsXml); + + var result = await sut.MigrateAsync(dataPath); + + result.ConvertedFiles.ShouldBe(1); + File.Exists(Path.Combine(newDataDir, "Accounts.xml")).ShouldBeFalse(); + XmlBackups("Accounts*.xml").Length.ShouldBe(2); + } + + [Fact] + public async Task ThrowAndKeepBothFilesWhenJsonExistsWithDifferentContent() + { + WriteFile(Path.Combine(newDataDir, "Accounts.xml"), AccountsXml); + WriteFile(Path.Combine(newDataDir, "Accounts.json"), "[]"); + + await Should.ThrowAsync(() => sut.MigrateAsync(dataPath)); + + File.Exists(Path.Combine(newDataDir, "Accounts.xml")).ShouldBeTrue(); + File.ReadAllText(Path.Combine(newDataDir, "Accounts.json")).ShouldBe("[]"); + } + + [Fact] + public async Task ConvertRemainingFilesAndThrowWhenOneXmlIsCorrupt() + { + WriteFile(Path.Combine(newDataDir, "Accounts.xml"), AccountsXml); + WriteFile(Path.Combine(newDataDir, "Transactions.xml"), ""); + + await Should.ThrowAsync(() => sut.MigrateAsync(dataPath)); + + File.Exists(Path.Combine(newDataDir, "Accounts.json")).ShouldBeTrue(); + File.Exists(Path.Combine(newDataDir, "Transactions.xml")).ShouldBeTrue(); + File.Exists(Path.Combine(newDataDir, "Transactions.json")).ShouldBeFalse(); + } +} diff --git a/Schaad.Accounting.Tests/SettingsServiceTestShould.cs b/Schaad.Accounting.Tests/SettingsServiceTestShould.cs new file mode 100644 index 0000000..568e348 --- /dev/null +++ b/Schaad.Accounting.Tests/SettingsServiceTestShould.cs @@ -0,0 +1,63 @@ +using Schaad.Accounting.Datasets; +using Schaad.Accounting.Services; +using Shouldly; + +namespace Schaad.Accounting.Tests; + +public class SettingsServiceTestShould : IDisposable +{ + private readonly string dataPath; + private readonly SettingsService sut; + + public SettingsServiceTestShould() + { + dataPath = Path.Combine(Path.GetTempPath(), "AccountingNext-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dataPath); + + sut = new SettingsService(new SettingsDataset { DataPath = dataPath, DefaultMandator = "Mandator" }); + sut.SetYear(2025); + } + + public void Dispose() + { + if (Directory.Exists(dataPath)) + { + Directory.Delete(dataPath, recursive: true); + } + } + + [Fact] + public void ReturnMandatorYearFolderWhenGettingDbPath() + { + sut.GetDbPath().ShouldBe(Path.Combine(dataPath, "Mandator", "2025")); + sut.GetLastYearDbPath().ShouldBe(Path.Combine(dataPath, "Mandator", "2024")); + } + + [Fact] + public void ReturnFoldersBelowRootUploadsWhenGettingUploadPaths() + { + sut.GetUploadPath().ShouldBe(Path.Combine(dataPath, "uploads", "Mandator", "2025")); + sut.GetCreditCardStatementPath().ShouldBe(Path.Combine(dataPath, "uploads", "Mandator", "2025", "creditCard")); + } + + [Fact] + public void ReturnZipBelowRootBackupWhenGettingBackupFilePath() + { + var path = sut.GetBackupFilePath(); + + Path.GetDirectoryName(path).ShouldBe(Path.Combine(dataPath, "backup", "Mandator", "2025")); + Path.GetExtension(path).ShouldBe(".zip"); + } + + [Fact] + public void ListOnlyMandatorsWithThatYearWhenGettingMandators() + { + Directory.CreateDirectory(Path.Combine(dataPath, "Mandator", "2025")); + Directory.CreateDirectory(Path.Combine(dataPath, "Other", "2025")); + Directory.CreateDirectory(Path.Combine(dataPath, "OnlyOlder", "2023")); + Directory.CreateDirectory(Path.Combine(dataPath, "uploads", "2025")); + Directory.CreateDirectory(Path.Combine(dataPath, "backup", "2025")); + + sut.GetMandators(2025).OrderBy(m => m).ShouldBe(["Mandator", "Other"]); + } +} diff --git a/Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs b/Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs deleted file mode 100644 index e910795..0000000 --- a/Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs +++ /dev/null @@ -1,209 +0,0 @@ -using Microsoft.Extensions.Logging.Abstractions; -using NSubstitute; -using Schaad.Accounting.Interfaces; -using Schaad.Accounting.Repositories; -using Shouldly; - -namespace Schaad.Accounting.Tests; - -public class XmlToJsonMigratorTestShould : IDisposable -{ - // Shaped like a file written by the old XmlSerializer-based repository, including the - // BOM-less declaration, namespaces and an xsi:nil FxRate. - private const string TransactionsXml = """ - - - - t1 - 2026-01-30T00:00:00 - 2026-01-31T00:00:00 - Gebäudeversicherung - 114.20 - a1 - a2 - - - - t2 - 2026-02-01T00:00:00 - 2026-02-01T00:00:00 - EUR Zahlung - -50.5 - a2 - a1 - 0.9312 - - - """; - - private const string AccountsXml = """ - - - - a1 - 1020 - Bank - CHF - 1000.50 - 0 - - - """; - - private readonly string dataPath; - private readonly string dataDir; - private readonly XmlToJsonMigrator sut = new(NullLogger.Instance); - - public XmlToJsonMigratorTestShould() - { - dataPath = Path.Combine(Path.GetTempPath(), "AccountingNext-tests-" + Guid.NewGuid().ToString("N")); - dataDir = Path.Combine(dataPath, "2026", "Mandator", "Data"); - Directory.CreateDirectory(dataDir); - } - - public void Dispose() - { - if (Directory.Exists(dataPath)) - { - Directory.Delete(dataPath, recursive: true); - } - } - - [Fact] - public async Task WriteJsonAndMoveXmlToBackupWhenDataFolderHasXml() - { - File.WriteAllText(Path.Combine(dataDir, "Transactions.xml"), TransactionsXml); - - var converted = await sut.MigrateAsync(dataPath); - - converted.ShouldBe(1); - File.Exists(Path.Combine(dataDir, "Transactions.json")).ShouldBeTrue(); - File.Exists(Path.Combine(dataDir, "Transactions.xml")).ShouldBeFalse(); - var backup = Directory.GetFiles(Path.Combine(dataPath, "2026", "backup", "Mandator"), "Transactions.xml", SearchOption.AllDirectories); - backup.Length.ShouldBe(1); - File.ReadAllText(backup[0]).ShouldBe(TransactionsXml); - } - - [Fact] - public async Task WriteHumanReadableJsonWhenConvertingXml() - { - File.WriteAllText(Path.Combine(dataDir, "Transactions.xml"), TransactionsXml); - - await sut.MigrateAsync(dataPath); - - var json = File.ReadAllText(Path.Combine(dataDir, "Transactions.json")); - json.ShouldContain("\"Text\": \"Gebäudeversicherung\"", Case.Sensitive); - json.ShouldContain("\n \"Id\": \"t1\"", Case.Sensitive); - json.ShouldNotContain("FxRate\": null", Case.Insensitive); - json.ShouldNotContain("ReadOnly", Case.Insensitive); - } - - [Fact] - public async Task PreserveAllValuesWhenReadingMigratedDataThroughRepository() - { - File.WriteAllText(Path.Combine(dataDir, "Transactions.xml"), TransactionsXml); - File.WriteAllText(Path.Combine(dataDir, "Accounts.xml"), AccountsXml); - - await sut.MigrateAsync(dataPath); - - var settingsService = Substitute.For(); - settingsService.GetDbPath().Returns(dataDir); - settingsService.GetLastYearDbPath().Returns(Path.Combine(dataPath, "no-such-dir")); - var accountRepository = new AccountRepository(settingsService, new RepositoryCache(), NullLogger.Instance); - var transactionRepository = new TransactionRepository(settingsService, new RepositoryCache(), accountRepository, NullLogger.Instance); - var transactions = await transactionRepository.GetTransactionListAsync(); - var accounts = await accountRepository.GetAccountListAsync(); - - transactions.Count.ShouldBe(2); - transactions[0].Text.ShouldBe("Gebäudeversicherung"); - transactions[0].Value.ShouldBe(114.20m); - transactions[0].ValueDate.ShouldBe(new DateTime(2026, 1, 30)); - transactions[0].BookingDate.ShouldBe(new DateTime(2026, 1, 31)); - transactions[0].OriginAccountId.ShouldBe("a1"); - transactions[0].TargetAccountId.ShouldBe("a2"); - transactions[0].FxRate.ShouldBeNull(); - transactions[1].Value.ShouldBe(-50.5m); - transactions[1].FxRate.ShouldBe(0.9312m); - accounts.Single().Number.ShouldBe(1020); - accounts.Single().StartBalance.ShouldBe(1000.50m); - } - - [Fact] - public async Task LeaveUnknownXmlFilesUntouchedWhenMigrating() - { - var statement = Path.Combine(dataDir, "camt053.xml"); - var upload = Path.Combine(dataPath, "2026", "Mandator", "uploads", "Accounts.xml"); - Directory.CreateDirectory(Path.GetDirectoryName(upload)!); - File.WriteAllText(statement, ""); - File.WriteAllText(upload, ""); - - var converted = await sut.MigrateAsync(dataPath); - - converted.ShouldBe(0); - File.Exists(statement).ShouldBeTrue(); - File.Exists(upload).ShouldBeTrue(); - } - - [Fact] - public async Task SkipBackupFolderWhenScanningMandators() - { - var backupData = Path.Combine(dataPath, "2026", "backup", "Data"); - Directory.CreateDirectory(backupData); - File.WriteAllText(Path.Combine(backupData, "Accounts.xml"), AccountsXml); - - var converted = await sut.MigrateAsync(dataPath); - - converted.ShouldBe(0); - File.Exists(Path.Combine(backupData, "Accounts.xml")).ShouldBeTrue(); - } - - [Fact] - public async Task DoNothingWhenAllDataIsAlreadyJson() - { - File.WriteAllText(Path.Combine(dataDir, "Accounts.xml"), AccountsXml); - await sut.MigrateAsync(dataPath); - - var converted = await sut.MigrateAsync(dataPath); - - converted.ShouldBe(0); - } - - [Fact] - public async Task FinishMigrationWhenJsonAlreadyMatchesXml() - { - // Simulates a crash after the JSON was written but before the XML was moved. - File.WriteAllText(Path.Combine(dataDir, "Accounts.xml"), AccountsXml); - await sut.MigrateAsync(dataPath); - File.WriteAllText(Path.Combine(dataDir, "Accounts.xml"), AccountsXml); - - var converted = await sut.MigrateAsync(dataPath); - - converted.ShouldBe(1); - File.Exists(Path.Combine(dataDir, "Accounts.xml")).ShouldBeFalse(); - } - - [Fact] - public async Task ThrowAndKeepBothFilesWhenJsonExistsWithDifferentContent() - { - File.WriteAllText(Path.Combine(dataDir, "Accounts.xml"), AccountsXml); - File.WriteAllText(Path.Combine(dataDir, "Accounts.json"), "[]"); - - await Should.ThrowAsync(() => sut.MigrateAsync(dataPath)); - - File.Exists(Path.Combine(dataDir, "Accounts.xml")).ShouldBeTrue(); - File.ReadAllText(Path.Combine(dataDir, "Accounts.json")).ShouldBe("[]"); - } - - [Fact] - public async Task ConvertRemainingFilesAndThrowWhenOneXmlIsCorrupt() - { - File.WriteAllText(Path.Combine(dataDir, "Accounts.xml"), AccountsXml); - File.WriteAllText(Path.Combine(dataDir, "Transactions.xml"), ""); - - await Should.ThrowAsync(() => sut.MigrateAsync(dataPath)); - - File.Exists(Path.Combine(dataDir, "Accounts.json")).ShouldBeTrue(); - File.Exists(Path.Combine(dataDir, "Transactions.xml")).ShouldBeTrue(); - File.Exists(Path.Combine(dataDir, "Transactions.json")).ShouldBeFalse(); - } -} diff --git a/Schaad.Accounting.UI/Extensions.cs b/Schaad.Accounting.UI/Extensions.cs index d9998b2..a87ad0e 100644 --- a/Schaad.Accounting.UI/Extensions.cs +++ b/Schaad.Accounting.UI/Extensions.cs @@ -16,7 +16,7 @@ namespace Schaad.Accounting.UI // can safely become Scoped. services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/Schaad.Accounting.UI/Program.cs b/Schaad.Accounting.UI/Program.cs index 51b5740..34f1027 100644 --- a/Schaad.Accounting.UI/Program.cs +++ b/Schaad.Accounting.UI/Program.cs @@ -30,9 +30,9 @@ namespace Schaad.Accounting.UI var app = builder.Build(); - // Convert any remaining XML data files to JSON before serving requests. Throws (and - // stops startup) if a file can't be converted, rather than running on partial data. - await app.Services.GetRequiredService() + // Move old-layout folders and convert XML data files to JSON before serving requests. + // Throws (and stops startup) if anything fails, rather than running on partial data. + await app.Services.GetRequiredService() .MigrateAsync(app.Services.GetRequiredService().DataPath); // Configure the HTTP request pipeline. -- 2.39.5