## Summary
- Repositories read and write **JSON instead of XML**. The JSON is human readable: indented, umlauts written as-is, property names as in the C# models (`BankTransactionText`), null values left out, computed properties (`Class`, `SubClass`, `IsFxAccount`, `ReadOnly`) not stored. Shared settings live in `JsonStorage`.
- **New data folder layout**, defined in `DataFolders`:
```
{DataPath}/{mandator}/{year}/*.json data files (no Data subfolder)
{DataPath}/uploads/{mandator}/{year}/ imported bank statements (+ creditCard/)
{DataPath}/backup/{mandator}/{year}/ backup zips and the original XML files
```
`SettingsService` builds the new paths. `GetYearMandatorPath` / `GetLastYearMandatorPath` are removed because they now equal the data paths. The mandator dropdown lists mandators that have a folder for the selected year.
- New **`DataMigrator`** runs at startup, before the app serves requests, in two phases:
1. **Restructure:** moves the old `{year}/{mandator}/Data`, `{year}/{mandator}/uploads` and `{year}/backup/{mandator}` folders into the new layout, unchanged.
2. **Convert:** turns the seven known XML data files in each `{mandator}/{year}` folder into JSON, checks that the JSON reads back to the same data, then moves the XML to `backup/{mandator}/{year}/xml-{timestamp}/`. Bank-statement XMLs are moved but never converted.
- **Safety:** nothing is ever overwritten. If a file already exists at the target, the source is dropped only when both are identical; otherwise it is an error. Any error stops startup (conversion is skipped if a move failed), so the app never runs on a half-migrated folder. Old folders are removed only once empty; unexpected leftovers are logged and kept. Both phases can safely run again.
- `CLAUDE.md` updated for JSON storage and the new layout.
## Upgrade notes
- **Make a full copy of the data folder before the first start** of this version.
- **Don't run an older (XML) version** on a migrated data folder. It would find no data and start new XML files in the old layout.
- The backup zip now contains only the data files of the current mandator/year. Uploads live in their own folder.
- Empty folders from the old layout are not carried over; the app recreates them when needed.
## Test plan
- [x] `dotnet build`: no warnings
- [x] `dotnet test`: 77/77 pass, including 15 `DataMigratorTestShould` tests (old-layout data, uploads with subfolders and year backups moved; XML converted in old and new layout; readable JSON; values round-trip through the repositories; unknown XMLs not converted; rerun does nothing; stray files kept; crash recovery for moves and conversions; conflicting files; corrupt XML) and 4 `SettingsServiceTestShould` tests for the new paths and mandator list
- [x] Ran the app against a copy of the real data folder: 136 files moved, 82 XML files converted, no old year folders left, Accounts / Balance report / Transactions pages render
- [x] Checked every one of the 137 original files against a checksum manifest: uploads and other files byte-identical at their new location, every XML backup identical to the original, and JSON vs. XML compared field by field (11,807 records, 101,564 fields, 0 differences). 8 dates with a UTC offset in the XML are written as the same instant in local time, which is what the old app also had in memory after reading them.
- [ ] Start once on the real data folder and check the pages
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Reviewed-on: #2
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
162 lines
7.7 KiB
C#
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.GetDbPath();
|
|
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;
|
|
}
|
|
}
|
|
}
|