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

@@ -26,7 +26,7 @@ namespace Khaemhat.Application.Purchases;
/// <param name="ComputedTotal">Taxable plus tax of the summary, plus rounding: what the total should be.</param>
/// <param name="Problems">What stops or warns (resource codes).</param>
public sealed record IncomingCandidate(
string FileName, IncomingInvoiceFile File, IncomingInvoice Invoice, string? DocumentTypeCode, long? SupplierId, bool Duplicate, decimal ComputedTotal,
string FileName, EInvoiceFile File, EInvoiceBody Invoice, string? DocumentTypeCode, long? SupplierId, bool Duplicate, decimal ComputedTotal,
IReadOnlyList<string> Problems)
{
/// <summary>Whether it can be registered.</summary>
@@ -141,7 +141,7 @@ public sealed class PurchaseInvoiceImportService
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var reader = pack.GetFeature<IIncomingInvoiceReader>();
var rules = pack.GetFeature<IIncomingInvoiceRules>();
var found = new List<(string Name, IncomingInvoiceFile File)>();
var found = new List<(string Name, EInvoiceFile File)>();
var rejected = new List<IncomingRejected>();
foreach (var (name, content) in Expand(files, rejected))
{
@@ -330,16 +330,16 @@ public sealed class PurchaseInvoiceImportService
return result;
}
private static string KeyOf(IncomingParty party) =>
private static string KeyOf(EInvoiceParty party) =>
(party.VatNumber is { Length: > 0 } vat ? (party.CountryCode ?? "IT") + vat : party.TaxCode ?? string.Empty).ToUpperInvariant();
// The VAT number as the archive keeps it: digits only for Italy, with the country prefix abroad.
private static string? VatOf(IncomingParty party) =>
private static string? VatOf(EInvoiceParty party) =>
party.VatNumber is not { Length: > 0 } vat ? null
: party.CountryCode is null or "IT" ? vat
: vat.StartsWith(party.CountryCode, StringComparison.OrdinalIgnoreCase) ? vat : party.CountryCode + vat;
private static async Task<long?> FindSupplierAsync(IUnitOfWork uow, IncomingParty party, CancellationToken cancellationToken)
private static async Task<long?> FindSupplierAsync(IUnitOfWork uow, EInvoiceParty party, CancellationToken cancellationToken)
{
var parties = uow.Repository<Party, long>();
if (VatOf(party) is { } vat)
@@ -365,7 +365,7 @@ public sealed class PurchaseInvoiceImportService
.OrderBy(p => p.Disabled).ThenBy(p => p.Kind == PartyKind.Supplier ? 0 : p.IsSupplier ? 1 : 2).ThenBy(p => p.Id).FirstOrDefault()?.Id;
}
private static async Task<bool> IsDuplicateAsync(IUnitOfWork uow, long supplierId, IncomingInvoice invoice, CancellationToken cancellationToken)
private static async Task<bool> IsDuplicateAsync(IUnitOfWork uow, long supplierId, EInvoiceBody invoice, CancellationToken cancellationToken)
{
var number = invoice.Number.Trim();
var from = new DateOnly(invoice.Date.Year, 1, 1);
@@ -377,7 +377,7 @@ public sealed class PurchaseInvoiceImportService
cancellationToken).ConfigureAwait(false) > 0;
}
private async Task<long> CreateSupplierAsync(Actor actor, string company, IncomingParty party, CancellationToken cancellationToken)
private async Task<long> CreateSupplierAsync(Actor actor, string company, EInvoiceParty party, CancellationToken cancellationToken)
{
var record = await _parties.NewAsync(actor, company, PartyKind.Supplier, cancellationToken).ConfigureAwait(false);
var p = record.Party;
@@ -493,7 +493,7 @@ public sealed class PurchaseInvoiceImportService
return (saved, warnings);
}
private static long? ItemOf(IncomingLine line, Dictionary<string, long> bySupplierCode, Dictionary<string, long> byBarcode, Dictionary<string, Item> byCode)
private static long? ItemOf(EInvoiceLine line, Dictionary<string, long> bySupplierCode, Dictionary<string, long> byBarcode, Dictionary<string, Item> byCode)
{
foreach (var code in line.Codes.Select(c => c.Value.Trim()))
{
@@ -0,0 +1,253 @@
namespace Khaemhat.Fiscal.Abstractions;
// The model of an e-invoice file of the country's format (Italy: FatturaPA), the same in both directions: the reader
// fills it from a received file (M6), the writer turns it into the file to send (M9). It keeps the codes of the format.
/// <summary>An 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 or as it will be sent.</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 EInvoiceFile(
string FileName, string? TransmissionFormat, string? ProgressiveNumber, string? RecipientCode,
EInvoiceParty Supplier, EInvoiceParty Customer, IReadOnlyList<EInvoiceBody> Invoices,
EInvoiceSignature? Signature, byte[] Xml)
{
/// <summary>The country of the transmitter (Italy: <c>IdTrasmittente/IdPaese</c>).</summary>
public string? TransmitterCountry { get; init; }
/// <summary>The tax identifier of the transmitter (Italy: <c>IdTrasmittente/IdCodice</c>).</summary>
public string? TransmitterId { get; init; }
/// <summary>The certified mailbox the invoice is delivered to, when there is no recipient code.</summary>
public string? RecipientPec { get; init; }
/// <summary>The e-mail of the transmitter, for the exchange system (Italy: <c>ContattiTrasmittente/Email</c>).</summary>
public string? TransmitterEmail { get; init; }
/// <summary>The third party that issues the invoice for the supplier, if any (Italy: <c>TerzoIntermediarioOSoggettoEmittente</c>).</summary>
public EInvoiceParty? Intermediary { get; init; }
/// <summary>Who issues the document when not the supplier (Italy: <c>SoggettoEmittente</c>, <c>CC</c> customer, <c>TZ</c> third party).</summary>
public string? IssuedBy { get; init; }
}
/// <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 EInvoiceSignature(bool Verified, string? Signer, string? SignerTaxCode, DateTimeOffset? SignedAt,
DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, string? Problem);
/// <summary>A party of the invoice (supplier, customer or intermediary) 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 EInvoiceParty(
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>The share capital, for a company in the companies register.</summary>
public decimal? ShareCapital { get; init; }
/// <summary>One or more shareholders (Italy: <c>SU</c> sole, <c>SM</c> several).</summary>
public string? Shareholders { get; init; }
/// <summary>Whether the company is being wound up (Italy: <c>LS</c> yes, <c>LN</c> no).</summary>
public string? LiquidationStatus { get; init; }
/// <summary>The reference of the administration, for the public administration (Italy: <c>RiferimentoAmministrazione</c>).</summary>
public string? AdministrationReference { get; init; }
}
/// <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 EInvoiceBody(
string DocumentType, string Currency, DateOnly Date, string Number, decimal? Total, decimal? Rounding,
IReadOnlyList<string> Causals, bool Art73,
IReadOnlyList<EInvoiceWithholding> Withholdings, EInvoiceStampDuty? StampDuty,
IReadOnlyList<EInvoiceSocialSecurity> SocialSecurity, IReadOnlyList<EInvoiceDiscount> Discounts,
IReadOnlyList<EInvoiceReference> Orders, IReadOnlyList<EInvoiceReference> Contracts,
IReadOnlyList<EInvoiceReference> RelatedInvoices, IReadOnlyList<EInvoiceReference> DeliveryNotes,
IReadOnlyList<EInvoiceLine> Lines, IReadOnlyList<EInvoiceTaxSummary> TaxSummary,
IReadOnlyList<EInvoicePayment> Payments, IReadOnlyList<EInvoiceAttachment> Attachments)
{
/// <summary>The transport data of an accompanying invoice, if any.</summary>
public EInvoiceTransport? Transport { get; init; }
/// <summary>The payment conditions of the whole document (Italy: <c>TP01</c>, <c>TP02</c>, <c>TP03</c>).</summary>
public string? PaymentConditions { get; init; }
}
/// <summary>The transport data of an accompanying invoice (Italy: <c>DatiTrasporto</c>).</summary>
/// <param name="CarrierName">The carrier.</param>
/// <param name="CarrierCountry">The country of the VAT number of the carrier.</param>
/// <param name="CarrierVat">The VAT number of the carrier.</param>
/// <param name="Means">The means of transport.</param>
/// <param name="Reason">The reason of the transport.</param>
/// <param name="Packages">The number of packages.</param>
/// <param name="Description">The appearance of the goods.</param>
/// <param name="GrossWeight">The gross weight, kg.</param>
/// <param name="NetWeight">The net weight, kg.</param>
/// <param name="Start">When the transport starts.</param>
/// <param name="ShippingTerms">The terms of delivery (Incoterms).</param>
public sealed record EInvoiceTransport(
string? CarrierName, string? CarrierCountry, string? CarrierVat, string? Means, string? Reason, int? Packages,
string? Description, decimal? GrossWeight, decimal? NetWeight, DateTime? Start, string? ShippingTerms);
/// <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 EInvoiceLine(
int Number, IReadOnlyList<EInvoiceItemCode> Codes, string Description, decimal? Quantity, string? Unit,
decimal UnitPrice, decimal TotalPrice, decimal TaxRate, string? Nature, IReadOnlyList<EInvoiceDiscount> Discounts,
bool Withheld, string? LineType, DateOnly? PeriodStart, DateOnly? PeriodEnd, string? AdministrativeReference)
{
/// <summary>Further data of the line (Italy: <c>AltriDatiGestionali</c>, such as the declaration of intent).</summary>
public IReadOnlyList<EInvoiceOtherData> OtherData { get; init; } = [];
}
/// <summary>Further data of a line (Italy: <c>AltriDatiGestionali</c>).</summary>
/// <param name="Type">The kind of data (Italy: <c>TipoDato</c>, such as <c>INTENTO</c>).</param>
/// <param name="Text">A text value.</param>
/// <param name="Number">A number value.</param>
/// <param name="Date">A date value.</param>
public sealed record EInvoiceOtherData(string Type, string? Text, decimal? Number, DateOnly? Date);
/// <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 EInvoiceItemCode(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 EInvoiceDiscount(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 EInvoiceTaxSummary(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 EInvoicePayment(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 EInvoiceReference(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 EInvoiceWithholding(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 EInvoiceStampDuty(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 EInvoiceSocialSecurity(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 EInvoiceAttachment(string Name, string? Format, string? Description, byte[] Content);
@@ -0,0 +1,280 @@
namespace Khaemhat.Fiscal.Abstractions;
// The electronic invoice of the country (SPEC §11.9, ADR 0039): writing and checking the file, reading the receipts of
// the exchange system and the channels that carry files to it and back. The model of the file is EInvoiceFile; the
// Italian pack implements everything with FatturaPA and the SDI. The rest of Khaemhat works with these contracts only.
/// <summary>Writes the e-invoice file of the country's format (Italy: FatturaPA <c>FPR12</c>/<c>FPA12</c>).</summary>
public interface IEInvoiceWriter
{
/// <summary>The name of the file to send (Italy: <c>IT01234567890_00A1Z.xml</c>).</summary>
/// <param name="transmitterCountry">The country of the transmitter.</param>
/// <param name="transmitterId">The tax identifier of the transmitter.</param>
/// <param name="progressive">The progressive number of the file for this transmitter, from 1.</param>
/// <returns>The file name.</returns>
string FileName(string transmitterCountry, string transmitterId, long progressive);
/// <summary>The progressive written in the file for a progressive number (Italy: base 36, five characters).</summary>
/// <param name="progressive">The progressive number, from 1.</param>
/// <returns>The text.</returns>
string Progressive(long progressive);
/// <summary>Writes the file.</summary>
/// <param name="file">The content; <see cref="EInvoiceFile.Xml"/> and <see cref="EInvoiceFile.Signature"/> are ignored.</param>
/// <returns>The XML, UTF-8.</returns>
byte[] Write(EInvoiceFile file);
}
/// <summary>How serious a problem found by <see cref="IEInvoiceValidator"/> is.</summary>
public enum EInvoiceProblemSeverity
{
/// <summary>The exchange system would reject the file: it is not sent.</summary>
Error = 0,
/// <summary>The file is accepted but something looks wrong.</summary>
Warning = 1,
}
/// <summary>A problem of an e-invoice found before sending.</summary>
/// <param name="Code">The code: the check of the exchange system when there is one (Italy: <c>00423</c>), else a
/// text code of Khaemhat (<c>einvoice.xml.schema</c>).</param>
/// <param name="Path">Where: the element of the format, such as <c>DettaglioLinee[2]/PrezzoTotale</c>.</param>
/// <param name="Message">What is wrong, in the language of the format's documentation (Italian for FatturaPA).</param>
/// <param name="Severity">Error or warning.</param>
public sealed record EInvoiceProblem(string Code, string Path, string Message, EInvoiceProblemSeverity Severity = EInvoiceProblemSeverity.Error);
/// <summary>Checks an e-invoice before it leaves: the rules of the exchange system and the schema of the format.</summary>
public interface IEInvoiceValidator
{
/// <summary>The version of the rules checked, shown with the results.</summary>
string RulesVersion { get; }
/// <summary>The checks on the content: code lists, lengths, totals, natures, recipient, references.</summary>
/// <param name="file">The file content.</param>
/// <returns>The problems, errors first; empty when the file can be sent.</returns>
IReadOnlyList<EInvoiceProblem> Validate(EInvoiceFile file);
/// <summary>The checks on the XML: well formed and valid against the schema of the format.</summary>
/// <param name="xml">The file.</param>
/// <returns>The problems; empty when the file is valid.</returns>
IReadOnlyList<EInvoiceProblem> ValidateXml(byte[] xml);
}
/// <summary>What a receipt of the exchange system says (Italy: the SDI notifications).</summary>
public enum EInvoiceReceiptKind
{
/// <summary>Delivered to the customer (Italy: <c>RC</c> ricevuta di consegna).</summary>
Delivered = 0,
/// <summary>Rejected by the exchange system: the invoice is not issued (Italy: <c>NS</c> notifica di scarto).</summary>
Rejected = 1,
/// <summary>Not delivered, made available to the customer (Italy: <c>MC</c> mancata consegna).</summary>
NotDelivered = 2,
/// <summary>The outcome of a public administration: accepted or refused (Italy: <c>NE</c> notifica di esito).</summary>
Outcome = 3,
/// <summary>The public administration did not answer in time (Italy: <c>DT</c> decorrenza termini).</summary>
TermsElapsed = 4,
/// <summary>Sent to a public administration that could not receive it (Italy: <c>AT</c> attestazione).</summary>
Undeliverable = 5,
/// <summary>The metadata that go with a received invoice (Italy: <c>MT</c> file metadati).</summary>
Metadata = 6,
/// <summary>The exchange system rejected the outcome the company sent (Italy: <c>SE</c> scarto esito).</summary>
OutcomeRejected = 7,
}
/// <summary>An error listed in a rejection.</summary>
/// <param name="Code">The code (Italy: <c>00311</c>).</param>
/// <param name="Description">The description given by the exchange system.</param>
/// <param name="Hint">The suggestion given with it, if any.</param>
public sealed record EInvoiceReceiptError(string Code, string Description, string? Hint);
/// <summary>A receipt or notification of the exchange system about one file.</summary>
/// <param name="Kind">What it says.</param>
/// <param name="Code">The short code of the format (Italy: <c>RC</c>, <c>NS</c>...).</param>
/// <param name="FileName">The name of the receipt file.</param>
/// <param name="InvoiceFileName">The name of the invoice file it is about.</param>
/// <param name="ExchangeId">The identifier the exchange system gave to the invoice file (Italy: <c>IdentificativoSdI</c>).</param>
/// <param name="ReceivedAt">When the exchange system received the invoice file.</param>
/// <param name="DeliveredAt">When it was delivered, for a delivery receipt.</param>
/// <param name="Outcome">The outcome of the administration (Italy: <c>EC01</c> accepted, <c>EC02</c> refused).</param>
/// <param name="Description">The free text of the notification.</param>
/// <param name="Errors">The errors of a rejection.</param>
/// <param name="MessageId">The identifier of the message.</param>
/// <param name="RecipientCode">The recipient code, for the metadata of a received invoice.</param>
/// <param name="Content">The file as received.</param>
public sealed record EInvoiceReceipt(
EInvoiceReceiptKind Kind, string Code, string FileName, string? InvoiceFileName, string? ExchangeId,
DateTimeOffset? ReceivedAt, DateTimeOffset? DeliveredAt, string? Outcome, string? Description,
IReadOnlyList<EInvoiceReceiptError> Errors, string? MessageId, string? RecipientCode, byte[] Content)
{
/// <summary>Whether an outcome says the administration refused the invoice.</summary>
public bool Refused => Kind == EInvoiceReceiptKind.Outcome && string.Equals(Outcome, "EC02", StringComparison.Ordinal);
}
/// <summary>Reads the receipts of the exchange system (Italy: SDI notifications, <c>MessaggiTypes</c> v1.0).</summary>
public interface IEInvoiceReceiptReader
{
/// <summary>Whether a file is a receipt, by its name or its root element.</summary>
/// <param name="fileName">The name of the file.</param>
/// <param name="content">The content.</param>
/// <returns><see langword="true"/> when <see cref="Read"/> is worth trying.</returns>
bool IsReceipt(string fileName, ReadOnlySpan<byte> content);
/// <summary>Reads a receipt.</summary>
/// <param name="fileName">The name of the file.</param>
/// <param name="content">The content.</param>
/// <returns>The receipt.</returns>
/// <exception cref="IncomingInvoiceException">The file is not a receipt.</exception>
EInvoiceReceipt Read(string fileName, byte[] content);
}
/// <summary>
/// The settings of a channel to the exchange system. Each channel uses the fields it needs (the PEC mailbox, the web
/// service, the API of an intermediary); secrets arrive decrypted and never leave the transport.
/// </summary>
public sealed record EInvoiceChannelSettings
{
/// <summary>The channel code (Italy: <c>PEC</c>, <c>SDICOOP</c>, <c>INTA</c>, <c>INTB</c>).</summary>
public required string Code { get; init; }
/// <summary>The certified mailbox of the company.</summary>
public string? Mailbox { get; init; }
/// <summary>The SMTP server of the mailbox.</summary>
public string? SmtpHost { get; init; }
/// <summary>The SMTP port (465 for TLS from the start, 587 for STARTTLS).</summary>
public int SmtpPort { get; init; } = 465;
/// <summary>The IMAP server of the mailbox.</summary>
public string? ImapHost { get; init; }
/// <summary>The IMAP port (993 for TLS).</summary>
public int ImapPort { get; init; } = 993;
/// <summary>Whether the connections are protected by TLS (always, except in tests on the local machine).</summary>
public bool Tls { get; init; } = true;
/// <summary>The user of the mailbox or of the service.</summary>
public string? User { get; init; }
/// <summary>The password of the mailbox or of the service.</summary>
public string? Password { get; init; }
/// <summary>The address of the exchange system to write to (Italy: <c>sdi01@pec.fatturapa.it</c>, then the one assigned).</summary>
public string? ExchangeAddress { get; init; }
/// <summary>The folder of the mailbox the processed messages are moved to.</summary>
public string? ArchiveFolder { get; init; }
/// <summary>The address of the web service or of the API.</summary>
public string? Endpoint { get; init; }
/// <summary>The client certificate (PKCS#12) of the web service.</summary>
public byte[]? Certificate { get; init; }
/// <summary>The password of the certificate.</summary>
public string? CertificatePassword { get; init; }
/// <summary>The API key or token of an intermediary.</summary>
public string? ApiKey { get; init; }
/// <summary>Whether the test environment of the service is used.</summary>
public bool TestEnvironment { get; init; }
}
/// <summary>A file to send.</summary>
/// <param name="FileName">The name of the file.</param>
/// <param name="Content">The content.</param>
/// <param name="Reference">What it is, for messages and logs (the number of the document).</param>
public sealed record EInvoiceOutgoing(string FileName, byte[] Content, string? Reference);
/// <summary>The answer of a channel to a file sent.</summary>
/// <param name="Accepted">Whether the channel took the file.</param>
/// <param name="ExchangeId">The identifier given by the exchange system, when the channel knows it at once (Italy: SdICoop).</param>
/// <param name="MessageId">The identifier of the message or of the upload at the channel.</param>
/// <param name="Error">Why the file was not taken.</param>
public sealed record EInvoiceSendResult(bool Accepted, string? ExchangeId, string? MessageId, string? Error);
/// <summary>A file received from a channel: a receipt, a supplier invoice or its metadata.</summary>
/// <param name="FileName">The name of the file.</param>
/// <param name="Content">The content.</param>
/// <param name="ReceivedAt">When the channel received it.</param>
/// <param name="MessageKey">The key of the message at the channel, to acknowledge it once stored.</param>
/// <param name="Sender">Who sent it (the address of the exchange system), if known.</param>
public sealed record EInvoiceIncoming(string FileName, byte[] Content, DateTimeOffset ReceivedAt, string MessageKey, string? Sender);
/// <summary>What a channel had for the company.</summary>
/// <param name="Files">The files received.</param>
/// <param name="MessagesRead">How many messages the channel read, files or not.</param>
/// <param name="ExchangeAddress">The address the exchange system assigned for the next files, if it changed (Italy: PEC).</param>
public sealed record EInvoiceFetchResult(IReadOnlyList<EInvoiceIncoming> Files, int MessagesRead, string? ExchangeAddress);
/// <summary>The outcome of a connection test.</summary>
/// <param name="Success">Whether every step worked.</param>
/// <param name="Message">What was checked, or what failed.</param>
public sealed record EInvoiceChannelCheck(bool Success, string Message);
/// <summary>
/// A channel to the exchange system (SPEC §11.9: <c>ISdiTransport</c>): send a file, fetch receipts and supplier
/// invoices, acknowledge what was stored, test the connection. Every channel has the same contract, so the rest of
/// Khaemhat does not change with the channel.
/// </summary>
public interface IEInvoiceTransport
{
/// <summary>The code of the channel (Italy: <c>PEC</c>, <c>SDICOOP</c>, <c>INTA</c>, <c>INTB</c>).</summary>
string Code { get; }
/// <summary>Whether receipts and invoices are fetched by polling (<see langword="false"/> when the exchange system pushes them).</summary>
bool Polls { get; }
/// <summary>Sends a file.</summary>
/// <param name="settings">The settings of the channel.</param>
/// <param name="file">The file.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The answer of the channel.</returns>
Task<EInvoiceSendResult> SendAsync(EInvoiceChannelSettings settings, EInvoiceOutgoing file, CancellationToken cancellationToken = default);
/// <summary>Fetches the files waiting at the channel; nothing is removed until <see cref="AcknowledgeAsync"/>.</summary>
/// <param name="settings">The settings of the channel.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The files.</returns>
Task<EInvoiceFetchResult> FetchAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default);
/// <summary>Marks messages as processed (Italy, PEC: moved to the archive folder).</summary>
/// <param name="settings">The settings of the channel.</param>
/// <param name="messageKeys">The keys of <see cref="EInvoiceIncoming.MessageKey"/>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection<string> messageKeys, CancellationToken cancellationToken = default);
/// <summary>Tests the connection without sending anything.</summary>
/// <param name="settings">The settings of the channel.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome.</returns>
Task<EInvoiceChannelCheck> CheckAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default);
}
/// <summary>A channel the pack offers, with its description for the configuration screen.</summary>
/// <param name="Code">The code.</param>
/// <param name="Name">The name shown.</param>
/// <param name="Transport">The implementation.</param>
public sealed record EInvoiceChannel(string Code, string Name, IEInvoiceTransport Transport);
/// <summary>The channels to the exchange system the pack offers (Italy: PEC, SdICoop, intermediary A and B).</summary>
public interface IEInvoiceChannels
{
/// <summary>The channels, in the order of the configuration screen.</summary>
IReadOnlyList<EInvoiceChannel> All { get; }
/// <summary>A channel by code.</summary>
/// <param name="code">The code.</param>
/// <returns>The channel, or <see langword="null"/>.</returns>
EInvoiceChannel? Find(string code);
}
@@ -25,7 +25,7 @@ public interface IIncomingInvoiceReader
/// <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);
EInvoiceFile 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>
@@ -85,189 +85,6 @@ public static class IncomingInvoiceErrors
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);
/// <summary>
/// How a received e-invoice becomes a document of the company: which document type registers each type of the format
/// (Italy: TD01 and the like as supplier invoice FF, TD04 and TD08 as supplier credit note NCF).
@@ -0,0 +1,558 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
FatturaPA v1.2 (FPR12, FPA12): the structure and the simple types of the official schema of the Agenzia delle
Entrate for the elements Khaemhat writes (ADR 0039). Written in house from the technical specifications: element
order, cardinality, lengths, patterns and enumerations follow the official schema; optional blocks Khaemhat never
writes (StabileOrganizzazione, RappresentanteFiscale, DatiSAL, DatiVeicoli...) are not declared, so a file that
uses them is not valid here. It checks the writer before a file leaves; the exchange system checks the rest.
-->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2"
targetNamespace="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2"
elementFormDefault="unqualified" attributeFormDefault="unqualified">
<xs:element name="FatturaElettronica" type="FatturaElettronicaType"/>
<xs:complexType name="FatturaElettronicaType">
<xs:sequence>
<xs:element name="FatturaElettronicaHeader" type="FatturaElettronicaHeaderType"/>
<xs:element name="FatturaElettronicaBody" type="FatturaElettronicaBodyType" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="versione" type="FormatoTrasmissioneType" use="required"/>
<xs:attribute name="SistemaEmittente" type="String10Type" use="optional"/>
</xs:complexType>
<!-- Header -->
<xs:complexType name="FatturaElettronicaHeaderType">
<xs:sequence>
<xs:element name="DatiTrasmissione" type="DatiTrasmissioneType"/>
<xs:element name="CedentePrestatore" type="CedentePrestatoreType"/>
<xs:element name="CessionarioCommittente" type="CessionarioCommittenteType"/>
<xs:element name="TerzoIntermediarioOSoggettoEmittente" type="TerzoIntermediarioType" minOccurs="0"/>
<xs:element name="SoggettoEmittente" type="SoggettoEmittenteType" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiTrasmissioneType">
<xs:sequence>
<xs:element name="IdTrasmittente" type="IdFiscaleType"/>
<xs:element name="ProgressivoInvio" type="String10Type"/>
<xs:element name="FormatoTrasmissione" type="FormatoTrasmissioneType"/>
<xs:element name="CodiceDestinatario" type="CodiceDestinatarioType"/>
<xs:element name="ContattiTrasmittente" type="ContattiTrasmittenteType" minOccurs="0"/>
<xs:element name="PECDestinatario" type="EmailType" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="IdFiscaleType">
<xs:sequence>
<xs:element name="IdPaese" type="NazioneType"/>
<xs:element name="IdCodice" type="CodiceType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="ContattiTrasmittenteType">
<xs:sequence>
<xs:element name="Telefono" type="TelFaxType" minOccurs="0"/>
<xs:element name="Email" type="EmailType" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="CedentePrestatoreType">
<xs:sequence>
<xs:element name="DatiAnagrafici" type="DatiAnagraficiCedenteType"/>
<xs:element name="Sede" type="IndirizzoType"/>
<xs:element name="IscrizioneREA" type="IscrizioneREAType" minOccurs="0"/>
<xs:element name="Contatti" type="ContattiType" minOccurs="0"/>
<xs:element name="RiferimentoAmministrazione" type="String20Type" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiAnagraficiCedenteType">
<xs:sequence>
<xs:element name="IdFiscaleIVA" type="IdFiscaleType"/>
<xs:element name="CodiceFiscale" type="CodiceFiscaleType" minOccurs="0"/>
<xs:element name="Anagrafica" type="AnagraficaType"/>
<xs:element name="RegimeFiscale" type="RegimeFiscaleType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="AnagraficaType">
<xs:choice>
<xs:element name="Denominazione" type="String80LatinType"/>
<xs:sequence>
<xs:element name="Nome" type="String60LatinType"/>
<xs:element name="Cognome" type="String60LatinType"/>
</xs:sequence>
</xs:choice>
</xs:complexType>
<xs:complexType name="IndirizzoType">
<xs:sequence>
<xs:element name="Indirizzo" type="String60LatinType"/>
<xs:element name="NumeroCivico" type="NumeroCivicoType" minOccurs="0"/>
<xs:element name="CAP" type="CAPType"/>
<xs:element name="Comune" type="String60LatinType"/>
<xs:element name="Provincia" type="ProvinciaType" minOccurs="0"/>
<xs:element name="Nazione" type="NazioneType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="IscrizioneREAType">
<xs:sequence>
<xs:element name="Ufficio" type="ProvinciaType"/>
<xs:element name="NumeroREA" type="String20Type"/>
<xs:element name="CapitaleSociale" type="Amount2DecimalType" minOccurs="0"/>
<xs:element name="SocioUnico" type="SocioUnicoType" minOccurs="0"/>
<xs:element name="StatoLiquidazione" type="StatoLiquidazioneType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="ContattiType">
<xs:sequence>
<xs:element name="Telefono" type="TelFaxType" minOccurs="0"/>
<xs:element name="Fax" type="TelFaxType" minOccurs="0"/>
<xs:element name="Email" type="EmailType" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="CessionarioCommittenteType">
<xs:sequence>
<xs:element name="DatiAnagrafici" type="DatiAnagraficiCessionarioType"/>
<xs:element name="Sede" type="IndirizzoType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiAnagraficiCessionarioType">
<xs:sequence>
<xs:element name="IdFiscaleIVA" type="IdFiscaleType" minOccurs="0"/>
<xs:element name="CodiceFiscale" type="CodiceFiscaleType" minOccurs="0"/>
<xs:element name="Anagrafica" type="AnagraficaType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="TerzoIntermediarioType">
<xs:sequence>
<xs:element name="DatiAnagrafici" type="DatiAnagraficiTerzoType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiAnagraficiTerzoType">
<xs:sequence>
<xs:element name="IdFiscaleIVA" type="IdFiscaleType" minOccurs="0"/>
<xs:element name="CodiceFiscale" type="CodiceFiscaleType" minOccurs="0"/>
<xs:element name="Anagrafica" type="AnagraficaType"/>
</xs:sequence>
</xs:complexType>
<!-- Body -->
<xs:complexType name="FatturaElettronicaBodyType">
<xs:sequence>
<xs:element name="DatiGenerali" type="DatiGeneraliType"/>
<xs:element name="DatiBeniServizi" type="DatiBeniServiziType"/>
<xs:element name="DatiPagamento" type="DatiPagamentoType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="Allegati" type="AllegatiType" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiGeneraliType">
<xs:sequence>
<xs:element name="DatiGeneraliDocumento" type="DatiGeneraliDocumentoType"/>
<xs:element name="DatiOrdineAcquisto" type="DatiDocumentiCorrelatiType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="DatiContratto" type="DatiDocumentiCorrelatiType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="DatiFattureCollegate" type="DatiDocumentiCorrelatiType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="DatiDDT" type="DatiDDTType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="DatiTrasporto" type="DatiTrasportoType" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiGeneraliDocumentoType">
<xs:sequence>
<xs:element name="TipoDocumento" type="TipoDocumentoType"/>
<xs:element name="Divisa" type="DivisaType"/>
<xs:element name="Data" type="DataFatturaType"/>
<xs:element name="Numero" type="String20Type"/>
<xs:element name="DatiRitenuta" type="DatiRitenutaType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="DatiBollo" type="DatiBolloType" minOccurs="0"/>
<xs:element name="DatiCassaPrevidenziale" type="DatiCassaPrevidenzialeType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="ScontoMaggiorazione" type="ScontoMaggiorazioneType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="ImportoTotaleDocumento" type="Amount2DecimalType" minOccurs="0"/>
<xs:element name="Arrotondamento" type="Amount2DecimalType" minOccurs="0"/>
<xs:element name="Causale" type="String200LatinType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="Art73" type="Art73Type" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiRitenutaType">
<xs:sequence>
<xs:element name="TipoRitenuta" type="TipoRitenutaType"/>
<xs:element name="ImportoRitenuta" type="Amount2DecimalType"/>
<xs:element name="AliquotaRitenuta" type="RateType"/>
<xs:element name="CausalePagamento" type="CausalePagamentoType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiBolloType">
<xs:sequence>
<xs:element name="BolloVirtuale" type="BolloVirtualeType"/>
<xs:element name="ImportoBollo" type="Amount2DecimalType" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiCassaPrevidenzialeType">
<xs:sequence>
<xs:element name="TipoCassa" type="TipoCassaType"/>
<xs:element name="AlCassa" type="RateType"/>
<xs:element name="ImportoContributoCassa" type="Amount2DecimalType"/>
<xs:element name="ImponibileCassa" type="Amount2DecimalType" minOccurs="0"/>
<xs:element name="AliquotaIVA" type="RateType"/>
<xs:element name="Ritenuta" type="RitenutaType" minOccurs="0"/>
<xs:element name="Natura" type="NaturaType" minOccurs="0"/>
<xs:element name="RiferimentoAmministrazione" type="String20Type" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="ScontoMaggiorazioneType">
<xs:sequence>
<xs:element name="Tipo" type="TipoScontoMaggiorazioneType"/>
<xs:element name="Percentuale" type="RateType" minOccurs="0"/>
<xs:element name="Importo" type="Amount8DecimalType" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiDocumentiCorrelatiType">
<xs:sequence>
<xs:element name="RiferimentoNumeroLinea" type="RiferimentoNumeroLineaType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="IdDocumento" type="String20Type"/>
<xs:element name="Data" type="xs:date" minOccurs="0"/>
<xs:element name="NumItem" type="String20Type" minOccurs="0"/>
<xs:element name="CodiceCommessaConvenzione" type="String100LatinType" minOccurs="0"/>
<xs:element name="CodiceCUP" type="String15Type" minOccurs="0"/>
<xs:element name="CodiceCIG" type="String15Type" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiDDTType">
<xs:sequence>
<xs:element name="NumeroDDT" type="String20Type"/>
<xs:element name="DataDDT" type="xs:date"/>
<xs:element name="RiferimentoNumeroLinea" type="RiferimentoNumeroLineaType" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiTrasportoType">
<xs:sequence>
<xs:element name="DatiAnagraficiVettore" type="DatiAnagraficiVettoreType" minOccurs="0"/>
<xs:element name="MezzoTrasporto" type="String80LatinType" minOccurs="0"/>
<xs:element name="CausaleTrasporto" type="String100LatinType" minOccurs="0"/>
<xs:element name="NumeroColli" type="NumeroColliType" minOccurs="0"/>
<xs:element name="Descrizione" type="String100LatinType" minOccurs="0"/>
<xs:element name="UnitaMisuraPeso" type="String10Type" minOccurs="0"/>
<xs:element name="PesoLordo" type="PesoType" minOccurs="0"/>
<xs:element name="PesoNetto" type="PesoType" minOccurs="0"/>
<xs:element name="DataOraRitiro" type="xs:dateTime" minOccurs="0"/>
<xs:element name="DataInizioTrasporto" type="xs:date" minOccurs="0"/>
<xs:element name="TipoResa" type="TipoResaType" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiAnagraficiVettoreType">
<xs:sequence>
<xs:element name="IdFiscaleIVA" type="IdFiscaleType"/>
<xs:element name="CodiceFiscale" type="CodiceFiscaleType" minOccurs="0"/>
<xs:element name="Anagrafica" type="AnagraficaType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiBeniServiziType">
<xs:sequence>
<xs:element name="DettaglioLinee" type="DettaglioLineeType" maxOccurs="unbounded"/>
<xs:element name="DatiRiepilogo" type="DatiRiepilogoType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DettaglioLineeType">
<xs:sequence>
<xs:element name="NumeroLinea" type="NumeroLineaType"/>
<xs:element name="TipoCessionePrestazione" type="TipoCessionePrestazioneType" minOccurs="0"/>
<xs:element name="CodiceArticolo" type="CodiceArticoloType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="Descrizione" type="String1000LatinType"/>
<xs:element name="Quantita" type="QuantitaType" minOccurs="0"/>
<xs:element name="UnitaMisura" type="String10Type" minOccurs="0"/>
<xs:element name="DataInizioPeriodo" type="xs:date" minOccurs="0"/>
<xs:element name="DataFinePeriodo" type="xs:date" minOccurs="0"/>
<xs:element name="PrezzoUnitario" type="Amount8DecimalType"/>
<xs:element name="ScontoMaggiorazione" type="ScontoMaggiorazioneType" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="PrezzoTotale" type="Amount8DecimalType"/>
<xs:element name="AliquotaIVA" type="RateType"/>
<xs:element name="Ritenuta" type="RitenutaType" minOccurs="0"/>
<xs:element name="Natura" type="NaturaType" minOccurs="0"/>
<xs:element name="RiferimentoAmministrazione" type="String20Type" minOccurs="0"/>
<xs:element name="AltriDatiGestionali" type="AltriDatiGestionaliType" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="CodiceArticoloType">
<xs:sequence>
<xs:element name="CodiceTipo" type="String35Type"/>
<xs:element name="CodiceValore" type="String35LatinType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="AltriDatiGestionaliType">
<xs:sequence>
<xs:element name="TipoDato" type="String10Type"/>
<xs:element name="RiferimentoTesto" type="String60LatinType" minOccurs="0"/>
<xs:element name="RiferimentoNumero" type="Amount8DecimalType" minOccurs="0"/>
<xs:element name="RiferimentoData" type="xs:date" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiRiepilogoType">
<xs:sequence>
<xs:element name="AliquotaIVA" type="RateType"/>
<xs:element name="Natura" type="NaturaType" minOccurs="0"/>
<xs:element name="SpeseAccessorie" type="Amount2DecimalType" minOccurs="0"/>
<xs:element name="Arrotondamento" type="Amount8DecimalType" minOccurs="0"/>
<xs:element name="ImponibileImporto" type="Amount2DecimalType"/>
<xs:element name="Imposta" type="Amount2DecimalType"/>
<xs:element name="EsigibilitaIVA" type="EsigibilitaIVAType" minOccurs="0"/>
<xs:element name="RiferimentoNormativo" type="String100LatinType" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DatiPagamentoType">
<xs:sequence>
<xs:element name="CondizioniPagamento" type="CondizioniPagamentoType"/>
<xs:element name="DettaglioPagamento" type="DettaglioPagamentoType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="DettaglioPagamentoType">
<xs:sequence>
<xs:element name="Beneficiario" type="String200LatinType" minOccurs="0"/>
<xs:element name="ModalitaPagamento" type="ModalitaPagamentoType"/>
<xs:element name="DataRiferimentoTerminiPagamento" type="xs:date" minOccurs="0"/>
<xs:element name="GiorniTerminiPagamento" type="GiorniTerminePagamentoType" minOccurs="0"/>
<xs:element name="DataScadenzaPagamento" type="xs:date" minOccurs="0"/>
<xs:element name="ImportoPagamento" type="Amount2DecimalType"/>
<xs:element name="IBAN" type="IBANType" minOccurs="0"/>
<xs:element name="BIC" type="BICType" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="AllegatiType">
<xs:sequence>
<xs:element name="NomeAttachment" type="String60LatinType"/>
<xs:element name="AlgoritmoCompressione" type="String10Type" minOccurs="0"/>
<xs:element name="FormatoAttachment" type="String10Type" minOccurs="0"/>
<xs:element name="DescrizioneAttachment" type="String100LatinType" minOccurs="0"/>
<xs:element name="Attachment" type="xs:base64Binary"/>
</xs:sequence>
</xs:complexType>
<!-- Simple types -->
<xs:simpleType name="FormatoTrasmissioneType">
<xs:restriction base="xs:string">
<xs:enumeration value="FPA12"/>
<xs:enumeration value="FPR12"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="CodiceDestinatarioType">
<xs:restriction base="xs:string"><xs:pattern value="[A-Z0-9]{6,7}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="CodiceType">
<xs:restriction base="xs:string"><xs:minLength value="1"/><xs:maxLength value="28"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="CodiceFiscaleType">
<xs:restriction base="xs:string"><xs:pattern value="[A-Z0-9]{11,16}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="NazioneType">
<xs:restriction base="xs:string"><xs:pattern value="[A-Z]{2}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="ProvinciaType">
<xs:restriction base="xs:string"><xs:pattern value="[A-Z]{2}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="CAPType">
<xs:restriction base="xs:string"><xs:pattern value="[0-9][0-9][0-9][0-9][0-9]"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="NumeroCivicoType">
<xs:restriction base="xs:string"><xs:pattern value="(\p{IsBasicLatin}{1,8})"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="TelFaxType">
<xs:restriction base="xs:string"><xs:pattern value="(\p{IsBasicLatin}{5,12})"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="EmailType">
<xs:restriction base="xs:string">
<xs:minLength value="7"/>
<xs:maxLength value="256"/>
<xs:pattern value=".+@.+[.]+.+"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="String10Type">
<xs:restriction base="xs:normalizedString"><xs:pattern value="(\p{IsBasicLatin}{1,10})"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="String15Type">
<xs:restriction base="xs:normalizedString"><xs:pattern value="(\p{IsBasicLatin}{1,15})"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="String20Type">
<xs:restriction base="xs:normalizedString"><xs:pattern value="(\p{IsBasicLatin}{1,20})"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="String35Type">
<xs:restriction base="xs:normalizedString"><xs:pattern value="(\p{IsBasicLatin}{1,35})"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="String35LatinType">
<xs:restriction base="xs:normalizedString"><xs:pattern value="[\p{IsBasicLatin}\p{IsLatin-1Supplement}]{1,35}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="String60LatinType">
<xs:restriction base="xs:normalizedString"><xs:pattern value="[\p{IsBasicLatin}\p{IsLatin-1Supplement}]{1,60}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="String80LatinType">
<xs:restriction base="xs:normalizedString"><xs:pattern value="[\p{IsBasicLatin}\p{IsLatin-1Supplement}]{1,80}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="String100LatinType">
<xs:restriction base="xs:normalizedString"><xs:pattern value="[\p{IsBasicLatin}\p{IsLatin-1Supplement}]{1,100}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="String200LatinType">
<xs:restriction base="xs:normalizedString"><xs:pattern value="[\p{IsBasicLatin}\p{IsLatin-1Supplement}]{1,200}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="String1000LatinType">
<xs:restriction base="xs:normalizedString"><xs:pattern value="[\p{IsBasicLatin}\p{IsLatin-1Supplement}]{1,1000}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="Amount2DecimalType">
<xs:restriction base="xs:decimal"><xs:pattern value="[\-]?[0-9]{1,11}\.[0-9]{2}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="Amount8DecimalType">
<xs:restriction base="xs:decimal"><xs:pattern value="[\-]?[0-9]{1,11}\.[0-9]{2,8}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="QuantitaType">
<xs:restriction base="xs:decimal"><xs:pattern value="[0-9]{1,12}\.[0-9]{2,8}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="RateType">
<xs:restriction base="xs:decimal">
<xs:maxInclusive value="100.00"/>
<xs:pattern value="[0-9]{1,3}\.[0-9]{2}"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="PesoType">
<xs:restriction base="xs:decimal"><xs:pattern value="[0-9]{1,4}\.[0-9]{1,2}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="NumeroColliType">
<xs:restriction base="xs:integer"><xs:minInclusive value="1"/><xs:maxInclusive value="9999"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="NumeroLineaType">
<xs:restriction base="xs:integer"><xs:minInclusive value="1"/><xs:maxInclusive value="9999"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="RiferimentoNumeroLineaType">
<xs:restriction base="xs:integer"><xs:minInclusive value="1"/><xs:maxInclusive value="9999"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="GiorniTerminePagamentoType">
<xs:restriction base="xs:integer"><xs:minInclusive value="0"/><xs:maxInclusive value="999"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="DataFatturaType">
<xs:restriction base="xs:date"><xs:minInclusive value="1970-01-01"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="DivisaType">
<xs:restriction base="xs:string"><xs:pattern value="[A-Z]{3}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="IBANType">
<xs:restriction base="xs:string"><xs:pattern value="[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{11,30}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="BICType">
<xs:restriction base="xs:string"><xs:pattern value="[A-Z]{6}[A-Z2-9][A-NP-Z0-9]([A-Z0-9]{3}){0,1}"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="TipoDocumentoType">
<xs:restriction base="xs:string">
<xs:enumeration value="TD01"/><xs:enumeration value="TD02"/><xs:enumeration value="TD03"/><xs:enumeration value="TD04"/>
<xs:enumeration value="TD05"/><xs:enumeration value="TD06"/><xs:enumeration value="TD16"/><xs:enumeration value="TD17"/>
<xs:enumeration value="TD18"/><xs:enumeration value="TD19"/><xs:enumeration value="TD20"/><xs:enumeration value="TD21"/>
<xs:enumeration value="TD22"/><xs:enumeration value="TD23"/><xs:enumeration value="TD24"/><xs:enumeration value="TD25"/>
<xs:enumeration value="TD26"/><xs:enumeration value="TD27"/><xs:enumeration value="TD28"/><xs:enumeration value="TD29"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="RegimeFiscaleType">
<xs:restriction base="xs:string">
<xs:enumeration value="RF01"/><xs:enumeration value="RF02"/><xs:enumeration value="RF04"/><xs:enumeration value="RF05"/>
<xs:enumeration value="RF06"/><xs:enumeration value="RF07"/><xs:enumeration value="RF08"/><xs:enumeration value="RF09"/>
<xs:enumeration value="RF10"/><xs:enumeration value="RF11"/><xs:enumeration value="RF12"/><xs:enumeration value="RF13"/>
<xs:enumeration value="RF14"/><xs:enumeration value="RF15"/><xs:enumeration value="RF16"/><xs:enumeration value="RF17"/>
<xs:enumeration value="RF18"/><xs:enumeration value="RF19"/><xs:enumeration value="RF20"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="NaturaType">
<xs:restriction base="xs:string">
<xs:enumeration value="N1"/><xs:enumeration value="N2.1"/><xs:enumeration value="N2.2"/><xs:enumeration value="N3.1"/>
<xs:enumeration value="N3.2"/><xs:enumeration value="N3.3"/><xs:enumeration value="N3.4"/><xs:enumeration value="N3.5"/>
<xs:enumeration value="N3.6"/><xs:enumeration value="N4"/><xs:enumeration value="N5"/><xs:enumeration value="N6.1"/>
<xs:enumeration value="N6.2"/><xs:enumeration value="N6.3"/><xs:enumeration value="N6.4"/><xs:enumeration value="N6.5"/>
<xs:enumeration value="N6.6"/><xs:enumeration value="N6.7"/><xs:enumeration value="N6.8"/><xs:enumeration value="N6.9"/>
<xs:enumeration value="N7"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="TipoRitenutaType">
<xs:restriction base="xs:string">
<xs:enumeration value="RT01"/><xs:enumeration value="RT02"/><xs:enumeration value="RT03"/>
<xs:enumeration value="RT04"/><xs:enumeration value="RT05"/><xs:enumeration value="RT06"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="CausalePagamentoType">
<xs:restriction base="xs:string"><xs:pattern value="[A-Z][A-Z0-9]?"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="TipoCassaType">
<xs:restriction base="xs:string"><xs:pattern value="TC(0[1-9]|1[0-9]|2[0-2])"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="ModalitaPagamentoType">
<xs:restriction base="xs:string"><xs:pattern value="MP(0[1-9]|1[0-9]|2[0-3])"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="CondizioniPagamentoType">
<xs:restriction base="xs:string">
<xs:enumeration value="TP01"/><xs:enumeration value="TP02"/><xs:enumeration value="TP03"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="EsigibilitaIVAType">
<xs:restriction base="xs:string">
<xs:enumeration value="D"/><xs:enumeration value="I"/><xs:enumeration value="S"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="TipoScontoMaggiorazioneType">
<xs:restriction base="xs:string"><xs:enumeration value="SC"/><xs:enumeration value="MG"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="TipoCessionePrestazioneType">
<xs:restriction base="xs:string">
<xs:enumeration value="SC"/><xs:enumeration value="PR"/><xs:enumeration value="AB"/><xs:enumeration value="AC"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="SocioUnicoType">
<xs:restriction base="xs:string"><xs:enumeration value="SU"/><xs:enumeration value="SM"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="StatoLiquidazioneType">
<xs:restriction base="xs:string"><xs:enumeration value="LS"/><xs:enumeration value="LN"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="SoggettoEmittenteType">
<xs:restriction base="xs:string"><xs:enumeration value="CC"/><xs:enumeration value="TZ"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="BolloVirtualeType">
<xs:restriction base="xs:string"><xs:enumeration value="SI"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="RitenutaType">
<xs:restriction base="xs:string"><xs:enumeration value="SI"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="Art73Type">
<xs:restriction base="xs:string"><xs:enumeration value="SI"/></xs:restriction>
</xs:simpleType>
<xs:simpleType name="TipoResaType">
<xs:restriction base="xs:string"><xs:pattern value="[A-Z]{3}"/></xs:restriction>
</xs:simpleType>
</xs:schema>
+87 -38
View File
@@ -39,7 +39,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
!content.IsEmpty && (CmsSignedData.LooksLikeCms(content) || LooksLikeXml(content));
/// <inheritdoc />
public IncomingInvoiceFile Read(string fileName, byte[] content)
public EInvoiceFile Read(string fileName, byte[] content)
{
ArgumentNullException.ThrowIfNull(fileName);
ArgumentNullException.ThrowIfNull(content);
@@ -53,7 +53,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, $"The file is larger than {MaxSize / (1024 * 1024)} MB.");
}
IncomingSignature? signature = null;
EInvoiceSignature? signature = null;
var xml = content;
if (!LooksLikeXml(content) && CmsSignedData.LooksLikeCms(content))
{
@@ -69,7 +69,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
xml = envelope.Content;
var signer = envelope.Signer;
signature = new IncomingSignature(
signature = new EInvoiceSignature(
envelope.Verified, signer?.Name, signer?.TaxCode, signer?.SigningTime,
signer?.CertificateNotBefore, signer?.CertificateNotAfter, envelope.Problem);
}
@@ -189,7 +189,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
// --- Ordinary invoice --------------------------------------------------------------------------------------------
private static IncomingInvoiceFile ReadOrdinary(string fileName, XElement root, IncomingSignature? signature, byte[] xml)
private static EInvoiceFile ReadOrdinary(string fileName, XElement root, EInvoiceSignature? signature, byte[] xml)
{
var header = El(root, "FatturaElettronicaHeader")
?? throw Invalid("The invoice has no FatturaElettronicaHeader.");
@@ -202,7 +202,9 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
throw Invalid("The invoice has no FatturaElettronicaBody.");
}
return new IncomingInvoiceFile(
var transmitter = El(transmission, "IdTrasmittente");
var third = El(header, "TerzoIntermediarioOSoggettoEmittente");
return new EInvoiceFile(
fileName,
Text(transmission, "FormatoTrasmissione"),
Text(transmission, "ProgressivoInvio"),
@@ -211,10 +213,18 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
ReadParty(customer),
bodies.Select(ReadBody).ToList(),
signature,
xml);
xml)
{
TransmitterCountry = Text(transmitter, "IdPaese"),
TransmitterId = Text(transmitter, "IdCodice"),
RecipientPec = Text(transmission, "PECDestinatario"),
TransmitterEmail = Text(El(transmission, "ContattiTrasmittente"), "Email"),
Intermediary = third is null ? null : ReadParty(third),
IssuedBy = Text(header, "SoggettoEmittente"),
};
}
private static IncomingParty ReadParty(XElement party)
private static EInvoiceParty ReadParty(XElement party)
{
var personal = El(party, "DatiAnagrafici");
var identifiers = El(party, "IdentificativiFiscali");
@@ -224,7 +234,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
var office = El(party, "Sede") ?? El(others, "Sede");
var register = El(party, "IscrizioneREA");
var contacts = El(party, "Contatti");
return new IncomingParty(
return new EInvoiceParty(
Text(vat, "IdPaese"),
Text(vat, "IdCodice"),
Text(personal, "CodiceFiscale") ?? Text(identifiers, "CodiceFiscale") ?? Text(party, "CodiceFiscale"),
@@ -241,10 +251,16 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
Text(contacts, "Email"),
Text(contacts, "Telefono"),
Text(register, "Ufficio"),
Text(register, "NumeroREA"));
Text(register, "NumeroREA"))
{
ShareCapital = OptionalDecimal(register, "CapitaleSociale"),
Shareholders = Text(register, "SocioUnico"),
LiquidationStatus = Text(register, "StatoLiquidazione"),
AdministrationReference = Text(party, "RiferimentoAmministrazione"),
};
}
private static IncomingInvoice ReadBody(XElement body, int index)
private static EInvoiceBody ReadBody(XElement body, int index)
{
var general = El(body, "DatiGenerali");
var document = El(general, "DatiGeneraliDocumento")
@@ -252,7 +268,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
var goods = El(body, "DatiBeniServizi");
var stamp = El(document, "DatiBollo");
return new IncomingInvoice(
return new EInvoiceBody(
Required(document, "TipoDocumento", index),
Text(document, "Divisa") ?? "EUR",
RequiredDate(document, "Data", index),
@@ -261,13 +277,13 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
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(
Els(document, "DatiRitenuta").Select(w => new EInvoiceWithholding(
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(
stamp is null ? null : new EInvoiceStampDuty(Flag(stamp, "BolloVirtuale"), OptionalDecimal(stamp, "ImportoBollo") ?? 0m),
Els(document, "DatiCassaPrevidenziale").Select(s => new EInvoiceSocialSecurity(
Required(s, "TipoCassa", index),
RequiredDecimal(s, "AlCassa", index),
RequiredDecimal(s, "ImportoContributoCassa", index),
@@ -279,10 +295,10 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
ReadReferences(general, "DatiOrdineAcquisto"),
ReadReferences(general, "DatiContratto"),
ReadReferences(general, "DatiFattureCollegate"),
Els(general, "DatiDDT").Select(d => new IncomingReference(
Els(general, "DatiDDT").Select(d => new EInvoiceReference(
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(
Els(goods, "DatiRiepilogo").Select(r => new EInvoiceTaxSummary(
RequiredDecimal(r, "AliquotaIVA", index),
Text(r, "Natura"),
RequiredDecimal(r, "ImponibileImporto", index),
@@ -292,13 +308,41 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
OptionalDecimal(r, "SpeseAccessorie"),
OptionalDecimal(r, "Arrotondamento"))).ToList(),
ReadPayments(body, index),
ReadAttachments(body));
ReadAttachments(body))
{
Transport = ReadTransport(El(general, "DatiTrasporto")),
PaymentConditions = Text(El(body, "DatiPagamento"), "CondizioniPagamento"),
};
}
private static IncomingLine ReadLine(XElement line, int position, int index) => new(
private static EInvoiceTransport? ReadTransport(XElement? transport)
{
if (transport is null)
{
return null;
}
var carrier = El(transport, "DatiAnagraficiVettore");
var carrierVat = El(carrier, "IdFiscaleIVA");
var start = OptionalDate(transport, "DataInizioTrasporto");
return new EInvoiceTransport(
Text(El(carrier, "Anagrafica"), "Denominazione"),
Text(carrierVat, "IdPaese"),
Text(carrierVat, "IdCodice"),
Text(transport, "MezzoTrasporto"),
Text(transport, "CausaleTrasporto"),
OptionalInt(transport, "NumeroColli"),
Text(transport, "Descrizione"),
OptionalDecimal(transport, "PesoLordo"),
OptionalDecimal(transport, "PesoNetto"),
start?.ToDateTime(TimeOnly.MinValue),
Text(transport, "TipoResa"));
}
private static EInvoiceLine 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))
.Select(c => new EInvoiceItemCode(Text(c, "CodiceTipo") ?? string.Empty, Text(c, "CodiceValore") ?? string.Empty))
.Where(c => c.Value.Length > 0)
.ToList(),
Text(line, "Descrizione") ?? string.Empty,
@@ -313,16 +357,21 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
Text(line, "TipoCessionePrestazione"),
OptionalDate(line, "DataInizioPeriodo"),
OptionalDate(line, "DataFinePeriodo"),
Text(line, "RiferimentoAmministrazione"));
Text(line, "RiferimentoAmministrazione"))
{
OtherData = Els(line, "AltriDatiGestionali")
.Select(d => new EInvoiceOtherData(Text(d, "TipoDato") ?? string.Empty, Text(d, "RiferimentoTesto"), OptionalDecimal(d, "RiferimentoNumero"), OptionalDate(d, "RiferimentoData")))
.ToList(),
};
private static List<IncomingDiscount> ReadDiscounts(XElement? parent) =>
Els(parent, "ScontoMaggiorazione").Select(d => new IncomingDiscount(
private static List<EInvoiceDiscount> ReadDiscounts(XElement? parent) =>
Els(parent, "ScontoMaggiorazione").Select(d => new EInvoiceDiscount(
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(
private static List<EInvoiceReference> ReadReferences(XElement? general, string name) =>
Els(general, name).Select(r => new EInvoiceReference(
Text(r, "IdDocumento"), OptionalDate(r, "Data"), LineNumbers(r), Text(r, "CodiceCIG"), Text(r, "CodiceCUP"))).ToList();
private static List<int> LineNumbers(XElement reference) =>
@@ -331,11 +380,11 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
.Where(n => n > 0)
.ToList();
private static List<IncomingPayment> ReadPayments(XElement body, int index) =>
private static List<EInvoicePayment> ReadPayments(XElement body, int index) =>
Els(body, "DatiPagamento").SelectMany(p =>
{
var conditions = Text(p, "CondizioniPagamento");
return Els(p, "DettaglioPagamento").Select(d => new IncomingPayment(
return Els(p, "DettaglioPagamento").Select(d => new EInvoicePayment(
conditions,
Text(d, "ModalitaPagamento"),
OptionalDate(d, "DataScadenzaPagamento"),
@@ -345,8 +394,8 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
Text(d, "Beneficiario")));
}).ToList();
private static List<IncomingAttachment> ReadAttachments(XElement body) =>
Els(body, "Allegati").Select(a => new IncomingAttachment(
private static List<EInvoiceAttachment> ReadAttachments(XElement body) =>
Els(body, "Allegati").Select(a => new EInvoiceAttachment(
Text(a, "NomeAttachment") ?? "allegato",
Text(a, "FormatoAttachment"),
Text(a, "DescrizioneAttachment"),
@@ -375,7 +424,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
// --- Simplified invoice ------------------------------------------------------------------------------------------
private static IncomingInvoiceFile ReadSimplified(string fileName, XElement root, IncomingSignature? signature, byte[] xml)
private static EInvoiceFile ReadSimplified(string fileName, XElement root, EInvoiceSignature? signature, byte[] xml)
{
var header = El(root, "FatturaElettronicaHeader")
?? throw Invalid("The invoice has no FatturaElettronicaHeader.");
@@ -388,7 +437,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
throw Invalid("The invoice has no FatturaElettronicaBody.");
}
return new IncomingInvoiceFile(
return new EInvoiceFile(
fileName,
Text(transmission, "FormatoTrasmissione"),
Text(transmission, "ProgressivoInvio"),
@@ -400,7 +449,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
xml);
}
private static IncomingInvoice ReadSimplifiedBody(XElement body, int index)
private static EInvoiceBody ReadSimplifiedBody(XElement body, int index)
{
var general = El(body, "DatiGenerali");
var document = El(general, "DatiGeneraliDocumento")
@@ -409,15 +458,15 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
var gross = Els(body, "DatiBeniServizi").Sum(l => RequiredDecimal(l, "Importo", index));
var summary = lines
.GroupBy(l => (l.TaxRate, l.Nature))
.Select(g => new IncomingTaxSummary(
.Select(g => new EInvoiceTaxSummary(
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))
.Select(r => new EInvoiceReference(Text(r, "NumeroFR"), OptionalDate(r, "DataFR"), [], null, null))
.ToList();
return new IncomingInvoice(
return new EInvoiceBody(
Required(document, "TipoDocumento", index),
Text(document, "Divisa") ?? "EUR",
RequiredDate(document, "Data", index),
@@ -427,7 +476,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
[],
false,
[],
Flag(document, "BolloVirtuale") ? new IncomingStampDuty(true, 0m) : null,
Flag(document, "BolloVirtuale") ? new EInvoiceStampDuty(true, 0m) : null,
[],
[],
[],
@@ -451,13 +500,13 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
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,
new EInvoiceLine(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)
private sealed record SimplifiedLine(EInvoiceLine Line, decimal Tax, string? LegalReference)
{
public decimal TaxRate => Line.TaxRate;
@@ -494,7 +543,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
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) =>
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)
@@ -0,0 +1,513 @@
using System.Globalization;
using System.Xml;
using System.Xml.Schema;
using Khaemhat.Core.Validation;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// Checks a FatturaPA before it is sent (SPEC §11.9, issue #74, ADR 0039): the content with the controls of the
/// exchange system that can be made offline, and the XML with the schema of the format.
/// </summary>
/// <remarks>
/// <para>The checks that the SDI documents with a code keep that code (<c>00400</c>, <c>00423</c>...), so the message is
/// the one the user would read in a rejection; the others have a code of Khaemhat (<c>einvoice.*</c>). Checks that need
/// the registers of the Agenzia (a VAT number that exists, a recipient code that is accredited, the office code of an
/// administration in the IPA index) cannot be made offline: only the form of those values is checked.</para>
/// <para>Tolerances follow the specifications: one cent on <c>PrezzoTotale</c> and <c>Imposta</c>, one euro on
/// <c>ImponibileImporto</c>.</para>
/// </remarks>
public sealed class FatturaPaValidator : IEInvoiceValidator
{
private static readonly Lazy<XmlSchemaSet> Schemas = new(LoadSchemas);
private static readonly HashSet<string> GenericNatures = new(StringComparer.Ordinal) { "N2", "N3", "N6" };
// Types where supplier and customer must be different subjects (an integration or self-invoice is issued by the
// customer for a supplier) and types where they must be the same subject (00471, 00472).
private static readonly HashSet<string> DifferentParties = new(StringComparer.Ordinal)
{
"TD01", "TD02", "TD03", "TD06", "TD16", "TD17", "TD18", "TD19", "TD20", "TD24", "TD25", "TD28", "TD29",
};
private static readonly HashSet<string> SameParty = new(StringComparer.Ordinal) { "TD21", "TD27" };
private static readonly HashSet<string> ForeignSupplier = new(StringComparer.Ordinal) { "TD17", "TD18", "TD19", "TD28" };
/// <inheritdoc />
public string RulesVersion => FatturaPaCodeLists.SpecVersion;
/// <inheritdoc />
public IReadOnlyList<EInvoiceProblem> Validate(EInvoiceFile file)
{
ArgumentNullException.ThrowIfNull(file);
var problems = new List<EInvoiceProblem>();
CheckTransmission(file, problems);
CheckSupplier(file.Supplier, problems);
CheckCustomer(file, problems);
for (var i = 0; i < file.Invoices.Count; i++)
{
CheckBody(file, file.Invoices[i], file.Invoices.Count > 1 ? $"FatturaElettronicaBody[{i + 1}]/" : string.Empty, problems);
}
return [.. problems.OrderBy(p => p.Severity)];
}
/// <inheritdoc />
public IReadOnlyList<EInvoiceProblem> ValidateXml(byte[] xml)
{
ArgumentNullException.ThrowIfNull(xml);
var problems = new List<EInvoiceProblem>();
var settings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null,
ValidationType = ValidationType.Schema,
Schemas = Schemas.Value,
};
settings.ValidationEventHandler += (_, e) =>
{
if (problems.Count < 50)
{
problems.Add(new EInvoiceProblem("einvoice.xml.schema", e.Exception?.LineNumber > 0 ? "riga " + e.Exception.LineNumber.ToString(CultureInfo.InvariantCulture) : string.Empty,
e.Message, e.Severity == XmlSeverityType.Error ? EInvoiceProblemSeverity.Error : EInvoiceProblemSeverity.Warning));
}
};
try
{
using var reader = XmlReader.Create(new MemoryStream(xml), settings);
while (reader.Read())
{
}
}
catch (XmlException ex)
{
problems.Add(new EInvoiceProblem("einvoice.xml.malformed", "riga " + ex.LineNumber.ToString(CultureInfo.InvariantCulture), ex.Message));
}
return problems;
}
// --- Header ------------------------------------------------------------------------------------------------------
private static void CheckTransmission(EInvoiceFile file, List<EInvoiceProblem> problems)
{
var format = file.TransmissionFormat;
if (format is not ("FPR12" or "FPA12"))
{
problems.Add(new("einvoice.format", "FormatoTrasmissione", $"Formato di trasmissione {format} non gestito: Khaemhat emette FPR12 e FPA12."));
return;
}
if (string.IsNullOrWhiteSpace(file.TransmitterId))
{
problems.Add(new("einvoice.transmitter", "IdTrasmittente/IdCodice", "Manca l'identificativo fiscale del trasmittente: compila partita IVA o codice fiscale nel profilo dell'azienda."));
}
var code = file.RecipientCode ?? string.Empty;
if (format == "FPA12" && code.Length != 6)
{
problems.Add(new("00427", "CodiceDestinatario", "Per una pubblica amministrazione (FPA12) il codice destinatario è il codice univoco dell'ufficio di 6 caratteri (indice IPA)."));
}
else if (format == "FPR12" && code.Length != 7)
{
problems.Add(new("00427", "CodiceDestinatario", "Per un privato (FPR12) il codice destinatario ha 7 caratteri: 0000000 senza codice, XXXXXXX per l'estero."));
}
else if (!code.All(char.IsAsciiLetterUpper) && !code.All(c => char.IsAsciiLetterUpper(c) || char.IsAsciiDigit(c)))
{
problems.Add(new("00311", "CodiceDestinatario", "Il codice destinatario contiene caratteri non ammessi (solo lettere maiuscole e cifre)."));
}
if (!string.IsNullOrWhiteSpace(file.RecipientPec) && code != FatturaPaCodeLists.RecipientCodeNone)
{
problems.Add(new("00426", "PECDestinatario", "La PEC del destinatario si indica solo con il codice destinatario 0000000."));
}
if (!string.IsNullOrWhiteSpace(file.RecipientPec) && !EmailValidator.IsValid(file.RecipientPec))
{
problems.Add(new("einvoice.recipient.pec", "PECDestinatario", "La PEC del destinatario non è un indirizzo valido."));
}
}
private static void CheckSupplier(EInvoiceParty supplier, List<EInvoiceProblem> problems)
{
const string Path = "CedentePrestatore/";
if (string.IsNullOrWhiteSpace(supplier.VatNumber))
{
problems.Add(new("einvoice.supplier.vat", Path + "IdFiscaleIVA", "Manca la partita IVA del cedente/prestatore."));
}
else if ((supplier.CountryCode ?? "IT") == "IT" && !ItalianVatNumberValidator.IsValid(supplier.VatNumber))
{
problems.Add(new("einvoice.supplier.vat", Path + "IdFiscaleIVA/IdCodice", $"La partita IVA {supplier.VatNumber} del cedente/prestatore non è valida."));
}
if (!string.IsNullOrWhiteSpace(supplier.TaxCode) && !FiscalCodeValidator.IsValid(supplier.TaxCode))
{
problems.Add(new("einvoice.supplier.tax-code", Path + "CodiceFiscale", $"Il codice fiscale {supplier.TaxCode} del cedente/prestatore non è valido."));
}
CheckNames(supplier, Path, problems);
CheckOffice(supplier, Path, problems);
if (supplier.TaxRegime is { } regime && FatturaPaCodeLists.TaxRegimes.Find(regime) is null)
{
problems.Add(new("einvoice.code-list", Path + "RegimeFiscale", $"Il regime fiscale {regime} non è fra quelli ammessi."));
}
if (string.IsNullOrWhiteSpace(supplier.ReaOffice) != string.IsNullOrWhiteSpace(supplier.ReaNumber))
{
problems.Add(new("einvoice.supplier.rea", Path + "IscrizioneREA", "Per l'iscrizione al REA servono ufficio e numero.", EInvoiceProblemSeverity.Warning));
}
}
private static void CheckCustomer(EInvoiceFile file, List<EInvoiceProblem> problems)
{
const string Path = "CessionarioCommittente/";
var customer = file.Customer;
var italian = (customer.CountryCode ?? customer.Country ?? "IT") == "IT";
if (string.IsNullOrWhiteSpace(customer.VatNumber) && string.IsNullOrWhiteSpace(customer.TaxCode))
{
problems.Add(new("00417", Path + "DatiAnagrafici", "Il cessionario/committente non ha né partita IVA né codice fiscale: almeno uno dei due è obbligatorio."));
}
if (italian && !string.IsNullOrWhiteSpace(customer.VatNumber) && !ItalianVatNumberValidator.IsValid(customer.VatNumber))
{
problems.Add(new("00305", Path + "IdFiscaleIVA/IdCodice", $"La partita IVA {customer.VatNumber} del cessionario/committente non è valida."));
}
if (italian && !string.IsNullOrWhiteSpace(customer.TaxCode) && !FiscalCodeValidator.IsValid(customer.TaxCode))
{
problems.Add(new("00306", Path + "CodiceFiscale", $"Il codice fiscale {customer.TaxCode} del cessionario/committente non è valido."));
}
CheckNames(customer, Path, problems);
CheckOffice(customer, Path, problems);
if (!italian && file.RecipientCode != FatturaPaCodeLists.RecipientCodeForeign)
{
problems.Add(new("einvoice.recipient.foreign", "CodiceDestinatario", "Per un cliente estero il codice destinatario è XXXXXXX.", EInvoiceProblemSeverity.Warning));
}
}
private static void CheckNames(EInvoiceParty party, string path, List<EInvoiceProblem> problems)
{
if (string.IsNullOrWhiteSpace(party.Name) && (string.IsNullOrWhiteSpace(party.FirstName) || string.IsNullOrWhiteSpace(party.LastName)))
{
problems.Add(new("einvoice.party.name", path + "Anagrafica", "Serve la denominazione, oppure nome e cognome."));
}
}
private static void CheckOffice(EInvoiceParty party, string path, List<EInvoiceProblem> problems)
{
var country = party.Country ?? party.CountryCode ?? "IT";
if (string.IsNullOrWhiteSpace(party.Address) || string.IsNullOrWhiteSpace(party.City))
{
problems.Add(new("einvoice.party.office", path + "Sede", "Servono indirizzo e comune della sede."));
}
if (country == "IT" && (party.PostalCode is not { Length: 5 } cap || !cap.All(char.IsAsciiDigit)))
{
problems.Add(new("einvoice.party.cap", path + "Sede/CAP", "Il CAP di una sede italiana ha 5 cifre."));
}
if (country == "IT" && party.Province is { Length: > 0 } province && (province.Length != 2 || !province.All(char.IsAsciiLetter)))
{
problems.Add(new("einvoice.party.province", path + "Sede/Provincia", "La provincia si indica con la sigla di due lettere."));
}
}
// --- Body --------------------------------------------------------------------------------------------------------
private static void CheckBody(EInvoiceFile file, EInvoiceBody body, string prefix, List<EInvoiceProblem> problems)
{
var document = prefix + "DatiGeneraliDocumento/";
if (FatturaPaCodeLists.DocumentTypes.Find(body.DocumentType) is null || FatturaPaCodeLists.SimplifiedDocumentTypes.Contains(body.DocumentType))
{
problems.Add(new("einvoice.code-list", document + "TipoDocumento", $"Il tipo documento {body.DocumentType} non è ammesso in una fattura ordinaria."));
}
if (string.IsNullOrWhiteSpace(body.Number) || body.Number.Length > 20 || !body.Number.Any(char.IsAsciiDigit))
{
problems.Add(new("einvoice.number", document + "Numero", "Il numero del documento è obbligatorio, contiene almeno una cifra e non supera 20 caratteri."));
}
if (body.Currency.Length != 3)
{
problems.Add(new("einvoice.currency", document + "Divisa", "La divisa è il codice ISO di 3 lettere."));
}
CheckParties(file, body, problems);
CheckWithholdings(body, document, problems);
CheckDiscounts(body.Discounts, document + "ScontoMaggiorazione", "00437", problems);
CheckReferences(file, body, prefix, problems);
var lines = prefix + "DatiBeniServizi/DettaglioLinee";
if (body.Lines.Count == 0)
{
problems.Add(new("einvoice.lines", lines, "La fattura non ha righe."));
}
foreach (var line in body.Lines)
{
CheckLine(line, $"{lines}[{line.Number}]/", problems);
}
CheckSummary(body, prefix + "DatiBeniServizi/DatiRiepilogo", problems);
CheckPayments(body, prefix + "DatiPagamento", problems);
}
private static void CheckParties(EInvoiceFile file, EInvoiceBody body, List<EInvoiceProblem> problems)
{
var same = SameSubject(file.Supplier, file.Customer);
if (DifferentParties.Contains(body.DocumentType) && same)
{
problems.Add(new("00471", "CedentePrestatore", $"Con il tipo documento {body.DocumentType} cedente/prestatore e cessionario/committente non possono coincidere."));
}
if (SameParty.Contains(body.DocumentType) && !same)
{
problems.Add(new("00472", "CedentePrestatore", $"Con il tipo documento {body.DocumentType} cedente/prestatore e cessionario/committente devono coincidere."));
}
if (ForeignSupplier.Contains(body.DocumentType) && (file.Supplier.CountryCode ?? "IT") == "IT")
{
problems.Add(new("00473", "CedentePrestatore/IdFiscaleIVA/IdPaese", $"Con il tipo documento {body.DocumentType} il cedente/prestatore non può essere residente in Italia."));
}
if (body.DocumentType == "TD28" && file.Supplier.CountryCode != "SM")
{
problems.Add(new("00473", "CedentePrestatore/IdFiscaleIVA/IdPaese", "Con il tipo documento TD28 il cedente/prestatore è di San Marino (SM)."));
}
}
private static bool SameSubject(EInvoiceParty a, EInvoiceParty b)
{
static string Key(EInvoiceParty p) => ((p.CountryCode ?? "IT") + ":" + (p.VatNumber ?? p.TaxCode ?? string.Empty)).Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant();
return !string.IsNullOrWhiteSpace(a.VatNumber ?? a.TaxCode) && Key(a) == Key(b);
}
private static void CheckWithholdings(EInvoiceBody body, string document, List<EInvoiceProblem> problems)
{
if (body.Withholdings.Count == 0 && body.Lines.Any(l => l.Withheld))
{
problems.Add(new("00411", document + "DatiRitenuta", "Ci sono righe soggette a ritenuta ma manca il blocco DatiRitenuta."));
}
if (body.Withholdings.Count == 0 && body.SocialSecurity.Any(s => s.Withheld))
{
problems.Add(new("00415", document + "DatiRitenuta", "Il contributo cassa è soggetto a ritenuta ma manca il blocco DatiRitenuta."));
}
foreach (var withholding in body.Withholdings)
{
if (FatturaPaCodeLists.WithholdingTypes.Find(withholding.Type) is null)
{
problems.Add(new("einvoice.code-list", document + "DatiRitenuta/TipoRitenuta", $"Il tipo di ritenuta {withholding.Type} non è ammesso."));
}
if (withholding.Reason is { } reason && FatturaPaCodeLists.WithholdingReasons.Find(reason) is null)
{
problems.Add(new("einvoice.code-list", document + "DatiRitenuta/CausalePagamento", $"La causale di pagamento {reason} non è ammessa."));
}
}
foreach (var fund in body.SocialSecurity)
{
if (FatturaPaCodeLists.SocialSecurityFunds.Find(fund.Fund) is null)
{
problems.Add(new("einvoice.code-list", document + "DatiCassaPrevidenziale/TipoCassa", $"La cassa {fund.Fund} non è ammessa."));
}
CheckNature(fund.TaxRate, fund.Nature, document + "DatiCassaPrevidenziale/", "00413", "00414", problems);
}
}
private static void CheckDiscounts(IReadOnlyList<EInvoiceDiscount> discounts, string path, string code, List<EInvoiceProblem> problems)
{
if (discounts.Any(d => d.Percent is null && d.Amount is null))
{
problems.Add(new(code, path, "Uno sconto o una maggiorazione non ha né percentuale né importo."));
}
}
private static void CheckReferences(EInvoiceFile file, EInvoiceBody body, string prefix, List<EInvoiceProblem> problems)
{
foreach (var reference in body.Orders.Concat(body.Contracts).Concat(body.RelatedInvoices))
{
if (string.IsNullOrWhiteSpace(reference.Id))
{
problems.Add(new("einvoice.reference.id", prefix + "DatiGenerali", "Un riferimento a ordine, contratto o fattura collegata non ha il numero del documento (IdDocumento)."));
}
if (reference.Cig is { Length: > 0 } cig && (cig.Length != 10 || !cig.All(char.IsAsciiLetterOrDigit)))
{
problems.Add(new("einvoice.reference.cig", prefix + "DatiGenerali/CodiceCIG", $"Il CIG {cig} non ha la forma di 10 caratteri alfanumerici.", EInvoiceProblemSeverity.Warning));
}
if (reference.Cup is { Length: > 0 } cup && (cup.Length != 15 || !cup.All(char.IsAsciiLetterOrDigit)))
{
problems.Add(new("einvoice.reference.cup", prefix + "DatiGenerali/CodiceCUP", $"Il CUP {cup} non ha la forma di 15 caratteri alfanumerici.", EInvoiceProblemSeverity.Warning));
}
}
if (body.DocumentType is "TD04" or "TD05" && body.RelatedInvoices.Count == 0)
{
problems.Add(new("einvoice.reference.related", prefix + "DatiGenerali/DatiFattureCollegate", "Una nota di credito o di debito di solito indica la fattura collegata.", EInvoiceProblemSeverity.Warning));
}
if (file.TransmissionFormat == "FPA12" && body.Orders.Concat(body.Contracts).All(r => string.IsNullOrWhiteSpace(r.Cig)))
{
problems.Add(new("einvoice.reference.pa-cig", prefix + "DatiGenerali", "Fattura verso una pubblica amministrazione senza CIG: indicalo, oppure verifica che il contratto ne sia escluso.", EInvoiceProblemSeverity.Warning));
}
}
private static void CheckLine(EInvoiceLine line, string path, List<EInvoiceProblem> problems)
{
if (string.IsNullOrWhiteSpace(line.Description))
{
problems.Add(new("einvoice.line.description", path + "Descrizione", "La riga non ha descrizione."));
}
if (line.Quantity is < 0m)
{
problems.Add(new("einvoice.line.quantity", path + "Quantita", "La quantità non può essere negativa: il segno va sul prezzo."));
}
CheckNature(line.TaxRate, line.Nature, path, "00400", "00401", problems);
CheckDiscounts(line.Discounts, path + "ScontoMaggiorazione", "00438", problems);
// PrezzoTotale = PrezzoUnitario × Quantita (1 without quantity), less discounts and plus surcharges in order.
var price = line.UnitPrice;
foreach (var discount in line.Discounts)
{
var change = discount.Amount ?? Math.Round(price * (discount.Percent ?? 0m) / 100m, 8, MidpointRounding.AwayFromZero);
price += discount.IsSurcharge ? change : -change;
}
var expected = price * (line.Quantity ?? 1m);
if (Math.Abs(expected - line.TotalPrice) > 0.01m)
{
problems.Add(new("00423", path + "PrezzoTotale",
$"PrezzoTotale {FatturaPaWriter.Amount8(line.TotalPrice)} non è PrezzoUnitario × Quantita al netto degli sconti ({FatturaPaWriter.Amount8(Math.Round(expected, 8))})."));
}
}
private static void CheckNature(decimal rate, string? nature, string path, string missingCode, string presentCode, List<EInvoiceProblem> problems)
{
if (rate == 0m && string.IsNullOrWhiteSpace(nature))
{
problems.Add(new(missingCode, path + "Natura", "Con aliquota IVA zero serve la natura dell'operazione (N1-N7)."));
}
else if (rate != 0m && !string.IsNullOrWhiteSpace(nature))
{
problems.Add(new(presentCode, path + "Natura", "La natura si indica solo con aliquota IVA zero."));
}
else if (nature is { Length: > 0 } && GenericNatures.Contains(nature))
{
problems.Add(new("00445", path + "Natura", $"La natura {nature} non è più ammessa: usa il sotto-codice (per esempio N2.2, N3.1, N6.3)."));
}
else if (nature is { Length: > 0 } && VatNatures.All.Find(nature) is null)
{
problems.Add(new("einvoice.code-list", path + "Natura", $"La natura {nature} non è fra quelle ammesse."));
}
if (rate is < 0m or > 100m)
{
problems.Add(new("einvoice.rate", path + "AliquotaIVA", "L'aliquota IVA è una percentuale fra 0 e 100."));
}
}
private static void CheckSummary(EInvoiceBody body, string path, List<EInvoiceProblem> problems)
{
static (decimal, string) Key(decimal rate, string? nature) => (rate, nature ?? string.Empty);
var rows = body.TaxSummary.GroupBy(r => Key(r.Rate, r.Nature)).ToDictionary(g => g.Key, g => g.ToList());
var lines = body.Lines.GroupBy(l => Key(l.TaxRate, l.Nature)).ToDictionary(g => g.Key, g => g.Sum(l => l.TotalPrice));
foreach (var fund in body.SocialSecurity)
{
var key = Key(fund.TaxRate, fund.Nature);
lines[key] = (lines.TryGetValue(key, out var sum) ? sum : 0m) + fund.Amount;
}
foreach (var (key, total) in lines)
{
if (!rows.TryGetValue(key, out var summary))
{
problems.Add(new("00419", path, $"Manca il riepilogo per l'aliquota {FatturaPaWriter.Rate(key.Item1)}{(key.Item2.Length > 0 ? " natura " + key.Item2 : string.Empty)} usata nelle righe."));
continue;
}
var declared = summary.Sum(r => r.Taxable - (r.Rounding ?? 0m));
var expenses = summary.Sum(r => r.ExpensesAmount ?? 0m);
if (Math.Abs(declared - expenses - total) > 1m)
{
problems.Add(new("00422", path + "/ImponibileImporto",
$"ImponibileImporto {FatturaPaWriter.Amount2(declared)} non corrisponde alla somma delle righe con aliquota {FatturaPaWriter.Rate(key.Item1)} ({FatturaPaWriter.Amount2(total)})."));
}
}
foreach (var row in body.TaxSummary)
{
CheckNature(row.Rate, row.Nature, path + "/", "00429", "00430", problems);
var tax = Math.Round(row.Taxable * row.Rate / 100m, 2, MidpointRounding.AwayFromZero);
if (Math.Abs(tax - row.Tax) > 0.01m)
{
problems.Add(new("00421", path + "/Imposta",
$"Imposta {FatturaPaWriter.Amount2(row.Tax)} non è ImponibileImporto × AliquotaIVA ({FatturaPaWriter.Amount2(tax)})."));
}
if (row.Exigibility is { } exigibility && exigibility is not ("I" or "D" or "S"))
{
problems.Add(new("einvoice.code-list", path + "/EsigibilitaIVA", $"L'esigibilità {exigibility} non è ammessa (I, D, S)."));
}
if (row.Exigibility == "S" && row.Nature is not null)
{
problems.Add(new("einvoice.split.nature", path + "/EsigibilitaIVA", "La scissione dei pagamenti (S) non si applica alle operazioni senza IVA."));
}
if (row.Nature is not null && string.IsNullOrWhiteSpace(row.LegalReference))
{
problems.Add(new("einvoice.summary.legal-reference", path + "/RiferimentoNormativo", $"Per la natura {row.Nature} conviene indicare la norma (RiferimentoNormativo).", EInvoiceProblemSeverity.Warning));
}
}
if (body.StampDuty is null && body.TaxSummary.Where(r => VatNatures.CountsForStampDuty(r.Nature)).Sum(r => r.Taxable) > 77.47m)
{
problems.Add(new("einvoice.stamp-duty", "DatiGeneraliDocumento/DatiBollo",
"Le operazioni senza IVA superano 77,47 euro: di solito è dovuto il bollo virtuale di 2 euro.", EInvoiceProblemSeverity.Warning));
}
}
private static void CheckPayments(EInvoiceBody body, string path, List<EInvoiceProblem> problems)
{
foreach (var payment in body.Payments)
{
if (payment.Method is { } method && FatturaPaCodeLists.PaymentMethods.Find(method) is null)
{
problems.Add(new("einvoice.code-list", path + "/DettaglioPagamento/ModalitaPagamento", $"La modalità di pagamento {method} non è ammessa."));
}
if (payment.Iban is { Length: > 0 } iban && !IbanValidator.IsValid(iban))
{
problems.Add(new("einvoice.payment.iban", path + "/DettaglioPagamento/IBAN", $"L'IBAN {iban} non è valido."));
}
}
if (body.PaymentConditions is { } conditions && FatturaPaCodeLists.PaymentConditions.Find(conditions) is null)
{
problems.Add(new("einvoice.code-list", path + "/CondizioniPagamento", $"La condizione di pagamento {conditions} non è ammessa."));
}
}
private static XmlSchemaSet LoadSchemas()
{
var assembly = typeof(FatturaPaValidator).Assembly;
var name = assembly.GetManifestResourceNames().Single(n => n.EndsWith("FatturaPA_v1.2_khaemhat.xsd", StringComparison.Ordinal));
using var stream = assembly.GetManifestResourceStream(name)!;
var set = new XmlSchemaSet { XmlResolver = null };
using var reader = XmlReader.Create(stream, new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null });
set.Add(FatturaPaWriter.Namespace, reader);
set.Compile();
return set;
}
}
@@ -0,0 +1,655 @@
using System.Globalization;
using System.Text;
using System.Xml;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// Writes FatturaPA files v1.2 (<c>FPR12</c> to businesses and consumers, <c>FPA12</c> to the public administration)
/// following the technical specifications of the Agenzia delle Entrate (<see cref="FatturaPaCodeLists.SpecVersion"/>,
/// SPEC §11.9, ADR 0039).
/// </summary>
/// <remarks>
/// <para>Only the root element is in the namespace of the schema (its <c>elementFormDefault</c> is unqualified); the
/// children follow the order of the schema. Amounts use the dot and the decimals of the schema types: two for
/// totals, from two to eight for prices and quantities. Optional values that are empty are left out.</para>
/// <para>Text fields of the schema accept Basic Latin and Latin-1 only: typographic quotes, dashes and the euro sign are
/// replaced by their plain equivalents, other characters by <c>?</c>, and texts longer than the field are cut. The
/// writer does not check the content: <see cref="FatturaPaValidator"/> does, before the file is written.</para>
/// <para>The simplified invoice <c>FSM10</c> is read (<see cref="FatturaPaReader"/>) but not written: Khaemhat issues
/// ordinary invoices only.</para>
/// </remarks>
public sealed class FatturaPaWriter : IEInvoiceWriter
{
/// <summary>The namespace of FatturaPA v1.2.</summary>
public const string Namespace = "http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2";
private const string DigitsBase36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/// <inheritdoc />
public string FileName(string transmitterCountry, string transmitterId, long progressive)
{
ArgumentException.ThrowIfNullOrWhiteSpace(transmitterCountry);
ArgumentException.ThrowIfNullOrWhiteSpace(transmitterId);
return transmitterCountry.Trim().ToUpperInvariant() + transmitterId.Trim().ToUpperInvariant() + "_" + Progressive(progressive) + ".xml";
}
/// <inheritdoc />
public string Progressive(long progressive)
{
ArgumentOutOfRangeException.ThrowIfLessThan(progressive, 1);
// Five characters of base 36 give 60,466,175 files per transmitter, more than the life of a company.
ArgumentOutOfRangeException.ThrowIfGreaterThan(progressive, 60_466_175);
var text = new char[5];
var value = progressive;
for (var i = text.Length - 1; i >= 0; i--)
{
text[i] = DigitsBase36[(int)(value % 36)];
value /= 36;
}
return new string(text);
}
/// <inheritdoc />
public byte[] Write(EInvoiceFile file)
{
ArgumentNullException.ThrowIfNull(file);
var format = file.TransmissionFormat ?? "FPR12";
if (format is not ("FPR12" or "FPA12"))
{
throw new ArgumentException($"The format {format} is not written: only FPR12 and FPA12.", nameof(file));
}
if (file.Invoices.Count == 0)
{
throw new ArgumentException("The file has no invoice.", nameof(file));
}
using var buffer = new MemoryStream();
var settings = new XmlWriterSettings
{
Encoding = new UTF8Encoding(false),
Indent = true,
IndentChars = " ",
NewLineChars = "\n",
};
using (var xml = XmlWriter.Create(buffer, settings))
{
xml.WriteStartDocument();
xml.WriteStartElement("p", "FatturaElettronica", Namespace);
xml.WriteAttributeString("versione", format);
xml.WriteAttributeString("xmlns", "ds", null, "http://www.w3.org/2000/09/xmldsig#");
xml.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
WriteHeader(xml, file, format);
foreach (var body in file.Invoices)
{
WriteBody(xml, body);
}
xml.WriteEndElement();
xml.WriteEndDocument();
}
return buffer.ToArray();
}
// --- Header ------------------------------------------------------------------------------------------------------
private static void WriteHeader(XmlWriter xml, EInvoiceFile file, string format)
{
xml.WriteStartElement("FatturaElettronicaHeader");
xml.WriteStartElement("DatiTrasmissione");
xml.WriteStartElement("IdTrasmittente");
Element(xml, "IdPaese", file.TransmitterCountry ?? file.Supplier.CountryCode ?? "IT");
Element(xml, "IdCodice", file.TransmitterId ?? file.Supplier.TaxCode ?? file.Supplier.VatNumber ?? string.Empty);
xml.WriteEndElement();
Element(xml, "ProgressivoInvio", file.ProgressiveNumber ?? "00001");
Element(xml, "FormatoTrasmissione", format);
Element(xml, "CodiceDestinatario", file.RecipientCode ?? (format == "FPA12" ? string.Empty : FatturaPaCodeLists.RecipientCodeNone));
if (!string.IsNullOrWhiteSpace(file.TransmitterEmail))
{
xml.WriteStartElement("ContattiTrasmittente");
Element(xml, "Email", Text(file.TransmitterEmail, 256));
xml.WriteEndElement();
}
Optional(xml, "PECDestinatario", file.RecipientPec, 256);
xml.WriteEndElement();
xml.WriteStartElement("CedentePrestatore");
xml.WriteStartElement("DatiAnagrafici");
WriteVat(xml, file.Supplier);
Optional(xml, "CodiceFiscale", file.Supplier.TaxCode, 16);
WriteNames(xml, file.Supplier);
Element(xml, "RegimeFiscale", file.Supplier.TaxRegime ?? "RF01");
xml.WriteEndElement();
WriteOffice(xml, file.Supplier);
if (!string.IsNullOrWhiteSpace(file.Supplier.ReaOffice) && !string.IsNullOrWhiteSpace(file.Supplier.ReaNumber))
{
xml.WriteStartElement("IscrizioneREA");
Element(xml, "Ufficio", file.Supplier.ReaOffice!.Trim().ToUpperInvariant());
Element(xml, "NumeroREA", Text(file.Supplier.ReaNumber, 20));
if (file.Supplier.ShareCapital is { } capital)
{
Element(xml, "CapitaleSociale", Amount2(capital));
}
Optional(xml, "SocioUnico", file.Supplier.Shareholders, 2);
Element(xml, "StatoLiquidazione", file.Supplier.LiquidationStatus ?? "LN");
xml.WriteEndElement();
}
if (!string.IsNullOrWhiteSpace(file.Supplier.Phone) || !string.IsNullOrWhiteSpace(file.Supplier.Email))
{
xml.WriteStartElement("Contatti");
Optional(xml, "Telefono", Phone(file.Supplier.Phone), 12);
Optional(xml, "Email", file.Supplier.Email, 256);
xml.WriteEndElement();
}
Optional(xml, "RiferimentoAmministrazione", file.Supplier.AdministrationReference, 20);
xml.WriteEndElement();
xml.WriteStartElement("CessionarioCommittente");
xml.WriteStartElement("DatiAnagrafici");
if (!string.IsNullOrWhiteSpace(file.Customer.VatNumber))
{
WriteVat(xml, file.Customer);
}
Optional(xml, "CodiceFiscale", file.Customer.TaxCode, 16);
WriteNames(xml, file.Customer);
xml.WriteEndElement();
WriteOffice(xml, file.Customer);
xml.WriteEndElement();
if (file.Intermediary is { } intermediary)
{
xml.WriteStartElement("TerzoIntermediarioOSoggettoEmittente");
xml.WriteStartElement("DatiAnagrafici");
if (!string.IsNullOrWhiteSpace(intermediary.VatNumber))
{
WriteVat(xml, intermediary);
}
Optional(xml, "CodiceFiscale", intermediary.TaxCode, 16);
WriteNames(xml, intermediary);
xml.WriteEndElement();
xml.WriteEndElement();
}
Optional(xml, "SoggettoEmittente", file.IssuedBy, 2);
xml.WriteEndElement();
}
private static void WriteVat(XmlWriter xml, EInvoiceParty party)
{
xml.WriteStartElement("IdFiscaleIVA");
Element(xml, "IdPaese", (party.CountryCode ?? "IT").Trim().ToUpperInvariant());
Element(xml, "IdCodice", Text(party.VatNumber, 28).Replace(" ", string.Empty, StringComparison.Ordinal));
xml.WriteEndElement();
}
private static void WriteNames(XmlWriter xml, EInvoiceParty party)
{
xml.WriteStartElement("Anagrafica");
if (!string.IsNullOrWhiteSpace(party.Name))
{
Element(xml, "Denominazione", Text(party.Name, 80));
}
else
{
Element(xml, "Nome", Text(party.FirstName, 60));
Element(xml, "Cognome", Text(party.LastName, 60));
}
xml.WriteEndElement();
}
private static void WriteOffice(XmlWriter xml, EInvoiceParty party)
{
var country = (party.Country ?? party.CountryCode ?? "IT").Trim().ToUpperInvariant();
xml.WriteStartElement("Sede");
Element(xml, "Indirizzo", Text(party.Address, 60));
Optional(xml, "NumeroCivico", party.StreetNumber, 8);
// A foreign address has no Italian postal code: the specifications ask for 00000 and no province.
Element(xml, "CAP", country == "IT" ? Text(party.PostalCode, 5) : "00000");
Element(xml, "Comune", Text(party.City, 60));
if (country == "IT")
{
Optional(xml, "Provincia", party.Province?.Trim().ToUpperInvariant(), 2);
}
Element(xml, "Nazione", country);
xml.WriteEndElement();
}
// --- Body --------------------------------------------------------------------------------------------------------
private static void WriteBody(XmlWriter xml, EInvoiceBody body)
{
xml.WriteStartElement("FatturaElettronicaBody");
xml.WriteStartElement("DatiGenerali");
WriteDocumentData(xml, body);
WriteReferences(xml, "DatiOrdineAcquisto", body.Orders);
WriteReferences(xml, "DatiContratto", body.Contracts);
WriteReferences(xml, "DatiFattureCollegate", body.RelatedInvoices);
foreach (var note in body.DeliveryNotes)
{
xml.WriteStartElement("DatiDDT");
Element(xml, "NumeroDDT", Text(note.Id, 20));
Element(xml, "DataDDT", Date(note.Date ?? body.Date));
foreach (var line in note.LineNumbers)
{
Element(xml, "RiferimentoNumeroLinea", line.ToString(CultureInfo.InvariantCulture));
}
xml.WriteEndElement();
}
if (body.Transport is { } transport)
{
WriteTransport(xml, transport);
}
xml.WriteEndElement();
xml.WriteStartElement("DatiBeniServizi");
foreach (var line in body.Lines)
{
WriteLine(xml, line);
}
foreach (var row in body.TaxSummary)
{
xml.WriteStartElement("DatiRiepilogo");
Element(xml, "AliquotaIVA", Rate(row.Rate));
Optional(xml, "Natura", row.Nature, 4);
if (row.ExpensesAmount is { } expenses)
{
Element(xml, "SpeseAccessorie", Amount2(expenses));
}
if (row.Rounding is { } rounding)
{
Element(xml, "Arrotondamento", Amount8(rounding));
}
Element(xml, "ImponibileImporto", Amount2(row.Taxable));
Element(xml, "Imposta", Amount2(row.Tax));
Optional(xml, "EsigibilitaIVA", row.Exigibility, 1);
Optional(xml, "RiferimentoNormativo", row.LegalReference, 100);
xml.WriteEndElement();
}
xml.WriteEndElement();
if (body.Payments.Count > 0)
{
xml.WriteStartElement("DatiPagamento");
Element(xml, "CondizioniPagamento", body.PaymentConditions ?? body.Payments[0].Conditions ?? (body.Payments.Count > 1 ? "TP01" : "TP02"));
foreach (var payment in body.Payments)
{
xml.WriteStartElement("DettaglioPagamento");
Optional(xml, "Beneficiario", payment.Beneficiary, 200);
Element(xml, "ModalitaPagamento", payment.Method ?? "MP05");
if (payment.DueDate is { } due)
{
Element(xml, "DataScadenzaPagamento", Date(due));
}
Element(xml, "ImportoPagamento", Amount2(payment.Amount));
Optional(xml, "IBAN", payment.Iban?.Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant(), 34);
Optional(xml, "BIC", payment.Bic?.Trim().ToUpperInvariant(), 11);
xml.WriteEndElement();
}
xml.WriteEndElement();
}
foreach (var attachment in body.Attachments)
{
xml.WriteStartElement("Allegati");
Element(xml, "NomeAttachment", Text(attachment.Name, 60));
Optional(xml, "FormatoAttachment", attachment.Format, 10);
Optional(xml, "DescrizioneAttachment", attachment.Description, 100);
Element(xml, "Attachment", Convert.ToBase64String(attachment.Content));
xml.WriteEndElement();
}
xml.WriteEndElement();
}
private static void WriteDocumentData(XmlWriter xml, EInvoiceBody body)
{
xml.WriteStartElement("DatiGeneraliDocumento");
Element(xml, "TipoDocumento", body.DocumentType);
Element(xml, "Divisa", body.Currency);
Element(xml, "Data", Date(body.Date));
Element(xml, "Numero", Text(body.Number, 20));
foreach (var withholding in body.Withholdings)
{
xml.WriteStartElement("DatiRitenuta");
Element(xml, "TipoRitenuta", withholding.Type);
Element(xml, "ImportoRitenuta", Amount2(withholding.Amount));
Element(xml, "AliquotaRitenuta", Rate(withholding.Rate));
Element(xml, "CausalePagamento", withholding.Reason ?? "A");
xml.WriteEndElement();
}
if (body.StampDuty is { } stamp)
{
xml.WriteStartElement("DatiBollo");
Element(xml, "BolloVirtuale", "SI");
Element(xml, "ImportoBollo", Amount2(stamp.Amount));
xml.WriteEndElement();
}
foreach (var fund in body.SocialSecurity)
{
xml.WriteStartElement("DatiCassaPrevidenziale");
Element(xml, "TipoCassa", fund.Fund);
Element(xml, "AlCassa", Rate(fund.Rate));
Element(xml, "ImportoContributoCassa", Amount2(fund.Amount));
if (fund.Taxable is { } taxable)
{
Element(xml, "ImponibileCassa", Amount2(taxable));
}
Element(xml, "AliquotaIVA", Rate(fund.TaxRate));
if (fund.Withheld)
{
Element(xml, "Ritenuta", "SI");
}
Optional(xml, "Natura", fund.Nature, 4);
xml.WriteEndElement();
}
WriteDiscounts(xml, body.Discounts);
if (body.Total is { } total)
{
Element(xml, "ImportoTotaleDocumento", Amount2(total));
}
if (body.Rounding is { } rounding)
{
Element(xml, "Arrotondamento", Amount2(rounding));
}
foreach (var causal in body.Causals.SelectMany(c => Chunks(c, 200)))
{
Element(xml, "Causale", causal);
}
if (body.Art73)
{
Element(xml, "Art73", "SI");
}
xml.WriteEndElement();
}
private static void WriteReferences(XmlWriter xml, string name, IReadOnlyList<EInvoiceReference> references)
{
foreach (var reference in references)
{
xml.WriteStartElement(name);
foreach (var line in reference.LineNumbers)
{
Element(xml, "RiferimentoNumeroLinea", line.ToString(CultureInfo.InvariantCulture));
}
Element(xml, "IdDocumento", Text(reference.Id, 20));
if (reference.Date is { } date)
{
Element(xml, "Data", Date(date));
}
Optional(xml, "CodiceCUP", reference.Cup, 15);
Optional(xml, "CodiceCIG", reference.Cig, 15);
xml.WriteEndElement();
}
}
private static void WriteTransport(XmlWriter xml, EInvoiceTransport transport)
{
xml.WriteStartElement("DatiTrasporto");
// The carrier is written only with its VAT number, which the schema requires.
if (!string.IsNullOrWhiteSpace(transport.CarrierVat) && !string.IsNullOrWhiteSpace(transport.CarrierName))
{
xml.WriteStartElement("DatiAnagraficiVettore");
xml.WriteStartElement("IdFiscaleIVA");
Element(xml, "IdPaese", transport.CarrierCountry ?? "IT");
Element(xml, "IdCodice", Text(transport.CarrierVat, 28));
xml.WriteEndElement();
xml.WriteStartElement("Anagrafica");
Element(xml, "Denominazione", Text(transport.CarrierName, 80));
xml.WriteEndElement();
xml.WriteEndElement();
}
Optional(xml, "MezzoTrasporto", transport.Means, 80);
Optional(xml, "CausaleTrasporto", transport.Reason, 100);
if (transport.Packages is { } packages and > 0)
{
Element(xml, "NumeroColli", packages.ToString(CultureInfo.InvariantCulture));
}
Optional(xml, "Descrizione", transport.Description, 100);
if (transport.GrossWeight is not null || transport.NetWeight is not null)
{
Element(xml, "UnitaMisuraPeso", "KG");
}
if (transport.GrossWeight is { } gross)
{
Element(xml, "PesoLordo", Weight(gross));
}
if (transport.NetWeight is { } net)
{
Element(xml, "PesoNetto", Weight(net));
}
if (transport.Start is { } start)
{
Element(xml, "DataInizioTrasporto", Date(DateOnly.FromDateTime(start)));
}
Optional(xml, "TipoResa", transport.ShippingTerms, 3);
xml.WriteEndElement();
}
private static void WriteLine(XmlWriter xml, EInvoiceLine line)
{
xml.WriteStartElement("DettaglioLinee");
Element(xml, "NumeroLinea", line.Number.ToString(CultureInfo.InvariantCulture));
Optional(xml, "TipoCessionePrestazione", line.LineType, 2);
foreach (var code in line.Codes)
{
xml.WriteStartElement("CodiceArticolo");
Element(xml, "CodiceTipo", Text(code.Type, 35));
Element(xml, "CodiceValore", Text(code.Value, 35));
xml.WriteEndElement();
}
Element(xml, "Descrizione", Text(line.Description, 1000));
if (line.Quantity is { } quantity)
{
Element(xml, "Quantita", Amount8(Math.Abs(quantity)));
}
Optional(xml, "UnitaMisura", line.Unit, 10);
if (line.PeriodStart is { } from)
{
Element(xml, "DataInizioPeriodo", Date(from));
}
if (line.PeriodEnd is { } to)
{
Element(xml, "DataFinePeriodo", Date(to));
}
Element(xml, "PrezzoUnitario", Amount8(line.UnitPrice));
WriteDiscounts(xml, line.Discounts);
Element(xml, "PrezzoTotale", Amount8(line.TotalPrice));
Element(xml, "AliquotaIVA", Rate(line.TaxRate));
if (line.Withheld)
{
Element(xml, "Ritenuta", "SI");
}
Optional(xml, "Natura", line.Nature, 4);
Optional(xml, "RiferimentoAmministrazione", line.AdministrativeReference, 20);
foreach (var data in line.OtherData)
{
xml.WriteStartElement("AltriDatiGestionali");
Element(xml, "TipoDato", Text(data.Type, 10));
Optional(xml, "RiferimentoTesto", data.Text, 60);
if (data.Number is { } number)
{
Element(xml, "RiferimentoNumero", Amount8(number));
}
if (data.Date is { } date)
{
Element(xml, "RiferimentoData", Date(date));
}
xml.WriteEndElement();
}
xml.WriteEndElement();
}
private static void WriteDiscounts(XmlWriter xml, IReadOnlyList<EInvoiceDiscount> discounts)
{
foreach (var discount in discounts)
{
xml.WriteStartElement("ScontoMaggiorazione");
Element(xml, "Tipo", discount.IsSurcharge ? "MG" : "SC");
if (discount.Percent is { } percent)
{
Element(xml, "Percentuale", Rate(percent));
}
if (discount.Amount is { } amount)
{
Element(xml, "Importo", Amount8(amount));
}
xml.WriteEndElement();
}
}
// --- Values ------------------------------------------------------------------------------------------------------
private static void Element(XmlWriter xml, string name, string value) => xml.WriteElementString(name, value);
private static void Optional(XmlWriter xml, string name, string? value, int maxLength)
{
if (!string.IsNullOrWhiteSpace(value))
{
xml.WriteElementString(name, Text(value, maxLength));
}
}
/// <summary>A text in the characters and length the schema accepts.</summary>
/// <param name="value">The text.</param>
/// <param name="maxLength">The length of the field.</param>
/// <returns>The text, trimmed, in Latin-1 and cut to the length.</returns>
public static string Text(string? value, int maxLength)
{
if (string.IsNullOrWhiteSpace(value))
{
return string.Empty;
}
var text = new StringBuilder(value.Length);
foreach (var c in value.Trim())
{
text.Append(c switch
{
'‘' or '’' or '‚' or '′' => "'",
'“' or '”' or '„' or '″' => "\"",
'–' or '—' or '−' => "-",
'…' => "...",
'€' => "EUR",
' ' or '\t' => " ",
'\r' => string.Empty,
'\n' => " ",
_ when c <= 'ÿ' && !char.IsControl(c) => c.ToString(),
_ => "?",
});
}
var result = text.ToString().Trim();
return result.Length <= maxLength ? result : result[..maxLength].TrimEnd();
}
// The causal is a list of fields of 200 characters: a long note becomes several, cut at a space when possible.
private static IEnumerable<string> Chunks(string value, int size)
{
var text = Text(value, int.MaxValue);
while (text.Length > size)
{
var cut = text.LastIndexOf(' ', size - 1);
if (cut < size / 2)
{
cut = size;
}
yield return text[..cut].TrimEnd();
text = text[cut..].TrimStart();
}
if (text.Length > 0)
{
yield return text;
}
}
private static string? Phone(string? value)
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
var digits = new string(value.Where(c => char.IsAsciiDigit(c) || c == '+').ToArray());
return digits.Length is >= 5 and <= 12 ? digits : null;
}
/// <summary>A date as the schema wants it.</summary>
/// <param name="date">The date.</param>
/// <returns><c>yyyy-MM-dd</c>.</returns>
public static string Date(DateOnly date) => date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
/// <summary>An amount with two decimals (<c>Amount2DecimalType</c>).</summary>
/// <param name="value">The amount.</param>
/// <returns>The text.</returns>
public static string Amount2(decimal value) =>
Math.Round(value, 2, MidpointRounding.AwayFromZero).ToString("0.00", CultureInfo.InvariantCulture);
/// <summary>An amount with two to eight decimals (<c>Amount8DecimalType</c>, <c>QuantitaType</c>).</summary>
/// <param name="value">The amount.</param>
/// <returns>The text.</returns>
public static string Amount8(decimal value) =>
Math.Round(value, 8, MidpointRounding.AwayFromZero).ToString("0.00######", CultureInfo.InvariantCulture);
/// <summary>A rate in percent (<c>RateType</c>).</summary>
/// <param name="value">The rate.</param>
/// <returns>The text with two decimals.</returns>
public static string Rate(decimal value) =>
Math.Round(value, 2, MidpointRounding.AwayFromZero).ToString("0.00", CultureInfo.InvariantCulture);
private static string Weight(decimal value) =>
Math.Round(value, 2, MidpointRounding.AwayFromZero).ToString("0.00", CultureInfo.InvariantCulture);
}
+1 -1
View File
@@ -3,7 +3,7 @@ using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy;
/// <summary>The FatturaPA format: version of the specifications and code lists (writer and reader arrive in M9).</summary>
/// <summary>The FatturaPA format: version of the specifications and code lists (writer, validator and readers are features of their own).</summary>
public sealed class FatturaPaFormat : IEInvoiceFormat
{
/// <inheritdoc />
@@ -18,6 +18,10 @@ public sealed class ItalyFiscalPack : FiscalPackBase
AddFeature<ILatePaymentRules>(new LatePaymentRulesIt());
AddFeature<IRemittanceMethods>(new RemittanceMethodsIt());
AddFeature<IIncomingInvoiceReader>(new FatturaPaReader());
AddFeature<IEInvoiceWriter>(new FatturaPaWriter());
AddFeature<IEInvoiceValidator>(new FatturaPaValidator());
AddFeature<IEInvoiceReceiptReader>(new SdiReceiptReader());
AddFeature<IEInvoiceChannels>(new Sdi.SdiChannels());
AddFeature<IIncomingInvoiceRules>(new IncomingInvoiceRulesIt());
AddFeature<ISelfInvoiceRules>(new SelfInvoiceRulesIt());
AddFeature<IWithholdingRules>(new WithholdingRulesIt());
@@ -7,6 +7,7 @@
<!-- Provinces and municipalities from the ISTAT list (ADR 0028). -->
<ItemGroup>
<EmbeddedResource Include="Data/*.csv" />
<EmbeddedResource Include="Data/*.xsd" />
</ItemGroup>
<ItemGroup>
@@ -0,0 +1,355 @@
using System.Globalization;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy.Sdi;
/// <summary>
/// The common part of the channels through an intermediary (SPEC §11.9, issue #77): an HTTP API that sends files to the
/// SDI on behalf of the company and keeps receipts and supplier invoices until they are acknowledged.
/// </summary>
/// <remarks>The two contracts (<see cref="IntermediaryATransport"/>, <see cref="IntermediaryBTransport"/>) are generic and
/// documented in ADR 0040: they become the API of a real provider once the user chooses one (issue #78), changing only
/// the requests of the derived class.</remarks>
/// <param name="handlerFactory">Makes the HTTP handler (tests); by default a plain handler.</param>
public abstract class IntermediaryTransportBase(Func<EInvoiceChannelSettings, HttpMessageHandler>? handlerFactory) : IEInvoiceTransport
{
/// <summary>JSON with camel-case names.</summary>
protected static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
/// <inheritdoc />
public abstract string Code { get; }
/// <inheritdoc />
public bool Polls => true;
/// <inheritdoc />
public async Task<EInvoiceSendResult> SendAsync(EInvoiceChannelSettings settings, EInvoiceOutgoing file, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(file);
if (Missing(settings) is { } missing)
{
return new EInvoiceSendResult(false, null, null, missing);
}
try
{
using var client = Client(settings);
using var request = SendRequest(settings, file);
using var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false);
var text = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
return new EInvoiceSendResult(false, null, null, $"{(int)response.StatusCode}: {ErrorOf(text)}");
}
var (messageId, exchangeId) = ReadSendAnswer(text);
return new EInvoiceSendResult(true, exchangeId, messageId, null);
}
catch (Exception ex) when (ex is HttpRequestException or JsonException || (ex is TaskCanceledException && !cancellationToken.IsCancellationRequested))
{
return new EInvoiceSendResult(false, null, null, ex.Message);
}
}
/// <inheritdoc />
public async Task<EInvoiceFetchResult> FetchAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
if (Missing(settings) is { } missing)
{
throw new HttpRequestException(missing);
}
using var client = Client(settings);
using var response = await client.SendAsync(FetchRequest(settings), cancellationToken).ConfigureAwait(false);
var text = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException($"{(int)response.StatusCode}: {ErrorOf(text)}");
}
var files = ReadFiles(text);
return new EInvoiceFetchResult(files, files.Select(f => f.MessageKey).Distinct().Count(), null);
}
/// <inheritdoc />
public async Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection<string> messageKeys, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(messageKeys);
using var client = Client(settings);
foreach (var key in messageKeys.Distinct(StringComparer.Ordinal))
{
using var response = await client.SendAsync(AcknowledgeRequest(settings, key), cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode && response.StatusCode != System.Net.HttpStatusCode.NotFound)
{
throw new HttpRequestException($"{(int)response.StatusCode} acknowledging {key}.");
}
}
}
/// <inheritdoc />
public async Task<EInvoiceChannelCheck> CheckAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
if (Missing(settings) is { } missing)
{
return new EInvoiceChannelCheck(false, missing);
}
try
{
using var client = Client(settings);
using var response = await client.SendAsync(CheckRequest(settings), cancellationToken).ConfigureAwait(false);
return response.IsSuccessStatusCode
? new EInvoiceChannelCheck(true, $"{settings.Endpoint} answered {(int)response.StatusCode}: credentials accepted.")
: new EInvoiceChannelCheck(false, $"{settings.Endpoint} answered {(int)response.StatusCode}.");
}
catch (Exception ex) when (ex is HttpRequestException || (ex is TaskCanceledException && !cancellationToken.IsCancellationRequested))
{
return new EInvoiceChannelCheck(false, ex.Message);
}
}
/// <summary>What is missing in the settings, or <see langword="null"/>.</summary>
/// <param name="settings">The settings.</param>
/// <returns>The message.</returns>
protected abstract string? Missing(EInvoiceChannelSettings settings);
/// <summary>The request that sends a file.</summary>
/// <param name="settings">The settings.</param>
/// <param name="file">The file.</param>
/// <returns>The request.</returns>
protected abstract HttpRequestMessage SendRequest(EInvoiceChannelSettings settings, EInvoiceOutgoing file);
/// <summary>Reads the answer to a file sent.</summary>
/// <param name="json">The body.</param>
/// <returns>The identifier at the intermediary and the one of the SDI, if already known.</returns>
protected abstract (string? MessageId, string? ExchangeId) ReadSendAnswer(string json);
/// <summary>The request that lists the waiting files.</summary>
/// <param name="settings">The settings.</param>
/// <returns>The request.</returns>
protected abstract HttpRequestMessage FetchRequest(EInvoiceChannelSettings settings);
/// <summary>Reads the waiting files.</summary>
/// <param name="json">The body.</param>
/// <returns>The files.</returns>
protected abstract IReadOnlyList<EInvoiceIncoming> ReadFiles(string json);
/// <summary>The request that acknowledges a file.</summary>
/// <param name="settings">The settings.</param>
/// <param name="key">The key.</param>
/// <returns>The request.</returns>
protected abstract HttpRequestMessage AcknowledgeRequest(EInvoiceChannelSettings settings, string key);
/// <summary>The request that tests the credentials.</summary>
/// <param name="settings">The settings.</param>
/// <returns>The request.</returns>
protected abstract HttpRequestMessage CheckRequest(EInvoiceChannelSettings settings);
/// <summary>An address under the endpoint.</summary>
/// <param name="settings">The settings.</param>
/// <param name="path">The relative path.</param>
/// <returns>The address.</returns>
protected static Uri Url(EInvoiceChannelSettings settings, string path)
{
ArgumentNullException.ThrowIfNull(settings);
return new Uri(settings.Endpoint!.TrimEnd('/') + "/" + path.TrimStart('/'));
}
/// <summary>A date of the API, or now.</summary>
/// <param name="text">The ISO 8601 text.</param>
/// <returns>The time.</returns>
protected static DateTimeOffset TimeOf(string? text) =>
DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var value) ? value : DateTimeOffset.UtcNow;
private static string ErrorOf(string text)
{
try
{
using var document = JsonDocument.Parse(text);
foreach (var name in new[] { "error", "message", "detail" })
{
if (document.RootElement.ValueKind == JsonValueKind.Object && document.RootElement.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String)
{
return value.GetString()!;
}
}
}
catch (JsonException)
{
}
return text.Length > 200 ? text[..200] : text;
}
private HttpClient Client(EInvoiceChannelSettings settings) =>
new(handlerFactory is null ? new SocketsHttpHandler() : handlerFactory(settings), disposeHandler: true) { Timeout = TimeSpan.FromMinutes(2) };
}
/// <summary>
/// Intermediary A: an API key as bearer token; the file is the body of the request.
/// <list type="bullet">
/// <item><c>POST {endpoint}/invoices</c>, body the file, header <c>X-File-Name</c> → <c>{ "id", "sdiId" }</c>.</item>
/// <item><c>GET {endpoint}/files</c> → <c>[{ "id", "fileName", "content" (base64), "receivedAt" }]</c>.</item>
/// <item><c>POST {endpoint}/files/{id}/ack</c>; <c>GET {endpoint}/status</c>.</item>
/// </list>
/// </summary>
/// <param name="handlerFactory">Makes the HTTP handler (tests).</param>
public sealed class IntermediaryATransport(Func<EInvoiceChannelSettings, HttpMessageHandler>? handlerFactory = null) : IntermediaryTransportBase(handlerFactory)
{
/// <summary>The code of the channel.</summary>
public const string ChannelCode = "INTA";
/// <inheritdoc />
public override string Code => ChannelCode;
/// <inheritdoc />
protected override string? Missing(EInvoiceChannelSettings settings) =>
string.IsNullOrWhiteSpace(settings.Endpoint) || string.IsNullOrWhiteSpace(settings.ApiKey) ? "Intermediary A needs the address of the API and the API key." : null;
/// <inheritdoc />
protected override HttpRequestMessage SendRequest(EInvoiceChannelSettings settings, EInvoiceOutgoing file)
{
var request = Authorized(settings, HttpMethod.Post, "invoices");
request.Content = new ByteArrayContent(file.Content);
request.Content.Headers.ContentType = new MediaTypeHeaderValue(file.FileName.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase) ? "application/pkcs7-mime" : "application/xml");
request.Headers.Add("X-File-Name", file.FileName);
return request;
}
/// <inheritdoc />
protected override (string? MessageId, string? ExchangeId) ReadSendAnswer(string json)
{
var answer = JsonSerializer.Deserialize<SendAnswer>(json, Json);
return (answer?.Id, answer?.SdiId);
}
/// <inheritdoc />
protected override HttpRequestMessage FetchRequest(EInvoiceChannelSettings settings) => Authorized(settings, HttpMethod.Get, "files");
/// <inheritdoc />
protected override IReadOnlyList<EInvoiceIncoming> ReadFiles(string json) =>
(JsonSerializer.Deserialize<List<FileItem>>(json, Json) ?? [])
.Where(f => !string.IsNullOrWhiteSpace(f.Id) && !string.IsNullOrWhiteSpace(f.FileName) && f.Content is not null)
.Select(f => new EInvoiceIncoming(Path.GetFileName(f.FileName!), Convert.FromBase64String(f.Content!), TimeOf(f.ReceivedAt), f.Id!, ChannelCode))
.ToList();
/// <inheritdoc />
protected override HttpRequestMessage AcknowledgeRequest(EInvoiceChannelSettings settings, string key) =>
Authorized(settings, HttpMethod.Post, "files/" + Uri.EscapeDataString(key) + "/ack");
/// <inheritdoc />
protected override HttpRequestMessage CheckRequest(EInvoiceChannelSettings settings) => Authorized(settings, HttpMethod.Get, "status");
private static HttpRequestMessage Authorized(EInvoiceChannelSettings settings, HttpMethod method, string path)
{
var request = new HttpRequestMessage(method, Url(settings, path));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", settings.ApiKey);
return request;
}
private sealed record SendAnswer(string? Id, string? SdiId);
private sealed record FileItem(string? Id, string? FileName, string? Content, string? ReceivedAt);
}
/// <summary>
/// Intermediary B: user and password with basic authentication; the file travels in JSON.
/// <list type="bullet">
/// <item><c>POST {endpoint}/api/v1/send</c> with <c>{ "fileName", "content" }</c> → <c>{ "uploadId", "identificativoSdi" }</c>.</item>
/// <item><c>GET {endpoint}/api/v1/inbox</c> → <c>{ "items": [{ "key", "name", "data" (base64), "date" }] }</c>.</item>
/// <item><c>DELETE {endpoint}/api/v1/inbox/{key}</c>; <c>GET {endpoint}/api/v1/ping</c>.</item>
/// </list>
/// </summary>
/// <param name="handlerFactory">Makes the HTTP handler (tests).</param>
public sealed class IntermediaryBTransport(Func<EInvoiceChannelSettings, HttpMessageHandler>? handlerFactory = null) : IntermediaryTransportBase(handlerFactory)
{
/// <summary>The code of the channel.</summary>
public const string ChannelCode = "INTB";
/// <inheritdoc />
public override string Code => ChannelCode;
/// <inheritdoc />
protected override string? Missing(EInvoiceChannelSettings settings) =>
string.IsNullOrWhiteSpace(settings.Endpoint) || string.IsNullOrWhiteSpace(settings.User) || string.IsNullOrEmpty(settings.Password)
? "Intermediary B needs the address of the API, the user and the password."
: null;
/// <inheritdoc />
protected override HttpRequestMessage SendRequest(EInvoiceChannelSettings settings, EInvoiceOutgoing file)
{
var request = Authorized(settings, HttpMethod.Post, "api/v1/send");
request.Content = new StringContent(JsonSerializer.Serialize(new { fileName = file.FileName, content = Convert.ToBase64String(file.Content) }), Encoding.UTF8, "application/json");
return request;
}
/// <inheritdoc />
protected override (string? MessageId, string? ExchangeId) ReadSendAnswer(string json)
{
var answer = JsonSerializer.Deserialize<SendAnswer>(json, Json);
return (answer?.UploadId, answer?.IdentificativoSdi);
}
/// <inheritdoc />
protected override HttpRequestMessage FetchRequest(EInvoiceChannelSettings settings) => Authorized(settings, HttpMethod.Get, "api/v1/inbox");
/// <inheritdoc />
protected override IReadOnlyList<EInvoiceIncoming> ReadFiles(string json) =>
(JsonSerializer.Deserialize<Inbox>(json, Json)?.Items ?? [])
.Where(f => !string.IsNullOrWhiteSpace(f.Key) && !string.IsNullOrWhiteSpace(f.Name) && f.Data is not null)
.Select(f => new EInvoiceIncoming(Path.GetFileName(f.Name!), Convert.FromBase64String(f.Data!), TimeOf(f.Date), f.Key!, ChannelCode))
.ToList();
/// <inheritdoc />
protected override HttpRequestMessage AcknowledgeRequest(EInvoiceChannelSettings settings, string key) =>
Authorized(settings, HttpMethod.Delete, "api/v1/inbox/" + Uri.EscapeDataString(key));
/// <inheritdoc />
protected override HttpRequestMessage CheckRequest(EInvoiceChannelSettings settings) => Authorized(settings, HttpMethod.Get, "api/v1/ping");
private static HttpRequestMessage Authorized(EInvoiceChannelSettings settings, HttpMethod method, string path)
{
var request = new HttpRequestMessage(method, Url(settings, path));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(settings.User + ":" + settings.Password)));
return request;
}
private sealed record SendAnswer(string? UploadId, string? IdentificativoSdi);
private sealed record Inbox(List<InboxItem>? Items);
private sealed record InboxItem(string? Key, string? Name, string? Data, string? Date);
}
/// <summary>The channels of the Italian pack, in the order of the configuration screen (mockup 059).</summary>
public sealed class SdiChannels : IEInvoiceChannels
{
/// <summary>Creates the channels.</summary>
/// <param name="pec">The PEC channel.</param>
/// <param name="coop">The SdICoop channel.</param>
/// <param name="intermediaryA">Intermediary A.</param>
/// <param name="intermediaryB">Intermediary B.</param>
public SdiChannels(PecSdiTransport? pec = null, SdiCoopTransport? coop = null, IntermediaryATransport? intermediaryA = null, IntermediaryBTransport? intermediaryB = null)
{
All =
[
new EInvoiceChannel(PecSdiTransport.ChannelCode, "PEC", pec ?? new PecSdiTransport()),
new EInvoiceChannel(SdiCoopTransport.ChannelCode, "SdICoop (web service)", coop ?? new SdiCoopTransport()),
new EInvoiceChannel(IntermediaryATransport.ChannelCode, "Intermediario A (API REST)", intermediaryA ?? new IntermediaryATransport()),
new EInvoiceChannel(IntermediaryBTransport.ChannelCode, "Intermediario B (API REST)", intermediaryB ?? new IntermediaryBTransport()),
];
}
/// <inheritdoc />
public IReadOnlyList<EInvoiceChannel> All { get; }
/// <inheritdoc />
public EInvoiceChannel? Find(string code) => All.FirstOrDefault(c => string.Equals(c.Code, code, StringComparison.OrdinalIgnoreCase));
}
@@ -0,0 +1,276 @@
using System.Globalization;
using System.Net.Security;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Infrastructure.Mail;
namespace Khaemhat.Fiscal.Italy.Sdi;
/// <summary>
/// The PEC channel to the SDI (SPEC §11.9, issue #76): files go by certified mail to the address of the SDI
/// (<c>sdi01@pec.fatturapa.it</c> the first time, then the <c>sdiNN</c> address the SDI writes from), receipts and
/// supplier invoices are read from the mailbox by IMAP.
/// </summary>
/// <remarks>
/// <para>Only messages whose sender contains <c>fatturapa.it</c> are read: the acceptance and delivery receipts of the
/// PEC provider stay where they are. The files are the <c>.xml</c> and <c>.p7m</c> attachments of the original message
/// (<c>postacert.eml</c>); <c>daticert.xml</c> and the signature of the provider are ignored.</para>
/// <para>With an archive folder, processed messages are moved there and every message of the SDI still in the inbox is
/// read again at the next poll (the services discard what they already have); without it, messages are marked as read
/// and only unread ones are fetched, so a message opened in webmail before the poll is missed: the archive folder is
/// the recommended setting.</para>
/// </remarks>
/// <param name="clock">The clock (date of the messages sent).</param>
/// <param name="certificateValidation">A custom check of the server certificates (tests only).</param>
public sealed partial class PecSdiTransport(TimeProvider? clock = null, RemoteCertificateValidationCallback? certificateValidation = null) : IEInvoiceTransport
{
/// <summary>The code of the channel.</summary>
public const string ChannelCode = "PEC";
/// <summary>The address of the SDI for the first file.</summary>
public const string FirstAddress = "sdi01@pec.fatturapa.it";
/// <summary>The most messages read in one poll.</summary>
public const int MaxMessages = 200;
private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2);
private readonly TimeProvider _clock = clock ?? TimeProvider.System;
/// <inheritdoc />
public string Code => ChannelCode;
/// <inheritdoc />
public bool Polls => true;
/// <summary>Whether an address is one the SDI writes from (<c>sdiNN@pec.fatturapa.it</c>).</summary>
/// <param name="address">The address, possibly with a display name.</param>
/// <returns>The bare address when it is one, otherwise <see langword="null"/>.</returns>
public static string? SdiAddress(string? address)
{
var match = SdiAddressPattern().Match(address ?? string.Empty);
return match.Success ? match.Value.ToLowerInvariant() : null;
}
/// <inheritdoc />
public async Task<EInvoiceSendResult> SendAsync(EInvoiceChannelSettings settings, EInvoiceOutgoing file, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(file);
if (Missing(settings, smtp: true) is { } missing)
{
return new EInvoiceSendResult(false, null, null, missing);
}
var to = SdiAddress(settings.ExchangeAddress) ?? settings.ExchangeAddress ?? FirstAddress;
var mediaType = file.FileName.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase) ? "application/pkcs7-mime" : "application/xml";
var mail = new OutgoingMail([to], "Invio file " + file.FileName, "File " + file.FileName + (file.Reference is null ? string.Empty : " (" + file.Reference + ")") + ".")
{
Attachments = [new MailAttachment(file.FileName, mediaType, file.Content)],
Reference = file.Reference,
};
try
{
await new SmtpMailSender(Smtp(settings), _clock).SendAsync(mail, cancellationToken).ConfigureAwait(false);
return new EInvoiceSendResult(true, null, null, null);
}
catch (MailException ex)
{
return new EInvoiceSendResult(false, null, null, ex.Message);
}
}
/// <inheritdoc />
public async Task<EInvoiceFetchResult> FetchAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
if (Missing(settings, smtp: false) is { } missing)
{
throw new MailException(missing);
}
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(Timeout);
var token = timeout.Token;
await using var imap = await OpenAsync(settings, token).ConfigureAwait(false);
var criteria = (string.IsNullOrWhiteSpace(settings.ArchiveFolder) ? "UNSEEN " : string.Empty) + "FROM " + ImapClient.Quote("fatturapa.it");
var uids = (await imap.SearchAsync(criteria, token).ConfigureAwait(false)).Take(MaxMessages).ToList();
var files = new List<EInvoiceIncoming>();
var empty = new List<long>();
string? exchange = null;
foreach (var uid in uids)
{
var message = await imap.FetchAsync(uid, token).ConfigureAwait(false);
if (message is null)
{
continue;
}
var (found, sender) = Files(message.Content, uid.ToString(CultureInfo.InvariantCulture), _clock.GetUtcNow());
exchange = SdiAddress(sender) ?? exchange;
if (found.Count == 0)
{
empty.Add(uid);
}
files.AddRange(found);
}
// A message of the SDI with no file (rare: a notice) is done at once.
foreach (var uid in empty)
{
await DoneAsync(imap, settings, uid, token).ConfigureAwait(false);
}
await imap.LogoutAsync(token).ConfigureAwait(false);
var known = SdiAddress(settings.ExchangeAddress);
return new EInvoiceFetchResult(files, uids.Count, exchange is not null && exchange != known ? exchange : null);
}
/// <inheritdoc />
public async Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection<string> messageKeys, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(messageKeys);
var uids = messageKeys.Select(k => long.TryParse(k, NumberStyles.None, CultureInfo.InvariantCulture, out var uid) ? uid : -1).Where(u => u > 0).Distinct().ToList();
if (uids.Count == 0)
{
return;
}
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(Timeout);
await using var imap = await OpenAsync(settings, timeout.Token).ConfigureAwait(false);
foreach (var uid in uids)
{
await DoneAsync(imap, settings, uid, timeout.Token).ConfigureAwait(false);
}
await imap.LogoutAsync(timeout.Token).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<EInvoiceChannelCheck> CheckAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
if (Missing(settings, smtp: true) is { } missing)
{
return new EInvoiceChannelCheck(false, missing);
}
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(30));
try
{
int count;
await using (var imap = await OpenAsync(settings, timeout.Token).ConfigureAwait(false))
{
count = (await imap.SearchAsync("FROM " + ImapClient.Quote("fatturapa.it"), timeout.Token).ConfigureAwait(false)).Count;
await imap.LogoutAsync(timeout.Token).ConfigureAwait(false);
}
using var smtp = new TcpClient();
await smtp.ConnectAsync(settings.SmtpHost!, settings.SmtpPort, timeout.Token).ConfigureAwait(false);
return new EInvoiceChannelCheck(true, $"IMAP {settings.ImapHost}:{settings.ImapPort}: login OK, {count} SDI messages in the inbox; SMTP {settings.SmtpHost}:{settings.SmtpPort}: reachable.");
}
catch (Exception ex) when (ex is MailException or SocketException or IOException || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
{
return new EInvoiceChannelCheck(false, ex.Message);
}
}
/// <summary>
/// The files of the SDI in a message: the <c>.xml</c> and <c>.p7m</c> attachments of the original message of a
/// certified mail (or of the message itself when it is not certified).
/// </summary>
/// <param name="message">The raw message.</param>
/// <param name="key">The key of the message.</param>
/// <param name="now">The time used when the message has no date.</param>
/// <returns>The files and the sender of the original message.</returns>
public static (IReadOnlyList<EInvoiceIncoming> Files, string? Sender) Files(byte[] message, string key, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(message);
var root = MimeParser.Parse(message);
var original = Original(root) ?? root;
var sender = original.Header("from");
var date = DateTimeOffset.TryParse(Strip(original.Header("date")), CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed) ? parsed : now;
var files = original.Attachments()
.Where(a => a.FileName is { } name && IsSdiFile(name))
.Select(a => new EInvoiceIncoming(Path.GetFileName(a.FileName!), a.Body, date, key, SdiAddress(sender) ?? sender))
.ToList();
return (files, sender);
}
private static bool IsSdiFile(string name) =>
(name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase))
&& !name.Equals("daticert.xml", StringComparison.OrdinalIgnoreCase)
&& !name.Equals("smime.p7m", StringComparison.OrdinalIgnoreCase);
// The message enclosed by the PEC provider (postacert.eml), searched in the parts of the envelope.
private static MimePart? Original(MimePart part)
{
if (part.Enclosed is not null)
{
return part.Enclosed;
}
return part.Parts.Select(Original).FirstOrDefault(p => p is not null);
}
// "Thu, 12 Nov 2026 10:15:00 +0100 (CET)": the comment is not part of the date.
private static string? Strip(string? date)
{
if (date is null)
{
return null;
}
var comment = date.IndexOf('(', StringComparison.Ordinal);
return (comment < 0 ? date : date[..comment]).Trim();
}
private static string? Missing(EInvoiceChannelSettings settings, bool smtp)
{
if (string.IsNullOrWhiteSpace(settings.ImapHost) || string.IsNullOrWhiteSpace(settings.User) || string.IsNullOrEmpty(settings.Password))
{
return "The PEC channel needs the IMAP server, the user and the password.";
}
return smtp && (string.IsNullOrWhiteSpace(settings.SmtpHost) || string.IsNullOrWhiteSpace(settings.Mailbox))
? "The PEC channel needs the SMTP server and the address of the mailbox."
: null;
}
private static SmtpSettings Smtp(EInvoiceChannelSettings settings) => new(
settings.SmtpHost,
settings.SmtpPort,
settings.User,
settings.Password,
settings.Mailbox,
!settings.Tls ? SmtpTransportSecurity.None : settings.SmtpPort == 587 ? SmtpTransportSecurity.StartTls : SmtpTransportSecurity.Ssl);
private async Task<ImapClient> OpenAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken)
{
var imap = await ImapClient.ConnectAsync(
new ImapSettings(settings.ImapHost!, settings.ImapPort, settings.Tls, settings.User!, settings.Password!), cancellationToken, certificateValidation).ConfigureAwait(false);
try
{
await imap.LoginAsync(settings.User!, settings.Password!, cancellationToken).ConfigureAwait(false);
await imap.SelectAsync("INBOX", cancellationToken).ConfigureAwait(false);
return imap;
}
catch
{
await imap.DisposeAsync().ConfigureAwait(false);
throw;
}
}
private static Task DoneAsync(ImapClient imap, EInvoiceChannelSettings settings, long uid, CancellationToken cancellationToken) =>
string.IsNullOrWhiteSpace(settings.ArchiveFolder)
? imap.AddFlagsAsync(uid, @"\Seen", cancellationToken)
: imap.MoveAsync(uid, settings.ArchiveFolder.Trim(), cancellationToken);
[GeneratedRegex(@"sdi[0-9]{2}@pec\.fatturapa\.it", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
private static partial Regex SdiAddressPattern();
}
@@ -0,0 +1,322 @@
using System.Globalization;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Infrastructure.Mail;
namespace Khaemhat.Fiscal.Italy.Sdi;
/// <summary>
/// The SdICoop channel (SPEC §11.9, issue #77): files go to the web service <c>SdIRiceviFile</c> of the SDI over SOAP
/// 1.1 with MTOM and the client certificate the Agenzia delle Entrate issues at accreditation; the SDI answers at once
/// with the <c>IdentificativoSdI</c>. Notifications and supplier invoices are pushed by the SDI to the web services of
/// the company (<c>TrasmissioneFatture</c>, <c>RicezioneFatture</c>), read by <see cref="SdiCoopMessages"/>.
/// </summary>
/// <remarks>Ready but meant to be enabled only after the accreditation of the company (issue #78): the endpoints of the
/// company must be published behind a proxy that checks the certificate of the SDI.</remarks>
/// <param name="handlerFactory">Makes the HTTP handler for a channel (tests); by default a handler with the client certificate.</param>
public sealed class SdiCoopTransport(Func<EInvoiceChannelSettings, HttpMessageHandler>? handlerFactory = null) : IEInvoiceTransport
{
/// <summary>The code of the channel.</summary>
public const string ChannelCode = "SDICOOP";
/// <summary>The address of <c>SdIRiceviFile</c> in production.</summary>
public const string ProductionEndpoint = "https://servizi.fatturapa.it/ricevi_file";
/// <summary>The address of <c>SdIRiceviFile</c> in the test environment.</summary>
public const string TestEndpoint = "https://testservizi.fatturapa.it/ricevi_file";
/// <summary>The SOAP action of <c>RiceviFile</c>.</summary>
public const string RiceviFileAction = "http://www.fatturapa.it/SdIRiceviFile/RiceviFile";
private const string TypesNamespace = "http://www.fatturapa.gov.it/sdi/ws/trasmissione/v1.0/types";
/// <inheritdoc />
public string Code => ChannelCode;
/// <inheritdoc />
public bool Polls => false;
/// <summary>The address to send to: the one configured, otherwise the one of the environment.</summary>
/// <param name="settings">The settings.</param>
/// <returns>The address.</returns>
public static string EndpointOf(EInvoiceChannelSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
return !string.IsNullOrWhiteSpace(settings.Endpoint) ? settings.Endpoint.Trim() : settings.TestEnvironment ? TestEndpoint : ProductionEndpoint;
}
/// <inheritdoc />
public async Task<EInvoiceSendResult> SendAsync(EInvoiceChannelSettings settings, EInvoiceOutgoing file, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(file);
if (settings.Certificate is null && handlerFactory is null)
{
return new EInvoiceSendResult(false, null, null, "The SdICoop channel needs the client certificate issued at accreditation.");
}
try
{
using var client = Client(settings);
using var request = new HttpRequestMessage(HttpMethod.Post, EndpointOf(settings)) { Content = Mtom(file) };
request.Headers.Add("SOAPAction", "\"" + RiceviFileAction + "\"");
using var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false);
var body = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
var envelope = SdiCoopMessages.Envelope(response.Content.Headers.ContentType?.ToString(), body);
if (envelope is null)
{
return new EInvoiceSendResult(false, null, null, $"The SDI answered {(int)response.StatusCode} without a SOAP envelope.");
}
var fault = Find(envelope, "faultstring");
if (fault is not null)
{
return new EInvoiceSendResult(false, null, null, "SOAP fault: " + fault);
}
var error = Find(envelope, "Errore");
var id = Find(envelope, "IdentificativoSdI");
return error is not null
? new EInvoiceSendResult(false, id, null, error + " " + ErrorText(error))
: new EInvoiceSendResult(id is not null, id, id, id is null ? "The answer of the SDI has no IdentificativoSdI." : null);
}
catch (Exception ex) when (ex is HttpRequestException or CryptographicException || (ex is TaskCanceledException && !cancellationToken.IsCancellationRequested))
{
return new EInvoiceSendResult(false, null, null, ex.Message);
}
}
/// <inheritdoc />
public Task<EInvoiceFetchResult> FetchAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default) =>
Task.FromResult(new EInvoiceFetchResult([], 0, null));
/// <inheritdoc />
public Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection<string> messageKeys, CancellationToken cancellationToken = default) =>
Task.CompletedTask;
/// <inheritdoc />
public async Task<EInvoiceChannelCheck> CheckAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
if (settings.Certificate is null && handlerFactory is null)
{
return new EInvoiceChannelCheck(false, "The SdICoop channel needs the client certificate issued at accreditation.");
}
try
{
string subject = "(test handler)";
if (settings.Certificate is not null)
{
using var certificate = X509CertificateLoader.LoadPkcs12(settings.Certificate, settings.CertificatePassword);
subject = certificate.Subject + ", valid until " + certificate.NotAfter.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
if (!certificate.HasPrivateKey)
{
return new EInvoiceChannelCheck(false, "The certificate has no private key.");
}
}
// An empty request: the service answers with a SOAP fault, which proves the TLS session with the certificate.
using var client = Client(settings);
using var response = await client.GetAsync(EndpointOf(settings) + "?wsdl", cancellationToken).ConfigureAwait(false);
return new EInvoiceChannelCheck(true, $"Certificate {subject}; {EndpointOf(settings)} answered {(int)response.StatusCode}.");
}
catch (Exception ex) when (ex is HttpRequestException or CryptographicException || (ex is TaskCanceledException && !cancellationToken.IsCancellationRequested))
{
return new EInvoiceChannelCheck(false, ex.Message);
}
}
/// <summary>The meaning of the error codes of <c>RiceviFile</c>.</summary>
/// <param name="code">EI01, EI02 or EI03.</param>
/// <returns>The description.</returns>
public static string ErrorText(string code) => code switch
{
"EI01" => "(empty file)",
"EI02" => "(service not available)",
"EI03" => "(user not enabled)",
_ => string.Empty,
};
// The request as MTOM: the SOAP envelope references the file, sent as a binary part.
private static MultipartContent Mtom(EInvoiceOutgoing file)
{
XNamespace soap = "http://schemas.xmlsoap.org/soap/envelope/";
XNamespace types = TypesNamespace;
XNamespace xop = "http://www.w3.org/2004/08/xop/include";
var envelope = new XElement(
soap + "Envelope",
new XAttribute(XNamespace.Xmlns + "soapenv", soap),
new XAttribute(XNamespace.Xmlns + "typ", types),
new XElement(soap + "Header"),
new XElement(
soap + "Body",
new XElement(
types + "fileSdIAccoglienza",
new XElement("NomeFile", file.FileName),
new XElement("File", new XElement(xop + "Include", new XAttribute(XNamespace.Xmlns + "xop", xop), new XAttribute("href", "cid:file@khaemhat"))))));
var content = new MultipartContent("related", "khaemhat-" + Guid.NewGuid().ToString("N"));
content.Headers.ContentType!.Parameters.Add(new NameValueHeaderValue("type", "\"application/xop+xml\""));
content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("start", "\"<root@khaemhat>\""));
content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("start-info", "\"text/xml\""));
var root = new ByteArrayContent(Encoding.UTF8.GetBytes(envelope.ToString(SaveOptions.DisableFormatting)));
root.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xop+xml; charset=UTF-8; type=\"text/xml\"");
root.Headers.Add("Content-Transfer-Encoding", "8bit");
root.Headers.Add("Content-ID", "<root@khaemhat>");
content.Add(root);
var binary = new ByteArrayContent(file.Content);
binary.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
binary.Headers.Add("Content-Transfer-Encoding", "binary");
binary.Headers.Add("Content-ID", "<file@khaemhat>");
content.Add(binary);
return content;
}
private static string? Find(XElement root, string localName) =>
root.Descendants().FirstOrDefault(e => e.Name.LocalName == localName)?.Value.Trim() is { Length: > 0 } value ? value : null;
private HttpClient Client(EInvoiceChannelSettings settings)
{
if (handlerFactory is not null)
{
return new HttpClient(handlerFactory(settings), disposeHandler: true) { Timeout = TimeSpan.FromMinutes(2) };
}
var handler = new SocketsHttpHandler();
handler.SslOptions.ClientCertificates = [X509CertificateLoader.LoadPkcs12(settings.Certificate!, settings.CertificatePassword)];
return new HttpClient(handler, disposeHandler: true) { Timeout = TimeSpan.FromMinutes(2) };
}
}
/// <summary>A file pushed by the SDI to the web services of the company.</summary>
/// <param name="Operation">The SOAP operation (<c>RicevutaConsegna</c>, <c>RiceviFatture</c>, …).</param>
/// <param name="ExchangeId">The <c>IdentificativoSdI</c>.</param>
/// <param name="Files">The files: the notification, or the invoice and its metadata.</param>
public sealed record SdiCoopInbound(string Operation, string? ExchangeId, IReadOnlyList<(string FileName, byte[] Content)> Files);
/// <summary>
/// Reads the SOAP messages the SDI sends to the company (<c>TrasmissioneFatture</c>: RicevutaConsegna,
/// NotificaMancataConsegna, NotificaScarto, NotificaEsito, NotificaDecorrenzaTermini, AttestazioneTrasmissioneFattura;
/// <c>RicezioneFatture</c>: RiceviFatture, NotificaDecorrenzaTermini) and writes the answers.
/// </summary>
public static class SdiCoopMessages
{
/// <summary>The SOAP envelope of a body, plain or MTOM, with the binary parts put back in place of the references.</summary>
/// <param name="contentType">The content type of the HTTP message.</param>
/// <param name="body">The body.</param>
/// <returns>The envelope, or <see langword="null"/> when the body is not SOAP.</returns>
public static XElement? Envelope(string? contentType, byte[] body)
{
ArgumentNullException.ThrowIfNull(body);
var parts = new Dictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase);
var xml = body;
if (contentType is not null && contentType.Contains("multipart/", StringComparison.OrdinalIgnoreCase))
{
var message = MimeParser.Parse([.. Encoding.ASCII.GetBytes("Content-Type: " + contentType + "\r\n\r\n"), .. body]);
if (message.Parts.Count == 0)
{
return null;
}
xml = message.Parts[0].Body;
foreach (var part in message.Parts.Skip(1))
{
if (part.Header("content-id") is { } id)
{
parts[id.Trim('<', '>', ' ')] = part.Body;
}
}
}
XElement root;
try
{
var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null };
using var reader = XmlReader.Create(new MemoryStream(xml), settings);
root = XDocument.Load(reader).Root!;
}
catch (XmlException)
{
return null;
}
if (root.Name.LocalName != "Envelope")
{
return null;
}
// xop:Include href="cid:..." becomes the base64 of the part, as if the file had been sent inline.
foreach (var include in root.Descendants().Where(e => e.Name.LocalName == "Include").ToList())
{
var href = (string?)include.Attribute("href") ?? string.Empty;
var id = Uri.UnescapeDataString(href.StartsWith("cid:", StringComparison.OrdinalIgnoreCase) ? href[4..] : href);
if (parts.TryGetValue(id, out var bytes) && include.Parent is { } parent)
{
include.Remove();
parent.Value = Convert.ToBase64String(bytes);
}
}
return root;
}
/// <summary>Reads a message of the SDI.</summary>
/// <param name="contentType">The content type of the HTTP message.</param>
/// <param name="body">The body.</param>
/// <returns>The files, or <see langword="null"/> when the message is not one of the SDI.</returns>
public static SdiCoopInbound? Read(string? contentType, byte[] body)
{
var envelope = Envelope(contentType, body);
var request = envelope?.Elements().FirstOrDefault(e => e.Name.LocalName == "Body")?.Elements().FirstOrDefault();
if (request is null)
{
return null;
}
string? Text(string name) => request.Elements().FirstOrDefault(e => e.Name.LocalName == name)?.Value.Trim();
byte[]? Bytes(string name) => Text(name) is { Length: > 0 } text ? MimeParser.Base64(Encoding.ASCII.GetBytes(text)) : null;
var files = new List<(string, byte[])>();
if (Text("NomeFile") is { Length: > 0 } name && Bytes("File") is { } file)
{
files.Add((Path.GetFileName(name), file));
}
if (Text("NomeFileMetadati") is { Length: > 0 } metadataName && Bytes("Metadati") is { } metadata)
{
files.Add((Path.GetFileName(metadataName), metadata));
}
var operation = request.Name.LocalName switch
{
"fileSdIConMetadati" => "RiceviFatture",
"fileSdI" => "Notifica",
_ => request.Name.LocalName,
};
return files.Count == 0 ? null : new SdiCoopInbound(operation, Text("IdentificativoSdI"), files);
}
/// <summary>The answer to a message of the SDI: empty, or <c>esito ER01</c> for <c>RiceviFatture</c>.</summary>
/// <param name="inbound">The message, or <see langword="null"/> when it could not be read.</param>
/// <returns>The SOAP envelope (text/xml).</returns>
public static string Answer(SdiCoopInbound? inbound)
{
const string Soap = "http://schemas.xmlsoap.org/soap/envelope/";
if (inbound is null)
{
return $"<soapenv:Envelope xmlns:soapenv=\"{Soap}\"><soapenv:Body><soapenv:Fault><faultcode>soapenv:Client</faultcode><faultstring>Not a message of the SDI.</faultstring></soapenv:Fault></soapenv:Body></soapenv:Envelope>";
}
var body = inbound.Operation == "RiceviFatture"
? "<typ:rispostaRiceviFatture xmlns:typ=\"http://www.fatturapa.gov.it/sdi/ws/ricezione/v1.0/types\"><Esito>ER01</Esito></typ:rispostaRiceviFatture>"
: string.Empty;
return $"<soapenv:Envelope xmlns:soapenv=\"{Soap}\"><soapenv:Body>{body}</soapenv:Body></soapenv:Envelope>";
}
}
@@ -0,0 +1,120 @@
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// Reads the notifications of the SDI (<c>MessaggiTypes</c> v1.0, SPEC §11.9, issue #75): delivery receipt (RC),
/// rejection (NS), failed delivery (MC), outcome of a public administration (NE, EC01/EC02), terms elapsed (DT),
/// transmission certificate (AT), metadata of a received invoice (MT) and rejection of an outcome (SE).
/// </summary>
/// <remarks>
/// Elements are matched by local name, whatever the prefix; the XAdES signature of the SDI is not checked (the file
/// arrives from the channel the company trusts). The name of a notification is the name of the invoice file followed by
/// the code and a progressive (<c>IT01234567890_00A1Z_RC_001.xml</c>); when the root element is clear the name is not
/// needed.
/// </remarks>
public sealed partial class SdiReceiptReader : IEInvoiceReceiptReader
{
private static readonly Dictionary<string, (EInvoiceReceiptKind Kind, string Code)> Roots = new(StringComparer.Ordinal)
{
["RicevutaConsegna"] = (EInvoiceReceiptKind.Delivered, "RC"),
["NotificaScarto"] = (EInvoiceReceiptKind.Rejected, "NS"),
["NotificaMancataConsegna"] = (EInvoiceReceiptKind.NotDelivered, "MC"),
["NotificaEsito"] = (EInvoiceReceiptKind.Outcome, "NE"),
["NotificaDecorrenzaTermini"] = (EInvoiceReceiptKind.TermsElapsed, "DT"),
["AttestazioneTrasmissioneFattura"] = (EInvoiceReceiptKind.Undeliverable, "AT"),
["FileMetadati"] = (EInvoiceReceiptKind.Metadata, "MT"),
["ScartoEsitoCommittente"] = (EInvoiceReceiptKind.OutcomeRejected, "SE"),
};
/// <summary>The code of a notification in a file name (<c>..._RC_001.xml</c>), or <see langword="null"/>.</summary>
/// <param name="fileName">The name.</param>
/// <returns>The code.</returns>
public static string? CodeOfName(string fileName)
{
var match = NamePattern().Match(Path.GetFileName(fileName ?? string.Empty));
return match.Success ? match.Groups["code"].Value : null;
}
/// <inheritdoc />
public bool IsReceipt(string fileName, ReadOnlySpan<byte> content)
{
if (CodeOfName(fileName) is not null)
{
return true;
}
var head = Encoding.UTF8.GetString(content[..Math.Min(content.Length, 2048)]);
return Roots.Keys.Any(root => head.Contains(":" + root, StringComparison.Ordinal) || head.Contains("<" + root, StringComparison.Ordinal));
}
/// <inheritdoc />
public EInvoiceReceipt Read(string fileName, byte[] content)
{
ArgumentNullException.ThrowIfNull(fileName);
ArgumentNullException.ThrowIfNull(content);
XElement root;
try
{
var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, IgnoreComments = true };
using var reader = XmlReader.Create(new MemoryStream(content), settings);
root = XDocument.Load(reader).Root ?? throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The notification has no root element.");
}
catch (XmlException ex)
{
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotReadable, "The notification is not well formed XML: " + ex.Message, ex);
}
if (!Roots.TryGetValue(root.Name.LocalName, out var kind))
{
throw new IncomingInvoiceException(IncomingInvoiceErrors.NotInvoice, $"The XML is a '{root.Name.LocalName}', not a notification of the SDI.");
}
var outcome = El(root, "EsitoCommittente");
var errors = Els(El(root, "ListaErrori"), "Errore")
.Select(e => new EInvoiceReceiptError(Text(e, "Codice") ?? string.Empty, Text(e, "Descrizione") ?? string.Empty, Text(e, "Suggerimento")))
.ToList();
if (kind.Kind == EInvoiceReceiptKind.OutcomeRejected && Text(root, "Scarto") is { } rejection)
{
errors.Add(new EInvoiceReceiptError(rejection, Text(root, "Descrizione") ?? rejection, null));
}
return new EInvoiceReceipt(
kind.Kind,
kind.Code,
Path.GetFileName(fileName),
Text(root, "NomeFile"),
Text(root, "IdentificativoSdI") ?? Text(outcome, "IdentificativoSdI"),
Time(Text(root, "DataOraRicezione")),
Time(Text(root, "DataOraConsegna")),
Text(outcome, "Esito"),
Text(outcome, "Descrizione") ?? Text(root, "Descrizione") ?? Text(root, "Note"),
errors,
Text(root, "MessageId"),
Text(root, "CodiceDestinatario"),
content);
}
private static DateTimeOffset? Time(string? text) =>
text is not null && DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var value) ? value : null;
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;
}
[GeneratedRegex(@"_(?<code>RC|NS|MC|NE|DT|AT|MT|SE)_[0-9A-Za-z]{1,3}\.xml$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
private static partial Regex NamePattern();
}
@@ -0,0 +1,431 @@
using System.Globalization;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
namespace Khaemhat.Infrastructure.Mail;
/// <summary>The IMAP server of a mailbox (for the PEC of the SDI: implicit TLS on port 993).</summary>
/// <param name="Host">The host.</param>
/// <param name="Port">The port.</param>
/// <param name="Tls">Whether the connection starts with TLS (port 993); <see langword="false"/> only for tests and LAN servers.</param>
/// <param name="User">The user.</param>
/// <param name="Password">The password.</param>
public sealed record ImapSettings(string Host, int Port, bool Tls, string User, string Password)
{
/// <summary>The server without the credentials.</summary>
/// <returns>Host and port.</returns>
public override string ToString() => $"{Host}:{Port}" + (Tls ? " (TLS)" : string.Empty);
}
/// <summary>A message fetched from a mailbox.</summary>
/// <param name="Uid">The unique identifier in the mailbox.</param>
/// <param name="Content">The raw message (RFC 5322).</param>
public sealed record ImapMessage(long Uid, byte[] Content);
/// <summary>
/// An IMAP4rev1 client (RFC 3501) written in house for the PEC channel of the SDI (SPEC §11.9, issue #76): connect with
/// implicit TLS, <c>LOGIN</c>, <c>SELECT</c>, <c>UID SEARCH</c>, <c>UID FETCH BODY.PEEK[]</c> (message read without
/// marking it), <c>UID STORE</c>, <c>UID MOVE</c> or <c>UID COPY</c> + <c>\Deleted</c> + <c>EXPUNGE</c> to archive,
/// <c>CREATE</c> when the archive folder is missing, <c>LOGOUT</c>.
/// </summary>
/// <remarks>One command at a time, no IDLE, no pipelining. Mailbox names must be ASCII (modified UTF-7 is not written).
/// Strings that are not plain ASCII (a password with accents) are sent as literals.</remarks>
public sealed partial class ImapClient : IAsyncDisposable
{
private const int MaxLiteral = 64 * 1024 * 1024;
private const int MaxLine = 1024 * 1024;
private readonly TcpClient _client;
private readonly Stream _stream;
private readonly byte[] _buffer = new byte[16384];
private int _start;
private int _end;
private int _tag;
private ImapClient(TcpClient client, Stream stream)
{
_client = client;
_stream = stream;
}
/// <summary>The capabilities the server announced, in upper case.</summary>
public IReadOnlySet<string> Capabilities { get; private set; } = new HashSet<string>(StringComparer.Ordinal);
/// <summary>Connects and reads the greeting.</summary>
/// <param name="settings">The server.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <param name="certificateValidation">A custom certificate check (tests); the system check when <see langword="null"/>.</param>
/// <returns>The client, not yet logged in.</returns>
public static async Task<ImapClient> ConnectAsync(ImapSettings settings, CancellationToken cancellationToken, RemoteCertificateValidationCallback? certificateValidation = null)
{
ArgumentNullException.ThrowIfNull(settings);
var client = new TcpClient();
try
{
await client.ConnectAsync(settings.Host, settings.Port, cancellationToken).ConfigureAwait(false);
Stream stream = client.GetStream();
if (settings.Tls)
{
var tls = new SslStream(stream, leaveInnerStreamOpen: false);
await tls.AuthenticateAsClientAsync(
new SslClientAuthenticationOptions { TargetHost = settings.Host, RemoteCertificateValidationCallback = certificateValidation },
cancellationToken).ConfigureAwait(false);
stream = tls;
}
var imap = new ImapClient(client, stream);
var greeting = await imap.ReadUntaggedAsync(cancellationToken).ConfigureAwait(false);
if (!greeting.Text.StartsWith("* OK", StringComparison.OrdinalIgnoreCase) && !greeting.Text.StartsWith("* PREAUTH", StringComparison.OrdinalIgnoreCase))
{
throw new MailException("The IMAP server " + settings + " refused the connection: " + greeting.Text);
}
return imap;
}
catch (Exception ex) when (ex is SocketException or IOException or System.Security.Authentication.AuthenticationException)
{
client.Dispose();
throw new MailException("The IMAP server " + settings + " could not be reached: " + ex.Message, ex);
}
catch
{
client.Dispose();
throw;
}
}
/// <summary>Logs in with user and password and reads the capabilities.</summary>
/// <param name="user">The user.</param>
/// <param name="password">The password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task LoginAsync(string user, string password, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(user);
ArgumentNullException.ThrowIfNull(password);
await CapabilityAsync(cancellationToken).ConfigureAwait(false);
if (Capabilities.Contains("LOGINDISABLED"))
{
throw new MailException("The IMAP server does not accept LOGIN on this connection: use TLS (port 993).");
}
var reply = await SendAsync(["LOGIN ", AString(user), " ", AString(password)], cancellationToken, "LOGIN ***").ConfigureAwait(false);
Ensure(reply, "LOGIN ***");
await CapabilityAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Selects a mailbox.</summary>
/// <param name="mailbox">The name (ASCII), such as <c>INBOX</c>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The number of messages in the mailbox.</returns>
public async Task<int> SelectAsync(string mailbox, CancellationToken cancellationToken)
{
var reply = await SendAsync(["SELECT ", Quote(mailbox)], cancellationToken).ConfigureAwait(false);
Ensure(reply, "SELECT " + mailbox);
foreach (var line in reply.Untagged)
{
var match = ExistsPattern().Match(line.Text);
if (match.Success)
{
return int.Parse(match.Groups["n"].Value, CultureInfo.InvariantCulture);
}
}
return 0;
}
/// <summary>Searches the selected mailbox.</summary>
/// <param name="criteria">The criteria, already in IMAP syntax (<c>UNSEEN FROM "fatturapa.it"</c>); see <see cref="Quote"/>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The unique identifiers, ascending.</returns>
public async Task<IReadOnlyList<long>> SearchAsync(string criteria, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(criteria);
var reply = await SendAsync(["UID SEARCH " + criteria], cancellationToken).ConfigureAwait(false);
Ensure(reply, "UID SEARCH");
var uids = new SortedSet<long>();
foreach (var line in reply.Untagged.Where(l => l.Text.StartsWith("* SEARCH", StringComparison.OrdinalIgnoreCase)))
{
foreach (var part in line.Text[8..].Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
if (long.TryParse(part, NumberStyles.None, CultureInfo.InvariantCulture, out var uid))
{
uids.Add(uid);
}
}
}
return [.. uids];
}
/// <summary>Fetches a whole message without marking it as read.</summary>
/// <param name="uid">The unique identifier.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The message, or <see langword="null"/> when it no longer exists.</returns>
public async Task<ImapMessage?> FetchAsync(long uid, CancellationToken cancellationToken)
{
var reply = await SendAsync([$"UID FETCH {uid.ToString(CultureInfo.InvariantCulture)} (UID BODY.PEEK[])"], cancellationToken).ConfigureAwait(false);
Ensure(reply, "UID FETCH");
var fetch = reply.Untagged.FirstOrDefault(l => l.Text.Contains(" FETCH ", StringComparison.OrdinalIgnoreCase) && l.Literals.Count > 0);
return fetch is null ? null : new ImapMessage(uid, fetch.Literals[0]);
}
/// <summary>Adds flags to a message.</summary>
/// <param name="uid">The unique identifier.</param>
/// <param name="flags">The flags, such as <c>\Seen</c>.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task AddFlagsAsync(long uid, string flags, CancellationToken cancellationToken)
{
var reply = await SendAsync([$"UID STORE {uid.ToString(CultureInfo.InvariantCulture)} +FLAGS.SILENT ({flags})"], cancellationToken).ConfigureAwait(false);
Ensure(reply, "UID STORE");
}
/// <summary>Moves a message to another mailbox, creating it when missing.</summary>
/// <param name="uid">The unique identifier.</param>
/// <param name="mailbox">The target (ASCII).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task MoveAsync(long uid, string mailbox, CancellationToken cancellationToken)
{
var id = uid.ToString(CultureInfo.InvariantCulture);
var command = Capabilities.Contains("MOVE") ? "UID MOVE " : "UID COPY ";
var reply = await SendAsync([command + id + " ", Quote(mailbox)], cancellationToken).ConfigureAwait(false);
if (reply.Status == "NO" && reply.Text.Contains("[TRYCREATE]", StringComparison.OrdinalIgnoreCase))
{
Ensure(await SendAsync(["CREATE ", Quote(mailbox)], cancellationToken).ConfigureAwait(false), "CREATE " + mailbox);
reply = await SendAsync([command + id + " ", Quote(mailbox)], cancellationToken).ConfigureAwait(false);
}
Ensure(reply, command.Trim() + " " + mailbox);
if (!Capabilities.Contains("MOVE"))
{
await AddFlagsAsync(uid, @"\Deleted", cancellationToken).ConfigureAwait(false);
var expunge = Capabilities.Contains("UIDPLUS") ? "UID EXPUNGE " + id : "EXPUNGE";
Ensure(await SendAsync([expunge], cancellationToken).ConfigureAwait(false), expunge);
}
}
/// <summary>Logs out (the server closes the connection).</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task LogoutAsync(CancellationToken cancellationToken)
{
try
{
await SendAsync(["LOGOUT"], cancellationToken).ConfigureAwait(false);
}
catch (MailException)
{
// The server may close before the tagged reply: the session is over either way.
}
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
await _stream.DisposeAsync().ConfigureAwait(false);
_client.Dispose();
}
/// <summary>A string in IMAP quoted form (backslash and double quote escaped).</summary>
/// <param name="value">The text (ASCII, no line breaks).</param>
/// <returns>The quoted string.</returns>
public static string Quote(string value)
{
ArgumentNullException.ThrowIfNull(value);
if (value.Any(c => c > 126 || c < 32))
{
throw new MailException("IMAP names and search texts must be printable ASCII: '" + value + "'.");
}
return "\"" + value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal) + "\"";
}
/// <summary>A date in the form of the search keys (<c>SINCE 1-Nov-2026</c>).</summary>
/// <param name="date">The date.</param>
/// <returns>The text.</returns>
public static string SearchDate(DateOnly date) => date.ToString("d-MMM-yyyy", CultureInfo.InvariantCulture);
// A string as quoted text when it is plain ASCII, otherwise as a literal of its UTF-8 bytes.
private static object AString(string value) =>
value.All(c => c is >= ' ' and <= '~') ? Quote(value) : Encoding.UTF8.GetBytes(value);
private static void Ensure(Reply reply, string shown)
{
if (reply.Status != "OK")
{
throw new MailException($"The IMAP server answered {reply.Status} {reply.Text} to {shown}.");
}
}
private async Task CapabilityAsync(CancellationToken cancellationToken)
{
var reply = await SendAsync(["CAPABILITY"], cancellationToken).ConfigureAwait(false);
Ensure(reply, "CAPABILITY");
var line = reply.Untagged.FirstOrDefault(l => l.Text.StartsWith("* CAPABILITY", StringComparison.OrdinalIgnoreCase));
if (line is not null)
{
Capabilities = line.Text[12..].Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(c => c.ToUpperInvariant()).ToHashSet(StringComparer.Ordinal);
}
}
// Sends a command made of text parts and literals (byte arrays, sent after the server's "+" continuation) and reads
// the untagged lines up to the tagged reply.
private async Task<Reply> SendAsync(IReadOnlyList<object> parts, CancellationToken cancellationToken, string? shown = null)
{
var tag = "K" + (++_tag).ToString("D4", CultureInfo.InvariantCulture);
var pending = new StringBuilder(tag).Append(' ');
foreach (var part in parts)
{
if (part is byte[] literal)
{
pending.Append('{').Append(literal.Length.ToString(CultureInfo.InvariantCulture)).Append("}\r\n");
await WriteAsync(pending.ToString(), cancellationToken).ConfigureAwait(false);
pending.Clear();
var go = await ReadUntaggedAsync(cancellationToken).ConfigureAwait(false);
if (!go.Text.StartsWith('+'))
{
throw new MailException($"The IMAP server refused a literal in {shown ?? parts[0]}: {go.Text}");
}
await _stream.WriteAsync(literal, cancellationToken).ConfigureAwait(false);
}
else
{
pending.Append((string)part);
}
}
pending.Append("\r\n");
await WriteAsync(pending.ToString(), cancellationToken).ConfigureAwait(false);
var untagged = new List<Response>();
while (true)
{
var response = await ReadUntaggedAsync(cancellationToken).ConfigureAwait(false);
if (response.Text.StartsWith(tag + " ", StringComparison.Ordinal))
{
var rest = response.Text[(tag.Length + 1)..];
var space = rest.IndexOf(' ', StringComparison.Ordinal);
var status = (space < 0 ? rest : rest[..space]).ToUpperInvariant();
return new Reply(status, space < 0 ? string.Empty : rest[(space + 1)..], untagged);
}
untagged.Add(response);
}
}
private async Task WriteAsync(string text, CancellationToken cancellationToken)
{
await _stream.WriteAsync(Encoding.UTF8.GetBytes(text), cancellationToken).ConfigureAwait(false);
await _stream.FlushAsync(cancellationToken).ConfigureAwait(false);
}
// One response: a line, and when it ends with {n} the n bytes that follow and the rest of the line, repeated.
private async Task<Response> ReadUntaggedAsync(CancellationToken cancellationToken)
{
var text = new StringBuilder();
var literals = new List<byte[]>();
while (true)
{
var line = await ReadLineAsync(cancellationToken).ConfigureAwait(false);
text.Append(line);
var match = LiteralPattern().Match(line);
if (!match.Success)
{
return new Response(text.ToString(), literals);
}
var length = long.Parse(match.Groups["n"].Value, CultureInfo.InvariantCulture);
if (length > MaxLiteral)
{
throw new MailException($"The IMAP server sent a literal of {length} bytes, more than {MaxLiteral}.");
}
literals.Add(await ReadExactAsync((int)length, cancellationToken).ConfigureAwait(false));
}
}
private async Task<string> ReadLineAsync(CancellationToken cancellationToken)
{
using var line = new MemoryStream();
while (true)
{
if (_start == _end)
{
await FillAsync(cancellationToken).ConfigureAwait(false);
}
var index = Array.IndexOf(_buffer, (byte)'\n', _start, _end - _start);
if (index < 0)
{
line.Write(_buffer, _start, _end - _start);
_start = _end;
if (line.Length > MaxLine)
{
throw new MailException("The IMAP server sent a line longer than " + MaxLine + " bytes.");
}
continue;
}
line.Write(_buffer, _start, index - _start);
_start = index + 1;
return Encoding.UTF8.GetString(line.GetBuffer(), 0, (int)line.Length).TrimEnd('\r');
}
}
private async Task<byte[]> ReadExactAsync(int length, CancellationToken cancellationToken)
{
var result = new byte[length];
var written = 0;
while (written < length)
{
if (_start == _end)
{
await FillAsync(cancellationToken).ConfigureAwait(false);
}
var take = Math.Min(length - written, _end - _start);
Array.Copy(_buffer, _start, result, written, take);
_start += take;
written += take;
}
return result;
}
private async Task FillAsync(CancellationToken cancellationToken)
{
int read;
try
{
read = await _stream.ReadAsync(_buffer, cancellationToken).ConfigureAwait(false);
}
catch (IOException ex)
{
throw new MailException("The IMAP connection failed: " + ex.Message, ex);
}
if (read == 0)
{
throw new MailException("The IMAP server closed the connection.");
}
_start = 0;
_end = read;
}
[GeneratedRegex(@"\{(?<n>[0-9]{1,10})\+?\}$", RegexOptions.CultureInvariant)]
private static partial Regex LiteralPattern();
[GeneratedRegex(@"^\* (?<n>[0-9]+) EXISTS", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
private static partial Regex ExistsPattern();
private sealed record Response(string Text, IReadOnlyList<byte[]> Literals);
private sealed record Reply(string Status, string Text, IReadOnlyList<Response> Untagged);
}
@@ -0,0 +1,541 @@
using System.Globalization;
using System.Text;
namespace Khaemhat.Infrastructure.Mail;
/// <summary>A part of a MIME message: headers and body, or the parts of a multipart, or an enclosed message.</summary>
public sealed class MimePart
{
/// <summary>The headers, names in lower case; repeated headers keep the first value.</summary>
public required IReadOnlyDictionary<string, string> Headers { get; init; }
/// <summary>The media type in lower case, such as <c>multipart/mixed</c> or <c>application/xml</c>.</summary>
public required string MediaType { get; init; }
/// <summary>The parameters of <c>Content-Type</c> (boundary, charset, name), names in lower case.</summary>
public required IReadOnlyDictionary<string, string> TypeParameters { get; init; }
/// <summary>The decoded body (transfer encoding removed); empty for a multipart.</summary>
public byte[] Body { get; init; } = [];
/// <summary>The parts of a multipart.</summary>
public IReadOnlyList<MimePart> Parts { get; init; } = [];
/// <summary>The message enclosed in a <c>message/rfc822</c> part.</summary>
public MimePart? Enclosed { get; init; }
/// <summary>The file name, from <c>Content-Disposition</c> or <c>Content-Type</c>, decoded.</summary>
public string? FileName { get; init; }
/// <summary>A header by name.</summary>
/// <param name="name">The name, any case.</param>
/// <returns>The value, decoded, or <see langword="null"/>.</returns>
public string? Header(string name) => Headers.TryGetValue(name.ToLowerInvariant(), out var value) ? value : null;
/// <summary>The body as text, in its charset (UTF-8 when not declared).</summary>
/// <returns>The text.</returns>
public string Text() => MimeParser.CharsetOf(TypeParameters.TryGetValue("charset", out var charset) ? charset : null).GetString(Body);
/// <summary>Every part with a file name, also inside multiparts and enclosed messages, in order.</summary>
/// <returns>The attachments.</returns>
public IEnumerable<MimePart> Attachments()
{
if (FileName is not null && Parts.Count == 0 && Enclosed is null)
{
yield return this;
}
foreach (var part in Parts)
{
foreach (var attachment in part.Attachments())
{
yield return attachment;
}
}
if (Enclosed is not null)
{
foreach (var attachment in Enclosed.Attachments())
{
yield return attachment;
}
}
}
}
/// <summary>
/// Reads MIME messages (RFC 5322, 2045-2047, 2231) written in house for the PEC channel of the SDI (SPEC §11.9,
/// issue #76): headers with folded lines and encoded words, multiparts at any depth, enclosed messages
/// (<c>message/rfc822</c>, the <c>postacert.eml</c> of a certified mail), bodies in base64, quoted-printable, 7bit and
/// 8bit, file names in <c>filename</c>, <c>filename*</c> and <c>name</c>.
/// </summary>
/// <remarks>Malformed input does not throw: a part whose boundary never closes ends with the message, a broken base64
/// body is decoded as far as it goes. Nesting is limited to 10 levels.</remarks>
public static class MimeParser
{
private const int MaxDepth = 10;
/// <summary>Parses a message.</summary>
/// <param name="message">The raw message.</param>
/// <returns>The root part.</returns>
public static MimePart Parse(byte[] message)
{
ArgumentNullException.ThrowIfNull(message);
return ParsePart(message, 0, message.Length, 0);
}
/// <summary>The encoding of a charset name, UTF-8 when unknown.</summary>
/// <param name="charset">The name.</param>
/// <returns>The encoding.</returns>
public static Encoding CharsetOf(string? charset)
{
switch (charset?.Trim().Trim('"').ToLowerInvariant())
{
case null or "" or "utf-8" or "utf8" or "us-ascii" or "ascii":
return new UTF8Encoding(false);
case "iso-8859-1" or "latin1":
return Encoding.Latin1;
case "windows-1252" or "cp1252":
return CodePagesEncodingProvider.Instance.GetEncoding(1252) ?? Encoding.Latin1;
case "iso-8859-15":
return CodePagesEncodingProvider.Instance.GetEncoding(28605) ?? Encoding.Latin1;
default:
try
{
return Encoding.GetEncoding(charset!.Trim().Trim('"'));
}
catch (ArgumentException)
{
return new UTF8Encoding(false);
}
}
}
/// <summary>Decodes the encoded words of a header (<c>=?utf-8?B?...?=</c>, <c>=?iso-8859-1?Q?...?=</c>).</summary>
/// <param name="value">The raw value.</param>
/// <returns>The text.</returns>
public static string DecodeHeader(string value)
{
ArgumentNullException.ThrowIfNull(value);
var text = new StringBuilder();
var position = 0;
var lastWasEncoded = false;
while (position < value.Length)
{
var start = value.IndexOf("=?", position, StringComparison.Ordinal);
var decoded = start < 0 ? null : TryDecodeWord(value, start, out var end, out var word) ? (end, word) : ((int, string)?)null;
if (decoded is null)
{
var next = start < 0 ? value.Length : start + 2;
text.Append(value, position, next - position);
position = next;
lastWasEncoded = false;
continue;
}
// White space between two encoded words is not part of the text (RFC 2047 §6.2).
var between = value[position..start];
if (!(lastWasEncoded && string.IsNullOrWhiteSpace(between)))
{
text.Append(between);
}
text.Append(decoded.Value.Item2);
position = decoded.Value.Item1;
lastWasEncoded = true;
}
return text.ToString();
}
private static bool TryDecodeWord(string value, int start, out int end, out string word)
{
end = start;
word = string.Empty;
var q1 = value.IndexOf('?', start + 2);
var q2 = q1 < 0 ? -1 : value.IndexOf('?', q1 + 1);
var close = q2 < 0 ? -1 : value.IndexOf("?=", q2 + 1, StringComparison.Ordinal);
if (close < 0)
{
return false;
}
var charset = value[(start + 2)..q1];
var star = charset.IndexOf('*', StringComparison.Ordinal);
if (star >= 0)
{
charset = charset[..star];
}
var mode = value[(q1 + 1)..q2].ToUpperInvariant();
var payload = value[(q2 + 1)..close];
byte[] bytes;
if (mode == "B")
{
bytes = Base64(Encoding.ASCII.GetBytes(payload));
}
else if (mode == "Q")
{
bytes = QuotedPrintable(Encoding.ASCII.GetBytes(payload.Replace('_', ' ')));
}
else
{
return false;
}
word = CharsetOf(charset).GetString(bytes);
end = close + 2;
return true;
}
// --- Parts -------------------------------------------------------------------------------------------------------
private static MimePart ParsePart(byte[] data, int start, int end, int depth)
{
var (headers, bodyStart) = ReadHeaders(data, start, end);
var (mediaType, parameters) = ContentType(headers.TryGetValue("content-type", out var type) ? type : "text/plain");
var disposition = headers.TryGetValue("content-disposition", out var d) ? Parameters(d) : new Dictionary<string, string>(StringComparer.Ordinal);
var fileName = disposition.GetValueOrDefault("filename") ?? parameters.GetValueOrDefault("name");
if (mediaType.StartsWith("multipart/", StringComparison.Ordinal) && parameters.TryGetValue("boundary", out var boundary) && depth < MaxDepth)
{
return new MimePart
{
Headers = headers,
MediaType = mediaType,
TypeParameters = parameters,
Parts = SplitMultipart(data, bodyStart, end, boundary).Select(p => ParsePart(data, p.Start, p.End, depth + 1)).ToList(),
FileName = fileName,
};
}
var body = Decode(data, bodyStart, end, headers.TryGetValue("content-transfer-encoding", out var encoding) ? encoding : null);
if (mediaType == "message/rfc822" && depth < MaxDepth)
{
return new MimePart
{
Headers = headers,
MediaType = mediaType,
TypeParameters = parameters,
Body = body,
Enclosed = ParsePart(body, 0, body.Length, depth + 1),
FileName = fileName,
};
}
return new MimePart { Headers = headers, MediaType = mediaType, TypeParameters = parameters, Body = body, FileName = fileName };
}
private static (Dictionary<string, string> Headers, int BodyStart) ReadHeaders(byte[] data, int start, int end)
{
var headers = new Dictionary<string, string>(StringComparer.Ordinal);
var position = start;
string? name = null;
var value = new StringBuilder();
void Flush()
{
if (name is not null && !headers.ContainsKey(name))
{
headers[name] = DecodeHeader(value.ToString().Trim());
}
name = null;
value.Clear();
}
while (position < end)
{
var lineEnd = IndexOf(data, (byte)'\n', position, end);
var next = lineEnd < 0 ? end : lineEnd + 1;
var line = Encoding.Latin1.GetString(data, position, (lineEnd < 0 ? end : lineEnd) - position).TrimEnd('\r');
position = next;
if (line.Length == 0)
{
Flush();
return (headers, position);
}
if ((line[0] == ' ' || line[0] == '\t') && name is not null)
{
value.Append(' ').Append(line.Trim());
continue;
}
Flush();
var colon = line.IndexOf(':', StringComparison.Ordinal);
if (colon > 0)
{
name = line[..colon].Trim().ToLowerInvariant();
value.Append(line[(colon + 1)..]);
}
}
Flush();
return (headers, end);
}
private static List<(int Start, int End)> SplitMultipart(byte[] data, int start, int end, string boundary)
{
var delimiter = Encoding.ASCII.GetBytes("--" + boundary);
var parts = new List<(int, int)>();
int? partStart = null;
var position = start;
while (position < end)
{
var lineEnd = IndexOf(data, (byte)'\n', position, end);
var contentEnd = lineEnd < 0 ? end : lineEnd;
var next = lineEnd < 0 ? end : lineEnd + 1;
if (StartsWith(data, position, contentEnd, delimiter))
{
var rest = Encoding.ASCII.GetString(data, position + delimiter.Length, contentEnd - position - delimiter.Length).TrimEnd('\r', ' ', '\t');
if (rest is "" or "--")
{
if (partStart is { } open)
{
// The line break before the delimiter belongs to the delimiter.
var close = position;
if (close > open && data[close - 1] == '\n')
{
close--;
}
if (close > open && data[close - 1] == '\r')
{
close--;
}
parts.Add((open, close));
}
if (rest == "--")
{
return parts;
}
partStart = next;
}
}
position = next;
}
if (partStart is { } last && last < end)
{
parts.Add((last, end));
}
return parts;
}
private static byte[] Decode(byte[] data, int start, int end, string? encoding)
{
var slice = data.AsSpan(start, Math.Max(0, end - start)).ToArray();
return encoding?.Trim().ToLowerInvariant() switch
{
"base64" => Base64(slice),
"quoted-printable" => QuotedPrintable(slice),
_ => slice,
};
}
/// <summary>Decodes base64, ignoring line breaks and stopping at the first character that is not base64.</summary>
/// <param name="text">The encoded bytes.</param>
/// <returns>The decoded bytes.</returns>
public static byte[] Base64(byte[] text)
{
ArgumentNullException.ThrowIfNull(text);
var clean = new StringBuilder(text.Length);
foreach (var b in text)
{
var c = (char)b;
if (char.IsAsciiLetterOrDigit(c) || c is '+' or '/' or '=')
{
clean.Append(c);
}
}
var value = clean.ToString().TrimEnd('=');
value = (value.Length % 4) switch
{
2 => value + "==",
3 => value + "=",
1 => value[..^1],
_ => value,
};
var buffer = new byte[value.Length / 4 * 3 + 3];
return Convert.TryFromBase64String(value, buffer, out var written) ? buffer[..written] : [];
}
/// <summary>Decodes quoted-printable (soft line breaks removed).</summary>
/// <param name="text">The encoded bytes.</param>
/// <returns>The decoded bytes.</returns>
public static byte[] QuotedPrintable(byte[] text)
{
ArgumentNullException.ThrowIfNull(text);
using var output = new MemoryStream(text.Length);
for (var i = 0; i < text.Length; i++)
{
var b = text[i];
if (b != '=')
{
output.WriteByte(b);
continue;
}
if (i + 1 < text.Length && text[i + 1] == '\n')
{
i++;
continue;
}
if (i + 2 < text.Length && text[i + 1] == '\r' && text[i + 2] == '\n')
{
i += 2;
continue;
}
if (i + 2 < text.Length && byte.TryParse(Encoding.ASCII.GetString(text, i + 1, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var value))
{
output.WriteByte(value);
i += 2;
continue;
}
output.WriteByte(b);
}
return output.ToArray();
}
private static (string MediaType, Dictionary<string, string> Parameters) ContentType(string value)
{
var semicolon = value.IndexOf(';', StringComparison.Ordinal);
var mediaType = (semicolon < 0 ? value : value[..semicolon]).Trim().ToLowerInvariant();
return (mediaType.Length == 0 ? "text/plain" : mediaType, Parameters(value));
}
// The parameters after the first ';': name=value, name="quoted value", and RFC 2231 name*=charset''encoded and
// name*0=..., name*1=... continuations, joined.
private static Dictionary<string, string> Parameters(string value)
{
var raw = new List<(string Name, string Value)>();
var position = value.IndexOf(';', StringComparison.Ordinal);
while (position >= 0 && position < value.Length)
{
position++;
var equals = value.IndexOf('=', position);
if (equals < 0)
{
break;
}
var name = value[position..equals].Trim().ToLowerInvariant();
position = equals + 1;
while (position < value.Length && value[position] == ' ')
{
position++;
}
string parameter;
if (position < value.Length && value[position] == '"')
{
var close = position + 1;
var quoted = new StringBuilder();
while (close < value.Length && value[close] != '"')
{
if (value[close] == '\\' && close + 1 < value.Length)
{
close++;
}
quoted.Append(value[close]);
close++;
}
parameter = quoted.ToString();
position = value.IndexOf(';', Math.Min(close + 1, value.Length));
}
else
{
var semicolon = value.IndexOf(';', position);
parameter = (semicolon < 0 ? value[position..] : value[position..semicolon]).Trim();
position = semicolon;
}
raw.Add((name, parameter));
}
var result = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var group in raw.GroupBy(p => p.Name.Split('*')[0]))
{
var extended = group.Where(p => p.Name.Contains('*', StringComparison.Ordinal)).ToList();
if (extended.Count == 0)
{
result[group.Key] = DecodeHeader(group.First().Value);
continue;
}
var ordered = extended
.OrderBy(p => int.TryParse(p.Name.Split('*').ElementAtOrDefault(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) ? n : 0)
.ToList();
var charset = "utf-8";
var bytes = new List<byte>();
foreach (var (name, part) in ordered)
{
var text = part;
if (name.EndsWith('*'))
{
var first = text.IndexOf('\'', StringComparison.Ordinal);
var second = first < 0 ? -1 : text.IndexOf('\'', first + 1);
if (second > first)
{
if (first > 0)
{
charset = text[..first];
}
text = text[(second + 1)..];
}
bytes.AddRange(PercentDecode(text));
}
else
{
bytes.AddRange(Encoding.UTF8.GetBytes(text));
}
}
result[group.Key] = CharsetOf(charset).GetString(bytes.ToArray());
}
return result;
}
private static byte[] PercentDecode(string text)
{
var output = new List<byte>(text.Length);
for (var i = 0; i < text.Length; i++)
{
if (text[i] == '%' && i + 2 < text.Length && byte.TryParse(text.AsSpan(i + 1, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var value))
{
output.Add(value);
i += 2;
}
else
{
output.AddRange(Encoding.UTF8.GetBytes(text[i].ToString()));
}
}
return [.. output];
}
private static int IndexOf(byte[] data, byte value, int start, int end)
{
var index = Array.IndexOf(data, value, start, end - start);
return index;
}
private static bool StartsWith(byte[] data, int start, int end, byte[] prefix) =>
end - start >= prefix.Length && data.AsSpan(start, prefix.Length).SequenceEqual(prefix);
}
@@ -277,7 +277,7 @@ else
private string ShownTitle => _shown is { } shown ? shown.File.Supplier.DisplayName + " · " + shown.Invoice.Number : T["Purchases.Import.View"];
private IReadOnlyList<KhStat> SummaryOf(IncomingInvoice invoice) =>
private IReadOnlyList<KhStat> SummaryOf(EInvoiceBody invoice) =>
[
new(T["Sales.Totals.Taxable"], T.Money(invoice.TaxSummary.Sum(t => t.Taxable))),
new(T["Sales.Totals.Tax"], T.Money(invoice.TaxSummary.Sum(t => t.Tax))),