Add "Texte bereinigen" page for cleaning booking texts #8
14 changed files with 951 additions and 0 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
|||
/// (<paramref name="loadedHash"/>), backs up the current file and saves the text.
|
||||
/// </summary>
|
||||
Task<RawDataSaveResult> SaveAsync(string fileName, string text, string loadedHash);
|
||||
|
||||
/// <summary>
|
||||
/// The transactions of the selected year as they are on disk, with the file's fingerprint
|
||||
/// for <see cref="SaveTransactionTextsAsync"/>.
|
||||
/// </summary>
|
||||
Task<TransactionSnapshot> LoadTransactionsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Changes only the Text of the given transactions (by Id), with the same safeguards as
|
||||
/// <see cref="SaveAsync"/>: refused if the file changed since <paramref name="loadedHash"/>,
|
||||
/// previous version backed up.
|
||||
/// </summary>
|
||||
Task<RawDataSaveResult> SaveTransactionTextsAsync(IReadOnlyDictionary<string, string> textById, string loadedHash);
|
||||
}
|
||||
|
||||
public record TransactionSnapshot(IReadOnlyList<Transaction> Transactions, string Hash);
|
||||
|
||||
/// <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);
|
||||
|
||||
|
|
|
|||
|
|
@ -112,6 +112,56 @@ namespace Schaad.Accounting.Repositories
|
|||
return new RawDataSaveResult([], await LoadAsync(fileName), backupPath);
|
||||
}
|
||||
|
||||
public async Task<TransactionSnapshot> LoadTransactionsAsync()
|
||||
{
|
||||
var file = await LoadAsync(TRANSACTIONS);
|
||||
return new TransactionSnapshot(ParseTransactions(file), file.Hash);
|
||||
}
|
||||
|
||||
private static List<Transaction> ParseTransactions(RawDataFile file)
|
||||
=> file.Text.Length == 0
|
||||
? new List<Transaction>()
|
||||
: JsonSerializer.Deserialize<List<Transaction>>(file.Text, JsonStorage.Options) ?? new List<Transaction>();
|
||||
|
||||
public async Task<RawDataSaveResult> SaveTransactionTextsAsync(IReadOnlyDictionary<string, string> 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<string>();
|
||||
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<string> CheckIds<T>(List<T> items)
|
||||
{
|
||||
var errors = new List<string>();
|
||||
|
|
|
|||
65
Schaad.Accounting.Services/TextReplacement.cs
Normal file
65
Schaad.Accounting.Services/TextReplacement.cs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Schaad.Accounting.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Search and replace for booking texts: plain text (taken literally) or a regular expression
|
||||
/// with $1-style groups in the replacement.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns null and an error message (German, for the user) if the pattern is empty or not
|
||||
/// a valid regular expression.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <exception cref="RegexMatchTimeoutException">The pattern took too long on this text.</exception>
|
||||
public string Apply(string text) => regex.Replace(text, replacement);
|
||||
|
||||
/// <summary>
|
||||
/// Removes leading/trailing spaces and collapses repeated spaces.
|
||||
/// </summary>
|
||||
public static string Tidy(string text) => Spaces.Replace(text.Trim(), " ");
|
||||
}
|
||||
}
|
||||
|
|
@ -174,4 +174,65 @@ public class RawDataRepositoryTestShould : IDisposable
|
|||
{
|
||||
await Should.ThrowAsync<ArgumentException>(() => 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<string, string> { ["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<string, string> { ["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<string, string> { ["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<string, string> { ["t1"] = "Coop" }, snapshot.Hash);
|
||||
|
||||
result.Saved.ShouldBeFalse();
|
||||
result.Errors.Single().ShouldContain("seit dem Laden geändert");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
67
Schaad.Accounting.Tests/TextReplacementTestShould.cs
Normal file
67
Schaad.Accounting.Tests/TextReplacementTestShould.cs
Normal file
|
|
@ -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");
|
||||
}
|
||||
}
|
||||
|
|
@ -15,6 +15,7 @@
|
|||
<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="json-editor" Icon="@(new Size20.Code())" IconColor="Color.Accent">JSON-Editor</FluentNavLink>
|
||||
<FluentNavLink Href="text-cleanup" Icon="@(new Size20.TextEditStyle())" IconColor="Color.Accent">Texte bereinigen</FluentNavLink>
|
||||
</FluentNavGroup>
|
||||
<FluentNavGroup Title="Charts" Icon="@(new Size32.ChartMultiple())">
|
||||
<FluentNavLink Href="analytics" Icon="@(new Size20.DataHistogram())" IconColor="Color.Accent">Analyse</FluentNavLink>
|
||||
|
|
|
|||
|
|
@ -18,6 +18,9 @@
|
|||
<PropertyColumn Property="@(p => p.BankAccountNumber)" />
|
||||
<PropertyColumn Property="@(p => p.StartBalance)" Format="C2"/>
|
||||
<PropertyColumn Property="@(p => p.LastBankBalance)" Format="C2" />
|
||||
<TemplateColumn Align="Align.Center" Width="50px">
|
||||
<FluentAnchor Href="@($"text-cleanup?acc={context.Number}")" Appearance="Appearance.Neutral" IconStart="@(new Icons.Regular.Size16.TextEditStyle())" title="Buchungstexte bereinigen" aria-label="Buchungstexte bereinigen" />
|
||||
</TemplateColumn>
|
||||
<TemplateColumn Align="Align.Center" Width="50px">
|
||||
<FluentButton IconEnd="@(new Icons.Regular.Size16.Delete())" Appearance="Appearance.Neutral" title="Löschen" aria-label="Löschen" OnClick="@(() => DeleteAsync(context.Id))" />
|
||||
</TemplateColumn>
|
||||
|
|
|
|||
|
|
@ -54,6 +54,7 @@
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<div class="crumbs">
|
||||
<FluentBreadcrumb>
|
||||
@for (var i = 0; i < result.Breadcrumb.Count; i++)
|
||||
{
|
||||
|
|
@ -68,6 +69,11 @@
|
|||
}
|
||||
}
|
||||
</FluentBreadcrumb>
|
||||
@if (node.Account is { } cleanupAccount)
|
||||
{
|
||||
<a class="cleanup-link" href="@($"text-cleanup?acc={cleanupAccount}")" title="Buchungstexte dieses Kontos im Jahr @settingsService.GetYear() bearbeiten">Texte @settingsService.GetYear() bereinigen</a>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="kpis">
|
||||
@if (IsAssets)
|
||||
|
|
|
|||
|
|
@ -312,3 +312,14 @@
|
|||
background: #ffffff;
|
||||
}
|
||||
}
|
||||
|
||||
.crumbs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px 16px;
|
||||
}
|
||||
|
||||
.cleanup-link {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
|
|
|||
148
Schaad.Accounting.UI/Components/Pages/TextCleanup.razor
Normal file
148
Schaad.Accounting.UI/Components/Pages/TextCleanup.razor
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
@page "/text-cleanup"
|
||||
@rendermode InteractiveServer
|
||||
|
||||
<PageTitle>Texte bereinigen</PageTitle>
|
||||
|
||||
@if (snapshot is null)
|
||||
{
|
||||
<Loading/>
|
||||
return;
|
||||
}
|
||||
|
||||
<div class="cleanup">
|
||||
<div class="toolbar">
|
||||
<FluentSelect TOption="Account" Label="Konto" Width="280px" Height="360px"
|
||||
Items="@accounts"
|
||||
OptionText="@AccountLabel"
|
||||
OptionValue="@(a => a.Number.ToString())"
|
||||
Placeholder="Konto wählen…"
|
||||
SelectedOption="@account"
|
||||
SelectedOptionChanged="@OnAccountChanged"/>
|
||||
<FluentSearch @bind-Value="filter" Immediate="true" Placeholder="Filter…" Style="width: 260px;"/>
|
||||
<span class="year">Jahr @Year</span>
|
||||
<span class="spacer"></span>
|
||||
<FluentButton Appearance="Appearance.Accent" IconStart="@(new Icons.Regular.Size16.Save())"
|
||||
Disabled="@(Dirty == false || saving)" Loading="@saving" OnClick="SaveAsync">
|
||||
Speichern@(Dirty ? $" ({edits.Count})" : "")
|
||||
</FluentButton>
|
||||
<FluentButton Appearance="Appearance.Neutral" Disabled="@(Dirty == false)" OnClick="DiscardAsync">Verwerfen</FluentButton>
|
||||
</div>
|
||||
|
||||
@* No early return here: it would leave this <div> unclosed (invalid render tree). *@
|
||||
@if (account is null)
|
||||
{
|
||||
<FluentMessageBar Intent="MessageIntent.Info" AllowDismiss="false">Bitte ein Konto wählen.</FluentMessageBar>
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
<div class="tools">
|
||||
<FluentTextField @bind-Value="find" Placeholder="Suchen" Style="width: 220px;" aria-label="Suchen"/>
|
||||
<FluentTextField @bind-Value="replacement" Placeholder="Ersetzen durch" Style="width: 220px;" aria-label="Ersetzen durch"/>
|
||||
<FluentCheckbox @bind-Value="useRegex" Label="Regex"/>
|
||||
<FluentCheckbox @bind-Value="matchCase" Label="Gross/klein"/>
|
||||
<FluentButton Appearance="Appearance.Neutral" IconStart="@(new Icons.Regular.Size16.ArrowSwap())"
|
||||
OnClick="ReplaceAsync" title="In den angezeigten Texten ersetzen">Ersetzen</FluentButton>
|
||||
<FluentButton Appearance="Appearance.Lightweight" OnClick="TidyAsync"
|
||||
title="Leerzeichen am Anfang/Ende entfernen, doppelte zusammenfassen">Leerzeichen bereinigen</FluentButton>
|
||||
</div>
|
||||
|
||||
@if (selected.Count > 0)
|
||||
{
|
||||
<div class="tools bulk">
|
||||
<span>@selected.Count ausgewählt:</span>
|
||||
<FluentTextField @bind-Value="bulkText" Placeholder="Neuer Text" Style="width: 260px;" aria-label="Neuer Text für die ausgewählten Buchungen"/>
|
||||
<FluentButton Appearance="Appearance.Neutral" OnClick="SetSelectedTextAsync">Text setzen</FluentButton>
|
||||
<FluentButton Appearance="Appearance.Lightweight" OnClick="@(() => selected.Clear())">Auswahl aufheben</FluentButton>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (toolMessage is not null)
|
||||
{
|
||||
<div class="tool-message @(toolMessageIsError ? "error" : "")">@toolMessage</div>
|
||||
}
|
||||
|
||||
@if (saveErrors.Count > 0)
|
||||
{
|
||||
<FluentMessageBar Intent="MessageIntent.Error" AllowDismiss="false" Title="Nicht gespeichert">
|
||||
@foreach (var error in saveErrors)
|
||||
{
|
||||
<div>@error</div>
|
||||
}
|
||||
</FluentMessageBar>
|
||||
}
|
||||
|
||||
<div class="main">
|
||||
<FluentCard class="groups">
|
||||
<div class="card-title">Gruppen (wie in der Analyse)</div>
|
||||
<table>
|
||||
<tbody>
|
||||
@foreach (var group in Groups)
|
||||
{
|
||||
<tr @key="group.Name">
|
||||
<td class="name">
|
||||
<button type="button" class="link" title="Nach dieser Gruppe filtern" @onclick="@(() => FilterByGroup(group.Name))">@(string.IsNullOrEmpty(group.Name) ? "(ohne Text)" : group.Name)</button>
|
||||
</td>
|
||||
<td class="count">@group.Count</td>
|
||||
<td class="amount">@Amount(group.Total)</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</FluentCard>
|
||||
|
||||
<FluentCard class="rows">
|
||||
<div class="card-title">
|
||||
@AccountLabel(account): @VisibleRows.Count() von @rows.Count Buchungen@(Dirty ? $", {edits.Count} geändert" : "")
|
||||
</div>
|
||||
<div class="table-scroll">
|
||||
<table class="bookings">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="check">
|
||||
<input type="checkbox" aria-label="Alle angezeigten auswählen" checked="@AllVisibleSelected"
|
||||
@onchange="@(e => ToggleAllVisible((bool)e.Value!))"/>
|
||||
</th>
|
||||
<th>Datum</th>
|
||||
<th class="amount">Betrag</th>
|
||||
<th>Gegenkonto</th>
|
||||
<th class="text">Text</th>
|
||||
<th>Banktext</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var row in VisibleRows)
|
||||
{
|
||||
var t = row.Transaction;
|
||||
<tr @key="t.Id" class="@(IsChanged(t) ? "changed" : "")">
|
||||
<td class="check">
|
||||
<input type="checkbox" aria-label="Auswählen" checked="@selected.Contains(t.Id)"
|
||||
@onchange="@(e => ToggleSelected(t.Id, (bool)e.Value!))"/>
|
||||
</td>
|
||||
<td class="date">@t.ValueDate.ToString("dd.MM.yyyy")</td>
|
||||
<td class="amount">@Amount(row.Amount)</td>
|
||||
<td class="counter" title="@row.CounterAccount">@row.CounterAccount</td>
|
||||
<td class="text">
|
||||
<input type="text" value="@TextOf(t)" aria-label="Text"
|
||||
@onchange="@(e => SetTextAsync(t, e.Value?.ToString() ?? ""))"/>
|
||||
@if (IsChanged(t))
|
||||
{
|
||||
<div class="original" title="Bisheriger Text">@t.Text</div>
|
||||
}
|
||||
</td>
|
||||
<td class="bank" title="@t.BankTransactionText">@t.BankTransactionText</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</FluentCard>
|
||||
</div>
|
||||
|
||||
<div class="hint">
|
||||
Ersetzen und „Leerzeichen bereinigen“ wirken auf die angezeigten Buchungen; mit dem Filter lässt sich das eingrenzen.
|
||||
Regex: z.B. Suchen <code>^(.+) Luzern$</code>, Ersetzen <code>Luzern $1</code> macht aus „Migros Luzern“ „Luzern Migros“.
|
||||
Gespeichert wird nur der Text; die bisherige Datei wird vorher unter backup/… gesichert.
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
341
Schaad.Accounting.UI/Components/Pages/TextCleanup.razor.cs
Normal file
341
Schaad.Accounting.UI/Components/Pages/TextCleanup.razor.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
174
Schaad.Accounting.UI/Components/Pages/TextCleanup.razor.css
Normal file
174
Schaad.Accounting.UI/Components/Pages/TextCleanup.razor.css
Normal file
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue