AccountingNext/Schaad.Accounting.Db/Repositories/RawDataRepository.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

262 lines
11 KiB
C#

#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Schaad.Accounting.Interfaces;
using Schaad.Accounting.Models;
namespace Schaad.Accounting.Repositories
{
/// <summary>
/// Plain-text access to the data files of the selected year and mandator for the JSON editor.
/// Saving goes through <see cref="BaseRepository.SaveAsync{T}"/> (atomic write, cache
/// invalidation), but only after the text has been checked, because a broken file would break
/// every page that reads it.
/// </summary>
public class RawDataRepository : BaseRepository, IRawDataRepository
{
private const string ACCOUNTS = "Accounts.json";
private const string TRANSACTIONS = "Transactions.json";
private const int MaxErrors = 20;
// Like the normal options, but property names that don't exist (typos) are errors instead
// of being silently dropped on save.
private static readonly JsonSerializerOptions StrictOptions = new(JsonStorage.Options)
{
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow
};
public RawDataRepository(ISettingsService settingsService, RepositoryCache cache, ILogger<RawDataRepository> logger)
: base(settingsService, cache, logger)
{
}
public IReadOnlyList<string> FileNames { get; } =
[
TRANSACTIONS,
ACCOUNTS,
"BankTransactions.json",
"BookingRules.json",
"BookingTexts.json",
"SplitPredefinitions.json",
"SubClasses.json"
];
public async Task<RawDataFile> LoadAsync(string fileName)
{
var path = PathOf(fileName);
var bytes = File.Exists(path) ? await File.ReadAllBytesAsync(path) : Array.Empty<byte>();
return new RawDataFile(fileName, path, Encoding.UTF8.GetString(bytes), Hash(bytes));
}
public Task<RawDataSaveResult> SaveAsync(string fileName, string text, string loadedHash) => fileName switch
{
TRANSACTIONS => SaveAsync<Transaction>(fileName, text, loadedHash),
ACCOUNTS => SaveAsync<Account>(fileName, text, loadedHash),
"BankTransactions.json" => SaveAsync<BankTransaction>(fileName, text, loadedHash),
"BookingRules.json" => SaveAsync<BookingRule>(fileName, text, loadedHash),
"BookingTexts.json" => SaveAsync<BookingText>(fileName, text, loadedHash),
"SplitPredefinitions.json" => SaveAsync<SplitPredefinition>(fileName, text, loadedHash),
"SubClasses.json" => SaveAsync<SubClass>(fileName, text, loadedHash),
_ => throw new ArgumentException($"Unknown data file '{fileName}'", nameof(fileName))
};
private async Task<RawDataSaveResult> SaveAsync<T>(string fileName, string text, string loadedHash)
{
List<T>? items;
try
{
items = JsonSerializer.Deserialize<List<T>>(text, StrictOptions);
}
catch (JsonException ex)
{
return Failed(Describe(ex));
}
if (items is null)
{
return Failed("Die Datei muss eine Liste enthalten: [ ... ]");
}
var errors = CheckIds(items);
if (items is List<Transaction> transactions)
{
errors.AddRange(await CheckAccountReferencesAsync(transactions));
}
if (items is List<Account> accounts)
{
errors.AddRange(await CheckAccountsStillUsedAsync(accounts));
}
if (errors.Count > 0)
{
return Failed(errors.ToArray());
}
var current = await LoadAsync(fileName);
if (current.Hash != loadedHash)
{
return Failed("Die Datei wurde seit dem Laden geändert (z.B. durch eine Buchung). Bitte neu laden; deine Änderungen gehen dabei verloren, also vorher kopieren.");
}
var backupPath = await BackupAsync(current);
await SaveAsync(items, fileName);
logger.LogInformation("Saved {FilePath} from the JSON editor; previous version in {BackupPath}", current.Path, backupPath);
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>();
var idProperty = typeof(T).GetProperty("Id");
if (idProperty is null)
{
return errors;
}
var ids = items.Select(item => idProperty.GetValue(item) as string).ToList();
for (var i = 0; i < ids.Count; i++)
{
if (string.IsNullOrWhiteSpace(ids[i]))
{
errors.Add($"Eintrag {i + 1}: \"Id\" fehlt.");
}
}
foreach (var duplicate in ids.Where(id => !string.IsNullOrWhiteSpace(id)).GroupBy(id => id).Where(g => g.Count() > 1))
{
errors.Add($"Id \"{duplicate.Key}\" kommt {duplicate.Count()}-mal vor.");
}
return Limit(errors);
}
private async Task<List<string>> CheckAccountReferencesAsync(List<Transaction> transactions)
{
var accountIds = (await LoadListAsync<Account>(ACCOUNTS)).Select(a => a.Id).ToHashSet();
var errors = new List<string>();
for (var i = 0; i < transactions.Count; i++)
{
var t = transactions[i];
foreach (var (id, role) in new[] { (t.OriginAccountId, "OriginAccountId"), (t.TargetAccountId, "TargetAccountId") })
{
if (accountIds.Contains(id) == false)
{
errors.Add($"Buchung {i + 1} ({t.ValueDate:dd.MM.yyyy} \"{t.Text}\"): {role} \"{id}\" ist kein Konto in {ACCOUNTS}.");
}
}
}
return Limit(errors);
}
private async Task<List<string>> CheckAccountsStillUsedAsync(List<Account> accounts)
{
var accountIds = accounts.Select(a => a.Id).ToHashSet();
var transactions = await LoadListAsync<Transaction>(TRANSACTIONS);
return Limit(transactions
.SelectMany(t => new[] { t.OriginAccountId, t.TargetAccountId })
.Where(id => accountIds.Contains(id) == false)
.GroupBy(id => id)
.Select(g => $"Konto-Id \"{g.Key}\" fehlt, wird aber von {g.Count()} Buchungen in {TRANSACTIONS} verwendet.")
.ToList());
}
private async Task<string> BackupAsync(RawDataFile current)
{
var settings = settingsService.GetSettings();
var directory = Path.Combine(settings.DataPath, DataFolders.Backup, settingsService.GetMandator(),
settingsService.GetYear().ToString(), "json-" + DateTime.Now.ToString("yyyyMMddHHmmss"));
Directory.CreateDirectory(directory);
var backupPath = Path.Combine(directory, current.FileName);
await File.WriteAllTextAsync(backupPath, current.Text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
return backupPath;
}
private string PathOf(string fileName)
{
if (FileNames.Contains(fileName) == false)
{
throw new ArgumentException($"Unknown data file '{fileName}'", nameof(fileName));
}
return Path.Combine(settingsService.GetDbPath(), fileName);
}
private static string Hash(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes));
private static string Describe(JsonException ex)
{
// Message ends with " Path: ... | LineNumber: ... | BytePositionInLine: ...", which we
// show in our own words.
var message = ex.Message;
var cut = message.IndexOf(" Path:", StringComparison.Ordinal);
if (cut > 0)
{
message = message[..cut];
}
var position = ex.LineNumber is { } line ? $"Zeile {line + 1}, Spalte {(ex.BytePositionInLine ?? 0) + 1}" : "Unbekannte Stelle";
return $"{position} ({ex.Path}): {message}";
}
private static List<string> Limit(List<string> errors)
=> errors.Count <= MaxErrors
? errors
: errors.Take(MaxErrors).Append($"… und {errors.Count - MaxErrors} weitere.").ToList();
private static RawDataSaveResult Failed(params string[] errors) => new(errors, null, null);
}
}