AccountingNext/Schaad.Accounting.Db/Repositories/RawDataRepository.cs
Claudio Schaad 255c133b85 Add JSON editor for the data files (#7)
## 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>
2026-10-22 17:55:20 +00:00

212 lines
8.8 KiB
C#

#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Schaad.Accounting.Interfaces;
using Schaad.Accounting.Models;
namespace Schaad.Accounting.Repositories
{
/// <summary>
/// Plain-text access to the data files of the selected year and mandator for the JSON editor.
/// Saving goes through <see cref="BaseRepository.SaveAsync{T}"/> (atomic write, cache
/// invalidation), but only after the text has been checked, because a broken file would break
/// every page that reads it.
/// </summary>
public class RawDataRepository : BaseRepository, IRawDataRepository
{
private const string ACCOUNTS = "Accounts.json";
private const string TRANSACTIONS = "Transactions.json";
private const int MaxErrors = 20;
// Like the normal options, but property names that don't exist (typos) are errors instead
// of being silently dropped on save.
private static readonly JsonSerializerOptions StrictOptions = new(JsonStorage.Options)
{
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow
};
public RawDataRepository(ISettingsService settingsService, RepositoryCache cache, ILogger<RawDataRepository> logger)
: base(settingsService, cache, logger)
{
}
public IReadOnlyList<string> FileNames { get; } =
[
TRANSACTIONS,
ACCOUNTS,
"BankTransactions.json",
"BookingRules.json",
"BookingTexts.json",
"SplitPredefinitions.json",
"SubClasses.json"
];
public async Task<RawDataFile> LoadAsync(string fileName)
{
var path = PathOf(fileName);
var bytes = File.Exists(path) ? await File.ReadAllBytesAsync(path) : Array.Empty<byte>();
return new RawDataFile(fileName, path, Encoding.UTF8.GetString(bytes), Hash(bytes));
}
public Task<RawDataSaveResult> SaveAsync(string fileName, string text, string loadedHash) => fileName switch
{
TRANSACTIONS => SaveAsync<Transaction>(fileName, text, loadedHash),
ACCOUNTS => SaveAsync<Account>(fileName, text, loadedHash),
"BankTransactions.json" => SaveAsync<BankTransaction>(fileName, text, loadedHash),
"BookingRules.json" => SaveAsync<BookingRule>(fileName, text, loadedHash),
"BookingTexts.json" => SaveAsync<BookingText>(fileName, text, loadedHash),
"SplitPredefinitions.json" => SaveAsync<SplitPredefinition>(fileName, text, loadedHash),
"SubClasses.json" => SaveAsync<SubClass>(fileName, text, loadedHash),
_ => throw new ArgumentException($"Unknown data file '{fileName}'", nameof(fileName))
};
private async Task<RawDataSaveResult> SaveAsync<T>(string fileName, string text, string loadedHash)
{
List<T>? items;
try
{
items = JsonSerializer.Deserialize<List<T>>(text, StrictOptions);
}
catch (JsonException ex)
{
return Failed(Describe(ex));
}
if (items is null)
{
return Failed("Die Datei muss eine Liste enthalten: [ ... ]");
}
var errors = CheckIds(items);
if (items is List<Transaction> transactions)
{
errors.AddRange(await CheckAccountReferencesAsync(transactions));
}
if (items is List<Account> accounts)
{
errors.AddRange(await CheckAccountsStillUsedAsync(accounts));
}
if (errors.Count > 0)
{
return Failed(errors.ToArray());
}
var current = await LoadAsync(fileName);
if (current.Hash != loadedHash)
{
return Failed("Die Datei wurde seit dem Laden geändert (z.B. durch eine Buchung). Bitte neu laden; deine Änderungen gehen dabei verloren, also vorher kopieren.");
}
var backupPath = await BackupAsync(current);
await SaveAsync(items, fileName);
logger.LogInformation("Saved {FilePath} from the JSON editor; previous version in {BackupPath}", current.Path, backupPath);
return new RawDataSaveResult([], await LoadAsync(fileName), backupPath);
}
private static List<string> CheckIds<T>(List<T> items)
{
var errors = new List<string>();
var idProperty = typeof(T).GetProperty("Id");
if (idProperty is null)
{
return errors;
}
var ids = items.Select(item => idProperty.GetValue(item) as string).ToList();
for (var i = 0; i < ids.Count; i++)
{
if (string.IsNullOrWhiteSpace(ids[i]))
{
errors.Add($"Eintrag {i + 1}: \"Id\" fehlt.");
}
}
foreach (var duplicate in ids.Where(id => !string.IsNullOrWhiteSpace(id)).GroupBy(id => id).Where(g => g.Count() > 1))
{
errors.Add($"Id \"{duplicate.Key}\" kommt {duplicate.Count()}-mal vor.");
}
return Limit(errors);
}
private async Task<List<string>> CheckAccountReferencesAsync(List<Transaction> transactions)
{
var accountIds = (await LoadListAsync<Account>(ACCOUNTS)).Select(a => a.Id).ToHashSet();
var errors = new List<string>();
for (var i = 0; i < transactions.Count; i++)
{
var t = transactions[i];
foreach (var (id, role) in new[] { (t.OriginAccountId, "OriginAccountId"), (t.TargetAccountId, "TargetAccountId") })
{
if (accountIds.Contains(id) == false)
{
errors.Add($"Buchung {i + 1} ({t.ValueDate:dd.MM.yyyy} \"{t.Text}\"): {role} \"{id}\" ist kein Konto in {ACCOUNTS}.");
}
}
}
return Limit(errors);
}
private async Task<List<string>> CheckAccountsStillUsedAsync(List<Account> accounts)
{
var accountIds = accounts.Select(a => a.Id).ToHashSet();
var transactions = await LoadListAsync<Transaction>(TRANSACTIONS);
return Limit(transactions
.SelectMany(t => new[] { t.OriginAccountId, t.TargetAccountId })
.Where(id => accountIds.Contains(id) == false)
.GroupBy(id => id)
.Select(g => $"Konto-Id \"{g.Key}\" fehlt, wird aber von {g.Count()} Buchungen in {TRANSACTIONS} verwendet.")
.ToList());
}
private async Task<string> BackupAsync(RawDataFile current)
{
var settings = settingsService.GetSettings();
var directory = Path.Combine(settings.DataPath, DataFolders.Backup, settingsService.GetMandator(),
settingsService.GetYear().ToString(), "json-" + DateTime.Now.ToString("yyyyMMddHHmmss"));
Directory.CreateDirectory(directory);
var backupPath = Path.Combine(directory, current.FileName);
await File.WriteAllTextAsync(backupPath, current.Text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
return backupPath;
}
private string PathOf(string fileName)
{
if (FileNames.Contains(fileName) == false)
{
throw new ArgumentException($"Unknown data file '{fileName}'", nameof(fileName));
}
return Path.Combine(settingsService.GetDbPath(), fileName);
}
private static string Hash(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes));
private static string Describe(JsonException ex)
{
// Message ends with " Path: ... | LineNumber: ... | BytePositionInLine: ...", which we
// show in our own words.
var message = ex.Message;
var cut = message.IndexOf(" Path:", StringComparison.Ordinal);
if (cut > 0)
{
message = message[..cut];
}
var position = ex.LineNumber is { } line ? $"Zeile {line + 1}, Spalte {(ex.BytePositionInLine ?? 0) + 1}" : "Unbekannte Stelle";
return $"{position} ({ex.Path}): {message}";
}
private static List<string> Limit(List<string> errors)
=> errors.Count <= MaxErrors
? errors
: errors.Take(MaxErrors).Append($"… und {errors.Count - MaxErrors} weitere.").ToList();
private static RawDataSaveResult Failed(params string[] errors) => new(errors, null, null);
}
}