diff --git a/src/Khaemhat.Core/Treasury/Camt053Reader.cs b/src/Khaemhat.Core/Treasury/Camt053Reader.cs new file mode 100644 index 0000000..11f4bd7 --- /dev/null +++ b/src/Khaemhat.Core/Treasury/Camt053Reader.cs @@ -0,0 +1,270 @@ +using System.Globalization; +using System.Text; +using System.Xml; +using System.Xml.Linq; + +namespace Khaemhat.Core.Treasury; + +/// +/// Reads ISO 20022 bank to customer statements (camt.053.001.xx, any version): the elements are found by their +/// local names, so the version of the namespace does not matter. +/// +/// +/// +/// account: Stmt/Acct/Id/IBAN and Stmt/Acct/Ccy (or the currency of the first amount); +/// balances: OPBD (or PRCD) as opening, CLBD as closing, negative when CdtDbtInd is DBIT; +/// period: FrToDt, otherwise the first and last booking dates; +/// each Ntry: amount signed by CdtDbtInd, BookgDt, ValDt, AcctSvcrRef or the +/// end-to-end id as reference, BkTxCd as bank code (Domn/Fmly/SubFmly or the proprietary code), the +/// description from AddtlNtryInf or the unstructured remittance information, the counterparty from +/// RltdPties (the debtor of a credit, the creditor of a debit); +/// entries with status PDNG or INFO are not booked and are skipped. +/// +/// When a file has several Stmt of the same account their entries are read in order; balances come from the first +/// opening and the last closing. +/// +public static class Camt053Reader +{ + /// Whether the start of a file looks like a camt.053 statement. + /// The first bytes of the file. + /// when the head is XML naming camt.053 or BkToCstmrStmt. + public static bool Recognizes(ReadOnlySpan 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)); + } + + /// Reads a statement. + /// The file. + /// The statement. + /// The file is not a readable camt.053 statement. + 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(); + 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() + .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()); + } + + 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 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)); +} diff --git a/src/Khaemhat.Core/Treasury/CsvStatementReader.cs b/src/Khaemhat.Core/Treasury/CsvStatementReader.cs new file mode 100644 index 0000000..2767c21 --- /dev/null +++ b/src/Khaemhat.Core/Treasury/CsvStatementReader.cs @@ -0,0 +1,400 @@ +using System.Globalization; +using System.Text; + +namespace Khaemhat.Core.Treasury; + +/// +/// Reads the CSV exports of home banking with a , and guesses the layout from the header +/// row of the common Italian and English exports. +/// +/// +/// +/// The file is UTF-8 (with or without BOM); when it is not valid UTF-8 it is read as Windows-1252. +/// Fields may be quoted, with doubled quotes inside; quoted fields may span lines. +/// Empty rows and the 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. +/// Numbers may carry a leading or trailing sign and the currency (€, EUR); the debit column is read as +/// money out whatever its sign. +/// +/// +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"]; + + /// Reads a statement. + /// The file. + /// Its columns. + /// The statement: no account, currency or balances, the period from the booking dates. + /// A row cannot be read; the message names it. + 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(); + 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); + } + + /// + /// Guesses the layout from the header row: the separator (;, tab or ,) 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 dd/MM/yyyy (the reader also tries the other common day-first formats). + /// + /// The first row of the file. + /// The layout with one header row, or when a date, a description or an amount column is missing. + 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); + } + + /// Reads a number as the bank writes it. + /// The text, such as -1.234,56, 1.234,56-, +12,00 €. + /// Whether the decimal separator is the comma. + /// The number, or for an empty field. + /// The text is not a number. + 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(); + 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 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)); +} diff --git a/src/Khaemhat.Core/Treasury/SepaXmlWriter.cs b/src/Khaemhat.Core/Treasury/SepaXmlWriter.cs new file mode 100644 index 0000000..db8be94 --- /dev/null +++ b/src/Khaemhat.Core/Treasury/SepaXmlWriter.cs @@ -0,0 +1,515 @@ +using System.Globalization; +using System.Text; +using System.Xml; +using Khaemhat.Core.Validation; + +namespace Khaemhat.Core.Treasury; + +/// +/// Writes SEPA remittances as ISO 20022 customer initiation messages, within the subset of the EPC rulebooks (2023): +/// credit transfers to suppliers as pain.001.001.09 and direct debits as pain.008.001.08. +/// +/// +/// +/// Every text is reduced to the SEPA Latin character set (a-z A-Z 0-9 / - ? : ( ) . , ' + 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. +/// +/// +/// When the company has a CBI CUC code it goes in GrpHdr/InitgPty/Id/OrgId/Othr with issuer CBI, as +/// Italian banks require. A bank without a known BIC is written as FinInstnId/Othr/Id NOTPROVIDED. +/// +/// +public static class SepaXmlWriter +{ + /// The namespace of credit transfer initiations. + public const string CreditTransferNamespace = "urn:iso:std:iso:20022:tech:xsd:pain.001.001.09"; + + /// The namespace of direct debit initiations. + public const string DirectDebitNamespace = "urn:iso:std:iso:20022:tech:xsd:pain.008.001.08"; + + /// The media type of the files. + 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"; + + /// Writes a remittance of SEPA credit transfers (pain.001.001.09). + /// The remittance, of kind . + /// The file SCT_<MsgId>.xml. + /// The remittance cannot be written as SEPA credit transfers. + 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); + } + + /// + /// Writes a remittance of SEPA direct debits (pain.008.001.08), with one payment information block for each + /// sequence and collection date. + /// + /// The remittance, of kind or . + /// The file SDD_<MsgId>.xml. + /// The remittance cannot be written as SEPA direct debits. + 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); + } + + /// + /// A text in the SEPA Latin character set: accents removed, other characters replaced by spaces, spaces collapsed, + /// cut to a length. + /// + /// The text. + /// The maximum length. + /// The text, possibly empty. + 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 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 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); +} diff --git a/src/Khaemhat.Fiscal.Italy/CbiStatementReader.cs b/src/Khaemhat.Fiscal.Italy/CbiStatementReader.cs new file mode 100644 index 0000000..d58f970 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/CbiStatementReader.cs @@ -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; + +/// +/// Reads the CBI current account statement (rendicontazione movimenti di conto corrente, flow RH): records of +/// 120 characters, the RH header, the opening balance 61, each movement 62 with its description +/// lines 63, the closing balance 64 and the EF footer. +/// +/// +/// 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 (credit, money in) and D (debit, money out); dates are DDMMYY. +/// +/// RecordPositions read +/// RH4-8 sender ABI; 9-13 receiver SIA; 14-19 creation date; 20-39 support name. +/// 614-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. +/// 624-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. +/// 634-10 progressive; 11-13 movement number; 14-120 more description, appended to the +/// movement before. +/// 644-10 progressive; 11-13 currency; 14-19 date of the closing balance; 20 sign; 21-35 +/// closing (book) balance. +/// EFend of the flow; nothing is read. +/// +/// 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. +/// +public sealed class CbiStatementReader : IBankStatementReader +{ + private const int RecordLength = 120; + + /// + public StatementFormat Format => StatementFormat.Cbi; + + /// + public bool Recognizes(ReadOnlySpan 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); + } + + /// + 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(); + 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); +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs index 9cb07d6..692e41e 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -28,6 +28,8 @@ public sealed class ItalyFiscalPack : FiscalPackBase AddFeature(new ItalianLedgerTemplate()); AddFeature(new VatSettlementRulesIt()); AddFeature(new LipeWriter()); + AddFeature(new RibaCbiWriter()); + AddFeature(new CbiStatementReader()); // ABI and CAB are read from every Italian IBAN; bank names and BICs arrive with the ABI list (ADR 0026). AddFeature(new ItalianBankDirectory([])); diff --git a/src/Khaemhat.Fiscal.Italy/RibaCbiWriter.cs b/src/Khaemhat.Fiscal.Italy/RibaCbiWriter.cs new file mode 100644 index 0000000..5062930 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/RibaCbiWriter.cs @@ -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; + +/// +/// Writes a remittance of bank receipts (ricevute bancarie) in the CBI fixed-width layout "Ricevute bancarie": records +/// of 120 characters separated by CRLF, the IB header, for each receipt the records 14, 20, +/// 30, 40, 50, 51, 70, and the EF footer. Texts are upper case ASCII (accents +/// dropped) padded with spaces, numbers are zero padded, dates are DDMMYY and amounts are in cents. +/// +/// +/// 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. +/// +/// RecordPositions +/// IB4-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 E. +/// 144-10 progressive; 23-28 due date; 29-33 causale 30000; 34-46 amount in cents; +/// 47 sign -; 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 4; 98-113 debtor code; 120 currency E. +/// 204-10 progressive; 11-34 creditor name; 35-58 street; 59-82 postal code, town and +/// province; 83-106 VAT number or tax code. +/// 304-10 progressive; 11-40 and 41-70 debtor name; 71-86 debtor tax code. +/// 404-10 progressive; 11-40 debtor street; 41-45 postal code; 46-67 town; 69-70 province; +/// 71-120 debtor bank and branch. +/// 504-10 progressive; 11-50 and 51-90 reference (the invoices paid); 101-116 creditor +/// tax code. +/// 514-10 progressive; 11-20 receipt number; 21-40 creditor name. +/// 704-10 progressive (closing record of the receipt). +/// EF4-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 E. +/// +/// +public sealed class RibaCbiWriter : IRemittanceFileWriter +{ + /// The length of every record. + public const int RecordLength = 120; + + /// The media type of the file. + public const string ContentType = "text/plain"; + + private const long MaximumItemCents = 9_999_999_999_999L; + private const long MaximumTotalCents = 999_999_999_999_999L; + + /// + public bool Supports(RemittanceKind kind) => kind == RemittanceKind.Riba; + + /// + 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(); + 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)); + } + + /// + /// 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. + /// + /// The text. + /// The length of the field. + /// The field, exactly characters. + 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); + } +} diff --git a/tests/Khaemhat.Core.Tests/Khaemhat.Core.Tests.csproj b/tests/Khaemhat.Core.Tests/Khaemhat.Core.Tests.csproj index b07fb57..bd9f648 100644 --- a/tests/Khaemhat.Core.Tests/Khaemhat.Core.Tests.csproj +++ b/tests/Khaemhat.Core.Tests/Khaemhat.Core.Tests.csproj @@ -8,4 +8,9 @@ + + + + + diff --git a/tests/Khaemhat.Core.Tests/Treasury/Camt053ReaderTests.cs b/tests/Khaemhat.Core.Tests/Treasury/Camt053ReaderTests.cs new file mode 100644 index 0000000..19b8c0a --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Treasury/Camt053ReaderTests.cs @@ -0,0 +1,185 @@ +using System.Text; +using Khaemhat.Core.Treasury; + +namespace Khaemhat.Core.Tests.Treasury; + +/// ISO 20022 camt.053 statements (issue #71), read whatever the version of the namespace. +[TestClass] +public sealed class Camt053ReaderTests +{ + private const string Sample = """ + + + + STMT-12026-11-01T06:00:00 + + 2026-10 + 2026-11-01T06:00:00 + 2026-10-01T00:00:002026-10-31T23:59:59 + IT60X0542811101000000123456EUR + + OPBD + 1000.00CRDT
2026-09-30
+
+ + CLBD + 1950.50CRDT
2026-10-31
+
+ + 1220.00CRDTBOOK +
2026-10-05
2026-10-06
+ CRO-0001 + PMNTRCDTESCT + + E2E-AAA + + Cliente Uno S.p.A. + IT63A0200801600000101234567 + + Saldo FT 2026/388e FT 2026/390 + +
+ + 30.50CRDTBOOK + 2026-10-10T10:15:00+02:00 + 48 + E2E-BBB + Bonifico da + Cliente Due + + + 300.00DBITBOOK +
2026-10-20
2026-10-20
+ + + Officine Balbo + Fornitore Tre + DE89 3704 0044 0532 0130 00 + + Pagamento fattura 77 + +
+ + 9.99DBITPDNG +
2026-10-31
+
+
+
+
+ """; + + // The 2009 version: plain status, parties without Pty, PRCD as opening, no period. + private const string Version02 = """ + + + + OLD2026-11-01T06:00:00 + + 1 + IT60X0542811101000000123456 + PRCD50.00DBIT
2026-10-31
+ CLBD150.00CRDT
2026-11-03
+ + 200.00CRDTBOOK +
2026-11-02
+ Cliente Vecchio + Accredito +
+ + 1.00CRDTBOOK +
2026-11-03
+
+
+
+
+ """; + + [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(""))); + } + + [TestMethod] + public void Read_RefusesBrokenOrForeignXml_AndDtds() + { + Assert.ThrowsExactly(() => Read("")); + Assert.ThrowsExactly(() => Read("")); + Assert.ThrowsExactly(() => Read("]>")); + Assert.ThrowsExactly(() => Read(Sample.Replace("30.50", "abc", StringComparison.Ordinal))); + } + + [TestMethod] + public void Read_TwoStatementsOfTwoAccounts_IsRefused() + { + var stmt = Sample[Sample.IndexOf("", StringComparison.Ordinal)..(Sample.IndexOf("", StringComparison.Ordinal) + 7)]; + var other = stmt.Replace("IT60X0542811101000000123456", "DE89370400440532013000", StringComparison.Ordinal); + + Assert.ThrowsExactly(() => Read(Sample.Replace("", "" + other, StringComparison.Ordinal))); + } + + private static StatementFile Read(string xml) + { + using var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)); + return Camt053Reader.Read(stream); + } +} diff --git a/tests/Khaemhat.Core.Tests/Treasury/CsvStatementReaderTests.cs b/tests/Khaemhat.Core.Tests/Treasury/CsvStatementReaderTests.cs new file mode 100644 index 0000000..cd0a1a6 --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Treasury/CsvStatementReaderTests.cs @@ -0,0 +1,184 @@ +using System.Text; +using Khaemhat.Core.Treasury; + +namespace Khaemhat.Core.Tests.Treasury; + +/// CSV exports of home banking (issue #71): layouts, Italian numbers, encodings and the guess of the layout. +[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(() => 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(() => Read("h\n01/10/2026;;a;uno;\n", SignedLayout)); + StringAssert.Contains(badAmount.Message, "Row 2"); + + var noAmount = Assert.ThrowsExactly(() => Read("h\n01/10/2026;;a;;\n", SignedLayout)); + StringAssert.Contains(noAmount.Message, "Row 2"); + + Assert.ThrowsExactly(() => 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(() => 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); + } +} diff --git a/tests/Khaemhat.Core.Tests/Treasury/Schemas/pain.001.001.09.xsd b/tests/Khaemhat.Core.Tests/Treasury/Schemas/pain.001.001.09.xsd new file mode 100644 index 0000000..cfbb599 --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Treasury/Schemas/pain.001.001.09.xsd @@ -0,0 +1,368 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Khaemhat.Core.Tests/Treasury/Schemas/pain.008.001.08.xsd b/tests/Khaemhat.Core.Tests/Treasury/Schemas/pain.008.001.08.xsd new file mode 100644 index 0000000..71ca93b --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Treasury/Schemas/pain.008.001.08.xsd @@ -0,0 +1,385 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Khaemhat.Core.Tests/Treasury/SepaXmlWriterTests.cs b/tests/Khaemhat.Core.Tests/Treasury/SepaXmlWriterTests.cs new file mode 100644 index 0000000..e7d2a03 --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Treasury/SepaXmlWriterTests.cs @@ -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; + +/// +/// SEPA credit transfers (pain.001.001.09) and direct debits (pain.008.001.08), issues #70 and #71: the +/// files validate against the schemas, totals and counts, the character set, the grouping of debits and the errors. +/// +[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("TRF", "DD", StringComparison.Ordinal), + transfer.Replace("IT60X", "it60x", StringComparison.Ordinal), + transfer.Replace(">1000.00<", ">1000.001234<", StringComparison.Ordinal), + transfer.Replace("SLEV", string.Empty, StringComparison.Ordinal).Replace("", "SLEV", 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("FRST", "FIRST", StringComparison.Ordinal)), + "pain.008.001.08.xsd", + SepaXmlWriter.DirectDebitNamespace)); + Assert.IsNotEmpty(Validate( + Encoding.UTF8.GetBytes(debit.Replace("MND-001", "" + new string('M', 36) + "", 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), ""); + } + + [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(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [] })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Amount = 0m }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Amount = -5m }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Amount = 0.004m }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Company = Company with { Iban = "" } })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Company = Company with { Iban = "IT61X0542811101000000123456" } })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Iban = null }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Iban = "DE89370400440532013001" }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Items = [transfer with { Bic = "NOT A BIC" }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Kind = RemittanceKind.SddCore })); + Assert.ThrowsExactly(() => SepaXmlWriter.CreditTransfer(transfers with { Kind = RemittanceKind.Riba })); + + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Items = [] })); + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Company = Company with { CreditorId = null } })); + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { MandateId = " " }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { MandateDate = null }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { Amount = 0m }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Items = [debit with { Iban = "" }] })); + Assert.ThrowsExactly(() => SepaXmlWriter.DirectDebit(debits with { Kind = RemittanceKind.SepaCreditTransfer })); + Assert.ThrowsExactly(() => 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 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(); + 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; + } +} diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/CbiStatementReaderTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/CbiStatementReaderTests.cs new file mode 100644 index 0000000..a162c4f --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/CbiStatementReaderTests.cs @@ -0,0 +1,147 @@ +using System.Text; +using Khaemhat.Core.Treasury; + +namespace Khaemhat.Fiscal.Italy.Tests; + +/// The CBI current account statement (issue #71): balances, movements and their description lines. +[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(() => Read(string.Join("\r\n", lines.Skip(1)))); + + var badSign = lines.ToArray(); + badSign[2] = Put(badSign[2], 26, "X"); + Assert.ThrowsExactly(() => Read(string.Join("\r\n", badSign))); + + var badAmount = lines.ToArray(); + badAmount[2] = Put(badAmount[2], 27, "00000ABC0000000"); + Assert.ThrowsExactly(() => Read(string.Join("\r\n", badAmount))); + + var badDate = lines.ToArray(); + badDate[2] = Put(badDate[2], 20, "321326"); + Assert.ThrowsExactly(() => Read(string.Join("\r\n", badDate))); + + var orphan = lines.ToList(); + orphan.Insert(2, Record("63", (4, "0000001"), (11, "001"), (14, "ORFANA"))); + Assert.ThrowsExactly(() => Read(string.Join("\r\n", orphan))); + } + + private static List 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); + } +} diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/RibaCbiWriterTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/RibaCbiWriterTests.cs new file mode 100644 index 0000000..ecd2af6 --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/RibaCbiWriterTests.cs @@ -0,0 +1,183 @@ +using System.Text; +using Khaemhat.Core.Treasury; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy.Tests; + +/// Bank receipts in the CBI fixed-width layout (issue #70): record lengths, order, positions and totals. +[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(() => Writer.Write(remittance with { Company = Company with { SiaCode = null } })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Company = Company with { SiaCode = "123" } })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Company = Company with { Iban = "DE89370400440532013000" } })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Company = Company with { Iban = "IT61X0542811101000000123456" } })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Items = [item with { Iban = null }] })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Items = [item with { Iban = "DE89370400440532013000" }] })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Items = [item with { Amount = 0m }] })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Items = [item with { Amount = 100_000_000_000m }] })); + Assert.ThrowsExactly(() => Writer.Write(remittance with { Items = [] })); + Assert.ThrowsExactly(() => 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().Supports(RemittanceKind.Riba)); + Assert.AreEqual(StatementFormat.Cbi, pack.Require().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]; +}