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

+270
View File
@@ -0,0 +1,270 @@
using System.Globalization;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace Khaemhat.Core.Treasury;
/// <summary>
/// Reads ISO 20022 bank to customer statements (<c>camt.053.001.xx</c>, any version): the elements are found by their
/// local names, so the version of the namespace does not matter.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item>account: <c>Stmt/Acct/Id/IBAN</c> and <c>Stmt/Acct/Ccy</c> (or the currency of the first amount);</item>
/// <item>balances: <c>OPBD</c> (or <c>PRCD</c>) as opening, <c>CLBD</c> as closing, negative when <c>CdtDbtInd</c> is <c>DBIT</c>;</item>
/// <item>period: <c>FrToDt</c>, otherwise the first and last booking dates;</item>
/// <item>each <c>Ntry</c>: amount signed by <c>CdtDbtInd</c>, <c>BookgDt</c>, <c>ValDt</c>, <c>AcctSvcrRef</c> or the
/// end-to-end id as reference, <c>BkTxCd</c> as bank code (<c>Domn/Fmly/SubFmly</c> or the proprietary code), the
/// description from <c>AddtlNtryInf</c> or the unstructured remittance information, the counterparty from
/// <c>RltdPties</c> (the debtor of a credit, the creditor of a debit);</item>
/// <item>entries with status <c>PDNG</c> or <c>INFO</c> are not booked and are skipped.</item>
/// </list>
/// When a file has several <c>Stmt</c> of the same account their entries are read in order; balances come from the first
/// opening and the last closing.
/// </remarks>
public static class Camt053Reader
{
/// <summary>Whether the start of a file looks like a <c>camt.053</c> statement.</summary>
/// <param name="head">The first bytes of the file.</param>
/// <returns><see langword="true"/> when the head is XML naming <c>camt.053</c> or <c>BkToCstmrStmt</c>.</returns>
public static bool Recognizes(ReadOnlySpan<byte> head)
{
var text = Encoding.UTF8.GetString(head);
return text.TrimStart('', ' ', '\t', '\r', '\n').StartsWith('<')
&& (text.Contains("camt.053", StringComparison.Ordinal) || text.Contains("BkToCstmrStmt", StringComparison.Ordinal));
}
/// <summary>Reads a statement.</summary>
/// <param name="content">The file.</param>
/// <returns>The statement.</returns>
/// <exception cref="BankFileException">The file is not a readable <c>camt.053</c> statement.</exception>
public static StatementFile Read(Stream content)
{
ArgumentNullException.ThrowIfNull(content);
XDocument document;
try
{
var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, IgnoreComments = true };
using var reader = XmlReader.Create(content, settings);
document = XDocument.Load(reader);
}
catch (XmlException ex)
{
throw new BankFileException($"The statement is not well-formed XML (line {ex.LineNumber}).", ex);
}
var root = document.Root;
var statement = root is null ? null : Child(root, "BkToCstmrStmt");
var statements = statement is null ? [] : Children(statement, "Stmt").ToList();
if (statements.Count == 0)
{
throw new BankFileException("The file has no camt.053 statement (Document/BkToCstmrStmt/Stmt).");
}
string? iban = null;
string? currency = null;
decimal? opening = null;
decimal? previousClosing = null;
decimal? closing = null;
DateOnly? from = null;
DateOnly? to = null;
var movements = new List<StatementMovement>();
foreach (var stmt in statements)
{
var account = Child(stmt, "Acct");
var accountIban = Value(Path(account, "Id", "IBAN"))?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant();
if (iban is not null && accountIban is not null && !string.Equals(iban, accountIban, StringComparison.Ordinal))
{
throw new BankFileException($"The file has statements of two accounts ({iban}, {accountIban}).");
}
iban ??= accountIban;
currency ??= Value(Child(account, "Ccy"));
foreach (var balance in Children(stmt, "Bal"))
{
var code = Value(Path(balance, "Tp", "CdOrPrtry", "Cd")) ?? Value(Path(balance, "Tp", "CdOrPrtry", "Prtry"));
var amountElement = Child(balance, "Amt");
currency ??= amountElement?.Attribute("Ccy")?.Value;
var amount = Signed(amountElement, balance, "balance");
switch (code)
{
case "OPBD":
opening ??= amount;
break;
case "PRCD":
previousClosing ??= amount;
break;
case "CLBD":
closing = amount;
break;
default:
break;
}
}
var period = Child(stmt, "FrToDt");
if (period is not null)
{
var start = DateOf(Child(period, "FrDtTm"));
var end = DateOf(Child(period, "ToDtTm"));
from = Min(from, start);
to = Max(to, end);
}
var number = 0;
foreach (var entry in Children(stmt, "Ntry"))
{
number++;
var status = Value(Child(entry, "Sts")) ?? Value(Path(entry, "Sts", "Cd"));
if (status is "PDNG" or "INFO")
{
continue;
}
movements.Add(Entry(entry, number));
}
}
if (movements.Count > 0)
{
from ??= movements.Min(m => m.BookingDate);
to ??= movements.Max(m => m.BookingDate);
}
return new StatementFile(StatementFormat.Camt053, iban, currency, from, to, opening ?? previousClosing, closing, movements);
}
private static StatementMovement Entry(XElement entry, int number)
{
var where = string.Create(CultureInfo.InvariantCulture, $"entry {number}");
var amount = Signed(Child(entry, "Amt"), entry, where);
var booking = DateOf(Child(entry, "BookgDt")) ?? DateOf(Child(entry, "ValDt"))
?? throw new BankFileException($"The {where} has no booking date.");
var value = DateOf(Child(entry, "ValDt"));
var transactions = Path(entry, "NtryDtls")?.Elements().Where(e => e.Name.LocalName == "TxDtls").ToList() ?? [];
var reference = Value(Child(entry, "AcctSvcrRef"));
if (reference is null)
{
reference = transactions
.Select(t => Value(Path(t, "Refs", "EndToEndId")) ?? Value(Path(t, "Refs", "AcctSvcrRef")))
.FirstOrDefault(r => r is not null && r != "NOTPROVIDED");
}
var description = Value(Child(entry, "AddtlNtryInf"));
if (description is null)
{
var lines = transactions
.SelectMany(t => Children(Child(t, "RmtInf"), "Ustrd"))
.Select(Value)
.OfType<string>()
.ToList();
description = lines.Count > 0 ? string.Join(" ", lines) : null;
}
description ??= transactions.Select(t => Value(Child(t, "AddtlTxInf"))).FirstOrDefault(d => d is not null);
var codes = Child(entry, "BkTxCd");
string? bankCode = null;
var domain = Child(codes, "Domn");
if (domain is not null)
{
bankCode = string.Join(
"/",
new[] { Value(Child(domain, "Cd")), Value(Path(domain, "Fmly", "Cd")), Value(Path(domain, "Fmly", "SubFmlyCd")) }.OfType<string>());
}
if (string.IsNullOrEmpty(bankCode))
{
bankCode = Value(Path(codes, "Prtry", "Cd"));
}
// The other party: who paid a credit, who was paid by a debit.
var side = amount >= 0m ? "Dbtr" : "Cdtr";
string? counterparty = null;
string? counterpartyIban = null;
foreach (var transaction in transactions)
{
var parties = Child(transaction, "RltdPties");
var party = Child(parties, side);
counterparty ??= Value(Child(party, "Nm")) ?? Value(Path(party, "Pty", "Nm"));
counterpartyIban ??= Value(Path(parties, side + "Acct", "Id", "IBAN"))?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant();
}
return new StatementMovement(
booking,
value,
amount,
OneLine(description),
reference,
counterparty is null ? null : OneLine(counterparty),
counterpartyIban,
string.IsNullOrEmpty(bankCode) ? null : bankCode);
}
private static decimal Signed(XElement? amountElement, XElement owner, string where)
{
var text = Value(amountElement);
if (text is null || !decimal.TryParse(text, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var amount))
{
throw new BankFileException($"The {where} has no readable amount.");
}
return Value(Child(owner, "CdtDbtInd")) == "DBIT" ? -amount : amount;
}
private static DateOnly? DateOf(XElement? element)
{
if (element is null)
{
return null;
}
var text = Value(Child(element, "Dt")) ?? Value(Child(element, "DtTm")) ?? Value(element);
if (text is null)
{
return null;
}
if (DateOnly.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date))
{
return date;
}
// Date and time: keep the local date as written, whatever the offset.
return text.Length >= 10 && DateOnly.TryParseExact(text[..10], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day)
? day
: null;
}
private static DateOnly? Min(DateOnly? a, DateOnly? b) => a is null ? b : b is null ? a : a < b ? a : b;
private static DateOnly? Max(DateOnly? a, DateOnly? b) => a is null ? b : b is null ? a : a > b ? a : b;
private static XElement? Child(XElement? parent, string localName) =>
parent?.Elements().FirstOrDefault(e => e.Name.LocalName == localName);
private static IEnumerable<XElement> Children(XElement? parent, string localName) =>
parent?.Elements().Where(e => e.Name.LocalName == localName) ?? [];
private static XElement? Path(XElement? parent, params string[] localNames)
{
var current = parent;
foreach (var name in localNames)
{
current = Child(current, name);
}
return current;
}
private static string? Value(XElement? element)
{
var text = element?.Value.Trim();
return string.IsNullOrEmpty(text) ? null : text;
}
private static string OneLine(string? text) =>
text is null ? string.Empty : string.Join(" ", text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
}
@@ -0,0 +1,400 @@
using System.Globalization;
using System.Text;
namespace Khaemhat.Core.Treasury;
/// <summary>
/// Reads the CSV exports of home banking with a <see cref="CsvStatementLayout"/>, and guesses the layout from the header
/// row of the common Italian and English exports.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item>The file is UTF-8 (with or without BOM); when it is not valid UTF-8 it is read as Windows-1252.</item>
/// <item>Fields may be quoted, with doubled quotes inside; quoted fields may span lines.</item>
/// <item>Empty rows and the <see cref="CsvStatementLayout.HeaderRows"/> are skipped; so are rows without a date and
/// without an amount (titles, totals without figures). A row with a date and no amount, or an amount and no date, is an
/// error that names the row.</item>
/// <item>Numbers may carry a leading or trailing sign and the currency (<c>€</c>, <c>EUR</c>); the debit column is read as
/// money out whatever its sign.</item>
/// </list>
/// </remarks>
public static class CsvStatementReader
{
// The common date formats tried when the layout format does not fit (never month-first, which is ambiguous).
private static readonly string[] FallbackDateFormats = ["dd/MM/yyyy", "d/M/yyyy", "dd/MM/yy", "yyyy-MM-dd", "dd-MM-yyyy", "dd.MM.yyyy"];
// Windows-1252 differs from Latin-1 in 0x80-0x9F; the undefined positions stay as they are.
private static readonly char[] Windows1252High =
[
'€', '\u0081', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u008D', 'Ž', '\u008F',
'\u0090', '‘', '’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '\u009D', 'ž', 'Ÿ',
];
private static readonly string[] BookingDateNames = ["data contabile", "booking date", "data operazione", "data registrazione", "data", "date"];
private static readonly string[] ValueDateNames = ["data valuta", "valuta", "value date"];
private static readonly string[] DescriptionNames = ["descrizione operazione", "descrizione", "description", "causale", "dettagli", "details"];
private static readonly string[] AmountNames = ["importo", "amount"];
private static readonly string[] CreditNames = ["entrate", "avere", "accrediti", "accredito", "importo avere", "credit", "credits"];
private static readonly string[] DebitNames = ["uscite", "dare", "addebiti", "addebito", "importo dare", "debit", "debits"];
private static readonly string[] ReferenceNames = ["riferimento", "cro", "reference", "riferimento banca", "cro/trn"];
private static readonly string[] EnglishNames = ["booking date", "value date", "description", "details", "amount", "credit", "credits", "debit", "debits", "reference", "date"];
/// <summary>Reads a statement.</summary>
/// <param name="content">The file.</param>
/// <param name="layout">Its columns.</param>
/// <returns>The statement: no account, currency or balances, the period from the booking dates.</returns>
/// <exception cref="BankFileException">A row cannot be read; the message names it.</exception>
public static StatementFile Read(Stream content, CsvStatementLayout layout)
{
ArgumentNullException.ThrowIfNull(content);
ArgumentNullException.ThrowIfNull(layout);
if (layout.AmountColumn is null && layout.CreditColumn is null && layout.DebitColumn is null)
{
throw new BankFileException("The CSV layout has no amount column.");
}
var movements = new List<StatementMovement>();
var index = 0;
foreach (var (row, fields) in Records(Decode(content), layout.Separator))
{
if (index++ < layout.HeaderRows || fields.All(string.IsNullOrWhiteSpace))
{
continue;
}
var date = ParseDate(Field(fields, layout.DateColumn), layout.DateFormat);
var amount = Amount(fields, layout, row);
if (date is null)
{
if (amount is null)
{
continue;
}
throw new BankFileException(string.Create(CultureInfo.InvariantCulture, $"Row {row}: the date '{Field(fields, layout.DateColumn)}' is not in the format {layout.DateFormat}."));
}
if (amount is null)
{
throw new BankFileException(string.Create(CultureInfo.InvariantCulture, $"Row {row}: there is no amount."));
}
var valueDate = layout.ValueDateColumn is { } valueColumn ? ParseDate(Field(fields, valueColumn), layout.DateFormat) : null;
var reference = layout.ReferenceColumn is { } referenceColumn ? OneLine(Field(fields, referenceColumn)) : string.Empty;
movements.Add(new StatementMovement(
date.Value,
valueDate,
amount.Value,
OneLine(Field(fields, layout.DescriptionColumn)),
reference.Length == 0 ? null : reference));
}
return new StatementFile(
StatementFormat.Csv,
null,
null,
movements.Count == 0 ? null : movements.Min(m => m.BookingDate),
movements.Count == 0 ? null : movements.Max(m => m.BookingDate),
null,
null,
movements);
}
/// <summary>
/// Guesses the layout from the header row: the separator (<c>;</c>, tab or <c>,</c>) and the columns from their
/// Italian or English names, without case and accents. Italian headers mean decimal comma, English ones decimal point;
/// the date format is <c>dd/MM/yyyy</c> (the reader also tries the other common day-first formats).
/// </summary>
/// <param name="headerLine">The first row of the file.</param>
/// <returns>The layout with one header row, or <see langword="null"/> when a date, a description or an amount column is missing.</returns>
public static CsvStatementLayout? Detect(string headerLine)
{
if (string.IsNullOrWhiteSpace(headerLine))
{
return null;
}
var line = headerLine.TrimStart('').TrimEnd('\r', '\n');
var separator = GuessSeparator(line);
var names = Records(line, separator).FirstOrDefault().Fields?.Select(NormalizeName).ToList() ?? [];
var date = Find(names, BookingDateNames);
var description = Find(names, DescriptionNames);
var amount = Find(names, AmountNames);
var credit = Find(names, CreditNames);
var debit = Find(names, DebitNames);
if (date is null || description is null || (amount is null && credit is null && debit is null))
{
return null;
}
var valueDate = Find(names, ValueDateNames, except: date);
var reference = Find(names, ReferenceNames);
var english = EnglishNames.Contains(names[date.Value], StringComparer.Ordinal);
return new CsvStatementLayout(
separator,
HeaderRows: 1,
date.Value,
valueDate,
description.Value,
amount,
amount is null ? credit : null,
amount is null ? debit : null,
reference,
"dd/MM/yyyy",
DecimalComma: !english);
}
/// <summary>Reads a number as the bank writes it.</summary>
/// <param name="text">The text, such as <c>-1.234,56</c>, <c>1.234,56-</c>, <c>+12,00 €</c>.</param>
/// <param name="decimalComma">Whether the decimal separator is the comma.</param>
/// <returns>The number, or <see langword="null"/> for an empty field.</returns>
/// <exception cref="FormatException">The text is not a number.</exception>
public static decimal? ParseAmount(string? text, bool decimalComma)
{
var value = (text ?? string.Empty)
.Replace("EUR", string.Empty, StringComparison.OrdinalIgnoreCase)
.Replace("€", string.Empty, StringComparison.Ordinal)
.Replace(" ", string.Empty, StringComparison.Ordinal)
.Replace(" ", string.Empty, StringComparison.Ordinal)
.Replace("'", string.Empty, StringComparison.Ordinal);
if (value.Length == 0)
{
return null;
}
var negative = false;
if (value.StartsWith('(') && value.EndsWith(')'))
{
negative = true;
value = value[1..^1];
}
if (value.Length > 0 && value[0] is '-' or '+')
{
negative ^= value[0] == '-';
value = value[1..];
}
else if (value.Length > 0 && value[^1] is '-' or '+')
{
negative ^= value[^1] == '-';
value = value[..^1];
}
value = decimalComma
? value.Replace(".", string.Empty, StringComparison.Ordinal).Replace(',', '.')
: value.Replace(",", string.Empty, StringComparison.Ordinal);
if (value.Length == 0 || !value.All(c => char.IsAsciiDigit(c) || c == '.')
|| !decimal.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var number))
{
throw new FormatException($"'{text}' is not an amount.");
}
return negative ? -number : number;
}
private static decimal? Amount(string[] fields, CsvStatementLayout layout, int row)
{
try
{
if (layout.AmountColumn is { } amountColumn)
{
return ParseAmount(Field(fields, amountColumn), layout.DecimalComma);
}
var credit = layout.CreditColumn is { } creditColumn ? ParseAmount(Field(fields, creditColumn), layout.DecimalComma) : null;
var debit = layout.DebitColumn is { } debitColumn ? ParseAmount(Field(fields, debitColumn), layout.DecimalComma) : null;
return credit is null && debit is null ? null : Math.Abs(credit ?? 0m) - Math.Abs(debit ?? 0m);
}
catch (FormatException ex)
{
throw new BankFileException(string.Create(CultureInfo.InvariantCulture, $"Row {row}: {ex.Message}"), ex);
}
}
private static DateOnly? ParseDate(string text, string format)
{
var value = text.Trim();
if (value.Length == 0)
{
return null;
}
string[] candidates = value.Contains(' ', StringComparison.Ordinal) ? [value, value[..value.IndexOf(' ', StringComparison.Ordinal)]] : [value];
foreach (var candidate in candidates)
{
if (DateOnly.TryParseExact(candidate, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)
|| DateOnly.TryParseExact(candidate, FallbackDateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
}
return null;
}
private static string Field(string[] fields, int column) => column >= 0 && column < fields.Length ? fields[column] : string.Empty;
private static string Decode(Stream content)
{
using var buffer = new MemoryStream();
content.CopyTo(buffer);
var bytes = buffer.ToArray();
var start = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF ? 3 : 0;
try
{
return new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(bytes, start, bytes.Length - start);
}
catch (DecoderFallbackException)
{
var text = Encoding.Latin1.GetString(bytes).ToCharArray();
for (var i = 0; i < text.Length; i++)
{
if (text[i] is >= '\u0080' and <= '\u009F')
{
text[i] = Windows1252High[text[i] - 0x80];
}
}
return new string(text);
}
}
// The records of the text with the row number where each starts (from 1); quoted fields may contain separators,
// doubled quotes and line breaks.
private static IEnumerable<(int Row, string[] Fields)> Records(string text, char separator)
{
var fields = new List<string>();
var field = new StringBuilder();
var quoted = false;
var line = 1;
var start = 1;
for (var i = 0; i < text.Length; i++)
{
var c = text[i];
if (quoted)
{
if (c == '"')
{
if (i + 1 < text.Length && text[i + 1] == '"')
{
field.Append('"');
i++;
}
else
{
quoted = false;
}
}
else
{
if (c == '\n')
{
line++;
}
field.Append(c);
}
continue;
}
if (c == '"' && field.ToString().Trim().Length == 0)
{
field.Clear();
quoted = true;
}
else if (c == separator)
{
fields.Add(field.ToString());
field.Clear();
}
else if (c is '\r' or '\n')
{
if (c == '\r' && i + 1 < text.Length && text[i + 1] == '\n')
{
i++;
}
fields.Add(field.ToString());
field.Clear();
yield return (start, fields.ToArray());
fields.Clear();
line++;
start = line;
}
else
{
field.Append(c);
}
}
if (field.Length > 0 || fields.Count > 0)
{
fields.Add(field.ToString());
yield return (start, fields.ToArray());
}
}
private static char GuessSeparator(string line)
{
int semicolons = 0, tabs = 0, commas = 0;
var quoted = false;
foreach (var c in line)
{
if (c == '"')
{
quoted = !quoted;
}
else if (!quoted)
{
semicolons += c == ';' ? 1 : 0;
tabs += c == '\t' ? 1 : 0;
commas += c == ',' ? 1 : 0;
}
}
return tabs > 0 && tabs >= semicolons && tabs >= commas ? '\t' : semicolons > 0 && semicolons >= commas ? ';' : ',';
}
private static int? Find(List<string> names, string[] candidates, int? except = null)
{
foreach (var candidate in candidates)
{
var index = names.FindIndex(n => string.Equals(n, candidate, StringComparison.Ordinal));
if (index >= 0 && index != except)
{
return index;
}
}
return null;
}
// Lower case, no accents, no currency or parenthesised notes, single spaces: "Importo (EUR)" is "importo".
private static string NormalizeName(string name)
{
var builder = new StringBuilder(name.Length);
var depth = 0;
foreach (var c in name.Normalize(NormalizationForm.FormD))
{
if (c == '(')
{
depth++;
}
else if (c == ')')
{
depth = Math.Max(0, depth - 1);
}
else if (depth == 0 && CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
{
builder.Append(char.IsLetterOrDigit(c) || c == '/' ? char.ToLowerInvariant(c) : ' ');
}
}
var words = builder.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries).Where(w => w is not ("eur" or "euro")).ToArray();
return string.Join(" ", words);
}
private static string OneLine(string text) => string.Join(" ", text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
}
+515
View File
@@ -0,0 +1,515 @@
using System.Globalization;
using System.Text;
using System.Xml;
using Khaemhat.Core.Validation;
namespace Khaemhat.Core.Treasury;
/// <summary>
/// Writes SEPA remittances as ISO 20022 customer initiation messages, within the subset of the EPC rulebooks (2023):
/// credit transfers to suppliers as <c>pain.001.001.09</c> and direct debits as <c>pain.008.001.08</c>.
/// </summary>
/// <remarks>
/// <para>
/// Every text is reduced to the SEPA Latin character set (<c>a-z A-Z 0-9 / - ? : ( ) . , ' +</c> and space): accented
/// letters lose the accent, anything else becomes a space, and texts are cut to the maxima of the schema (names 70,
/// remittance information 140, identifiers 35). Amounts have two decimals and a dot, the currency is always euro.
/// </para>
/// <para>
/// When the company has a CBI CUC code it goes in <c>GrpHdr/InitgPty/Id/OrgId/Othr</c> with issuer <c>CBI</c>, as
/// Italian banks require. A bank without a known BIC is written as <c>FinInstnId/Othr/Id</c> <c>NOTPROVIDED</c>.
/// </para>
/// </remarks>
public static class SepaXmlWriter
{
/// <summary>The namespace of credit transfer initiations.</summary>
public const string CreditTransferNamespace = "urn:iso:std:iso:20022:tech:xsd:pain.001.001.09";
/// <summary>The namespace of direct debit initiations.</summary>
public const string DirectDebitNamespace = "urn:iso:std:iso:20022:tech:xsd:pain.008.001.08";
/// <summary>The media type of the files.</summary>
public const string ContentType = "application/xml";
private const int NameLength = 70;
private const int RemittanceLength = 140;
private const int IdLength = 35;
private const int AddressLineLength = 70;
private const int TownLength = 35;
private const int PostalCodeLength = 16;
private const decimal MaximumAmount = 999_999_999.99m;
private const string NotProvided = "NOTPROVIDED";
/// <summary>Writes a remittance of SEPA credit transfers (<c>pain.001.001.09</c>).</summary>
/// <param name="remittance">The remittance, of kind <see cref="RemittanceKind.SepaCreditTransfer"/>.</param>
/// <returns>The file <c>SCT_&lt;MsgId&gt;.xml</c>.</returns>
/// <exception cref="BankFileException">The remittance cannot be written as SEPA credit transfers.</exception>
public static BankFile CreditTransfer(BankFileRemittance remittance)
{
ArgumentNullException.ThrowIfNull(remittance);
if (remittance.Kind != RemittanceKind.SepaCreditTransfer)
{
throw new BankFileException($"A remittance of kind {remittance.Kind} is not a SEPA credit transfer.");
}
var header = Check(remittance);
var items = remittance.Items.Select((item, index) => CheckItem(item, index, debit: false)).ToList();
var bytes = Write(CreditTransferNamespace, "CstmrCdtTrfInitn", xml =>
{
GroupHeader(xml, header, items);
xml.WriteStartElement("PmtInf");
xml.WriteElementString("PmtInfId", PaymentInformationId(header.MessageId, 1));
xml.WriteElementString("PmtMtd", "TRF");
xml.WriteElementString("BtchBookg", "true");
xml.WriteElementString("NbOfTxs", Count(items.Count));
xml.WriteElementString("CtrlSum", Amount(items.Sum(i => i.Amount)));
xml.WriteStartElement("PmtTpInf");
xml.WriteStartElement("SvcLvl");
xml.WriteElementString("Cd", "SEPA");
xml.WriteEndElement();
xml.WriteEndElement();
xml.WriteStartElement("ReqdExctnDt");
xml.WriteElementString("Dt", Date(remittance.ExecutionDate));
xml.WriteEndElement();
Party(xml, "Dbtr", header.Name, header.Country, header.Company.Address, header.Company.PostalCode, header.Company.City);
Account(xml, "DbtrAcct", header.Iban);
Agent(xml, "DbtrAgt", header.Bic);
xml.WriteElementString("ChrgBr", "SLEV");
foreach (var item in items)
{
xml.WriteStartElement("CdtTrfTxInf");
xml.WriteStartElement("PmtId");
xml.WriteElementString("EndToEndId", item.EndToEndId);
xml.WriteEndElement();
xml.WriteStartElement("Amt");
InstructedAmount(xml, item.Amount);
xml.WriteEndElement();
if (item.Bic is not null)
{
Agent(xml, "CdtrAgt", item.Bic);
}
Party(xml, "Cdtr", item.Name, item.Country, item.Source.Address, item.Source.PostalCode, item.Source.City);
Account(xml, "CdtrAcct", item.Iban);
Remittance(xml, item.Reference);
xml.WriteEndElement();
}
xml.WriteEndElement();
});
return new BankFile($"SCT_{FileSafe(header.MessageId)}.xml", ContentType, bytes);
}
/// <summary>
/// Writes a remittance of SEPA direct debits (<c>pain.008.001.08</c>), with one payment information block for each
/// sequence and collection date.
/// </summary>
/// <param name="remittance">The remittance, of kind <see cref="RemittanceKind.SddCore"/> or <see cref="RemittanceKind.SddB2b"/>.</param>
/// <returns>The file <c>SDD_&lt;MsgId&gt;.xml</c>.</returns>
/// <exception cref="BankFileException">The remittance cannot be written as SEPA direct debits.</exception>
public static BankFile DirectDebit(BankFileRemittance remittance)
{
ArgumentNullException.ThrowIfNull(remittance);
if (remittance.Kind is not (RemittanceKind.SddCore or RemittanceKind.SddB2b))
{
throw new BankFileException($"A remittance of kind {remittance.Kind} is not a SEPA direct debit.");
}
var header = Check(remittance);
var creditorId = Text(remittance.Company.CreditorId, IdLength).Replace(" ", string.Empty, StringComparison.Ordinal);
if (creditorId.Length == 0)
{
throw new BankFileException("The company has no SEPA creditor identifier.");
}
var items = remittance.Items.Select((item, index) => CheckItem(item, index, debit: true)).ToList();
var groups = items
.GroupBy(i => (i.Source.DueDate, i.Source.Sequence))
.OrderBy(g => g.Key.DueDate)
.ThenBy(g => g.Key.Sequence)
.ToList();
var scheme = remittance.Kind == RemittanceKind.SddB2b ? "B2B" : "CORE";
var bytes = Write(DirectDebitNamespace, "CstmrDrctDbtInitn", xml =>
{
GroupHeader(xml, header, items);
var number = 0;
foreach (var group in groups)
{
var debits = group.ToList();
xml.WriteStartElement("PmtInf");
xml.WriteElementString("PmtInfId", PaymentInformationId(header.MessageId, ++number));
xml.WriteElementString("PmtMtd", "DD");
xml.WriteElementString("BtchBookg", "true");
xml.WriteElementString("NbOfTxs", Count(debits.Count));
xml.WriteElementString("CtrlSum", Amount(debits.Sum(i => i.Amount)));
xml.WriteStartElement("PmtTpInf");
xml.WriteStartElement("SvcLvl");
xml.WriteElementString("Cd", "SEPA");
xml.WriteEndElement();
xml.WriteStartElement("LclInstrm");
xml.WriteElementString("Cd", scheme);
xml.WriteEndElement();
xml.WriteElementString("SeqTp", SequenceCode(group.Key.Sequence));
xml.WriteEndElement();
xml.WriteElementString("ReqdColltnDt", Date(group.Key.DueDate));
Party(xml, "Cdtr", header.Name, header.Country, header.Company.Address, header.Company.PostalCode, header.Company.City);
Account(xml, "CdtrAcct", header.Iban);
Agent(xml, "CdtrAgt", header.Bic);
xml.WriteElementString("ChrgBr", "SLEV");
xml.WriteStartElement("CdtrSchmeId");
xml.WriteStartElement("Id");
xml.WriteStartElement("PrvtId");
xml.WriteStartElement("Othr");
xml.WriteElementString("Id", creditorId);
xml.WriteStartElement("SchmeNm");
xml.WriteElementString("Prtry", "SEPA");
xml.WriteEndElement();
xml.WriteEndElement();
xml.WriteEndElement();
xml.WriteEndElement();
xml.WriteEndElement();
foreach (var item in debits)
{
xml.WriteStartElement("DrctDbtTxInf");
xml.WriteStartElement("PmtId");
xml.WriteElementString("EndToEndId", item.EndToEndId);
xml.WriteEndElement();
InstructedAmount(xml, item.Amount);
xml.WriteStartElement("DrctDbtTx");
xml.WriteStartElement("MndtRltdInf");
xml.WriteElementString("MndtId", item.MandateId);
xml.WriteElementString("DtOfSgntr", Date(item.Source.MandateDate!.Value));
xml.WriteEndElement();
xml.WriteEndElement();
Agent(xml, "DbtrAgt", item.Bic);
Party(xml, "Dbtr", item.Name, item.Country, item.Source.Address, item.Source.PostalCode, item.Source.City);
Account(xml, "DbtrAcct", item.Iban);
Remittance(xml, item.Reference);
xml.WriteEndElement();
}
xml.WriteEndElement();
}
});
return new BankFile($"SDD_{FileSafe(header.MessageId)}.xml", ContentType, bytes);
}
/// <summary>
/// A text in the SEPA Latin character set: accents removed, other characters replaced by spaces, spaces collapsed,
/// cut to a length.
/// </summary>
/// <param name="value">The text.</param>
/// <param name="maxLength">The maximum length.</param>
/// <returns>The text, possibly empty.</returns>
public static string Text(string? value, int maxLength)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxLength);
if (string.IsNullOrWhiteSpace(value))
{
return string.Empty;
}
var builder = new StringBuilder(value.Length);
foreach (var c in value.Normalize(NormalizationForm.FormD))
{
if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.NonSpacingMark)
{
continue;
}
var allowed = char.IsAsciiLetterOrDigit(c) || c is '/' or '-' or '?' or ':' or '(' or ')' or '.' or ',' or '\'' or '+' or ' ';
var next = allowed ? c : ' ';
if (next == ' ' && (builder.Length == 0 || builder[^1] == ' '))
{
continue;
}
builder.Append(next);
}
var text = builder.ToString().Trim();
return text.Length <= maxLength ? text : text[..maxLength].TrimEnd();
}
private static Header Check(BankFileRemittance remittance)
{
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 items.");
}
var messageId = Text(remittance.MessageId, IdLength);
if (messageId.Length == 0)
{
throw new BankFileException("The remittance has no message identifier.");
}
var iban = IbanValidator.Normalize(company.Iban);
if (iban.Length == 0)
{
throw new BankFileException("The company account has no IBAN.");
}
if (!IbanValidator.IsValid(iban))
{
throw new BankFileException($"The IBAN of the company account {iban} is not valid.");
}
var name = Text(company.Name, NameLength);
if (name.Length == 0)
{
throw new BankFileException("The company has no name.");
}
return new Header(company, messageId, name, iban, Bic(company.Bic, "the company"), Country(company.CountryCode, iban), remittance.CreatedAt);
}
private static Item CheckItem(BankFileItem item, int index, bool debit)
{
var where = $"item {index + 1}";
if (item is null)
{
throw new BankFileException($"The {where} is missing.");
}
var amount = Math.Round(item.Amount, 2, MidpointRounding.AwayFromZero);
if (amount <= 0m)
{
throw new BankFileException($"The amount of {where} must be positive: {item.Amount.ToString(CultureInfo.InvariantCulture)}.");
}
if (amount > MaximumAmount)
{
throw new BankFileException($"The amount of {where} is over the SEPA maximum.");
}
var iban = IbanValidator.Normalize(item.Iban);
if (iban.Length == 0)
{
throw new BankFileException($"The counterparty of {where} has no IBAN.");
}
if (!IbanValidator.IsValid(iban))
{
throw new BankFileException($"The IBAN {iban} of {where} is not valid.");
}
var name = Text(item.CounterpartyName, NameLength);
if (name.Length == 0)
{
throw new BankFileException($"The counterparty of {where} has no name.");
}
var endToEnd = Text(item.EndToEndId, IdLength);
var mandate = string.Empty;
if (debit)
{
mandate = Text(item.MandateId, IdLength);
if (mandate.Length == 0)
{
throw new BankFileException($"The direct debit of {where} has no mandate reference.");
}
if (item.MandateDate is null)
{
throw new BankFileException($"The direct debit of {where} has no mandate signature date.");
}
}
return new Item(
item,
name,
iban,
Bic(item.Bic, where),
Country(item.CountryCode, iban),
amount,
endToEnd.Length == 0 ? NotProvided : endToEnd,
Text(item.Reference, RemittanceLength),
mandate);
}
private static string? Bic(string? value, string where)
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
var bic = string.Concat(value.Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant();
var valid = bic.Length is 8 or 11
&& bic.All(char.IsAsciiLetterOrDigit)
&& char.IsAsciiLetterUpper(bic[4]) && char.IsAsciiLetterUpper(bic[5]);
return valid ? bic : throw new BankFileException($"The BIC {bic} of {where} is not valid.");
}
private static string Country(string? value, string iban)
{
var country = (value ?? string.Empty).Trim().ToUpperInvariant();
return country.Length == 2 && country.All(char.IsAsciiLetterUpper) ? country : iban[..2];
}
private static byte[] Write(string ns, string root, Action<XmlWriter> body)
{
var settings = new XmlWriterSettings { Encoding = new UTF8Encoding(false), Indent = true };
using var buffer = new MemoryStream();
using (var xml = XmlWriter.Create(buffer, settings))
{
xml.WriteStartDocument();
xml.WriteStartElement("Document", ns);
xml.WriteStartElement(root);
body(xml);
xml.WriteEndElement();
xml.WriteEndElement();
xml.WriteEndDocument();
}
return buffer.ToArray();
}
private static void GroupHeader(XmlWriter xml, Header header, List<Item> items)
{
xml.WriteStartElement("GrpHdr");
xml.WriteElementString("MsgId", header.MessageId);
xml.WriteElementString("CreDtTm", header.CreatedAt.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture));
xml.WriteElementString("NbOfTxs", Count(items.Count));
xml.WriteElementString("CtrlSum", Amount(items.Sum(i => i.Amount)));
xml.WriteStartElement("InitgPty");
xml.WriteElementString("Nm", header.Name);
var cuc = Text(header.Company.CucCode, IdLength).Replace(" ", string.Empty, StringComparison.Ordinal);
if (cuc.Length > 0)
{
xml.WriteStartElement("Id");
xml.WriteStartElement("OrgId");
xml.WriteStartElement("Othr");
xml.WriteElementString("Id", cuc);
xml.WriteElementString("Issr", "CBI");
xml.WriteEndElement();
xml.WriteEndElement();
xml.WriteEndElement();
}
xml.WriteEndElement();
xml.WriteEndElement();
}
private static void Party(XmlWriter xml, string element, string name, string country, string? address, string? postalCode, string? city)
{
xml.WriteStartElement(element);
xml.WriteElementString("Nm", name);
xml.WriteStartElement("PstlAdr");
var postal = Text(postalCode, PostalCodeLength);
var town = Text(city, TownLength);
if (postal.Length > 0 && town.Length > 0)
{
xml.WriteElementString("PstCd", postal);
}
if (town.Length > 0)
{
xml.WriteElementString("TwnNm", town);
}
xml.WriteElementString("Ctry", country);
var line = Text(address, AddressLineLength);
if (line.Length > 0)
{
xml.WriteElementString("AdrLine", line);
}
xml.WriteEndElement();
xml.WriteEndElement();
}
private static void Account(XmlWriter xml, string element, string iban)
{
xml.WriteStartElement(element);
xml.WriteStartElement("Id");
xml.WriteElementString("IBAN", iban);
xml.WriteEndElement();
xml.WriteEndElement();
}
private static void Agent(XmlWriter xml, string element, string? bic)
{
xml.WriteStartElement(element);
xml.WriteStartElement("FinInstnId");
if (bic is not null)
{
xml.WriteElementString("BICFI", bic);
}
else
{
xml.WriteStartElement("Othr");
xml.WriteElementString("Id", NotProvided);
xml.WriteEndElement();
}
xml.WriteEndElement();
xml.WriteEndElement();
}
private static void InstructedAmount(XmlWriter xml, decimal amount)
{
xml.WriteStartElement("InstdAmt");
xml.WriteAttributeString("Ccy", "EUR");
xml.WriteString(Amount(amount));
xml.WriteEndElement();
}
private static void Remittance(XmlWriter xml, string reference)
{
if (reference.Length > 0)
{
xml.WriteStartElement("RmtInf");
xml.WriteElementString("Ustrd", reference);
xml.WriteEndElement();
}
}
private static string SequenceCode(SddSequence sequence) => sequence switch
{
SddSequence.First => "FRST",
SddSequence.Final => "FNAL",
SddSequence.OneOff => "OOFF",
_ => "RCUR",
};
private static string PaymentInformationId(string messageId, int number)
{
var suffix = string.Create(CultureInfo.InvariantCulture, $"-{number}");
var room = IdLength - suffix.Length;
return (messageId.Length <= room ? messageId : messageId[..room]) + suffix;
}
private static string Count(int count) => count.ToString(CultureInfo.InvariantCulture);
private static string Amount(decimal amount) => amount.ToString("0.00", CultureInfo.InvariantCulture);
private static string Date(DateOnly date) => date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
private static string FileSafe(string value) =>
string.Concat(value.Select(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '.' ? c : '_'));
private sealed record Header(
BankFileCompany Company,
string MessageId,
string Name,
string Iban,
string? Bic,
string Country,
DateTime CreatedAt);
private sealed record Item(
BankFileItem Source,
string Name,
string Iban,
string? Bic,
string Country,
decimal Amount,
string EndToEndId,
string Reference,
string MandateId);
}
@@ -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);
}
}