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:
1 parent
b12dc79317
commit
5fbbe4d3a4
14 files changed
+3467
No files matched your search
@@ -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));
|
||||
}
|
||||
@@ -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_<MsgId>.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_<MsgId>.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([]));
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -8,4 +8,9 @@
|
||||
<ProjectReference Include="../../src/Khaemhat.Core/Khaemhat.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Hand-written subsets of the ISO 20022 schemas the SEPA files are validated against (no download). -->
|
||||
<ItemGroup>
|
||||
<None Include="Treasury\Schemas\*.xsd" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,185 @@
|
||||
using System.Text;
|
||||
using Khaemhat.Core.Treasury;
|
||||
|
||||
namespace Khaemhat.Core.Tests.Treasury;
|
||||
|
||||
/// <summary>ISO 20022 <c>camt.053</c> statements (issue #71), read whatever the version of the namespace.</summary>
|
||||
[TestClass]
|
||||
public sealed class Camt053ReaderTests
|
||||
{
|
||||
private const string Sample = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.08">
|
||||
<BkToCstmrStmt>
|
||||
<GrpHdr><MsgId>STMT-1</MsgId><CreDtTm>2026-11-01T06:00:00</CreDtTm></GrpHdr>
|
||||
<Stmt>
|
||||
<Id>2026-10</Id>
|
||||
<CreDtTm>2026-11-01T06:00:00</CreDtTm>
|
||||
<FrToDt><FrDtTm>2026-10-01T00:00:00</FrDtTm><ToDtTm>2026-10-31T23:59:59</ToDtTm></FrToDt>
|
||||
<Acct><Id><IBAN>IT60X0542811101000000123456</IBAN></Id><Ccy>EUR</Ccy></Acct>
|
||||
<Bal>
|
||||
<Tp><CdOrPrtry><Cd>OPBD</Cd></CdOrPrtry></Tp>
|
||||
<Amt Ccy="EUR">1000.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Dt><Dt>2026-09-30</Dt></Dt>
|
||||
</Bal>
|
||||
<Bal>
|
||||
<Tp><CdOrPrtry><Cd>CLBD</Cd></CdOrPrtry></Tp>
|
||||
<Amt Ccy="EUR">1950.50</Amt><CdtDbtInd>CRDT</CdtDbtInd><Dt><Dt>2026-10-31</Dt></Dt>
|
||||
</Bal>
|
||||
<Ntry>
|
||||
<Amt Ccy="EUR">1220.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Sts><Cd>BOOK</Cd></Sts>
|
||||
<BookgDt><Dt>2026-10-05</Dt></BookgDt><ValDt><Dt>2026-10-06</Dt></ValDt>
|
||||
<AcctSvcrRef>CRO-0001</AcctSvcrRef>
|
||||
<BkTxCd><Domn><Cd>PMNT</Cd><Fmly><Cd>RCDT</Cd><SubFmlyCd>ESCT</SubFmlyCd></Fmly></Domn></BkTxCd>
|
||||
<NtryDtls><TxDtls>
|
||||
<Refs><EndToEndId>E2E-AAA</EndToEndId></Refs>
|
||||
<RltdPties>
|
||||
<Dbtr><Pty><Nm>Cliente Uno S.p.A.</Nm></Pty></Dbtr>
|
||||
<DbtrAcct><Id><IBAN>IT63A0200801600000101234567</IBAN></Id></DbtrAcct>
|
||||
</RltdPties>
|
||||
<RmtInf><Ustrd>Saldo FT 2026/388</Ustrd><Ustrd>e FT 2026/390</Ustrd></RmtInf>
|
||||
</TxDtls></NtryDtls>
|
||||
</Ntry>
|
||||
<Ntry>
|
||||
<Amt Ccy="EUR">30.50</Amt><CdtDbtInd>CRDT</CdtDbtInd><Sts><Cd>BOOK</Cd></Sts>
|
||||
<BookgDt><DtTm>2026-10-10T10:15:00+02:00</DtTm></BookgDt>
|
||||
<BkTxCd><Prtry><Cd>48</Cd></Prtry></BkTxCd>
|
||||
<NtryDtls><TxDtls><Refs><EndToEndId>E2E-BBB</EndToEndId></Refs></TxDtls></NtryDtls>
|
||||
<AddtlNtryInf>Bonifico da
|
||||
Cliente Due</AddtlNtryInf>
|
||||
</Ntry>
|
||||
<Ntry>
|
||||
<Amt Ccy="EUR">300.00</Amt><CdtDbtInd>DBIT</CdtDbtInd><Sts><Cd>BOOK</Cd></Sts>
|
||||
<BookgDt><Dt>2026-10-20</Dt></BookgDt><ValDt><Dt>2026-10-20</Dt></ValDt>
|
||||
<NtryDtls><TxDtls>
|
||||
<RltdPties>
|
||||
<Dbtr><Pty><Nm>Officine Balbo</Nm></Pty></Dbtr>
|
||||
<Cdtr><Pty><Nm>Fornitore Tre</Nm></Pty></Cdtr>
|
||||
<CdtrAcct><Id><IBAN>DE89 3704 0044 0532 0130 00</IBAN></Id></CdtrAcct>
|
||||
</RltdPties>
|
||||
<RmtInf><Ustrd>Pagamento fattura 77</Ustrd></RmtInf>
|
||||
</TxDtls></NtryDtls>
|
||||
</Ntry>
|
||||
<Ntry>
|
||||
<Amt Ccy="EUR">9.99</Amt><CdtDbtInd>DBIT</CdtDbtInd><Sts><Cd>PDNG</Cd></Sts>
|
||||
<BookgDt><Dt>2026-10-31</Dt></BookgDt>
|
||||
</Ntry>
|
||||
</Stmt>
|
||||
</BkToCstmrStmt>
|
||||
</Document>
|
||||
""";
|
||||
|
||||
// The 2009 version: plain status, parties without Pty, PRCD as opening, no period.
|
||||
private const string Version02 = """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.02">
|
||||
<BkToCstmrStmt>
|
||||
<GrpHdr><MsgId>OLD</MsgId><CreDtTm>2026-11-01T06:00:00</CreDtTm></GrpHdr>
|
||||
<Stmt>
|
||||
<Id>1</Id>
|
||||
<Acct><Id><IBAN>IT60X0542811101000000123456</IBAN></Id></Acct>
|
||||
<Bal><Tp><CdOrPrtry><Cd>PRCD</Cd></CdOrPrtry></Tp><Amt Ccy="EUR">50.00</Amt><CdtDbtInd>DBIT</CdtDbtInd><Dt><Dt>2026-10-31</Dt></Dt></Bal>
|
||||
<Bal><Tp><CdOrPrtry><Cd>CLBD</Cd></CdOrPrtry></Tp><Amt Ccy="EUR">150.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Dt><Dt>2026-11-03</Dt></Dt></Bal>
|
||||
<Ntry>
|
||||
<Amt Ccy="EUR">200.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Sts>BOOK</Sts>
|
||||
<BookgDt><Dt>2026-11-02</Dt></BookgDt>
|
||||
<NtryDtls><TxDtls><RltdPties><Dbtr><Nm>Cliente Vecchio</Nm></Dbtr></RltdPties></TxDtls></NtryDtls>
|
||||
<AddtlNtryInf>Accredito</AddtlNtryInf>
|
||||
</Ntry>
|
||||
<Ntry>
|
||||
<Amt Ccy="EUR">1.00</Amt><CdtDbtInd>CRDT</CdtDbtInd><Sts>BOOK</Sts>
|
||||
<BookgDt><Dt>2026-11-03</Dt></BookgDt>
|
||||
</Ntry>
|
||||
</Stmt>
|
||||
</BkToCstmrStmt>
|
||||
</Document>
|
||||
""";
|
||||
|
||||
[TestMethod]
|
||||
public void Read_TwoCreditsAndADebit_WithBalancesAndPeriod()
|
||||
{
|
||||
var statement = Read(Sample);
|
||||
|
||||
Assert.AreEqual(StatementFormat.Camt053, statement.Format);
|
||||
Assert.AreEqual("IT60X0542811101000000123456", statement.AccountIban);
|
||||
Assert.AreEqual("EUR", statement.Currency);
|
||||
Assert.AreEqual(1000m, statement.OpeningBalance);
|
||||
Assert.AreEqual(1950.50m, statement.ClosingBalance);
|
||||
Assert.AreEqual(new DateOnly(2026, 10, 1), statement.FromDate);
|
||||
Assert.AreEqual(new DateOnly(2026, 10, 31), statement.ToDate);
|
||||
Assert.HasCount(3, statement.Movements);
|
||||
Assert.AreEqual(statement.ClosingBalance, statement.OpeningBalance + statement.Movements.Sum(m => m.Amount));
|
||||
|
||||
var first = statement.Movements[0];
|
||||
Assert.AreEqual(new DateOnly(2026, 10, 5), first.BookingDate);
|
||||
Assert.AreEqual(new DateOnly(2026, 10, 6), first.ValueDate);
|
||||
Assert.AreEqual(1220m, first.Amount);
|
||||
Assert.AreEqual("CRO-0001", first.Reference);
|
||||
Assert.AreEqual("PMNT/RCDT/ESCT", first.BankCode);
|
||||
Assert.AreEqual("Saldo FT 2026/388 e FT 2026/390", first.Description);
|
||||
Assert.AreEqual("Cliente Uno S.p.A.", first.CounterpartyName);
|
||||
Assert.AreEqual("IT63A0200801600000101234567", first.CounterpartyIban);
|
||||
|
||||
var second = statement.Movements[1];
|
||||
Assert.AreEqual(new DateOnly(2026, 10, 10), second.BookingDate);
|
||||
Assert.IsNull(second.ValueDate);
|
||||
Assert.AreEqual("E2E-BBB", second.Reference);
|
||||
Assert.AreEqual("48", second.BankCode);
|
||||
Assert.AreEqual("Bonifico da Cliente Due", second.Description);
|
||||
|
||||
var debit = statement.Movements[2];
|
||||
Assert.AreEqual(-300m, debit.Amount);
|
||||
Assert.AreEqual("Fornitore Tre", debit.CounterpartyName);
|
||||
Assert.AreEqual("DE89370400440532013000", debit.CounterpartyIban);
|
||||
Assert.AreEqual("Pagamento fattura 77", debit.Description);
|
||||
Assert.IsNull(debit.Reference);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_Version02_UsesThePreviousClosingAndTheBookingDates()
|
||||
{
|
||||
var statement = Read(Version02);
|
||||
|
||||
Assert.AreEqual(-50m, statement.OpeningBalance);
|
||||
Assert.AreEqual(150m, statement.ClosingBalance);
|
||||
Assert.AreEqual("EUR", statement.Currency);
|
||||
Assert.AreEqual(new DateOnly(2026, 11, 2), statement.FromDate);
|
||||
Assert.AreEqual(new DateOnly(2026, 11, 3), statement.ToDate);
|
||||
Assert.HasCount(2, statement.Movements);
|
||||
Assert.AreEqual("Cliente Vecchio", statement.Movements[0].CounterpartyName);
|
||||
Assert.AreEqual("Accredito", statement.Movements[0].Description);
|
||||
Assert.AreEqual(string.Empty, statement.Movements[1].Description);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Recognizes_Camt053_ButNotOtherFiles()
|
||||
{
|
||||
Assert.IsTrue(Camt053Reader.Recognizes(Encoding.UTF8.GetBytes(Sample)));
|
||||
Assert.IsTrue(Camt053Reader.Recognizes(Encoding.UTF8.GetBytes(Version02)));
|
||||
Assert.IsFalse(Camt053Reader.Recognizes(Encoding.UTF8.GetBytes("Data;Descrizione;Importo\n")));
|
||||
Assert.IsFalse(Camt053Reader.Recognizes(Encoding.UTF8.GetBytes("<Document xmlns=\"urn:iso:std:iso:20022:tech:xsd:pain.001.001.09\"/>")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_RefusesBrokenOrForeignXml_AndDtds()
|
||||
{
|
||||
Assert.ThrowsExactly<BankFileException>(() => Read("<Document><BkToCstmrStmt>"));
|
||||
Assert.ThrowsExactly<BankFileException>(() => Read("<Document xmlns=\"urn:iso:std:iso:20022:tech:xsd:pain.001.001.09\"><CstmrCdtTrfInitn/></Document>"));
|
||||
Assert.ThrowsExactly<BankFileException>(() => Read("<?xml version=\"1.0\"?><!DOCTYPE d [<!ENTITY x \"y\">]><Document><BkToCstmrStmt><Stmt/></BkToCstmrStmt></Document>"));
|
||||
Assert.ThrowsExactly<BankFileException>(() => Read(Sample.Replace("<Amt Ccy=\"EUR\">30.50</Amt>", "<Amt Ccy=\"EUR\">abc</Amt>", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_TwoStatementsOfTwoAccounts_IsRefused()
|
||||
{
|
||||
var stmt = Sample[Sample.IndexOf("<Stmt>", StringComparison.Ordinal)..(Sample.IndexOf("</Stmt>", StringComparison.Ordinal) + 7)];
|
||||
var other = stmt.Replace("IT60X0542811101000000123456", "DE89370400440532013000", StringComparison.Ordinal);
|
||||
|
||||
Assert.ThrowsExactly<BankFileException>(() => Read(Sample.Replace("</Stmt>", "</Stmt>" + other, StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
private static StatementFile Read(string xml)
|
||||
{
|
||||
using var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
|
||||
return Camt053Reader.Read(stream);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
using System.Text;
|
||||
using Khaemhat.Core.Treasury;
|
||||
|
||||
namespace Khaemhat.Core.Tests.Treasury;
|
||||
|
||||
/// <summary>CSV exports of home banking (issue #71): layouts, Italian numbers, encodings and the guess of the layout.</summary>
|
||||
[TestClass]
|
||||
public sealed class CsvStatementReaderTests
|
||||
{
|
||||
private static readonly CsvStatementLayout SignedLayout = new(';', 1, 0, 1, 2, 3, null, null, 4);
|
||||
private static readonly CsvStatementLayout TwoColumnLayout = new(';', 1, 0, 1, 2, null, 3, 4, null);
|
||||
|
||||
[TestMethod]
|
||||
public void Read_OneSignedColumn_WithItalianNumbersAndSigns()
|
||||
{
|
||||
const string csv = """
|
||||
Data contabile;Data valuta;Descrizione;Importo;CRO
|
||||
01/10/2026;02/10/2026;"Bonifico da ""Cliente Uno""; saldo";1.234,56;CRO1
|
||||
03/10/2026;03/10/2026;Commissioni;-2,50;
|
||||
|
||||
05/10/2026;;Pagamento F24;1.000,00-;
|
||||
06/10/2026;06/10/2026;Storno;+10;
|
||||
""";
|
||||
|
||||
var statement = Read(csv, SignedLayout);
|
||||
|
||||
Assert.AreEqual(StatementFormat.Csv, statement.Format);
|
||||
Assert.HasCount(4, statement.Movements);
|
||||
Assert.AreEqual(new DateOnly(2026, 10, 1), statement.FromDate);
|
||||
Assert.AreEqual(new DateOnly(2026, 10, 6), statement.ToDate);
|
||||
Assert.IsNull(statement.OpeningBalance);
|
||||
|
||||
var first = statement.Movements[0];
|
||||
Assert.AreEqual(1234.56m, first.Amount);
|
||||
Assert.AreEqual(new DateOnly(2026, 10, 2), first.ValueDate);
|
||||
Assert.AreEqual("Bonifico da \"Cliente Uno\"; saldo", first.Description);
|
||||
Assert.AreEqual("CRO1", first.Reference);
|
||||
Assert.AreEqual(-2.50m, statement.Movements[1].Amount);
|
||||
Assert.IsNull(statement.Movements[1].Reference);
|
||||
Assert.AreEqual(-1000m, statement.Movements[2].Amount);
|
||||
Assert.IsNull(statement.Movements[2].ValueDate);
|
||||
Assert.AreEqual(10m, statement.Movements[3].Amount);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_TwoColumns_GivesMoneyInAndOut()
|
||||
{
|
||||
const string csv = """
|
||||
Data;Valuta;Causale;Entrate;Uscite
|
||||
01/10/2026;01/10/2026;Accredito;500,00;
|
||||
02/10/2026;02/10/2026;Addebito SDD;;120,30
|
||||
02/10/2026;02/10/2026;Addebito con segno;;-80,00
|
||||
Saldo finale;;;;
|
||||
""";
|
||||
|
||||
var statement = Read(csv, TwoColumnLayout);
|
||||
|
||||
CollectionAssert.AreEqual(new[] { 500m, -120.30m, -80m }, statement.Movements.Select(m => m.Amount).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_DecimalPoint_AndQuotedFieldsOnTwoLines()
|
||||
{
|
||||
var layout = new CsvStatementLayout(',', 1, 0, null, 1, 2, null, null, null, "yyyy-MM-dd", DecimalComma: false);
|
||||
const string csv = "Booking date,Description,Amount\r\n2026-10-01,\"Transfer\r\nfrom ACME, Inc.\",\"1,234.50\"\r\n2026-10-02,Fee,-1.25\r\n";
|
||||
|
||||
var statement = Read(csv, layout);
|
||||
|
||||
Assert.HasCount(2, statement.Movements);
|
||||
Assert.AreEqual("Transfer from ACME, Inc.", statement.Movements[0].Description);
|
||||
Assert.AreEqual(1234.50m, statement.Movements[0].Amount);
|
||||
Assert.AreEqual(-1.25m, statement.Movements[1].Amount);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_Utf8WithBom_AndWindows1252()
|
||||
{
|
||||
const string csv = "Data;Valuta;Descrizione;Importo;CRO\n01/10/2026;01/10/2026;Caffè € e più;-1,20;\n";
|
||||
var bom = Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(csv)).ToArray();
|
||||
|
||||
var utf8 = CsvStatementReader.Read(new MemoryStream(bom), SignedLayout);
|
||||
Assert.AreEqual("Caffè € e più", utf8.Movements.Single().Description);
|
||||
|
||||
// Windows-1252: è = E8, ù = F9, € = 80 (not valid UTF-8).
|
||||
var ansi = Encoding.Latin1.GetBytes("Data;Valuta;Descrizione;Importo;CRO\n01/10/2026;01/10/2026;Caffè X e più;-1,20;\n");
|
||||
ansi[Array.IndexOf(ansi, (byte)'X')] = 0x80;
|
||||
var windows = CsvStatementReader.Read(new MemoryStream(ansi), SignedLayout);
|
||||
Assert.AreEqual("Caffè € e più", windows.Movements.Single().Description);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_BadRows_NameTheRow()
|
||||
{
|
||||
var badDate = Assert.ThrowsExactly<BankFileException>(() => Read("h\n01/10/2026;;a;1,00;\n32/13/2026;;b;2,00;\n", SignedLayout));
|
||||
StringAssert.Contains(badDate.Message, "Row 3");
|
||||
|
||||
var badAmount = Assert.ThrowsExactly<BankFileException>(() => Read("h\n01/10/2026;;a;uno;\n", SignedLayout));
|
||||
StringAssert.Contains(badAmount.Message, "Row 2");
|
||||
|
||||
var noAmount = Assert.ThrowsExactly<BankFileException>(() => Read("h\n01/10/2026;;a;;\n", SignedLayout));
|
||||
StringAssert.Contains(noAmount.Message, "Row 2");
|
||||
|
||||
Assert.ThrowsExactly<BankFileException>(() => Read("h\n", new CsvStatementLayout(';', 1, 0, null, 1, null, null, null, null)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_SkipsHeaderRowsAndRowsWithoutDateAndAmount()
|
||||
{
|
||||
var layout = SignedLayout with { HeaderRows = 3 };
|
||||
const string csv = "Banca X\nConto 123\nData;Valuta;Descrizione;Importo;CRO\n01/10/2026;;a;1,00;\nTotale;;;;\n;;;;\n";
|
||||
|
||||
Assert.HasCount(1, Read(csv, layout).Movements);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ParseAmount_ReadsTheBankFormats()
|
||||
{
|
||||
Assert.AreEqual(-1234.56m, CsvStatementReader.ParseAmount("-1.234,56", decimalComma: true));
|
||||
Assert.AreEqual(-1234.56m, CsvStatementReader.ParseAmount("1.234,56-", decimalComma: true));
|
||||
Assert.AreEqual(12m, CsvStatementReader.ParseAmount("+12,00 €", decimalComma: true));
|
||||
Assert.AreEqual(-5m, CsvStatementReader.ParseAmount("(5,00)", decimalComma: true));
|
||||
Assert.AreEqual(1234.5m, CsvStatementReader.ParseAmount("EUR 1,234.50", decimalComma: false));
|
||||
Assert.IsNull(CsvStatementReader.ParseAmount(" ", decimalComma: true));
|
||||
Assert.ThrowsExactly<FormatException>(() => CsvStatementReader.ParseAmount("12a", decimalComma: true));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Detect_ItalianBankHeaders()
|
||||
{
|
||||
// One signed column, value date and reference.
|
||||
var a = CsvStatementReader.Detect("Data contabile;Data valuta;Descrizione operazione;Importo (EUR);CRO")!;
|
||||
Assert.AreEqual(new CsvStatementLayout(';', 1, 0, 1, 2, 3, null, null, 4), a);
|
||||
|
||||
// Money in and out, accents and case.
|
||||
var b = CsvStatementReader.Detect("\"DATA OPERAZIONE\";\"DATA VALUTA\";\"CAUSALE\";\"DESCRIZIONE\";\"ADDEBITI\";\"ACCREDITI\"")!;
|
||||
Assert.AreEqual(0, b.DateColumn);
|
||||
Assert.AreEqual(1, b.ValueDateColumn);
|
||||
Assert.AreEqual(3, b.DescriptionColumn);
|
||||
Assert.IsNull(b.AmountColumn);
|
||||
Assert.AreEqual(5, b.CreditColumn);
|
||||
Assert.AreEqual(4, b.DebitColumn);
|
||||
Assert.IsTrue(b.DecimalComma);
|
||||
|
||||
// Tabs, Dare/Avere, "Riferimento".
|
||||
var c = CsvStatementReader.Detect("Data\tValuta\tDescrizione\tDare\tAvere\tRiferimento")!;
|
||||
Assert.AreEqual('\t', c.Separator);
|
||||
Assert.AreEqual(3, c.DebitColumn);
|
||||
Assert.AreEqual(4, c.CreditColumn);
|
||||
Assert.AreEqual(5, c.ReferenceColumn);
|
||||
|
||||
// Accent-insensitive: "Entrate" and "Uscite" with "Descrizióne".
|
||||
var d = CsvStatementReader.Detect("Data;Descrizióne;Entrate;Uscite")!;
|
||||
Assert.AreEqual(1, d.DescriptionColumn);
|
||||
Assert.AreEqual(2, d.CreditColumn);
|
||||
Assert.IsNull(d.ValueDateColumn);
|
||||
|
||||
// English export.
|
||||
var e = CsvStatementReader.Detect("Booking date,Value date,Description,Amount,Reference")!;
|
||||
Assert.AreEqual(',', e.Separator);
|
||||
Assert.IsFalse(e.DecimalComma);
|
||||
Assert.AreEqual(4, e.ReferenceColumn);
|
||||
|
||||
Assert.IsNull(CsvStatementReader.Detect("Data;Importo"));
|
||||
Assert.IsNull(CsvStatementReader.Detect("Nome;Cognome;Telefono"));
|
||||
Assert.IsNull(CsvStatementReader.Detect(""));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Detect_ThenRead_WorksEndToEnd()
|
||||
{
|
||||
const string csv = "Data operazione;Data valuta;Descrizione;Uscite;Entrate\n12/11/2026;12/11/2026;Bonifico;;1.500,00\n13/11/2026;13/11/2026;POS;12,40;\n";
|
||||
var layout = CsvStatementReader.Detect(csv[..csv.IndexOf('\n', StringComparison.Ordinal)])!;
|
||||
|
||||
var statement = Read(csv, layout);
|
||||
|
||||
CollectionAssert.AreEqual(new[] { 1500m, -12.40m }, statement.Movements.Select(m => m.Amount).ToArray());
|
||||
}
|
||||
|
||||
private static StatementFile Read(string csv, CsvStatementLayout layout)
|
||||
{
|
||||
using var stream = new MemoryStream(Encoding.UTF8.GetBytes(csv));
|
||||
return CsvStatementReader.Read(stream, layout);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
pain.001.001.09 (CustomerCreditTransferInitiationV09) - HAND-WRITTEN SUBSET.
|
||||
This is not the official ISO 20022 schema: it reproduces, from the published message definition, the elements,
|
||||
their order, types and facets for the part Khaemhat writes (SepaXmlWriter.CreditTransfer), with the official type
|
||||
names and target namespace. Elements Khaemhat never writes are left out. Replace this file with the official
|
||||
pain.001.001.09.xsd when it is available in the repository; the tests must keep passing against it.
|
||||
-->
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
|
||||
xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.09"
|
||||
targetNamespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.09"
|
||||
elementFormDefault="qualified">
|
||||
|
||||
<xs:element name="Document" type="Document" />
|
||||
|
||||
<xs:complexType name="Document">
|
||||
<xs:sequence>
|
||||
<xs:element name="CstmrCdtTrfInitn" type="CustomerCreditTransferInitiationV09" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="CustomerCreditTransferInitiationV09">
|
||||
<xs:sequence>
|
||||
<xs:element name="GrpHdr" type="GroupHeader85" />
|
||||
<xs:element name="PmtInf" type="PaymentInstruction30" maxOccurs="unbounded" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="GroupHeader85">
|
||||
<xs:sequence>
|
||||
<xs:element name="MsgId" type="Max35Text" />
|
||||
<xs:element name="CreDtTm" type="ISODateTime" />
|
||||
<xs:element name="NbOfTxs" type="Max15NumericText" />
|
||||
<xs:element name="CtrlSum" type="DecimalNumber" minOccurs="0" />
|
||||
<xs:element name="InitgPty" type="PartyIdentification135" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="PaymentInstruction30">
|
||||
<xs:sequence>
|
||||
<xs:element name="PmtInfId" type="Max35Text" />
|
||||
<xs:element name="PmtMtd" type="PaymentMethod3Code" />
|
||||
<xs:element name="BtchBookg" type="BatchBookingIndicator" minOccurs="0" />
|
||||
<xs:element name="NbOfTxs" type="Max15NumericText" minOccurs="0" />
|
||||
<xs:element name="CtrlSum" type="DecimalNumber" minOccurs="0" />
|
||||
<xs:element name="PmtTpInf" type="PaymentTypeInformation26" minOccurs="0" />
|
||||
<xs:element name="ReqdExctnDt" type="DateAndDateTime2Choice" />
|
||||
<xs:element name="Dbtr" type="PartyIdentification135" />
|
||||
<xs:element name="DbtrAcct" type="CashAccount38" />
|
||||
<xs:element name="DbtrAgt" type="BranchAndFinancialInstitutionIdentification6" />
|
||||
<xs:element name="ChrgBr" type="ChargeBearerType1Code" minOccurs="0" />
|
||||
<xs:element name="CdtTrfTxInf" type="CreditTransferTransaction34" maxOccurs="unbounded" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="PaymentTypeInformation26">
|
||||
<xs:sequence>
|
||||
<xs:element name="SvcLvl" type="ServiceLevel8Choice" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="LclInstrm" type="LocalInstrument2Choice" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="CreditTransferTransaction34">
|
||||
<xs:sequence>
|
||||
<xs:element name="PmtId" type="PaymentIdentification6" />
|
||||
<xs:element name="Amt" type="AmountType4Choice" />
|
||||
<xs:element name="CdtrAgt" type="BranchAndFinancialInstitutionIdentification6" minOccurs="0" />
|
||||
<xs:element name="Cdtr" type="PartyIdentification135" minOccurs="0" />
|
||||
<xs:element name="CdtrAcct" type="CashAccount38" minOccurs="0" />
|
||||
<xs:element name="RmtInf" type="RemittanceInformation16" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="PaymentIdentification6">
|
||||
<xs:sequence>
|
||||
<xs:element name="InstrId" type="Max35Text" minOccurs="0" />
|
||||
<xs:element name="EndToEndId" type="Max35Text" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="AmountType4Choice">
|
||||
<xs:choice>
|
||||
<xs:element name="InstdAmt" type="ActiveOrHistoricCurrencyAndAmount" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="DateAndDateTime2Choice">
|
||||
<xs:choice>
|
||||
<xs:element name="Dt" type="ISODate" />
|
||||
<xs:element name="DtTm" type="ISODateTime" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="PartyIdentification135">
|
||||
<xs:sequence>
|
||||
<xs:element name="Nm" type="Max140Text" minOccurs="0" />
|
||||
<xs:element name="PstlAdr" type="PostalAddress24" minOccurs="0" />
|
||||
<xs:element name="Id" type="Party38Choice" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="PostalAddress24">
|
||||
<xs:sequence>
|
||||
<xs:element name="StrtNm" type="Max70Text" minOccurs="0" />
|
||||
<xs:element name="BldgNb" type="Max16Text" minOccurs="0" />
|
||||
<xs:element name="PstCd" type="Max16Text" minOccurs="0" />
|
||||
<xs:element name="TwnNm" type="Max35Text" minOccurs="0" />
|
||||
<xs:element name="CtrySubDvsn" type="Max35Text" minOccurs="0" />
|
||||
<xs:element name="Ctry" type="CountryCode" minOccurs="0" />
|
||||
<xs:element name="AdrLine" type="Max70Text" minOccurs="0" maxOccurs="7" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="Party38Choice">
|
||||
<xs:choice>
|
||||
<xs:element name="OrgId" type="OrganisationIdentification29" />
|
||||
<xs:element name="PrvtId" type="PersonIdentification13" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="OrganisationIdentification29">
|
||||
<xs:sequence>
|
||||
<xs:element name="AnyBIC" type="AnyBICDec2014Identifier" minOccurs="0" />
|
||||
<xs:element name="LEI" type="LEIIdentifier" minOccurs="0" />
|
||||
<xs:element name="Othr" type="GenericOrganisationIdentification1" minOccurs="0" maxOccurs="unbounded" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="GenericOrganisationIdentification1">
|
||||
<xs:sequence>
|
||||
<xs:element name="Id" type="Max35Text" />
|
||||
<xs:element name="SchmeNm" type="OrganisationIdentificationSchemeName1Choice" minOccurs="0" />
|
||||
<xs:element name="Issr" type="Max35Text" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="OrganisationIdentificationSchemeName1Choice">
|
||||
<xs:choice>
|
||||
<xs:element name="Cd" type="ExternalOrganisationIdentification1Code" />
|
||||
<xs:element name="Prtry" type="Max35Text" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="PersonIdentification13">
|
||||
<xs:sequence>
|
||||
<xs:element name="Othr" type="GenericPersonIdentification1" minOccurs="0" maxOccurs="unbounded" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="GenericPersonIdentification1">
|
||||
<xs:sequence>
|
||||
<xs:element name="Id" type="Max35Text" />
|
||||
<xs:element name="SchmeNm" type="PersonIdentificationSchemeName1Choice" minOccurs="0" />
|
||||
<xs:element name="Issr" type="Max35Text" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="PersonIdentificationSchemeName1Choice">
|
||||
<xs:choice>
|
||||
<xs:element name="Cd" type="ExternalPersonIdentification1Code" />
|
||||
<xs:element name="Prtry" type="Max35Text" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="CashAccount38">
|
||||
<xs:sequence>
|
||||
<xs:element name="Id" type="AccountIdentification4Choice" />
|
||||
<xs:element name="Ccy" type="ActiveOrHistoricCurrencyCode" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="AccountIdentification4Choice">
|
||||
<xs:choice>
|
||||
<xs:element name="IBAN" type="IBAN2007Identifier" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="BranchAndFinancialInstitutionIdentification6">
|
||||
<xs:sequence>
|
||||
<xs:element name="FinInstnId" type="FinancialInstitutionIdentification18" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="FinancialInstitutionIdentification18">
|
||||
<xs:sequence>
|
||||
<xs:element name="BICFI" type="BICFIDec2014Identifier" minOccurs="0" />
|
||||
<xs:element name="Othr" type="GenericFinancialIdentification1" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="GenericFinancialIdentification1">
|
||||
<xs:sequence>
|
||||
<xs:element name="Id" type="Max35Text" />
|
||||
<xs:element name="Issr" type="Max35Text" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="ServiceLevel8Choice">
|
||||
<xs:choice>
|
||||
<xs:element name="Cd" type="ExternalServiceLevel1Code" />
|
||||
<xs:element name="Prtry" type="Max35Text" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="LocalInstrument2Choice">
|
||||
<xs:choice>
|
||||
<xs:element name="Cd" type="ExternalLocalInstrument1Code" />
|
||||
<xs:element name="Prtry" type="Max35Text" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="RemittanceInformation16">
|
||||
<xs:sequence>
|
||||
<xs:element name="Ustrd" type="Max140Text" minOccurs="0" maxOccurs="unbounded" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="ActiveOrHistoricCurrencyAndAmount">
|
||||
<xs:simpleContent>
|
||||
<xs:extension base="ActiveOrHistoricCurrencyAndAmount_SimpleType">
|
||||
<xs:attribute name="Ccy" type="ActiveOrHistoricCurrencyCode" use="required" />
|
||||
</xs:extension>
|
||||
</xs:simpleContent>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:simpleType name="ActiveOrHistoricCurrencyAndAmount_SimpleType">
|
||||
<xs:restriction base="xs:decimal">
|
||||
<xs:fractionDigits value="5" />
|
||||
<xs:totalDigits value="18" />
|
||||
<xs:minInclusive value="0" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ActiveOrHistoricCurrencyCode">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:pattern value="[A-Z]{3,3}" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="DecimalNumber">
|
||||
<xs:restriction base="xs:decimal">
|
||||
<xs:fractionDigits value="17" />
|
||||
<xs:totalDigits value="18" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="Max15NumericText">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:pattern value="[0-9]{1,15}" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="BatchBookingIndicator">
|
||||
<xs:restriction base="xs:boolean" />
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="PaymentMethod3Code">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:enumeration value="CHK" />
|
||||
<xs:enumeration value="TRF" />
|
||||
<xs:enumeration value="TRA" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ChargeBearerType1Code">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:enumeration value="DEBT" />
|
||||
<xs:enumeration value="CRED" />
|
||||
<xs:enumeration value="SHAR" />
|
||||
<xs:enumeration value="SLEV" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="IBAN2007Identifier">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:pattern value="[A-Z]{2,2}[0-9]{2,2}[a-zA-Z0-9]{1,30}" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="BICFIDec2014Identifier">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:pattern value="[A-Z0-9]{4,4}[A-Z]{2,2}[A-Z0-9]{2,2}([A-Z0-9]{3,3}){0,1}" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="AnyBICDec2014Identifier">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:pattern value="[A-Z0-9]{4,4}[A-Z]{2,2}[A-Z0-9]{2,2}([A-Z0-9]{3,3}){0,1}" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="LEIIdentifier">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:pattern value="[A-Z0-9]{18,18}[0-9]{2,2}" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="CountryCode">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:pattern value="[A-Z]{2,2}" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ISODate">
|
||||
<xs:restriction base="xs:date" />
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ISODateTime">
|
||||
<xs:restriction base="xs:dateTime" />
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ExternalServiceLevel1Code">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="4" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ExternalLocalInstrument1Code">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="35" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ExternalOrganisationIdentification1Code">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="4" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ExternalPersonIdentification1Code">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="4" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="Max16Text">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="16" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="Max35Text">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="35" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="Max70Text">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="70" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="Max140Text">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="140" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
</xs:schema>
|
||||
@@ -0,0 +1,385 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
pain.008.001.08 (CustomerDirectDebitInitiationV08) - HAND-WRITTEN SUBSET.
|
||||
This is not the official ISO 20022 schema: it reproduces, from the published message definition, the elements,
|
||||
their order, types and facets for the part Khaemhat writes (SepaXmlWriter.DirectDebit), with the official type
|
||||
names and target namespace. Elements Khaemhat never writes are left out. Replace this file with the official
|
||||
pain.008.001.08.xsd when it is available in the repository; the tests must keep passing against it.
|
||||
-->
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
|
||||
xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.001.08"
|
||||
targetNamespace="urn:iso:std:iso:20022:tech:xsd:pain.008.001.08"
|
||||
elementFormDefault="qualified">
|
||||
|
||||
<xs:element name="Document" type="Document" />
|
||||
|
||||
<xs:complexType name="Document">
|
||||
<xs:sequence>
|
||||
<xs:element name="CstmrDrctDbtInitn" type="CustomerDirectDebitInitiationV08" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="CustomerDirectDebitInitiationV08">
|
||||
<xs:sequence>
|
||||
<xs:element name="GrpHdr" type="GroupHeader83" />
|
||||
<xs:element name="PmtInf" type="PaymentInstruction29" maxOccurs="unbounded" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="GroupHeader83">
|
||||
<xs:sequence>
|
||||
<xs:element name="MsgId" type="Max35Text" />
|
||||
<xs:element name="CreDtTm" type="ISODateTime" />
|
||||
<xs:element name="NbOfTxs" type="Max15NumericText" />
|
||||
<xs:element name="CtrlSum" type="DecimalNumber" minOccurs="0" />
|
||||
<xs:element name="InitgPty" type="PartyIdentification135" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="PaymentInstruction29">
|
||||
<xs:sequence>
|
||||
<xs:element name="PmtInfId" type="Max35Text" />
|
||||
<xs:element name="PmtMtd" type="PaymentMethod2Code" />
|
||||
<xs:element name="BtchBookg" type="BatchBookingIndicator" minOccurs="0" />
|
||||
<xs:element name="NbOfTxs" type="Max15NumericText" minOccurs="0" />
|
||||
<xs:element name="CtrlSum" type="DecimalNumber" minOccurs="0" />
|
||||
<xs:element name="PmtTpInf" type="PaymentTypeInformation29" minOccurs="0" />
|
||||
<xs:element name="ReqdColltnDt" type="ISODate" />
|
||||
<xs:element name="Cdtr" type="PartyIdentification135" />
|
||||
<xs:element name="CdtrAcct" type="CashAccount38" />
|
||||
<xs:element name="CdtrAgt" type="BranchAndFinancialInstitutionIdentification6" />
|
||||
<xs:element name="ChrgBr" type="ChargeBearerType1Code" minOccurs="0" />
|
||||
<xs:element name="CdtrSchmeId" type="PartyIdentification135" minOccurs="0" />
|
||||
<xs:element name="DrctDbtTxInf" type="DirectDebitTransactionInformation23" maxOccurs="unbounded" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="PaymentTypeInformation29">
|
||||
<xs:sequence>
|
||||
<xs:element name="SvcLvl" type="ServiceLevel8Choice" minOccurs="0" maxOccurs="unbounded" />
|
||||
<xs:element name="LclInstrm" type="LocalInstrument2Choice" minOccurs="0" />
|
||||
<xs:element name="SeqTp" type="SequenceType3Code" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="DirectDebitTransactionInformation23">
|
||||
<xs:sequence>
|
||||
<xs:element name="PmtId" type="PaymentIdentification6" />
|
||||
<xs:element name="InstdAmt" type="ActiveOrHistoricCurrencyAndAmount" />
|
||||
<xs:element name="DrctDbtTx" type="DirectDebitTransaction10" minOccurs="0" />
|
||||
<xs:element name="DbtrAgt" type="BranchAndFinancialInstitutionIdentification6" />
|
||||
<xs:element name="Dbtr" type="PartyIdentification135" />
|
||||
<xs:element name="DbtrAcct" type="CashAccount38" />
|
||||
<xs:element name="RmtInf" type="RemittanceInformation16" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="DirectDebitTransaction10">
|
||||
<xs:sequence>
|
||||
<xs:element name="MndtRltdInf" type="MandateRelatedInformation14" minOccurs="0" />
|
||||
<xs:element name="CdtrSchmeId" type="PartyIdentification135" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="MandateRelatedInformation14">
|
||||
<xs:sequence>
|
||||
<xs:element name="MndtId" type="Max35Text" minOccurs="0" />
|
||||
<xs:element name="DtOfSgntr" type="ISODate" minOccurs="0" />
|
||||
<xs:element name="AmdmntInd" type="TrueFalseIndicator" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="PaymentIdentification6">
|
||||
<xs:sequence>
|
||||
<xs:element name="InstrId" type="Max35Text" minOccurs="0" />
|
||||
<xs:element name="EndToEndId" type="Max35Text" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="PartyIdentification135">
|
||||
<xs:sequence>
|
||||
<xs:element name="Nm" type="Max140Text" minOccurs="0" />
|
||||
<xs:element name="PstlAdr" type="PostalAddress24" minOccurs="0" />
|
||||
<xs:element name="Id" type="Party38Choice" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="PostalAddress24">
|
||||
<xs:sequence>
|
||||
<xs:element name="StrtNm" type="Max70Text" minOccurs="0" />
|
||||
<xs:element name="BldgNb" type="Max16Text" minOccurs="0" />
|
||||
<xs:element name="PstCd" type="Max16Text" minOccurs="0" />
|
||||
<xs:element name="TwnNm" type="Max35Text" minOccurs="0" />
|
||||
<xs:element name="CtrySubDvsn" type="Max35Text" minOccurs="0" />
|
||||
<xs:element name="Ctry" type="CountryCode" minOccurs="0" />
|
||||
<xs:element name="AdrLine" type="Max70Text" minOccurs="0" maxOccurs="7" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="Party38Choice">
|
||||
<xs:choice>
|
||||
<xs:element name="OrgId" type="OrganisationIdentification29" />
|
||||
<xs:element name="PrvtId" type="PersonIdentification13" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="OrganisationIdentification29">
|
||||
<xs:sequence>
|
||||
<xs:element name="AnyBIC" type="AnyBICDec2014Identifier" minOccurs="0" />
|
||||
<xs:element name="LEI" type="LEIIdentifier" minOccurs="0" />
|
||||
<xs:element name="Othr" type="GenericOrganisationIdentification1" minOccurs="0" maxOccurs="unbounded" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="GenericOrganisationIdentification1">
|
||||
<xs:sequence>
|
||||
<xs:element name="Id" type="Max35Text" />
|
||||
<xs:element name="SchmeNm" type="OrganisationIdentificationSchemeName1Choice" minOccurs="0" />
|
||||
<xs:element name="Issr" type="Max35Text" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="OrganisationIdentificationSchemeName1Choice">
|
||||
<xs:choice>
|
||||
<xs:element name="Cd" type="ExternalOrganisationIdentification1Code" />
|
||||
<xs:element name="Prtry" type="Max35Text" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="PersonIdentification13">
|
||||
<xs:sequence>
|
||||
<xs:element name="Othr" type="GenericPersonIdentification1" minOccurs="0" maxOccurs="unbounded" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="GenericPersonIdentification1">
|
||||
<xs:sequence>
|
||||
<xs:element name="Id" type="Max35Text" />
|
||||
<xs:element name="SchmeNm" type="PersonIdentificationSchemeName1Choice" minOccurs="0" />
|
||||
<xs:element name="Issr" type="Max35Text" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="PersonIdentificationSchemeName1Choice">
|
||||
<xs:choice>
|
||||
<xs:element name="Cd" type="ExternalPersonIdentification1Code" />
|
||||
<xs:element name="Prtry" type="Max35Text" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="CashAccount38">
|
||||
<xs:sequence>
|
||||
<xs:element name="Id" type="AccountIdentification4Choice" />
|
||||
<xs:element name="Ccy" type="ActiveOrHistoricCurrencyCode" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="AccountIdentification4Choice">
|
||||
<xs:choice>
|
||||
<xs:element name="IBAN" type="IBAN2007Identifier" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="BranchAndFinancialInstitutionIdentification6">
|
||||
<xs:sequence>
|
||||
<xs:element name="FinInstnId" type="FinancialInstitutionIdentification18" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="FinancialInstitutionIdentification18">
|
||||
<xs:sequence>
|
||||
<xs:element name="BICFI" type="BICFIDec2014Identifier" minOccurs="0" />
|
||||
<xs:element name="Othr" type="GenericFinancialIdentification1" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="GenericFinancialIdentification1">
|
||||
<xs:sequence>
|
||||
<xs:element name="Id" type="Max35Text" />
|
||||
<xs:element name="Issr" type="Max35Text" minOccurs="0" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="ServiceLevel8Choice">
|
||||
<xs:choice>
|
||||
<xs:element name="Cd" type="ExternalServiceLevel1Code" />
|
||||
<xs:element name="Prtry" type="Max35Text" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="LocalInstrument2Choice">
|
||||
<xs:choice>
|
||||
<xs:element name="Cd" type="ExternalLocalInstrument1Code" />
|
||||
<xs:element name="Prtry" type="Max35Text" />
|
||||
</xs:choice>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="RemittanceInformation16">
|
||||
<xs:sequence>
|
||||
<xs:element name="Ustrd" type="Max140Text" minOccurs="0" maxOccurs="unbounded" />
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:complexType name="ActiveOrHistoricCurrencyAndAmount">
|
||||
<xs:simpleContent>
|
||||
<xs:extension base="ActiveOrHistoricCurrencyAndAmount_SimpleType">
|
||||
<xs:attribute name="Ccy" type="ActiveOrHistoricCurrencyCode" use="required" />
|
||||
</xs:extension>
|
||||
</xs:simpleContent>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:simpleType name="ActiveOrHistoricCurrencyAndAmount_SimpleType">
|
||||
<xs:restriction base="xs:decimal">
|
||||
<xs:fractionDigits value="5" />
|
||||
<xs:totalDigits value="18" />
|
||||
<xs:minInclusive value="0" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ActiveOrHistoricCurrencyCode">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:pattern value="[A-Z]{3,3}" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="DecimalNumber">
|
||||
<xs:restriction base="xs:decimal">
|
||||
<xs:fractionDigits value="17" />
|
||||
<xs:totalDigits value="18" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="Max15NumericText">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:pattern value="[0-9]{1,15}" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="BatchBookingIndicator">
|
||||
<xs:restriction base="xs:boolean" />
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ChargeBearerType1Code">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:enumeration value="DEBT" />
|
||||
<xs:enumeration value="CRED" />
|
||||
<xs:enumeration value="SHAR" />
|
||||
<xs:enumeration value="SLEV" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="IBAN2007Identifier">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:pattern value="[A-Z]{2,2}[0-9]{2,2}[a-zA-Z0-9]{1,30}" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="BICFIDec2014Identifier">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:pattern value="[A-Z0-9]{4,4}[A-Z]{2,2}[A-Z0-9]{2,2}([A-Z0-9]{3,3}){0,1}" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="AnyBICDec2014Identifier">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:pattern value="[A-Z0-9]{4,4}[A-Z]{2,2}[A-Z0-9]{2,2}([A-Z0-9]{3,3}){0,1}" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="LEIIdentifier">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:pattern value="[A-Z0-9]{18,18}[0-9]{2,2}" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="CountryCode">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:pattern value="[A-Z]{2,2}" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ISODate">
|
||||
<xs:restriction base="xs:date" />
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ISODateTime">
|
||||
<xs:restriction base="xs:dateTime" />
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ExternalServiceLevel1Code">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="4" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ExternalLocalInstrument1Code">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="35" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ExternalOrganisationIdentification1Code">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="4" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="ExternalPersonIdentification1Code">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="4" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="Max16Text">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="16" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="Max35Text">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="35" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="Max70Text">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="70" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="Max140Text">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:minLength value="1" />
|
||||
<xs:maxLength value="140" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="PaymentMethod2Code">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:enumeration value="DD" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="SequenceType3Code">
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:enumeration value="FRST" />
|
||||
<xs:enumeration value="RCUR" />
|
||||
<xs:enumeration value="FNAL" />
|
||||
<xs:enumeration value="OOFF" />
|
||||
<xs:enumeration value="RPRE" />
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
|
||||
<xs:simpleType name="TrueFalseIndicator">
|
||||
<xs:restriction base="xs:boolean" />
|
||||
</xs:simpleType>
|
||||
|
||||
</xs:schema>
|
||||
@@ -0,0 +1,338 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Xml;
|
||||
using System.Xml.Linq;
|
||||
using System.Xml.Schema;
|
||||
using Khaemhat.Core.Treasury;
|
||||
|
||||
namespace Khaemhat.Core.Tests.Treasury;
|
||||
|
||||
/// <summary>
|
||||
/// SEPA credit transfers (<c>pain.001.001.09</c>) and direct debits (<c>pain.008.001.08</c>), issues #70 and #71: the
|
||||
/// files validate against the schemas, totals and counts, the character set, the grouping of debits and the errors.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class SepaXmlWriterTests
|
||||
{
|
||||
private const string CompanyIban = "IT60X0542811101000000123456";
|
||||
|
||||
private static readonly BankFileCompany Company = new(
|
||||
"Officine Bàlbo S.r.l.",
|
||||
"01234567890",
|
||||
"Via Roma 1",
|
||||
"10121",
|
||||
"Torino",
|
||||
"TO",
|
||||
"IT",
|
||||
CompanyIban,
|
||||
"BPMOIT22XXX",
|
||||
"A1B2C",
|
||||
"ABC1234X",
|
||||
"IT66ZZZA1B2C3D4E5F6G7H8");
|
||||
|
||||
[TestMethod]
|
||||
public void CreditTransfer_ValidatesAgainstTheSchema_WithCountsAndTotals()
|
||||
{
|
||||
var file = SepaXmlWriter.CreditTransfer(Transfers());
|
||||
|
||||
Assert.AreEqual("SCT_DIST-2026-0042.xml", file.FileName);
|
||||
Assert.AreEqual("application/xml", file.ContentType);
|
||||
AssertValid(file.Content, "pain.001.001.09.xsd", SepaXmlWriter.CreditTransferNamespace);
|
||||
|
||||
var doc = Load(file.Content);
|
||||
XNamespace ns = SepaXmlWriter.CreditTransferNamespace;
|
||||
var header = doc.Descendants(ns + "GrpHdr").Single();
|
||||
Assert.AreEqual("DIST-2026-0042", header.Element(ns + "MsgId")!.Value);
|
||||
Assert.AreEqual("2026-11-13T09:30:00", header.Element(ns + "CreDtTm")!.Value);
|
||||
Assert.AreEqual("3", header.Element(ns + "NbOfTxs")!.Value);
|
||||
Assert.AreEqual("1601.25", header.Element(ns + "CtrlSum")!.Value);
|
||||
var initiator = header.Element(ns + "InitgPty")!;
|
||||
Assert.AreEqual("ABC1234X", initiator.Descendants(ns + "Othr").Single().Element(ns + "Id")!.Value);
|
||||
Assert.AreEqual("CBI", initiator.Descendants(ns + "Issr").Single().Value);
|
||||
|
||||
var payment = doc.Descendants(ns + "PmtInf").Single();
|
||||
Assert.AreEqual("TRF", payment.Element(ns + "PmtMtd")!.Value);
|
||||
Assert.AreEqual("true", payment.Element(ns + "BtchBookg")!.Value);
|
||||
Assert.AreEqual("3", payment.Element(ns + "NbOfTxs")!.Value);
|
||||
Assert.AreEqual("1601.25", payment.Element(ns + "CtrlSum")!.Value);
|
||||
Assert.AreEqual("SEPA", payment.Element(ns + "PmtTpInf")!.Descendants(ns + "Cd").Single().Value);
|
||||
Assert.AreEqual("2026-11-16", payment.Element(ns + "ReqdExctnDt")!.Element(ns + "Dt")!.Value);
|
||||
Assert.AreEqual(CompanyIban, payment.Element(ns + "DbtrAcct")!.Descendants(ns + "IBAN").Single().Value);
|
||||
Assert.AreEqual("BPMOIT22XXX", payment.Element(ns + "DbtrAgt")!.Descendants(ns + "BICFI").Single().Value);
|
||||
Assert.AreEqual("SLEV", payment.Element(ns + "ChrgBr")!.Value);
|
||||
|
||||
var transactions = payment.Elements(ns + "CdtTrfTxInf").ToList();
|
||||
Assert.HasCount(3, transactions);
|
||||
var first = transactions[0];
|
||||
Assert.AreEqual("E2E-1", first.Descendants(ns + "EndToEndId").Single().Value);
|
||||
var amount = first.Descendants(ns + "InstdAmt").Single();
|
||||
Assert.AreEqual("1000.00", amount.Value);
|
||||
Assert.AreEqual("EUR", amount.Attribute("Ccy")!.Value);
|
||||
Assert.AreEqual("DEUTDEFFXXX", first.Element(ns + "CdtrAgt")!.Descendants(ns + "BICFI").Single().Value);
|
||||
Assert.AreEqual("DE", first.Element(ns + "Cdtr")!.Descendants(ns + "Ctry").Single().Value);
|
||||
Assert.AreEqual("Berlin", first.Element(ns + "Cdtr")!.Descendants(ns + "TwnNm").Single().Value);
|
||||
Assert.AreEqual("FT 2026/000388 del 31/08/2026", first.Descendants(ns + "Ustrd").Single().Value);
|
||||
|
||||
// A creditor without BIC has no agent; the amount is rounded to two decimals.
|
||||
Assert.IsNull(transactions[1].Element(ns + "CdtrAgt"));
|
||||
Assert.AreEqual("0.25", transactions[2].Descendants(ns + "InstdAmt").Single().Value);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CreditTransfer_WithoutBicOrCuc_WritesNotProvided_AndNoInitiatorId()
|
||||
{
|
||||
var remittance = Transfers() with { Company = Company with { Bic = null, CucCode = null } };
|
||||
|
||||
var file = SepaXmlWriter.CreditTransfer(remittance);
|
||||
|
||||
AssertValid(file.Content, "pain.001.001.09.xsd", SepaXmlWriter.CreditTransferNamespace);
|
||||
var doc = Load(file.Content);
|
||||
XNamespace ns = SepaXmlWriter.CreditTransferNamespace;
|
||||
Assert.AreEqual("NOTPROVIDED", doc.Descendants(ns + "DbtrAgt").Single().Descendants(ns + "Id").Single().Value);
|
||||
Assert.IsNull(doc.Descendants(ns + "InitgPty").Single().Element(ns + "Id"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Schemas_RejectAFileOutOfTheRules()
|
||||
{
|
||||
var transfer = Encoding.UTF8.GetString(SepaXmlWriter.CreditTransfer(Transfers()).Content);
|
||||
var debit = Encoding.UTF8.GetString(SepaXmlWriter.DirectDebit(Debits(RemittanceKind.SddCore)).Content);
|
||||
|
||||
string[] brokenTransfers =
|
||||
[
|
||||
transfer.Replace("<PmtMtd>TRF</PmtMtd>", "<PmtMtd>DD</PmtMtd>", StringComparison.Ordinal),
|
||||
transfer.Replace("<IBAN>IT60X", "<IBAN>it60x", StringComparison.Ordinal),
|
||||
transfer.Replace(">1000.00<", ">1000.001234<", StringComparison.Ordinal),
|
||||
transfer.Replace("<ChrgBr>SLEV</ChrgBr>", string.Empty, StringComparison.Ordinal).Replace("<BtchBookg>", "<ChrgBr>SLEV</ChrgBr><BtchBookg>", StringComparison.Ordinal),
|
||||
transfer.Replace("pain.001.001.09", "pain.001.001.03", StringComparison.Ordinal),
|
||||
];
|
||||
foreach (var broken in brokenTransfers)
|
||||
{
|
||||
Assert.IsNotEmpty(Validate(Encoding.UTF8.GetBytes(broken), "pain.001.001.09.xsd", SepaXmlWriter.CreditTransferNamespace));
|
||||
}
|
||||
|
||||
Assert.IsNotEmpty(Validate(
|
||||
Encoding.UTF8.GetBytes(debit.Replace("<SeqTp>FRST</SeqTp>", "<SeqTp>FIRST</SeqTp>", StringComparison.Ordinal)),
|
||||
"pain.008.001.08.xsd",
|
||||
SepaXmlWriter.DirectDebitNamespace));
|
||||
Assert.IsNotEmpty(Validate(
|
||||
Encoding.UTF8.GetBytes(debit.Replace("<MndtId>MND-001</MndtId>", "<MndtId>" + new string('M', 36) + "</MndtId>", StringComparison.Ordinal)),
|
||||
"pain.008.001.08.xsd",
|
||||
SepaXmlWriter.DirectDebitNamespace));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CreditTransfer_IsUtf8WithoutBom()
|
||||
{
|
||||
var file = SepaXmlWriter.CreditTransfer(Transfers());
|
||||
|
||||
Assert.AreEqual((byte)'<', file.Content[0]);
|
||||
StringAssert.StartsWith(Encoding.UTF8.GetString(file.Content), "<?xml version=\"1.0\" encoding=\"utf-8\"?>");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Texts_AreReducedToTheSepaCharacterSet_AndCut()
|
||||
{
|
||||
Assert.AreEqual("Officine Balbo S.r.l.", SepaXmlWriter.Text("Officine Bàlbo S.r.l.", 70));
|
||||
Assert.AreEqual("Citta Perche Pero E E AEIOU", SepaXmlWriter.Text("Città Perché Però È É ÀÈÌÒÙ", 70));
|
||||
Assert.AreEqual("Rossi Figli - n 5 (ok)", SepaXmlWriter.Text("Rossi & Figli - n° 5 (ok)", 70));
|
||||
Assert.AreEqual("abc", SepaXmlWriter.Text(" abc€ ", 70));
|
||||
Assert.AreEqual(string.Empty, SepaXmlWriter.Text(null, 70));
|
||||
Assert.AreEqual("12345", SepaXmlWriter.Text("123456789", 5));
|
||||
|
||||
var item = Transfers().Items[0] with
|
||||
{
|
||||
CounterpartyName = "Società " + new string('x', 100),
|
||||
Reference = new string('r', 200) + " & co",
|
||||
EndToEndId = new string('e', 50),
|
||||
};
|
||||
var doc = Load(SepaXmlWriter.CreditTransfer(Transfers() with { Items = [item] }).Content);
|
||||
XNamespace ns = SepaXmlWriter.CreditTransferNamespace;
|
||||
var name = doc.Descendants(ns + "Cdtr").Single().Element(ns + "Nm")!.Value;
|
||||
Assert.AreEqual(70, name.Length);
|
||||
StringAssert.StartsWith(name, "Societa x");
|
||||
Assert.AreEqual(140, doc.Descendants(ns + "Ustrd").Single().Value.Length);
|
||||
Assert.AreEqual(35, doc.Descendants(ns + "EndToEndId").Single().Value.Length);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DirectDebit_ValidatesAgainstTheSchema_AndGroupsBySequenceAndDate()
|
||||
{
|
||||
var file = SepaXmlWriter.DirectDebit(Debits(RemittanceKind.SddCore));
|
||||
|
||||
Assert.AreEqual("SDD_RID-7.xml", file.FileName);
|
||||
AssertValid(file.Content, "pain.008.001.08.xsd", SepaXmlWriter.DirectDebitNamespace);
|
||||
|
||||
var doc = Load(file.Content);
|
||||
XNamespace ns = SepaXmlWriter.DirectDebitNamespace;
|
||||
var header = doc.Descendants(ns + "GrpHdr").Single();
|
||||
Assert.AreEqual("4", header.Element(ns + "NbOfTxs")!.Value);
|
||||
Assert.AreEqual("460.00", header.Element(ns + "CtrlSum")!.Value);
|
||||
|
||||
var groups = doc.Descendants(ns + "PmtInf").ToList();
|
||||
Assert.HasCount(3, groups);
|
||||
string Describe(XElement g) => string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"{g.Element(ns + "ReqdColltnDt")!.Value} {g.Descendants(ns + "SeqTp").Single().Value} {g.Element(ns + "NbOfTxs")!.Value} {g.Element(ns + "CtrlSum")!.Value}");
|
||||
Assert.AreEqual("2026-12-01 FRST 1 100.00", Describe(groups[0]));
|
||||
Assert.AreEqual("2026-12-01 RCUR 2 300.00", Describe(groups[1]));
|
||||
Assert.AreEqual("2026-12-15 RCUR 1 60.00", Describe(groups[2]));
|
||||
Assert.AreEqual("RID-7-1", groups[0].Element(ns + "PmtInfId")!.Value);
|
||||
Assert.AreEqual("RID-7-3", groups[2].Element(ns + "PmtInfId")!.Value);
|
||||
|
||||
var first = groups[0];
|
||||
Assert.AreEqual("DD", first.Element(ns + "PmtMtd")!.Value);
|
||||
Assert.AreEqual("CORE", first.Descendants(ns + "LclInstrm").Single().Element(ns + "Cd")!.Value);
|
||||
Assert.AreEqual("IT66ZZZA1B2C3D4E5F6G7H8", first.Element(ns + "CdtrSchmeId")!.Descendants(ns + "Id").Last().Value);
|
||||
Assert.AreEqual("SEPA", first.Element(ns + "CdtrSchmeId")!.Descendants(ns + "Prtry").Single().Value);
|
||||
Assert.AreEqual(CompanyIban, first.Element(ns + "CdtrAcct")!.Descendants(ns + "IBAN").Single().Value);
|
||||
|
||||
var debit = first.Elements(ns + "DrctDbtTxInf").Single();
|
||||
Assert.AreEqual("100.00", debit.Element(ns + "InstdAmt")!.Value);
|
||||
Assert.AreEqual("MND-001", debit.Descendants(ns + "MndtId").Single().Value);
|
||||
Assert.AreEqual("2025-03-01", debit.Descendants(ns + "DtOfSgntr").Single().Value);
|
||||
Assert.AreEqual("NOTPROVIDED", debit.Element(ns + "DbtrAgt")!.Descendants(ns + "Id").Single().Value);
|
||||
Assert.AreEqual("IT63A0200801600000101234567", debit.Element(ns + "DbtrAcct")!.Descendants(ns + "IBAN").Single().Value);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DirectDebit_B2b_WritesTheB2bInstrument()
|
||||
{
|
||||
var file = SepaXmlWriter.DirectDebit(Debits(RemittanceKind.SddB2b));
|
||||
|
||||
AssertValid(file.Content, "pain.008.001.08.xsd", SepaXmlWriter.DirectDebitNamespace);
|
||||
XNamespace ns = SepaXmlWriter.DirectDebitNamespace;
|
||||
Assert.IsTrue(Load(file.Content).Descendants(ns + "LclInstrm").All(l => l.Element(ns + "Cd")!.Value == "B2B"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DirectDebit_SequenceCodes_CoverEveryValue()
|
||||
{
|
||||
var debits = Debits(RemittanceKind.SddCore);
|
||||
var items = new[] { SddSequence.First, SddSequence.Recurrent, SddSequence.Final, SddSequence.OneOff }
|
||||
.Select((s, i) => debits.Items[0] with { Sequence = s, EndToEndId = "E" + i.ToString(CultureInfo.InvariantCulture) })
|
||||
.ToList();
|
||||
|
||||
var doc = Load(SepaXmlWriter.DirectDebit(debits with { Items = items }).Content);
|
||||
|
||||
XNamespace ns = SepaXmlWriter.DirectDebitNamespace;
|
||||
CollectionAssert.AreEqual(new[] { "FRST", "RCUR", "FNAL", "OOFF" }, doc.Descendants(ns + "SeqTp").Select(s => s.Value).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Errors_AreBankFileExceptions()
|
||||
{
|
||||
var transfers = Transfers();
|
||||
var debits = Debits(RemittanceKind.SddCore);
|
||||
var transfer = transfers.Items[0];
|
||||
var debit = debits.Items[0];
|
||||
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Amount = 0m }] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Amount = -5m }] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Amount = 0.004m }] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Company = Company with { Iban = "" } }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Company = Company with { Iban = "IT61X0542811101000000123456" } }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Iban = null }] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Iban = "DE89370400440532013001" }] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Bic = "NOT A BIC" }] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Kind = RemittanceKind.SddCore }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.CreditTransfer(transfers with { Kind = RemittanceKind.Riba }));
|
||||
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Items = [] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Company = Company with { CreditorId = null } }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { MandateId = " " }] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { MandateDate = null }] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { Amount = 0m }] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { Iban = "" }] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Kind = RemittanceKind.SepaCreditTransfer }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => SepaXmlWriter.DirectDebit(debits with { Kind = RemittanceKind.Riba }));
|
||||
}
|
||||
|
||||
private static BankFileRemittance Transfers() => new(
|
||||
RemittanceKind.SepaCreditTransfer,
|
||||
"DIST-2026-0042",
|
||||
new DateTime(2026, 11, 13, 9, 30, 0, DateTimeKind.Local),
|
||||
new DateOnly(2026, 11, 16),
|
||||
Company,
|
||||
[
|
||||
new BankFileItem(1, "F001", "Müller GmbH", "DE123456789", "Hauptstraße 5", "10115", "Berlin", null, "DE", "DE89370400440532013000", "DEUTDEFF XXX", null, 1000m, new DateOnly(2026, 11, 16), "FT 2026/000388 del 31/08/2026", "E2E-1"),
|
||||
new BankFileItem(2, "F002", "Fornitore Rossi & C.", "01234567897", null, null, null, null, "it", "IT68 X030 6909 6061 0000 0063 241", null, null, 601m, new DateOnly(2026, 11, 16), "Saldo fattura 12", "E2E-2"),
|
||||
new BankFileItem(3, "F003", "Société Générale Client", null, "1 rue de la Paix", "75002", "Paris", null, "FR", "FR1420041010050500013M02606", null, null, 0.249m, new DateOnly(2026, 11, 16), "Arrotondamento", "E2E-3"),
|
||||
]);
|
||||
|
||||
private static BankFileRemittance Debits(RemittanceKind kind)
|
||||
{
|
||||
BankFileItem Debit(int n, decimal amount, DateOnly due, SddSequence sequence) => new(
|
||||
n,
|
||||
"C00" + n.ToString(CultureInfo.InvariantCulture),
|
||||
"Cliente " + n.ToString(CultureInfo.InvariantCulture),
|
||||
null,
|
||||
"Via Po " + n.ToString(CultureInfo.InvariantCulture),
|
||||
"20121",
|
||||
"Milano",
|
||||
"MI",
|
||||
"IT",
|
||||
"IT63A0200801600000101234567",
|
||||
null,
|
||||
null,
|
||||
amount,
|
||||
due,
|
||||
"Canone dicembre",
|
||||
"RID7-" + n.ToString(CultureInfo.InvariantCulture),
|
||||
"MND-00" + n.ToString(CultureInfo.InvariantCulture),
|
||||
new DateOnly(2025, 3, 1),
|
||||
sequence);
|
||||
|
||||
var first = new DateOnly(2026, 12, 1);
|
||||
var second = new DateOnly(2026, 12, 15);
|
||||
return new BankFileRemittance(
|
||||
kind,
|
||||
"RID-7",
|
||||
new DateTime(2026, 11, 13, 10, 0, 0, DateTimeKind.Local),
|
||||
first,
|
||||
Company,
|
||||
[
|
||||
Debit(1, 100m, first, SddSequence.First),
|
||||
Debit(2, 120m, first, SddSequence.Recurrent),
|
||||
Debit(3, 60m, second, SddSequence.Recurrent),
|
||||
Debit(4, 180m, first, SddSequence.Recurrent),
|
||||
]);
|
||||
}
|
||||
|
||||
private static XDocument Load(byte[] content)
|
||||
{
|
||||
using var stream = new MemoryStream(content);
|
||||
return XDocument.Load(stream);
|
||||
}
|
||||
|
||||
private static void AssertValid(byte[] content, string schemaFile, string ns)
|
||||
{
|
||||
var errors = Validate(content, schemaFile, ns);
|
||||
Assert.IsEmpty(errors, string.Join(Environment.NewLine, errors));
|
||||
}
|
||||
|
||||
// Warnings are reported too, so that an element the schema does not know (or a wrong namespace) is not skipped.
|
||||
private static List<string> Validate(byte[] content, string schemaFile, string ns)
|
||||
{
|
||||
var schemas = new XmlSchemaSet();
|
||||
schemas.Add(ns, Path.Combine(AppContext.BaseDirectory, "Treasury", "Schemas", schemaFile));
|
||||
var errors = new List<string>();
|
||||
var settings = new XmlReaderSettings
|
||||
{
|
||||
ValidationType = ValidationType.Schema,
|
||||
Schemas = schemas,
|
||||
ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints,
|
||||
};
|
||||
settings.ValidationEventHandler += (_, e) => errors.Add($"{e.Severity}: {e.Message} (line {e.Exception?.LineNumber})");
|
||||
using var stream = new MemoryStream(content);
|
||||
using (var reader = XmlReader.Create(stream, settings))
|
||||
{
|
||||
while (reader.Read())
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
using System.Text;
|
||||
using Khaemhat.Core.Treasury;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy.Tests;
|
||||
|
||||
/// <summary>The CBI current account statement (issue #71): balances, movements and their description lines.</summary>
|
||||
[TestClass]
|
||||
public sealed class CbiStatementReaderTests
|
||||
{
|
||||
private static readonly CbiStatementReader Reader = new();
|
||||
|
||||
[TestMethod]
|
||||
public void Read_SampleStatement_WithBalancesMovementsAndDescriptions()
|
||||
{
|
||||
var statement = Read(string.Join("\r\n", Sample()));
|
||||
|
||||
Assert.AreEqual(StatementFormat.Cbi, Reader.Format);
|
||||
Assert.AreEqual(StatementFormat.Cbi, statement.Format);
|
||||
Assert.AreEqual("IT60X0542811101000000123456", statement.AccountIban);
|
||||
Assert.AreEqual("EUR", statement.Currency);
|
||||
Assert.AreEqual(1000m, statement.OpeningBalance);
|
||||
Assert.AreEqual(2207.50m, statement.ClosingBalance);
|
||||
Assert.AreEqual(new DateOnly(2026, 10, 31), statement.FromDate);
|
||||
Assert.AreEqual(new DateOnly(2026, 11, 3), statement.ToDate);
|
||||
Assert.HasCount(3, statement.Movements);
|
||||
Assert.AreEqual(statement.ClosingBalance, statement.OpeningBalance + statement.Movements.Sum(m => m.Amount));
|
||||
|
||||
var first = statement.Movements[0];
|
||||
Assert.AreEqual(new DateOnly(2026, 11, 2), first.BookingDate);
|
||||
Assert.AreEqual(new DateOnly(2026, 11, 3), first.ValueDate);
|
||||
Assert.AreEqual(1220.50m, first.Amount);
|
||||
Assert.AreEqual("48", first.BankCode);
|
||||
Assert.AreEqual("CRO123456", first.Reference);
|
||||
Assert.AreEqual("BONIFICO A VOSTRO FAVORE DA CLIENTE UNO SPA SALDO FT 388", first.Description);
|
||||
|
||||
var second = statement.Movements[1];
|
||||
Assert.AreEqual(-12.50m, second.Amount);
|
||||
Assert.AreEqual("COMMISSIONI", second.Description);
|
||||
Assert.IsNull(second.Reference);
|
||||
|
||||
// The amount with the comma as some banks write it.
|
||||
Assert.AreEqual(-0.50m, statement.Movements[2].Amount);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_LinesWithoutLeadingSpace_AndWithoutLineBreaks()
|
||||
{
|
||||
var trimmed = string.Join("\n", Sample().Select(l => l[1..]));
|
||||
Assert.HasCount(3, Read(trimmed).Movements);
|
||||
|
||||
var stream = string.Concat(Sample());
|
||||
var statement = Read(stream);
|
||||
Assert.HasCount(3, statement.Movements);
|
||||
Assert.AreEqual(2207.50m, statement.ClosingBalance);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Recognizes_TheRhHeader_WithOrWithoutLeadingSpace()
|
||||
{
|
||||
var lines = Sample();
|
||||
Assert.IsTrue(Reader.Recognizes(Encoding.ASCII.GetBytes(string.Join("\r\n", lines))));
|
||||
Assert.IsTrue(Reader.Recognizes(Encoding.ASCII.GetBytes("\r\n" + string.Join("\r\n", lines.Select(l => l[1..])))));
|
||||
Assert.IsTrue(Reader.Recognizes(Encoding.ASCII.GetBytes(string.Concat(lines))));
|
||||
Assert.IsFalse(Reader.Recognizes(Encoding.ASCII.GetBytes(" RH short\r\n")));
|
||||
Assert.IsFalse(Reader.Recognizes(Encoding.ASCII.GetBytes("Data;Descrizione;Importo\r\n")));
|
||||
Assert.IsFalse(Reader.Recognizes(Encoding.ASCII.GetBytes(" IB" + new string(' ', 117))));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Read_Errors_AreBankFileExceptions()
|
||||
{
|
||||
var lines = Sample();
|
||||
Assert.ThrowsExactly<BankFileException>(() => Read(string.Join("\r\n", lines.Skip(1))));
|
||||
|
||||
var badSign = lines.ToArray();
|
||||
badSign[2] = Put(badSign[2], 26, "X");
|
||||
Assert.ThrowsExactly<BankFileException>(() => Read(string.Join("\r\n", badSign)));
|
||||
|
||||
var badAmount = lines.ToArray();
|
||||
badAmount[2] = Put(badAmount[2], 27, "00000ABC0000000");
|
||||
Assert.ThrowsExactly<BankFileException>(() => Read(string.Join("\r\n", badAmount)));
|
||||
|
||||
var badDate = lines.ToArray();
|
||||
badDate[2] = Put(badDate[2], 20, "321326");
|
||||
Assert.ThrowsExactly<BankFileException>(() => Read(string.Join("\r\n", badDate)));
|
||||
|
||||
var orphan = lines.ToList();
|
||||
orphan.Insert(2, Record("63", (4, "0000001"), (11, "001"), (14, "ORFANA")));
|
||||
Assert.ThrowsExactly<BankFileException>(() => Read(string.Join("\r\n", orphan)));
|
||||
}
|
||||
|
||||
private static List<string> Sample() =>
|
||||
[
|
||||
Record("RH", (4, "05428"), (9, "A1B2C"), (14, "041126"), (20, "ESTRATTO-2026-11"), (114, "E")),
|
||||
Record(
|
||||
"61",
|
||||
(4, "0000001"),
|
||||
(52, "X"),
|
||||
(53, "05428"),
|
||||
(58, "11101"),
|
||||
(63, "000000123456"),
|
||||
(75, "EUR"),
|
||||
(78, "311026"),
|
||||
(84, "C"),
|
||||
(85, "000000000100000"),
|
||||
(100, "IT"),
|
||||
(102, "60")),
|
||||
Record(
|
||||
"62",
|
||||
(4, "0000001"),
|
||||
(11, "001"),
|
||||
(14, "031126"),
|
||||
(20, "021126"),
|
||||
(26, "C"),
|
||||
(27, "000000000122050"),
|
||||
(42, "48"),
|
||||
(44, "00"),
|
||||
(62, "CRO123456"),
|
||||
(87, "BONIFICO A VOSTRO FAVORE")),
|
||||
Record("63", (4, "0000001"), (11, "001"), (14, "DA CLIENTE UNO SPA")),
|
||||
Record("63", (4, "0000001"), (11, "001"), (14, "SALDO FT 388")),
|
||||
Record("62", (4, "0000001"), (11, "002"), (14, "031126"), (20, "031126"), (26, "D"), (27, "000000000001250"), (42, "26"), (87, "COMMISSIONI")),
|
||||
Record("62", (4, "0000001"), (11, "003"), (14, "031126"), (20, "031126"), (26, "D"), (27, " 0,50"), (42, "26"), (87, "BOLLO")),
|
||||
Record("64", (4, "0000001"), (11, "EUR"), (14, "031126"), (20, "C"), (21, "000000000220750"), (36, "C"), (37, "000000000220750")),
|
||||
Record("EF", (4, "05428"), (9, "A1B2C"), (14, "041126"), (20, "ESTRATTO-2026-11"), (46, "0000001"), (83, "0000009"), (114, "E")),
|
||||
];
|
||||
|
||||
private static string Record(string type, params (int Position, string Value)[] fields)
|
||||
{
|
||||
var line = " " + type + new string(' ', 117);
|
||||
foreach (var (position, value) in fields)
|
||||
{
|
||||
line = Put(line, position, value);
|
||||
}
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
private static string Put(string line, int position, string value) =>
|
||||
line[..(position - 1)] + value + line[(position - 1 + value.Length)..];
|
||||
|
||||
private static StatementFile Read(string text)
|
||||
{
|
||||
using var stream = new MemoryStream(Encoding.Latin1.GetBytes(text));
|
||||
return Reader.Read(stream);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
using System.Text;
|
||||
using Khaemhat.Core.Treasury;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy.Tests;
|
||||
|
||||
/// <summary>Bank receipts in the CBI fixed-width layout (issue #70): record lengths, order, positions and totals.</summary>
|
||||
[TestClass]
|
||||
public sealed class RibaCbiWriterTests
|
||||
{
|
||||
private static readonly RibaCbiWriter Writer = new();
|
||||
|
||||
private static readonly BankFileCompany Company = new(
|
||||
"Officine Bàlbo S.r.l.",
|
||||
"01234567890",
|
||||
"Via Roma 1",
|
||||
"10121",
|
||||
"Torino",
|
||||
"TO",
|
||||
"IT",
|
||||
"IT60X0542811101000000123456",
|
||||
null,
|
||||
"a1b2c",
|
||||
null,
|
||||
null);
|
||||
|
||||
[TestMethod]
|
||||
public void Supports_OnlyRiba()
|
||||
{
|
||||
Assert.IsTrue(Writer.Supports(RemittanceKind.Riba));
|
||||
Assert.IsFalse(Writer.Supports(RemittanceKind.SddCore));
|
||||
Assert.IsFalse(Writer.Supports(RemittanceKind.SepaCreditTransfer));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Write_EveryRecordIs120Characters_InTheCbiOrder()
|
||||
{
|
||||
var file = Writer.Write(Remittance());
|
||||
|
||||
Assert.AreEqual("RIBA_RB-2026-11.txt", file.FileName);
|
||||
Assert.AreEqual("text/plain", file.ContentType);
|
||||
var text = Encoding.ASCII.GetString(file.Content);
|
||||
Assert.IsTrue(text.EndsWith("\r\n", StringComparison.Ordinal));
|
||||
Assert.IsTrue(file.Content.All(b => b < 128));
|
||||
var lines = Lines(file);
|
||||
Assert.IsTrue(lines.All(l => l.Length == 120), string.Join("\n", lines.Where(l => l.Length != 120)));
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { "IB", "14", "20", "30", "40", "50", "51", "70", "14", "20", "30", "40", "50", "51", "70", "EF" },
|
||||
lines.Select(l => l[1..3]).ToArray());
|
||||
Assert.IsTrue(lines.All(l => l[0] == ' '));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Write_HeaderAndReceipt_HaveTheValuesAtTheirPositions()
|
||||
{
|
||||
var lines = Lines(Writer.Write(Remittance()));
|
||||
|
||||
var header = lines[0];
|
||||
Assert.AreEqual("A1B2C", At(header, 4, 8));
|
||||
Assert.AreEqual("05428", At(header, 9, 13));
|
||||
Assert.AreEqual("131126", At(header, 14, 19));
|
||||
Assert.AreEqual("RB-2026-11 ", At(header, 20, 39));
|
||||
Assert.AreEqual("E", At(header, 114, 114));
|
||||
|
||||
var receipt = lines[1];
|
||||
Assert.AreEqual("0000001", At(receipt, 4, 10));
|
||||
Assert.AreEqual("311226", At(receipt, 23, 28));
|
||||
Assert.AreEqual("30000", At(receipt, 29, 33));
|
||||
Assert.AreEqual("0000000122050", At(receipt, 34, 46));
|
||||
Assert.AreEqual("-", At(receipt, 47, 47));
|
||||
Assert.AreEqual("05428", At(receipt, 48, 52));
|
||||
Assert.AreEqual("11101", At(receipt, 53, 57));
|
||||
Assert.AreEqual("000000123456", At(receipt, 58, 69));
|
||||
Assert.AreEqual("02008", At(receipt, 70, 74));
|
||||
Assert.AreEqual("01600", At(receipt, 75, 79));
|
||||
Assert.AreEqual("A1B2C", At(receipt, 92, 96));
|
||||
Assert.AreEqual("4", At(receipt, 97, 97));
|
||||
Assert.AreEqual("C0001 ", At(receipt, 98, 113));
|
||||
Assert.AreEqual("E", At(receipt, 120, 120));
|
||||
|
||||
var creditor = lines[2];
|
||||
Assert.AreEqual("OFFICINE BALBO S.R.L. ", At(creditor, 11, 34));
|
||||
Assert.AreEqual("VIA ROMA 1", At(creditor, 35, 58).TrimEnd());
|
||||
Assert.AreEqual("10121 TORINO TO", At(creditor, 59, 82).TrimEnd());
|
||||
Assert.AreEqual("01234567890", At(creditor, 83, 106).TrimEnd());
|
||||
|
||||
var debtor = lines[3];
|
||||
Assert.AreEqual("CITTA DI MONDOVI SOCIETA COOPE", At(debtor, 11, 40));
|
||||
Assert.AreEqual("RATIVA", At(debtor, 41, 70).TrimEnd());
|
||||
Assert.AreEqual("RSSMRA80A01H501U", At(debtor, 71, 86));
|
||||
|
||||
var address = lines[4];
|
||||
Assert.AreEqual("PIAZZA MAGGIORE 3", At(address, 11, 40).TrimEnd());
|
||||
Assert.AreEqual("12084", At(address, 41, 45));
|
||||
Assert.AreEqual("MONDOVI", At(address, 46, 67).TrimEnd());
|
||||
Assert.AreEqual("CN", At(address, 69, 70));
|
||||
Assert.AreEqual("UNICREDIT AG. 2", At(address, 71, 120).TrimEnd());
|
||||
|
||||
var reference = lines[5];
|
||||
Assert.AreEqual("FT 2026/000388 DEL 31/08/2026", At(reference, 11, 50).TrimEnd());
|
||||
Assert.AreEqual("01234567890", At(reference, 101, 116).TrimEnd());
|
||||
|
||||
var number = lines[6];
|
||||
Assert.AreEqual("0000000007", At(number, 11, 20));
|
||||
Assert.AreEqual("OFFICINE BALBO S.R.L", At(number, 21, 40));
|
||||
|
||||
Assert.AreEqual("0000001", At(lines[7], 4, 10));
|
||||
Assert.AreEqual(string.Empty, At(lines[7], 11, 120).Trim());
|
||||
Assert.AreEqual("0000002", At(lines[8], 4, 10));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Write_Footer_CountsReceiptsRecordsAndTotal()
|
||||
{
|
||||
var footer = Lines(Writer.Write(Remittance()))[^1];
|
||||
|
||||
Assert.AreEqual("EF", At(footer, 2, 3));
|
||||
Assert.AreEqual("A1B2C", At(footer, 4, 8));
|
||||
Assert.AreEqual("05428", At(footer, 9, 13));
|
||||
Assert.AreEqual("131126", At(footer, 14, 19));
|
||||
Assert.AreEqual("RB-2026-11", At(footer, 20, 39).TrimEnd());
|
||||
Assert.AreEqual("0000002", At(footer, 46, 52));
|
||||
Assert.AreEqual("000000000132050", At(footer, 53, 67));
|
||||
Assert.AreEqual("000000000000000", At(footer, 68, 82));
|
||||
Assert.AreEqual("0000016", At(footer, 83, 89));
|
||||
Assert.AreEqual("E", At(footer, 114, 114));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Write_Errors_AreBankFileExceptions()
|
||||
{
|
||||
var remittance = Remittance();
|
||||
var item = remittance.Items[0];
|
||||
|
||||
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Company = Company with { SiaCode = null } }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Company = Company with { SiaCode = "123" } }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Company = Company with { Iban = "DE89370400440532013000" } }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Company = Company with { Iban = "IT61X0542811101000000123456" } }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Items = [item with { Iban = null }] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Items = [item with { Iban = "DE89370400440532013000" }] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Items = [item with { Amount = 0m }] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Items = [item with { Amount = 100_000_000_000m }] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Items = [] }));
|
||||
Assert.ThrowsExactly<BankFileException>(() => Writer.Write(remittance with { Kind = RemittanceKind.SddCore }));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Text_IsUpperCaseAsciiPaddedOrCut()
|
||||
{
|
||||
Assert.AreEqual("PERCHE CITTA ", RibaCbiWriter.Text("perché città", 14));
|
||||
Assert.AreEqual("ABC", RibaCbiWriter.Text("abcdef", 3));
|
||||
Assert.AreEqual("A B ", RibaCbiWriter.Text("a€b", 4));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Pack_ExposesTheRemittanceWriterAndTheStatementReader()
|
||||
{
|
||||
var pack = new ItalyFiscalPack();
|
||||
|
||||
Assert.IsTrue(pack.Require<IRemittanceFileWriter>().Supports(RemittanceKind.Riba));
|
||||
Assert.AreEqual(StatementFormat.Cbi, pack.Require<IBankStatementReader>().Format);
|
||||
}
|
||||
|
||||
private static BankFileRemittance Remittance() => new(
|
||||
RemittanceKind.Riba,
|
||||
"RB-2026-11",
|
||||
new DateTime(2026, 11, 13, 9, 0, 0, DateTimeKind.Local),
|
||||
new DateOnly(2026, 11, 13),
|
||||
Company,
|
||||
[
|
||||
new BankFileItem(
|
||||
7, "C0001", "Città di Mondovì Società Cooperativa", "RSSMRA80A01H501U", "Piazza Maggiore 3", "12084", "Mondovì", "CN", "IT",
|
||||
"IT63A0200801600000101234567", null, "UniCredit Ag. 2", 1220.50m, new DateOnly(2026, 12, 31), "FT 2026/000388 del 31/08/2026", "E1"),
|
||||
new BankFileItem(
|
||||
8, "C0002", "Bianchi Snc", "01234567897", "Via Po 2", "20121", "Milano", "MI", "IT",
|
||||
"IT11B0503401633000000012345", null, "Banco BPM", 100m, new DateOnly(2027, 1, 31), "FT 2026/000401", "E2"),
|
||||
]);
|
||||
|
||||
private static string[] Lines(BankFile file) =>
|
||||
Encoding.ASCII.GetString(file.Content).Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
private static string At(string line, int from, int to) => line[(from - 1)..to];
|
||||
}
|
||||
Reference in new issue
Block a user