AccountingNext/Schaad.Accounting.UI/Components/Pages/TextCleanup.razor.cs
Claudio Schaad c9a25481f2 Add "Texte bereinigen" page for cleaning booking texts (#8)
## Summary
A new page **Stammdaten → Texte bereinigen** (`/text-cleanup?acc=<number>`) to view and clean the booking texts of one account, e.g. "Ferien", in the year selected in the header.

Scope, as agreed: one account, the selected year, **only the `Text` field**, only existing bookings. Booking rules and the booking-text list are not touched.

### Page
- **Account dropdown**, filter, and a table of all bookings of the account (both sides, so refunds are negative): date, amount, counter account, the **editable text**, and the bank text as a read-only hint.
- **Group panel:** the texts grouped by first word, exactly as the Analyse page groups them, with count and total. It updates live while editing, and clicking a group filters the table.
- **Tools, acting on the rows currently shown** (the filter limits their reach):
  - **Search and replace:** plain text, or regex with `$1` groups. For example `^(.+) Luzern$` → `Luzern $1` turns "Migros Luzern" into "Luzern Migros".
  - **Leerzeichen bereinigen:** trims and collapses repeated spaces.
  - **Several rows at once:** checkboxes plus "Text setzen" give selected rows one text.
- **Changes:** changed rows are highlighted, with the old text crossed out underneath. Nothing is written until **Speichern (n)**; **Verwerfen** discards.
- **Unsaved changes:** leaving the page asks first (same `unsaved-guard.js` as the JSON editor).
- **Entry points:** the menu, a new button per account on **Konten**, and a "Texte <Jahr> bereinigen" link on the **Analyse** page at account level.

### Saving
`RawDataRepository.SaveTransactionTextsAsync` changes only the `Text` of the given bookings (by ID):
- refused if the file changed since loading (SHA-256), if a text is empty, or if a booking no longer exists;
- the previous version is backed up to `backup/{mandator}/{year}/json-{timestamp}/`, then saved atomically through `BaseRepository`, so cached data is refreshed;
- the file is read once, so the backup is exactly the version that was checked.

`TextReplacement` (Services) holds the search and replace logic:
- plain search is literal, including a `$` in the replacement;
- regex has a 500 ms timeout against runaway patterns;
- invalid patterns give a German error message.

### Layout fix (app-wide)
The content area (`.body-content`) scrolls its own content and was only as tall as the page, so on short pages open dropdowns were cut off after a line or two. It now fills at least the window between header and footer (`app.css`). On short pages the footer therefore sits at the bottom of the window. The account list is also limited to 360 px and scrolls.

## Test plan
- [x] `dotnet build`: no warnings
- [x] `dotnet test`: 111/111 pass, including 13 new tests:
  - 5 `RawDataRepositoryTestShould`: load with hash, only Text changes plus backup, empty text refused, unknown booking refused, changed file refused
  - 8 `TextReplacementTestShould`: case handling, literal special characters, regex groups, no match, invalid regex, empty search, tidy
- [x] Headless Chrome on a copy of the real data, Ferien account (21 bookings in 2026):
  - "Mailand" → "Milano" via replace, 1 direct edit, and 3 rows set via "Text setzen"; the group panel showed "Milano" before saving
  - after saving, exactly those 7 texts changed on disk, no other field of any booking, and a backup was written
- [x] Opening the page without an account: hint shown, no render error. An early `return` inside an element first caused "A frame of type 'Element' was left unclosed"; fixed and checked.
- [x] Account dropdown on the empty page opens fully (360 px, scrollable) within the content area
- [x] Links from Konten and Analyse open the page with the account preselected

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reviewed-on: #8
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
2026-10-22 18:32:23 +00:00

341 lines
11 KiB
C#

using System.Globalization;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Components;
using Microsoft.FluentUI.AspNetCore.Components;
using Microsoft.JSInterop;
using Schaad.Accounting.Datasets;
using Schaad.Accounting.Interfaces;
using Schaad.Accounting.Models;
using Schaad.Accounting.Services;
namespace Schaad.Accounting.UI.Components.Pages;
/// <summary>
/// Shows the booking texts of one account in the selected year and lets the user clean them:
/// edit single texts, search and replace (plain or regex) over the listed rows, tidy spaces, or
/// give several rows the same text. Only the Text field changes; saving goes through
/// <see cref="IRawDataRepository.SaveTransactionTextsAsync"/> (change check, backup).
/// </summary>
public partial class TextCleanup : ComponentBase, IAsyncDisposable
{
private static readonly CultureInfo SwissNumbers = CreateSwissNumbers();
[Inject]
private IRawDataRepository rawDataRepository { get; set; } = null!;
[Inject]
private IAccountRepository accountRepository { get; set; } = null!;
[Inject]
private ISettingsService settingsService { get; set; } = null!;
[Inject]
private NavigationManager navigation { get; set; } = null!;
[Inject]
private IDialogService dialogService { get; set; } = null!;
[Inject]
private IToastService toastService { get; set; } = null!;
[Inject]
private IJSRuntime js { get; set; } = null!;
[SupplyParameterFromQuery(Name = "acc")]
public int? AccountNumber { get; set; }
private record Row(Transaction Transaction, decimal Amount, string CounterAccount);
private record Group(string Name, int Count, decimal Total);
private IReadOnlyList<Account> accounts = [];
private Dictionary<string, Account> accountsById = [];
private Account? account;
private TransactionSnapshot? snapshot;
private List<Row> rows = [];
// Pending edits: transaction id → new text (only entries that differ from the stored text).
private readonly Dictionary<string, string> edits = [];
private readonly HashSet<string> selected = [];
private string filter = "";
private string find = "";
private string replacement = "";
private bool useRegex;
private bool matchCase;
private string bulkText = "";
private string? toolMessage;
private bool toolMessageIsError;
private IReadOnlyList<string> saveErrors = [];
private bool saving;
private IJSObjectReference? unsavedGuard;
protected override async Task OnParametersSetAsync()
{
if (accounts.Count == 0)
{
accounts = (await accountRepository.GetAccountListAsync()).OrderBy(a => a.Number).ToList();
accountsById = accounts.Where(a => a.Id != null).ToDictionary(a => a.Id);
}
var requested = accounts.FirstOrDefault(a => a.Number == AccountNumber);
if (requested?.Number == account?.Number && snapshot is not null)
{
return;
}
account = requested;
await LoadAsync();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
unsavedGuard = await js.InvokeAsync<IJSObjectReference>("import", "./js/unsaved-guard.js");
await UpdateGuardAsync();
}
}
private async Task LoadAsync()
{
snapshot = await rawDataRepository.LoadTransactionsAsync();
rows = account is null
? []
: snapshot.Transactions
.Where(t => t.TargetAccountId == account.Id || t.OriginAccountId == account.Id)
.OrderBy(t => t.ValueDate)
.Select(t =>
{
var isTarget = t.TargetAccountId == account.Id;
var counterId = isTarget ? t.OriginAccountId : t.TargetAccountId;
var counter = accountsById.TryGetValue(counterId ?? "", out var c) ? $"{c.Number} {c.Name}" : counterId ?? "";
// From the account's point of view: bookings to it count positive.
return new Row(t, isTarget ? t.Value : -t.Value, counter);
})
.ToList();
edits.Clear();
selected.Clear();
saveErrors = [];
toolMessage = null;
await UpdateGuardAsync();
}
private bool Dirty => edits.Count > 0;
private string TextOf(Transaction transaction) => edits.GetValueOrDefault(transaction.Id) ?? transaction.Text ?? "";
private bool IsChanged(Transaction transaction) => edits.ContainsKey(transaction.Id);
private async Task SetTextAsync(Transaction transaction, string text)
{
if (text == (transaction.Text ?? ""))
{
edits.Remove(transaction.Id);
}
else
{
edits[transaction.Id] = text;
}
await UpdateGuardAsync();
}
private IEnumerable<Row> VisibleRows => string.IsNullOrWhiteSpace(filter)
? rows
: rows.Where(r => Contains(TextOf(r.Transaction), filter)
|| Contains(r.Transaction.Text, filter)
|| Contains(r.Transaction.BankTransactionText, filter)
|| Contains(r.CounterAccount, filter));
private static bool Contains(string? text, string part) => text?.Contains(part, StringComparison.OrdinalIgnoreCase) == true;
// Same grouping as the Analyse page: by the first word of the text.
private IReadOnlyList<Group> Groups => rows
.GroupBy(r => TransactionDataset.GetTextGroup(TextOf(r.Transaction)) ?? "")
.Select(g => new Group(g.Key, g.Count(), g.Sum(r => r.Amount)))
.OrderByDescending(g => Math.Abs(g.Total))
.ToList();
private void FilterByGroup(string group) => filter = group;
private async Task ReplaceAsync()
{
var replacer = TextReplacement.Create(find, replacement, useRegex, matchCase, out var error);
if (replacer is null)
{
ShowToolMessage(error!, isError: true);
return;
}
try
{
var changed = await ChangeVisibleAsync(replacer.Apply);
ShowToolMessage(changed == 0 ? "Kein Text gefunden." : $"{changed} Texte geändert (noch nicht gespeichert).", isError: false);
}
catch (RegexMatchTimeoutException)
{
ShowToolMessage("Der reguläre Ausdruck braucht zu lange; bitte vereinfachen.", isError: true);
}
}
private async Task TidyAsync()
{
var changed = await ChangeVisibleAsync(TextReplacement.Tidy);
ShowToolMessage(changed == 0 ? "Keine überflüssigen Leerzeichen gefunden." : $"{changed} Texte bereinigt (noch nicht gespeichert).", isError: false);
}
private async Task<int> ChangeVisibleAsync(Func<string, string> change)
{
var changed = 0;
foreach (var row in VisibleRows.ToList())
{
var current = TextOf(row.Transaction);
var updated = change(current);
if (updated != current)
{
await SetTextAsync(row.Transaction, updated);
changed++;
}
}
return changed;
}
private void ToggleSelected(string id, bool on)
{
if (on)
{
selected.Add(id);
}
else
{
selected.Remove(id);
}
}
private bool AllVisibleSelected => VisibleRows.Any() && VisibleRows.All(r => selected.Contains(r.Transaction.Id));
private void ToggleAllVisible(bool on)
{
foreach (var row in VisibleRows)
{
ToggleSelected(row.Transaction.Id, on);
}
}
private async Task SetSelectedTextAsync()
{
if (string.IsNullOrWhiteSpace(bulkText))
{
ShowToolMessage("Bitte einen Text eingeben.", isError: true);
return;
}
foreach (var row in rows.Where(r => selected.Contains(r.Transaction.Id)))
{
await SetTextAsync(row.Transaction, bulkText.Trim());
}
ShowToolMessage($"{selected.Count} Texte gesetzt (noch nicht gespeichert).", isError: false);
selected.Clear();
}
private void ShowToolMessage(string message, bool isError)
{
toolMessage = message;
toolMessageIsError = isError;
}
private async Task SaveAsync()
{
if (snapshot is null || Dirty == false)
{
return;
}
saving = true;
try
{
var count = edits.Count;
var result = await rawDataRepository.SaveTransactionTextsAsync(new Dictionary<string, string>(edits), snapshot.Hash);
saveErrors = result.Errors;
if (result.Saved)
{
await LoadAsync();
toastService.ShowToast(ToastIntent.Success, $"{count} Texte gespeichert. Vorherige Version: {result.BackupPath}", 6000);
}
}
finally
{
saving = false;
}
}
private async Task DiscardAsync()
{
if (Dirty && await ConfirmDiscardAsync() == false)
{
return;
}
await LoadAsync();
}
private async Task OnAccountChanged(Account? chosen)
{
if (chosen is null || chosen.Number == account?.Number)
{
return;
}
if (Dirty)
{
if (await ConfirmDiscardAsync() == false)
{
StateHasChanged();
return;
}
edits.Clear();
await UpdateGuardAsync();
}
filter = "";
navigation.NavigateTo(navigation.GetUriWithQueryParameter("acc", chosen.Number));
}
private async Task<bool> ConfirmDiscardAsync()
{
var dialog = await dialogService.ShowConfirmationAsync(
$"{edits.Count} geänderte Texte sind noch nicht gespeichert. Verwerfen?", "Verwerfen", "Abbrechen", "Ungespeicherte Änderungen");
return (await dialog.Result).Cancelled == false;
}
// Asks before leaving the page while there are unsaved edits (see unsaved-guard.js).
private async Task UpdateGuardAsync()
{
if (unsavedGuard is not null)
{
await unsavedGuard.InvokeVoidAsync("set", Dirty ? $"{edits.Count} geänderte Texte sind noch nicht gespeichert. Seite trotzdem verlassen?" : null);
}
}
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 static string AccountLabel(Account a) => $"{a.Number} {a.Name}";
private static string Amount(decimal value) => value.ToString("#,0.00", SwissNumbers);
private int Year => settingsService.GetYear();
private static CultureInfo CreateSwissNumbers()
{
var culture = new CultureInfo("de-CH");
culture.NumberFormat.NumberGroupSeparator = "'";
return culture;
}
}