Files
Khaemhat/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs
T
Alby96andClaude Opus 5.5 9a40adecfe feat: read FatturaPA invoices and signed p7m files (#57)
The import of supplier e-invoices needs a reading layer that turns a
received file into plain records, whatever form the file arrives in.

- Fiscal.Abstractions: IIncomingInvoiceReader, an optional pack feature,
  with the IncomingInvoiceFile records and the incoming.* error codes the
  import service and screens build on.
- Infrastructure: CmsSignedData, a minimal CMS SignedData (CAdES .p7m)
  reader on System.Formats.Asn1, since System.Security.Cryptography.Pkcs
  is a separate package. It accepts DER, BER with indefinite lengths and
  chunked content, base64 text and nested envelopes; it checks the
  message digest and the RSA (PKCS#1, PSS) or ECDSA signature with the
  embedded certificate and reports signer, tax code, validity and signing
  time. No trust chain or revocation check: no trusted list offline.
- Fiscal.Italy: FatturaPaReader for FPR12/FPA12 v1.2.x and FSM10, matched
  by local name, DTD prohibited and no resolver, BOM/windows-1252/missing
  declaration tolerated, batches as one invoice per body, attachments
  decoded; registered in ItalyFiscalPack.
- Tests build every sample and signed envelope in code (AsnWriter and
  self-signed certificates), nothing downloaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:08:29 +01:00

518 lines
23 KiB
C#
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Globalization;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Infrastructure.Security;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// Reads the FatturaPA files received from suppliers (SPEC §11.9, issue #57): ordinary invoices v1.2.x
/// (<c>FPR12</c>, <c>FPA12</c>), simplified invoices (<c>FSM10</c>), plain <c>.xml</c> or signed CAdES <c>.p7m</c>
/// (binary or base64 text, also nested).
/// </summary>
/// <remarks>
/// <para>Elements are matched by local name, whatever the namespace or prefix (<c>p:</c>, <c>ns2:</c>, none). The XML
/// is read with DTDs prohibited and no resolver, so nothing external is ever loaded. A UTF-8 byte order mark, a
/// missing XML declaration, an ISO-8859-1 or windows-1252 declaration and leading whitespace are tolerated.</para>
/// <para>Amounts use the invariant culture (<c>.</c> separator) and dates <c>yyyy-MM-dd</c>. The reader does not
/// validate the file against the XSD nor recompute totals: it reports what the supplier wrote and rejects only files
/// without the data an import cannot do without (document type, date, number, prices and rates of the lines, the
/// rows of the tax summary, the amounts of withholdings and payments). A missing <c>Divisa</c> is read as
/// <c>EUR</c>; an attachment whose content is not valid base64 is kept with an empty content.</para>
/// <para>For signed files the signature is checked for integrity only (see <see cref="CmsSignedData"/>): no trust chain
/// and no revocation check.</para>
/// <para>Simplified invoices (<c>FSM10</c>): each <c>DatiBeniServizi</c> becomes a line with no quantity whose unit and
/// total price are <c>Importo</c> minus the tax, because there <c>Importo</c> includes the tax. The tax is
/// <c>DatiIVA/Imposta</c> or, when only the rate is given, the tax included in <c>Importo</c> at that rate; the rate is
/// <c>DatiIVA/Aliquota</c> or, when only the tax is given, derived from it. The tax summary groups the lines by rate and
/// nature, the total is the sum of <c>Importo</c> and <c>DatiFatturaRettificata</c> becomes the related invoice.</para>
/// </remarks>
public sealed class FatturaPaReader : IIncomingInvoiceReader
{
/// <summary>The largest file read, as for signed envelopes (50 MB).</summary>
public const int MaxSize = CmsSignedData.MaxSize;
/// <inheritdoc />
public bool CanRead(string fileName, ReadOnlySpan<byte> content) =>
!content.IsEmpty && (CmsSignedData.LooksLikeCms(content) || LooksLikeXml(content));
/// <inheritdoc />
public IncomingInvoiceFile Read(string fileName, byte[] content)
{
ArgumentNullException.ThrowIfNull(fileName);
ArgumentNullException.ThrowIfNull(content);
if (content.Length == 0)
{
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The file is empty.");
}
if (content.Length > MaxSize)
{
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, $"The file is larger than {MaxSize / (1024 * 1024)} MB.");
}
IncomingSignature? signature = null;
var xml = content;
if (!LooksLikeXml(content) && CmsSignedData.LooksLikeCms(content))
{
CmsContent envelope;
try
{
envelope = CmsSignedData.Read(content);
}
catch (CmsFormatException ex)
{
throw new IncomingInvoiceException(IncomingInvoiceErrors.SignatureBroken, "The content of the signed file cannot be extracted: " + ex.Message, ex);
}
xml = envelope.Content;
var signer = envelope.Signer;
signature = new IncomingSignature(
envelope.Verified, signer?.Name, signer?.TaxCode, signer?.SigningTime,
signer?.CertificateNotBefore, signer?.CertificateNotAfter, envelope.Problem);
}
if (!LooksLikeXml(xml))
{
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The file is neither XML nor a signed envelope.");
}
var root = Parse(xml).Root
?? throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The XML has no root element.");
return root.Name.LocalName switch
{
"FatturaElettronica" => ReadOrdinary(fileName, root, signature, xml),
"FatturaElettronicaSemplificata" => ReadSimplified(fileName, root, signature, xml),
_ => throw new IncomingInvoiceException(IncomingInvoiceErrors.NotInvoice, $"The XML is a '{root.Name.LocalName}', not an electronic invoice."),
};
}
// --- XML -------------------------------------------------------------------------------------------------------
private static bool LooksLikeXml(ReadOnlySpan<byte> content)
{
if (content.StartsWith((ReadOnlySpan<byte>)[0xEF, 0xBB, 0xBF]))
{
content = content[3..];
}
else if (content.StartsWith((ReadOnlySpan<byte>)[0xFF, 0xFE]) || content.StartsWith((ReadOnlySpan<byte>)[0xFE, 0xFF]))
{
return true;
}
var trimmed = content.TrimStart((ReadOnlySpan<byte>)[(byte)' ', (byte)'\t', (byte)'\r', (byte)'\n']);
return !trimmed.IsEmpty && trimmed[0] == (byte)'<';
}
private static XDocument Parse(byte[] xml)
{
var text = Decode(xml).TrimStart('', ' ', '\t', '\r', '\n');
var settings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null,
IgnoreComments = true,
IgnoreProcessingInstructions = true,
};
try
{
using var reader = XmlReader.Create(new StringReader(text), settings);
return XDocument.Load(reader);
}
catch (XmlException ex)
{
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The XML is not well formed: " + ex.Message, ex);
}
}
// The text is decoded here, then read from a string: the encoding of the declaration is honoured without the
// reader having to know code pages (windows-1252 is common in files written by older programs).
private static string Decode(byte[] xml)
{
if (xml.AsSpan().StartsWith((ReadOnlySpan<byte>)[0xEF, 0xBB, 0xBF]))
{
return new UTF8Encoding(false).GetString(xml, 3, xml.Length - 3);
}
if (xml.AsSpan().StartsWith((ReadOnlySpan<byte>)[0xFF, 0xFE]))
{
return Encoding.Unicode.GetString(xml, 2, xml.Length - 2);
}
if (xml.AsSpan().StartsWith((ReadOnlySpan<byte>)[0xFE, 0xFF]))
{
return Encoding.BigEndianUnicode.GetString(xml, 2, xml.Length - 2);
}
return EncodingOfDeclaration(xml).GetString(xml);
}
private static Encoding EncodingOfDeclaration(byte[] xml)
{
var head = Encoding.ASCII.GetString(xml, 0, Math.Min(xml.Length, 256));
var start = head.IndexOf("<?xml", StringComparison.Ordinal);
var end = start < 0 ? -1 : head.IndexOf("?>", start, StringComparison.Ordinal);
if (end < 0)
{
return new UTF8Encoding(false);
}
var declaration = head[start..end];
var at = declaration.IndexOf("encoding", StringComparison.OrdinalIgnoreCase);
if (at < 0)
{
return new UTF8Encoding(false);
}
var quote = declaration.IndexOfAny(['"', '\''], at);
var close = quote < 0 ? -1 : declaration.IndexOf(declaration[quote], quote + 1);
if (close < 0)
{
return new UTF8Encoding(false);
}
var name = declaration[(quote + 1)..close].Trim().ToUpperInvariant();
return name switch
{
"UTF-8" or "UTF8" => new UTF8Encoding(false),
"ISO-8859-1" or "LATIN1" or "ISO8859-1" => Encoding.Latin1,
"WINDOWS-1252" or "CP1252" => CodePage(1252),
"ISO-8859-15" => CodePage(28605),
_ => new UTF8Encoding(false),
};
}
private static Encoding CodePage(int codePage) =>
CodePagesEncodingProvider.Instance.GetEncoding(codePage) ?? Encoding.Latin1;
// --- Ordinary invoice --------------------------------------------------------------------------------------------
private static IncomingInvoiceFile ReadOrdinary(string fileName, XElement root, IncomingSignature? signature, byte[] xml)
{
var header = El(root, "FatturaElettronicaHeader")
?? throw Invalid("The invoice has no FatturaElettronicaHeader.");
var transmission = El(header, "DatiTrasmissione");
var supplier = El(header, "CedentePrestatore") ?? throw Invalid("The invoice has no CedentePrestatore.");
var customer = El(header, "CessionarioCommittente") ?? throw Invalid("The invoice has no CessionarioCommittente.");
var bodies = Els(root, "FatturaElettronicaBody").ToList();
if (bodies.Count == 0)
{
throw Invalid("The invoice has no FatturaElettronicaBody.");
}
return new IncomingInvoiceFile(
fileName,
Text(transmission, "FormatoTrasmissione"),
Text(transmission, "ProgressivoInvio"),
Text(transmission, "CodiceDestinatario"),
ReadParty(supplier),
ReadParty(customer),
bodies.Select(ReadBody).ToList(),
signature,
xml);
}
private static IncomingParty ReadParty(XElement party)
{
var personal = El(party, "DatiAnagrafici");
var identifiers = El(party, "IdentificativiFiscali");
var others = El(party, "AltriDatiIdentificativi");
var vat = El(personal, "IdFiscaleIVA") ?? El(identifiers, "IdFiscaleIVA") ?? El(party, "IdFiscaleIVA");
var names = El(personal, "Anagrafica") ?? others ?? party;
var office = El(party, "Sede") ?? El(others, "Sede");
var register = El(party, "IscrizioneREA");
var contacts = El(party, "Contatti");
return new IncomingParty(
Text(vat, "IdPaese"),
Text(vat, "IdCodice"),
Text(personal, "CodiceFiscale") ?? Text(identifiers, "CodiceFiscale") ?? Text(party, "CodiceFiscale"),
Text(names, "Denominazione"),
Text(names, "Nome"),
Text(names, "Cognome"),
Text(office, "Indirizzo"),
Text(office, "NumeroCivico"),
Text(office, "CAP"),
Text(office, "Comune"),
Text(office, "Provincia"),
Text(office, "Nazione"),
Text(personal, "RegimeFiscale") ?? Text(party, "RegimeFiscale"),
Text(contacts, "Email"),
Text(contacts, "Telefono"),
Text(register, "Ufficio"),
Text(register, "NumeroREA"));
}
private static IncomingInvoice ReadBody(XElement body, int index)
{
var general = El(body, "DatiGenerali");
var document = El(general, "DatiGeneraliDocumento")
?? throw Invalid($"Body {index + 1}: no DatiGeneraliDocumento.");
var goods = El(body, "DatiBeniServizi");
var stamp = El(document, "DatiBollo");
return new IncomingInvoice(
Required(document, "TipoDocumento", index),
Text(document, "Divisa") ?? "EUR",
RequiredDate(document, "Data", index),
Required(document, "Numero", index),
OptionalDecimal(document, "ImportoTotaleDocumento"),
OptionalDecimal(document, "Arrotondamento"),
Els(document, "Causale").Select(c => c.Value.Trim()).Where(c => c.Length > 0).ToList(),
Flag(document, "Art73"),
Els(document, "DatiRitenuta").Select(w => new IncomingWithholding(
Required(w, "TipoRitenuta", index),
RequiredDecimal(w, "ImportoRitenuta", index),
RequiredDecimal(w, "AliquotaRitenuta", index),
Text(w, "CausalePagamento"))).ToList(),
stamp is null ? null : new IncomingStampDuty(Flag(stamp, "BolloVirtuale"), OptionalDecimal(stamp, "ImportoBollo") ?? 0m),
Els(document, "DatiCassaPrevidenziale").Select(s => new IncomingSocialSecurity(
Required(s, "TipoCassa", index),
RequiredDecimal(s, "AlCassa", index),
RequiredDecimal(s, "ImportoContributoCassa", index),
OptionalDecimal(s, "ImponibileCassa"),
RequiredDecimal(s, "AliquotaIVA", index),
Flag(s, "Ritenuta"),
Text(s, "Natura"))).ToList(),
ReadDiscounts(document),
ReadReferences(general, "DatiOrdineAcquisto"),
ReadReferences(general, "DatiContratto"),
ReadReferences(general, "DatiFattureCollegate"),
Els(general, "DatiDDT").Select(d => new IncomingReference(
Text(d, "NumeroDDT"), OptionalDate(d, "DataDDT"), LineNumbers(d), null, null)).ToList(),
Els(goods, "DettaglioLinee").Select((l, i) => ReadLine(l, i, index)).ToList(),
Els(goods, "DatiRiepilogo").Select(r => new IncomingTaxSummary(
RequiredDecimal(r, "AliquotaIVA", index),
Text(r, "Natura"),
RequiredDecimal(r, "ImponibileImporto", index),
RequiredDecimal(r, "Imposta", index),
Text(r, "EsigibilitaIVA"),
Text(r, "RiferimentoNormativo"),
OptionalDecimal(r, "SpeseAccessorie"),
OptionalDecimal(r, "Arrotondamento"))).ToList(),
ReadPayments(body, index),
ReadAttachments(body));
}
private static IncomingLine ReadLine(XElement line, int position, int index) => new(
OptionalInt(line, "NumeroLinea") ?? position + 1,
Els(line, "CodiceArticolo")
.Select(c => new IncomingItemCode(Text(c, "CodiceTipo") ?? string.Empty, Text(c, "CodiceValore") ?? string.Empty))
.Where(c => c.Value.Length > 0)
.ToList(),
Text(line, "Descrizione") ?? string.Empty,
OptionalDecimal(line, "Quantita"),
Text(line, "UnitaMisura"),
RequiredDecimal(line, "PrezzoUnitario", index),
RequiredDecimal(line, "PrezzoTotale", index),
RequiredDecimal(line, "AliquotaIVA", index),
Text(line, "Natura"),
ReadDiscounts(line),
Flag(line, "Ritenuta"),
Text(line, "TipoCessionePrestazione"),
OptionalDate(line, "DataInizioPeriodo"),
OptionalDate(line, "DataFinePeriodo"),
Text(line, "RiferimentoAmministrazione"));
private static List<IncomingDiscount> ReadDiscounts(XElement? parent) =>
Els(parent, "ScontoMaggiorazione").Select(d => new IncomingDiscount(
string.Equals(Text(d, "Tipo"), "MG", StringComparison.OrdinalIgnoreCase),
OptionalDecimal(d, "Percentuale"),
OptionalDecimal(d, "Importo"))).ToList();
private static List<IncomingReference> ReadReferences(XElement? general, string name) =>
Els(general, name).Select(r => new IncomingReference(
Text(r, "IdDocumento"), OptionalDate(r, "Data"), LineNumbers(r), Text(r, "CodiceCIG"), Text(r, "CodiceCUP"))).ToList();
private static List<int> LineNumbers(XElement reference) =>
Els(reference, "RiferimentoNumeroLinea")
.Select(n => int.TryParse(n.Value.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var number) ? number : 0)
.Where(n => n > 0)
.ToList();
private static List<IncomingPayment> ReadPayments(XElement body, int index) =>
Els(body, "DatiPagamento").SelectMany(p =>
{
var conditions = Text(p, "CondizioniPagamento");
return Els(p, "DettaglioPagamento").Select(d => new IncomingPayment(
conditions,
Text(d, "ModalitaPagamento"),
OptionalDate(d, "DataScadenzaPagamento"),
RequiredDecimal(d, "ImportoPagamento", index),
Text(d, "IBAN"),
Text(d, "BIC"),
Text(d, "Beneficiario")));
}).ToList();
private static List<IncomingAttachment> ReadAttachments(XElement body) =>
Els(body, "Allegati").Select(a => new IncomingAttachment(
Text(a, "NomeAttachment") ?? "allegato",
Text(a, "FormatoAttachment"),
Text(a, "DescrizioneAttachment"),
DecodeAttachment(El(a, "Attachment")?.Value))).ToList();
private static byte[] DecodeAttachment(string? base64)
{
if (string.IsNullOrWhiteSpace(base64))
{
return [];
}
var compact = new StringBuilder(base64.Length);
foreach (var c in base64)
{
if (!char.IsWhiteSpace(c))
{
compact.Append(c);
}
}
var text = compact.ToString();
var buffer = new byte[text.Length / 4 * 3 + 3];
return Convert.TryFromBase64String(text, buffer, out var written) ? buffer[..written] : [];
}
// --- Simplified invoice ------------------------------------------------------------------------------------------
private static IncomingInvoiceFile ReadSimplified(string fileName, XElement root, IncomingSignature? signature, byte[] xml)
{
var header = El(root, "FatturaElettronicaHeader")
?? throw Invalid("The invoice has no FatturaElettronicaHeader.");
var transmission = El(header, "DatiTrasmissione");
var supplier = El(header, "CedentePrestatore") ?? throw Invalid("The invoice has no CedentePrestatore.");
var customer = El(header, "CessionarioCommittente") ?? throw Invalid("The invoice has no CessionarioCommittente.");
var bodies = Els(root, "FatturaElettronicaBody").ToList();
if (bodies.Count == 0)
{
throw Invalid("The invoice has no FatturaElettronicaBody.");
}
return new IncomingInvoiceFile(
fileName,
Text(transmission, "FormatoTrasmissione"),
Text(transmission, "ProgressivoInvio"),
Text(transmission, "CodiceDestinatario"),
ReadParty(supplier),
ReadParty(customer),
bodies.Select(ReadSimplifiedBody).ToList(),
signature,
xml);
}
private static IncomingInvoice ReadSimplifiedBody(XElement body, int index)
{
var general = El(body, "DatiGenerali");
var document = El(general, "DatiGeneraliDocumento")
?? throw Invalid($"Body {index + 1}: no DatiGeneraliDocumento.");
var lines = Els(body, "DatiBeniServizi").Select((l, i) => ReadSimplifiedLine(l, i, index)).ToList();
var gross = Els(body, "DatiBeniServizi").Sum(l => RequiredDecimal(l, "Importo", index));
var summary = lines
.GroupBy(l => (l.TaxRate, l.Nature))
.Select(g => new IncomingTaxSummary(
g.Key.TaxRate, g.Key.Nature, g.Sum(l => l.TotalPrice), g.Sum(l => l.Tax), null,
g.Select(l => l.LegalReference).FirstOrDefault(r => r is not null), null, null))
.ToList();
var corrected = Els(general, "DatiFatturaRettificata")
.Select(r => new IncomingReference(Text(r, "NumeroFR"), OptionalDate(r, "DataFR"), [], null, null))
.ToList();
return new IncomingInvoice(
Required(document, "TipoDocumento", index),
Text(document, "Divisa") ?? "EUR",
RequiredDate(document, "Data", index),
Required(document, "Numero", index),
gross,
null,
[],
false,
[],
Flag(document, "BolloVirtuale") ? new IncomingStampDuty(true, 0m) : null,
[],
[],
[],
[],
corrected,
[],
lines.Select(l => l.Line).ToList(),
summary,
[],
ReadAttachments(body));
}
private static SimplifiedLine ReadSimplifiedLine(XElement line, int position, int index)
{
var gross = RequiredDecimal(line, "Importo", index);
var vat = El(line, "DatiIVA");
var tax = OptionalDecimal(vat, "Imposta");
var rate = OptionalDecimal(vat, "Aliquota");
tax ??= rate is { } r && r != 0m ? Math.Round(gross * r / (100m + r), 2, MidpointRounding.AwayFromZero) : 0m;
var net = gross - tax.Value;
rate ??= net != 0m ? Math.Round(tax.Value / net * 100m, 2, MidpointRounding.AwayFromZero) : 0m;
var nature = Text(line, "Natura");
return new SimplifiedLine(
new IncomingLine(position + 1, [], Text(line, "Descrizione") ?? string.Empty, null, null, net, net, rate.Value, nature,
[], false, null, null, null, null),
tax.Value,
Text(line, "RiferimentoNormativo"));
}
private sealed record SimplifiedLine(IncomingLine Line, decimal Tax, string? LegalReference)
{
public decimal TaxRate => Line.TaxRate;
public string? Nature => Line.Nature;
public decimal TotalPrice => Line.TotalPrice;
}
// --- Helpers -----------------------------------------------------------------------------------------------------
private static XElement? El(XElement? parent, string localName) =>
parent?.Elements().FirstOrDefault(e => e.Name.LocalName == localName);
private static IEnumerable<XElement> Els(XElement? parent, string localName) =>
parent is null ? [] : parent.Elements().Where(e => e.Name.LocalName == localName);
private static string? Text(XElement? parent, string localName)
{
var value = El(parent, localName)?.Value.Trim();
return string.IsNullOrEmpty(value) ? null : value;
}
private static bool Flag(XElement? parent, string localName) =>
string.Equals(Text(parent, localName), "SI", StringComparison.OrdinalIgnoreCase);
private static string Required(XElement parent, string localName, int index) =>
Text(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing.");
private static decimal? OptionalDecimal(XElement? parent, string localName) =>
Text(parent, localName) is { } text && decimal.TryParse(text, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var value)
? value
: null;
private static decimal RequiredDecimal(XElement parent, string localName, int index) =>
OptionalDecimal(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing or not a number.");
private static int? OptionalInt(XElement parent, string localName) =>
Text(parent, localName) is { } text && int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : null;
private static DateOnly? OptionalDate(XElement? parent, string localName)
{
var text = Text(parent, localName);
if (text is null)
{
return null;
}
// xs:date may carry a time zone (2026-03-15+01:00): the day is what counts.
var day = text.Length > 10 ? text[..10] : text;
return DateOnly.TryParseExact(day, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) ? date : null;
}
private static DateOnly RequiredDate(XElement parent, string localName, int index) =>
OptionalDate(parent, localName) ?? throw Invalid($"Body {index + 1}: {parent.Name.LocalName}/{localName} is missing or not a date.");
private static IncomingInvoiceException Invalid(string message) => new(IncomingInvoiceErrors.Invalid, message);
}