Stammdaten -> Texte bereinigen shows the bookings of one account in the selected year and edits only their Text: inline, search and replace (plain or regex with $1 groups) over the listed rows, tidying spaces, or setting one text for selected rows. A group panel shows the first-word groups the Analyse page will use, updated live. Saving goes through RawDataRepository.SaveTransactionTextsAsync: refused if the file changed since loading or a text is empty, previous version backed up, atomic save. Opened from the menu, a button per account on Konten, and a link on the Analyse page at account level. Also: the content area fills the window between header and footer, so dropdowns on short pages are no longer cut off. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
341 lines
11 KiB
C#
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;
|
|
}
|
|
}
|