using System.Globalization; using System.Xml; using System.Xml.Schema; using Khaemhat.Core.Validation; using Khaemhat.Fiscal.Abstractions; namespace Khaemhat.Fiscal.Italy; /// /// Checks a FatturaPA before it is sent (SPEC §11.9, issue #74, ADR 0039): the content with the controls of the /// exchange system that can be made offline, and the XML with the schema of the format. /// /// /// The checks that the SDI documents with a code keep that code (00400, 00423...), so the message is /// the one the user would read in a rejection; the others have a code of Khaemhat (einvoice.*). Checks that need /// the registers of the Agenzia (a VAT number that exists, a recipient code that is accredited, the office code of an /// administration in the IPA index) cannot be made offline: only the form of those values is checked. /// Tolerances follow the specifications: one cent on PrezzoTotale and Imposta, one euro on /// ImponibileImporto. /// public sealed class FatturaPaValidator : IEInvoiceValidator { private static readonly Lazy Schemas = new(LoadSchemas); private static readonly HashSet GenericNatures = new(StringComparer.Ordinal) { "N2", "N3", "N6" }; // Types where supplier and customer must be different subjects (an integration or self-invoice is issued by the // customer for a supplier) and types where they must be the same subject (00471, 00472). private static readonly HashSet DifferentParties = new(StringComparer.Ordinal) { "TD01", "TD02", "TD03", "TD06", "TD16", "TD17", "TD18", "TD19", "TD20", "TD24", "TD25", "TD28", "TD29", }; private static readonly HashSet SameParty = new(StringComparer.Ordinal) { "TD21", "TD27" }; private static readonly HashSet ForeignSupplier = new(StringComparer.Ordinal) { "TD17", "TD18", "TD19", "TD28" }; /// public string RulesVersion => FatturaPaCodeLists.SpecVersion; /// public IReadOnlyList Validate(EInvoiceFile file) { ArgumentNullException.ThrowIfNull(file); var problems = new List(); CheckTransmission(file, problems); CheckSupplier(file.Supplier, problems); CheckCustomer(file, problems); for (var i = 0; i < file.Invoices.Count; i++) { CheckBody(file, file.Invoices[i], file.Invoices.Count > 1 ? $"FatturaElettronicaBody[{i + 1}]/" : string.Empty, problems); } return [.. problems.OrderBy(p => p.Severity)]; } /// public IReadOnlyList ValidateXml(byte[] xml) { ArgumentNullException.ThrowIfNull(xml); var problems = new List(); var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, ValidationType = ValidationType.Schema, Schemas = Schemas.Value, }; settings.ValidationEventHandler += (_, e) => { if (problems.Count < 50) { problems.Add(new EInvoiceProblem("einvoice.xml.schema", e.Exception?.LineNumber > 0 ? "riga " + e.Exception.LineNumber.ToString(CultureInfo.InvariantCulture) : string.Empty, e.Message, e.Severity == XmlSeverityType.Error ? EInvoiceProblemSeverity.Error : EInvoiceProblemSeverity.Warning)); } }; try { using var reader = XmlReader.Create(new MemoryStream(xml), settings); while (reader.Read()) { } } catch (XmlException ex) { problems.Add(new EInvoiceProblem("einvoice.xml.malformed", "riga " + ex.LineNumber.ToString(CultureInfo.InvariantCulture), ex.Message)); } return problems; } // --- Header ------------------------------------------------------------------------------------------------------ private static void CheckTransmission(EInvoiceFile file, List problems) { var format = file.TransmissionFormat; if (format is not ("FPR12" or "FPA12")) { problems.Add(new("einvoice.format", "FormatoTrasmissione", $"Formato di trasmissione {format} non gestito: Khaemhat emette FPR12 e FPA12.")); return; } if (string.IsNullOrWhiteSpace(file.TransmitterId)) { problems.Add(new("einvoice.transmitter", "IdTrasmittente/IdCodice", "Manca l'identificativo fiscale del trasmittente: compila partita IVA o codice fiscale nel profilo dell'azienda.")); } var code = file.RecipientCode ?? string.Empty; if (format == "FPA12" && code.Length != 6) { problems.Add(new("00427", "CodiceDestinatario", "Per una pubblica amministrazione (FPA12) il codice destinatario è il codice univoco dell'ufficio di 6 caratteri (indice IPA).")); } else if (format == "FPR12" && code.Length != 7) { problems.Add(new("00427", "CodiceDestinatario", "Per un privato (FPR12) il codice destinatario ha 7 caratteri: 0000000 senza codice, XXXXXXX per l'estero.")); } else if (!code.All(char.IsAsciiLetterUpper) && !code.All(c => char.IsAsciiLetterUpper(c) || char.IsAsciiDigit(c))) { problems.Add(new("00311", "CodiceDestinatario", "Il codice destinatario contiene caratteri non ammessi (solo lettere maiuscole e cifre).")); } if (!string.IsNullOrWhiteSpace(file.RecipientPec) && code != FatturaPaCodeLists.RecipientCodeNone) { problems.Add(new("00426", "PECDestinatario", "La PEC del destinatario si indica solo con il codice destinatario 0000000.")); } if (!string.IsNullOrWhiteSpace(file.RecipientPec) && !EmailValidator.IsValid(file.RecipientPec)) { problems.Add(new("einvoice.recipient.pec", "PECDestinatario", "La PEC del destinatario non è un indirizzo valido.")); } } private static void CheckSupplier(EInvoiceParty supplier, List problems) { const string Path = "CedentePrestatore/"; if (string.IsNullOrWhiteSpace(supplier.VatNumber)) { problems.Add(new("einvoice.supplier.vat", Path + "IdFiscaleIVA", "Manca la partita IVA del cedente/prestatore.")); } else if ((supplier.CountryCode ?? "IT") == "IT" && !ItalianVatNumberValidator.IsValid(supplier.VatNumber)) { problems.Add(new("einvoice.supplier.vat", Path + "IdFiscaleIVA/IdCodice", $"La partita IVA {supplier.VatNumber} del cedente/prestatore non è valida.")); } if (!string.IsNullOrWhiteSpace(supplier.TaxCode) && !FiscalCodeValidator.IsValid(supplier.TaxCode)) { problems.Add(new("einvoice.supplier.tax-code", Path + "CodiceFiscale", $"Il codice fiscale {supplier.TaxCode} del cedente/prestatore non è valido.")); } CheckNames(supplier, Path, problems); CheckOffice(supplier, Path, problems); if (supplier.TaxRegime is { } regime && FatturaPaCodeLists.TaxRegimes.Find(regime) is null) { problems.Add(new("einvoice.code-list", Path + "RegimeFiscale", $"Il regime fiscale {regime} non è fra quelli ammessi.")); } if (string.IsNullOrWhiteSpace(supplier.ReaOffice) != string.IsNullOrWhiteSpace(supplier.ReaNumber)) { problems.Add(new("einvoice.supplier.rea", Path + "IscrizioneREA", "Per l'iscrizione al REA servono ufficio e numero.", EInvoiceProblemSeverity.Warning)); } } private static void CheckCustomer(EInvoiceFile file, List problems) { const string Path = "CessionarioCommittente/"; var customer = file.Customer; var italian = (customer.CountryCode ?? customer.Country ?? "IT") == "IT"; if (string.IsNullOrWhiteSpace(customer.VatNumber) && string.IsNullOrWhiteSpace(customer.TaxCode)) { problems.Add(new("00417", Path + "DatiAnagrafici", "Il cessionario/committente non ha né partita IVA né codice fiscale: almeno uno dei due è obbligatorio.")); } if (italian && !string.IsNullOrWhiteSpace(customer.VatNumber) && !ItalianVatNumberValidator.IsValid(customer.VatNumber)) { problems.Add(new("00305", Path + "IdFiscaleIVA/IdCodice", $"La partita IVA {customer.VatNumber} del cessionario/committente non è valida.")); } if (italian && !string.IsNullOrWhiteSpace(customer.TaxCode) && !FiscalCodeValidator.IsValid(customer.TaxCode)) { problems.Add(new("00306", Path + "CodiceFiscale", $"Il codice fiscale {customer.TaxCode} del cessionario/committente non è valido.")); } CheckNames(customer, Path, problems); CheckOffice(customer, Path, problems); if (!italian && file.RecipientCode != FatturaPaCodeLists.RecipientCodeForeign) { problems.Add(new("einvoice.recipient.foreign", "CodiceDestinatario", "Per un cliente estero il codice destinatario è XXXXXXX.", EInvoiceProblemSeverity.Warning)); } } private static void CheckNames(EInvoiceParty party, string path, List problems) { if (string.IsNullOrWhiteSpace(party.Name) && (string.IsNullOrWhiteSpace(party.FirstName) || string.IsNullOrWhiteSpace(party.LastName))) { problems.Add(new("einvoice.party.name", path + "Anagrafica", "Serve la denominazione, oppure nome e cognome.")); } } private static void CheckOffice(EInvoiceParty party, string path, List problems) { var country = party.Country ?? party.CountryCode ?? "IT"; if (string.IsNullOrWhiteSpace(party.Address) || string.IsNullOrWhiteSpace(party.City)) { problems.Add(new("einvoice.party.office", path + "Sede", "Servono indirizzo e comune della sede.")); } if (country == "IT" && (party.PostalCode is not { Length: 5 } cap || !cap.All(char.IsAsciiDigit))) { problems.Add(new("einvoice.party.cap", path + "Sede/CAP", "Il CAP di una sede italiana ha 5 cifre.")); } if (country == "IT" && party.Province is { Length: > 0 } province && (province.Length != 2 || !province.All(char.IsAsciiLetter))) { problems.Add(new("einvoice.party.province", path + "Sede/Provincia", "La provincia si indica con la sigla di due lettere.")); } } // --- Body -------------------------------------------------------------------------------------------------------- private static void CheckBody(EInvoiceFile file, EInvoiceBody body, string prefix, List problems) { var document = prefix + "DatiGeneraliDocumento/"; if (FatturaPaCodeLists.DocumentTypes.Find(body.DocumentType) is null || FatturaPaCodeLists.SimplifiedDocumentTypes.Contains(body.DocumentType)) { problems.Add(new("einvoice.code-list", document + "TipoDocumento", $"Il tipo documento {body.DocumentType} non è ammesso in una fattura ordinaria.")); } if (string.IsNullOrWhiteSpace(body.Number) || body.Number.Length > 20 || !body.Number.Any(char.IsAsciiDigit)) { problems.Add(new("einvoice.number", document + "Numero", "Il numero del documento è obbligatorio, contiene almeno una cifra e non supera 20 caratteri.")); } if (body.Currency.Length != 3) { problems.Add(new("einvoice.currency", document + "Divisa", "La divisa è il codice ISO di 3 lettere.")); } CheckParties(file, body, problems); CheckWithholdings(body, document, problems); CheckDiscounts(body.Discounts, document + "ScontoMaggiorazione", "00437", problems); CheckReferences(file, body, prefix, problems); var lines = prefix + "DatiBeniServizi/DettaglioLinee"; if (body.Lines.Count == 0) { problems.Add(new("einvoice.lines", lines, "La fattura non ha righe.")); } foreach (var line in body.Lines) { CheckLine(line, $"{lines}[{line.Number}]/", problems); } CheckSummary(body, prefix + "DatiBeniServizi/DatiRiepilogo", problems); CheckPayments(body, prefix + "DatiPagamento", problems); } private static void CheckParties(EInvoiceFile file, EInvoiceBody body, List problems) { var same = SameSubject(file.Supplier, file.Customer); if (DifferentParties.Contains(body.DocumentType) && same) { problems.Add(new("00471", "CedentePrestatore", $"Con il tipo documento {body.DocumentType} cedente/prestatore e cessionario/committente non possono coincidere.")); } if (SameParty.Contains(body.DocumentType) && !same) { problems.Add(new("00472", "CedentePrestatore", $"Con il tipo documento {body.DocumentType} cedente/prestatore e cessionario/committente devono coincidere.")); } if (ForeignSupplier.Contains(body.DocumentType) && (file.Supplier.CountryCode ?? "IT") == "IT") { problems.Add(new("00473", "CedentePrestatore/IdFiscaleIVA/IdPaese", $"Con il tipo documento {body.DocumentType} il cedente/prestatore non può essere residente in Italia.")); } if (body.DocumentType == "TD28" && file.Supplier.CountryCode != "SM") { problems.Add(new("00473", "CedentePrestatore/IdFiscaleIVA/IdPaese", "Con il tipo documento TD28 il cedente/prestatore è di San Marino (SM).")); } } private static bool SameSubject(EInvoiceParty a, EInvoiceParty b) { static string Key(EInvoiceParty p) => ((p.CountryCode ?? "IT") + ":" + (p.VatNumber ?? p.TaxCode ?? string.Empty)).Replace(" ", string.Empty, StringComparison.Ordinal).ToUpperInvariant(); return !string.IsNullOrWhiteSpace(a.VatNumber ?? a.TaxCode) && Key(a) == Key(b); } private static void CheckWithholdings(EInvoiceBody body, string document, List problems) { if (body.Withholdings.Count == 0 && body.Lines.Any(l => l.Withheld)) { problems.Add(new("00411", document + "DatiRitenuta", "Ci sono righe soggette a ritenuta ma manca il blocco DatiRitenuta.")); } if (body.Withholdings.Count == 0 && body.SocialSecurity.Any(s => s.Withheld)) { problems.Add(new("00415", document + "DatiRitenuta", "Il contributo cassa è soggetto a ritenuta ma manca il blocco DatiRitenuta.")); } foreach (var withholding in body.Withholdings) { if (FatturaPaCodeLists.WithholdingTypes.Find(withholding.Type) is null) { problems.Add(new("einvoice.code-list", document + "DatiRitenuta/TipoRitenuta", $"Il tipo di ritenuta {withholding.Type} non è ammesso.")); } if (withholding.Reason is { } reason && FatturaPaCodeLists.WithholdingReasons.Find(reason) is null) { problems.Add(new("einvoice.code-list", document + "DatiRitenuta/CausalePagamento", $"La causale di pagamento {reason} non è ammessa.")); } } foreach (var fund in body.SocialSecurity) { if (FatturaPaCodeLists.SocialSecurityFunds.Find(fund.Fund) is null) { problems.Add(new("einvoice.code-list", document + "DatiCassaPrevidenziale/TipoCassa", $"La cassa {fund.Fund} non è ammessa.")); } CheckNature(fund.TaxRate, fund.Nature, document + "DatiCassaPrevidenziale/", "00413", "00414", problems); } } private static void CheckDiscounts(IReadOnlyList discounts, string path, string code, List problems) { if (discounts.Any(d => d.Percent is null && d.Amount is null)) { problems.Add(new(code, path, "Uno sconto o una maggiorazione non ha né percentuale né importo.")); } } private static void CheckReferences(EInvoiceFile file, EInvoiceBody body, string prefix, List problems) { foreach (var reference in body.Orders.Concat(body.Contracts).Concat(body.RelatedInvoices)) { if (string.IsNullOrWhiteSpace(reference.Id)) { problems.Add(new("einvoice.reference.id", prefix + "DatiGenerali", "Un riferimento a ordine, contratto o fattura collegata non ha il numero del documento (IdDocumento).")); } if (reference.Cig is { Length: > 0 } cig && (cig.Length != 10 || !cig.All(char.IsAsciiLetterOrDigit))) { problems.Add(new("einvoice.reference.cig", prefix + "DatiGenerali/CodiceCIG", $"Il CIG {cig} non ha la forma di 10 caratteri alfanumerici.", EInvoiceProblemSeverity.Warning)); } if (reference.Cup is { Length: > 0 } cup && (cup.Length != 15 || !cup.All(char.IsAsciiLetterOrDigit))) { problems.Add(new("einvoice.reference.cup", prefix + "DatiGenerali/CodiceCUP", $"Il CUP {cup} non ha la forma di 15 caratteri alfanumerici.", EInvoiceProblemSeverity.Warning)); } } if (body.DocumentType is "TD04" or "TD05" && body.RelatedInvoices.Count == 0) { problems.Add(new("einvoice.reference.related", prefix + "DatiGenerali/DatiFattureCollegate", "Una nota di credito o di debito di solito indica la fattura collegata.", EInvoiceProblemSeverity.Warning)); } if (file.TransmissionFormat == "FPA12" && body.Orders.Concat(body.Contracts).All(r => string.IsNullOrWhiteSpace(r.Cig))) { problems.Add(new("einvoice.reference.pa-cig", prefix + "DatiGenerali", "Fattura verso una pubblica amministrazione senza CIG: indicalo, oppure verifica che il contratto ne sia escluso.", EInvoiceProblemSeverity.Warning)); } } private static void CheckLine(EInvoiceLine line, string path, List problems) { if (string.IsNullOrWhiteSpace(line.Description)) { problems.Add(new("einvoice.line.description", path + "Descrizione", "La riga non ha descrizione.")); } if (line.Quantity is < 0m) { problems.Add(new("einvoice.line.quantity", path + "Quantita", "La quantità non può essere negativa: il segno va sul prezzo.")); } CheckNature(line.TaxRate, line.Nature, path, "00400", "00401", problems); CheckDiscounts(line.Discounts, path + "ScontoMaggiorazione", "00438", problems); // PrezzoTotale = PrezzoUnitario × Quantita (1 without quantity), less discounts and plus surcharges in order. var price = line.UnitPrice; foreach (var discount in line.Discounts) { var change = discount.Amount ?? Math.Round(price * (discount.Percent ?? 0m) / 100m, 8, MidpointRounding.AwayFromZero); price += discount.IsSurcharge ? change : -change; } var expected = price * (line.Quantity ?? 1m); if (Math.Abs(expected - line.TotalPrice) > 0.01m) { problems.Add(new("00423", path + "PrezzoTotale", $"PrezzoTotale {FatturaPaWriter.Amount8(line.TotalPrice)} non è PrezzoUnitario × Quantita al netto degli sconti ({FatturaPaWriter.Amount8(Math.Round(expected, 8))}).")); } } private static void CheckNature(decimal rate, string? nature, string path, string missingCode, string presentCode, List problems) { if (rate == 0m && string.IsNullOrWhiteSpace(nature)) { problems.Add(new(missingCode, path + "Natura", "Con aliquota IVA zero serve la natura dell'operazione (N1-N7).")); } else if (rate != 0m && !string.IsNullOrWhiteSpace(nature)) { problems.Add(new(presentCode, path + "Natura", "La natura si indica solo con aliquota IVA zero.")); } else if (nature is { Length: > 0 } && GenericNatures.Contains(nature)) { problems.Add(new("00445", path + "Natura", $"La natura {nature} non è più ammessa: usa il sotto-codice (per esempio N2.2, N3.1, N6.3).")); } else if (nature is { Length: > 0 } && VatNatures.All.Find(nature) is null) { problems.Add(new("einvoice.code-list", path + "Natura", $"La natura {nature} non è fra quelle ammesse.")); } if (rate is < 0m or > 100m) { problems.Add(new("einvoice.rate", path + "AliquotaIVA", "L'aliquota IVA è una percentuale fra 0 e 100.")); } } private static void CheckSummary(EInvoiceBody body, string path, List problems) { static (decimal, string) Key(decimal rate, string? nature) => (rate, nature ?? string.Empty); var rows = body.TaxSummary.GroupBy(r => Key(r.Rate, r.Nature)).ToDictionary(g => g.Key, g => g.ToList()); var lines = body.Lines.GroupBy(l => Key(l.TaxRate, l.Nature)).ToDictionary(g => g.Key, g => g.Sum(l => l.TotalPrice)); foreach (var fund in body.SocialSecurity) { var key = Key(fund.TaxRate, fund.Nature); lines[key] = (lines.TryGetValue(key, out var sum) ? sum : 0m) + fund.Amount; } foreach (var (key, total) in lines) { if (!rows.TryGetValue(key, out var summary)) { problems.Add(new("00419", path, $"Manca il riepilogo per l'aliquota {FatturaPaWriter.Rate(key.Item1)}{(key.Item2.Length > 0 ? " natura " + key.Item2 : string.Empty)} usata nelle righe.")); continue; } var declared = summary.Sum(r => r.Taxable - (r.Rounding ?? 0m)); var expenses = summary.Sum(r => r.ExpensesAmount ?? 0m); if (Math.Abs(declared - expenses - total) > 1m) { problems.Add(new("00422", path + "/ImponibileImporto", $"ImponibileImporto {FatturaPaWriter.Amount2(declared)} non corrisponde alla somma delle righe con aliquota {FatturaPaWriter.Rate(key.Item1)} ({FatturaPaWriter.Amount2(total)}).")); } } foreach (var row in body.TaxSummary) { CheckNature(row.Rate, row.Nature, path + "/", "00429", "00430", problems); var tax = Math.Round(row.Taxable * row.Rate / 100m, 2, MidpointRounding.AwayFromZero); if (Math.Abs(tax - row.Tax) > 0.01m) { problems.Add(new("00421", path + "/Imposta", $"Imposta {FatturaPaWriter.Amount2(row.Tax)} non è ImponibileImporto × AliquotaIVA ({FatturaPaWriter.Amount2(tax)}).")); } if (row.Exigibility is { } exigibility && exigibility is not ("I" or "D" or "S")) { problems.Add(new("einvoice.code-list", path + "/EsigibilitaIVA", $"L'esigibilità {exigibility} non è ammessa (I, D, S).")); } if (row.Exigibility == "S" && row.Nature is not null) { problems.Add(new("einvoice.split.nature", path + "/EsigibilitaIVA", "La scissione dei pagamenti (S) non si applica alle operazioni senza IVA.")); } if (row.Nature is not null && string.IsNullOrWhiteSpace(row.LegalReference)) { problems.Add(new("einvoice.summary.legal-reference", path + "/RiferimentoNormativo", $"Per la natura {row.Nature} conviene indicare la norma (RiferimentoNormativo).", EInvoiceProblemSeverity.Warning)); } } if (body.StampDuty is null && body.TaxSummary.Where(r => VatNatures.CountsForStampDuty(r.Nature)).Sum(r => r.Taxable) > 77.47m) { problems.Add(new("einvoice.stamp-duty", "DatiGeneraliDocumento/DatiBollo", "Le operazioni senza IVA superano 77,47 euro: di solito è dovuto il bollo virtuale di 2 euro.", EInvoiceProblemSeverity.Warning)); } } private static void CheckPayments(EInvoiceBody body, string path, List problems) { foreach (var payment in body.Payments) { if (payment.Method is { } method && FatturaPaCodeLists.PaymentMethods.Find(method) is null) { problems.Add(new("einvoice.code-list", path + "/DettaglioPagamento/ModalitaPagamento", $"La modalità di pagamento {method} non è ammessa.")); } if (payment.Iban is { Length: > 0 } iban && !IbanValidator.IsValid(iban)) { problems.Add(new("einvoice.payment.iban", path + "/DettaglioPagamento/IBAN", $"L'IBAN {iban} non è valido.")); } } if (body.PaymentConditions is { } conditions && FatturaPaCodeLists.PaymentConditions.Find(conditions) is null) { problems.Add(new("einvoice.code-list", path + "/CondizioniPagamento", $"La condizione di pagamento {conditions} non è ammessa.")); } } private static XmlSchemaSet LoadSchemas() { var assembly = typeof(FatturaPaValidator).Assembly; var name = assembly.GetManifestResourceNames().Single(n => n.EndsWith("FatturaPA_v1.2_khaemhat.xsd", StringComparison.Ordinal)); using var stream = assembly.GetManifestResourceStream(name)!; var set = new XmlSchemaSet { XmlResolver = null }; using var reader = XmlReader.Create(stream, new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }); set.Add(FatturaPaWriter.Namespace, reader); set.Compile(); return set; } }