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>
This commit is contained in:
Claudio Schaad 2026-10-22 17:55:20 +00:00 committed by clayschaad
parent 9138f08287
commit 255c133b85
14 changed files with 909 additions and 1 deletions

View file

@ -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 - **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 - **ChartService** — produces data for the Plotly booking-text charts on the transactions page
- **SettingsService** — manages the active year, mandator, and file paths - **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 - **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 ### 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.) - `Microsoft.FluentUI.AspNetCore.Components` — UI components (FluentDataGrid, FluentDialog, etc.)
- `Plotly.Blazor` — charts on the older chart pages - `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` - 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 - `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`) - `Schaad.Finance.dll` / `Schaad.Finance.Api.dll` — proprietary DLLs for MT940/CAMT053 parsing and FX rate lookups (FixerIo API key in `appsettings.Development.json`)

View file

@ -3,6 +3,7 @@
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally> <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageVersion Include="BlazorMonaco" Version="3.5.0" />
<PackageVersion Include="coverlet.collector" Version="10.1.0" /> <PackageVersion Include="coverlet.collector" Version="10.1.0" />
<PackageVersion Include="FreeSpire.PDF" Version="12.4.0" /> <PackageVersion Include="FreeSpire.PDF" Version="12.4.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.13" /> <PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.13" />

View file

@ -0,0 +1,33 @@
#nullable enable
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Schaad.Accounting.Interfaces
{
/// <summary>
/// The data files of the selected year and mandator as plain JSON text, for the JSON editor.
/// </summary>
public interface IRawDataRepository
{
/// <summary>Data file names, e.g. "Transactions.json".</summary>
IReadOnlyList<string> FileNames { get; }
Task<RawDataFile> LoadAsync(string fileName);
/// <summary>
/// Validates the text and, if it is valid and the file is still as loaded
/// (<paramref name="loadedHash"/>), backs up the current file and saves the text.
/// </summary>
Task<RawDataSaveResult> SaveAsync(string fileName, string text, string loadedHash);
}
/// <param name="Hash">Fingerprint of the file content, to detect changes made elsewhere.</param>
public record RawDataFile(string FileName, string Path, string Text, string Hash);
/// <param name="File">The saved file as now on disk (re-formatted); null if not saved.</param>
public record RawDataSaveResult(IReadOnlyList<string> Errors, RawDataFile? File, string? BackupPath)
{
public bool Saved => File != null;
}
}

View file

@ -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
{
/// <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);
}
}

View file

@ -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<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"));
}
}

View file

@ -14,6 +14,7 @@
<FluentNavLink Href="bookingtexts" Icon="@(new Size32.Text())" IconColor="Color.Accent">Buchungstexte</FluentNavLink> <FluentNavLink Href="bookingtexts" Icon="@(new Size32.Text())" IconColor="Color.Accent">Buchungstexte</FluentNavLink>
<FluentNavLink Href="Classes" Icon="@(new Icons.Filled.Size20.Class())" IconColor="Color.Accent">Klassen</FluentNavLink> <FluentNavLink Href="Classes" Icon="@(new Icons.Filled.Size20.Class())" IconColor="Color.Accent">Klassen</FluentNavLink>
<FluentNavLink Href="Accounts" Icon="@(new Size20.PersonAccounts())" IconColor="Color.Accent">Konten</FluentNavLink> <FluentNavLink Href="Accounts" Icon="@(new Size20.PersonAccounts())" IconColor="Color.Accent">Konten</FluentNavLink>
<FluentNavLink Href="json-editor" Icon="@(new Size20.Code())" IconColor="Color.Accent">JSON-Editor</FluentNavLink>
</FluentNavGroup> </FluentNavGroup>
<FluentNavGroup Title="Charts" Icon="@(new Size32.ChartMultiple())"> <FluentNavGroup Title="Charts" Icon="@(new Size32.ChartMultiple())">
<FluentNavLink Href="analytics" Icon="@(new Size20.DataHistogram())" IconColor="Color.Accent">Analyse</FluentNavLink> <FluentNavLink Href="analytics" Icon="@(new Size20.DataHistogram())" IconColor="Color.Accent">Analyse</FluentNavLink>

View file

