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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-12 21:08:29 +01:00
1 parent 2c56c0dff0
commit 9a40adecfe
8 files changed
+2516

No files matched your search

@@ -0,0 +1,269 @@
namespace Khaemhat.Fiscal.Abstractions;
// The supplier invoices received as files of the country's e-invoice format (Italy: FatturaPA, also signed .p7m).
// The records keep the file as it is, with the codes of the format; the import service maps them to documents.
/// <summary>
/// Reads the e-invoice files received from suppliers: an optional feature of a country pack, like
/// <see cref="IEInvoiceFormat"/>. The reader only reads: it never contacts a service and never resolves external
/// references.
/// </summary>
public interface IIncomingInvoiceReader
{
/// <summary>
/// Whether the file looks like one the reader understands (Italy: <c>.xml</c>, <c>.p7m</c> in DER or as base64
/// text). The content is sniffed, not only the name.
/// </summary>
/// <param name="fileName">The name of the file, extension included.</param>
/// <param name="content">The content, or at least its first bytes.</param>
/// <returns><see langword="true"/> when <see cref="Read"/> is worth trying.</returns>
bool CanRead(string fileName, ReadOnlySpan<byte> content);
/// <summary>Reads a file.</summary>
/// <param name="fileName">The name of the file, extension included.</param>
/// <param name="content">The whole content.</param>
/// <returns>The file with its invoices.</returns>
/// <exception cref="IncomingInvoiceException">The file is not readable, not an invoice, or misses mandatory data;
/// <see cref="IncomingInvoiceException.Code"/> is one of <see cref="IncomingInvoiceErrors"/>.</exception>
IncomingInvoiceFile Read(string fileName, byte[] content);
}
/// <summary>A received e-invoice file that cannot be read; <see cref="Code"/> is one of <see cref="IncomingInvoiceErrors"/>.</summary>
public sealed class IncomingInvoiceException : Exception
{
/// <summary>Creates the exception.</summary>
public IncomingInvoiceException()
: this(IncomingInvoiceErrors.NotReadable, "The file is not readable.")
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
public IncomingInvoiceException(string message)
: this(IncomingInvoiceErrors.NotReadable, message)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">What went wrong.</param>
/// <param name="innerException">The cause.</param>
public IncomingInvoiceException(string message, Exception innerException)
: this(IncomingInvoiceErrors.NotReadable, message, innerException)
{
}
/// <summary>Creates the exception with a code.</summary>
/// <param name="code">One of <see cref="IncomingInvoiceErrors"/>.</param>
/// <param name="message">What went wrong.</param>
public IncomingInvoiceException(string code, string message)
: base(message) => Code = code;
/// <summary>Creates the exception with a code and its cause.</summary>
/// <param name="code">One of <see cref="IncomingInvoiceErrors"/>.</param>
/// <param name="message">What went wrong.</param>
/// <param name="innerException">The cause.</param>
public IncomingInvoiceException(string code, string message, Exception? innerException)
: base(message, innerException) => Code = code;
/// <summary>The text code of the error, one of <see cref="IncomingInvoiceErrors"/>.</summary>
public string Code { get; }
}
/// <summary>The codes of <see cref="IncomingInvoiceException"/>.</summary>
public static class IncomingInvoiceErrors
{
/// <summary>Neither XML nor a signed envelope: garbage, an empty file, a truncated download.</summary>
public const string NotReadable = "incoming.not-readable";
/// <summary>A well-formed XML document that is not an e-invoice.</summary>
public const string NotInvoice = "incoming.not-invoice";
/// <summary>A signed envelope whose content cannot be extracted.</summary>
public const string SignatureBroken = "incoming.signature-broken";
/// <summary>An e-invoice that misses mandatory data (date, number, document type...).</summary>
public const string Invalid = "incoming.invalid";
}
/// <summary>A received e-invoice file: the transmission header, the two parties and one or more invoices.</summary>
/// <param name="FileName">The name of the file as received.</param>
/// <param name="TransmissionFormat">The transmission format (Italy: <c>FPR12</c>, <c>FPA12</c>, <c>FSM10</c>).</param>
/// <param name="ProgressiveNumber">The progressive number of the transmission given by the sender.</param>
/// <param name="RecipientCode">The recipient code of the transmission.</param>
/// <param name="Supplier">The supplier who issued the invoices.</param>
/// <param name="Customer">The customer the invoices are addressed to (normally the company).</param>
/// <param name="Invoices">The invoices, one per body of the file (a batch has more than one).</param>
/// <param name="Signature">The signature of the envelope, or <see langword="null"/> for an unsigned file.</param>
/// <param name="Xml">The XML of the invoice, taken out of the envelope when the file was signed.</param>
public sealed record IncomingInvoiceFile(
string FileName, string? TransmissionFormat, string? ProgressiveNumber, string? RecipientCode,
IncomingParty Supplier, IncomingParty Customer, IReadOnlyList<IncomingInvoice> Invoices,
IncomingSignature? Signature, byte[] Xml);
/// <summary>
/// The signature of a signed file. <see cref="Verified"/> says only that the content is intact and signed by the key
/// of the embedded certificate: the trust chain and the revocation of the certificate are not checked, because no
/// trusted list is available offline.
/// </summary>
/// <param name="Verified">Whether the digest and the signature match the content.</param>
/// <param name="Signer">The name of the signer, from the certificate.</param>
/// <param name="SignerTaxCode">The tax code of the signer, when the certificate carries it.</param>
/// <param name="SignedAt">The signing time declared by the signer, if any (not a trusted timestamp).</param>
/// <param name="CertificateNotBefore">The start of validity of the certificate.</param>
/// <param name="CertificateNotAfter">The end of validity of the certificate.</param>
/// <param name="Problem">Why the signature is not verified, or <see langword="null"/>.</param>
public sealed record IncomingSignature(bool Verified, string? Signer, string? SignerTaxCode, DateTimeOffset? SignedAt,
DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, string? Problem);
/// <summary>A party of the invoice (supplier or customer) as written in the file.</summary>
/// <param name="CountryCode">The country of the VAT number.</param>
/// <param name="VatNumber">The VAT number without the country prefix.</param>
/// <param name="TaxCode">The tax code.</param>
/// <param name="Name">The company name, when the party is a company.</param>
/// <param name="FirstName">The first name, when the party is a person.</param>
/// <param name="LastName">The last name, when the party is a person.</param>
/// <param name="Address">The street of the registered office.</param>
/// <param name="StreetNumber">The street number.</param>
/// <param name="PostalCode">The postal code.</param>
/// <param name="City">The city.</param>
/// <param name="Province">The province.</param>
/// <param name="Country">The country of the registered office.</param>
/// <param name="TaxRegime">The tax regime (supplier only).</param>
/// <param name="Email">The e-mail address (supplier only).</param>
/// <param name="Phone">The phone number (supplier only).</param>
/// <param name="ReaOffice">The office of the companies register.</param>
/// <param name="ReaNumber">The number in the companies register.</param>
public sealed record IncomingParty(
string? CountryCode, string? VatNumber, string? TaxCode, string? Name, string? FirstName, string? LastName,
string? Address, string? StreetNumber, string? PostalCode, string? City, string? Province, string? Country,
string? TaxRegime, string? Email, string? Phone, string? ReaOffice, string? ReaNumber)
{
/// <summary>The company name, or first and last name of a person.</summary>
public string DisplayName => Name ?? string.Join(' ', new[] { FirstName, LastName }.Where(s => !string.IsNullOrWhiteSpace(s)));
}
/// <summary>An invoice of the file (one body).</summary>
/// <param name="DocumentType">The document type (Italy: <c>TD01</c>, <c>TD04</c>...).</param>
/// <param name="Currency">The currency code.</param>
/// <param name="Date">The date of the document.</param>
/// <param name="Number">The number of the document.</param>
/// <param name="Total">The total amount declared by the supplier, if any.</param>
/// <param name="Rounding">The rounding on the total, if any.</param>
/// <param name="Causals">The free-text causals.</param>
/// <param name="Art73">Whether the document is issued under the rule that allows several documents with the same
/// number in a year (Italy: art. 73 DPR 633/72).</param>
/// <param name="Withholdings">The withholding taxes.</param>
/// <param name="StampDuty">The stamp duty, if any.</param>
/// <param name="SocialSecurity">The social security contributions.</param>
/// <param name="Discounts">The discounts and surcharges on the whole document.</param>
/// <param name="Orders">The purchase orders referred to.</param>
/// <param name="Contracts">The contracts referred to.</param>
/// <param name="RelatedInvoices">The invoices referred to (the invoice a credit note corrects).</param>
/// <param name="DeliveryNotes">The delivery notes referred to.</param>
/// <param name="Lines">The lines.</param>
/// <param name="TaxSummary">The tax summary, one row per rate or nature.</param>
/// <param name="Payments">The payment installments.</param>
/// <param name="Attachments">The attached files.</param>
public sealed record IncomingInvoice(
string DocumentType, string Currency, DateOnly Date, string Number, decimal? Total, decimal? Rounding,
IReadOnlyList<string> Causals, bool Art73,
IReadOnlyList<IncomingWithholding> Withholdings, IncomingStampDuty? StampDuty,
IReadOnlyList<IncomingSocialSecurity> SocialSecurity, IReadOnlyList<IncomingDiscount> Discounts,
IReadOnlyList<IncomingReference> Orders, IReadOnlyList<IncomingReference> Contracts,
IReadOnlyList<IncomingReference> RelatedInvoices, IReadOnlyList<IncomingReference> DeliveryNotes,
IReadOnlyList<IncomingLine> Lines, IReadOnlyList<IncomingTaxSummary> TaxSummary,
IReadOnlyList<IncomingPayment> Payments, IReadOnlyList<IncomingAttachment> Attachments);
/// <summary>A line of an invoice.</summary>
/// <param name="Number">The line number.</param>
/// <param name="Codes">The item codes (type and value).</param>
/// <param name="Description">The description.</param>
/// <param name="Quantity">The quantity, if given.</param>
/// <param name="Unit">The unit of measure, if given.</param>
/// <param name="UnitPrice">The unit price.</param>
/// <param name="TotalPrice">The total of the line, net of tax.</param>
/// <param name="TaxRate">The tax rate in percent (zero with a nature).</param>
/// <param name="Nature">The reason of a zero rate (Italy: <c>N2.2</c>...).</param>
/// <param name="Discounts">The discounts and surcharges of the line.</param>
/// <param name="Withheld">Whether the line is subject to withholding tax.</param>
/// <param name="LineType">The kind of line (Italy: <c>SC</c> discount, <c>PR</c> premium, <c>AB</c> rebate,
/// <c>AC</c> ancillary cost).</param>
/// <param name="PeriodStart">The start of the period the line refers to.</param>
/// <param name="PeriodEnd">The end of the period the line refers to.</param>
/// <param name="AdministrativeReference">The administrative reference (cost centre, internal code).</param>
public sealed record IncomingLine(
int Number, IReadOnlyList<IncomingItemCode> Codes, string Description, decimal? Quantity, string? Unit,
decimal UnitPrice, decimal TotalPrice, decimal TaxRate, string? Nature, IReadOnlyList<IncomingDiscount> Discounts,
bool Withheld, string? LineType, DateOnly? PeriodStart, DateOnly? PeriodEnd, string? AdministrativeReference);
/// <summary>A code of the item of a line.</summary>
/// <param name="Type">The kind of code (<c>EAN</c>, <c>SKU</c>, the supplier's code...).</param>
/// <param name="Value">The code.</param>
public sealed record IncomingItemCode(string Type, string Value);
/// <summary>A discount or surcharge.</summary>
/// <param name="IsSurcharge">Whether it is a surcharge (Italy: <c>MG</c>) instead of a discount (<c>SC</c>).</param>
/// <param name="Percent">The percentage, if given.</param>
/// <param name="Amount">The amount, if given.</param>
public sealed record IncomingDiscount(bool IsSurcharge, decimal? Percent, decimal? Amount);
/// <summary>A row of the tax summary.</summary>
/// <param name="Rate">The tax rate in percent.</param>
/// <param name="Nature">The reason of a zero rate.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="Tax">The tax.</param>
/// <param name="Exigibility">When the tax is due (Italy: <c>I</c> immediate, <c>D</c> deferred, <c>S</c> split payment).</param>
/// <param name="LegalReference">The law that justifies the nature.</param>
/// <param name="ExpensesAmount">Ancillary expenses, if any.</param>
/// <param name="Rounding">The rounding, if any.</param>
public sealed record IncomingTaxSummary(decimal Rate, string? Nature, decimal Taxable, decimal Tax, string? Exigibility,
string? LegalReference, decimal? ExpensesAmount, decimal? Rounding);
/// <summary>A payment installment.</summary>
/// <param name="Conditions">The payment conditions (Italy: <c>TP01</c> installments, <c>TP02</c> full, <c>TP03</c> advance).</param>
/// <param name="Method">The payment method (Italy: <c>MP05</c> bank transfer...).</param>
/// <param name="DueDate">The due date, if given.</param>
/// <param name="Amount">The amount.</param>
/// <param name="Iban">The IBAN to pay to, if given.</param>
/// <param name="Bic">The BIC, if given.</param>
/// <param name="Beneficiary">The beneficiary, if different from the supplier.</param>
public sealed record IncomingPayment(string? Conditions, string? Method, DateOnly? DueDate, decimal Amount,
string? Iban, string? Bic, string? Beneficiary);
/// <summary>A reference to another document (order, contract, invoice, delivery note).</summary>
/// <param name="Id">The number of the document.</param>
/// <param name="Date">The date of the document.</param>
/// <param name="LineNumbers">The lines of the invoice the reference applies to; empty when it applies to all.</param>
/// <param name="Cig">The tender code, if any (public administration).</param>
/// <param name="Cup">The project code, if any (public administration).</param>
public sealed record IncomingReference(string? Id, DateOnly? Date, IReadOnlyList<int> LineNumbers, string? Cig, string? Cup);
/// <summary>A withholding tax.</summary>
/// <param name="Type">The kind of withholding (Italy: <c>RT01</c>...).</param>
/// <param name="Amount">The amount withheld.</param>
/// <param name="Rate">The rate in percent.</param>
/// <param name="Reason">The payment reason (Italy: <c>A</c>...), if given.</param>
public sealed record IncomingWithholding(string Type, decimal Amount, decimal Rate, string? Reason);
/// <summary>The stamp duty of an invoice.</summary>
/// <param name="Virtual">Whether it is paid virtually by the issuer.</param>
/// <param name="Amount">The amount.</param>
public sealed record IncomingStampDuty(bool Virtual, decimal Amount);
/// <summary>A social security contribution added to the invoice.</summary>
/// <param name="Fund">The fund (Italy: <c>TC01</c>...).</param>
/// <param name="Rate">The rate of the contribution in percent.</param>
/// <param name="Amount">The amount of the contribution.</param>
/// <param name="Taxable">The amount the contribution is computed on, if given.</param>
/// <param name="TaxRate">The tax rate applied to the contribution.</param>
/// <param name="Withheld">Whether the contribution is subject to withholding tax.</param>
/// <param name="Nature">The reason of a zero tax rate.</param>
public sealed record IncomingSocialSecurity(string Fund, decimal Rate, decimal Amount, decimal? Taxable, decimal TaxRate,
bool Withheld, string? Nature);
/// <summary>A file attached to the invoice.</summary>
/// <param name="Name">The name of the attachment.</param>
/// <param name="Format">The format declared by the supplier (such as <c>PDF</c>), if any.</param>
/// <param name="Description">The description, if any.</param>
/// <param name="Content">The decoded content.</param>
public sealed record IncomingAttachment(string Name, string? Format, string? Description, byte[] Content);