diff --git a/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs b/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs
index 19bff2a..0dc30e0 100644
--- a/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs
+++ b/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs
@@ -26,7 +26,7 @@ namespace Khaemhat.Application.Purchases;
/// Taxable plus tax of the summary, plus rounding: what the total should be.
/// What stops or warns (resource codes).
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 Problems)
{
/// Whether it can be registered.
@@ -141,7 +141,7 @@ public sealed class PurchaseInvoiceImportService
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var reader = pack.GetFeature();
var rules = pack.GetFeature();
- var found = new List<(string Name, IncomingInvoiceFile File)>();
+ var found = new List<(string Name, EInvoiceFile File)>();
var rejected = new List();
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 FindSupplierAsync(IUnitOfWork uow, IncomingParty party, CancellationToken cancellationToken)
+ private static async Task FindSupplierAsync(IUnitOfWork uow, EInvoiceParty party, CancellationToken cancellationToken)
{
var parties = uow.Repository();
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 IsDuplicateAsync(IUnitOfWork uow, long supplierId, IncomingInvoice invoice, CancellationToken cancellationToken)
+ private static async Task 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 CreateSupplierAsync(Actor actor, string company, IncomingParty party, CancellationToken cancellationToken)
+ private async Task 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 bySupplierCode, Dictionary byBarcode, Dictionary byCode)
+ private static long? ItemOf(EInvoiceLine line, Dictionary bySupplierCode, Dictionary byBarcode, Dictionary byCode)
{
foreach (var code in line.Codes.Select(c => c.Value.Trim()))
{
diff --git a/src/Khaemhat.Fiscal.Abstractions/EInvoices.cs b/src/Khaemhat.Fiscal.Abstractions/EInvoices.cs
new file mode 100644
index 0000000..2901975
--- /dev/null
+++ b/src/Khaemhat.Fiscal.Abstractions/EInvoices.cs
@@ -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.
+
+/// An e-invoice file: the transmission header, the two parties and one or more invoices.
+/// The name of the file, as received or as it will be sent.
+/// The transmission format (Italy: FPR12, FPA12, FSM10).
+/// The progressive number of the transmission given by the sender.
+/// The recipient code of the transmission.
+/// The supplier who issued the invoices.
+/// The customer the invoices are addressed to (normally the company).
+/// The invoices, one per body of the file (a batch has more than one).
+/// The signature of the envelope, or for an unsigned file.
+/// The XML of the invoice, taken out of the envelope when the file was signed.
+public sealed record EInvoiceFile(
+ string FileName, string? TransmissionFormat, string? ProgressiveNumber, string? RecipientCode,
+ EInvoiceParty Supplier, EInvoiceParty Customer, IReadOnlyList Invoices,
+ EInvoiceSignature? Signature, byte[] Xml)
+{
+ /// The country of the transmitter (Italy: IdTrasmittente/IdPaese).
+ public string? TransmitterCountry { get; init; }
+
+ /// The tax identifier of the transmitter (Italy: IdTrasmittente/IdCodice).
+ public string? TransmitterId { get; init; }
+
+ /// The certified mailbox the invoice is delivered to, when there is no recipient code.
+ public string? RecipientPec { get; init; }
+
+ /// The e-mail of the transmitter, for the exchange system (Italy: ContattiTrasmittente/Email).
+ public string? TransmitterEmail { get; init; }
+
+ /// The third party that issues the invoice for the supplier, if any (Italy: TerzoIntermediarioOSoggettoEmittente).
+ public EInvoiceParty? Intermediary { get; init; }
+
+ /// Who issues the document when not the supplier (Italy: SoggettoEmittente, CC customer, TZ third party).
+ public string? IssuedBy { get; init; }
+}
+
+///
+/// The signature of a signed file. 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.
+///
+/// Whether the digest and the signature match the content.
+/// The name of the signer, from the certificate.
+/// The tax code of the signer, when the certificate carries it.
+/// The signing time declared by the signer, if any (not a trusted timestamp).
+/// The start of validity of the certificate.
+/// The end of validity of the certificate.
+/// Why the signature is not verified, or .
+public sealed record EInvoiceSignature(bool Verified, string? Signer, string? SignerTaxCode, DateTimeOffset? SignedAt,
+ DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, string? Problem);
+
+/// A party of the invoice (supplier, customer or intermediary) as written in the file.
+/// The country of the VAT number.
+/// The VAT number without the country prefix.
+/// The tax code.
+/// The company name, when the party is a company.
+/// The first name, when the party is a person.
+/// The last name, when the party is a person.
+/// The street of the registered office.
+/// The street number.
+/// The postal code.
+/// The city.
+/// The province.
+/// The country of the registered office.
+/// The tax regime (supplier only).
+/// The e-mail address (supplier only).
+/// The phone number (supplier only).
+/// The office of the companies register.
+/// The number in the companies register.
+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)
+{
+ /// The company name, or first and last name of a person.
+ public string DisplayName => Name ?? string.Join(' ', new[] { FirstName, LastName }.Where(s => !string.IsNullOrWhiteSpace(s)));
+
+ /// The share capital, for a company in the companies register.
+ public decimal? ShareCapital { get; init; }
+
+ /// One or more shareholders (Italy: SU sole, SM several).
+ public string? Shareholders { get; init; }
+
+ /// Whether the company is being wound up (Italy: LS yes, LN no).
+ public string? LiquidationStatus { get; init; }
+
+ /// The reference of the administration, for the public administration (Italy: RiferimentoAmministrazione).
+ public string? AdministrationReference { get; init; }
+}
+
+/// An invoice of the file (one body).
+/// The document type (Italy: TD01, TD04...).
+/// The currency code.
+/// The date of the document.
+/// The number of the document.
+/// The total amount declared by the supplier, if any.
+/// The rounding on the total, if any.
+/// The free-text causals.
+/// 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).
+/// The withholding taxes.
+/// The stamp duty, if any.
+/// The social security contributions.
+/// The discounts and surcharges on the whole document.
+/// The purchase orders referred to.
+/// The contracts referred to.
+/// The invoices referred to (the invoice a credit note corrects).
+/// The delivery notes referred to.
+/// The lines.
+/// The tax summary, one row per rate or nature.
+/// The payment installments.
+/// The attached files.
+public sealed record EInvoiceBody(
+ string DocumentType, string Currency, DateOnly Date, string Number, decimal? Total, decimal? Rounding,
+ IReadOnlyList Causals, bool Art73,
+ IReadOnlyList Withholdings, EInvoiceStampDuty? StampDuty,
+ IReadOnlyList SocialSecurity, IReadOnlyList Discounts,
+ IReadOnlyList Orders, IReadOnlyList Contracts,
+ IReadOnlyList RelatedInvoices, IReadOnlyList DeliveryNotes,
+ IReadOnlyList Lines, IReadOnlyList TaxSummary,
+ IReadOnlyList Payments, IReadOnlyList Attachments)
+{
+ /// The transport data of an accompanying invoice, if any.
+ public EInvoiceTransport? Transport { get; init; }
+
+ /// The payment conditions of the whole document (Italy: TP01, TP02, TP03).
+ public string? PaymentConditions { get; init; }
+}
+
+/// The transport data of an accompanying invoice (Italy: DatiTrasporto).
+/// The carrier.
+/// The country of the VAT number of the carrier.
+/// The VAT number of the carrier.
+/// The means of transport.
+/// The reason of the transport.
+/// The number of packages.
+/// The appearance of the goods.
+/// The gross weight, kg.
+/// The net weight, kg.
+/// When the transport starts.
+/// The terms of delivery (Incoterms).
+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);
+
+/// A line of an invoice.
+/// The line number.
+/// The item codes (type and value).
+/// The description.
+/// The quantity, if given.
+/// The unit of measure, if given.
+/// The unit price.
+/// The total of the line, net of tax.
+/// The tax rate in percent (zero with a nature).
+/// The reason of a zero rate (Italy: N2.2...).
+/// The discounts and surcharges of the line.
+/// Whether the line is subject to withholding tax.
+/// The kind of line (Italy: SC discount, PR premium, AB rebate,
+/// AC ancillary cost).
+/// The start of the period the line refers to.
+/// The end of the period the line refers to.
+/// The administrative reference (cost centre, internal code).
+public sealed record EInvoiceLine(
+ int Number, IReadOnlyList Codes, string Description, decimal? Quantity, string? Unit,
+ decimal UnitPrice, decimal TotalPrice, decimal TaxRate, string? Nature, IReadOnlyList Discounts,
+ bool Withheld, string? LineType, DateOnly? PeriodStart, DateOnly? PeriodEnd, string? AdministrativeReference)
+{
+ /// Further data of the line (Italy: AltriDatiGestionali, such as the declaration of intent).
+ public IReadOnlyList OtherData { get; init; } = [];
+}
+
+/// Further data of a line (Italy: AltriDatiGestionali).
+/// The kind of data (Italy: TipoDato, such as INTENTO).
+/// A text value.
+/// A number value.
+/// A date value.
+public sealed record EInvoiceOtherData(string Type, string? Text, decimal? Number, DateOnly? Date);
+
+/// A code of the item of a line.
+/// The kind of code (EAN, SKU, the supplier's code...).
+/// The code.
+public sealed record EInvoiceItemCode(string Type, string Value);
+
+/// A discount or surcharge.
+/// Whether it is a surcharge (Italy: MG) instead of a discount (SC).
+/// The percentage, if given.
+/// The amount, if given.
+public sealed record EInvoiceDiscount(bool IsSurcharge, decimal? Percent, decimal? Amount);
+
+/// A row of the tax summary.
+/// The tax rate in percent.
+/// The reason of a zero rate.
+/// The taxable amount.
+/// The tax.
+/// When the tax is due (Italy: I immediate, D deferred, S split payment).
+/// The law that justifies the nature.
+/// Ancillary expenses, if any.
+/// The rounding, if any.
+public sealed record EInvoiceTaxSummary(decimal Rate, string? Nature, decimal Taxable, decimal Tax, string? Exigibility,
+ string? LegalReference, decimal? ExpensesAmount, decimal? Rounding);
+
+/// A payment installment.
+/// The payment conditions (Italy: TP01 installments, TP02 full, TP03 advance).
+/// The payment method (Italy: MP05 bank transfer...).
+/// The due date, if given.
+/// The amount.
+/// The IBAN to pay to, if given.
+/// The BIC, if given.
+/// The beneficiary, if different from the supplier.
+public sealed record EInvoicePayment(string? Conditions, string? Method, DateOnly? DueDate, decimal Amount,
+ string? Iban, string? Bic, string? Beneficiary);
+
+/// A reference to another document (order, contract, invoice, delivery note).
+/// The number of the document.
+/// The date of the document.
+/// The lines of the invoice the reference applies to; empty when it applies to all.
+/// The tender code, if any (public administration).
+/// The project code, if any (public administration).
+public sealed record EInvoiceReference(string? Id, DateOnly? Date, IReadOnlyList LineNumbers, string? Cig, string? Cup);
+
+/// A withholding tax.
+/// The kind of withholding (Italy: RT01...).
+/// The amount withheld.
+/// The rate in percent.
+/// The payment reason (Italy: A...), if given.
+public sealed record EInvoiceWithholding(string Type, decimal Amount, decimal Rate, string? Reason);
+
+/// The stamp duty of an invoice.
+/// Whether it is paid virtually by the issuer.
+/// The amount.
+public sealed record EInvoiceStampDuty(bool Virtual, decimal Amount);
+
+/// A social security contribution added to the invoice.
+/// The fund (Italy: TC01...).
+/// The rate of the contribution in percent.
+/// The amount of the contribution.
+/// The amount the contribution is computed on, if given.
+/// The tax rate applied to the contribution.
+/// Whether the contribution is subject to withholding tax.
+/// The reason of a zero tax rate.
+public sealed record EInvoiceSocialSecurity(string Fund, decimal Rate, decimal Amount, decimal? Taxable, decimal TaxRate,
+ bool Withheld, string? Nature);
+
+/// A file attached to the invoice.
+/// The name of the attachment.
+/// The format declared by the supplier (such as PDF), if any.
+/// The description, if any.
+/// The decoded content.
+public sealed record EInvoiceAttachment(string Name, string? Format, string? Description, byte[] Content);
+
diff --git a/src/Khaemhat.Fiscal.Abstractions/EInvoicing.cs b/src/Khaemhat.Fiscal.Abstractions/EInvoicing.cs
new file mode 100644
index 0000000..f787af3
--- /dev/null
+++ b/src/Khaemhat.Fiscal.Abstractions/EInvoicing.cs
@@ -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.
+
+/// Writes the e-invoice file of the country's format (Italy: FatturaPA FPR12/FPA12).
+public interface IEInvoiceWriter
+{
+ /// The name of the file to send (Italy: IT01234567890_00A1Z.xml).
+ /// The country of the transmitter.
+ /// The tax identifier of the transmitter.
+ /// The progressive number of the file for this transmitter, from 1.
+ /// The file name.
+ string FileName(string transmitterCountry, string transmitterId, long progressive);
+
+ /// The progressive written in the file for a progressive number (Italy: base 36, five characters).
+ /// The progressive number, from 1.
+ /// The text.
+ string Progressive(long progressive);
+
+ /// Writes the file.
+ /// The content; and are ignored.
+ /// The XML, UTF-8.
+ byte[] Write(EInvoiceFile file);
+}
+
+/// How serious a problem found by is.
+public enum EInvoiceProblemSeverity
+{
+ /// The exchange system would reject the file: it is not sent.
+ Error = 0,
+
+ /// The file is accepted but something looks wrong.
+ Warning = 1,
+}
+
+/// A problem of an e-invoice found before sending.
+/// The code: the check of the exchange system when there is one (Italy: 00423), else a
+/// text code of Khaemhat (einvoice.xml.schema).
+/// Where: the element of the format, such as DettaglioLinee[2]/PrezzoTotale.
+/// What is wrong, in the language of the format's documentation (Italian for FatturaPA).
+/// Error or warning.
+public sealed record EInvoiceProblem(string Code, string Path, string Message, EInvoiceProblemSeverity Severity = EInvoiceProblemSeverity.Error);
+
+/// Checks an e-invoice before it leaves: the rules of the exchange system and the schema of the format.
+public interface IEInvoiceValidator
+{
+ /// The version of the rules checked, shown with the results.
+ string RulesVersion { get; }
+
+ /// The checks on the content: code lists, lengths, totals, natures, recipient, references.
+ /// The file content.
+ /// The problems, errors first; empty when the file can be sent.
+ IReadOnlyList Validate(EInvoiceFile file);
+
+ /// The checks on the XML: well formed and valid against the schema of the format.
+ /// The file.
+ /// The problems; empty when the file is valid.
+ IReadOnlyList ValidateXml(byte[] xml);
+}
+
+/// What a receipt of the exchange system says (Italy: the SDI notifications).
+public enum EInvoiceReceiptKind
+{
+ /// Delivered to the customer (Italy: RC ricevuta di consegna).
+ Delivered = 0,
+
+ /// Rejected by the exchange system: the invoice is not issued (Italy: NS notifica di scarto).
+ Rejected = 1,
+
+ /// Not delivered, made available to the customer (Italy: MC mancata consegna).
+ NotDelivered = 2,
+
+ /// The outcome of a public administration: accepted or refused (Italy: NE notifica di esito).
+ Outcome = 3,
+
+ /// The public administration did not answer in time (Italy: DT decorrenza termini).
+ TermsElapsed = 4,
+
+ /// Sent to a public administration that could not receive it (Italy: AT attestazione).
+ Undeliverable = 5,
+
+ /// The metadata that go with a received invoice (Italy: MT file metadati).
+ Metadata = 6,
+
+ /// The exchange system rejected the outcome the company sent (Italy: SE scarto esito).
+ OutcomeRejected = 7,
+}
+
+/// An error listed in a rejection.
+/// The code (Italy: 00311).
+/// The description given by the exchange system.
+/// The suggestion given with it, if any.
+public sealed record EInvoiceReceiptError(string Code, string Description, string? Hint);
+
+/// A receipt or notification of the exchange system about one file.
+/// What it says.
+/// The short code of the format (Italy: RC, NS...).
+/// The name of the receipt file.
+/// The name of the invoice file it is about.
+/// The identifier the exchange system gave to the invoice file (Italy: IdentificativoSdI).
+/// When the exchange system received the invoice file.
+/// When it was delivered, for a delivery receipt.
+/// The outcome of the administration (Italy: EC01 accepted, EC02 refused).
+/// The free text of the notification.
+/// The errors of a rejection.
+/// The identifier of the message.
+/// The recipient code, for the metadata of a received invoice.
+/// The file as received.
+public sealed record EInvoiceReceipt(
+ EInvoiceReceiptKind Kind, string Code, string FileName, string? InvoiceFileName, string? ExchangeId,
+ DateTimeOffset? ReceivedAt, DateTimeOffset? DeliveredAt, string? Outcome, string? Description,
+ IReadOnlyList Errors, string? MessageId, string? RecipientCode, byte[] Content)
+{
+ /// Whether an outcome says the administration refused the invoice.
+ public bool Refused => Kind == EInvoiceReceiptKind.Outcome && string.Equals(Outcome, "EC02", StringComparison.Ordinal);
+}
+
+/// Reads the receipts of the exchange system (Italy: SDI notifications, MessaggiTypes v1.0).
+public interface IEInvoiceReceiptReader
+{
+ /// Whether a file is a receipt, by its name or its root element.
+ /// The name of the file.
+ /// The content.
+ /// when is worth trying.
+ bool IsReceipt(string fileName, ReadOnlySpan content);
+
+ /// Reads a receipt.
+ /// The name of the file.
+ /// The content.
+ /// The receipt.
+ /// The file is not a receipt.
+ EInvoiceReceipt Read(string fileName, byte[] content);
+}
+
+///
+/// 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.
+///
+public sealed record EInvoiceChannelSettings
+{
+ /// The channel code (Italy: PEC, SDICOOP, INTA, INTB).
+ public required string Code { get; init; }
+
+ /// The certified mailbox of the company.
+ public string? Mailbox { get; init; }
+
+ /// The SMTP server of the mailbox.
+ public string? SmtpHost { get; init; }
+
+ /// The SMTP port (465 for TLS from the start, 587 for STARTTLS).
+ public int SmtpPort { get; init; } = 465;
+
+ /// The IMAP server of the mailbox.
+ public string? ImapHost { get; init; }
+
+ /// The IMAP port (993 for TLS).
+ public int ImapPort { get; init; } = 993;
+
+ /// Whether the connections are protected by TLS (always, except in tests on the local machine).
+ public bool Tls { get; init; } = true;
+
+ /// The user of the mailbox or of the service.
+ public string? User { get; init; }
+
+ /// The password of the mailbox or of the service.
+ public string? Password { get; init; }
+
+ /// The address of the exchange system to write to (Italy: sdi01@pec.fatturapa.it, then the one assigned).
+ public string? ExchangeAddress { get; init; }
+
+ /// The folder of the mailbox the processed messages are moved to.
+ public string? ArchiveFolder { get; init; }
+
+ /// The address of the web service or of the API.
+ public string? Endpoint { get; init; }
+
+ /// The client certificate (PKCS#12) of the web service.
+ public byte[]? Certificate { get; init; }
+
+ /// The password of the certificate.
+ public string? CertificatePassword { get; init; }
+
+ /// The API key or token of an intermediary.
+ public string? ApiKey { get; init; }
+
+ /// Whether the test environment of the service is used.
+ public bool TestEnvironment { get; init; }
+}
+
+/// A file to send.
+/// The name of the file.
+/// The content.
+/// What it is, for messages and logs (the number of the document).
+public sealed record EInvoiceOutgoing(string FileName, byte[] Content, string? Reference);
+
+/// The answer of a channel to a file sent.
+/// Whether the channel took the file.
+/// The identifier given by the exchange system, when the channel knows it at once (Italy: SdICoop).
+/// The identifier of the message or of the upload at the channel.
+/// Why the file was not taken.
+public sealed record EInvoiceSendResult(bool Accepted, string? ExchangeId, string? MessageId, string? Error);
+
+/// A file received from a channel: a receipt, a supplier invoice or its metadata.
+/// The name of the file.
+/// The content.
+/// When the channel received it.
+/// The key of the message at the channel, to acknowledge it once stored.
+/// Who sent it (the address of the exchange system), if known.
+public sealed record EInvoiceIncoming(string FileName, byte[] Content, DateTimeOffset ReceivedAt, string MessageKey, string? Sender);
+
+/// What a channel had for the company.
+/// The files received.
+/// How many messages the channel read, files or not.
+/// The address the exchange system assigned for the next files, if it changed (Italy: PEC).
+public sealed record EInvoiceFetchResult(IReadOnlyList Files, int MessagesRead, string? ExchangeAddress);
+
+/// The outcome of a connection test.
+/// Whether every step worked.
+/// What was checked, or what failed.
+public sealed record EInvoiceChannelCheck(bool Success, string Message);
+
+///
+/// A channel to the exchange system (SPEC §11.9: ISdiTransport): 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.
+///
+public interface IEInvoiceTransport
+{
+ /// The code of the channel (Italy: PEC, SDICOOP, INTA, INTB).
+ string Code { get; }
+
+ /// Whether receipts and invoices are fetched by polling ( when the exchange system pushes them).
+ bool Polls { get; }
+
+ /// Sends a file.
+ /// The settings of the channel.
+ /// The file.
+ /// Cancellation.
+ /// The answer of the channel.
+ Task SendAsync(EInvoiceChannelSettings settings, EInvoiceOutgoing file, CancellationToken cancellationToken = default);
+
+ /// Fetches the files waiting at the channel; nothing is removed until .
+ /// The settings of the channel.
+ /// Cancellation.
+ /// The files.
+ Task FetchAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default);
+
+ /// Marks messages as processed (Italy, PEC: moved to the archive folder).
+ /// The settings of the channel.
+ /// The keys of .
+ /// Cancellation.
+ /// A task.
+ Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection messageKeys, CancellationToken cancellationToken = default);
+
+ /// Tests the connection without sending anything.
+ /// The settings of the channel.
+ /// Cancellation.
+ /// The outcome.
+ Task CheckAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default);
+}
+
+/// A channel the pack offers, with its description for the configuration screen.
+/// The code.
+/// The name shown.
+/// The implementation.
+public sealed record EInvoiceChannel(string Code, string Name, IEInvoiceTransport Transport);
+
+/// The channels to the exchange system the pack offers (Italy: PEC, SdICoop, intermediary A and B).
+public interface IEInvoiceChannels
+{
+ /// The channels, in the order of the configuration screen.
+ IReadOnlyList All { get; }
+
+ /// A channel by code.
+ /// The code.
+ /// The channel, or .
+ EInvoiceChannel? Find(string code);
+}
diff --git a/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs b/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs
index 6949382..9d938c1 100644
--- a/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs
+++ b/src/Khaemhat.Fiscal.Abstractions/IncomingInvoices.cs
@@ -25,7 +25,7 @@ public interface IIncomingInvoiceReader
/// The file with its invoices.
/// The file is not readable, not an invoice, or misses mandatory data;
/// is one of .
- IncomingInvoiceFile Read(string fileName, byte[] content);
+ EInvoiceFile Read(string fileName, byte[] content);
}
/// A received e-invoice file that cannot be read; is one of .
@@ -85,189 +85,6 @@ public static class IncomingInvoiceErrors
public const string Invalid = "incoming.invalid";
}
-/// A received e-invoice file: the transmission header, the two parties and one or more invoices.
-/// The name of the file as received.
-/// The transmission format (Italy: FPR12, FPA12, FSM10).
-/// The progressive number of the transmission given by the sender.
-/// The recipient code of the transmission.
-/// The supplier who issued the invoices.
-/// The customer the invoices are addressed to (normally the company).
-/// The invoices, one per body of the file (a batch has more than one).
-/// The signature of the envelope, or for an unsigned file.
-/// The XML of the invoice, taken out of the envelope when the file was signed.
-public sealed record IncomingInvoiceFile(
- string FileName, string? TransmissionFormat, string? ProgressiveNumber, string? RecipientCode,
- IncomingParty Supplier, IncomingParty Customer, IReadOnlyList Invoices,
- IncomingSignature? Signature, byte[] Xml);
-
-///
-/// The signature of a signed file. 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.
-///
-/// Whether the digest and the signature match the content.
-/// The name of the signer, from the certificate.
-/// The tax code of the signer, when the certificate carries it.
-/// The signing time declared by the signer, if any (not a trusted timestamp).
-/// The start of validity of the certificate.
-/// The end of validity of the certificate.
-/// Why the signature is not verified, or .
-public sealed record IncomingSignature(bool Verified, string? Signer, string? SignerTaxCode, DateTimeOffset? SignedAt,
- DateTimeOffset? CertificateNotBefore, DateTimeOffset? CertificateNotAfter, string? Problem);
-
-/// A party of the invoice (supplier or customer) as written in the file.
-/// The country of the VAT number.
-/// The VAT number without the country prefix.
-/// The tax code.
-/// The company name, when the party is a company.
-/// The first name, when the party is a person.
-/// The last name, when the party is a person.
-/// The street of the registered office.
-/// The street number.
-/// The postal code.
-/// The city.
-/// The province.
-/// The country of the registered office.
-/// The tax regime (supplier only).
-/// The e-mail address (supplier only).
-/// The phone number (supplier only).
-/// The office of the companies register.
-/// The number in the companies register.
-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)
-{
- /// The company name, or first and last name of a person.
- public string DisplayName => Name ?? string.Join(' ', new[] { FirstName, LastName }.Where(s => !string.IsNullOrWhiteSpace(s)));
-}
-
-/// An invoice of the file (one body).
-/// The document type (Italy: TD01, TD04...).
-/// The currency code.
-/// The date of the document.
-/// The number of the document.
-/// The total amount declared by the supplier, if any.
-/// The rounding on the total, if any.
-/// The free-text causals.
-/// 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).
-/// The withholding taxes.
-/// The stamp duty, if any.
-/// The social security contributions.
-/// The discounts and surcharges on the whole document.
-/// The purchase orders referred to.
-/// The contracts referred to.
-/// The invoices referred to (the invoice a credit note corrects).
-/// The delivery notes referred to.
-/// The lines.
-/// The tax summary, one row per rate or nature.
-/// The payment installments.
-/// The attached files.
-public sealed record IncomingInvoice(
- string DocumentType, string Currency, DateOnly Date, string Number, decimal? Total, decimal? Rounding,
- IReadOnlyList Causals, bool Art73,
- IReadOnlyList Withholdings, IncomingStampDuty? StampDuty,
- IReadOnlyList SocialSecurity, IReadOnlyList Discounts,
- IReadOnlyList Orders, IReadOnlyList Contracts,
- IReadOnlyList RelatedInvoices, IReadOnlyList DeliveryNotes,
- IReadOnlyList Lines, IReadOnlyList TaxSummary,
- IReadOnlyList Payments, IReadOnlyList Attachments);
-
-/// A line of an invoice.
-/// The line number.
-/// The item codes (type and value).
-/// The description.
-/// The quantity, if given.
-/// The unit of measure, if given.
-/// The unit price.
-/// The total of the line, net of tax.
-/// The tax rate in percent (zero with a nature).
-/// The reason of a zero rate (Italy: N2.2...).
-/// The discounts and surcharges of the line.
-/// Whether the line is subject to withholding tax.
-/// The kind of line (Italy: SC discount, PR premium, AB rebate,
-/// AC ancillary cost).
-/// The start of the period the line refers to.
-/// The end of the period the line refers to.
-/// The administrative reference (cost centre, internal code).
-public sealed record IncomingLine(
- int Number, IReadOnlyList Codes, string Description, decimal? Quantity, string? Unit,
- decimal UnitPrice, decimal TotalPrice, decimal TaxRate, string? Nature, IReadOnlyList Discounts,
- bool Withheld, string? LineType, DateOnly? PeriodStart, DateOnly? PeriodEnd, string? AdministrativeReference);
-
-/// A code of the item of a line.
-/// The kind of code (EAN, SKU, the supplier's code...).
-/// The code.
-public sealed record IncomingItemCode(string Type, string Value);
-
-/// A discount or surcharge.
-/// Whether it is a surcharge (Italy: MG) instead of a discount (SC).
-/// The percentage, if given.
-/// The amount, if given.
-public sealed record IncomingDiscount(bool IsSurcharge, decimal? Percent, decimal? Amount);
-
-/// A row of the tax summary.
-/// The tax rate in percent.
-/// The reason of a zero rate.
-/// The taxable amount.
-/// The tax.
-/// When the tax is due (Italy: I immediate, D deferred, S split payment).
-/// The law that justifies the nature.
-/// Ancillary expenses, if any.
-/// The rounding, if any.
-public sealed record IncomingTaxSummary(decimal Rate, string? Nature, decimal Taxable, decimal Tax, string? Exigibility,
- string? LegalReference, decimal? ExpensesAmount, decimal? Rounding);
-
-/// A payment installment.
-/// The payment conditions (Italy: TP01 installments, TP02 full, TP03 advance).
-/// The payment method (Italy: MP05 bank transfer...).
-/// The due date, if given.
-/// The amount.
-/// The IBAN to pay to, if given.
-/// The BIC, if given.
-/// The beneficiary, if different from the supplier.
-public sealed record IncomingPayment(string? Conditions, string? Method, DateOnly? DueDate, decimal Amount,
- string? Iban, string? Bic, string? Beneficiary);
-
-/// A reference to another document (order, contract, invoice, delivery note).
-/// The number of the document.
-/// The date of the document.
-/// The lines of the invoice the reference applies to; empty when it applies to all.
-/// The tender code, if any (public administration).
-/// The project code, if any (public administration).
-public sealed record IncomingReference(string? Id, DateOnly? Date, IReadOnlyList LineNumbers, string? Cig, string? Cup);
-
-/// A withholding tax.
-/// The kind of withholding (Italy: RT01...).
-/// The amount withheld.
-/// The rate in percent.
-/// The payment reason (Italy: A...), if given.
-public sealed record IncomingWithholding(string Type, decimal Amount, decimal Rate, string? Reason);
-
-/// The stamp duty of an invoice.
-/// Whether it is paid virtually by the issuer.
-/// The amount.
-public sealed record IncomingStampDuty(bool Virtual, decimal Amount);
-
-/// A social security contribution added to the invoice.
-/// The fund (Italy: TC01...).
-/// The rate of the contribution in percent.
-/// The amount of the contribution.
-/// The amount the contribution is computed on, if given.
-/// The tax rate applied to the contribution.
-/// Whether the contribution is subject to withholding tax.
-/// The reason of a zero tax rate.
-public sealed record IncomingSocialSecurity(string Fund, decimal Rate, decimal Amount, decimal? Taxable, decimal TaxRate,
- bool Withheld, string? Nature);
-
-/// A file attached to the invoice.
-/// The name of the attachment.
-/// The format declared by the supplier (such as PDF), if any.
-/// The description, if any.
-/// The decoded content.
-public sealed record IncomingAttachment(string Name, string? Format, string? Description, byte[] Content);
-
///
/// 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).
diff --git a/src/Khaemhat.Fiscal.Italy/Data/FatturaPA_v1.2_khaemhat.xsd b/src/Khaemhat.Fiscal.Italy/Data/FatturaPA_v1.2_khaemhat.xsd
new file mode 100644
index 0000000..e156fc8
--- /dev/null
+++ b/src/Khaemhat.Fiscal.Italy/Data/FatturaPA_v1.2_khaemhat.xsd
@@ -0,0 +1,558 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs b/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs
index 9775730..9d49cd0 100644
--- a/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs
+++ b/src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs
@@ -39,7 +39,7 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
!content.IsEmpty && (CmsSignedData.LooksLikeCms(content) || LooksLikeXml(content));
///
- 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 ReadDiscounts(XElement? parent) =>
- Els(parent, "ScontoMaggiorazione").Select(d => new IncomingDiscount(
+ private static List 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 ReadReferences(XElement? general, string name) =>
- Els(general, name).Select(r => new IncomingReference(
+ private static List 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 LineNumbers(XElement reference) =>
@@ -331,11 +380,11 @@ public sealed class FatturaPaReader : IIncomingInvoiceReader
.Where(n => n > 0)
.ToList();
- private static List ReadPayments(XElement body, int index) =>
+ private static List 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 ReadAttachments(XElement body) =>
- Els(body, "Allegati").Select(a => new IncomingAttachment(
+ private static List 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)
diff --git a/src/Khaemhat.Fiscal.Italy/FatturaPaValidator.cs b/src/Khaemhat.Fiscal.Italy/FatturaPaValidator.cs
new file mode 100644
index 0000000..7fce25a
--- /dev/null
+++ b/src/Khaemhat.Fiscal.Italy/FatturaPaValidator.cs
@@ -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;
+
+///
+/// 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.
+///
+///
+/// The checks that the SDI documents with a code keep that code (00400, 00423...), so the message is
+/// the one the user would read in a rejection; the others have a code of Khaemhat (einvoice.*). 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.
+/// Tolerances follow the specifications: one cent on PrezzoTotale and Imposta, one euro on
+/// ImponibileImporto.
+///
+public sealed class FatturaPaValidator : IEInvoiceValidator
+{
+ private static readonly Lazy Schemas = new(LoadSchemas);
+
+ private static readonly HashSet 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 DifferentParties = new(StringComparer.Ordinal)
+ {
+ "TD01", "TD02", "TD03", "TD06", "TD16", "TD17", "TD18", "TD19", "TD20", "TD24", "TD25", "TD28", "TD29",
+ };
+
+ private static readonly HashSet SameParty = new(StringComparer.Ordinal) { "TD21", "TD27" };
+
+ private static readonly HashSet ForeignSupplier = new(StringComparer.Ordinal) { "TD17", "TD18", "TD19", "TD28" };
+
+ ///
+ public string RulesVersion => FatturaPaCodeLists.SpecVersion;
+
+ ///
+ public IReadOnlyList Validate(EInvoiceFile file)
+ {
+ ArgumentNullException.ThrowIfNull(file);
+ var problems = new List();
+ 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)];
+ }
+
+ ///
+ public IReadOnlyList ValidateXml(byte[] xml)
+ {
+ ArgumentNullException.ThrowIfNull(xml);
+ var problems = new List();
+ 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 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 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 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 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 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 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 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 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 discounts, string path, string code, List 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 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 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 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 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 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;
+ }
+}
diff --git a/src/Khaemhat.Fiscal.Italy/FatturaPaWriter.cs b/src/Khaemhat.Fiscal.Italy/FatturaPaWriter.cs
new file mode 100644
index 0000000..4099463
--- /dev/null
+++ b/src/Khaemhat.Fiscal.Italy/FatturaPaWriter.cs
@@ -0,0 +1,655 @@
+using System.Globalization;
+using System.Text;
+using System.Xml;
+using Khaemhat.Fiscal.Abstractions;
+
+namespace Khaemhat.Fiscal.Italy;
+
+///
+/// Writes FatturaPA files v1.2 (FPR12 to businesses and consumers, FPA12 to the public administration)
+/// following the technical specifications of the Agenzia delle Entrate (,
+/// SPEC §11.9, ADR 0039).
+///
+///
+/// Only the root element is in the namespace of the schema (its elementFormDefault 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.
+/// 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 ?, and texts longer than the field are cut. The
+/// writer does not check the content: does, before the file is written.
+/// The simplified invoice FSM10 is read () but not written: Khaemhat issues
+/// ordinary invoices only.
+///
+public sealed class FatturaPaWriter : IEInvoiceWriter
+{
+ /// The namespace of FatturaPA v1.2.
+ public const string Namespace = "http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2";
+
+ private const string DigitsBase36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+
+ ///
+ 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";
+ }
+
+ ///
+ 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);
+ }
+
+ ///
+ 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 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 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));
+ }
+ }
+
+ /// A text in the characters and length the schema accepts.
+ /// The text.
+ /// The length of the field.
+ /// The text, trimmed, in Latin-1 and cut to the length.
+ 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 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;
+ }
+
+ /// A date as the schema wants it.
+ /// The date.
+ /// yyyy-MM-dd.
+ public static string Date(DateOnly date) => date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
+
+ /// An amount with two decimals (Amount2DecimalType).
+ /// The amount.
+ /// The text.
+ public static string Amount2(decimal value) =>
+ Math.Round(value, 2, MidpointRounding.AwayFromZero).ToString("0.00", CultureInfo.InvariantCulture);
+
+ /// An amount with two to eight decimals (Amount8DecimalType, QuantitaType).
+ /// The amount.
+ /// The text.
+ public static string Amount8(decimal value) =>
+ Math.Round(value, 8, MidpointRounding.AwayFromZero).ToString("0.00######", CultureInfo.InvariantCulture);
+
+ /// A rate in percent (RateType).
+ /// The rate.
+ /// The text with two decimals.
+ 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);
+}
diff --git a/src/Khaemhat.Fiscal.Italy/ItalianRules.cs b/src/Khaemhat.Fiscal.Italy/ItalianRules.cs
index 39bbbe1..3b055d1 100644
--- a/src/Khaemhat.Fiscal.Italy/ItalianRules.cs
+++ b/src/Khaemhat.Fiscal.Italy/ItalianRules.cs
@@ -3,7 +3,7 @@ using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy;
-/// The FatturaPA format: version of the specifications and code lists (writer and reader arrive in M9).
+/// The FatturaPA format: version of the specifications and code lists (writer, validator and readers are features of their own).
public sealed class FatturaPaFormat : IEInvoiceFormat
{
///
diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs
index 2996c89..b8eb7ca 100644
--- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs
+++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs
@@ -18,6 +18,10 @@ public sealed class ItalyFiscalPack : FiscalPackBase
AddFeature(new LatePaymentRulesIt());
AddFeature(new RemittanceMethodsIt());
AddFeature(new FatturaPaReader());
+ AddFeature(new FatturaPaWriter());
+ AddFeature(new FatturaPaValidator());
+ AddFeature(new SdiReceiptReader());
+ AddFeature(new Sdi.SdiChannels());
AddFeature(new IncomingInvoiceRulesIt());
AddFeature(new SelfInvoiceRulesIt());
AddFeature(new WithholdingRulesIt());
diff --git a/src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj b/src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj
index a03d77e..bafab0b 100644
--- a/src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj
+++ b/src/Khaemhat.Fiscal.Italy/Khaemhat.Fiscal.Italy.csproj
@@ -7,6 +7,7 @@
+
diff --git a/src/Khaemhat.Fiscal.Italy/Sdi/IntermediaryTransports.cs b/src/Khaemhat.Fiscal.Italy/Sdi/IntermediaryTransports.cs
new file mode 100644
index 0000000..c30cdaa
--- /dev/null
+++ b/src/Khaemhat.Fiscal.Italy/Sdi/IntermediaryTransports.cs
@@ -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;
+
+///
+/// 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.
+///
+/// The two contracts (, ) 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.
+/// Makes the HTTP handler (tests); by default a plain handler.
+public abstract class IntermediaryTransportBase(Func? handlerFactory) : IEInvoiceTransport
+{
+ /// JSON with camel-case names.
+ protected static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
+
+ ///
+ public abstract string Code { get; }
+
+ ///
+ public bool Polls => true;
+
+ ///
+ public async Task 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);
+ }
+ }
+
+ ///
+ public async Task 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);
+ }
+
+ ///
+ public async Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection 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}.");
+ }
+ }
+ }
+
+ ///
+ public async Task 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);
+ }
+ }
+
+ /// What is missing in the settings, or .
+ /// The settings.
+ /// The message.
+ protected abstract string? Missing(EInvoiceChannelSettings settings);
+
+ /// The request that sends a file.
+ /// The settings.
+ /// The file.
+ /// The request.
+ protected abstract HttpRequestMessage SendRequest(EInvoiceChannelSettings settings, EInvoiceOutgoing file);
+
+ /// Reads the answer to a file sent.
+ /// The body.
+ /// The identifier at the intermediary and the one of the SDI, if already known.
+ protected abstract (string? MessageId, string? ExchangeId) ReadSendAnswer(string json);
+
+ /// The request that lists the waiting files.
+ /// The settings.
+ /// The request.
+ protected abstract HttpRequestMessage FetchRequest(EInvoiceChannelSettings settings);
+
+ /// Reads the waiting files.
+ /// The body.
+ /// The files.
+ protected abstract IReadOnlyList ReadFiles(string json);
+
+ /// The request that acknowledges a file.
+ /// The settings.
+ /// The key.
+ /// The request.
+ protected abstract HttpRequestMessage AcknowledgeRequest(EInvoiceChannelSettings settings, string key);
+
+ /// The request that tests the credentials.
+ /// The settings.
+ /// The request.
+ protected abstract HttpRequestMessage CheckRequest(EInvoiceChannelSettings settings);
+
+ /// An address under the endpoint.
+ /// The settings.
+ /// The relative path.
+ /// The address.
+ protected static Uri Url(EInvoiceChannelSettings settings, string path)
+ {
+ ArgumentNullException.ThrowIfNull(settings);
+ return new Uri(settings.Endpoint!.TrimEnd('/') + "/" + path.TrimStart('/'));
+ }
+
+ /// A date of the API, or now.
+ /// The ISO 8601 text.
+ /// The time.
+ 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) };
+}
+
+///
+/// Intermediary A: an API key as bearer token; the file is the body of the request.
+///
+/// POST {endpoint}/invoices, body the file, header X-File-Name → { "id", "sdiId" }.
+/// GET {endpoint}/files → [{ "id", "fileName", "content" (base64), "receivedAt" }].
+/// POST {endpoint}/files/{id}/ack; GET {endpoint}/status.
+///
+///
+/// Makes the HTTP handler (tests).
+public sealed class IntermediaryATransport(Func? handlerFactory = null) : IntermediaryTransportBase(handlerFactory)
+{
+ /// The code of the channel.
+ public const string ChannelCode = "INTA";
+
+ ///
+ public override string Code => ChannelCode;
+
+ ///
+ 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;
+
+ ///
+ 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;
+ }
+
+ ///
+ protected override (string? MessageId, string? ExchangeId) ReadSendAnswer(string json)
+ {
+ var answer = JsonSerializer.Deserialize(json, Json);
+ return (answer?.Id, answer?.SdiId);
+ }
+
+ ///
+ protected override HttpRequestMessage FetchRequest(EInvoiceChannelSettings settings) => Authorized(settings, HttpMethod.Get, "files");
+
+ ///
+ protected override IReadOnlyList ReadFiles(string json) =>
+ (JsonSerializer.Deserialize>(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();
+
+ ///
+ protected override HttpRequestMessage AcknowledgeRequest(EInvoiceChannelSettings settings, string key) =>
+ Authorized(settings, HttpMethod.Post, "files/" + Uri.EscapeDataString(key) + "/ack");
+
+ ///
+ 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);
+}
+
+///
+/// Intermediary B: user and password with basic authentication; the file travels in JSON.
+///
+/// POST {endpoint}/api/v1/send with { "fileName", "content" } → { "uploadId", "identificativoSdi" }.
+/// GET {endpoint}/api/v1/inbox → { "items": [{ "key", "name", "data" (base64), "date" }] }.
+/// DELETE {endpoint}/api/v1/inbox/{key}; GET {endpoint}/api/v1/ping.
+///
+///
+/// Makes the HTTP handler (tests).
+public sealed class IntermediaryBTransport(Func? handlerFactory = null) : IntermediaryTransportBase(handlerFactory)
+{
+ /// The code of the channel.
+ public const string ChannelCode = "INTB";
+
+ ///
+ public override string Code => ChannelCode;
+
+ ///
+ 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;
+
+ ///
+ 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;
+ }
+
+ ///
+ protected override (string? MessageId, string? ExchangeId) ReadSendAnswer(string json)
+ {
+ var answer = JsonSerializer.Deserialize(json, Json);
+ return (answer?.UploadId, answer?.IdentificativoSdi);
+ }
+
+ ///
+ protected override HttpRequestMessage FetchRequest(EInvoiceChannelSettings settings) => Authorized(settings, HttpMethod.Get, "api/v1/inbox");
+
+ ///
+ protected override IReadOnlyList ReadFiles(string json) =>
+ (JsonSerializer.Deserialize(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();
+
+ ///
+ protected override HttpRequestMessage AcknowledgeRequest(EInvoiceChannelSettings settings, string key) =>
+ Authorized(settings, HttpMethod.Delete, "api/v1/inbox/" + Uri.EscapeDataString(key));
+
+ ///
+ 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? Items);
+
+ private sealed record InboxItem(string? Key, string? Name, string? Data, string? Date);
+}
+
+/// The channels of the Italian pack, in the order of the configuration screen (mockup 059).
+public sealed class SdiChannels : IEInvoiceChannels
+{
+ /// Creates the channels.
+ /// The PEC channel.
+ /// The SdICoop channel.
+ /// Intermediary A.
+ /// Intermediary B.
+ 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()),
+ ];
+ }
+
+ ///
+ public IReadOnlyList All { get; }
+
+ ///
+ public EInvoiceChannel? Find(string code) => All.FirstOrDefault(c => string.Equals(c.Code, code, StringComparison.OrdinalIgnoreCase));
+}
diff --git a/src/Khaemhat.Fiscal.Italy/Sdi/PecSdiTransport.cs b/src/Khaemhat.Fiscal.Italy/Sdi/PecSdiTransport.cs
new file mode 100644
index 0000000..90110be
--- /dev/null
+++ b/src/Khaemhat.Fiscal.Italy/Sdi/PecSdiTransport.cs
@@ -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;
+
+///
+/// The PEC channel to the SDI (SPEC §11.9, issue #76): files go by certified mail to the address of the SDI
+/// (sdi01@pec.fatturapa.it the first time, then the sdiNN address the SDI writes from), receipts and
+/// supplier invoices are read from the mailbox by IMAP.
+///
+///
+/// Only messages whose sender contains fatturapa.it are read: the acceptance and delivery receipts of the
+/// PEC provider stay where they are. The files are the .xml and .p7m attachments of the original message
+/// (postacert.eml); daticert.xml and the signature of the provider are ignored.
+/// 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.
+///
+/// The clock (date of the messages sent).
+/// A custom check of the server certificates (tests only).
+public sealed partial class PecSdiTransport(TimeProvider? clock = null, RemoteCertificateValidationCallback? certificateValidation = null) : IEInvoiceTransport
+{
+ /// The code of the channel.
+ public const string ChannelCode = "PEC";
+
+ /// The address of the SDI for the first file.
+ public const string FirstAddress = "sdi01@pec.fatturapa.it";
+
+ /// The most messages read in one poll.
+ public const int MaxMessages = 200;
+
+ private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2);
+ private readonly TimeProvider _clock = clock ?? TimeProvider.System;
+
+ ///
+ public string Code => ChannelCode;
+
+ ///
+ public bool Polls => true;
+
+ /// Whether an address is one the SDI writes from (sdiNN@pec.fatturapa.it).
+ /// The address, possibly with a display name.
+ /// The bare address when it is one, otherwise .
+ public static string? SdiAddress(string? address)
+ {
+ var match = SdiAddressPattern().Match(address ?? string.Empty);
+ return match.Success ? match.Value.ToLowerInvariant() : null;
+ }
+
+ ///
+ public async Task 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);
+ }
+ }
+
+ ///
+ public async Task 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();
+ var empty = new List();
+ 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);
+ }
+
+ ///
+ public async Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection 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);
+ }
+
+ ///
+ public async Task 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);
+ }
+ }
+
+ ///
+ /// The files of the SDI in a message: the .xml and .p7m attachments of the original message of a
+ /// certified mail (or of the message itself when it is not certified).
+ ///
+ /// The raw message.
+ /// The key of the message.
+ /// The time used when the message has no date.
+ /// The files and the sender of the original message.
+ public static (IReadOnlyList 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 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();
+}
diff --git a/src/Khaemhat.Fiscal.Italy/Sdi/SdiCoopTransport.cs b/src/Khaemhat.Fiscal.Italy/Sdi/SdiCoopTransport.cs
new file mode 100644
index 0000000..0940bb7
--- /dev/null
+++ b/src/Khaemhat.Fiscal.Italy/Sdi/SdiCoopTransport.cs
@@ -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;
+
+///
+/// The SdICoop channel (SPEC §11.9, issue #77): files go to the web service SdIRiceviFile 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 IdentificativoSdI. Notifications and supplier invoices are pushed by the SDI to the web services of
+/// the company (TrasmissioneFatture, RicezioneFatture), read by .
+///
+/// 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.
+/// Makes the HTTP handler for a channel (tests); by default a handler with the client certificate.
+public sealed class SdiCoopTransport(Func? handlerFactory = null) : IEInvoiceTransport
+{
+ /// The code of the channel.
+ public const string ChannelCode = "SDICOOP";
+
+ /// The address of SdIRiceviFile in production.
+ public const string ProductionEndpoint = "https://servizi.fatturapa.it/ricevi_file";
+
+ /// The address of SdIRiceviFile in the test environment.
+ public const string TestEndpoint = "https://testservizi.fatturapa.it/ricevi_file";
+
+ /// The SOAP action of RiceviFile.
+ 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";
+
+ ///
+ public string Code => ChannelCode;
+
+ ///
+ public bool Polls => false;
+
+ /// The address to send to: the one configured, otherwise the one of the environment.
+ /// The settings.
+ /// The address.
+ public static string EndpointOf(EInvoiceChannelSettings settings)
+ {
+ ArgumentNullException.ThrowIfNull(settings);
+ return !string.IsNullOrWhiteSpace(settings.Endpoint) ? settings.Endpoint.Trim() : settings.TestEnvironment ? TestEndpoint : ProductionEndpoint;
+ }
+
+ ///
+ public async Task 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);
+ }
+ }
+
+ ///
+ public Task FetchAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default) =>
+ Task.FromResult(new EInvoiceFetchResult([], 0, null));
+
+ ///
+ public Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection messageKeys, CancellationToken cancellationToken = default) =>
+ Task.CompletedTask;
+
+ ///
+ public async Task 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);
+ }
+ }
+
+ /// The meaning of the error codes of RiceviFile.
+ /// EI01, EI02 or EI03.
+ /// The description.
+ 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", "\"\""));
+ 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", "");
+ 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", "");
+ 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) };
+ }
+}
+
+/// A file pushed by the SDI to the web services of the company.
+/// The SOAP operation (RicevutaConsegna, RiceviFatture, …).
+/// The IdentificativoSdI.
+/// The files: the notification, or the invoice and its metadata.
+public sealed record SdiCoopInbound(string Operation, string? ExchangeId, IReadOnlyList<(string FileName, byte[] Content)> Files);
+
+///
+/// Reads the SOAP messages the SDI sends to the company (TrasmissioneFatture: RicevutaConsegna,
+/// NotificaMancataConsegna, NotificaScarto, NotificaEsito, NotificaDecorrenzaTermini, AttestazioneTrasmissioneFattura;
+/// RicezioneFatture: RiceviFatture, NotificaDecorrenzaTermini) and writes the answers.
+///
+public static class SdiCoopMessages
+{
+ /// The SOAP envelope of a body, plain or MTOM, with the binary parts put back in place of the references.
+ /// The content type of the HTTP message.
+ /// The body.
+ /// The envelope, or when the body is not SOAP.
+ public static XElement? Envelope(string? contentType, byte[] body)
+ {
+ ArgumentNullException.ThrowIfNull(body);
+ var parts = new Dictionary(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;
+ }
+
+ /// Reads a message of the SDI.
+ /// The content type of the HTTP message.
+ /// The body.
+ /// The files, or when the message is not one of the SDI.
+ 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);
+ }
+
+ /// The answer to a message of the SDI: empty, or esito ER01 for RiceviFatture.
+ /// The message, or when it could not be read.
+ /// The SOAP envelope (text/xml).
+ public static string Answer(SdiCoopInbound? inbound)
+ {
+ const string Soap = "http://schemas.xmlsoap.org/soap/envelope/";
+ if (inbound is null)
+ {
+ return $"soapenv:ClientNot a message of the SDI.";
+ }
+
+ var body = inbound.Operation == "RiceviFatture"
+ ? "ER01"
+ : string.Empty;
+ return $"{body}";
+ }
+}
diff --git a/src/Khaemhat.Fiscal.Italy/SdiReceiptReader.cs b/src/Khaemhat.Fiscal.Italy/SdiReceiptReader.cs
new file mode 100644
index 0000000..0983ab5
--- /dev/null
+++ b/src/Khaemhat.Fiscal.Italy/SdiReceiptReader.cs
@@ -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;
+
+///
+/// Reads the notifications of the SDI (MessaggiTypes 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).
+///
+///
+/// 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 (IT01234567890_00A1Z_RC_001.xml); when the root element is clear the name is not
+/// needed.
+///
+public sealed partial class SdiReceiptReader : IEInvoiceReceiptReader
+{
+ private static readonly Dictionary 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"),
+ };
+
+ /// The code of a notification in a file name (..._RC_001.xml), or .
+ /// The name.
+ /// The code.
+ public static string? CodeOfName(string fileName)
+ {
+ var match = NamePattern().Match(Path.GetFileName(fileName ?? string.Empty));
+ return match.Success ? match.Groups["code"].Value : null;
+ }
+
+ ///
+ public bool IsReceipt(string fileName, ReadOnlySpan 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));
+ }
+
+ ///
+ 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 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(@"_(?RC|NS|MC|NE|DT|AT|MT|SE)_[0-9A-Za-z]{1,3}\.xml$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
+ private static partial Regex NamePattern();
+}
diff --git a/src/Khaemhat.Infrastructure/Mail/ImapClient.cs b/src/Khaemhat.Infrastructure/Mail/ImapClient.cs
new file mode 100644
index 0000000..51de0b1
--- /dev/null
+++ b/src/Khaemhat.Infrastructure/Mail/ImapClient.cs
@@ -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;
+
+/// The IMAP server of a mailbox (for the PEC of the SDI: implicit TLS on port 993).
+/// The host.
+/// The port.
+/// Whether the connection starts with TLS (port 993); only for tests and LAN servers.
+/// The user.
+/// The password.
+public sealed record ImapSettings(string Host, int Port, bool Tls, string User, string Password)
+{
+ /// The server without the credentials.
+ /// Host and port.
+ public override string ToString() => $"{Host}:{Port}" + (Tls ? " (TLS)" : string.Empty);
+}
+
+/// A message fetched from a mailbox.
+/// The unique identifier in the mailbox.
+/// The raw message (RFC 5322).
+public sealed record ImapMessage(long Uid, byte[] Content);
+
+///
+/// An IMAP4rev1 client (RFC 3501) written in house for the PEC channel of the SDI (SPEC §11.9, issue #76): connect with
+/// implicit TLS, LOGIN, SELECT, UID SEARCH, UID FETCH BODY.PEEK[] (message read without
+/// marking it), UID STORE, UID MOVE or UID COPY + \Deleted + EXPUNGE to archive,
+/// CREATE when the archive folder is missing, LOGOUT.
+///
+/// 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.
+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;
+ }
+
+ /// The capabilities the server announced, in upper case.
+ public IReadOnlySet Capabilities { get; private set; } = new HashSet(StringComparer.Ordinal);
+
+ /// Connects and reads the greeting.
+ /// The server.
+ /// Cancellation.
+ /// A custom certificate check (tests); the system check when .
+ /// The client, not yet logged in.
+ public static async Task 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;
+ }
+ }
+
+ /// Logs in with user and password and reads the capabilities.
+ /// The user.
+ /// The password.
+ /// Cancellation.
+ /// A task.
+ 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);
+ }
+
+ /// Selects a mailbox.
+ /// The name (ASCII), such as INBOX.
+ /// Cancellation.
+ /// The number of messages in the mailbox.
+ public async Task 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;
+ }
+
+ /// Searches the selected mailbox.
+ /// The criteria, already in IMAP syntax (UNSEEN FROM "fatturapa.it"); see .
+ /// Cancellation.
+ /// The unique identifiers, ascending.
+ public async Task> 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();
+ 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];
+ }
+
+ /// Fetches a whole message without marking it as read.
+ /// The unique identifier.
+ /// Cancellation.
+ /// The message, or when it no longer exists.
+ public async Task 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]);
+ }
+
+ /// Adds flags to a message.
+ /// The unique identifier.
+ /// The flags, such as \Seen.
+ /// Cancellation.
+ /// A task.
+ 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");
+ }
+
+ /// Moves a message to another mailbox, creating it when missing.
+ /// The unique identifier.
+ /// The target (ASCII).
+ /// Cancellation.
+ /// A task.
+ 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);
+ }
+ }
+
+ /// Logs out (the server closes the connection).
+ /// Cancellation.
+ /// A task.
+ 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.
+ }
+ }
+
+ ///
+ public async ValueTask DisposeAsync()
+ {
+ await _stream.DisposeAsync().ConfigureAwait(false);
+ _client.Dispose();
+ }
+
+ /// A string in IMAP quoted form (backslash and double quote escaped).
+ /// The text (ASCII, no line breaks).
+ /// The quoted string.
+ 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) + "\"";
+ }
+
+ /// A date in the form of the search keys (SINCE 1-Nov-2026).
+ /// The date.
+ /// The text.
+ 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 SendAsync(IReadOnlyList