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

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

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

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

No files matched your search

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