## Summary
A new page **Stammdaten → JSON-Editor** (`/json-editor`) for viewing and editing the data files of the year and mandator selected in the header, as plain JSON.
### Editor
- **Files:** opens `Transactions.json` by default; the dropdown offers the other six data files. The file is part of the URL (`?file=`).
- **Monaco** (the VS Code editor) via **BlazorMonaco 3.5.0** (MIT). Its files ship inside the NuGet package, so there is no CDN. `wwwroot/js/monaco.js` loads it only when the page opens, instead of three script tags on every page.
- **Features:**
- JSON highlighting, line numbers, folding, minimap, and live syntax error markers
- **Suchen / Ersetzen** buttons, or Ctrl+F / Ctrl+H, with case, whole-word and regex options
- **Formatieren** tidies the indentation
- **Status line:** mandator / year / file, size, and an "Ungespeicherte Änderungen" marker. Undoing all edits clears it again.
### Saving (`RawDataRepository`)
Only validated text is saved, because a broken file would break every page that reads it:
- **Strict JSON:** unknown property names are errors (e.g. `"Vlaue"`), reported with line, column and path. Clicking an error jumps to the line.
- **IDs:** every entry needs an `Id`, and IDs must be unique.
- **Account references:**
- `Transactions.json` may only reference accounts in `Accounts.json`;
- `Accounts.json` may not drop accounts that transactions still use.
- **No silent overwrite:** saving is refused if the file changed on disk since it was loaded (SHA-256 of the content).
- **Backup:** the previous version is copied to `backup/{mandator}/{year}/json-{timestamp}/`.
- **Saved through `BaseRepository.SaveAsync`:** an atomic write that refreshes the cached data, so other pages see the change immediately. The file is written in the normal format; unchanged parts stay byte-identical.
### Infrastructure
- **Hub message size** raised to 8 MB (`Program.cs`): the editor sends whole files from the browser (`Transactions.json` is several hundred KB), and the default is 32 KB per message.
- **Unsaved changes:** `wwwroot/js/unsaved-guard.js` asks before leaving via a link, and the browser's own prompt covers reload, closing the tab and switching year or mandator. Blazor's `NavigationLock` can't do this here: pages are interactive one by one, so routing between them is static enhanced navigation, which doesn't consult interactive components. Switching files or "Neu laden" inside the page uses a Fluent confirmation dialog.
## Test plan
- [x] `dotnet build`: no warnings
- [x] `dotnet test`: 98/98 pass, including 10 new `RawDataRepositoryTestShould` tests:
- loading
- save with backup
- cached data refreshed after saving
- invalid JSON with line and column
- unknown property
- unknown account
- missing and duplicate IDs
- removing an account that is still used
- refusing when the file changed since loading
- unknown file name rejected
- [x] Headless Chrome on a copy of the real data:
- editor loads the 433 KB / 9'023-line `Transactions.json` with JSON highlighting; Ersetzen opens the replace widget
- replacing 88 occurrences and saving: the file on disk equals the original plus exactly those replacements, and a backup is written
- a typo is rejected, the file stays untouched, and the error jumps to the line
- leaving with changes: "Abbrechen" stays, "OK" leaves, no prompt without changes, reload asks after real typing
## Notes
- Monaco's own UI texts (Find, Replace, …) are English.
- Not part of this PR: every menu link throws a harmless console error (`navmenu-toggle` is null). The Fluent nav template expects a toggle element that this app doesn't render.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Reviewed-on: #7
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
177 lines
6.5 KiB
C#
177 lines
6.5 KiB
C#
using Microsoft.Extensions.Logging.Abstractions;
|
|
using NSubstitute;
|
|
using Schaad.Accounting.Datasets;
|
|
using Schaad.Accounting.Interfaces;
|
|
using Schaad.Accounting.Repositories;
|
|
using Shouldly;
|
|
|
|
namespace Schaad.Accounting.Tests;
|
|
|
|
public class RawDataRepositoryTestShould : IDisposable
|
|
{
|
|
private const string Accounts = """
|
|
[
|
|
{ "Id": "a1", "Number": 1020, "Name": "Bank", "Currency": "CHF" },
|
|
{ "Id": "a2", "Number": 4000, "Name": "Lebensmittel", "Currency": "CHF" }
|
|
]
|
|
""";
|
|
|
|
private const string Transactions = """
|
|
[
|
|
{ "Id": "t1", "ValueDate": "2026-01-10T00:00:00", "Text": "Migros", "Value": 12.5, "OriginAccountId": "a1", "TargetAccountId": "a2" }
|
|
]
|
|
""";
|
|
|
|
private readonly string dataPath;
|
|
private readonly string dbDir;
|
|
private readonly RepositoryCache cache = new();
|
|
private readonly ISettingsService settingsService;
|
|
private readonly RawDataRepository sut;
|
|
|
|
public RawDataRepositoryTestShould()
|
|
{
|
|
dataPath = Path.Combine(Path.GetTempPath(), "AccountingNext-tests-" + Guid.NewGuid().ToString("N"));
|
|
dbDir = Path.Combine(dataPath, "Mandator", "2026");
|
|
Directory.CreateDirectory(dbDir);
|
|
File.WriteAllText(Path.Combine(dbDir, "Accounts.json"), Accounts);
|
|
File.WriteAllText(Path.Combine(dbDir, "Transactions.json"), Transactions);
|
|
|
|
settingsService = Substitute.For<ISettingsService>();
|
|
settingsService.GetDbPath().Returns(dbDir);
|
|
settingsService.GetLastYearDbPath().Returns(Path.Combine(dataPath, "no-such-dir"));
|
|
settingsService.GetSettings().Returns(new SettingsDataset { DataPath = dataPath });
|
|
settingsService.GetMandator().Returns("Mandator");
|
|
settingsService.GetYear().Returns(2026);
|
|
|
|
sut = new RawDataRepository(settingsService, cache, NullLogger<RawDataRepository>.Instance);
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
if (Directory.Exists(dataPath))
|
|
{
|
|
Directory.Delete(dataPath, recursive: true);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ReturnFileTextWhenLoading()
|
|
{
|
|
var file = await sut.LoadAsync("Transactions.json");
|
|
|
|
file.Text.ShouldBe(Transactions);
|
|
file.Hash.ShouldNotBeNullOrEmpty();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task SaveAndBackUpPreviousVersionWhenTextIsValid()
|
|
{
|
|
var loaded = await sut.LoadAsync("Transactions.json");
|
|
var edited = loaded.Text.Replace("\"Migros\"", "\"Migros Bern\"");
|
|
|
|
var result = await sut.SaveAsync("Transactions.json", edited, loaded.Hash);
|
|
|
|
result.Errors.ShouldBeEmpty();
|
|
result.Saved.ShouldBeTrue();
|
|
result.File!.Text.ShouldContain("\"Text\": \"Migros Bern\"");
|
|
result.File.Hash.ShouldNotBe(loaded.Hash);
|
|
File.ReadAllText(result.BackupPath!).ShouldBe(Transactions);
|
|
result.BackupPath!.ShouldStartWith(Path.Combine(dataPath, "backup", "Mandator", "2026", "json-"));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RefreshCachedDataWhenSaving()
|
|
{
|
|
var transactionRepository = new TransactionRepository(settingsService, cache, Substitute.For<IAccountRepository>(), NullLogger<TransactionRepository>.Instance);
|
|
(await transactionRepository.GetTransactionListAsync()).Single().Text.ShouldBe("Migros");
|
|
var loaded = await sut.LoadAsync("Transactions.json");
|
|
|
|
await sut.SaveAsync("Transactions.json", loaded.Text.Replace("\"Migros\"", "\"Coop\""), loaded.Hash);
|
|
|
|
(await transactionRepository.GetTransactionListAsync()).Single().Text.ShouldBe("Coop");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RejectInvalidJsonWithLineAndColumnWhenSaving()
|
|
{
|
|
var loaded = await sut.LoadAsync("Transactions.json");
|
|
|
|
var result = await sut.SaveAsync("Transactions.json", "[\n { \"Id\": \"t1\",, }\n]", loaded.Hash);
|
|
|
|
result.Saved.ShouldBeFalse();
|
|
result.Errors.Single().ShouldStartWith("Zeile 2, Spalte");
|
|
File.ReadAllText(Path.Combine(dbDir, "Transactions.json")).ShouldBe(Transactions);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RejectUnknownPropertyWhenSaving()
|
|
{
|
|
var loaded = await sut.LoadAsync("Transactions.json");
|
|
|
|
var result = await sut.SaveAsync("Transactions.json", loaded.Text.Replace("\"Value\"", "\"Vlaue\""), loaded.Hash);
|
|
|
|
result.Saved.ShouldBeFalse();
|
|
result.Errors.Single().ShouldContain("Vlaue");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RejectUnknownAccountWhenSavingTransactions()
|
|
{
|
|
var loaded = await sut.LoadAsync("Transactions.json");
|
|
|
|
var result = await sut.SaveAsync("Transactions.json", loaded.Text.Replace("\"a2\"", "\"a9\""), loaded.Hash);
|
|
|
|
result.Saved.ShouldBeFalse();
|
|
result.Errors.Single().ShouldContain("TargetAccountId \"a9\"");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RejectMissingAndDuplicateIdsWhenSaving()
|
|
{
|
|
var loaded = await sut.LoadAsync("Accounts.json");
|
|
var text = """
|
|
[
|
|
{ "Id": "a1", "Number": 1020, "Name": "Bank" },
|
|
{ "Id": "a1", "Number": 4000, "Name": "Lebensmittel" },
|
|
{ "Number": 4100, "Name": "Miete" }
|
|
]
|
|
""";
|
|
|
|
var result = await sut.SaveAsync("Accounts.json", text, loaded.Hash);
|
|
|
|
result.Saved.ShouldBeFalse();
|
|
result.Errors.ShouldContain(e => e.Contains("Eintrag 3"));
|
|
result.Errors.ShouldContain(e => e.Contains("\"a1\" kommt 2-mal vor"));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RejectRemovingAccountStillUsedByTransactionsWhenSaving()
|
|
{
|
|
var loaded = await sut.LoadAsync("Accounts.json");
|
|
var text = """[ { "Id": "a1", "Number": 1020, "Name": "Bank" } ]""";
|
|
|
|
var result = await sut.SaveAsync("Accounts.json", text, loaded.Hash);
|
|
|
|
result.Saved.ShouldBeFalse();
|
|
result.Errors.Single().ShouldContain("\"a2\" fehlt, wird aber von 1 Buchungen");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RefuseToOverwriteWhenFileChangedSinceLoading()
|
|
{
|
|
var loaded = await sut.LoadAsync("Transactions.json");
|
|
File.WriteAllText(Path.Combine(dbDir, "Transactions.json"), Transactions.Replace("12.5", "13"));
|
|
|
|
var result = await sut.SaveAsync("Transactions.json", loaded.Text, loaded.Hash);
|
|
|
|
result.Saved.ShouldBeFalse();
|
|
result.Errors.Single().ShouldContain("seit dem Laden geändert");
|
|
File.ReadAllText(Path.Combine(dbDir, "Transactions.json")).ShouldContain("13");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RejectUnknownFileNameWhenLoading()
|
|
{
|
|
await Should.ThrowAsync<ArgumentException>(() => sut.LoadAsync("../appsettings.json"));
|
|
}
|
|
}
|