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