Compare commits
2 commits
e00368bf7c
...
acf6753d07
| Author | SHA1 | Date | |
|---|---|---|---|
| acf6753d07 | |||
| 24bdfe60bc |
16 changed files with 431 additions and 44 deletions
10
CLAUDE.md
10
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.
|
||||
|
|
|
|||
|
|
@ -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"; }
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
22
Schaad.Accounting.Db/JsonStorage.cs
Normal file
22
Schaad.Accounting.Db/JsonStorage.cs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Schaad.Accounting.Repositories
|
||||
{
|
||||
/// <summary>
|
||||
/// Serializer settings shared by the repositories and the XML-to-JSON migration, so both
|
||||
/// produce byte-identical files.
|
||||
/// </summary>
|
||||
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,
|
||||
PropertyNameCaseInsensitive = true,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -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<AccountRepository> logger)
|
||||
: base(settingsService, cache, logger)
|
||||
|
|
|
|||
|
|
@ -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<BankTransactionRepository> logger)
|
||||
: base(settingsService, cache, logger)
|
||||
|
|
|
|||
|
|
@ -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
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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. <see cref="SaveAsync"/> invalidates the entry.
|
||||
/// </summary>
|
||||
protected Task<List<T>> LoadListAsync<T>(string fileName)
|
||||
|
|
@ -68,7 +66,7 @@ namespace Schaad.Accounting.Repositories
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
|
|
@ -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
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="LoadListAsync{T}"/> for repository reads.
|
||||
/// </summary>
|
||||
protected async Task<T> LoadAsync<T>(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<T>(stream, JsonStorage.Options);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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<BookingRuleRepository> logger)
|
||||
: base(settingsService, cache, logger)
|
||||
|
|
|
|||
|
|
@ -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<BookingTextRepository> logger)
|
||||
: base(settingsService, cache, logger)
|
||||
|
|
|
|||
|
|
@ -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<SplitPredefinitionRepository> logger)
|
||||
: base(settingsService, cache, logger)
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ namespace Schaad.Accounting.Repositories
|
|||
public class SubclassRepository : BaseRepository, ISubclassRepository
|
||||
{
|
||||
private readonly Dictionary<int, string> classes = new Dictionary<int, string>();
|
||||
private readonly string SUBCLASSES = "SubClasses.xml";
|
||||
private readonly string SUBCLASSES = "SubClasses.json";
|
||||
|
||||
public SubclassRepository(ISettingsService settingsService, RepositoryCache cache, ILogger<SubclassRepository> logger)
|
||||
: base(settingsService, cache, logger)
|
||||
|
|
|
|||
|
|
@ -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<TransactionRepository> logger)
|
||||
: base(settingsService, cache, logger)
|
||||
|
|
|
|||
164
Schaad.Accounting.Db/XmlToJsonMigrator.cs
Normal file
164
Schaad.Accounting.Db/XmlToJsonMigrator.cs
Normal file
|
|
@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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}/.
|
||||
/// </summary>
|
||||
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<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<XmlToJsonMigrator> logger;
|
||||
|
||||
public XmlToJsonMigrator(ILogger<XmlToJsonMigrator> logger)
|
||||
{
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public async Task<int> MigrateAsync(string dataPath)
|
||||
{
|
||||
if (Directory.Exists(dataPath) == false)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
|
||||
var converted = 0;
|
||||
var errors = new List<Exception>();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
}
|
||||
209
Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs
Normal file
209
Schaad.Accounting.Tests/XmlToJsonMigratorTestShould.cs
Normal file
|
|
@ -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 = """
|
||||
<?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;
|
||||
private readonly string dataDir;
|
||||
private readonly XmlToJsonMigrator sut = new(NullLogger<XmlToJsonMigrator>.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<ISettingsService>();
|
||||
settingsService.GetDbPath().Returns(dataDir);
|
||||
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 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, "<Document />");
|
||||
File.WriteAllText(upload, "<Document />");
|
||||
|
||||
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<AggregateException>(() => 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"), "<ArrayOfTransaction><Transaction>");
|
||||
|
||||
await Should.ThrowAsync<AggregateException>(() => 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();
|
||||
}
|
||||
}
|
||||
|
|
@ -16,6 +16,7 @@ namespace Schaad.Accounting.UI
|
|||
// can safely become Scoped.
|
||||
services.AddSingleton<ISettingsService, SettingsService>();
|
||||
|
||||
services.AddSingleton<XmlToJsonMigrator>();
|
||||
services.AddScoped<RepositoryCache>();
|
||||
services.AddScoped<IAccountRepository, AccountRepository>();
|
||||
services.AddScoped<IBankTransactionRepository, BankTransactionRepository>();
|
||||
|
|
|
|||
|
|
@ -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<XmlToJsonMigrator>()
|
||||
.MigrateAsync(app.Services.GetRequiredService<SettingsDataset>().DataPath);
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
|
|
@ -52,7 +58,7 @@ namespace Schaad.Accounting.UI
|
|||
app.MapRazorComponents<App>()
|
||||
.AddInteractiveServerRenderMode();
|
||||
|
||||
app.Run();
|
||||
await app.RunAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue