Remove XML-to-JSON data migration (#3)
## Summary
All data folders are now migrated to JSON in the `{mandator}/{year}` layout, so the one-time migration from #2 is no longer needed.
- Remove `DataMigrator` and its 15 tests, its DI registration and the startup call in `Program.cs` (`Main` is back to a plain `app.Run()`).
- Remove the old-layout year-folder filter in `SettingsService.GetMandators` and the `DataFolders.IsYear` helper it used.
- Remove the migration notes from `CLAUDE.md` and code comments.
- Rename `.xml` paths to `.json` in a repository-cache test (cosmetic).
Bank-statement import (CAMT053 `.xml` in `StatementImport`) is unaffected.
**Note:** this version expects every data folder to be migrated already. An old-layout or XML data folder is no longer converted. The original XMLs remain in `backup/{mandator}/{year}/xml-<timestamp>/` and can be deleted manually.
## Test plan
- [x] `dotnet build --no-incremental`: no warnings
- [x] `dotnet test`: 62/62 pass
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Reviewed-on: #3
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
This commit is contained in:
parent
6ab5ac133e
commit
883f424fd7
9 changed files with 9 additions and 604 deletions
|
|
@ -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, startup data migration |
|
||||
| `Schaad.Accounting.Db` | Repository layer — JSON serialization/deserialization |
|
||||
| `Schaad.Accounting.Common` | Shared models, DTOs, interfaces |
|
||||
|
||||
### Data flow
|
||||
|
|
@ -47,13 +47,11 @@ Data is multi-mandator and multi-year. The layout below `DataPath` (configured i
|
|||
```
|
||||
{DataPath}/{mandator}/{year}/*.json data files
|
||||
{DataPath}/uploads/{mandator}/{year}/ imported bank statements (+ creditCard/)
|
||||
{DataPath}/backup/{mandator}/{year}/ backup zips and migrated XML files
|
||||
{DataPath}/backup/{mandator}/{year}/ backup zips
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
- **ViewService** — aggregates account balances, applies FX rates, builds datasets for the UI
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ namespace Schaad.Accounting
|
|||
/// <code>
|
||||
/// {DataPath}/{mandator}/{year}/*.json data files
|
||||
/// {DataPath}/uploads/{mandator}/{year}/ imported bank statements (+ creditCard/)
|
||||
/// {DataPath}/backup/{mandator}/{year}/ backup zips and migrated XML files
|
||||
/// {DataPath}/backup/{mandator}/{year}/ backup zips
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public static class DataFolders
|
||||
|
|
@ -20,11 +20,5 @@ namespace Schaad.Accounting
|
|||
public static bool IsReserved(string folderName)
|
||||
=> folderName.Equals(Uploads, System.StringComparison.OrdinalIgnoreCase)
|
||||
|| folderName.Equals(Backup, System.StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Year folders are four-digit numbers.
|
||||
/// </summary>
|
||||
public static bool IsYear(string folderName)
|
||||
=> folderName.Length == 4 && int.TryParse(folderName, out _);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,280 +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
|
||||
{
|
||||
/// <summary>
|
||||
/// Startup migration of the data folder, in two phases:
|
||||
/// <list type="number">
|
||||
/// <item>Restructure: move the old {year}/{mandator}/Data, {year}/{mandator}/uploads and
|
||||
/// {year}/backup/{mandator} folders into the layout described in <see cref="DataFolders"/>.
|
||||
/// Files are moved unchanged.</item>
|
||||
/// <item>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}/.</item>
|
||||
/// </list>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public class DataMigrator
|
||||
{
|
||||
// Only these files are data files; bank statement XMLs live in uploads/ and are never
|
||||
// converted.
|
||||
private static readonly Dictionary<string, Type> DataFiles = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["Accounts"] = typeof(List<Account>),
|
||||
["BankTransactions"] = typeof(List<BankTransaction>),
|
||||
["BookingRules"] = typeof(List<BookingRule>),
|
||||
["BookingTexts"] = typeof(List<BookingText>),
|
||||
["SplitPredefinitions"] = typeof(List<SplitPredefinition>),
|
||||
["SubClasses"] = typeof(List<SubClass>),
|
||||
["Transactions"] = typeof(List<Transaction>)
|
||||
};
|
||||
|
||||
private readonly ILogger<DataMigrator> logger;
|
||||
|
||||
public DataMigrator(ILogger<DataMigrator> logger)
|
||||
{
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public record Result(int MovedFiles, int ConvertedFiles);
|
||||
|
||||
public async Task<Result> MigrateAsync(string dataPath)
|
||||
{
|
||||
if (Directory.Exists(dataPath) == false)
|
||||
{
|
||||
return new Result(0, 0);
|
||||
}
|
||||
|
||||
var errors = new List<Exception>();
|
||||
|
||||
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<Exception> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private int MoveTree(string source, string target, List<Exception> 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<int> ConvertAsync(string dataPath, List<Exception> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Never overwrite an existing backup: "Accounts.xml", then "Accounts (2).xml", ...
|
||||
/// </summary>
|
||||
private static string GetFreeBackupPath(string backupDir, string fileName)
|
||||
{
|
||||
var path = Path.Combine(backupDir, fileName);
|
||||
for (var i = 2; File.Exists(path); i++)
|
||||
{
|
||||
path = Path.Combine(backupDir, $"{Path.GetFileNameWithoutExtension(fileName)} ({i}){Path.GetExtension(fileName)}");
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes dir and its subdirectories bottom-up, but only those that are empty.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -5,8 +5,7 @@ using System.Text.Json.Serialization;
|
|||
namespace Schaad.Accounting.Repositories
|
||||
{
|
||||
/// <summary>
|
||||
/// Serializer settings shared by the repositories and the data migration, so both
|
||||
/// produce byte-identical files.
|
||||
/// Serializer settings for the JSON data files.
|
||||
/// </summary>
|
||||
public static class JsonStorage
|
||||
{
|
||||
|
|
|
|||
|
|
@ -59,7 +59,7 @@ namespace Schaad.Accounting.Services
|
|||
return Directory.GetDirectories(dataPath)
|
||||
.Where(d => Directory.Exists(Path.Combine(d, year.ToString())))
|
||||
.Select(Path.GetFileName)
|
||||
.Where(name => !DataFolders.IsReserved(name) && !DataFolders.IsYear(name))
|
||||
.Where(name => !DataFolders.IsReserved(name))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,299 +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 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();
|
||||
}
|
||||
}
|
||||
|
|
@ -50,8 +50,8 @@ public class RepositoryCacheTestShould
|
|||
{
|
||||
var cache = new RepositoryCache();
|
||||
|
||||
await cache.GetOrLoadAsync("Path/To/File.xml", () => Task.FromResult(new List<int> { 1 }));
|
||||
var upper = await cache.GetOrLoadAsync("PATH/TO/FILE.XML", () => Task.FromResult(new List<int> { 99 }));
|
||||
await cache.GetOrLoadAsync("Path/To/File.json", () => Task.FromResult(new List<int> { 1 }));
|
||||
var upper = await cache.GetOrLoadAsync("PATH/TO/FILE.JSON", () => Task.FromResult(new List<int> { 99 }));
|
||||
|
||||
upper.ShouldBe(new[] { 1 });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,7 +16,6 @@ namespace Schaad.Accounting.UI
|
|||
// can safely become Scoped.
|
||||
services.AddSingleton<ISettingsService, SettingsService>();
|
||||
|
||||
services.AddSingleton<DataMigrator>();
|
||||
services.AddScoped<RepositoryCache>();
|
||||
services.AddScoped<IAccountRepository, AccountRepository>();
|
||||
services.AddScoped<IBankTransactionRepository, BankTransactionRepository>();
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ 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;
|
||||
|
||||
|
|
@ -10,7 +9,7 @@ namespace Schaad.Accounting.UI
|
|||
{
|
||||
public class Program
|
||||
{
|
||||
public static async Task Main(string[] args)
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
|
|
@ -30,11 +29,6 @@ namespace Schaad.Accounting.UI
|
|||
|
||||
var app = builder.Build();
|
||||
|
||||
// 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<DataMigrator>()
|
||||
.MigrateAsync(app.Services.GetRequiredService<SettingsDataset>().DataPath);
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
|
|
@ -58,7 +52,7 @@ namespace Schaad.Accounting.UI
|
|||
app.MapRazorComponents<App>()
|
||||
.AddInteractiveServerRenderMode();
|
||||
|
||||
await app.RunAsync();
|
||||
app.Run();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue