AccountingNext/Schaad.Accounting.Services/FileService.cs
Claudio Schaad f9084dc074 PR P: full async I/O top to bottom (item 19)
Every repository, service, Blazor page/dialog, and test now uses
async/await. Single atomic diff; the codebase does not compile in
intermediate states.

- BaseRepository: LoadListAsync/LoadAsync/SaveAsync return Task<T>;
  per-file locks use SemaphoreSlim so waiters can await; Save
  serialises to a MemoryStream sync (XmlSerializer has no async
  form), then File.WriteAllBytesAsync + sync File.Move.
- RepositoryCache.GetOrLoadAsync takes a Func<Task<List<T>>>.
- All 7 repository interfaces + implementations async.
- All service interfaces + implementations async (except vendor
  IFxService and stateless IFxConverter / SettingsService).
- Every Blazor OnInitializedAsync switches to await base.
- Test suite fully async, 42 tests pass.

AccountRepository.EnsureAccountsFile keeps two .GetAwaiter().GetResult()
bridges because it runs from the constructor.

Null-render guard follow-up (folded in):
Blazor now renders the component once with fields at their initial
values while OnInitializedAsync awaits — so fields declared `= null!`
are actually null on that first render and things like
`accounts.GroupBy(...)` throw ArgumentNullException. Fixed across
Transactions, BalanceReport, BalanceSheetReport, ProfitLossReport,
DetailReport, Assets, Spendings, SpendingsOverTime, TransactionDialog,
TransactionSplitDialog, and BookingRuleDialog:
- Collection fields initialise to [] so first-render loops are empty.
- Single-object data fields become nullable; the razor wraps
  consumption in `@if (field is null) { <p>Lädt…</p> return; }`.
- <PlotlyChart> guarded behind a null check on config/layout/data so
  Plotly.Blazor's @bind doesn't see nulls.
- Header/footer strings initialise to "" instead of null!.

Architectural hygiene on a single-user local Blazor Server app: the
observed win is one File.ReadAllBytesAsync and one
File.WriteAllBytesAsync per Load/Save, and after PR D each file is
loaded at most once per SignalR circuit.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-03 18:30:44 +02:00

162 lines
7.7 KiB
C#

using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Schaad.Accounting.Datasets;
using Schaad.Accounting.Interfaces;
using Schaad.Finance.Api;
using Schaad.Finance.Api.Datasets;
namespace Schaad.Accounting.Services
{
public class FileService : IFileService
{
private readonly IAccountRepository accountRepository;
private readonly ITransactionRepository transactionsRepository;
private readonly IBankTransactionRepository bankTransactionRepository;
private readonly ISettingsService settingsService;
private readonly IAccountStatementService accountStatementService;
private readonly ICreditCardStatementService creditCardStatementService;
private readonly ILogger<FileService> logger;
public FileService(
ISettingsService settingsService,
IAccountRepository accountRepository,
ITransactionRepository transactionsRepository,
IBankTransactionRepository bankTransactionRepository,
IAccountStatementService accountStatementService,
ICreditCardStatementService creditCardStatementService,
ILogger<FileService> logger)
{
this.settingsService = settingsService;
this.accountRepository = accountRepository;
this.transactionsRepository = transactionsRepository;
this.bankTransactionRepository = bankTransactionRepository;
this.accountStatementService = accountStatementService;
this.creditCardStatementService = creditCardStatementService;
this.logger = logger;
}
public string Backup()
{
var outpath = settingsService.GetBackupFilePath();
var sourcepath = settingsService.GetYearMandatorPath();
ZipFile.CreateFromDirectory(sourcepath, outpath);
return $"Backup '{outpath}' erfolgreich erstellt";
}
// Upload account statement file (mt940, camt053)
public async Task<IReadOnlyList<MessageDataset>> ImportAccountStatementFileAsync(string filePath)
{
logger.LogInformation("Importing account statement file {FilePath}", filePath);
var messages = new List<MessageDataset>();
var accountStatementResults = accountStatementService.ReadFile(filePath, Encoding.UTF8);
var accountList = (await accountRepository.GetAccountListAsync()).Select(a => a.BankAccountNumber).ToList();
foreach (var accountStatementResult in accountStatementResults)
{
var account = accountStatementResult.AccountStatement;
if (accountStatementResult.IsSuccess == false)
{
logger.LogError("Statement parse failed for account {AccountNumber}: {Error}", account.AccountNumber, accountStatementResult.Error);
messages.Add(new MessageDataset($"Account {account.AccountNumber} NICHT importiert: {accountStatementResult.Error}", MessageStatus.Error));
}
if (accountStatementResult.AccountStatement.Transactions.Any() == false)
{
continue;
}
var message = new MessageDataset($"Konto {account.AccountNumber}");
messages.Add(message);
// only accounts that are in select mandator
if (accountList.Contains(account.AccountNumber))
{
var transactionsThisYear = account.Transactions
.Where(t => t.BookingDate.Year == settingsService.GetYear())
.Select(
t => new BankTransactionDataset
{
Id = t.Id,
Value = (decimal)t.Value,
ValueDate = t.ValueDate,
BookingDate = t.BookingDate,
Text = t.Text,
Debtor = t.Debtor,
Creditor = t.Creditor
})
.ToList();
var count = await bankTransactionRepository.SaveBankTransactionListAsync(account.AccountNumber, transactionsThisYear);
await accountRepository.SaveBankAccountBalanceAsync(account.AccountNumber, (decimal)account.EndBalance.Value);
logger.LogInformation("Imported {Imported} of {Total} transactions for account {AccountNumber}",
count, account.Transactions.Count, account.AccountNumber);
var status = count == account.Transactions.Count ? MessageStatus.Success : MessageStatus.Info;
message.Add($"{count} von {account.Transactions.Count} Transaktion(en) importiert.", status);
// not imported transactions
var notImportedTransactions = account.Transactions.Where(t => transactionsThisYear.Select(tt => tt.Id).Contains(t.Id) == false);
foreach (var trx in notImportedTransactions)
{
message.Add($"Transaktion wegen BookingDatum {trx.BookingDate} nicht importiert: {trx.Text}", MessageStatus.Warning);
}
}
else
{
logger.LogWarning("Skipping account {AccountNumber}: not part of the currently selected mandator ({Skipped} transactions ignored)",
account.AccountNumber, account.Transactions.Count);
message.Add($"Falscher Mandant: {account.Transactions.Count} Transaktion(en) nicht importiert.", MessageStatus.Warning);
}
}
return messages;
}
public IReadOnlyList<CreditCardTransaction> ImportCreditCardStatementFile(CreditCardProvider creditCardProvider, string filePath)
{
var creditCardTransactions = creditCardStatementService.ReadFile(creditCardProvider, filePath, Encoding.UTF8);
return creditCardTransactions;
}
public async Task<byte[]> GetTransactionListCsvAsync(string accountId)
{
var sb = new StringBuilder();
var account = await accountRepository.GetAccountAsync(accountId);
var transactions = (await transactionsRepository.GetTransactionListAsync())
.Where(t => t.OriginAccountId == accountId || t.TargetAccountId == accountId)
.OrderBy(t => t.BookingDate)
.ThenBy(t => t.ValueDate)
.ThenBy(t => t.Value)
.ToList();
var balance = account.StartBalance;
sb.AppendLine($"Buchungsdatum;Valuta;Buchungstext;Belastung;Gutschrift;Saldo {account.Currency}");
sb.AppendLine($";;Startsaldo;;;{balance}");
foreach (var trx in transactions)
{
var credit = "";
var debit = "";
var signedValue = trx.Value;
if (trx.OriginAccountId == accountId)
{
debit = trx.Value.ToFormattedString();
signedValue = -trx.Value;
}
else
{
credit = trx.Value.ToFormattedString();
}
balance += signedValue;
sb.AppendLine($"{trx.BookingDate:dd.MM.yyyy};{trx.ValueDate:dd.MM.yyyy};{trx.Text};{debit};{credit};{balance.ToFormattedString()}");
}
var fileBytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(sb.ToString());
return fileBytes;
}
}
}