AccountingNext/Schaad.Accounting.Services/TextReplacement.cs
Claudio Schaad f4d9158552 Add "Texte bereinigen" page for cleaning booking texts
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>
2026-10-22 20:31:09 +02:00

65 lines
2.4 KiB
C#

#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(), " ");
}
}