feat: SEPA, RiBa and bank statement file formats for treasury (#70 #71)

Remittances need files the banks accept and statements need readers for
reconciliation, without external libraries:

- SepaXmlWriter writes pain.001.001.09 credit transfers and pain.008.001.08
  direct debits (one PmtInf per sequence and collection date), reducing texts
  to the SEPA Latin set and refusing what a bank would reject.
- Camt053Reader reads any camt.053.001.xx by local names; CsvStatementReader
  reads home banking exports (UTF-8 or Windows-1252, Italian or English
  numbers) and guesses the layout from the header row.
- The Italian pack gains RibaCbiWriter (CBI Ricevute bancarie, 120-character
  records IB/14/20/30/40/50/51/70/EF) and CbiStatementReader (RH/61-64/EF).
- Tests validate the SEPA files against hand-written subsets of the ISO 20022
  schemas, to be replaced by the official XSDs when available.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-13 08:51:09 +01:00
1 parent b12dc79317
commit 5fbbe4d3a4
14 files changed
+3467

No files matched your search

@@ -0,0 +1,232 @@
using System.Globalization;
using System.Text;
using Khaemhat.Core.Treasury;
using Khaemhat.Core.Validation;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// Reads the CBI current account statement (rendicontazione movimenti di conto corrente, flow <c>RH</c>): records of
/// 120 characters, the <c>RH</c> header, the opening balance <c>61</c>, each movement <c>62</c> with its description
/// lines <c>63</c>, the closing balance <c>64</c> and the <c>EF</c> footer.
/// </summary>
/// <remarks>
/// Positions are 1-based and inclusive, with position 1 a space and 2-3 the record type. Lines written without the
/// leading space (some banks trim it) are accepted, as are files without line breaks (records one after the other).
/// Amounts are 15 characters, either digits with two implied decimals or with the comma the bank writes; signs are
/// <c>C</c> (credit, money in) and <c>D</c> (debit, money out); dates are <c>DDMMYY</c>.
/// <list type="table">
/// <listheader><term>Record</term><description>Positions read</description></listheader>
/// <item><term>RH</term><description>4-8 sender ABI; 9-13 receiver SIA; 14-19 creation date; 20-39 support name.</description></item>
/// <item><term>61</term><description>4-10 progressive; 52 CIN; 53-57 ABI; 58-62 CAB; 63-74 account; 75-77 currency; 78-83
/// date of the opening balance; 84 sign; 85-99 opening balance; 100-101 country and 102-103 check digits of the
/// IBAN.</description></item>
/// <item><term>62</term><description>4-10 progressive; 11-13 movement number; 14-19 value date; 20-25 booking date; 26
/// sign; 27-41 amount; 42-43 CBI causale; 44-45 internal causale; 46-61 cheque number; 62-77 bank reference; 87-120
/// description.</description></item>
/// <item><term>63</term><description>4-10 progressive; 11-13 movement number; 14-120 more description, appended to the
/// movement before.</description></item>
/// <item><term>64</term><description>4-10 progressive; 11-13 currency; 14-19 date of the closing balance; 20 sign; 21-35
/// closing (book) balance.</description></item>
/// <item><term>EF</term><description>end of the flow; nothing is read.</description></item>
/// </list>
/// The IBAN is rebuilt from country, check digits, CIN, ABI, CAB and account when they make a valid IBAN. A flow with
/// statements of two accounts is refused.
/// </remarks>
public sealed class CbiStatementReader : IBankStatementReader
{
private const int RecordLength = 120;
/// <inheritdoc />
public StatementFormat Format => StatementFormat.Cbi;
/// <inheritdoc />
public bool Recognizes(ReadOnlySpan<byte> head)
{
var text = Encoding.Latin1.GetString(head).TrimStart('', '\r', '\n');
var end = text.IndexOfAny(['\r', '\n']);
var first = end < 0 ? text : text[..end];
if (end < 0 && first.Length > RecordLength)
{
first = first[..RecordLength];
}
return (first.StartsWith(" RH", StringComparison.Ordinal) && first.Length == RecordLength)
|| (first.StartsWith("RH", StringComparison.Ordinal) && first.Length is RecordLength or RecordLength - 1);
}
/// <inheritdoc />
public StatementFile Read(Stream content)
{
ArgumentNullException.ThrowIfNull(content);
using var buffer = new MemoryStream();
content.CopyTo(buffer);
var records = Records(Encoding.Latin1.GetString(buffer.ToArray()));
if (records.Count == 0 || records[0].Line[1..3] != "RH")
{
throw new BankFileException("The file is not a CBI statement: the first record is not RH.");
}
string? iban = null;
string? currency = null;
decimal? opening = null;
decimal? closing = null;
DateOnly? from = null;
DateOnly? to = null;
var movements = new List<Movement>();
foreach (var (row, line) in records)
{
switch (line[1..3])
{
case "61":
var accountIban = AccountIban(line);
if (iban is not null && accountIban is not null && iban != accountIban)
{
throw new BankFileException($"Row {row}: the flow has statements of two accounts ({iban}, {accountIban}).");
}
iban ??= accountIban;
currency ??= Field(line, 75, 3) is { Length: > 0 } code ? code : null;
opening ??= Signed(line, 84, 85, row);
from ??= Date(Field(line, 78, 6), row);
break;
case "62":
var booking = Date(Field(line, 20, 6), row) ?? throw new BankFileException($"Row {row}: the movement has no booking date.");
var reference = Field(line, 62, 16);
var causale = Field(line, 42, 2);
movements.Add(new Movement(
booking,
Date(Field(line, 14, 6), row),
Signed(line, 26, 27, row),
new StringBuilder(Field(line, 87, 34)),
reference.Length == 0 ? null : reference,
causale.Length == 0 ? null : causale));
break;
case "63":
if (movements.Count == 0)
{
throw new BankFileException($"Row {row}: a description record 63 comes before any movement.");
}
movements[^1].Description.Append(' ').Append(Field(line, 14, 107));
break;
case "64":
closing = Signed(line, 20, 21, row);
to = Date(Field(line, 14, 6), row) ?? to;
break;
default:
break;
}
}
if (movements.Count > 0)
{
from ??= movements.Min(m => m.Booking);
to ??= movements.Max(m => m.Booking);
}
return new StatementFile(
StatementFormat.Cbi,
iban,
currency,
from,
to,
opening,
closing,
[.. movements.Select(m => new StatementMovement(
m.Booking,
m.Value,
m.Amount,
string.Join(" ", m.Description.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries)),
m.Reference,
BankCode: m.Causale))]);
}
// Records padded to 120 characters with the leading space restored; files without line breaks are cut every 120.
private static List<(int Row, string Line)> Records(string text)
{
var lines = text.Contains('\n', StringComparison.Ordinal) || text.Contains('\r', StringComparison.Ordinal)
? text.Split(["\r\n", "\n", "\r"], StringSplitOptions.None)
: Enumerable.Range(0, (text.Length + RecordLength - 1) / RecordLength)
.Select(i => text.Substring(i * RecordLength, Math.Min(RecordLength, text.Length - (i * RecordLength))))
.ToArray();
var records = new List<(int, string)>();
for (var i = 0; i < lines.Length; i++)
{
var line = lines[i].TrimStart('');
if (line.Trim().Length == 0)
{
continue;
}
if (line[0] != ' ')
{
line = " " + line;
}
records.Add((i + 1, line.Length >= RecordLength ? line[..RecordLength] : line.PadRight(RecordLength)));
}
return records;
}
private static string Field(string line, int position, int length) => line.Substring(position - 1, length).Trim();
private static DateOnly? Date(string text, int row)
{
if (text.Length == 0 || text.All(c => c == '0'))
{
return null;
}
return DateOnly.TryParseExact(text, "ddMMyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)
? date
: throw new BankFileException($"Row {row}: '{text}' is not a date DDMMYY.");
}
private static decimal Signed(string line, int signPosition, int amountPosition, int row)
{
var sign = line[signPosition - 1];
if (sign is not ('C' or 'D'))
{
throw new BankFileException($"Row {row}: the sign at position {signPosition.ToString(CultureInfo.InvariantCulture)} is not C or D.");
}
var amount = Amount(Field(line, amountPosition, 15), row);
return sign == 'D' ? -amount : amount;
}
private static decimal Amount(string text, int row)
{
if (text.Contains(',', StringComparison.Ordinal))
{
var value = text.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.');
if (decimal.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var withComma))
{
return withComma;
}
}
else if (text.Length > 0 && text.All(char.IsAsciiDigit))
{
return decimal.Parse(text, NumberStyles.None, CultureInfo.InvariantCulture) / 100m;
}
throw new BankFileException($"Row {row}: '{text}' is not an amount.");
}
private static string? AccountIban(string line)
{
var bban = Field(line, 52, 1) + Field(line, 53, 5) + Field(line, 58, 5) + Field(line, 63, 12);
var iban = IbanValidator.Normalize(Field(line, 100, 2) + Field(line, 102, 2) + bban);
return IbanValidator.IsValid(iban) ? iban : null;
}
private sealed record Movement(
DateOnly Booking,
DateOnly? Value,
decimal Amount,
StringBuilder Description,
string? Reference,
string? Causale);
}
@@ -28,6 +28,8 @@ public sealed class ItalyFiscalPack : FiscalPackBase
AddFeature<ILedgerTemplate>(new ItalianLedgerTemplate());
AddFeature<IVatSettlementRules>(new VatSettlementRulesIt());
AddFeature<IPeriodicVatReturnWriter>(new LipeWriter());
AddFeature<IRemittanceFileWriter>(new RibaCbiWriter());
AddFeature<IBankStatementReader>(new CbiStatementReader());
// ABI and CAB are read from every Italian IBAN; bank names and BICs arrive with the ABI list (ADR 0026).
AddFeature<IBankDirectory>(new ItalianBankDirectory([]));
+253
View File
@@ -0,0 +1,253 @@
using System.Globalization;
using System.Text;
using Khaemhat.Core.Treasury;
using Khaemhat.Core.Validation;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// Writes a remittance of bank receipts (ricevute bancarie) in the CBI fixed-width layout "Ricevute bancarie": records
/// of 120 characters separated by CRLF, the <c>IB</c> header, for each receipt the records <c>14</c>, <c>20</c>,
/// <c>30</c>, <c>40</c>, <c>50</c>, <c>51</c>, <c>70</c>, and the <c>EF</c> footer. Texts are upper case ASCII (accents
/// dropped) padded with spaces, numbers are zero padded, dates are <c>DDMMYY</c> and amounts are in cents.
/// </summary>
/// <remarks>
/// Positions are 1-based and inclusive; position 1 of every record is a space and positions 2-3 the record type.
/// Fields not listed are spaces.
/// <list type="table">
/// <listheader><term>Record</term><description>Positions</description></listheader>
/// <item><term>IB</term><description>4-8 sender SIA code; 9-13 receiving bank ABI (from the company IBAN); 14-19 creation
/// date; 20-39 support name (the message id); 114 currency <c>E</c>.</description></item>
/// <item><term>14</term><description>4-10 progressive; 23-28 due date; 29-33 causale <c>30000</c>; 34-46 amount in cents;
/// 47 sign <c>-</c>; 48-52 ABI, 53-57 CAB, 58-69 account of the company; 70-74 ABI, 75-79 CAB of the debtor bank; 92-96
/// company SIA code; 97 code type <c>4</c>; 98-113 debtor code; 120 currency <c>E</c>.</description></item>
/// <item><term>20</term><description>4-10 progressive; 11-34 creditor name; 35-58 street; 59-82 postal code, town and
/// province; 83-106 VAT number or tax code.</description></item>
/// <item><term>30</term><description>4-10 progressive; 11-40 and 41-70 debtor name; 71-86 debtor tax code.</description></item>
/// <item><term>40</term><description>4-10 progressive; 11-40 debtor street; 41-45 postal code; 46-67 town; 69-70 province;
/// 71-120 debtor bank and branch.</description></item>
/// <item><term>50</term><description>4-10 progressive; 11-50 and 51-90 reference (the invoices paid); 101-116 creditor
/// tax code.</description></item>
/// <item><term>51</term><description>4-10 progressive; 11-20 receipt number; 21-40 creditor name.</description></item>
/// <item><term>70</term><description>4-10 progressive (closing record of the receipt).</description></item>
/// <item><term>EF</term><description>4-8 sender SIA; 9-13 receiving ABI; 14-19 creation date; 20-39 support name; 46-52
/// number of receipts; 53-67 total of the receipts in cents (the "negative" amounts, as the sign of record 14); 68-82
/// zeros (positive amounts); 83-89 number of records, header and footer included; 114 currency <c>E</c>.</description></item>
/// </list>
/// </remarks>
public sealed class RibaCbiWriter : IRemittanceFileWriter
{
/// <summary>The length of every record.</summary>
public const int RecordLength = 120;
/// <summary>The media type of the file.</summary>
public const string ContentType = "text/plain";
private const long MaximumItemCents = 9_999_999_999_999L;
private const long MaximumTotalCents = 999_999_999_999_999L;
/// <inheritdoc />
public bool Supports(RemittanceKind kind) => kind == RemittanceKind.Riba;
/// <inheritdoc />
public BankFile Write(BankFileRemittance remittance)
{
ArgumentNullException.ThrowIfNull(remittance);
if (remittance.Kind != RemittanceKind.Riba)
{
throw new BankFileException($"A remittance of kind {remittance.Kind} is not a remittance of bank receipts.");
}
var company = remittance.Company ?? throw new BankFileException("The remittance has no company.");
if (remittance.Items is null || remittance.Items.Count == 0)
{
throw new BankFileException("The remittance has no receipts.");
}
var sia = Text(company.SiaCode, 5).Trim();
if (sia.Length != 5)
{
throw new BankFileException("The company has no SIA code (five characters) for bank receipts.");
}
var companyIban = IbanValidator.Normalize(company.Iban);
if (!IbanValidator.IsValid(companyIban) || !companyIban.StartsWith("IT", StringComparison.Ordinal))
{
throw new BankFileException($"The company account '{companyIban}' is not a valid Italian IBAN.");
}
var (abi, cab, account) = BankCodes(companyIban);
var date = Date(DateOnly.FromDateTime(remittance.CreatedAt));
var support = Text(remittance.MessageId, 20);
var creditorName = Text(company.Name, 24);
var creditorTaxCode = Text(company.TaxCode, 16);
var records = new List<string>();
records.Add(Record("IB", (4, sia), (9, abi), (14, date), (20, support), (114, "E")));
long total = 0;
for (var i = 0; i < remittance.Items.Count; i++)
{
var item = remittance.Items[i];
var progressive = Number(i + 1, 7);
var where = string.Create(CultureInfo.InvariantCulture, $"receipt {i + 1}");
var cents = decimal.ToInt64(Math.Round(item.Amount * 100m, 0, MidpointRounding.AwayFromZero));
if (cents <= 0)
{
throw new BankFileException($"The amount of {where} must be positive.");
}
if (cents > MaximumItemCents)
{
throw new BankFileException($"The amount of {where} does not fit the 13 digits of the record.");
}
total += cents;
if (total > MaximumTotalCents)
{
throw new BankFileException("The total of the remittance does not fit the 15 digits of the footer.");
}
var debtorIban = IbanValidator.Normalize(item.Iban);
if (debtorIban.Length == 0)
{
throw new BankFileException($"The debtor of {where} has no IBAN (ABI and CAB of the paying bank).");
}
if (!IbanValidator.IsValid(debtorIban) || !debtorIban.StartsWith("IT", StringComparison.Ordinal))
{
throw new BankFileException($"The IBAN of the debtor of {where} is not a valid Italian IBAN.");
}
var (debtorAbi, debtorCab, _) = BankCodes(debtorIban);
var debtorName = Text(item.CounterpartyName, 60);
if (debtorName.Trim().Length == 0)
{
throw new BankFileException($"The debtor of {where} has no name.");
}
var reference = Text(item.Reference, 80);
var place = string.Join(" ", new[] { Text(company.PostalCode, 5).Trim(), Text(company.City, 24).Trim(), Text(company.Province, 2).Trim() }.Where(s => s.Length > 0));
records.Add(Record(
"14",
(4, progressive),
(23, Date(item.DueDate)),
(29, "30000"),
(34, Number(cents, 13)),
(47, "-"),
(48, abi),
(53, cab),
(58, account),
(70, debtorAbi),
(75, debtorCab),
(92, sia),
(97, "4"),
(98, Text(item.CounterpartyCode, 16)),
(120, "E")));
records.Add(Record(
"20",
(4, progressive),
(11, creditorName),
(35, Text(company.Address, 24)),
(59, Text(place, 24)),
(83, creditorTaxCode)));
records.Add(Record(
"30",
(4, progressive),
(11, Cut(debtorName, 0, 30)),
(41, Cut(debtorName, 30, 30)),
(71, Text(item.CounterpartyTaxCode, 16))));
records.Add(Record(
"40",
(4, progressive),
(11, Text(item.Address, 30)),
(41, Text(item.PostalCode, 5)),
(46, Text(item.City, 22)),
(69, Text(item.Province, 2)),
(71, Text(item.BankName, 50))));
records.Add(Record(
"50",
(4, progressive),
(11, Cut(reference, 0, 40)),
(51, Cut(reference, 40, 40)),
(101, creditorTaxCode)));
records.Add(Record(
"51",
(4, progressive),
(11, Number(item.Number, 10)),
(21, Text(company.Name, 20))));
records.Add(Record("70", (4, progressive)));
}
var count = remittance.Items.Count;
records.Add(Record(
"EF",
(4, sia),
(9, abi),
(14, date),
(20, support),
(46, Number(count, 7)),
(53, Number(total, 15)),
(68, Number(0, 15)),
(83, Number(records.Count + 1, 7)),
(114, "E")));
var text = string.Join("\r\n", records) + "\r\n";
var name = string.Concat(Text(remittance.MessageId, 35).Trim().Select(c => char.IsAsciiLetterOrDigit(c) || c == '-' ? c : '_'));
return new BankFile($"RIBA_{name}.txt", ContentType, Encoding.ASCII.GetBytes(text));
}
/// <summary>
/// A text as the CBI records want it: upper case ASCII, accents dropped, other characters replaced by spaces, padded
/// with spaces or cut to a length.
/// </summary>
/// <param name="value">The text.</param>
/// <param name="length">The length of the field.</param>
/// <returns>The field, exactly <paramref name="length"/> characters.</returns>
public static string Text(string? value, int length)
{
var builder = new StringBuilder();
foreach (var c in (value ?? string.Empty).Normalize(NormalizationForm.FormD).ToUpperInvariant())
{
if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.NonSpacingMark)
{
continue;
}
var next = c is >= ' ' and <= '~' ? c : ' ';
if (next == ' ' && (builder.Length == 0 || builder[^1] == ' '))
{
continue;
}
builder.Append(next);
}
var text = builder.ToString().TrimEnd();
return text.Length >= length ? text[..length] : text.PadRight(length);
}
private static (string Abi, string Cab, string Account) BankCodes(string iban) => (iban[5..10], iban[10..15], iban[15..27]);
private static string Cut(string text, int start, int length) => text.Substring(start, length);
private static string Number(long value, int length) => value.ToString(CultureInfo.InvariantCulture).PadLeft(length, '0');
private static string Date(DateOnly date) => date.ToString("ddMMyy", CultureInfo.InvariantCulture);
private static string Record(string type, params (int Position, string Value)[] fields)
{
var record = new char[RecordLength];
Array.Fill(record, ' ');
record[1] = type[0];
record[2] = type[1];
foreach (var (position, value) in fields)
{
value.CopyTo(0, record, position - 1, Math.Min(value.Length, RecordLength - position + 1));
}
return new string(record);
}
}