## Summary
- Repositories read and write **JSON instead of XML**. The JSON is human readable: indented, umlauts written as-is, property names as in the C# models (`BankTransactionText`), null values left out, computed properties (`Class`, `SubClass`, `IsFxAccount`, `ReadOnly`) not stored. Shared settings live in `JsonStorage`.
- **New data folder layout**, defined in `DataFolders`:
```
{DataPath}/{mandator}/{year}/*.json data files (no Data subfolder)
{DataPath}/uploads/{mandator}/{year}/ imported bank statements (+ creditCard/)
{DataPath}/backup/{mandator}/{year}/ backup zips and the original XML files
```
`SettingsService` builds the new paths. `GetYearMandatorPath` / `GetLastYearMandatorPath` are removed because they now equal the data paths. The mandator dropdown lists mandators that have a folder for the selected year.
- New **`DataMigrator`** runs at startup, before the app serves requests, in two phases:
1. **Restructure:** moves the old `{year}/{mandator}/Data`, `{year}/{mandator}/uploads` and `{year}/backup/{mandator}` folders into the new layout, unchanged.
2. **Convert:** turns the seven known XML data files in each `{mandator}/{year}` folder into JSON, checks that the JSON reads back to the same data, then moves the XML to `backup/{mandator}/{year}/xml-{timestamp}/`. Bank-statement XMLs are moved but never converted.
- **Safety:** nothing is ever overwritten. If a file already exists at the target, the source is dropped only when both are identical; otherwise it is an error. Any error stops startup (conversion is skipped if a move failed), so the app never runs on a half-migrated folder. Old folders are removed only once empty; unexpected leftovers are logged and kept. Both phases can safely run again.
- `CLAUDE.md` updated for JSON storage and the new layout.
## Upgrade notes
- **Make a full copy of the data folder before the first start** of this version.
- **Don't run an older (XML) version** on a migrated data folder. It would find no data and start new XML files in the old layout.
- The backup zip now contains only the data files of the current mandator/year. Uploads live in their own folder.
- Empty folders from the old layout are not carried over; the app recreates them when needed.
## Test plan
- [x] `dotnet build`: no warnings
- [x] `dotnet test`: 77/77 pass, including 15 `DataMigratorTestShould` tests (old-layout data, uploads with subfolders and year backups moved; XML converted in old and new layout; readable JSON; values round-trip through the repositories; unknown XMLs not converted; rerun does nothing; stray files kept; crash recovery for moves and conversions; conflicting files; corrupt XML) and 4 `SettingsServiceTestShould` tests for the new paths and mandator list
- [x] Ran the app against a copy of the real data folder: 136 files moved, 82 XML files converted, no old year folders left, Accounts / Balance report / Transactions pages render
- [x] Checked every one of the 137 original files against a checksum manifest: uploads and other files byte-identical at their new location, every XML backup identical to the original, and JSON vs. XML compared field by field (11,807 records, 101,564 fields, 0 differences). 8 dates with a UTC offset in the XML are written as the same instant in local time, which is what the old app also had in memory after reading them.
- [ ] Start once on the real data folder and check the pages
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Reviewed-on: #2
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
299 lines
12 KiB
C#
299 lines
12 KiB
C#
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 = """
|
|
<?xml version="1.0" encoding="utf-8"?>
|
|
<ArrayOfTransaction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
|
|
<Transaction>
|
|
<Id>t1</Id>
|
|
<ValueDate>2026-01-30T00:00:00</ValueDate>
|
|
<BookingDate>2026-01-31T00:00:00</BookingDate>
|
|
<Text>Gebäudeversicherung</Text>
|
|
<Value>114.20</Value>
|
|
<OriginAccountId>a1</OriginAccountId>
|
|
<TargetAccountId>a2</TargetAccountId>
|
|
<FxRate xsi:nil="true" />
|
|
</Transaction>
|
|
<Transaction>
|
|
<Id>t2</Id>
|
|
<ValueDate>2026-02-01T00:00:00</ValueDate>
|
|
<BookingDate>2026-02-01T00:00:00</BookingDate>
|
|
<Text>EUR Zahlung</Text>
|
|
<Value>-50.5</Value>
|
|
<OriginAccountId>a2</OriginAccountId>
|
|
<TargetAccountId>a1</TargetAccountId>
|
|
<FxRate>0.9312</FxRate>
|
|
</Transaction>
|
|
</ArrayOfTransaction>
|
|
""";
|
|
|
|
private const string AccountsXml = """
|
|
<?xml version="1.0" encoding="utf-8"?>
|
|
<ArrayOfAccount xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
|
|
<Account>
|
|
<Id>a1</Id>
|
|
<Number>1020</Number>
|
|
<Name>Bank</Name>
|
|
<Currency>CHF</Currency>
|
|
<StartBalance>1000.50</StartBalance>
|
|
<LastBankBalance>0</LastBankBalance>
|
|
</Account>
|
|
</ArrayOfAccount>
|
|
""";
|
|
|
|
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<DataMigrator>.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"), "<Document />");
|
|
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("<Document />");
|
|
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<ISettingsService>();
|
|
settingsService.GetDbPath().Returns(newDataDir);
|
|
settingsService.GetLastYearDbPath().Returns(Path.Combine(dataPath, "no-such-dir"));
|
|
var accountRepository = new AccountRepository(settingsService, new RepositoryCache(), NullLogger<AccountRepository>.Instance);
|
|
var transactionRepository = new TransactionRepository(settingsService, new RepositoryCache(), accountRepository, NullLogger<TransactionRepository>.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"), "<Document />");
|
|
WriteFile(Path.Combine(dataPath, "uploads", "Mandator", "2026", "Accounts.xml"), "<Document />");
|
|
|
|
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<AggregateException>(() => 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<AggregateException>(() => 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"), "<ArrayOfTransaction><Transaction>");
|
|
|
|
await Should.ThrowAsync<AggregateException>(() => 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();
|
|
}
|
|
}
|