feat: FatturaPA writer, validator, SDI receipts and transport channels (#74 #75 #76 #77)

The Italian pack can now produce and check the e-invoice and talk to the SDI:
- FatturaPaWriter writes FPR12/FPA12 v1.2 with SDI file naming; FatturaPaValidator
  checks it against an embedded schema and the AdE semantic rules (official codes).
- SdiReceiptReader reads RC, NS, MC, NE, DT, AT, MT and SE notifications.
- The incoming-invoice model becomes the shared EInvoice* model, read and written.
- In-house ImapClient and MimeParser (no external libraries) back the PEC channel;
  SdICoop (SOAP/MTOM with client certificate) and two generic REST intermediaries
  sit behind the same IEInvoiceTransport contract, with fake-server tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-13 11:51:31 +01:00
1 parent 0debd82983
commit 709bb13532
26 files changed
+5916 -243

No files matched your search

@@ -159,7 +159,7 @@ public sealed class FatturaPaReaderTests
<DatiRiepilogo><AliquotaIVA>22.00</AliquotaIVA><ImponibileImporto>100.00</ImponibileImporto><Imposta>22.00</Imposta><EsigibilitaIVA>I</EsigibilitaIVA></DatiRiepilogo>
""";
private static IncomingInvoiceFile Read(string xml, string fileName = FileName) => Reader.Read(fileName, Encoding.UTF8.GetBytes(xml));
private static EInvoiceFile Read(string xml, string fileName = FileName) => Reader.Read(fileName, Encoding.UTF8.GetBytes(xml));
[TestMethod]
public void Read_OrdinaryInvoice_ReadsHeaderPartiesAndTransmission()
@@ -209,14 +209,14 @@ public sealed class FatturaPaReaderTests
Assert.IsNull(invoice.Rounding);
CollectionAssert.AreEqual(new[] { "Fornitura di marzo", "Consegna in cantiere" }, invoice.Causals.ToArray());
Assert.IsFalse(invoice.Art73);
Assert.AreEqual(new IncomingDiscount(false, 2.00m, null), invoice.Discounts[0]);
Assert.AreEqual(new IncomingDiscount(true, null, 1.50m), invoice.Discounts[1]);
Assert.AreEqual(new EInvoiceDiscount(false, 2.00m, null), invoice.Discounts[0]);
Assert.AreEqual(new EInvoiceDiscount(true, null, 1.50m), invoice.Discounts[1]);
Assert.HasCount(3, invoice.Lines);
var bolts = invoice.Lines[0];
Assert.AreEqual(1, bolts.Number);
Assert.AreEqual(new IncomingItemCode("SKU", "B-M8-ZN"), bolts.Codes[0]);
Assert.AreEqual(new IncomingItemCode("EAN", "8001234567895"), bolts.Codes[1]);
Assert.AreEqual(new EInvoiceItemCode("SKU", "B-M8-ZN"), bolts.Codes[0]);
Assert.AreEqual(new EInvoiceItemCode("EAN", "8001234567895"), bolts.Codes[1]);
Assert.AreEqual("Bulloni M8 zincati", bolts.Description);
Assert.AreEqual(100m, bolts.Quantity);
Assert.AreEqual("PZ", bolts.Unit);
@@ -224,7 +224,7 @@ public sealed class FatturaPaReaderTests
Assert.AreEqual(45m, bolts.TotalPrice);
Assert.AreEqual(22m, bolts.TaxRate);
Assert.IsNull(bolts.Nature);
Assert.AreEqual(new IncomingDiscount(false, 10m, null), bolts.Discounts.Single());
Assert.AreEqual(new EInvoiceDiscount(false, 10m, null), bolts.Discounts.Single());
Assert.IsFalse(bolts.Withheld);
Assert.AreEqual(4m, invoice.Lines[1].TaxRate);
@@ -238,13 +238,13 @@ public sealed class FatturaPaReaderTests
Assert.AreEqual("CC-12", contribution.AdministrativeReference);
Assert.HasCount(3, invoice.TaxSummary);
Assert.AreEqual(new IncomingTaxSummary(22m, null, 45m, 9.90m, "I", null, null, null), invoice.TaxSummary[0]);
Assert.AreEqual(new EInvoiceTaxSummary(22m, null, 45m, 9.90m, "I", null, null, null), invoice.TaxSummary[0]);
Assert.AreEqual(4m, invoice.TaxSummary[1].Rate);
Assert.AreEqual("N2.2", invoice.TaxSummary[2].Nature);
Assert.AreEqual("Non soggetto art. 15 DPR 633/72", invoice.TaxSummary[2].LegalReference);
Assert.HasCount(2, invoice.Payments);
Assert.AreEqual(new IncomingPayment("TP01", "MP05", new DateOnly(2026, 4, 30), 58.45m, "IT60X0542811101000000123456", null, null), invoice.Payments[0]);
Assert.AreEqual(new EInvoicePayment("TP01", "MP05", new DateOnly(2026, 4, 30), 58.45m, "IT60X0542811101000000123456", null, null), invoice.Payments[0]);
Assert.AreEqual("BPMOIT22XXX", invoice.Payments[1].Bic);
Assert.AreEqual("Ferramenta Piemontese S.r.l.", invoice.Payments[1].Beneficiary);
Assert.IsEmpty(invoice.Attachments);
@@ -377,9 +377,9 @@ public sealed class FatturaPaReaderTests
Assert.AreEqual("Giulia", file.Supplier.FirstName);
Assert.AreEqual("Bianchi", file.Supplier.LastName);
Assert.AreEqual("Giulia Bianchi", file.Supplier.DisplayName);
Assert.AreEqual(new IncomingWithholding("RT01", 208m, 20m, "A"), invoice.Withholdings.Single());
Assert.AreEqual(new IncomingStampDuty(true, 2m), invoice.StampDuty);
Assert.AreEqual(new IncomingSocialSecurity("TC01", 4m, 40m, 1000m, 22m, true, null), invoice.SocialSecurity.Single());
Assert.AreEqual(new EInvoiceWithholding("RT01", 208m, 20m, "A"), invoice.Withholdings.Single());
Assert.AreEqual(new EInvoiceStampDuty(true, 2m), invoice.StampDuty);
Assert.AreEqual(new EInvoiceSocialSecurity("TC01", 4m, 40m, 1000m, 22m, true, null), invoice.SocialSecurity.Single());
Assert.AreEqual(1270.88m, invoice.Total);
Assert.AreEqual(0.01m, invoice.Rounding);
Assert.IsTrue(invoice.Art73);
@@ -0,0 +1,335 @@
using System.Text;
using System.Xml.Linq;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy.Tests;
/// <summary>
/// The writer and the validator of FatturaPA (issue #74): every file written is valid against the schema, reads back to
/// the same content and passes the checks of the exchange system; each check is shown failing on a broken invoice.
/// The parties are fictitious, with VAT numbers that only pass the check digit.
/// </summary>
[TestClass]
public sealed class FatturaPaWriterTests
{
private static readonly FatturaPaWriter Writer = new();
private static readonly FatturaPaValidator Validator = new();
private static readonly FatturaPaReader Reader = new();
/// <summary>The company: an Italian limited company in the companies register.</summary>
public static EInvoiceParty Company { get; } = new(
"IT", "01234567897", "01234567897", "Khaemhat Demo S.r.l.", null, null,
"Via dei Granai", "57", "10121", "Torino", "TO", "IT", "RF01", "amministrazione@demo.example", "011 555 1234", "TO", "123456")
{
ShareCapital = 10_000m,
Shareholders = "SU",
LiquidationStatus = "LN",
};
/// <summary>A business customer.</summary>
public static EInvoiceParty Customer { get; } = new(
"IT", "09876543217", null, "Officine Esempio S.p.A.", null, null,
"Corso Milano", "4", "20121", "Milano", "MI", "IT", null, null, null, null, null);
/// <summary>An invoice with two rates, a discount, a delivery note and two installments.</summary>
/// <returns>The file.</returns>
public static EInvoiceFile Invoice() => new(
"IT01234567897_00001.xml", "FPR12", "00001", "ABC1234", Company, Customer,
[
new EInvoiceBody(
"TD01", "EUR", new DateOnly(2026, 10, 9), "FT/2026/000414", 1_311.62m, null,
["Fornitura di ottobre"], false, [], null, [], [],
[new EInvoiceReference("ORD-77", new DateOnly(2026, 9, 30), [], null, null)], [], [],
[new EInvoiceReference("DDT/2026/88", new DateOnly(2026, 10, 2), [1, 2], null, null)],
[
new EInvoiceLine(1, [new EInvoiceItemCode("INTERNO", "VIT-08")], "Viti autofilettanti 8 mm", 100m, "PZ", 0.85m, 80.75m, 22m, null,
[new EInvoiceDiscount(false, 5m, null)], false, null, null, null, null),
new EInvoiceLine(2, [], "Trapano a percussione", 2m, "PZ", 489.50m, 979m, 22m, null, [], false, null, null, null, null),
new EInvoiceLine(3, [], "Manuale tecnico", 1m, "PZ", 18m, 18m, 4m, null, [], false, null, null, null, null),
],
[
new EInvoiceTaxSummary(22m, null, 1_059.75m, 233.15m, "I", null, null, null),
new EInvoiceTaxSummary(4m, null, 18m, 0.72m, "I", null, null, null),
],
[
new EInvoicePayment("TP01", "MP05", new DateOnly(2026, 11, 30), 655.81m, "IT60X0542811101000000123456", null, null),
new EInvoicePayment("TP01", "MP05", new DateOnly(2026, 12, 31), 655.81m, "IT60X0542811101000000123456", null, null),
],
[]),
],
null, [])
{
TransmitterCountry = "IT",
TransmitterId = "01234567897",
};
[TestMethod]
public void FileName_UsesTheTransmitterAndAFiveCharacterBase36Progressive()
{
Assert.AreEqual("IT01234567897_00001.xml", Writer.FileName("IT", "01234567897", 1));
Assert.AreEqual("00010", Writer.Progressive(36));
Assert.AreEqual("0000Z", Writer.Progressive(35));
Assert.AreEqual("ZZZZZ", Writer.Progressive(60_466_175));
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => Writer.Progressive(0));
}
[TestMethod]
public void Write_Invoice_IsValidAgainstTheSchemaAndPassesTheChecks()
{
var file = Invoice();
Assert.IsEmpty(Validator.Validate(file).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList());
var xml = Writer.Write(file);
var problems = Validator.ValidateXml(xml);
Assert.IsEmpty(problems, string.Join("\n", problems.Select(p => p.Path + ": " + p.Message)));
}
[TestMethod]
public void Write_Invoice_ReadsBackToTheSameContent()
{
var file = Invoice();
var read = Reader.Read(file.FileName, Writer.Write(file));
Assert.AreEqual("FPR12", read.TransmissionFormat);
Assert.AreEqual("ABC1234", read.RecipientCode);
Assert.AreEqual("01234567897", read.TransmitterId);
Assert.AreEqual("Khaemhat Demo S.r.l.", read.Supplier.Name);
Assert.AreEqual(10_000m, read.Supplier.ShareCapital);
Assert.AreEqual("SU", read.Supplier.Shareholders);
Assert.AreEqual("0115551234", read.Supplier.Phone);
var body = read.Invoices.Single();
Assert.AreEqual("FT/2026/000414", body.Number);
Assert.AreEqual(1_311.62m, body.Total);
Assert.HasCount(3, body.Lines);
Assert.AreEqual(80.75m, body.Lines[0].TotalPrice);
Assert.AreEqual(5m, body.Lines[0].Discounts.Single().Percent);
Assert.AreEqual("VIT-08", body.Lines[0].Codes.Single().Value);
Assert.HasCount(2, body.TaxSummary);
Assert.AreEqual("DDT/2026/88", body.DeliveryNotes.Single().Id);
CollectionAssert.AreEqual(new[] { 1, 2 }, body.DeliveryNotes.Single().LineNumbers.ToArray());
Assert.AreEqual("ORD-77", body.Orders.Single().Id);
Assert.HasCount(2, body.Payments);
Assert.AreEqual("TP01", body.PaymentConditions);
}
[TestMethod]
public void Write_RootIsQualifiedAndChildrenAreNot()
{
var root = XDocument.Parse(Encoding.UTF8.GetString(Writer.Write(Invoice()))).Root!;
Assert.AreEqual(FatturaPaWriter.Namespace, root.Name.NamespaceName);
Assert.AreEqual("FPR12", root.Attribute("versione")!.Value);
Assert.IsTrue(root.Elements().All(e => e.Name.NamespaceName.Length == 0));
}
[TestMethod]
public void Write_ProfessionalFee_WithWithholdingFundStampAndNature()
{
var professional = Company with { TaxRegime = "RF19" };
var body = new EInvoiceBody(
"TD06", "EUR", new DateOnly(2026, 10, 12), "P/2026/7", 1_286.80m, null, [], false,
[new EInvoiceWithholding("RT01", 200m, 20m, "A")], new EInvoiceStampDuty(true, 2m),
[new EInvoiceSocialSecurity("TC04", 4m, 40m, 1_000m, 22m, false, null)], [], [], [], [], [],
[
new EInvoiceLine(1, [], "Consulenza tecnica di ottobre", null, null, 1_000m, 1_000m, 22m, null, [], true, null, null, null, null),
new EInvoiceLine(2, [], "Diritti di segreteria anticipati", null, null, 16m, 16m, 0m, "N1", [], false, null, null, null, null),
],
[
new EInvoiceTaxSummary(22m, null, 1_040m, 228.80m, "I", null, null, null),
new EInvoiceTaxSummary(0m, "N1", 16m, 0m, null, "Art. 15 DPR 633/72", null, null),
],
[new EInvoicePayment("TP02", "MP05", null, 1_086.80m, null, null, null)],
[new EInvoiceAttachment("cortesia.pdf", "PDF", "Copia di cortesia", Encoding.ASCII.GetBytes("%PDF-1.4"))]);
var file = Invoice() with { Supplier = professional, Invoices = [body] };
var errors = Validator.Validate(file).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList();
Assert.IsEmpty(errors, string.Join("\n", errors));
var xml = Writer.Write(file);
Assert.IsEmpty(Validator.ValidateXml(xml));
var read = Reader.Read(file.FileName, xml).Invoices.Single();
Assert.AreEqual(200m, read.Withholdings.Single().Amount);
Assert.AreEqual("TC04", read.SocialSecurity.Single().Fund);
Assert.AreEqual(2m, read.StampDuty!.Amount);
Assert.IsTrue(read.Lines[0].Withheld);
Assert.AreEqual("N1", read.Lines[1].Nature);
Assert.AreEqual("%PDF-1.4", Encoding.ASCII.GetString(read.Attachments.Single().Content));
}
[TestMethod]
public void Write_PublicAdministration_SplitPaymentWithCigCupAndIntentData()
{
var administration = Customer with { VatNumber = null, TaxCode = "80012345676", Name = "Comune di Esempio" };
var line = new EInvoiceLine(1, [], "Manutenzione impianto", 1m, null, 1_000m, 1_000m, 22m, null, [], false, null, null, null, "UFF-12")
{
OtherData = [new EInvoiceOtherData("INTENTO", "26012345678901-000001", null, new DateOnly(2026, 1, 8))],
};
var body = new EInvoiceBody(
"TD01", "EUR", new DateOnly(2026, 9, 30), "FT/2026/390", 1_220m, null, [], false, [], null, [], [],
[new EInvoiceReference("DET-2026-15", new DateOnly(2026, 6, 1), [], "ZAB1234567", "J51B26000010007")], [], [], [],
[line],
[new EInvoiceTaxSummary(22m, null, 1_000m, 220m, "S", null, null, null)],
[new EInvoicePayment("TP02", "MP05", new DateOnly(2026, 10, 30), 1_000m, "IT60X0542811101000000123456", null, null)],
[]);
var file = Invoice() with { TransmissionFormat = "FPA12", RecipientCode = "UFE7GH", Customer = administration, Invoices = [body] };
Assert.IsEmpty(Validator.Validate(file).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList());
var xml = Writer.Write(file);
Assert.IsEmpty(Validator.ValidateXml(xml));
var read = Reader.Read(file.FileName, xml);
Assert.AreEqual("FPA12", read.TransmissionFormat);
Assert.AreEqual("ZAB1234567", read.Invoices[0].Orders.Single().Cig);
Assert.AreEqual("J51B26000010007", read.Invoices[0].Orders.Single().Cup);
Assert.AreEqual("S", read.Invoices[0].TaxSummary.Single().Exigibility);
Assert.AreEqual("INTENTO", read.Invoices[0].Lines[0].OtherData.Single().Type);
Assert.AreEqual("UFF-12", read.Invoices[0].Lines[0].AdministrativeReference);
}
[TestMethod]
public void Write_ForeignCustomerAndConsumerWithPec()
{
var foreign = Customer with { CountryCode = "DE", VatNumber = "DE123456789", Country = "DE", PostalCode = "80331", Province = null, City = "München", Name = "Alpenbau GmbH" };
var file = Invoice() with { RecipientCode = "XXXXXXX", Customer = foreign };
var xml = Writer.Write(file);
Assert.IsEmpty(Validator.ValidateXml(xml));
var read = Reader.Read(file.FileName, xml);
Assert.AreEqual("00000", read.Customer.PostalCode);
Assert.IsNull(read.Customer.Province);
Assert.AreEqual("München", read.Customer.City);
var consumer = new EInvoiceParty("IT", null, "RSSMRA80A01H501U", null, "Mario", "Rossi", "Via Po", "1", "10124", "Torino", "TO", "IT", null, null, null, null, null);
var toConsumer = Invoice() with { RecipientCode = "0000000", RecipientPec = "mario.rossi@pec.example.it", Customer = consumer };
Assert.IsEmpty(Validator.Validate(toConsumer).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList());
var consumerXml = Writer.Write(toConsumer);
Assert.IsEmpty(Validator.ValidateXml(consumerXml));
Assert.AreEqual("mario.rossi@pec.example.it", Reader.Read(toConsumer.FileName, consumerXml).RecipientPec);
}
[TestMethod]
public void Write_TextOutsideLatin1_IsReplacedAndCut()
{
Assert.AreEqual("Viti 'speciali' - EUR 5...", FatturaPaWriter.Text("Viti ‘speciali’ — € 5…", 100));
Assert.AreEqual("abc", FatturaPaWriter.Text("abcdef", 3));
Assert.AreEqual("a ? b", FatturaPaWriter.Text("a 漢 b", 10));
var line = Invoice().Invoices[0].Lines[2] with { Description = "Manuale “tecnico” – ed. 2026 ✓" };
var body = Invoice().Invoices[0] with { Lines = [.. Invoice().Invoices[0].Lines.Take(2), line] };
Assert.IsEmpty(Validator.ValidateXml(Writer.Write(Invoice() with { Invoices = [body] })));
}
[TestMethod]
public void Write_LongCausal_IsSplitIntoFieldsOf200Characters()
{
var note = string.Join(' ', Enumerable.Repeat("Consegna al magazzino di via dei Granai.", 12));
var body = Invoice().Invoices[0] with { Causals = [note] };
var root = XDocument.Parse(Encoding.UTF8.GetString(Writer.Write(Invoice() with { Invoices = [body] }))).Root!;
var causals = root.Descendants("Causale").Select(c => c.Value).ToList();
Assert.IsGreaterThan(1, causals.Count);
Assert.IsTrue(causals.All(c => c.Length <= 200));
Assert.AreEqual(note.Replace(" ", string.Empty, StringComparison.Ordinal), string.Concat(causals).Replace(" ", string.Empty, StringComparison.Ordinal));
}
[TestMethod]
public void Validate_WrongLineTotal_Gives00423()
{
var body = Invoice().Invoices[0];
var wrong = body with { Lines = [body.Lines[0] with { TotalPrice = 85m }, body.Lines[1], body.Lines[2]] };
var problems = Validator.Validate(Invoice() with { Invoices = [wrong] });
Assert.IsTrue(problems.Any(p => p.Code == "00423" && p.Path.Contains("DettaglioLinee[1]", StringComparison.Ordinal)));
}
[TestMethod]
public void Validate_NatureRules_Give00400_00401_00445_00429()
{
var body = Invoice().Invoices[0];
var noNature = body with { Lines = [.. body.Lines.Take(2), body.Lines[2] with { TaxRate = 0m }] };
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [noNature] }).Any(p => p.Code == "00400"));
var natureWithRate = body with { Lines = [.. body.Lines.Take(2), body.Lines[2] with { Nature = "N4" }] };
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [natureWithRate] }).Any(p => p.Code == "00401"));
var generic = body with
{
Lines = [.. body.Lines.Take(2), body.Lines[2] with { TaxRate = 0m, Nature = "N2" }],
TaxSummary = [body.TaxSummary[0], new EInvoiceTaxSummary(0m, "N2", 18m, 0m, null, "Art. 7", null, null)],
};
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [generic] }).Any(p => p.Code == "00445"));
var summaryWithout = body with { TaxSummary = [body.TaxSummary[0], new EInvoiceTaxSummary(0m, null, 18m, 0m, null, null, null, null)] };
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [summaryWithout] }).Any(p => p.Code == "00429"));
}
[TestMethod]
public void Validate_SummaryRules_Give00419_00421_00422()
{
var body = Invoice().Invoices[0];
var missing = body with { TaxSummary = [body.TaxSummary[0]] };
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [missing] }).Any(p => p.Code == "00419"));
var wrongTax = body with { TaxSummary = [body.TaxSummary[0] with { Tax = 230m }, body.TaxSummary[1]] };
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [wrongTax] }).Any(p => p.Code == "00421"));
var wrongTaxable = body with { TaxSummary = [body.TaxSummary[0] with { Taxable = 1_070m, Tax = 235.40m }, body.TaxSummary[1]] };
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [wrongTaxable] }).Any(p => p.Code == "00422"));
}
[TestMethod]
public void Validate_RecipientAndCustomerRules()
{
Assert.IsTrue(Validator.Validate(Invoice() with { RecipientCode = "ABC123" }).Any(p => p.Code == "00427"));
Assert.IsTrue(Validator.Validate(Invoice() with { TransmissionFormat = "FPA12" }).Any(p => p.Code == "00427"));
Assert.IsTrue(Validator.Validate(Invoice() with { RecipientPec = "a@pec.example.it" }).Any(p => p.Code == "00426"));
Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Customer with { VatNumber = null, TaxCode = null } }).Any(p => p.Code == "00417"));
Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Customer with { VatNumber = "09876543210" } }).Any(p => p.Code == "00305"));
Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Customer with { TaxCode = "RSSMRA80A01H501X" } }).Any(p => p.Code == "00306"));
Assert.IsTrue(Validator.Validate(Invoice() with { TransmitterId = null }).Any(p => p.Code == "einvoice.transmitter"));
}
[TestMethod]
public void Validate_SelfInvoiceRules_Give00471_00472_00473()
{
var body = Invoice().Invoices[0];
Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Company }).Any(p => p.Code == "00471"));
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [body with { DocumentType = "TD27" }] }).Any(p => p.Code == "00472"));
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [body with { DocumentType = "TD17" }] }).Any(p => p.Code == "00473"));
}
[TestMethod]
public void Validate_WithholdingLinesWithoutData_Give00411()
{
var body = Invoice().Invoices[0];
var withheld = body with { Lines = [body.Lines[0] with { Withheld = true }, body.Lines[1], body.Lines[2]] };
Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [withheld] }).Any(p => p.Code == "00411"));
}
[TestMethod]
public void Validate_ExemptOverThresholdWithoutStamp_IsAWarning()
{
var body = Invoice().Invoices[0] with
{
Lines = [new EInvoiceLine(1, [], "Servizio esente", 1m, null, 100m, 100m, 0m, "N4", [], false, null, null, null, null)],
TaxSummary = [new EInvoiceTaxSummary(0m, "N4", 100m, 0m, null, "Art. 10 DPR 633/72", null, null)],
};
var problem = Validator.Validate(Invoice() with { Invoices = [body] }).Single(p => p.Code == "einvoice.stamp-duty");
Assert.AreEqual(EInvoiceProblemSeverity.Warning, problem.Severity);
}
[TestMethod]
public void ValidateXml_BrokenFile_ReportsSchemaErrors()
{
var xml = Encoding.UTF8.GetString(Writer.Write(Invoice())).Replace("<Divisa>EUR</Divisa>", "<Divisa>EURO</Divisa>", StringComparison.Ordinal);
var problems = Validator.ValidateXml(Encoding.UTF8.GetBytes(xml));
Assert.IsTrue(problems.Any(p => p.Code == "einvoice.xml.schema"));
Assert.AreEqual("einvoice.xml.malformed", Validator.ValidateXml(Encoding.UTF8.GetBytes("<p:FatturaElettronica")).Single().Code);
}
}
@@ -11,6 +11,8 @@
<!-- The builder of signed envelopes is shared with the CMS tests: the p7m files are made in the test, never downloaded. -->
<ItemGroup>
<Compile Include="../Khaemhat.Infrastructure.Tests/Security/CmsTestSigner.cs" Link="Shared/CmsTestSigner.cs" />
<Compile Include="../Khaemhat.Infrastructure.Tests/Mail/FakeMailServers.cs" Link="Shared/FakeMailServers.cs" />
<Compile Include="../Khaemhat.Infrastructure.Tests/Mail/PecSamples.cs" Link="Shared/PecSamples.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,102 @@
using System.Text;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy.Tests;
/// <summary>The notifications of the SDI (issue #75), written here in the layout of <c>MessaggiTypes</c> v1.0.</summary>
[TestClass]
public sealed class SdiReceiptReaderTests
{
private const string Ns = "http://www.fatturapa.gov.it/sdi/messaggi/v1.0";
private static readonly SdiReceiptReader Reader = new();
/// <summary>A notification as the SDI writes it.</summary>
/// <param name="root">The root element.</param>
/// <param name="body">The children.</param>
/// <returns>The file.</returns>
public static byte[] Notification(string root, string body) => Encoding.UTF8.GetBytes(
$"""<?xml version="1.0" encoding="UTF-8"?><types:{root} xmlns:types="{Ns}" versione="1.0">{body}<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"/></types:{root}>""");
[TestMethod]
public void Read_DeliveryReceipt()
{
var content = Notification("RicevutaConsegna", """
<IdentificativoSdI>111222333</IdentificativoSdI><NomeFile>IT01234567897_00001.xml</NomeFile><Hash>abc</Hash>
<DataOraRicezione>2026-10-12T15:40:10.000+02:00</DataOraRicezione><DataOraConsegna>2026-10-12T15:41:00.000+02:00</DataOraConsegna>
<Destinatario><Codice>ABC1234</Codice><Descrizione>Officine</Descrizione></Destinatario><MessageId>9001</MessageId>
""");
var receipt = Reader.Read("IT01234567897_00001_RC_001.xml", content);
Assert.AreEqual(EInvoiceReceiptKind.Delivered, receipt.Kind);
Assert.AreEqual("RC", receipt.Code);
Assert.AreEqual("IT01234567897_00001.xml", receipt.InvoiceFileName);
Assert.AreEqual("111222333", receipt.ExchangeId);
Assert.AreEqual(new DateTimeOffset(2026, 10, 12, 15, 41, 0, TimeSpan.FromHours(2)), receipt.DeliveredAt);
Assert.AreEqual("9001", receipt.MessageId);
}
[TestMethod]
public void Read_Rejection_ListsTheErrors()
{
var content = Notification("NotificaScarto", """
<IdentificativoSdI>111222334</IdentificativoSdI><NomeFile>IT01234567897_00002.xml</NomeFile>
<DataOraRicezione>2026-10-09T10:00:00</DataOraRicezione>
<ListaErrori>
<Errore><Codice>00311</Codice><Descrizione>1.1.4 CodiceDestinatario non valido</Descrizione></Errore>
<Errore><Codice>00423</Codice><Descrizione>2.2.1.11 PrezzoTotale non calcolato correttamente</Descrizione><Suggerimento>Verificare</Suggerimento></Errore>
</ListaErrori><MessageId>9002</MessageId>
""");
var receipt = Reader.Read("IT01234567897_00002_NS_001.xml", content);
Assert.AreEqual(EInvoiceReceiptKind.Rejected, receipt.Kind);
Assert.HasCount(2, receipt.Errors);
Assert.AreEqual("00311", receipt.Errors[0].Code);
Assert.AreEqual("Verificare", receipt.Errors[1].Hint);
}
[TestMethod]
public void Read_OutcomeOfAnAdministration()
{
var content = Notification("NotificaEsito", """
<IdentificativoSdI>555</IdentificativoSdI><NomeFile>IT01234567897_00003.xml</NomeFile>
<EsitoCommittente><IdentificativoSdI>555</IdentificativoSdI><Esito>EC02</Esito><Descrizione>CIG errato</Descrizione></EsitoCommittente>
<MessageId>9003</MessageId>
""");
var receipt = Reader.Read("IT01234567897_00003_NE_001.xml", content);
Assert.AreEqual(EInvoiceReceiptKind.Outcome, receipt.Kind);
Assert.AreEqual("EC02", receipt.Outcome);
Assert.IsTrue(receipt.Refused);
Assert.AreEqual("CIG errato", receipt.Description);
}
[TestMethod]
[DataRow("NotificaMancataConsegna", "MC", EInvoiceReceiptKind.NotDelivered)]
[DataRow("NotificaDecorrenzaTermini", "DT", EInvoiceReceiptKind.TermsElapsed)]
[DataRow("AttestazioneTrasmissioneFattura", "AT", EInvoiceReceiptKind.Undeliverable)]
[DataRow("FileMetadati", "MT", EInvoiceReceiptKind.Metadata)]
public void Read_OtherNotifications(string root, string code, EInvoiceReceiptKind kind)
{
var content = Notification(root, "<IdentificativoSdI>777</IdentificativoSdI><NomeFile>IT09876543217_0A1B2.xml.p7m</NomeFile><CodiceDestinatario>ABC1234</CodiceDestinatario><MessageId>1</MessageId>");
var receipt = Reader.Read("anything.xml", content);
Assert.AreEqual(kind, receipt.Kind);
Assert.AreEqual(code, receipt.Code);
Assert.AreEqual("777", receipt.ExchangeId);
Assert.AreEqual("IT09876543217_0A1B2.xml.p7m", receipt.InvoiceFileName);
}
[TestMethod]
public void IsReceipt_ByNameOrRoot_AndNotForInvoices()
{
Assert.IsTrue(Reader.IsReceipt("IT01234567897_00001_NS_001.xml", []));
Assert.IsTrue(Reader.IsReceipt("x.xml", Notification("RicevutaConsegna", string.Empty)));
Assert.IsFalse(Reader.IsReceipt("IT01234567897_00001.xml", Encoding.UTF8.GetBytes("<p:FatturaElettronica/>")));
Assert.AreEqual("MT", SdiReceiptReader.CodeOfName("IT09876543217_0A1B2_MT_001.xml"));
Assert.ThrowsExactly<IncomingInvoiceException>(() => Reader.Read("a.xml", Encoding.UTF8.GetBytes("<FatturaElettronica/>")));
}
}
@@ -0,0 +1,345 @@
using System.Collections.Concurrent;
using System.Net;
using System.Text;
using System.Text.Json;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Fiscal.Italy.Sdi;
using Khaemhat.Infrastructure.Mail;
using Khaemhat.Infrastructure.Tests.Mail;
namespace Khaemhat.Fiscal.Italy.Tests;
[TestClass]
public sealed class PecSdiTransportTests
{
private const string Mailbox = "fatture@pec.example.it";
private const string Secret = "test-secret";
public TestContext TestContext { get; set; } = null!;
private static EInvoiceChannelSettings Settings(FakeSmtpServer? smtp, FakeImapServer? imap, string? archive = null, string? exchange = null) => new()
{
Code = PecSdiTransport.ChannelCode,
Mailbox = Mailbox,
SmtpHost = "127.0.0.1",
SmtpPort = smtp?.Port ?? 1,
ImapHost = "127.0.0.1",
ImapPort = imap?.Port ?? 1,
Tls = false,
User = Mailbox,
Password = Secret,
ArchiveFolder = archive,
ExchangeAddress = exchange,
};
[TestMethod]
public async Task First_file_goes_to_sdi01_then_to_the_assigned_address()
{
await using var smtp = new FakeSmtpServer();
var transport = new PecSdiTransport();
var file = new EInvoiceOutgoing("IT01234567897_00001.xml", Encoding.UTF8.GetBytes("<p:FatturaElettronica/>"), "FT 1/2026");
var first = await transport.SendAsync(Settings(smtp, null), file, TestContext.CancellationToken);
var next = await transport.SendAsync(Settings(smtp, null, exchange: "sdi23@pec.fatturapa.it"), file, TestContext.CancellationToken);
Assert.IsTrue(first.Accepted, first.Error);
Assert.IsTrue(next.Accepted, next.Error);
var messages = smtp.Messages.ToList();
Assert.AreEqual("sdi01@pec.fatturapa.it", messages[0].To.Single());
Assert.AreEqual("sdi23@pec.fatturapa.it", messages[1].To.Single());
Assert.AreEqual(Mailbox, messages[0].From);
var sent = MimeParser.Parse(messages[0].Content);
var attachment = sent.Attachments().Single();
Assert.AreEqual("IT01234567897_00001.xml", attachment.FileName);
CollectionAssert.AreEqual(file.Content, attachment.Body);
}
[TestMethod]
public async Task Refused_recipient_is_reported_not_thrown()
{
await using var smtp = new FakeSmtpServer { RejectRecipient = "550 Mailbox unavailable" };
var result = await new PecSdiTransport().SendAsync(Settings(smtp, null), new EInvoiceOutgoing("a.xml", [1], null), TestContext.CancellationToken);
Assert.IsFalse(result.Accepted);
StringAssert.Contains(result.Error, "550");
}
[TestMethod]
public async Task Fetch_reads_only_the_sdi_and_learns_its_address()
{
var receipt = Encoding.UTF8.GetBytes("<ns:RicevutaConsegna xmlns:ns=\"x\"/>");
var invoice = Encoding.UTF8.GetBytes("<p:FatturaElettronica/>");
var metadata = Encoding.UTF8.GetBytes("<ns:FileMetadati xmlns:ns=\"x\"/>");
await using var imap = new FakeImapServer(Mailbox, Secret,
PecSamples.Envelope("sdi07@pec.fatturapa.it", "Ricevuta di consegna", ("IT01234567897_00001_RC_001.xml", receipt)),
PecSamples.Acceptance("Invio file IT01234567897_00002.xml"),
PecSamples.Envelope("sdi07@pec.fatturapa.it", "Invio File 99", ("IT09876543217_0A1B2.xml", invoice), ("IT09876543217_0A1B2_MT_001.xml", metadata)));
var transport = new PecSdiTransport();
var settings = Settings(null, imap, archive: "Khaemhat/SDI");
var result = await transport.FetchAsync(settings, TestContext.CancellationToken);
Assert.AreEqual(2, result.MessagesRead, "The acceptance of the provider is not a message of the SDI.");
CollectionAssert.AreEqual(
new[] { "IT01234567897_00001_RC_001.xml", "IT09876543217_0A1B2.xml", "IT09876543217_0A1B2_MT_001.xml" },
result.Files.Select(f => f.FileName).ToList());
Assert.AreEqual("sdi07@pec.fatturapa.it", result.ExchangeAddress);
Assert.AreEqual("sdi07@pec.fatturapa.it", result.Files[0].Sender);
CollectionAssert.AreEqual(receipt, result.Files[0].Content);
await transport.AcknowledgeAsync(settings, result.Files.Select(f => f.MessageKey).ToList(), TestContext.CancellationToken);
Assert.AreEqual(2, imap.Mailboxes["Khaemhat/SDI"].Count);
Assert.AreEqual(1, imap.Mailboxes["INBOX"].Count, "Only the acceptance of the provider is left.");
var again = await transport.FetchAsync(settings with { ExchangeAddress = "sdi07@pec.fatturapa.it" }, TestContext.CancellationToken);
Assert.AreEqual(0, again.Files.Count);
Assert.IsNull(again.ExchangeAddress, "The address did not change.");
}
[TestMethod]
public async Task Without_archive_messages_are_marked_as_read()
{
await using var imap = new FakeImapServer(Mailbox, Secret,
PecSamples.Envelope("sdi01@pec.fatturapa.it", "Scarto", ("IT01234567897_00003_NS_001.xml", [1, 2])));
var transport = new PecSdiTransport();
var settings = Settings(null, imap);
var first = await transport.FetchAsync(settings, TestContext.CancellationToken);
Assert.AreEqual(1, first.Files.Count);
Assert.AreEqual(1, (await transport.FetchAsync(settings, TestContext.CancellationToken)).Files.Count, "Not acknowledged: read again.");
await transport.AcknowledgeAsync(settings, [first.Files[0].MessageKey], TestContext.CancellationToken);
Assert.AreEqual(0, (await transport.FetchAsync(settings, TestContext.CancellationToken)).Files.Count);
Assert.IsTrue(imap.Mailboxes["INBOX"][0].Flags.Contains(@"\Seen"));
}
[TestMethod]
public async Task Check_reports_login_and_missing_settings()
{
await using var smtp = new FakeSmtpServer();
await using var imap = new FakeImapServer(Mailbox, Secret);
var transport = new PecSdiTransport();
var ok = await transport.CheckAsync(Settings(smtp, imap), TestContext.CancellationToken);
var wrong = await transport.CheckAsync(Settings(smtp, imap) with { Password = "other" }, TestContext.CancellationToken);
var missing = await transport.CheckAsync(new EInvoiceChannelSettings { Code = "PEC" }, TestContext.CancellationToken);
Assert.IsTrue(ok.Success, ok.Message);
Assert.IsFalse(wrong.Success);
Assert.IsFalse(wrong.Message.Contains("other", StringComparison.Ordinal), "The password must not appear.");
Assert.IsFalse(missing.Success);
}
[TestMethod]
public void Sdi_addresses_are_recognised()
{
Assert.AreEqual("sdi07@pec.fatturapa.it", PecSdiTransport.SdiAddress("\"Per conto di: SDI07@pec.fatturapa.it\" <posta-certificata@x.it>"));
Assert.IsNull(PecSdiTransport.SdiAddress("info@fatturapa.it"));
}
}
/// <summary>An HTTP handler that answers from a function and keeps the requests (with their bodies).</summary>
internal sealed class StubHandler(Func<HttpRequestMessage, byte[], HttpResponseMessage> answer, ConcurrentQueue<(HttpRequestMessage Request, byte[] Body)> log) : HttpMessageHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var body = request.Content is null ? [] : await request.Content.ReadAsByteArrayAsync(cancellationToken);
log.Enqueue((request, body));
return answer(request, body);
}
}
[TestClass]
public sealed class SdiCoopTransportTests
{
public TestContext TestContext { get; set; } = null!;
private static HttpResponseMessage Soap(string body) => new(HttpStatusCode.OK)
{
Content = new StringContent(
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Body>" + body + "</soapenv:Body></soapenv:Envelope>",
Encoding.UTF8,
"text/xml"),
};
[TestMethod]
public async Task Send_posts_mtom_and_reads_the_identifier()
{
var log = new ConcurrentQueue<(HttpRequestMessage, byte[])>();
var transport = new SdiCoopTransport(_ => new StubHandler((_, _) => Soap(
"<ns2:rispostaSdIRiceviFile xmlns:ns2=\"http://www.fatturapa.gov.it/sdi/ws/trasmissione/v1.0/types\"><IdentificativoSdI>111222333</IdentificativoSdI><DataOraRicezione>2026-11-13T10:00:00.000+01:00</DataOraRicezione></ns2:rispostaSdIRiceviFile>"), log));
var content = Encoding.UTF8.GetBytes("<p:FatturaElettronica versione=\"FPR12\"/>");
var settings = new EInvoiceChannelSettings { Code = "SDICOOP", TestEnvironment = true };
var result = await transport.SendAsync(settings, new EInvoiceOutgoing("IT01234567897_00001.xml", content, null), TestContext.CancellationToken);
Assert.IsTrue(result.Accepted, result.Error);
Assert.AreEqual("111222333", result.ExchangeId);
var (request, body) = log.Single();
Assert.AreEqual(SdiCoopTransport.TestEndpoint, request.RequestUri!.ToString());
Assert.AreEqual("multipart/related", request.Content!.Headers.ContentType!.MediaType);
Assert.AreEqual("\"" + SdiCoopTransport.RiceviFileAction + "\"", request.Headers.GetValues("SOAPAction").Single());
// What the SDI would read: the envelope with the file put back in place of the reference.
var envelope = SdiCoopMessages.Envelope(request.Content.Headers.ContentType.ToString(), body)!;
Assert.AreEqual("IT01234567897_00001.xml", envelope.Descendants().Single(e => e.Name.LocalName == "NomeFile").Value);
CollectionAssert.AreEqual(content, Convert.FromBase64String(envelope.Descendants().Single(e => e.Name.LocalName == "File").Value));
}
[TestMethod]
public async Task Errors_of_the_service_are_reported()
{
var log = new ConcurrentQueue<(HttpRequestMessage, byte[])>();
var error = new SdiCoopTransport(_ => new StubHandler((_, _) => Soap("<r><Errore>EI03</Errore></r>"), log));
var fault = new SdiCoopTransport(_ => new StubHandler((_, _) => Soap("<soapenv:Fault><faultcode>x</faultcode><faultstring>Bad request</faultstring></soapenv:Fault>"), log));
var settings = new EInvoiceChannelSettings { Code = "SDICOOP" };
var file = new EInvoiceOutgoing("a.xml", [1], null);
var refused = await error.SendAsync(settings, file, TestContext.CancellationToken);
var faulted = await fault.SendAsync(settings, file, TestContext.CancellationToken);
var noCertificate = await new SdiCoopTransport().SendAsync(settings, file, TestContext.CancellationToken);
StringAssert.Contains(refused.Error, "EI03");
StringAssert.Contains(faulted.Error, "Bad request");
Assert.IsFalse(noCertificate.Accepted);
Assert.AreEqual(SdiCoopTransport.ProductionEndpoint, SdiCoopTransport.EndpointOf(settings));
}
[TestMethod]
public void Inbound_messages_are_read_inline_and_mtom()
{
var receipt = Convert.ToBase64String(Encoding.UTF8.GetBytes("<NotificaScarto/>"));
var inline = Encoding.UTF8.GetBytes(
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><t:fileSdI xmlns:t=\"http://www.fatturapa.gov.it/sdi/ws/trasmissione/v1.0/types\">" +
"<IdentificativoSdI>42</IdentificativoSdI><NomeFile>IT01234567897_00001_NS_001.xml</NomeFile><File>" + receipt + "</File></t:fileSdI></s:Body></s:Envelope>");
var notification = SdiCoopMessages.Read("text/xml; charset=utf-8", inline)!;
Assert.AreEqual("Notifica", notification.Operation);
Assert.AreEqual("42", notification.ExchangeId);
Assert.AreEqual("<NotificaScarto/>", Encoding.UTF8.GetString(notification.Files.Single().Content));
Assert.IsFalse(SdiCoopMessages.Answer(notification).Contains("ER01", StringComparison.Ordinal));
const string Boundary = "uuid:b1";
var mtom = Encoding.UTF8.GetBytes(
"--" + Boundary + "\r\nContent-Type: application/xop+xml; type=\"text/xml\"\r\nContent-ID: <root>\r\n\r\n" +
"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><t:fileSdIConMetadati xmlns:t=\"http://www.fatturapa.gov.it/sdi/ws/ricezione/v1.0/types\">" +
"<IdentificativoSdI>77</IdentificativoSdI><NomeFile>IT09876543217_0A1B2.xml.p7m</NomeFile><File><xop:Include xmlns:xop=\"http://www.w3.org/2004/08/xop/include\" href=\"cid:f1\"/></File>" +
"<NomeFileMetadati>IT09876543217_0A1B2_MT_001.xml</NomeFileMetadati><Metadati><xop:Include xmlns:xop=\"http://www.w3.org/2004/08/xop/include\" href=\"cid:f2\"/></Metadati>" +
"</t:fileSdIConMetadati></s:Body></s:Envelope>\r\n" +
"--" + Boundary + "\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\nContent-ID: <f1>\r\n\r\nP7M\r\n" +
"--" + Boundary + "\r\nContent-Type: application/octet-stream\r\nContent-ID: <f2>\r\n\r\n<FileMetadati/>\r\n" +
"--" + Boundary + "--\r\n");
var invoice = SdiCoopMessages.Read("multipart/related; type=\"application/xop+xml\"; boundary=\"" + Boundary + "\"", mtom)!;
Assert.AreEqual("RiceviFatture", invoice.Operation);
Assert.AreEqual("77", invoice.ExchangeId);
Assert.AreEqual("IT09876543217_0A1B2.xml.p7m", invoice.Files[0].FileName);
Assert.AreEqual("P7M", Encoding.UTF8.GetString(invoice.Files[0].Content));
Assert.AreEqual("<FileMetadati/>", Encoding.UTF8.GetString(invoice.Files[1].Content));
StringAssert.Contains(SdiCoopMessages.Answer(invoice), "<Esito>ER01</Esito>");
Assert.IsNull(SdiCoopMessages.Read("text/xml", Encoding.UTF8.GetBytes("<not-soap/>")));
StringAssert.Contains(SdiCoopMessages.Answer(null), "Fault");
}
}
[TestClass]
public sealed class IntermediaryTransportTests
{
public TestContext TestContext { get; set; } = null!;
private static HttpResponseMessage Json(object value, HttpStatusCode status = HttpStatusCode.OK) =>
new(status) { Content = new StringContent(JsonSerializer.Serialize(value), Encoding.UTF8, "application/json") };
[TestMethod]
public async Task Intermediary_a_sends_lists_and_acknowledges()
{
var log = new ConcurrentQueue<(HttpRequestMessage Request, byte[] Body)>();
var waiting = Convert.ToBase64String(Encoding.UTF8.GetBytes("<RicevutaConsegna/>"));
var transport = new IntermediaryATransport(_ => new StubHandler((request, _) => (request.Method.Method, request.RequestUri!.AbsolutePath) switch
{
("POST", "/v1/invoices") => Json(new { id = "up-1", sdiId = (string?)null }),
("GET", "/v1/files") => Json(new[] { new { id = "f-9", fileName = "IT01234567897_00001_RC_001.xml", content = waiting, receivedAt = "2026-11-13T09:00:00Z" } }),
("POST", "/v1/files/f-9/ack") => new HttpResponseMessage(HttpStatusCode.NoContent),
("GET", "/v1/status") => Json(new { ok = true }),
_ => new HttpResponseMessage(HttpStatusCode.NotFound),
}, log));
var settings = new EInvoiceChannelSettings { Code = "INTA", Endpoint = "https://int-a.example/v1/", ApiKey = "test-key" };
var sent = await transport.SendAsync(settings, new EInvoiceOutgoing("IT01234567897_00001.xml", [1, 2, 3], null), TestContext.CancellationToken);
var fetched = await transport.FetchAsync(settings, TestContext.CancellationToken);
await transport.AcknowledgeAsync(settings, [fetched.Files[0].MessageKey], TestContext.CancellationToken);
var check = await transport.CheckAsync(settings, TestContext.CancellationToken);
Assert.IsTrue(sent.Accepted, sent.Error);
Assert.AreEqual("up-1", sent.MessageId);
var post = log.First();
Assert.AreEqual("Bearer", post.Request.Headers.Authorization!.Scheme);
Assert.AreEqual("IT01234567897_00001.xml", post.Request.Headers.GetValues("X-File-Name").Single());
CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, post.Body);
Assert.AreEqual("IT01234567897_00001_RC_001.xml", fetched.Files.Single().FileName);
Assert.AreEqual("<RicevutaConsegna/>", Encoding.UTF8.GetString(fetched.Files[0].Content));
Assert.IsTrue(log.Any(l => l.Request.RequestUri!.AbsolutePath == "/v1/files/f-9/ack"));
Assert.IsTrue(check.Success, check.Message);
}
[TestMethod]
public async Task Intermediary_b_uses_basic_authentication_and_json()
{
var log = new ConcurrentQueue<(HttpRequestMessage Request, byte[] Body)>();
var transport = new IntermediaryBTransport(_ => new StubHandler((request, _) => (request.Method.Method, request.RequestUri!.AbsolutePath) switch
{
("POST", "/api/v1/send") => Json(new { uploadId = "u-5", identificativoSdi = "998877" }),
("GET", "/api/v1/inbox") => Json(new { items = new[] { new { key = "k1", name = "IT09876543217_0A1B2.xml", data = Convert.ToBase64String([9]), date = "2026-11-12" } } }),
("DELETE", "/api/v1/inbox/k1") => new HttpResponseMessage(HttpStatusCode.OK),
("GET", "/api/v1/ping") => new HttpResponseMessage(HttpStatusCode.Unauthorized),
_ => new HttpResponseMessage(HttpStatusCode.NotFound),
}, log));
var settings = new EInvoiceChannelSettings { Code = "INTB", Endpoint = "https://int-b.example", User = "azienda", Password = "test-secret" };
var sent = await transport.SendAsync(settings, new EInvoiceOutgoing("IT01234567897_00002.xml", [7], null), TestContext.CancellationToken);
var fetched = await transport.FetchAsync(settings, TestContext.CancellationToken);
await transport.AcknowledgeAsync(settings, ["k1"], TestContext.CancellationToken);
var check = await transport.CheckAsync(settings, TestContext.CancellationToken);
var missing = await transport.SendAsync(settings with { Password = null }, new EInvoiceOutgoing("a.xml", [1], null), TestContext.CancellationToken);
Assert.AreEqual("998877", sent.ExchangeId);
Assert.AreEqual("Basic", log.First().Request.Headers.Authorization!.Scheme);
using (var body = JsonDocument.Parse(log.First().Body))
{
Assert.AreEqual("IT01234567897_00002.xml", body.RootElement.GetProperty("fileName").GetString());
}
Assert.AreEqual("k1", fetched.Files.Single().MessageKey);
Assert.IsTrue(log.Any(l => l.Request.Method == HttpMethod.Delete));
Assert.IsFalse(check.Success);
Assert.IsFalse(missing.Accepted);
}
[TestMethod]
public async Task Refused_file_is_reported_with_the_message_of_the_api()
{
var log = new ConcurrentQueue<(HttpRequestMessage, byte[])>();
var transport = new IntermediaryATransport(_ => new StubHandler((_, _) => Json(new { error = "Invalid XML" }, HttpStatusCode.UnprocessableEntity), log));
var result = await transport.SendAsync(
new EInvoiceChannelSettings { Code = "INTA", Endpoint = "https://a.example", ApiKey = "k" }, new EInvoiceOutgoing("a.xml", [1], null), TestContext.CancellationToken);
Assert.IsFalse(result.Accepted);
Assert.AreEqual("422: Invalid XML", result.Error);
}
[TestMethod]
public void The_pack_offers_the_four_channels()
{
var channels = new ItalyFiscalPack().GetFeature<IEInvoiceChannels>()!;
CollectionAssert.AreEqual(new[] { "PEC", "SDICOOP", "INTA", "INTB" }, channels.All.Select(c => c.Code).ToList());
Assert.IsFalse(channels.Find("sdicoop")!.Transport.Polls);
Assert.IsNull(channels.Find("X"));
}
}