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(); } }