Files
Khaemhat/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaWriterTests.cs
T
Alby96andClaude Opus 5.5 709bb13532 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>
2026-11-13 11:51:31 +01:00

336 lines
18 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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);
}
}