From 0c6e78b0d8da74144bf5e90ee607783325dc0893 Mon Sep 17 00:00:00 2001 From: Claudio Schaad Date: Thu, 22 Oct 2026 19:52:20 +0200 Subject: [PATCH] Add JSON editor for the data files New page Stammdaten -> JSON-Editor edits the data files of the selected year and mandator (default Transactions.json) as plain JSON in Monaco (BlazorMonaco 3.5.0, loaded on demand): highlighting, folding, live syntax errors, search and replace with regex, format. RawDataRepository saves only validated text: strict JSON (unknown properties rejected with line/column), unique non-empty Ids, transactions referencing existing accounts, accounts still used by transactions not removed. It refuses if the file changed since loading, backs up the previous version to backup/{mandator}/{year}/json-{timestamp}/, and saves through BaseRepository so caches are refreshed. - Hub MaximumReceiveMessageSize raised to 8 MB (files are several hundred KB) - unsaved-guard.js asks before leaving with unsaved changes; NavigationLock doesn't apply because routing between per-page interactive pages is static Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 + Directory.Packages.props | 1 + .../Interfaces/IRawDataRepository.cs | 33 +++ .../Repositories/RawDataRepository.cs | 212 ++++++++++++++++ .../RawDataRepositoryTestShould.cs | 177 +++++++++++++ .../Components/Layout/NavMenu.razor | 1 + .../Components/Pages/JsonEditor.razor | 93 +++++++ .../Components/Pages/JsonEditor.razor.cs | 239 ++++++++++++++++++ .../Components/Pages/JsonEditor.razor.css | 74 ++++++ Schaad.Accounting.UI/Extensions.cs | 1 + Schaad.Accounting.UI/Program.cs | 5 +- .../Schaad.Accounting.UI.csproj | 1 + Schaad.Accounting.UI/wwwroot/js/monaco.js | 27 ++ .../wwwroot/js/unsaved-guard.js | 44 ++++ 14 files changed, 909 insertions(+), 1 deletion(-) create mode 100644 Schaad.Accounting.Common/Interfaces/IRawDataRepository.cs create mode 100644 Schaad.Accounting.Db/Repositories/RawDataRepository.cs create mode 100644 Schaad.Accounting.Tests/RawDataRepositoryTestShould.cs create mode 100644 Schaad.Accounting.UI/Components/Pages/JsonEditor.razor create mode 100644 Schaad.Accounting.UI/Components/Pages/JsonEditor.razor.cs create mode 100644 Schaad.Accounting.UI/Components/Pages/JsonEditor.razor.css create mode 100644 Schaad.Accounting.UI/wwwroot/js/monaco.js create mode 100644 Schaad.Accounting.UI/wwwroot/js/unsaved-guard.js diff --git a/CLAUDE.md b/CLAUDE.md index 18d0bf2..b9cf9d9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,6 +58,7 @@ When a new year is opened, the previous year's data is copied as the starting po - **FileService** — imports bank statements (MT940, CAMT053 via external `Schaad.Finance.dll`), parses PDFs, manages backups - **ChartService** — produces data for the Plotly booking-text charts on the transactions page - **SettingsService** — manages the active year, mandator, and file paths +- **RawDataRepository** — plain-text load/save of the data files for the JSON editor page; validates (strict JSON, unique Ids, account references), refuses if the file changed since loading, and backs up the old version to `backup/{mandator}/{year}/json-{timestamp}/` - **AnalyticsService** — loads all years of the current mandator (via `MultiYearRepository`) into an `AccountingAnalysis` (expenses, income, net, assets) for the Analyse page; queries run in memory ### UI structure @@ -68,6 +69,7 @@ Pages live in `Schaad.Accounting.UI/Components/Pages/`. Each page typically has - `Microsoft.FluentUI.AspNetCore.Components` — UI components (FluentDataGrid, FluentDialog, etc.) - `Plotly.Blazor` — charts on the older chart pages +- `BlazorMonaco` — Monaco editor for the JSON editor page; loaded on demand by `wwwroot/js/monaco.js` instead of script tags in `App.razor` - Chart.js 4 + `chartjs-chart-treemap` — charts on the Analyse page; vendored in `wwwroot/lib/` (no CDN), wrapped by `wwwroot/js/charts.js` and `ChartJsChart.razor` - `FreeSpire.PDF` — PDF parsing for bank statement imports - `Schaad.Finance.dll` / `Schaad.Finance.Api.dll` — proprietary DLLs for MT940/CAMT053 parsing and FX rate lookups (FixerIo API key in `appsettings.Development.json`) diff --git a/Directory.Packages.props b/Directory.Packages.props index 1691407..b845095 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -3,6 +3,7 @@ true + diff --git a/Schaad.Accounting.Common/Interfaces/IRawDataRepository.cs b/Schaad.Accounting.Common/Interfaces/IRawDataRepository.cs new file mode 100644 index 0000000..32e1b5f --- /dev/null +++ b/Schaad.Accounting.Common/Interfaces/IRawDataRepository.cs @@ -0,0 +1,33 @@ +#nullable enable + +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Schaad.Accounting.Interfaces +{ + /// + /// The data files of the selected year and mandator as plain JSON text, for the JSON editor. + /// + public interface IRawDataRepository + { + /// Data file names, e.g. "Transactions.json". + IReadOnlyList FileNames { get; } + + Task LoadAsync(string fileName); + + /// + /// Validates the text and, if it is valid and the file is still as loaded + /// (), backs up the current file and saves the text. + /// + Task SaveAsync(string fileName, string text, string loadedHash); + } + + /// Fingerprint of the file content, to detect changes made elsewhere. + public record RawDataFile(string FileName, string Path, string Text, string Hash); + + /// The saved file as now on disk (re-formatted); null if not saved. + public record RawDataSaveResult(IReadOnlyList Errors, RawDataFile? File, string? BackupPath) + { + public bool Saved => File != null; + } +} diff --git a/Schaad.Accounting.Db/Repositories/RawDataRepository.cs b/Schaad.Accounting.Db/Repositories/RawDataRepository.cs new file mode 100644 index 0000000..f8da4d9 --- /dev/null +++ b/Schaad.Accounting.Db/Repositories/RawDataRepository.cs @@ -0,0 +1,212 @@ +#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 +{ + /// + /// Plain-text access to the data files of the selected year and mandator for the JSON editor. + /// Saving goes through (atomic write, cache + /// invalidation), but only after the text has been checked, because a broken file would break + /// every page that reads it. + /// + 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 logger) + : base(settingsService, cache, logger) + { + } + + public IReadOnlyList FileNames { get; } = + [ + TRANSACTIONS, + ACCOUNTS, + "BankTransactions.json", + "BookingRules.json", + "BookingTexts.json", + "SplitPredefinitions.json", + "SubClasses.json" + ]; + + public async Task LoadAsync(string fileName) + { + var path = PathOf(fileName); + var bytes = File.Exists(path) ? await File.ReadAllBytesAsync(path) : Array.Empty(); + return new RawDataFile(fileName, path, Encoding.UTF8.GetString(bytes), Hash(bytes)); + } + + public Task SaveAsync(string fileName, string text, string loadedHash) => fileName switch + { + TRANSACTIONS => SaveAsync(fileName, text, loadedHash), + ACCOUNTS => SaveAsync(fileName, text, loadedHash), + "BankTransactions.json" => SaveAsync(fileName, text, loadedHash), + "BookingRules.json" => SaveAsync(fileName, text, loadedHash), + "BookingTexts.json" => SaveAsync(fileName, text, loadedHash), + "SplitPredefinitions.json" => SaveAsync(fileName, text, loadedHash), + "SubClasses.json" => SaveAsync(fileName, text, loadedHash), + _ => throw new ArgumentException($"Unknown data file '{fileName}'", nameof(fileName)) + }; + + private async Task SaveAsync(string fileName, string text, string loadedHash) + { + List? items; + try + { + items = JsonSerializer.Deserialize>(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 transactions) + { + errors.AddRange(await CheckAccountReferencesAsync(transactions)); + } + if (items is List 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 CheckIds(List items) + { + var errors = new List(); + 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> CheckAccountReferencesAsync(List transactions) + { + var accountIds = (await LoadListAsync(ACCOUNTS)).Select(a => a.Id).ToHashSet(); + var errors = new List(); + 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> CheckAccountsStillUsedAsync(List accounts) + { + var accountIds = accounts.Select(a => a.Id).ToHashSet(); + var transactions = await LoadListAsync(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 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 Limit(List 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); + } +} diff --git a/Schaad.Accounting.Tests/RawDataRepositoryTestShould.cs b/Schaad.Accounting.Tests/RawDataRepositoryTestShould.cs new file mode 100644 index 0000000..32a06b9 --- /dev/null +++ b/Schaad.Accounting.Tests/RawDataRepositoryTestShould.cs @@ -0,0 +1,177 @@ +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(); + 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.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(), NullLogger.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(() => sut.LoadAsync("../appsettings.json")); + } +} diff --git a/Schaad.Accounting.UI/Components/Layout/NavMenu.razor b/Schaad.Accounting.UI/Components/Layout/NavMenu.razor index 0a8359d..a3287d2 100644 --- a/Schaad.Accounting.UI/Components/Layout/NavMenu.razor +++ b/Schaad.Accounting.UI/Components/Layout/NavMenu.razor @@ -14,6 +14,7 @@ Buchungstexte Klassen Konten + JSON-Editor Analyse diff --git a/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor b/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor new file mode 100644 index 0000000..9e33f15 --- /dev/null +++ b/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor @@ -0,0 +1,93 @@ +@page "/json-editor" +@rendermode InteractiveServer +@using BlazorMonaco.Editor + +JSON-Editor + +@if (file is null) +{ + + return; +} + +
+
+ + +
+ Speichern + Neu laden + + Suchen + Ersetzen + Formatieren +
+
+ +
+ @Location / @fileName + @SizeLabel + @if (dirty) + { + ● Ungespeicherte Änderungen + } +
+ + @if (errors.Count > 0) + { + +
    + @foreach (var error in errors) + { +
  • + @if (LineOf(error) is { } line) + { + + } + else + { + @error + } +
  • + } +
+
+ } + +
+ @if (monacoError is not null) + { + Der Editor konnte nicht geladen werden: @monacoError + } + else if (monacoLoaded) + { + + } + else + { + + } +
+ +
+ Gespeichert wird nur gültiges JSON mit bekannten Feldern, eindeutigen Ids und (bei Buchungen) existierenden Konten. + Vor dem Speichern wird die bisherige Datei unter backup/… gesichert. Suchen und Ersetzen können reguläre Ausdrücke (.*). +
+
diff --git a/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor.cs b/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor.cs new file mode 100644 index 0000000..4831b8b --- /dev/null +++ b/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor.cs @@ -0,0 +1,239 @@ +using System.Text.RegularExpressions; +using BlazorMonaco; +using BlazorMonaco.Editor; +using Microsoft.AspNetCore.Components; +using Microsoft.FluentUI.AspNetCore.Components; +using Microsoft.JSInterop; +using Schaad.Accounting.Interfaces; + +namespace Schaad.Accounting.UI.Components.Pages; + +/// +/// Plain-text editor for the data files of the selected year and mandator. Saving is validated +/// and backed up by ; this page only handles the editor. +/// +public partial class JsonEditor : ComponentBase, IAsyncDisposable +{ + private static readonly Regex LinePrefix = new(@"^Zeile (\d+)", RegexOptions.Compiled); + + [Inject] + private IRawDataRepository repository { get; set; } = null!; + + [Inject] + private ISettingsService settingsService { get; set; } = null!; + + [Inject] + private IJSRuntime js { get; set; } = null!; + + [Inject] + private NavigationManager navigation { get; set; } = null!; + + [Inject] + private IDialogService dialogService { get; set; } = null!; + + [Inject] + private IToastService toastService { get; set; } = null!; + + [SupplyParameterFromQuery(Name = "file")] + public string? FileParameter { get; set; } + + private StandaloneCodeEditor? editor; + private IJSObjectReference? unsavedGuard; + private bool monacoLoaded; + private string? monacoError; + private RawDataFile? file; + private string fileName = ""; + private int savedVersion; + private bool dirty; + private bool saving; + private IReadOnlyList errors = []; + + protected override async Task OnParametersSetAsync() + { + var requested = repository.FileNames.Contains(FileParameter ?? "") ? FileParameter! : repository.FileNames[0]; + if (requested == fileName) + { + return; + } + fileName = requested; + file = await repository.LoadAsync(fileName); + errors = []; + if (editor is not null) + { + await ShowFileAsync(); + } + } + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (firstRender == false) + { + return; + } + unsavedGuard = await js.InvokeAsync("import", "./js/unsaved-guard.js"); + try + { + await using var module = await js.InvokeAsync("import", "./js/monaco.js"); + await module.InvokeVoidAsync("ensureLoaded"); + monacoLoaded = true; + } + catch (JSException ex) + { + monacoError = ex.Message; + } + StateHasChanged(); + } + + private StandaloneEditorConstructionOptions EditorOptions(StandaloneCodeEditor _) => new() + { + Language = "json", + Value = file?.Text ?? "", + AutomaticLayout = true, + Folding = true, + FormatOnPaste = true, + ScrollBeyondLastLine = false, + TabSize = 2, + Minimap = new EditorMinimapOptions { Enabled = true } + }; + + private async Task OnEditorInit() => savedVersion = await CurrentVersionAsync(); + + // The alternative version id goes back to its old value on undo, so undoing all edits + // makes the file clean again. + private async Task CurrentVersionAsync() => await (await editor!.GetModel()).GetAlternativeVersionId(); + + private async Task OnContentChanged(ModelContentChangedEvent _) => await SetDirtyAsync(await CurrentVersionAsync() != savedVersion); + + // Also tells the browser-side guard to ask before leaving the page (links, reload, closing + // the tab, switching year or mandator). + private async Task SetDirtyAsync(bool value) + { + if (value == dirty) + { + return; + } + dirty = value; + if (unsavedGuard is not null) + { + await unsavedGuard.InvokeVoidAsync("set", dirty ? $"Die Änderungen an {fileName} sind noch nicht gespeichert. Seite trotzdem verlassen?" : null); + } + } + + private async Task ShowFileAsync() + { + await editor!.SetValue(file!.Text); + savedVersion = await CurrentVersionAsync(); + await SetDirtyAsync(false); + } + + private async Task SaveAsync() + { + if (editor is null || file is null) + { + return; + } + saving = true; + try + { + var text = await editor.GetValue(); + var result = await repository.SaveAsync(fileName, text, file.Hash); + errors = result.Errors; + if (result.Saved) + { + // Saved re-formatted; show what is on disk now, at the same place. + var position = await editor.GetPosition(); + file = result.File!; + await ShowFileAsync(); + await editor.SetPosition(position, "save"); + await editor.RevealLineInCenter(position.LineNumber); + toastService.ShowToast(ToastIntent.Success, $"{fileName} gespeichert. Vorherige Version: {result.BackupPath}", 6000); + } + } + finally + { + saving = false; + } + } + + private async Task ReloadAsync() + { + if (dirty && await ConfirmDiscardAsync() == false) + { + return; + } + file = await repository.LoadAsync(fileName); + errors = []; + await ShowFileAsync(); + } + + // Switching goes through the URL, so the file is part of bookmarks and back/forward. + private async Task OnFileChanged(string name) + { + if (name == fileName) + { + return; + } + if (dirty) + { + if (await ConfirmDiscardAsync() == false) + { + // Re-render puts the select back on the current file. + StateHasChanged(); + return; + } + await SetDirtyAsync(false); + } + navigation.NavigateTo(navigation.GetUriWithQueryParameter("file", name)); + } + + private async Task ConfirmDiscardAsync() + { + var dialog = await dialogService.ShowConfirmationAsync( + $"Die Änderungen an {fileName} sind noch nicht gespeichert. Verwerfen?", "Verwerfen", "Abbrechen", "Ungespeicherte Änderungen"); + var result = await dialog.Result; + return result.Cancelled == false; + } + + private async Task RunEditorActionAsync(string actionId) + { + if (editor is null) + { + return; + } + await editor.Focus(); + await editor.Trigger("toolbar", actionId); + } + + private static int? LineOf(string error) => LinePrefix.Match(error) is { Success: true } match ? int.Parse(match.Groups[1].Value) : null; + + private async Task GoToLineAsync(int line) + { + if (editor is null) + { + return; + } + await editor.SetPosition(new Position { LineNumber = line, Column = 1 }, "error"); + await editor.RevealLineInCenter(line); + await editor.Focus(); + } + + public async ValueTask DisposeAsync() + { + try + { + if (unsavedGuard is not null) + { + await unsavedGuard.InvokeVoidAsync("set", (object?)null); + await unsavedGuard.DisposeAsync(); + } + } + catch (JSDisconnectedException) + { + // Circuit gone; the page and its guard are gone with it. + } + } + + private string SizeLabel => file is null ? "" : $"{System.Text.Encoding.UTF8.GetByteCount(file.Text) / 1024.0:0} KB"; + + private string Location => $"{settingsService.GetMandator()} / {settingsService.GetYear()}"; +} diff --git a/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor.css b/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor.css new file mode 100644 index 0000000..c3f96a2 --- /dev/null +++ b/Schaad.Accounting.UI/Components/Pages/JsonEditor.razor.css @@ -0,0 +1,74 @@ +.json-editor { + display: flex; + flex-direction: column; + gap: 10px; +} + +.toolbar { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + justify-content: space-between; + gap: 12px; +} + +.actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} + +.separator { + width: 1px; + align-self: stretch; + background: #e1e0d9; + margin: 0 4px; +} + +.status { + display: flex; + flex-wrap: wrap; + gap: 16px; + color: #52514e; + font-size: 12px; +} + +.dirty { + color: #c50f1f; + font-weight: 600; +} + +.errors { + margin: 4px 0 0; + padding-left: 18px; +} + +/* A button, not a link: it only moves the cursor, it must not navigate. */ +.errors .link { + border: none; + background: none; + padding: 0; + font: inherit; + color: #0f6cbd; + text-align: left; + text-decoration: underline; + cursor: pointer; +} + +.editor-frame { + height: calc(100vh - 290px); + min-height: 380px; + border: 1px solid #e1e0d9; + border-radius: 4px; + overflow: hidden; +} + +.editor-frame ::deep .monaco-host { + height: 100%; +} + +.hint { + color: #52514e; + font-size: 12px; +} diff --git a/Schaad.Accounting.UI/Extensions.cs b/Schaad.Accounting.UI/Extensions.cs index 1c7e815..16cc13d 100644 --- a/Schaad.Accounting.UI/Extensions.cs +++ b/Schaad.Accounting.UI/Extensions.cs @@ -25,6 +25,7 @@ namespace Schaad.Accounting.UI services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/Schaad.Accounting.UI/Program.cs b/Schaad.Accounting.UI/Program.cs index 5475d30..6591285 100644 --- a/Schaad.Accounting.UI/Program.cs +++ b/Schaad.Accounting.UI/Program.cs @@ -15,7 +15,10 @@ namespace Schaad.Accounting.UI // Add services to the container. builder.Services.AddRazorComponents() - .AddInteractiveServerComponents(); + .AddInteractiveServerComponents() + // The JSON editor sends whole data files (Transactions.json is several hundred KB) + // from the browser; the default limit is 32 KB per message. + .AddHubOptions(options => options.MaximumReceiveMessageSize = 8 * 1024 * 1024); builder.Services.AddFluentUIComponents(); diff --git a/Schaad.Accounting.UI/Schaad.Accounting.UI.csproj b/Schaad.Accounting.UI/Schaad.Accounting.UI.csproj index d9c617f..d8ecedb 100644 --- a/Schaad.Accounting.UI/Schaad.Accounting.UI.csproj +++ b/Schaad.Accounting.UI/Schaad.Accounting.UI.csproj @@ -21,6 +21,7 @@
+ diff --git a/Schaad.Accounting.UI/wwwroot/js/monaco.js b/Schaad.Accounting.UI/wwwroot/js/monaco.js new file mode 100644 index 0000000..cc18080 --- /dev/null +++ b/Schaad.Accounting.UI/wwwroot/js/monaco.js @@ -0,0 +1,27 @@ +// Loads the Monaco editor (shipped inside the BlazorMonaco package) on first use, so only the +// JSON editor page pays for it. BlazorMonaco normally expects three script tags in App.razor; +// this loads the same three in the same order. + +let loading; + +function loadScript(src) { + return new Promise((resolve, reject) => { + const script = document.createElement('script'); + script.src = src; + script.onload = resolve; + script.onerror = () => reject(new Error(`${src} could not be loaded`)); + document.head.appendChild(script); + }); +} + +export function ensureLoaded() { + loading ??= (async () => { + // Sets the AMD path config (var require = ...) and window.blazorMonaco. + await loadScript('_content/BlazorMonaco/jsInterop.js'); + await loadScript('_content/BlazorMonaco/lib/monaco-editor/min/vs/loader.js'); + await loadScript('_content/BlazorMonaco/lib/monaco-editor/min/vs/editor/editor.main.js'); + // editor.main registers itself as an AMD module; wait until it (and window.monaco) is ready. + await new Promise(resolve => window.require(['vs/editor/editor.main'], resolve)); + })(); + return loading; +} diff --git a/Schaad.Accounting.UI/wwwroot/js/unsaved-guard.js b/Schaad.Accounting.UI/wwwroot/js/unsaved-guard.js new file mode 100644 index 0000000..015c124 --- /dev/null +++ b/Schaad.Accounting.UI/wwwroot/js/unsaved-guard.js @@ -0,0 +1,44 @@ +// Asks before leaving a page with unsaved changes. Blazor's NavigationLock can't do this here: +// pages are interactive one by one, so navigation between them runs through the static router +// (enhanced navigation), which doesn't consult interactive components. + +let message = null; + +function onClick(event) { + if (message === null || event.defaultPrevented || event.button !== 0 + || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) { + return; + } + const link = event.target.closest?.('a[href]'); + if (!link || link.target === '_blank' || link.hasAttribute('download')) { + return; + } + const url = new URL(link.href, document.baseURI); + if (url.origin !== location.origin || (url.pathname === location.pathname && url.search === location.search)) { + return; + } + if (confirm(message)) { + // Leaving for good; don't ask a second time on unload. + message = null; + } else { + // Runs in the capture phase, before Blazor's own link handling. + event.preventDefault(); + event.stopImmediatePropagation(); + } +} + +function onBeforeUnload(event) { + if (message !== null) { + // Browsers show their own text; the call just has to ask. + event.preventDefault(); + event.returnValue = ''; + } +} + +document.addEventListener('click', onClick, true); +window.addEventListener('beforeunload', onBeforeUnload); + +/** Ask with this message before leaving the page; null stops asking. */ +export function set(newMessage) { + message = newMessage ?? null; +}