@ -0,0 +1,93 @@
@page "/json-editor"
@rendermode InteractiveServer
@using BlazorMonaco.Editor
<PageTitle>JSON-Editor</PageTitle>
@if (file is null)
{
<Loading/>
return;
}
<div class="json-editor">
<div class="toolbar">
<FluentSelect TOption="string" Label="Datei" Width="230px"
Items="@repository.FileNames"
OptionText="@(n => n)"
OptionValue="@(n => n)"
SelectedOption="@fileName"
SelectedOptionChanged="@OnFileChanged"/>
<div class="actions">
<FluentButton Appearance="Appearance.Accent" IconStart="@(new Icons.Regular.Size16.Save())"
Disabled="@(dirty == false || saving || monacoLoaded == false)" Loading="@saving"
OnClick="SaveAsync">Speichern</FluentButton>
<FluentButton Appearance="Appearance.Neutral" IconStart="@(new Icons.Regular.Size16.ArrowClockwise())"
Disabled="@(monacoLoaded == false)" OnClick="ReloadAsync">Neu laden</FluentButton>
<span class="separator"></span>
<FluentButton Appearance="Appearance.Neutral" IconStart="@(new Icons.Regular.Size16.Search())"
Disabled="@(monacoLoaded == false)" title="Suchen (Ctrl+F)"
OnClick="@(() => RunEditorActionAsync("actions.find"))">Suchen</FluentButton>
<FluentButton Appearance="Appearance.Neutral" IconStart="@(new Icons.Regular.Size16.ArrowSwap())"
Disabled="@(monacoLoaded == false)" title="Suchen und ersetzen (Ctrl+H)"
OnClick="@(() => RunEditorActionAsync("editor.action.startFindReplaceAction"))">Ersetzen</FluentButton>
<FluentButton Appearance="Appearance.Neutral" IconStart="@(new Icons.Regular.Size16.TextAlignLeft())"
Disabled="@(monacoLoaded == false)" title="Formatieren (Shift+Alt+F)"
OnClick="@(() => RunEditorActionAsync("editor.action.formatDocument"))">Formatieren</FluentButton>
</div>
</div>
<div class="status">
<span>@Location / @fileName</span>
<span>@SizeLabel</span>
@if (dirty)
{
<span class="dirty">● Ungespeicherte Änderungen</span>
}
</div>
@if (errors.Count > 0)
{
<FluentMessageBar Intent="MessageIntent.Error" AllowDismiss="false" Title="Nicht gespeichert">
<ul class="errors">
@foreach (var error in errors)
{
<li>
@if (LineOf(error) is { } line)
{
<button type="button" class="link" title="Zu Zeile @line springen" @onclick="@(() => GoToLineAsync(line))">@error</button>
}
else
{
@error
}
</li>
}
</ul>
</FluentMessageBar>
}
<div class="editor-frame">
@if (monacoError is not null)
{
<FluentMessageBar Intent="MessageIntent.Error" AllowDismiss="false">Der Editor konnte nicht geladen werden: @monacoError</FluentMessageBar>
}
else if (monacoLoaded)
{
<StandaloneCodeEditor @ref="editor" Id="json-editor" CssClass="monaco-host"
ConstructionOptions="EditorOptions"
OnDidInit="OnEditorInit"
OnDidChangeModelContent="OnContentChanged"/>
}
else
{
<Loading/>
}
</div>
<div class="hint">
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 (.*).
</div>
</div>

View file

@ -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;
/// <summary>
/// Plain-text editor for the data files of the selected year and mandator. Saving is validated
/// and backed up by <see cref="IRawDataRepository"/>; this page only handles the editor.
/// </summary>
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<string> 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<IJSObjectReference>("import", "./js/unsaved-guard.js");
try
{
await using var module = await js.InvokeAsync<IJSObjectReference>("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<int> 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<bool> 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()}";
}

View file

@ -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;
}

View file

@ -25,6 +25,7 @@ namespace Schaad.Accounting.UI
services.AddScoped<ISubclassRepository, SubclassRepository>(); services.AddScoped<ISubclassRepository, SubclassRepository>();
services.AddScoped<ITransactionRepository, TransactionRepository>(); services.AddScoped<ITransactionRepository, TransactionRepository>();
services.AddScoped<IMultiYearRepository, MultiYearRepository>(); services.AddScoped<IMultiYearRepository, MultiYearRepository>();
services.AddScoped<IRawDataRepository, RawDataRepository>();
services.AddScoped<IChartService, ChartService>(); services.AddScoped<IChartService, ChartService>();
services.AddScoped<IAnalyticsService, AnalyticsService>(); services.AddScoped<IAnalyticsService, AnalyticsService>();

View file

@ -15,7 +15,10 @@ namespace Schaad.Accounting.UI
// Add services to the container. // Add services to the container.
builder.Services.AddRazorComponents() 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(); builder.Services.AddFluentUIComponents();

View file

@ -21,6 +21,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="BlazorMonaco" />
<PackageReference Include="Microsoft.FluentUI.AspNetCore.Components" /> <PackageReference Include="Microsoft.FluentUI.AspNetCore.Components" />
<PackageReference Include="Microsoft.FluentUI.AspNetCore.Components.Emoji" /> <PackageReference Include="Microsoft.FluentUI.AspNetCore.Components.Emoji" />
<PackageReference Include="Microsoft.FluentUI.AspNetCore.Components.Icons" /> <PackageReference Include="Microsoft.FluentUI.AspNetCore.Components.Icons" />

View file

@ -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;
}

View file

@ -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;
}