From 709bb135325a70b5b08a758ee3d7522bfe84b598 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 13 Nov 2026 11:51:31 +0100 Subject: [PATCH] feat: FatturaPA writer, validator, SDI receipts and transport channels (#74 #75 #76 #77) The Italian pack can now produce and check the e-invoice and talk to the SDI: - FatturaPaWriter writes FPR12/FPA12 v1.2 with SDI file naming; FatturaPaValidator checks it against an embedded schema and the AdE semantic rules (official codes). - SdiReceiptReader reads RC, NS, MC, NE, DT, AT, MT and SE notifications. - The incoming-invoice model becomes the shared EInvoice* model, read and written. - In-house ImapClient and MimeParser (no external libraries) back the PEC channel; SdICoop (SOAP/MTOM with client certificate) and two generic REST intermediaries sit behind the same IEInvoiceTransport contract, with fake-server tests. Co-Authored-By: Claude Opus 5.5 --- .../Purchases/PurchaseInvoiceImportService.cs | 16 +- src/Khaemhat.Fiscal.Abstractions/EInvoices.cs | 253 +++++++ .../EInvoicing.cs | 280 ++++++++ .../IncomingInvoices.cs | 185 +---- .../Data/FatturaPA_v1.2_khaemhat.xsd | 558 +++++++++++++++ src/Khaemhat.Fiscal.Italy/FatturaPaReader.cs | 125 +++- .../FatturaPaValidator.cs | 513 ++++++++++++++ src/Khaemhat.Fiscal.Italy/FatturaPaWriter.cs | 655 ++++++++++++++++++ src/Khaemhat.Fiscal.Italy/ItalianRules.cs | 2 +- src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs | 4 + .../Khaemhat.Fiscal.Italy.csproj | 1 + .../Sdi/IntermediaryTransports.cs | 355 ++++++++++ .../Sdi/PecSdiTransport.cs | 276 ++++++++ .../Sdi/SdiCoopTransport.cs | 322 +++++++++ src/Khaemhat.Fiscal.Italy/SdiReceiptReader.cs | 120 ++++ .../Mail/ImapClient.cs | 431 ++++++++++++ .../Mail/MimeParser.cs | 541 +++++++++++++++ .../Pages/Purchases/PurchaseImportPage.razor | 2 +- .../FatturaPaReaderTests.cs | 22 +- .../FatturaPaWriterTests.cs | 335 +++++++++ .../Khaemhat.Fiscal.Italy.Tests.csproj | 2 + .../SdiReceiptReaderTests.cs | 102 +++ .../SdiTransportTests.cs | 345 +++++++++ .../Mail/FakeMailServers.cs | 477 +++++++++++++ .../Mail/MimeAndImapTests.cs | 151 ++++ .../Mail/PecSamples.cs | 86 +++ 26 files changed, 5916 insertions(+), 243 deletions(-) create mode 100644 src/Khaemhat.Fiscal.Abstractions/EInvoices.cs create mode 100644 src/Khaemhat.Fiscal.Abstractions/EInvoicing.cs create mode 100644 src/Khaemhat.Fiscal.Italy/Data/FatturaPA_v1.2_khaemhat.xsd create mode 100644 src/Khaemhat.Fiscal.Italy/FatturaPaValidator.cs create mode 100644 src/Khaemhat.Fiscal.Italy/FatturaPaWriter.cs create mode 100644 src/Khaemhat.Fiscal.Italy/Sdi/IntermediaryTransports.cs create mode 100644 src/Khaemhat.Fiscal.Italy/Sdi/PecSdiTransport.cs create mode 100644 src/Khaemhat.Fiscal.Italy/Sdi/SdiCoopTransport.cs create mode 100644 src/Khaemhat.Fiscal.Italy/SdiReceiptReader.cs create mode 100644 src/Khaemhat.Infrastructure/Mail/ImapClient.cs create mode 100644 src/Khaemhat.Infrastructure/Mail/MimeParser.cs create mode 100644 tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaWriterTests.cs create mode 100644 tests/Khaemhat.Fiscal.Italy.Tests/SdiReceiptReaderTests.cs create mode 100644 tests/Khaemhat.Fiscal.Italy.Tests/SdiTransportTests.cs create mode 100644 tests/Khaemhat.Infrastructure.Tests/Mail/FakeMailServers.cs create mode 100644 tests/Khaemhat.Infrastructure.Tests/Mail/MimeAndImapTests.cs create mode 100644 tests/Khaemhat.Infrastructure.Tests/Mail/PecSamples.cs 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 parts, CancellationToken cancellationToken, string? shown = null) + { + var tag = "K" + (++_tag).ToString("D4", CultureInfo.InvariantCulture); + var pending = new StringBuilder(tag).Append(' '); + foreach (var part in parts) + { + if (part is byte[] literal) + { + pending.Append('{').Append(literal.Length.ToString(CultureInfo.InvariantCulture)).Append("}\r\n"); + await WriteAsync(pending.ToString(), cancellationToken).ConfigureAwait(false); + pending.Clear(); + var go = await ReadUntaggedAsync(cancellationToken).ConfigureAwait(false); + if (!go.Text.StartsWith('+')) + { + throw new MailException($"The IMAP server refused a literal in {shown ?? parts[0]}: {go.Text}"); + } + + await _stream.WriteAsync(literal, cancellationToken).ConfigureAwait(false); + } + else + { + pending.Append((string)part); + } + } + + pending.Append("\r\n"); + await WriteAsync(pending.ToString(), cancellationToken).ConfigureAwait(false); + + var untagged = new List(); + while (true) + { + var response = await ReadUntaggedAsync(cancellationToken).ConfigureAwait(false); + if (response.Text.StartsWith(tag + " ", StringComparison.Ordinal)) + { + var rest = response.Text[(tag.Length + 1)..]; + var space = rest.IndexOf(' ', StringComparison.Ordinal); + var status = (space < 0 ? rest : rest[..space]).ToUpperInvariant(); + return new Reply(status, space < 0 ? string.Empty : rest[(space + 1)..], untagged); + } + + untagged.Add(response); + } + } + + private async Task WriteAsync(string text, CancellationToken cancellationToken) + { + await _stream.WriteAsync(Encoding.UTF8.GetBytes(text), cancellationToken).ConfigureAwait(false); + await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + // One response: a line, and when it ends with {n} the n bytes that follow and the rest of the line, repeated. + private async Task ReadUntaggedAsync(CancellationToken cancellationToken) + { + var text = new StringBuilder(); + var literals = new List(); + while (true) + { + var line = await ReadLineAsync(cancellationToken).ConfigureAwait(false); + text.Append(line); + var match = LiteralPattern().Match(line); + if (!match.Success) + { + return new Response(text.ToString(), literals); + } + + var length = long.Parse(match.Groups["n"].Value, CultureInfo.InvariantCulture); + if (length > MaxLiteral) + { + throw new MailException($"The IMAP server sent a literal of {length} bytes, more than {MaxLiteral}."); + } + + literals.Add(await ReadExactAsync((int)length, cancellationToken).ConfigureAwait(false)); + } + } + + private async Task ReadLineAsync(CancellationToken cancellationToken) + { + using var line = new MemoryStream(); + while (true) + { + if (_start == _end) + { + await FillAsync(cancellationToken).ConfigureAwait(false); + } + + var index = Array.IndexOf(_buffer, (byte)'\n', _start, _end - _start); + if (index < 0) + { + line.Write(_buffer, _start, _end - _start); + _start = _end; + if (line.Length > MaxLine) + { + throw new MailException("The IMAP server sent a line longer than " + MaxLine + " bytes."); + } + + continue; + } + + line.Write(_buffer, _start, index - _start); + _start = index + 1; + return Encoding.UTF8.GetString(line.GetBuffer(), 0, (int)line.Length).TrimEnd('\r'); + } + } + + private async Task ReadExactAsync(int length, CancellationToken cancellationToken) + { + var result = new byte[length]; + var written = 0; + while (written < length) + { + if (_start == _end) + { + await FillAsync(cancellationToken).ConfigureAwait(false); + } + + var take = Math.Min(length - written, _end - _start); + Array.Copy(_buffer, _start, result, written, take); + _start += take; + written += take; + } + + return result; + } + + private async Task FillAsync(CancellationToken cancellationToken) + { + int read; + try + { + read = await _stream.ReadAsync(_buffer, cancellationToken).ConfigureAwait(false); + } + catch (IOException ex) + { + throw new MailException("The IMAP connection failed: " + ex.Message, ex); + } + + if (read == 0) + { + throw new MailException("The IMAP server closed the connection."); + } + + _start = 0; + _end = read; + } + + [GeneratedRegex(@"\{(?[0-9]{1,10})\+?\}$", RegexOptions.CultureInvariant)] + private static partial Regex LiteralPattern(); + + [GeneratedRegex(@"^\* (?[0-9]+) EXISTS", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex ExistsPattern(); + + private sealed record Response(string Text, IReadOnlyList Literals); + + private sealed record Reply(string Status, string Text, IReadOnlyList Untagged); +} diff --git a/src/Khaemhat.Infrastructure/Mail/MimeParser.cs b/src/Khaemhat.Infrastructure/Mail/MimeParser.cs new file mode 100644 index 0000000..d297e0e --- /dev/null +++ b/src/Khaemhat.Infrastructure/Mail/MimeParser.cs @@ -0,0 +1,541 @@ +using System.Globalization; +using System.Text; + +namespace Khaemhat.Infrastructure.Mail; + +/// A part of a MIME message: headers and body, or the parts of a multipart, or an enclosed message. +public sealed class MimePart +{ + /// The headers, names in lower case; repeated headers keep the first value. + public required IReadOnlyDictionary Headers { get; init; } + + /// The media type in lower case, such as multipart/mixed or application/xml. + public required string MediaType { get; init; } + + /// The parameters of Content-Type (boundary, charset, name), names in lower case. + public required IReadOnlyDictionary TypeParameters { get; init; } + + /// The decoded body (transfer encoding removed); empty for a multipart. + public byte[] Body { get; init; } = []; + + /// The parts of a multipart. + public IReadOnlyList Parts { get; init; } = []; + + /// The message enclosed in a message/rfc822 part. + public MimePart? Enclosed { get; init; } + + /// The file name, from Content-Disposition or Content-Type, decoded. + public string? FileName { get; init; } + + /// A header by name. + /// The name, any case. + /// The value, decoded, or . + public string? Header(string name) => Headers.TryGetValue(name.ToLowerInvariant(), out var value) ? value : null; + + /// The body as text, in its charset (UTF-8 when not declared). + /// The text. + public string Text() => MimeParser.CharsetOf(TypeParameters.TryGetValue("charset", out var charset) ? charset : null).GetString(Body); + + /// Every part with a file name, also inside multiparts and enclosed messages, in order. + /// The attachments. + public IEnumerable Attachments() + { + if (FileName is not null && Parts.Count == 0 && Enclosed is null) + { + yield return this; + } + + foreach (var part in Parts) + { + foreach (var attachment in part.Attachments()) + { + yield return attachment; + } + } + + if (Enclosed is not null) + { + foreach (var attachment in Enclosed.Attachments()) + { + yield return attachment; + } + } + } +} + +/// +/// Reads MIME messages (RFC 5322, 2045-2047, 2231) written in house for the PEC channel of the SDI (SPEC §11.9, +/// issue #76): headers with folded lines and encoded words, multiparts at any depth, enclosed messages +/// (message/rfc822, the postacert.eml of a certified mail), bodies in base64, quoted-printable, 7bit and +/// 8bit, file names in filename, filename* and name. +/// +/// Malformed input does not throw: a part whose boundary never closes ends with the message, a broken base64 +/// body is decoded as far as it goes. Nesting is limited to 10 levels. +public static class MimeParser +{ + private const int MaxDepth = 10; + + /// Parses a message. + /// The raw message. + /// The root part. + public static MimePart Parse(byte[] message) + { + ArgumentNullException.ThrowIfNull(message); + return ParsePart(message, 0, message.Length, 0); + } + + /// The encoding of a charset name, UTF-8 when unknown. + /// The name. + /// The encoding. + public static Encoding CharsetOf(string? charset) + { + switch (charset?.Trim().Trim('"').ToLowerInvariant()) + { + case null or "" or "utf-8" or "utf8" or "us-ascii" or "ascii": + return new UTF8Encoding(false); + case "iso-8859-1" or "latin1": + return Encoding.Latin1; + case "windows-1252" or "cp1252": + return CodePagesEncodingProvider.Instance.GetEncoding(1252) ?? Encoding.Latin1; + case "iso-8859-15": + return CodePagesEncodingProvider.Instance.GetEncoding(28605) ?? Encoding.Latin1; + default: + try + { + return Encoding.GetEncoding(charset!.Trim().Trim('"')); + } + catch (ArgumentException) + { + return new UTF8Encoding(false); + } + } + } + + /// Decodes the encoded words of a header (=?utf-8?B?...?=, =?iso-8859-1?Q?...?=). + /// The raw value. + /// The text. + public static string DecodeHeader(string value) + { + ArgumentNullException.ThrowIfNull(value); + var text = new StringBuilder(); + var position = 0; + var lastWasEncoded = false; + while (position < value.Length) + { + var start = value.IndexOf("=?", position, StringComparison.Ordinal); + var decoded = start < 0 ? null : TryDecodeWord(value, start, out var end, out var word) ? (end, word) : ((int, string)?)null; + if (decoded is null) + { + var next = start < 0 ? value.Length : start + 2; + text.Append(value, position, next - position); + position = next; + lastWasEncoded = false; + continue; + } + + // White space between two encoded words is not part of the text (RFC 2047 §6.2). + var between = value[position..start]; + if (!(lastWasEncoded && string.IsNullOrWhiteSpace(between))) + { + text.Append(between); + } + + text.Append(decoded.Value.Item2); + position = decoded.Value.Item1; + lastWasEncoded = true; + } + + return text.ToString(); + } + + private static bool TryDecodeWord(string value, int start, out int end, out string word) + { + end = start; + word = string.Empty; + var q1 = value.IndexOf('?', start + 2); + var q2 = q1 < 0 ? -1 : value.IndexOf('?', q1 + 1); + var close = q2 < 0 ? -1 : value.IndexOf("?=", q2 + 1, StringComparison.Ordinal); + if (close < 0) + { + return false; + } + + var charset = value[(start + 2)..q1]; + var star = charset.IndexOf('*', StringComparison.Ordinal); + if (star >= 0) + { + charset = charset[..star]; + } + + var mode = value[(q1 + 1)..q2].ToUpperInvariant(); + var payload = value[(q2 + 1)..close]; + byte[] bytes; + if (mode == "B") + { + bytes = Base64(Encoding.ASCII.GetBytes(payload)); + } + else if (mode == "Q") + { + bytes = QuotedPrintable(Encoding.ASCII.GetBytes(payload.Replace('_', ' '))); + } + else + { + return false; + } + + word = CharsetOf(charset).GetString(bytes); + end = close + 2; + return true; + } + + // --- Parts ------------------------------------------------------------------------------------------------------- + + private static MimePart ParsePart(byte[] data, int start, int end, int depth) + { + var (headers, bodyStart) = ReadHeaders(data, start, end); + var (mediaType, parameters) = ContentType(headers.TryGetValue("content-type", out var type) ? type : "text/plain"); + var disposition = headers.TryGetValue("content-disposition", out var d) ? Parameters(d) : new Dictionary(StringComparer.Ordinal); + var fileName = disposition.GetValueOrDefault("filename") ?? parameters.GetValueOrDefault("name"); + + if (mediaType.StartsWith("multipart/", StringComparison.Ordinal) && parameters.TryGetValue("boundary", out var boundary) && depth < MaxDepth) + { + return new MimePart + { + Headers = headers, + MediaType = mediaType, + TypeParameters = parameters, + Parts = SplitMultipart(data, bodyStart, end, boundary).Select(p => ParsePart(data, p.Start, p.End, depth + 1)).ToList(), + FileName = fileName, + }; + } + + var body = Decode(data, bodyStart, end, headers.TryGetValue("content-transfer-encoding", out var encoding) ? encoding : null); + if (mediaType == "message/rfc822" && depth < MaxDepth) + { + return new MimePart + { + Headers = headers, + MediaType = mediaType, + TypeParameters = parameters, + Body = body, + Enclosed = ParsePart(body, 0, body.Length, depth + 1), + FileName = fileName, + }; + } + + return new MimePart { Headers = headers, MediaType = mediaType, TypeParameters = parameters, Body = body, FileName = fileName }; + } + + private static (Dictionary Headers, int BodyStart) ReadHeaders(byte[] data, int start, int end) + { + var headers = new Dictionary(StringComparer.Ordinal); + var position = start; + string? name = null; + var value = new StringBuilder(); + void Flush() + { + if (name is not null && !headers.ContainsKey(name)) + { + headers[name] = DecodeHeader(value.ToString().Trim()); + } + + name = null; + value.Clear(); + } + + while (position < end) + { + var lineEnd = IndexOf(data, (byte)'\n', position, end); + var next = lineEnd < 0 ? end : lineEnd + 1; + var line = Encoding.Latin1.GetString(data, position, (lineEnd < 0 ? end : lineEnd) - position).TrimEnd('\r'); + position = next; + if (line.Length == 0) + { + Flush(); + return (headers, position); + } + + if ((line[0] == ' ' || line[0] == '\t') && name is not null) + { + value.Append(' ').Append(line.Trim()); + continue; + } + + Flush(); + var colon = line.IndexOf(':', StringComparison.Ordinal); + if (colon > 0) + { + name = line[..colon].Trim().ToLowerInvariant(); + value.Append(line[(colon + 1)..]); + } + } + + Flush(); + return (headers, end); + } + + private static List<(int Start, int End)> SplitMultipart(byte[] data, int start, int end, string boundary) + { + var delimiter = Encoding.ASCII.GetBytes("--" + boundary); + var parts = new List<(int, int)>(); + int? partStart = null; + var position = start; + while (position < end) + { + var lineEnd = IndexOf(data, (byte)'\n', position, end); + var contentEnd = lineEnd < 0 ? end : lineEnd; + var next = lineEnd < 0 ? end : lineEnd + 1; + if (StartsWith(data, position, contentEnd, delimiter)) + { + var rest = Encoding.ASCII.GetString(data, position + delimiter.Length, contentEnd - position - delimiter.Length).TrimEnd('\r', ' ', '\t'); + if (rest is "" or "--") + { + if (partStart is { } open) + { + // The line break before the delimiter belongs to the delimiter. + var close = position; + if (close > open && data[close - 1] == '\n') + { + close--; + } + + if (close > open && data[close - 1] == '\r') + { + close--; + } + + parts.Add((open, close)); + } + + if (rest == "--") + { + return parts; + } + + partStart = next; + } + } + + position = next; + } + + if (partStart is { } last && last < end) + { + parts.Add((last, end)); + } + + return parts; + } + + private static byte[] Decode(byte[] data, int start, int end, string? encoding) + { + var slice = data.AsSpan(start, Math.Max(0, end - start)).ToArray(); + return encoding?.Trim().ToLowerInvariant() switch + { + "base64" => Base64(slice), + "quoted-printable" => QuotedPrintable(slice), + _ => slice, + }; + } + + /// Decodes base64, ignoring line breaks and stopping at the first character that is not base64. + /// The encoded bytes. + /// The decoded bytes. + public static byte[] Base64(byte[] text) + { + ArgumentNullException.ThrowIfNull(text); + var clean = new StringBuilder(text.Length); + foreach (var b in text) + { + var c = (char)b; + if (char.IsAsciiLetterOrDigit(c) || c is '+' or '/' or '=') + { + clean.Append(c); + } + } + + var value = clean.ToString().TrimEnd('='); + value = (value.Length % 4) switch + { + 2 => value + "==", + 3 => value + "=", + 1 => value[..^1], + _ => value, + }; + var buffer = new byte[value.Length / 4 * 3 + 3]; + return Convert.TryFromBase64String(value, buffer, out var written) ? buffer[..written] : []; + } + + /// Decodes quoted-printable (soft line breaks removed). + /// The encoded bytes. + /// The decoded bytes. + public static byte[] QuotedPrintable(byte[] text) + { + ArgumentNullException.ThrowIfNull(text); + using var output = new MemoryStream(text.Length); + for (var i = 0; i < text.Length; i++) + { + var b = text[i]; + if (b != '=') + { + output.WriteByte(b); + continue; + } + + if (i + 1 < text.Length && text[i + 1] == '\n') + { + i++; + continue; + } + + if (i + 2 < text.Length && text[i + 1] == '\r' && text[i + 2] == '\n') + { + i += 2; + continue; + } + + if (i + 2 < text.Length && byte.TryParse(Encoding.ASCII.GetString(text, i + 1, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var value)) + { + output.WriteByte(value); + i += 2; + continue; + } + + output.WriteByte(b); + } + + return output.ToArray(); + } + + private static (string MediaType, Dictionary Parameters) ContentType(string value) + { + var semicolon = value.IndexOf(';', StringComparison.Ordinal); + var mediaType = (semicolon < 0 ? value : value[..semicolon]).Trim().ToLowerInvariant(); + return (mediaType.Length == 0 ? "text/plain" : mediaType, Parameters(value)); + } + + // The parameters after the first ';': name=value, name="quoted value", and RFC 2231 name*=charset''encoded and + // name*0=..., name*1=... continuations, joined. + private static Dictionary Parameters(string value) + { + var raw = new List<(string Name, string Value)>(); + var position = value.IndexOf(';', StringComparison.Ordinal); + while (position >= 0 && position < value.Length) + { + position++; + var equals = value.IndexOf('=', position); + if (equals < 0) + { + break; + } + + var name = value[position..equals].Trim().ToLowerInvariant(); + position = equals + 1; + while (position < value.Length && value[position] == ' ') + { + position++; + } + + string parameter; + if (position < value.Length && value[position] == '"') + { + var close = position + 1; + var quoted = new StringBuilder(); + while (close < value.Length && value[close] != '"') + { + if (value[close] == '\\' && close + 1 < value.Length) + { + close++; + } + + quoted.Append(value[close]); + close++; + } + + parameter = quoted.ToString(); + position = value.IndexOf(';', Math.Min(close + 1, value.Length)); + } + else + { + var semicolon = value.IndexOf(';', position); + parameter = (semicolon < 0 ? value[position..] : value[position..semicolon]).Trim(); + position = semicolon; + } + + raw.Add((name, parameter)); + } + + var result = new Dictionary(StringComparer.Ordinal); + foreach (var group in raw.GroupBy(p => p.Name.Split('*')[0])) + { + var extended = group.Where(p => p.Name.Contains('*', StringComparison.Ordinal)).ToList(); + if (extended.Count == 0) + { + result[group.Key] = DecodeHeader(group.First().Value); + continue; + } + + var ordered = extended + .OrderBy(p => int.TryParse(p.Name.Split('*').ElementAtOrDefault(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) ? n : 0) + .ToList(); + var charset = "utf-8"; + var bytes = new List(); + foreach (var (name, part) in ordered) + { + var text = part; + if (name.EndsWith('*')) + { + var first = text.IndexOf('\'', StringComparison.Ordinal); + var second = first < 0 ? -1 : text.IndexOf('\'', first + 1); + if (second > first) + { + if (first > 0) + { + charset = text[..first]; + } + + text = text[(second + 1)..]; + } + + bytes.AddRange(PercentDecode(text)); + } + else + { + bytes.AddRange(Encoding.UTF8.GetBytes(text)); + } + } + + result[group.Key] = CharsetOf(charset).GetString(bytes.ToArray()); + } + + return result; + } + + private static byte[] PercentDecode(string text) + { + var output = new List(text.Length); + for (var i = 0; i < text.Length; i++) + { + if (text[i] == '%' && i + 2 < text.Length && byte.TryParse(text.AsSpan(i + 1, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var value)) + { + output.Add(value); + i += 2; + } + else + { + output.AddRange(Encoding.UTF8.GetBytes(text[i].ToString())); + } + } + + return [.. output]; + } + + private static int IndexOf(byte[] data, byte value, int start, int end) + { + var index = Array.IndexOf(data, value, start, end - start); + return index; + } + + private static bool StartsWith(byte[] data, int start, int end, byte[] prefix) => + end - start >= prefix.Length && data.AsSpan(start, prefix.Length).SequenceEqual(prefix); +} diff --git a/src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor b/src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor index 3196542..c0995b3 100644 --- a/src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Purchases/PurchaseImportPage.razor @@ -277,7 +277,7 @@ else private string ShownTitle => _shown is { } shown ? shown.File.Supplier.DisplayName + " · " + shown.Invoice.Number : T["Purchases.Import.View"]; - private IReadOnlyList SummaryOf(IncomingInvoice invoice) => + private IReadOnlyList SummaryOf(EInvoiceBody invoice) => [ new(T["Sales.Totals.Taxable"], T.Money(invoice.TaxSummary.Sum(t => t.Taxable))), new(T["Sales.Totals.Tax"], T.Money(invoice.TaxSummary.Sum(t => t.Tax))), diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs index 96fc5f6..b44aa5f 100644 --- a/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs +++ b/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaReaderTests.cs @@ -159,7 +159,7 @@ public sealed class FatturaPaReaderTests 22.00100.0022.00I """; - private static IncomingInvoiceFile Read(string xml, string fileName = FileName) => Reader.Read(fileName, Encoding.UTF8.GetBytes(xml)); + private static EInvoiceFile Read(string xml, string fileName = FileName) => Reader.Read(fileName, Encoding.UTF8.GetBytes(xml)); [TestMethod] public void Read_OrdinaryInvoice_ReadsHeaderPartiesAndTransmission() @@ -209,14 +209,14 @@ public sealed class FatturaPaReaderTests Assert.IsNull(invoice.Rounding); CollectionAssert.AreEqual(new[] { "Fornitura di marzo", "Consegna in cantiere" }, invoice.Causals.ToArray()); Assert.IsFalse(invoice.Art73); - Assert.AreEqual(new IncomingDiscount(false, 2.00m, null), invoice.Discounts[0]); - Assert.AreEqual(new IncomingDiscount(true, null, 1.50m), invoice.Discounts[1]); + Assert.AreEqual(new EInvoiceDiscount(false, 2.00m, null), invoice.Discounts[0]); + Assert.AreEqual(new EInvoiceDiscount(true, null, 1.50m), invoice.Discounts[1]); Assert.HasCount(3, invoice.Lines); var bolts = invoice.Lines[0]; Assert.AreEqual(1, bolts.Number); - Assert.AreEqual(new IncomingItemCode("SKU", "B-M8-ZN"), bolts.Codes[0]); - Assert.AreEqual(new IncomingItemCode("EAN", "8001234567895"), bolts.Codes[1]); + Assert.AreEqual(new EInvoiceItemCode("SKU", "B-M8-ZN"), bolts.Codes[0]); + Assert.AreEqual(new EInvoiceItemCode("EAN", "8001234567895"), bolts.Codes[1]); Assert.AreEqual("Bulloni M8 zincati", bolts.Description); Assert.AreEqual(100m, bolts.Quantity); Assert.AreEqual("PZ", bolts.Unit); @@ -224,7 +224,7 @@ public sealed class FatturaPaReaderTests Assert.AreEqual(45m, bolts.TotalPrice); Assert.AreEqual(22m, bolts.TaxRate); Assert.IsNull(bolts.Nature); - Assert.AreEqual(new IncomingDiscount(false, 10m, null), bolts.Discounts.Single()); + Assert.AreEqual(new EInvoiceDiscount(false, 10m, null), bolts.Discounts.Single()); Assert.IsFalse(bolts.Withheld); Assert.AreEqual(4m, invoice.Lines[1].TaxRate); @@ -238,13 +238,13 @@ public sealed class FatturaPaReaderTests Assert.AreEqual("CC-12", contribution.AdministrativeReference); Assert.HasCount(3, invoice.TaxSummary); - Assert.AreEqual(new IncomingTaxSummary(22m, null, 45m, 9.90m, "I", null, null, null), invoice.TaxSummary[0]); + Assert.AreEqual(new EInvoiceTaxSummary(22m, null, 45m, 9.90m, "I", null, null, null), invoice.TaxSummary[0]); Assert.AreEqual(4m, invoice.TaxSummary[1].Rate); Assert.AreEqual("N2.2", invoice.TaxSummary[2].Nature); Assert.AreEqual("Non soggetto art. 15 DPR 633/72", invoice.TaxSummary[2].LegalReference); Assert.HasCount(2, invoice.Payments); - Assert.AreEqual(new IncomingPayment("TP01", "MP05", new DateOnly(2026, 4, 30), 58.45m, "IT60X0542811101000000123456", null, null), invoice.Payments[0]); + Assert.AreEqual(new EInvoicePayment("TP01", "MP05", new DateOnly(2026, 4, 30), 58.45m, "IT60X0542811101000000123456", null, null), invoice.Payments[0]); Assert.AreEqual("BPMOIT22XXX", invoice.Payments[1].Bic); Assert.AreEqual("Ferramenta Piemontese S.r.l.", invoice.Payments[1].Beneficiary); Assert.IsEmpty(invoice.Attachments); @@ -377,9 +377,9 @@ public sealed class FatturaPaReaderTests Assert.AreEqual("Giulia", file.Supplier.FirstName); Assert.AreEqual("Bianchi", file.Supplier.LastName); Assert.AreEqual("Giulia Bianchi", file.Supplier.DisplayName); - Assert.AreEqual(new IncomingWithholding("RT01", 208m, 20m, "A"), invoice.Withholdings.Single()); - Assert.AreEqual(new IncomingStampDuty(true, 2m), invoice.StampDuty); - Assert.AreEqual(new IncomingSocialSecurity("TC01", 4m, 40m, 1000m, 22m, true, null), invoice.SocialSecurity.Single()); + Assert.AreEqual(new EInvoiceWithholding("RT01", 208m, 20m, "A"), invoice.Withholdings.Single()); + Assert.AreEqual(new EInvoiceStampDuty(true, 2m), invoice.StampDuty); + Assert.AreEqual(new EInvoiceSocialSecurity("TC01", 4m, 40m, 1000m, 22m, true, null), invoice.SocialSecurity.Single()); Assert.AreEqual(1270.88m, invoice.Total); Assert.AreEqual(0.01m, invoice.Rounding); Assert.IsTrue(invoice.Art73); diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaWriterTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaWriterTests.cs new file mode 100644 index 0000000..bbfc9a3 --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/FatturaPaWriterTests.cs @@ -0,0 +1,335 @@ +using System.Text; +using System.Xml.Linq; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy.Tests; + +/// +/// The writer and the validator of FatturaPA (issue #74): every file written is valid against the schema, reads back to +/// the same content and passes the checks of the exchange system; each check is shown failing on a broken invoice. +/// The parties are fictitious, with VAT numbers that only pass the check digit. +/// +[TestClass] +public sealed class FatturaPaWriterTests +{ + private static readonly FatturaPaWriter Writer = new(); + private static readonly FatturaPaValidator Validator = new(); + private static readonly FatturaPaReader Reader = new(); + + /// The company: an Italian limited company in the companies register. + public static EInvoiceParty Company { get; } = new( + "IT", "01234567897", "01234567897", "Khaemhat Demo S.r.l.", null, null, + "Via dei Granai", "57", "10121", "Torino", "TO", "IT", "RF01", "amministrazione@demo.example", "011 555 1234", "TO", "123456") + { + ShareCapital = 10_000m, + Shareholders = "SU", + LiquidationStatus = "LN", + }; + + /// A business customer. + public static EInvoiceParty Customer { get; } = new( + "IT", "09876543217", null, "Officine Esempio S.p.A.", null, null, + "Corso Milano", "4", "20121", "Milano", "MI", "IT", null, null, null, null, null); + + /// An invoice with two rates, a discount, a delivery note and two installments. + /// The file. + public static EInvoiceFile Invoice() => new( + "IT01234567897_00001.xml", "FPR12", "00001", "ABC1234", Company, Customer, + [ + new EInvoiceBody( + "TD01", "EUR", new DateOnly(2026, 10, 9), "FT/2026/000414", 1_311.62m, null, + ["Fornitura di ottobre"], false, [], null, [], [], + [new EInvoiceReference("ORD-77", new DateOnly(2026, 9, 30), [], null, null)], [], [], + [new EInvoiceReference("DDT/2026/88", new DateOnly(2026, 10, 2), [1, 2], null, null)], + [ + new EInvoiceLine(1, [new EInvoiceItemCode("INTERNO", "VIT-08")], "Viti autofilettanti 8 mm", 100m, "PZ", 0.85m, 80.75m, 22m, null, + [new EInvoiceDiscount(false, 5m, null)], false, null, null, null, null), + new EInvoiceLine(2, [], "Trapano a percussione", 2m, "PZ", 489.50m, 979m, 22m, null, [], false, null, null, null, null), + new EInvoiceLine(3, [], "Manuale tecnico", 1m, "PZ", 18m, 18m, 4m, null, [], false, null, null, null, null), + ], + [ + new EInvoiceTaxSummary(22m, null, 1_059.75m, 233.15m, "I", null, null, null), + new EInvoiceTaxSummary(4m, null, 18m, 0.72m, "I", null, null, null), + ], + [ + new EInvoicePayment("TP01", "MP05", new DateOnly(2026, 11, 30), 655.81m, "IT60X0542811101000000123456", null, null), + new EInvoicePayment("TP01", "MP05", new DateOnly(2026, 12, 31), 655.81m, "IT60X0542811101000000123456", null, null), + ], + []), + ], + null, []) + { + TransmitterCountry = "IT", + TransmitterId = "01234567897", + }; + + [TestMethod] + public void FileName_UsesTheTransmitterAndAFiveCharacterBase36Progressive() + { + Assert.AreEqual("IT01234567897_00001.xml", Writer.FileName("IT", "01234567897", 1)); + Assert.AreEqual("00010", Writer.Progressive(36)); + Assert.AreEqual("0000Z", Writer.Progressive(35)); + Assert.AreEqual("ZZZZZ", Writer.Progressive(60_466_175)); + Assert.ThrowsExactly(() => Writer.Progressive(0)); + } + + [TestMethod] + public void Write_Invoice_IsValidAgainstTheSchemaAndPassesTheChecks() + { + var file = Invoice(); + Assert.IsEmpty(Validator.Validate(file).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList()); + + var xml = Writer.Write(file); + + var problems = Validator.ValidateXml(xml); + Assert.IsEmpty(problems, string.Join("\n", problems.Select(p => p.Path + ": " + p.Message))); + } + + [TestMethod] + public void Write_Invoice_ReadsBackToTheSameContent() + { + var file = Invoice(); + + var read = Reader.Read(file.FileName, Writer.Write(file)); + + Assert.AreEqual("FPR12", read.TransmissionFormat); + Assert.AreEqual("ABC1234", read.RecipientCode); + Assert.AreEqual("01234567897", read.TransmitterId); + Assert.AreEqual("Khaemhat Demo S.r.l.", read.Supplier.Name); + Assert.AreEqual(10_000m, read.Supplier.ShareCapital); + Assert.AreEqual("SU", read.Supplier.Shareholders); + Assert.AreEqual("0115551234", read.Supplier.Phone); + var body = read.Invoices.Single(); + Assert.AreEqual("FT/2026/000414", body.Number); + Assert.AreEqual(1_311.62m, body.Total); + Assert.HasCount(3, body.Lines); + Assert.AreEqual(80.75m, body.Lines[0].TotalPrice); + Assert.AreEqual(5m, body.Lines[0].Discounts.Single().Percent); + Assert.AreEqual("VIT-08", body.Lines[0].Codes.Single().Value); + Assert.HasCount(2, body.TaxSummary); + Assert.AreEqual("DDT/2026/88", body.DeliveryNotes.Single().Id); + CollectionAssert.AreEqual(new[] { 1, 2 }, body.DeliveryNotes.Single().LineNumbers.ToArray()); + Assert.AreEqual("ORD-77", body.Orders.Single().Id); + Assert.HasCount(2, body.Payments); + Assert.AreEqual("TP01", body.PaymentConditions); + } + + [TestMethod] + public void Write_RootIsQualifiedAndChildrenAreNot() + { + var root = XDocument.Parse(Encoding.UTF8.GetString(Writer.Write(Invoice()))).Root!; + + Assert.AreEqual(FatturaPaWriter.Namespace, root.Name.NamespaceName); + Assert.AreEqual("FPR12", root.Attribute("versione")!.Value); + Assert.IsTrue(root.Elements().All(e => e.Name.NamespaceName.Length == 0)); + } + + [TestMethod] + public void Write_ProfessionalFee_WithWithholdingFundStampAndNature() + { + var professional = Company with { TaxRegime = "RF19" }; + var body = new EInvoiceBody( + "TD06", "EUR", new DateOnly(2026, 10, 12), "P/2026/7", 1_286.80m, null, [], false, + [new EInvoiceWithholding("RT01", 200m, 20m, "A")], new EInvoiceStampDuty(true, 2m), + [new EInvoiceSocialSecurity("TC04", 4m, 40m, 1_000m, 22m, false, null)], [], [], [], [], [], + [ + new EInvoiceLine(1, [], "Consulenza tecnica di ottobre", null, null, 1_000m, 1_000m, 22m, null, [], true, null, null, null, null), + new EInvoiceLine(2, [], "Diritti di segreteria anticipati", null, null, 16m, 16m, 0m, "N1", [], false, null, null, null, null), + ], + [ + new EInvoiceTaxSummary(22m, null, 1_040m, 228.80m, "I", null, null, null), + new EInvoiceTaxSummary(0m, "N1", 16m, 0m, null, "Art. 15 DPR 633/72", null, null), + ], + [new EInvoicePayment("TP02", "MP05", null, 1_086.80m, null, null, null)], + [new EInvoiceAttachment("cortesia.pdf", "PDF", "Copia di cortesia", Encoding.ASCII.GetBytes("%PDF-1.4"))]); + var file = Invoice() with { Supplier = professional, Invoices = [body] }; + + var errors = Validator.Validate(file).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList(); + Assert.IsEmpty(errors, string.Join("\n", errors)); + var xml = Writer.Write(file); + Assert.IsEmpty(Validator.ValidateXml(xml)); + var read = Reader.Read(file.FileName, xml).Invoices.Single(); + Assert.AreEqual(200m, read.Withholdings.Single().Amount); + Assert.AreEqual("TC04", read.SocialSecurity.Single().Fund); + Assert.AreEqual(2m, read.StampDuty!.Amount); + Assert.IsTrue(read.Lines[0].Withheld); + Assert.AreEqual("N1", read.Lines[1].Nature); + Assert.AreEqual("%PDF-1.4", Encoding.ASCII.GetString(read.Attachments.Single().Content)); + } + + [TestMethod] + public void Write_PublicAdministration_SplitPaymentWithCigCupAndIntentData() + { + var administration = Customer with { VatNumber = null, TaxCode = "80012345676", Name = "Comune di Esempio" }; + var line = new EInvoiceLine(1, [], "Manutenzione impianto", 1m, null, 1_000m, 1_000m, 22m, null, [], false, null, null, null, "UFF-12") + { + OtherData = [new EInvoiceOtherData("INTENTO", "26012345678901-000001", null, new DateOnly(2026, 1, 8))], + }; + var body = new EInvoiceBody( + "TD01", "EUR", new DateOnly(2026, 9, 30), "FT/2026/390", 1_220m, null, [], false, [], null, [], [], + [new EInvoiceReference("DET-2026-15", new DateOnly(2026, 6, 1), [], "ZAB1234567", "J51B26000010007")], [], [], [], + [line], + [new EInvoiceTaxSummary(22m, null, 1_000m, 220m, "S", null, null, null)], + [new EInvoicePayment("TP02", "MP05", new DateOnly(2026, 10, 30), 1_000m, "IT60X0542811101000000123456", null, null)], + []); + var file = Invoice() with { TransmissionFormat = "FPA12", RecipientCode = "UFE7GH", Customer = administration, Invoices = [body] }; + + Assert.IsEmpty(Validator.Validate(file).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList()); + var xml = Writer.Write(file); + Assert.IsEmpty(Validator.ValidateXml(xml)); + var read = Reader.Read(file.FileName, xml); + Assert.AreEqual("FPA12", read.TransmissionFormat); + Assert.AreEqual("ZAB1234567", read.Invoices[0].Orders.Single().Cig); + Assert.AreEqual("J51B26000010007", read.Invoices[0].Orders.Single().Cup); + Assert.AreEqual("S", read.Invoices[0].TaxSummary.Single().Exigibility); + Assert.AreEqual("INTENTO", read.Invoices[0].Lines[0].OtherData.Single().Type); + Assert.AreEqual("UFF-12", read.Invoices[0].Lines[0].AdministrativeReference); + } + + [TestMethod] + public void Write_ForeignCustomerAndConsumerWithPec() + { + var foreign = Customer with { CountryCode = "DE", VatNumber = "DE123456789", Country = "DE", PostalCode = "80331", Province = null, City = "München", Name = "Alpenbau GmbH" }; + var file = Invoice() with { RecipientCode = "XXXXXXX", Customer = foreign }; + var xml = Writer.Write(file); + Assert.IsEmpty(Validator.ValidateXml(xml)); + var read = Reader.Read(file.FileName, xml); + Assert.AreEqual("00000", read.Customer.PostalCode); + Assert.IsNull(read.Customer.Province); + Assert.AreEqual("München", read.Customer.City); + + var consumer = new EInvoiceParty("IT", null, "RSSMRA80A01H501U", null, "Mario", "Rossi", "Via Po", "1", "10124", "Torino", "TO", "IT", null, null, null, null, null); + var toConsumer = Invoice() with { RecipientCode = "0000000", RecipientPec = "mario.rossi@pec.example.it", Customer = consumer }; + Assert.IsEmpty(Validator.Validate(toConsumer).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList()); + var consumerXml = Writer.Write(toConsumer); + Assert.IsEmpty(Validator.ValidateXml(consumerXml)); + Assert.AreEqual("mario.rossi@pec.example.it", Reader.Read(toConsumer.FileName, consumerXml).RecipientPec); + } + + [TestMethod] + public void Write_TextOutsideLatin1_IsReplacedAndCut() + { + Assert.AreEqual("Viti 'speciali' - EUR 5...", FatturaPaWriter.Text("Viti ‘speciali’ — € 5…", 100)); + Assert.AreEqual("abc", FatturaPaWriter.Text("abcdef", 3)); + Assert.AreEqual("a ? b", FatturaPaWriter.Text("a 漢 b", 10)); + + var line = Invoice().Invoices[0].Lines[2] with { Description = "Manuale “tecnico” – ed. 2026 ✓" }; + var body = Invoice().Invoices[0] with { Lines = [.. Invoice().Invoices[0].Lines.Take(2), line] }; + Assert.IsEmpty(Validator.ValidateXml(Writer.Write(Invoice() with { Invoices = [body] }))); + } + + [TestMethod] + public void Write_LongCausal_IsSplitIntoFieldsOf200Characters() + { + var note = string.Join(' ', Enumerable.Repeat("Consegna al magazzino di via dei Granai.", 12)); + var body = Invoice().Invoices[0] with { Causals = [note] }; + + var root = XDocument.Parse(Encoding.UTF8.GetString(Writer.Write(Invoice() with { Invoices = [body] }))).Root!; + + var causals = root.Descendants("Causale").Select(c => c.Value).ToList(); + Assert.IsGreaterThan(1, causals.Count); + Assert.IsTrue(causals.All(c => c.Length <= 200)); + Assert.AreEqual(note.Replace(" ", string.Empty, StringComparison.Ordinal), string.Concat(causals).Replace(" ", string.Empty, StringComparison.Ordinal)); + } + + [TestMethod] + public void Validate_WrongLineTotal_Gives00423() + { + var body = Invoice().Invoices[0]; + var wrong = body with { Lines = [body.Lines[0] with { TotalPrice = 85m }, body.Lines[1], body.Lines[2]] }; + + var problems = Validator.Validate(Invoice() with { Invoices = [wrong] }); + + Assert.IsTrue(problems.Any(p => p.Code == "00423" && p.Path.Contains("DettaglioLinee[1]", StringComparison.Ordinal))); + } + + [TestMethod] + public void Validate_NatureRules_Give00400_00401_00445_00429() + { + var body = Invoice().Invoices[0]; + var noNature = body with { Lines = [.. body.Lines.Take(2), body.Lines[2] with { TaxRate = 0m }] }; + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [noNature] }).Any(p => p.Code == "00400")); + + var natureWithRate = body with { Lines = [.. body.Lines.Take(2), body.Lines[2] with { Nature = "N4" }] }; + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [natureWithRate] }).Any(p => p.Code == "00401")); + + var generic = body with + { + Lines = [.. body.Lines.Take(2), body.Lines[2] with { TaxRate = 0m, Nature = "N2" }], + TaxSummary = [body.TaxSummary[0], new EInvoiceTaxSummary(0m, "N2", 18m, 0m, null, "Art. 7", null, null)], + }; + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [generic] }).Any(p => p.Code == "00445")); + + var summaryWithout = body with { TaxSummary = [body.TaxSummary[0], new EInvoiceTaxSummary(0m, null, 18m, 0m, null, null, null, null)] }; + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [summaryWithout] }).Any(p => p.Code == "00429")); + } + + [TestMethod] + public void Validate_SummaryRules_Give00419_00421_00422() + { + var body = Invoice().Invoices[0]; + var missing = body with { TaxSummary = [body.TaxSummary[0]] }; + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [missing] }).Any(p => p.Code == "00419")); + + var wrongTax = body with { TaxSummary = [body.TaxSummary[0] with { Tax = 230m }, body.TaxSummary[1]] }; + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [wrongTax] }).Any(p => p.Code == "00421")); + + var wrongTaxable = body with { TaxSummary = [body.TaxSummary[0] with { Taxable = 1_070m, Tax = 235.40m }, body.TaxSummary[1]] }; + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [wrongTaxable] }).Any(p => p.Code == "00422")); + } + + [TestMethod] + public void Validate_RecipientAndCustomerRules() + { + Assert.IsTrue(Validator.Validate(Invoice() with { RecipientCode = "ABC123" }).Any(p => p.Code == "00427")); + Assert.IsTrue(Validator.Validate(Invoice() with { TransmissionFormat = "FPA12" }).Any(p => p.Code == "00427")); + Assert.IsTrue(Validator.Validate(Invoice() with { RecipientPec = "a@pec.example.it" }).Any(p => p.Code == "00426")); + Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Customer with { VatNumber = null, TaxCode = null } }).Any(p => p.Code == "00417")); + Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Customer with { VatNumber = "09876543210" } }).Any(p => p.Code == "00305")); + Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Customer with { TaxCode = "RSSMRA80A01H501X" } }).Any(p => p.Code == "00306")); + Assert.IsTrue(Validator.Validate(Invoice() with { TransmitterId = null }).Any(p => p.Code == "einvoice.transmitter")); + } + + [TestMethod] + public void Validate_SelfInvoiceRules_Give00471_00472_00473() + { + var body = Invoice().Invoices[0]; + Assert.IsTrue(Validator.Validate(Invoice() with { Customer = Company }).Any(p => p.Code == "00471")); + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [body with { DocumentType = "TD27" }] }).Any(p => p.Code == "00472")); + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [body with { DocumentType = "TD17" }] }).Any(p => p.Code == "00473")); + } + + [TestMethod] + public void Validate_WithholdingLinesWithoutData_Give00411() + { + var body = Invoice().Invoices[0]; + var withheld = body with { Lines = [body.Lines[0] with { Withheld = true }, body.Lines[1], body.Lines[2]] }; + + Assert.IsTrue(Validator.Validate(Invoice() with { Invoices = [withheld] }).Any(p => p.Code == "00411")); + } + + [TestMethod] + public void Validate_ExemptOverThresholdWithoutStamp_IsAWarning() + { + var body = Invoice().Invoices[0] with + { + Lines = [new EInvoiceLine(1, [], "Servizio esente", 1m, null, 100m, 100m, 0m, "N4", [], false, null, null, null, null)], + TaxSummary = [new EInvoiceTaxSummary(0m, "N4", 100m, 0m, null, "Art. 10 DPR 633/72", null, null)], + }; + + var problem = Validator.Validate(Invoice() with { Invoices = [body] }).Single(p => p.Code == "einvoice.stamp-duty"); + + Assert.AreEqual(EInvoiceProblemSeverity.Warning, problem.Severity); + } + + [TestMethod] + public void ValidateXml_BrokenFile_ReportsSchemaErrors() + { + var xml = Encoding.UTF8.GetString(Writer.Write(Invoice())).Replace("EUR", "EURO", StringComparison.Ordinal); + + var problems = Validator.ValidateXml(Encoding.UTF8.GetBytes(xml)); + + Assert.IsTrue(problems.Any(p => p.Code == "einvoice.xml.schema")); + Assert.AreEqual("einvoice.xml.malformed", Validator.ValidateXml(Encoding.UTF8.GetBytes(" + + diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/SdiReceiptReaderTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/SdiReceiptReaderTests.cs new file mode 100644 index 0000000..863299b --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/SdiReceiptReaderTests.cs @@ -0,0 +1,102 @@ +using System.Text; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy.Tests; + +/// The notifications of the SDI (issue #75), written here in the layout of MessaggiTypes v1.0. +[TestClass] +public sealed class SdiReceiptReaderTests +{ + private const string Ns = "http://www.fatturapa.gov.it/sdi/messaggi/v1.0"; + private static readonly SdiReceiptReader Reader = new(); + + /// A notification as the SDI writes it. + /// The root element. + /// The children. + /// The file. + public static byte[] Notification(string root, string body) => Encoding.UTF8.GetBytes( + $"""{body}"""); + + [TestMethod] + public void Read_DeliveryReceipt() + { + var content = Notification("RicevutaConsegna", """ + 111222333IT01234567897_00001.xmlabc + 2026-10-12T15:40:10.000+02:002026-10-12T15:41:00.000+02:00 + ABC1234Officine9001 + """); + + var receipt = Reader.Read("IT01234567897_00001_RC_001.xml", content); + + Assert.AreEqual(EInvoiceReceiptKind.Delivered, receipt.Kind); + Assert.AreEqual("RC", receipt.Code); + Assert.AreEqual("IT01234567897_00001.xml", receipt.InvoiceFileName); + Assert.AreEqual("111222333", receipt.ExchangeId); + Assert.AreEqual(new DateTimeOffset(2026, 10, 12, 15, 41, 0, TimeSpan.FromHours(2)), receipt.DeliveredAt); + Assert.AreEqual("9001", receipt.MessageId); + } + + [TestMethod] + public void Read_Rejection_ListsTheErrors() + { + var content = Notification("NotificaScarto", """ + 111222334IT01234567897_00002.xml + 2026-10-09T10:00:00 + + 003111.1.4 CodiceDestinatario non valido + 004232.2.1.11 PrezzoTotale non calcolato correttamenteVerificare + 9002 + """); + + var receipt = Reader.Read("IT01234567897_00002_NS_001.xml", content); + + Assert.AreEqual(EInvoiceReceiptKind.Rejected, receipt.Kind); + Assert.HasCount(2, receipt.Errors); + Assert.AreEqual("00311", receipt.Errors[0].Code); + Assert.AreEqual("Verificare", receipt.Errors[1].Hint); + } + + [TestMethod] + public void Read_OutcomeOfAnAdministration() + { + var content = Notification("NotificaEsito", """ + 555IT01234567897_00003.xml + 555EC02CIG errato + 9003 + """); + + var receipt = Reader.Read("IT01234567897_00003_NE_001.xml", content); + + Assert.AreEqual(EInvoiceReceiptKind.Outcome, receipt.Kind); + Assert.AreEqual("EC02", receipt.Outcome); + Assert.IsTrue(receipt.Refused); + Assert.AreEqual("CIG errato", receipt.Description); + } + + [TestMethod] + [DataRow("NotificaMancataConsegna", "MC", EInvoiceReceiptKind.NotDelivered)] + [DataRow("NotificaDecorrenzaTermini", "DT", EInvoiceReceiptKind.TermsElapsed)] + [DataRow("AttestazioneTrasmissioneFattura", "AT", EInvoiceReceiptKind.Undeliverable)] + [DataRow("FileMetadati", "MT", EInvoiceReceiptKind.Metadata)] + public void Read_OtherNotifications(string root, string code, EInvoiceReceiptKind kind) + { + var content = Notification(root, "777IT09876543217_0A1B2.xml.p7mABC12341"); + + var receipt = Reader.Read("anything.xml", content); + + Assert.AreEqual(kind, receipt.Kind); + Assert.AreEqual(code, receipt.Code); + Assert.AreEqual("777", receipt.ExchangeId); + Assert.AreEqual("IT09876543217_0A1B2.xml.p7m", receipt.InvoiceFileName); + } + + [TestMethod] + public void IsReceipt_ByNameOrRoot_AndNotForInvoices() + { + Assert.IsTrue(Reader.IsReceipt("IT01234567897_00001_NS_001.xml", [])); + Assert.IsTrue(Reader.IsReceipt("x.xml", Notification("RicevutaConsegna", string.Empty))); + Assert.IsFalse(Reader.IsReceipt("IT01234567897_00001.xml", Encoding.UTF8.GetBytes(""))); + Assert.AreEqual("MT", SdiReceiptReader.CodeOfName("IT09876543217_0A1B2_MT_001.xml")); + Assert.ThrowsExactly(() => Reader.Read("a.xml", Encoding.UTF8.GetBytes(""))); + } +} diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/SdiTransportTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/SdiTransportTests.cs new file mode 100644 index 0000000..6348f00 --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/SdiTransportTests.cs @@ -0,0 +1,345 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Text; +using System.Text.Json; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Fiscal.Italy.Sdi; +using Khaemhat.Infrastructure.Mail; +using Khaemhat.Infrastructure.Tests.Mail; + +namespace Khaemhat.Fiscal.Italy.Tests; + +[TestClass] +public sealed class PecSdiTransportTests +{ + private const string Mailbox = "fatture@pec.example.it"; + private const string Secret = "test-secret"; + + public TestContext TestContext { get; set; } = null!; + + private static EInvoiceChannelSettings Settings(FakeSmtpServer? smtp, FakeImapServer? imap, string? archive = null, string? exchange = null) => new() + { + Code = PecSdiTransport.ChannelCode, + Mailbox = Mailbox, + SmtpHost = "127.0.0.1", + SmtpPort = smtp?.Port ?? 1, + ImapHost = "127.0.0.1", + ImapPort = imap?.Port ?? 1, + Tls = false, + User = Mailbox, + Password = Secret, + ArchiveFolder = archive, + ExchangeAddress = exchange, + }; + + [TestMethod] + public async Task First_file_goes_to_sdi01_then_to_the_assigned_address() + { + await using var smtp = new FakeSmtpServer(); + var transport = new PecSdiTransport(); + var file = new EInvoiceOutgoing("IT01234567897_00001.xml", Encoding.UTF8.GetBytes(""), "FT 1/2026"); + + var first = await transport.SendAsync(Settings(smtp, null), file, TestContext.CancellationToken); + var next = await transport.SendAsync(Settings(smtp, null, exchange: "sdi23@pec.fatturapa.it"), file, TestContext.CancellationToken); + + Assert.IsTrue(first.Accepted, first.Error); + Assert.IsTrue(next.Accepted, next.Error); + var messages = smtp.Messages.ToList(); + Assert.AreEqual("sdi01@pec.fatturapa.it", messages[0].To.Single()); + Assert.AreEqual("sdi23@pec.fatturapa.it", messages[1].To.Single()); + Assert.AreEqual(Mailbox, messages[0].From); + + var sent = MimeParser.Parse(messages[0].Content); + var attachment = sent.Attachments().Single(); + Assert.AreEqual("IT01234567897_00001.xml", attachment.FileName); + CollectionAssert.AreEqual(file.Content, attachment.Body); + } + + [TestMethod] + public async Task Refused_recipient_is_reported_not_thrown() + { + await using var smtp = new FakeSmtpServer { RejectRecipient = "550 Mailbox unavailable" }; + + var result = await new PecSdiTransport().SendAsync(Settings(smtp, null), new EInvoiceOutgoing("a.xml", [1], null), TestContext.CancellationToken); + + Assert.IsFalse(result.Accepted); + StringAssert.Contains(result.Error, "550"); + } + + [TestMethod] + public async Task Fetch_reads_only_the_sdi_and_learns_its_address() + { + var receipt = Encoding.UTF8.GetBytes(""); + var invoice = Encoding.UTF8.GetBytes(""); + var metadata = Encoding.UTF8.GetBytes(""); + await using var imap = new FakeImapServer(Mailbox, Secret, + PecSamples.Envelope("sdi07@pec.fatturapa.it", "Ricevuta di consegna", ("IT01234567897_00001_RC_001.xml", receipt)), + PecSamples.Acceptance("Invio file IT01234567897_00002.xml"), + PecSamples.Envelope("sdi07@pec.fatturapa.it", "Invio File 99", ("IT09876543217_0A1B2.xml", invoice), ("IT09876543217_0A1B2_MT_001.xml", metadata))); + var transport = new PecSdiTransport(); + var settings = Settings(null, imap, archive: "Khaemhat/SDI"); + + var result = await transport.FetchAsync(settings, TestContext.CancellationToken); + + Assert.AreEqual(2, result.MessagesRead, "The acceptance of the provider is not a message of the SDI."); + CollectionAssert.AreEqual( + new[] { "IT01234567897_00001_RC_001.xml", "IT09876543217_0A1B2.xml", "IT09876543217_0A1B2_MT_001.xml" }, + result.Files.Select(f => f.FileName).ToList()); + Assert.AreEqual("sdi07@pec.fatturapa.it", result.ExchangeAddress); + Assert.AreEqual("sdi07@pec.fatturapa.it", result.Files[0].Sender); + CollectionAssert.AreEqual(receipt, result.Files[0].Content); + + await transport.AcknowledgeAsync(settings, result.Files.Select(f => f.MessageKey).ToList(), TestContext.CancellationToken); + + Assert.AreEqual(2, imap.Mailboxes["Khaemhat/SDI"].Count); + Assert.AreEqual(1, imap.Mailboxes["INBOX"].Count, "Only the acceptance of the provider is left."); + var again = await transport.FetchAsync(settings with { ExchangeAddress = "sdi07@pec.fatturapa.it" }, TestContext.CancellationToken); + Assert.AreEqual(0, again.Files.Count); + Assert.IsNull(again.ExchangeAddress, "The address did not change."); + } + + [TestMethod] + public async Task Without_archive_messages_are_marked_as_read() + { + await using var imap = new FakeImapServer(Mailbox, Secret, + PecSamples.Envelope("sdi01@pec.fatturapa.it", "Scarto", ("IT01234567897_00003_NS_001.xml", [1, 2]))); + var transport = new PecSdiTransport(); + var settings = Settings(null, imap); + + var first = await transport.FetchAsync(settings, TestContext.CancellationToken); + Assert.AreEqual(1, first.Files.Count); + Assert.AreEqual(1, (await transport.FetchAsync(settings, TestContext.CancellationToken)).Files.Count, "Not acknowledged: read again."); + + await transport.AcknowledgeAsync(settings, [first.Files[0].MessageKey], TestContext.CancellationToken); + + Assert.AreEqual(0, (await transport.FetchAsync(settings, TestContext.CancellationToken)).Files.Count); + Assert.IsTrue(imap.Mailboxes["INBOX"][0].Flags.Contains(@"\Seen")); + } + + [TestMethod] + public async Task Check_reports_login_and_missing_settings() + { + await using var smtp = new FakeSmtpServer(); + await using var imap = new FakeImapServer(Mailbox, Secret); + var transport = new PecSdiTransport(); + + var ok = await transport.CheckAsync(Settings(smtp, imap), TestContext.CancellationToken); + var wrong = await transport.CheckAsync(Settings(smtp, imap) with { Password = "other" }, TestContext.CancellationToken); + var missing = await transport.CheckAsync(new EInvoiceChannelSettings { Code = "PEC" }, TestContext.CancellationToken); + + Assert.IsTrue(ok.Success, ok.Message); + Assert.IsFalse(wrong.Success); + Assert.IsFalse(wrong.Message.Contains("other", StringComparison.Ordinal), "The password must not appear."); + Assert.IsFalse(missing.Success); + } + + [TestMethod] + public void Sdi_addresses_are_recognised() + { + Assert.AreEqual("sdi07@pec.fatturapa.it", PecSdiTransport.SdiAddress("\"Per conto di: SDI07@pec.fatturapa.it\" ")); + Assert.IsNull(PecSdiTransport.SdiAddress("info@fatturapa.it")); + } +} + +/// An HTTP handler that answers from a function and keeps the requests (with their bodies). +internal sealed class StubHandler(Func answer, ConcurrentQueue<(HttpRequestMessage Request, byte[] Body)> log) : HttpMessageHandler +{ + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var body = request.Content is null ? [] : await request.Content.ReadAsByteArrayAsync(cancellationToken); + log.Enqueue((request, body)); + return answer(request, body); + } +} + +[TestClass] +public sealed class SdiCoopTransportTests +{ + public TestContext TestContext { get; set; } = null!; + + private static HttpResponseMessage Soap(string body) => new(HttpStatusCode.OK) + { + Content = new StringContent( + "" + body + "", + Encoding.UTF8, + "text/xml"), + }; + + [TestMethod] + public async Task Send_posts_mtom_and_reads_the_identifier() + { + var log = new ConcurrentQueue<(HttpRequestMessage, byte[])>(); + var transport = new SdiCoopTransport(_ => new StubHandler((_, _) => Soap( + "1112223332026-11-13T10:00:00.000+01:00"), log)); + var content = Encoding.UTF8.GetBytes(""); + var settings = new EInvoiceChannelSettings { Code = "SDICOOP", TestEnvironment = true }; + + var result = await transport.SendAsync(settings, new EInvoiceOutgoing("IT01234567897_00001.xml", content, null), TestContext.CancellationToken); + + Assert.IsTrue(result.Accepted, result.Error); + Assert.AreEqual("111222333", result.ExchangeId); + var (request, body) = log.Single(); + Assert.AreEqual(SdiCoopTransport.TestEndpoint, request.RequestUri!.ToString()); + Assert.AreEqual("multipart/related", request.Content!.Headers.ContentType!.MediaType); + Assert.AreEqual("\"" + SdiCoopTransport.RiceviFileAction + "\"", request.Headers.GetValues("SOAPAction").Single()); + + // What the SDI would read: the envelope with the file put back in place of the reference. + var envelope = SdiCoopMessages.Envelope(request.Content.Headers.ContentType.ToString(), body)!; + Assert.AreEqual("IT01234567897_00001.xml", envelope.Descendants().Single(e => e.Name.LocalName == "NomeFile").Value); + CollectionAssert.AreEqual(content, Convert.FromBase64String(envelope.Descendants().Single(e => e.Name.LocalName == "File").Value)); + } + + [TestMethod] + public async Task Errors_of_the_service_are_reported() + { + var log = new ConcurrentQueue<(HttpRequestMessage, byte[])>(); + var error = new SdiCoopTransport(_ => new StubHandler((_, _) => Soap("EI03"), log)); + var fault = new SdiCoopTransport(_ => new StubHandler((_, _) => Soap("xBad request"), log)); + var settings = new EInvoiceChannelSettings { Code = "SDICOOP" }; + var file = new EInvoiceOutgoing("a.xml", [1], null); + + var refused = await error.SendAsync(settings, file, TestContext.CancellationToken); + var faulted = await fault.SendAsync(settings, file, TestContext.CancellationToken); + var noCertificate = await new SdiCoopTransport().SendAsync(settings, file, TestContext.CancellationToken); + + StringAssert.Contains(refused.Error, "EI03"); + StringAssert.Contains(faulted.Error, "Bad request"); + Assert.IsFalse(noCertificate.Accepted); + Assert.AreEqual(SdiCoopTransport.ProductionEndpoint, SdiCoopTransport.EndpointOf(settings)); + } + + [TestMethod] + public void Inbound_messages_are_read_inline_and_mtom() + { + var receipt = Convert.ToBase64String(Encoding.UTF8.GetBytes("")); + var inline = Encoding.UTF8.GetBytes( + "" + + "42IT01234567897_00001_NS_001.xml" + receipt + ""); + + var notification = SdiCoopMessages.Read("text/xml; charset=utf-8", inline)!; + + Assert.AreEqual("Notifica", notification.Operation); + Assert.AreEqual("42", notification.ExchangeId); + Assert.AreEqual("", Encoding.UTF8.GetString(notification.Files.Single().Content)); + Assert.IsFalse(SdiCoopMessages.Answer(notification).Contains("ER01", StringComparison.Ordinal)); + + const string Boundary = "uuid:b1"; + var mtom = Encoding.UTF8.GetBytes( + "--" + Boundary + "\r\nContent-Type: application/xop+xml; type=\"text/xml\"\r\nContent-ID: \r\n\r\n" + + "" + + "77IT09876543217_0A1B2.xml.p7m" + + "IT09876543217_0A1B2_MT_001.xml" + + "\r\n" + + "--" + Boundary + "\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\nContent-ID: \r\n\r\nP7M\r\n" + + "--" + Boundary + "\r\nContent-Type: application/octet-stream\r\nContent-ID: \r\n\r\n\r\n" + + "--" + Boundary + "--\r\n"); + + var invoice = SdiCoopMessages.Read("multipart/related; type=\"application/xop+xml\"; boundary=\"" + Boundary + "\"", mtom)!; + + Assert.AreEqual("RiceviFatture", invoice.Operation); + Assert.AreEqual("77", invoice.ExchangeId); + Assert.AreEqual("IT09876543217_0A1B2.xml.p7m", invoice.Files[0].FileName); + Assert.AreEqual("P7M", Encoding.UTF8.GetString(invoice.Files[0].Content)); + Assert.AreEqual("", Encoding.UTF8.GetString(invoice.Files[1].Content)); + StringAssert.Contains(SdiCoopMessages.Answer(invoice), "ER01"); + Assert.IsNull(SdiCoopMessages.Read("text/xml", Encoding.UTF8.GetBytes(""))); + StringAssert.Contains(SdiCoopMessages.Answer(null), "Fault"); + } +} + +[TestClass] +public sealed class IntermediaryTransportTests +{ + public TestContext TestContext { get; set; } = null!; + + private static HttpResponseMessage Json(object value, HttpStatusCode status = HttpStatusCode.OK) => + new(status) { Content = new StringContent(JsonSerializer.Serialize(value), Encoding.UTF8, "application/json") }; + + [TestMethod] + public async Task Intermediary_a_sends_lists_and_acknowledges() + { + var log = new ConcurrentQueue<(HttpRequestMessage Request, byte[] Body)>(); + var waiting = Convert.ToBase64String(Encoding.UTF8.GetBytes("")); + var transport = new IntermediaryATransport(_ => new StubHandler((request, _) => (request.Method.Method, request.RequestUri!.AbsolutePath) switch + { + ("POST", "/v1/invoices") => Json(new { id = "up-1", sdiId = (string?)null }), + ("GET", "/v1/files") => Json(new[] { new { id = "f-9", fileName = "IT01234567897_00001_RC_001.xml", content = waiting, receivedAt = "2026-11-13T09:00:00Z" } }), + ("POST", "/v1/files/f-9/ack") => new HttpResponseMessage(HttpStatusCode.NoContent), + ("GET", "/v1/status") => Json(new { ok = true }), + _ => new HttpResponseMessage(HttpStatusCode.NotFound), + }, log)); + var settings = new EInvoiceChannelSettings { Code = "INTA", Endpoint = "https://int-a.example/v1/", ApiKey = "test-key" }; + + var sent = await transport.SendAsync(settings, new EInvoiceOutgoing("IT01234567897_00001.xml", [1, 2, 3], null), TestContext.CancellationToken); + var fetched = await transport.FetchAsync(settings, TestContext.CancellationToken); + await transport.AcknowledgeAsync(settings, [fetched.Files[0].MessageKey], TestContext.CancellationToken); + var check = await transport.CheckAsync(settings, TestContext.CancellationToken); + + Assert.IsTrue(sent.Accepted, sent.Error); + Assert.AreEqual("up-1", sent.MessageId); + var post = log.First(); + Assert.AreEqual("Bearer", post.Request.Headers.Authorization!.Scheme); + Assert.AreEqual("IT01234567897_00001.xml", post.Request.Headers.GetValues("X-File-Name").Single()); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, post.Body); + Assert.AreEqual("IT01234567897_00001_RC_001.xml", fetched.Files.Single().FileName); + Assert.AreEqual("", Encoding.UTF8.GetString(fetched.Files[0].Content)); + Assert.IsTrue(log.Any(l => l.Request.RequestUri!.AbsolutePath == "/v1/files/f-9/ack")); + Assert.IsTrue(check.Success, check.Message); + } + + [TestMethod] + public async Task Intermediary_b_uses_basic_authentication_and_json() + { + var log = new ConcurrentQueue<(HttpRequestMessage Request, byte[] Body)>(); + var transport = new IntermediaryBTransport(_ => new StubHandler((request, _) => (request.Method.Method, request.RequestUri!.AbsolutePath) switch + { + ("POST", "/api/v1/send") => Json(new { uploadId = "u-5", identificativoSdi = "998877" }), + ("GET", "/api/v1/inbox") => Json(new { items = new[] { new { key = "k1", name = "IT09876543217_0A1B2.xml", data = Convert.ToBase64String([9]), date = "2026-11-12" } } }), + ("DELETE", "/api/v1/inbox/k1") => new HttpResponseMessage(HttpStatusCode.OK), + ("GET", "/api/v1/ping") => new HttpResponseMessage(HttpStatusCode.Unauthorized), + _ => new HttpResponseMessage(HttpStatusCode.NotFound), + }, log)); + var settings = new EInvoiceChannelSettings { Code = "INTB", Endpoint = "https://int-b.example", User = "azienda", Password = "test-secret" }; + + var sent = await transport.SendAsync(settings, new EInvoiceOutgoing("IT01234567897_00002.xml", [7], null), TestContext.CancellationToken); + var fetched = await transport.FetchAsync(settings, TestContext.CancellationToken); + await transport.AcknowledgeAsync(settings, ["k1"], TestContext.CancellationToken); + var check = await transport.CheckAsync(settings, TestContext.CancellationToken); + var missing = await transport.SendAsync(settings with { Password = null }, new EInvoiceOutgoing("a.xml", [1], null), TestContext.CancellationToken); + + Assert.AreEqual("998877", sent.ExchangeId); + Assert.AreEqual("Basic", log.First().Request.Headers.Authorization!.Scheme); + using (var body = JsonDocument.Parse(log.First().Body)) + { + Assert.AreEqual("IT01234567897_00002.xml", body.RootElement.GetProperty("fileName").GetString()); + } + + Assert.AreEqual("k1", fetched.Files.Single().MessageKey); + Assert.IsTrue(log.Any(l => l.Request.Method == HttpMethod.Delete)); + Assert.IsFalse(check.Success); + Assert.IsFalse(missing.Accepted); + } + + [TestMethod] + public async Task Refused_file_is_reported_with_the_message_of_the_api() + { + var log = new ConcurrentQueue<(HttpRequestMessage, byte[])>(); + var transport = new IntermediaryATransport(_ => new StubHandler((_, _) => Json(new { error = "Invalid XML" }, HttpStatusCode.UnprocessableEntity), log)); + + var result = await transport.SendAsync( + new EInvoiceChannelSettings { Code = "INTA", Endpoint = "https://a.example", ApiKey = "k" }, new EInvoiceOutgoing("a.xml", [1], null), TestContext.CancellationToken); + + Assert.IsFalse(result.Accepted); + Assert.AreEqual("422: Invalid XML", result.Error); + } + + [TestMethod] + public void The_pack_offers_the_four_channels() + { + var channels = new ItalyFiscalPack().GetFeature()!; + + CollectionAssert.AreEqual(new[] { "PEC", "SDICOOP", "INTA", "INTB" }, channels.All.Select(c => c.Code).ToList()); + Assert.IsFalse(channels.Find("sdicoop")!.Transport.Polls); + Assert.IsNull(channels.Find("X")); + } +} diff --git a/tests/Khaemhat.Infrastructure.Tests/Mail/FakeMailServers.cs b/tests/Khaemhat.Infrastructure.Tests/Mail/FakeMailServers.cs new file mode 100644 index 0000000..3ffc8cb --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Mail/FakeMailServers.cs @@ -0,0 +1,477 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.RegularExpressions; + +namespace Khaemhat.Infrastructure.Tests.Mail; + +/// A message held by . +internal sealed class FakeImapMessage(long uid, byte[] content) +{ + public long Uid { get; } = uid; + + public byte[] Content { get; } = content; + + public HashSet Flags { get; } = new(StringComparer.OrdinalIgnoreCase); +} + +/// +/// An IMAP server on the loopback interface, enough for the tests of the client and of the PEC channel: CAPABILITY, +/// LOGIN (quoted or literal), SELECT, UID SEARCH (ALL, UNSEEN, FROM, SINCE ignored), UID FETCH, UID STORE, UID MOVE, +/// UID COPY (NO [TRYCREATE] for a missing folder), CREATE, EXPUNGE, UID EXPUNGE, LOGOUT. One connection at a time. +/// +internal sealed partial class FakeImapServer : IAsyncDisposable +{ + private readonly TcpListener _listener = new(IPAddress.Loopback, 0); + private readonly CancellationTokenSource _stop = new(); + private readonly Task _loop; + private long _nextUid = 100; + + public FakeImapServer(string user, string password, params byte[][] messages) + { + User = user; + Password = password; + Mailboxes["INBOX"] = [.. messages.Select(m => new FakeImapMessage(_nextUid++, m))]; + _listener.Start(); + _loop = Task.Run(AcceptAsync); + } + + public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port; + + public string User { get; } + + public string Password { get; } + + /// Whether MOVE and UIDPLUS are announced. + public bool SupportsMove { get; init; } = true; + + public ConcurrentDictionary> Mailboxes { get; } = new(StringComparer.OrdinalIgnoreCase); + + public ConcurrentQueue Commands { get; } = new(); + + public void Add(byte[] message) => Mailboxes["INBOX"].Add(new FakeImapMessage(_nextUid++, message)); + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync(); + _listener.Stop(); + try + { + await _loop; + } + catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException) + { + } + + _stop.Dispose(); + } + + private async Task AcceptAsync() + { + while (!_stop.IsCancellationRequested) + { + TcpClient client; + try + { + client = await _listener.AcceptTcpClientAsync(_stop.Token); + } + catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException) + { + return; + } + + using (client) + { + try + { + await ServeAsync(client.GetStream()); + } + catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException) + { + } + } + } + } + + private async Task ServeAsync(NetworkStream stream) + { + var reader = new LineReader(stream); + async Task Send(string text) => await stream.WriteAsync(Encoding.ASCII.GetBytes(text + "\r\n"), _stop.Token); + await Send("* OK Fake IMAP ready"); + var authenticated = false; + List? selected = null; + while (true) + { + var (line, literals) = await reader.CommandAsync(() => Send("+ go ahead"), _stop.Token); + if (line is null) + { + return; + } + + Commands.Enqueue(line); + var space = line.IndexOf(' ', StringComparison.Ordinal); + var tag = line[..space]; + var rest = line[(space + 1)..]; + var verb = rest.Split(' ')[0].ToUpperInvariant(); + if (verb == "UID") + { + verb = "UID " + rest.Split(' ')[1].ToUpperInvariant(); + } + + switch (verb) + { + case "CAPABILITY": + await Send("* CAPABILITY IMAP4rev1" + (SupportsMove ? " MOVE UIDPLUS" : string.Empty)); + await Send(tag + " OK CAPABILITY completed"); + break; + case "LOGIN": + var values = Arguments(rest[6..], literals); + authenticated = values.Count == 2 && values[0] == User && values[1] == Password; + await Send(tag + (authenticated ? " OK LOGIN completed" : " NO [AUTHENTICATIONFAILED] Invalid credentials")); + break; + case "SELECT" when authenticated: + var name = Arguments(rest[7..], literals)[0]; + selected = Mailboxes.GetValueOrDefault(name); + await Send(selected is null ? tag + " NO Mailbox does not exist" : $"* {selected.Count} EXISTS"); + if (selected is not null) + { + await Send(tag + " OK [READ-WRITE] SELECT completed"); + } + + break; + case "UID SEARCH" when selected is not null: + var criteria = rest[11..]; + var found = selected.Where(m => + (!criteria.Contains("UNSEEN", StringComparison.OrdinalIgnoreCase) || !m.Flags.Contains(@"\Seen")) + && !m.Flags.Contains(@"\Deleted") + && (FromPattern().Match(criteria) is not { Success: true } from + || Encoding.Latin1.GetString(m.Content).Contains(from.Groups["v"].Value, StringComparison.OrdinalIgnoreCase))); + await Send("* SEARCH " + string.Join(' ', found.Select(m => m.Uid.ToString(CultureInfo.InvariantCulture)))); + await Send(tag + " OK SEARCH completed"); + break; + case "UID FETCH" when selected is not null: + var fetchUid = long.Parse(rest.Split(' ')[2], CultureInfo.InvariantCulture); + var message = selected.FirstOrDefault(m => m.Uid == fetchUid); + if (message is not null) + { + var index = selected.IndexOf(message) + 1; + await stream.WriteAsync(Encoding.ASCII.GetBytes($"* {index} FETCH (UID {message.Uid} BODY[] {{{message.Content.Length}}}\r\n"), _stop.Token); + await stream.WriteAsync(message.Content, _stop.Token); + await Send(")"); + } + + await Send(tag + " OK FETCH completed"); + break; + case "UID STORE" when selected is not null: + var storeUid = long.Parse(rest.Split(' ')[2], CultureInfo.InvariantCulture); + var flags = rest[(rest.IndexOf('(', StringComparison.Ordinal) + 1)..rest.LastIndexOf(')')]; + foreach (var m in selected.Where(m => m.Uid == storeUid)) + { + m.Flags.UnionWith(flags.Split(' ', StringSplitOptions.RemoveEmptyEntries)); + } + + await Send(tag + " OK STORE completed"); + break; + case "UID MOVE" or "UID COPY" when selected is not null: + var parts = rest.Split(' ', 4); + var uid = long.Parse(parts[2], CultureInfo.InvariantCulture); + var target = Arguments(parts[3], literals)[0]; + if (!Mailboxes.TryGetValue(target, out var targetBox)) + { + await Send(tag + " NO [TRYCREATE] Mailbox does not exist"); + break; + } + + foreach (var m in selected.Where(m => m.Uid == uid).ToList()) + { + targetBox.Add(new FakeImapMessage(_nextUid++, m.Content)); + if (verb == "UID MOVE") + { + selected.Remove(m); + } + } + + await Send(tag + " OK done"); + break; + case "CREATE" when authenticated: + Mailboxes.TryAdd(Arguments(rest[7..], literals)[0], []); + await Send(tag + " OK CREATE completed"); + break; + case "EXPUNGE" or "UID EXPUNGE" when selected is not null: + selected.RemoveAll(m => m.Flags.Contains(@"\Deleted")); + await Send(tag + " OK EXPUNGE completed"); + break; + case "LOGOUT": + await Send("* BYE Logging out"); + await Send(tag + " OK LOGOUT completed"); + return; + default: + await Send(tag + " BAD Unknown or not allowed: " + verb); + break; + } + } + } + + // The arguments: quoted strings, atoms, and {n} literals taken in order. + private static List Arguments(string text, Queue literals) + { + var values = new List(); + var i = 0; + while (i < text.Length) + { + if (text[i] == ' ') + { + i++; + } + else if (text[i] == '"') + { + var value = new StringBuilder(); + i++; + while (i < text.Length && text[i] != '"') + { + if (text[i] == '\\') + { + i++; + } + + value.Append(text[i]); + i++; + } + + values.Add(value.ToString()); + i++; + } + else if (text[i] == '{') + { + values.Add(Encoding.UTF8.GetString(literals.Dequeue())); + i = text.IndexOf('}', i) + 1; + } + else + { + var end = text.IndexOf(' ', i); + values.Add(end < 0 ? text[i..] : text[i..end]); + i = end < 0 ? text.Length : end; + } + } + + return values; + } + + [GeneratedRegex("FROM \"(?[^\"]*)\"", RegexOptions.IgnoreCase)] + private static partial Regex FromPattern(); +} + +/// An SMTP server on the loopback interface that keeps every message it receives (no TLS). +internal sealed class FakeSmtpServer : IAsyncDisposable +{ + private readonly TcpListener _listener = new(IPAddress.Loopback, 0); + private readonly CancellationTokenSource _stop = new(); + private readonly Task _loop; + + public FakeSmtpServer() + { + _listener.Start(); + _loop = Task.Run(AcceptAsync); + } + + public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port; + + /// The messages: sender, recipients, raw content. + public ConcurrentQueue<(string From, IReadOnlyList To, byte[] Content)> Messages { get; } = new(); + + /// When set, RCPT TO is refused with this reply. + public string? RejectRecipient { get; set; } + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync(); + _listener.Stop(); + try + { + await _loop; + } + catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException) + { + } + + _stop.Dispose(); + } + + private async Task AcceptAsync() + { + while (!_stop.IsCancellationRequested) + { + TcpClient client; + try + { + client = await _listener.AcceptTcpClientAsync(_stop.Token); + } + catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException) + { + return; + } + + using (client) + { + try + { + await ServeAsync(client.GetStream()); + } + catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException) + { + } + } + } + } + + private async Task ServeAsync(NetworkStream stream) + { + var reader = new LineReader(stream); + async Task Send(string text) => await stream.WriteAsync(Encoding.ASCII.GetBytes(text + "\r\n"), _stop.Token); + await Send("220 fake.smtp ESMTP"); + string from = string.Empty; + var to = new List(); + while (true) + { + var line = await reader.LineAsync(_stop.Token); + if (line is null) + { + return; + } + + var upper = line.ToUpperInvariant(); + if (upper.StartsWith("EHLO", StringComparison.Ordinal)) + { + await Send("250-fake.smtp"); + await Send("250 AUTH PLAIN LOGIN"); + } + else if (upper.StartsWith("AUTH PLAIN", StringComparison.Ordinal)) + { + await Send("235 Authenticated"); + } + else if (upper.StartsWith("MAIL FROM:", StringComparison.Ordinal)) + { + from = line[10..].Trim('<', '>', ' '); + to.Clear(); + await Send("250 OK"); + } + else if (upper.StartsWith("RCPT TO:", StringComparison.Ordinal)) + { + if (RejectRecipient is not null) + { + await Send(RejectRecipient); + continue; + } + + to.Add(line[8..].Trim('<', '>', ' ')); + await Send("250 OK"); + } + else if (upper == "DATA") + { + await Send("354 End data with ."); + var data = new StringBuilder(); + while (await reader.LineAsync(_stop.Token) is { } dataLine && dataLine != ".") + { + data.Append(dataLine.StartsWith("..", StringComparison.Ordinal) ? dataLine[1..] : dataLine).Append("\r\n"); + } + + Messages.Enqueue((from, [.. to], Encoding.Latin1.GetBytes(data.ToString()))); + await Send("250 OK queued"); + } + else if (upper == "QUIT") + { + await Send("221 Bye"); + return; + } + else + { + await Send("502 Not implemented"); + } + } + } +} + +/// Reads CRLF lines and IMAP literals from a stream. +internal sealed class LineReader(Stream stream) +{ + private readonly byte[] _buffer = new byte[8192]; + private int _start; + private int _end; + + public async Task LineAsync(CancellationToken cancellationToken) + { + using var line = new MemoryStream(); + while (true) + { + if (_start == _end) + { + _start = 0; + _end = await stream.ReadAsync(_buffer, cancellationToken); + if (_end == 0) + { + return null; + } + } + + var index = Array.IndexOf(_buffer, (byte)'\n', _start, _end - _start); + if (index < 0) + { + line.Write(_buffer, _start, _end - _start); + _start = _end; + continue; + } + + line.Write(_buffer, _start, index - _start); + _start = index + 1; + return Encoding.Latin1.GetString(line.ToArray()).TrimEnd('\r'); + } + } + + // A command line with its literals: after each {n} the server says "+" and reads n bytes. + public async Task<(string? Line, Queue Literals)> CommandAsync(Func continuation, CancellationToken cancellationToken) + { + var text = new StringBuilder(); + var literals = new Queue(); + while (true) + { + var line = await LineAsync(cancellationToken); + if (line is null) + { + return (null, literals); + } + + text.Append(line); + var match = Regex.Match(line, @"\{(?[0-9]+)\}$"); + if (!match.Success) + { + return (text.ToString(), literals); + } + + await continuation(); + var length = int.Parse(match.Groups["n"].Value, CultureInfo.InvariantCulture); + var bytes = new byte[length]; + var read = 0; + while (read < length) + { + if (_start == _end) + { + _start = 0; + _end = await stream.ReadAsync(_buffer, cancellationToken); + if (_end == 0) + { + return (null, literals); + } + } + + var take = Math.Min(length - read, _end - _start); + Array.Copy(_buffer, _start, bytes, read, take); + _start += take; + read += take; + } + + literals.Enqueue(bytes); + } + } +} diff --git a/tests/Khaemhat.Infrastructure.Tests/Mail/MimeAndImapTests.cs b/tests/Khaemhat.Infrastructure.Tests/Mail/MimeAndImapTests.cs new file mode 100644 index 0000000..1e17af0 --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Mail/MimeAndImapTests.cs @@ -0,0 +1,151 @@ +using System.Text; +using Khaemhat.Infrastructure.Mail; + +namespace Khaemhat.Infrastructure.Tests.Mail; + +[TestClass] +public sealed class MimeParserTests +{ + [TestMethod] + public void Certified_mail_gives_the_files_of_the_enclosed_message() + { + var receipt = Encoding.UTF8.GetBytes(""); + var message = MimeParser.Parse(PecSamples.Envelope("sdi07@pec.fatturapa.it", "Consegna", ("IT01234567897_00001_RC_001.xml", receipt))); + + Assert.AreEqual("multipart/signed", message.MediaType); + Assert.AreEqual("POSTA CERTIFICATA: Consegna", message.Header("Subject")); + var envelope = message.Parts[0]; + var original = envelope.Parts.Single(p => p.MediaType == "message/rfc822"); + Assert.AreEqual("postacert.eml", original.FileName); + Assert.IsNotNull(original.Enclosed); + Assert.AreEqual("sdi07@pec.fatturapa.it", original.Enclosed.Header("from")); + var file = original.Enclosed.Attachments().Single(); + Assert.AreEqual("IT01234567897_00001_RC_001.xml", file.FileName); + CollectionAssert.AreEqual(receipt, file.Body); + + var all = message.Attachments().Select(a => a.FileName).ToList(); + CollectionAssert.AreEqual(new[] { "daticert.xml", "IT01234567897_00001_RC_001.xml", "smime.p7s" }, all); + StringAssert.Contains(envelope.Parts[0].Text(), "il messaggio originale è allegato"); + } + + [TestMethod] + public void Encoded_words_are_decoded_and_joined() + { + Assert.AreEqual("Fattura n° 12", MimeParser.DecodeHeader("=?utf-8?Q?Fattura_n=C2=B0?= 12")); + Assert.AreEqual("perché sì", MimeParser.DecodeHeader("=?iso-8859-1?Q?perch=E9?= =?iso-8859-1?Q?_s=EC?=")); + Assert.AreEqual("città", MimeParser.DecodeHeader("=?UTF-8?B?Y2l0dMOg?=")); + Assert.AreEqual("plain =? text", MimeParser.DecodeHeader("plain =? text")); + } + + [TestMethod] + public void File_names_follow_rfc_2231() + { + var message = Encoding.ASCII.GetBytes( + "Content-Type: multipart/mixed; boundary=b\r\n\r\n" + + "--b\r\nContent-Type: application/xml\r\nContent-Disposition: attachment; filename*=utf-8''fattura%20citt%C3%A0.xml\r\n\r\n\r\n" + + "--b\r\nContent-Type: application/xml\r\nContent-Disposition: attachment;\r\n filename*0=\"IT0123_\"; filename*1=\"00001.xml\"\r\n\r\n\r\n" + + "--b\r\nContent-Type: application/xml; name=\"=?utf-8?Q?n=C2=B0.xml?=\"\r\n\r\n\r\n" + + "--b--\r\n"); + + var names = MimeParser.Parse(message).Attachments().Select(a => a.FileName).ToList(); + + CollectionAssert.AreEqual(new[] { "fattura città.xml", "IT0123_00001.xml", "n°.xml" }, names); + } + + [TestMethod] + public void Quoted_printable_and_broken_input_do_not_throw() + { + CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("a=b c"), MimeParser.QuotedPrintable(Encoding.ASCII.GetBytes("a=3Db =\r\nc"))); + CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("ab"), MimeParser.Base64(Encoding.ASCII.GetBytes("YW\r\nI="))); + + var unclosed = MimeParser.Parse(Encoding.ASCII.GetBytes("Content-Type: multipart/mixed; boundary=x\r\n\r\n--x\r\nContent-Type: text/plain\r\n\r\nhello")); + Assert.AreEqual("hello", unclosed.Parts.Single().Text()); + + var noHeaders = MimeParser.Parse(Encoding.ASCII.GetBytes("just text")); + Assert.AreEqual("text/plain", noHeaders.MediaType); + } +} + +[TestClass] +public sealed class ImapClientTests +{ + private static readonly byte[] First = PecSamples.Envelope("sdi01@pec.fatturapa.it", "Uno", ("IT01234567897_00001_RC_001.xml", [1])); + private static readonly byte[] Second = PecSamples.Acceptance("Due"); + + [TestMethod] + public async Task Search_fetch_flag_and_move() + { + await using var server = new FakeImapServer("fatture@pec.example.it", "segreto", First, Second); + var token = TestContext.CancellationToken; + await using var imap = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "fatture@pec.example.it", "segreto"), token); + await imap.LoginAsync("fatture@pec.example.it", "segreto", token); + Assert.IsTrue(imap.Capabilities.Contains("MOVE")); + + Assert.AreEqual(2, await imap.SelectAsync("INBOX", token)); + var uids = await imap.SearchAsync("UNSEEN FROM " + ImapClient.Quote("fatturapa.it"), token); + Assert.AreEqual(1, uids.Count); + + var message = await imap.FetchAsync(uids[0], token); + Assert.IsNotNull(message); + CollectionAssert.AreEqual(First, message.Content); + Assert.IsFalse(server.Mailboxes["INBOX"][0].Flags.Contains(@"\Seen"), "BODY.PEEK must not mark the message."); + + await imap.AddFlagsAsync(uids[0], @"\Seen", token); + Assert.IsTrue(server.Mailboxes["INBOX"][0].Flags.Contains(@"\Seen")); + Assert.AreEqual(0, (await imap.SearchAsync("UNSEEN FROM \"fatturapa.it\"", token)).Count); + + await imap.MoveAsync(uids[0], "Khaemhat/SDI", token); + Assert.AreEqual(1, server.Mailboxes["Khaemhat/SDI"].Count); + Assert.AreEqual(1, server.Mailboxes["INBOX"].Count); + Assert.IsNull(await imap.FetchAsync(uids[0], token)); + await imap.LogoutAsync(token); + } + + [TestMethod] + public async Task Without_move_the_message_is_copied_and_expunged() + { + await using var server = new FakeImapServer("u", "p", First) { SupportsMove = false }; + server.Mailboxes["Archivio"] = []; + var token = TestContext.CancellationToken; + await using var imap = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "u", "p"), token); + await imap.LoginAsync("u", "p", token); + await imap.SelectAsync("INBOX", token); + + await imap.MoveAsync((await imap.SearchAsync("ALL", token))[0], "Archivio", token); + + Assert.AreEqual(0, server.Mailboxes["INBOX"].Count); + Assert.AreEqual(1, server.Mailboxes["Archivio"].Count); + Assert.IsTrue(server.Commands.Any(c => c.Contains("UID COPY", StringComparison.Ordinal))); + Assert.IsTrue(server.Commands.Any(c => c.EndsWith("EXPUNGE", StringComparison.Ordinal))); + } + + [TestMethod] + public async Task Password_with_accents_goes_as_a_literal_and_wrong_password_fails() + { + await using var server = new FakeImapServer("u", "pàssword"); + var token = TestContext.CancellationToken; + await using (var imap = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "u", "pàssword"), token)) + { + await imap.LoginAsync("u", "pàssword", token); + } + + Assert.IsTrue(server.Commands.Any(c => c.StartsWith("K0002 LOGIN \"u\" {", StringComparison.Ordinal))); + + await using var wrong = await ImapClient.ConnectAsync(new ImapSettings("127.0.0.1", server.Port, false, "u", "x"), token); + var error = await Assert.ThrowsExactlyAsync(() => wrong.LoginAsync("u", "x", token)); + StringAssert.Contains(error.Message, "LOGIN ***"); + Assert.IsFalse(error.Message.Contains("\"x\"", StringComparison.Ordinal), "The password must not appear in the error."); + } + + [TestMethod] + public async Task Unreachable_server_gives_a_mail_exception() + { + var settings = new ImapSettings("127.0.0.1", 1, false, "u", "p"); + await Assert.ThrowsExactlyAsync(() => ImapClient.ConnectAsync(settings, TestContext.CancellationToken)); + Assert.AreEqual("127.0.0.1:1", settings.ToString()); + Assert.AreEqual("1-Nov-2026", ImapClient.SearchDate(new DateOnly(2026, 11, 1))); + Assert.ThrowsExactly(() => ImapClient.Quote("città")); + } + + public TestContext TestContext { get; set; } = null!; +} diff --git a/tests/Khaemhat.Infrastructure.Tests/Mail/PecSamples.cs b/tests/Khaemhat.Infrastructure.Tests/Mail/PecSamples.cs new file mode 100644 index 0000000..28b7961 --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/Mail/PecSamples.cs @@ -0,0 +1,86 @@ +using System.Text; + +namespace Khaemhat.Infrastructure.Tests.Mail; + +/// +/// Certified mail messages built in the test, shaped like the ones a PEC provider delivers: a multipart/mixed +/// envelope with the text of the provider, daticert.xml, the original message as postacert.eml +/// (message/rfc822) and the signature smime.p7s. Nothing is downloaded. +/// +internal static class PecSamples +{ + /// A certified message whose original was sent by with the given files. + public static byte[] Envelope(string sender, string subject, params (string Name, byte[] Content)[] files) + { + var inner = new StringBuilder() + .Append("From: ").Append(sender).Append("\r\n") + .Append("To: fatture@pec.example.it\r\n") + .Append("Subject: ").Append(subject).Append("\r\n") + .Append("MIME-Version: 1.0\r\n") + .Append("Content-Type: multipart/mixed; boundary=\"inner-b\"\r\n\r\n") + .Append("--inner-b\r\n") + .Append("Content-Type: text/plain; charset=utf-8\r\n\r\n") + .Append("Messaggio del Sistema di Interscambio\r\n"); + foreach (var (name, content) in files) + { + inner.Append("--inner-b\r\n") + .Append("Content-Type: application/octet-stream; name=\"").Append(name).Append("\"\r\n") + .Append("Content-Transfer-Encoding: base64\r\n") + .Append("Content-Disposition: attachment; filename=\"").Append(name).Append("\"\r\n\r\n") + .Append(Wrap(Convert.ToBase64String(content))).Append("\r\n"); + } + + inner.Append("--inner-b--\r\n"); + + var outer = new StringBuilder() + .Append("From: \"Per conto di: ").Append(sender).Append("\" \r\n") + .Append("To: fatture@pec.example.it\r\n") + .Append("Subject: =?utf-8?B?").Append(Convert.ToBase64String(Encoding.UTF8.GetBytes("POSTA CERTIFICATA: " + subject))).Append("?=\r\n") + .Append("X-Trasporto: posta-certificata\r\n") + .Append("MIME-Version: 1.0\r\n") + .Append("Content-Type: multipart/signed; protocol=\"application/pkcs7-signature\"; micalg=sha-256;\r\n boundary=\"signed-b\"\r\n\r\n") + .Append("--signed-b\r\n") + .Append("Content-Type: multipart/mixed; boundary=\"outer-b\"\r\n\r\n") + .Append("--outer-b\r\n") + .Append("Content-Type: text/plain; charset=iso-8859-1\r\n") + .Append("Content-Transfer-Encoding: quoted-printable\r\n\r\n") + .Append("Messaggio di posta certificata: il messaggio originale =E8 allegato.\r\n") + .Append("--outer-b\r\n") + .Append("Content-Type: application/xml; name=daticert.xml\r\n") + .Append("Content-Disposition: inline; filename=daticert.xml\r\n\r\n") + .Append("\r\n") + .Append("--outer-b\r\n") + .Append("Content-Type: message/rfc822; name=postacert.eml\r\n") + .Append("Content-Disposition: inline; filename=postacert.eml\r\n\r\n") + .Append(inner) + .Append("--outer-b--\r\n") + .Append("--signed-b\r\n") + .Append("Content-Type: application/pkcs7-signature; name=smime.p7s\r\n") + .Append("Content-Transfer-Encoding: base64\r\n") + .Append("Content-Disposition: attachment; filename=smime.p7s\r\n\r\n") + .Append(Convert.ToBase64String([1, 2, 3, 4])).Append("\r\n") + .Append("--signed-b--\r\n"); + return Encoding.UTF8.GetBytes(outer.ToString()); + } + + /// The acceptance receipt of the provider: no original message, no files of the SDI. + public static byte[] Acceptance(string subject) => Encoding.UTF8.GetBytes( + "From: posta-certificata@pec.provider.example\r\n" + + "Subject: ACCETTAZIONE: " + subject + "\r\n" + + "X-Ricevuta: accettazione\r\n" + + "Content-Type: multipart/mixed; boundary=\"a\"\r\n\r\n" + + "--a\r\nContent-Type: text/plain\r\n\r\nIl messaggio e' stato accettato dal sistema.\r\n" + + "--a\r\nContent-Type: application/xml; name=daticert.xml\r\nContent-Disposition: attachment; filename=daticert.xml\r\n\r\n\r\n" + + "--a--\r\n"); + + private static string Wrap(string base64) + { + var lines = new StringBuilder(); + for (var i = 0; i < base64.Length; i += 76) + { + lines.Append(base64, i, Math.Min(76, base64.Length - i)).Append("\r\n"); + } + + return lines.ToString().TrimEnd(); + } +}