From c9a25481f2d87b49da236af5af01843bde002593 Mon Sep 17 00:00:00 2001 From: Claudio Schaad Date: Thu, 22 Oct 2026 18:32:23 +0000 Subject: [PATCH] Add "Texte bereinigen" page for cleaning booking texts (#8) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary A new page **Stammdaten → Texte bereinigen** (`/text-cleanup?acc=`) 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 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: https://git.schaad.solutions/clayschaad/AccountingNext/pulls/8 Co-authored-by: Claudio Schaad Co-committed-by: Claudio Schaad --- CLAUDE.md | 1 + .../Interfaces/IRawDataRepository.cs | 16 + .../Repositories/RawDataRepository.cs | 50 +++ Schaad.Accounting.Services/TextReplacement.cs | 65 ++++ .../RawDataRepositoryTestShould.cs | 61 ++++ .../TextReplacementTestShould.cs | 67 ++++ .../Components/Layout/NavMenu.razor | 1 + .../Components/Pages/Accounts.razor | 3 + .../Pages/Analytics/Analytics.razor | 6 + .../Pages/Analytics/Analytics.razor.css | 11 + .../Components/Pages/TextCleanup.razor | 148 ++++++++ .../Components/Pages/TextCleanup.razor.cs | 341 ++++++++++++++++++ .../Components/Pages/TextCleanup.razor.css | 174 +++++++++ Schaad.Accounting.UI/wwwroot/app.css | 7 + 14 files changed, 951 insertions(+) create mode 100644 Schaad.Accounting.Services/TextReplacement.cs create mode 100644 Schaad.Accounting.Tests/TextReplacementTestShould.cs create mode 100644 Schaad.Accounting.UI/Components/Pages/TextCleanup.razor create mode 100644 Schaad.Accounting.UI/Components/Pages/TextCleanup.razor.cs create mode 100644 Schaad.Accounting.UI/Components/Pages/TextCleanup.razor.css diff --git a/CLAUDE.md b/CLAUDE.md index b9cf9d9..5349be2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,6 +59,7 @@ When a new year is opened, the previous year's data is copied as the starting po - **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}/` +- **Texte bereinigen** page (`TextCleanup`) — edits only the `Text` of one account's bookings in the selected year (inline, search/replace via `TextReplacement`, bulk set); saves through `RawDataRepository.SaveTransactionTextsAsync` - **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 diff --git a/Schaad.Accounting.Common/Interfaces/IRawDataRepository.cs b/Schaad.Accounting.Common/Interfaces/IRawDataRepository.cs index 32e1b5f..a17f7a7 100644 --- a/Schaad.Accounting.Common/Interfaces/IRawDataRepository.cs +++ b/Schaad.Accounting.Common/Interfaces/IRawDataRepository.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Threading.Tasks; +using Schaad.Accounting.Models; namespace Schaad.Accounting.Interfaces { @@ -20,8 +21,23 @@ namespace Schaad.Accounting.Interfaces /// (), backs up the current file and saves the text. /// Task SaveAsync(string fileName, string text, string loadedHash); + + /// + /// The transactions of the selected year as they are on disk, with the file's fingerprint + /// for . + /// + Task LoadTransactionsAsync(); + + /// + /// Changes only the Text of the given transactions (by Id), with the same safeguards as + /// : refused if the file changed since , + /// previous version backed up. + /// + Task SaveTransactionTextsAsync(IReadOnlyDictionary textById, string loadedHash); } + public record TransactionSnapshot(IReadOnlyList Transactions, string Hash); + /// Fingerprint of the file content, to detect changes made elsewhere. public record RawDataFile(string FileName, string Path, string Text, string Hash); diff --git a/Schaad.Accounting.Db/Repositories/RawDataRepository.cs b/Schaad.Accounting.Db/Repositories/RawDataRepository.cs index f8da4d9..1cf4713 100644 --- a/Schaad.Accounting.Db/Repositories/RawDataRepository.cs +++ b/Schaad.Accounting.Db/Repositories/RawDataRepository.cs @@ -112,6 +112,56 @@ namespace Schaad.Accounting.Repositories return new RawDataSaveResult([], await LoadAsync(fileName), backupPath); } + public async Task LoadTransactionsAsync() + { + var file = await LoadAsync(TRANSACTIONS); + return new TransactionSnapshot(ParseTransactions(file), file.Hash); + } + + private static List ParseTransactions(RawDataFile file) + => file.Text.Length == 0 + ? new List() + : JsonSerializer.Deserialize>(file.Text, JsonStorage.Options) ?? new List(); + + public async Task SaveTransactionTextsAsync(IReadOnlyDictionary textById, string loadedHash) + { + // One read: the backup is exactly the version that was checked. + var file = await LoadAsync(TRANSACTIONS); + if (file.Hash != loadedHash) + { + return Failed("Die Buchungen wurden seit dem Laden geändert (z.B. durch eine neue Buchung). Bitte neu laden."); + } + + var transactions = ParseTransactions(file); + var byId = transactions.Where(t => t.Id != null).ToDictionary(t => t.Id); + var errors = new List(); + foreach (var (id, text) in textById) + { + if (byId.TryGetValue(id, out var transaction) == false) + { + errors.Add($"Buchung \"{id}\" gibt es nicht mehr."); + } + else if (string.IsNullOrWhiteSpace(text)) + { + errors.Add($"Buchung vom {transaction.ValueDate:dd.MM.yyyy} über {transaction.Value:0.00}: Der Text darf nicht leer sein."); + } + else + { + transaction.Text = text; + } + } + if (errors.Count > 0) + { + return Failed(Limit(errors).ToArray()); + } + + var backupPath = await BackupAsync(file); + await SaveAsync(transactions, TRANSACTIONS); + logger.LogInformation("Changed {Count} transaction texts in {FilePath}; previous version in {BackupPath}", textById.Count, file.Path, backupPath); + + return new RawDataSaveResult([], await LoadAsync(TRANSACTIONS), backupPath); + } + private static List CheckIds(List items) { var errors = new List(); diff --git a/Schaad.Accounting.Services/TextReplacement.cs b/Schaad.Accounting.Services/TextReplacement.cs new file mode 100644 index 0000000..0302146 --- /dev/null +++ b/Schaad.Accounting.Services/TextReplacement.cs @@ -0,0 +1,65 @@ +#nullable enable + +using System; +using System.Text.RegularExpressions; + +namespace Schaad.Accounting.Services +{ + /// + /// Search and replace for booking texts: plain text (taken literally) or a regular expression + /// with $1-style groups in the replacement. + /// + public sealed class TextReplacement + { + // A pattern like (a+)+ on a long text could otherwise run for minutes. + private static readonly TimeSpan Timeout = TimeSpan.FromMilliseconds(500); + private static readonly Regex Spaces = new(" {2,}", RegexOptions.Compiled); + + private readonly Regex regex; + private readonly string replacement; + + private TextReplacement(Regex regex, string replacement) + { + this.regex = regex; + this.replacement = replacement; + } + + /// + /// Returns null and an error message (German, for the user) if the pattern is empty or not + /// a valid regular expression. + /// + public static TextReplacement? Create(string find, string replacement, bool useRegex, bool matchCase, out string? error) + { + error = null; + if (string.IsNullOrEmpty(find)) + { + error = "Bitte einen Suchtext eingeben."; + return null; + } + + var options = RegexOptions.CultureInvariant | (matchCase ? RegexOptions.None : RegexOptions.IgnoreCase); + try + { + return useRegex + ? new TextReplacement(new Regex(find, options, Timeout), replacement) + // Plain text: both the pattern and a '$' in the replacement are literal. + : new TextReplacement(new Regex(Regex.Escape(find), options, Timeout), replacement.Replace("$", "$$")); + } + catch (ArgumentException ex) + { + error = $"Ungültiger regulärer Ausdruck: {ex.Message}"; + return null; + } + } + + public bool IsMatch(string text) => regex.IsMatch(text); + + /// The pattern took too long on this text. + public string Apply(string text) => regex.Replace(text, replacement); + + /// + /// Removes leading/trailing spaces and collapses repeated spaces. + /// + public static string Tidy(string text) => Spaces.Replace(text.Trim(), " "); + } +} diff --git a/Schaad.Accounting.Tests/RawDataRepositoryTestShould.cs b/Schaad.Accounting.Tests/RawDataRepositoryTestShould.cs index 32a06b9..2e917ac 100644 --- a/Schaad.Accounting.Tests/RawDataRepositoryTestShould.cs +++ b/Schaad.Accounting.Tests/RawDataRepositoryTestShould.cs @@ -174,4 +174,65 @@ public class RawDataRepositoryTestShould : IDisposable { await Should.ThrowAsync(() => sut.LoadAsync("../appsettings.json")); } + + [Fact] + public async Task ReturnParsedTransactionsWithHashWhenLoadingTransactions() + { + var snapshot = await sut.LoadTransactionsAsync(); + + snapshot.Transactions.Single().Text.ShouldBe("Migros"); + snapshot.Hash.ShouldBe((await sut.LoadAsync("Transactions.json")).Hash); + } + + [Fact] + public async Task ChangeOnlyTheTextWhenSavingTransactionTexts() + { + var snapshot = await sut.LoadTransactionsAsync(); + + var result = await sut.SaveTransactionTextsAsync(new Dictionary { ["t1"] = "Luzern Migros" }, snapshot.Hash); + + result.Errors.ShouldBeEmpty(); + var saved = (await sut.LoadTransactionsAsync()).Transactions.Single(); + saved.Text.ShouldBe("Luzern Migros"); + saved.Value.ShouldBe(12.5m); + saved.OriginAccountId.ShouldBe("a1"); + saved.TargetAccountId.ShouldBe("a2"); + saved.ValueDate.ShouldBe(new DateTime(2026, 1, 10)); + File.ReadAllText(result.BackupPath!).ShouldBe(Transactions); + } + + [Fact] + public async Task RefuseEmptyTextWhenSavingTransactionTexts() + { + var snapshot = await sut.LoadTransactionsAsync(); + + var result = await sut.SaveTransactionTextsAsync(new Dictionary { ["t1"] = " " }, snapshot.Hash); + + result.Saved.ShouldBeFalse(); + result.Errors.Single().ShouldContain("darf nicht leer sein"); + File.ReadAllText(Path.Combine(dbDir, "Transactions.json")).ShouldBe(Transactions); + } + + [Fact] + public async Task RefuseUnknownTransactionWhenSavingTransactionTexts() + { + var snapshot = await sut.LoadTransactionsAsync(); + + var result = await sut.SaveTransactionTextsAsync(new Dictionary { ["gone"] = "Text" }, snapshot.Hash); + + result.Saved.ShouldBeFalse(); + result.Errors.Single().ShouldContain("\"gone\" gibt es nicht mehr"); + } + + [Fact] + public async Task RefuseWhenFileChangedSinceLoadingTransactions() + { + var snapshot = await sut.LoadTransactionsAsync(); + File.WriteAllText(Path.Combine(dbDir, "Transactions.json"), Transactions.Replace("12.5", "13")); + + var result = await sut.SaveTransactionTextsAsync(new Dictionary { ["t1"] = "Coop" }, snapshot.Hash); + + result.Saved.ShouldBeFalse(); + result.Errors.Single().ShouldContain("seit dem Laden geändert"); + } } diff --git a/Schaad.Accounting.Tests/TextReplacementTestShould.cs b/Schaad.Accounting.Tests/TextReplacementTestShould.cs new file mode 100644 index 0000000..68b95dc --- /dev/null +++ b/Schaad.Accounting.Tests/TextReplacementTestShould.cs @@ -0,0 +1,67 @@ +using Schaad.Accounting.Services; +using Shouldly; + +namespace Schaad.Accounting.Tests; + +public class TextReplacementTestShould +{ + private static TextReplacement Create(string find, string replacement, bool useRegex = false, bool matchCase = false) + { + var result = TextReplacement.Create(find, replacement, useRegex, matchCase, out var error); + error.ShouldBeNull(); + return result!; + } + + [Fact] + public void ReplaceIgnoringCaseWhenSearchingPlainText() + { + Create("urlaub", "Ferien").Apply("Urlaub Flims").ShouldBe("Ferien Flims"); + } + + [Fact] + public void RespectCaseWhenMatchCaseIsSet() + { + Create("urlaub", "Ferien", matchCase: true).Apply("Urlaub Flims").ShouldBe("Urlaub Flims"); + } + + [Fact] + public void TreatSpecialCharactersLiterallyWhenSearchingPlainText() + { + Create("(2022)", "$1").Apply("Provence (2022)").ShouldBe("Provence $1"); + } + + [Fact] + public void UseGroupsWhenSearchingWithRegex() + { + Create("^(.+) Luzern$", "Luzern $1", useRegex: true).Apply("Migros Luzern").ShouldBe("Luzern Migros"); + } + + [Fact] + public void LeaveTextUnchangedWhenNothingMatches() + { + Create("^(.+) Luzern$", "Luzern $1", useRegex: true).Apply("Florenz").ShouldBe("Florenz"); + } + + [Fact] + public void ReturnErrorWhenRegexIsInvalid() + { + TextReplacement.Create("Provence (", "x", useRegex: true, matchCase: false, out var error).ShouldBeNull(); + + error.ShouldNotBeNull(); + error.ShouldStartWith("Ungültiger regulärer Ausdruck"); + } + + [Fact] + public void ReturnErrorWhenSearchTextIsEmpty() + { + TextReplacement.Create("", "x", useRegex: false, matchCase: false, out var error).ShouldBeNull(); + + error.ShouldBe("Bitte einen Suchtext eingeben."); + } + + [Fact] + public void TrimAndCollapseSpacesWhenTidying() + { + TextReplacement.Tidy(" Schrankfachgebühr TKB ").ShouldBe("Schrankfachgebühr TKB"); + } +} diff --git a/Schaad.Accounting.UI/Components/Layout/NavMenu.razor b/Schaad.Accounting.UI/Components/Layout/NavMenu.razor index a3287d2..7bda4bb 100644 --- a/Schaad.Accounting.UI/Components/Layout/NavMenu.razor +++ b/Schaad.Accounting.UI/Components/Layout/NavMenu.razor @@ -15,6 +15,7 @@ Klassen Konten JSON-Editor + Texte bereinigen Analyse diff --git a/Schaad.Accounting.UI/Components/Pages/Accounts.razor b/Schaad.Accounting.UI/Components/Pages/Accounts.razor index 1fc9862..b297568 100644 --- a/Schaad.Accounting.UI/Components/Pages/Accounts.razor +++ b/Schaad.Accounting.UI/Components/Pages/Accounts.razor @@ -18,6 +18,9 @@ + + + diff --git a/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor b/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor index 1d90e84..8bcac02 100644 --- a/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor +++ b/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor @@ -54,6 +54,7 @@ +
@for (var i = 0; i < result.Breadcrumb.Count; i++) { @@ -68,6 +69,11 @@ } } + @if (node.Account is { } cleanupAccount) + { + Texte @settingsService.GetYear() bereinigen + } +
@if (IsAssets) diff --git a/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.css b/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.css index db84fda..ddb6022 100644 --- a/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.css +++ b/Schaad.Accounting.UI/Components/Pages/Analytics/Analytics.razor.css @@ -312,3 +312,14 @@ background: #ffffff; } } + +.crumbs { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px 16px; +} + +.cleanup-link { + font-size: 13px; +} diff --git a/Schaad.Accounting.UI/Components/Pages/TextCleanup.razor b/Schaad.Accounting.UI/Components/Pages/TextCleanup.razor new file mode 100644 index 0000000..7d9ae97 --- /dev/null +++ b/Schaad.Accounting.UI/Components/Pages/TextCleanup.razor @@ -0,0 +1,148 @@ +@page "/text-cleanup" +@rendermode InteractiveServer + +Texte bereinigen + +@if (snapshot is null) +{ + + return; +} + +
+
+ + + Jahr @Year + + + Speichern@(Dirty ? $" ({edits.Count})" : "") + + Verwerfen +
+ + @* No early return here: it would leave this
unclosed (invalid render tree). *@ + @if (account is null) + { + Bitte ein Konto wählen. + } + else + { + +
+ + + + + Ersetzen + Leerzeichen bereinigen +
+ + @if (selected.Count > 0) + { +
+ @selected.Count ausgewählt: + + Text setzen + Auswahl aufheben +
+ } + + @if (toolMessage is not null) + { +
@toolMessage
+ } + + @if (saveErrors.Count > 0) + { + + @foreach (var error in saveErrors) + { +
@error
+ } +
+ } + +
+ +
Gruppen (wie in der Analyse)
+ + + @foreach (var group in Groups) + { + + + + + + } + +
+ + @group.Count@Amount(group.Total)
+
+ + +
+ @AccountLabel(account): @VisibleRows.Count() von @rows.Count Buchungen@(Dirty ? $", {edits.Count} geändert" : "") +
+
+ + + + + + + + + + + + + @foreach (var row in VisibleRows) + { + var t = row.Transaction; + + + + + + + + + } + +
+ + DatumBetragGegenkontoTextBanktext
+ + @t.ValueDate.ToString("dd.MM.yyyy")@Amount(row.Amount)@row.CounterAccount + + @if (IsChanged(t)) + { +
@t.Text
+ } +
@t.BankTransactionText
+
+
+
+ +
+ Ersetzen und „Leerzeichen bereinigen“ wirken auf die angezeigten Buchungen; mit dem Filter lässt sich das eingrenzen. + Regex: z.B. Suchen ^(.+) Luzern$, Ersetzen Luzern $1 macht aus „Migros Luzern“ „Luzern Migros“. + Gespeichert wird nur der Text; die bisherige Datei wird vorher unter backup/… gesichert. +
+ } +
diff --git a/Schaad.Accounting.UI/Components/Pages/TextCleanup.razor.cs b/Schaad.Accounting.UI/Components/Pages/TextCleanup.razor.cs new file mode 100644 index 0000000..4f55763 --- /dev/null +++ b/Schaad.Accounting.UI/Components/Pages/TextCleanup.razor.cs @@ -0,0 +1,341 @@ +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; + +/// +/// 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 +/// (change check, backup). +/// +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 accounts = []; + private Dictionary accountsById = []; + private Account? account; + private TransactionSnapshot? snapshot; + private List rows = []; + + // Pending edits: transaction id → new text (only entries that differ from the stored text). + private readonly Dictionary edits = []; + private readonly HashSet 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 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("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 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 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 ChangeVisibleAsync(Func 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(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 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; + } +} diff --git a/Schaad.Accounting.UI/Components/Pages/TextCleanup.razor.css b/Schaad.Accounting.UI/Components/Pages/TextCleanup.razor.css new file mode 100644 index 0000000..5446824 --- /dev/null +++ b/Schaad.Accounting.UI/Components/Pages/TextCleanup.razor.css @@ -0,0 +1,174 @@ +.cleanup { + display: flex; + flex-direction: column; + gap: 10px; +} + +.toolbar, +.tools { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 8px; +} + +.tools { + align-items: center; +} + +.tools.bulk { + padding: 6px 10px; + background: #ebf3fc; + border-radius: 4px; +} + +.year { + color: #52514e; + padding-bottom: 6px; +} + +.spacer { + flex: 1; +} + +.tool-message { + color: #107c10; + font-size: 13px; +} + +.tool-message.error { + color: #c50f1f; +} + +.main { + display: grid; + grid-template-columns: 260px minmax(0, 1fr); + gap: 12px; + align-items: start; +} + +@media (max-width: 900px) { + .main { + grid-template-columns: minmax(0, 1fr); + } +} + +::deep .groups, +::deep .rows { + padding: 12px; + min-width: 0; +} + +.card-title { + font-weight: 600; + margin-bottom: 8px; +} + +.groups table { + width: 100%; + border-collapse: collapse; + font-size: 13px; +} + +.groups td { + padding: 3px 2px; + border-bottom: 1px solid #f0efea; +} + +.groups .name { + overflow-wrap: anywhere; +} + +.groups .count, +.amount { + text-align: right; + white-space: nowrap; + font-variant-numeric: tabular-nums; +} + +.link { + border: none; + background: none; + padding: 0; + font: inherit; + color: #0f6cbd; + text-align: left; + cursor: pointer; +} + +.link:hover, +.link:focus-visible { + text-decoration: underline; +} + +.table-scroll { + overflow-x: auto; +} + +.bookings { + width: 100%; + border-collapse: collapse; + font-size: 13px; +} + +.bookings th { + text-align: left; + color: #52514e; + font-weight: 600; + font-size: 12px; + padding: 4px 6px; + border-bottom: 1px solid #e1e0d9; +} + +.bookings td { + padding: 3px 6px; + border-bottom: 1px solid #f0efea; + vertical-align: top; +} + +.bookings .check { + width: 24px; +} + +.bookings .date { + white-space: nowrap; +} + +.bookings .counter, +.bookings .bank { + max-width: 220px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: #52514e; +} + +.bookings .text { + min-width: 240px; +} + +.bookings .text input { + width: 100%; + box-sizing: border-box; + font: inherit; + padding: 3px 6px; + border: 1px solid #d1d1d1; + border-radius: 3px; +} + +.bookings tr.changed .text input { + border-color: #0f6cbd; + background: #ebf3fc; +} + +.original { + color: #898781; + font-size: 11px; + text-decoration: line-through; + padding: 1px 2px; +} + +.hint { + color: #52514e; + font-size: 12px; +} diff --git a/Schaad.Accounting.UI/wwwroot/app.css b/Schaad.Accounting.UI/wwwroot/app.css index 1d2bc9a..a5c5ed9 100644 --- a/Schaad.Accounting.UI/wwwroot/app.css +++ b/Schaad.Accounting.UI/wwwroot/app.css @@ -20,6 +20,13 @@ a, .btn-link { padding-top: 1.1rem; } +/* The content area scrolls its own content (overflow: auto) and was only as tall as the page. + On short pages that cut off open dropdowns after a line or two; filling the window below the + header (50px) and above the footer (46px) leaves them room. */ +.body-content { + min-height: calc(100vh - 96px); +} + h1:focus { outline: none; }