feat: FatturaPA writer, validator, SDI receipts and transport channels (#74 #75 #76 #77)

The Italian pack can now produce and check the e-invoice and talk to the SDI:
- FatturaPaWriter writes FPR12/FPA12 v1.2 with SDI file naming; FatturaPaValidator
  checks it against an embedded schema and the AdE semantic rules (official codes).
- SdiReceiptReader reads RC, NS, MC, NE, DT, AT, MT and SE notifications.
- The incoming-invoice model becomes the shared EInvoice* model, read and written.
- In-house ImapClient and MimeParser (no external libraries) back the PEC channel;
  SdICoop (SOAP/MTOM with client certificate) and two generic REST intermediaries
  sit behind the same IEInvoiceTransport contract, with fake-server tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-13 11:51:31 +01:00
1 parent 0debd82983
commit 709bb13532
26 files changed
+5916 -243

No files matched your search

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