diff --git a/CHANGELOG.md b/CHANGELOG.md index e15ef94..658fe72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,10 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`. RF, ritenute, casse previdenziali), castelletto IVA con arrotondamento sul totale per aliquota, regola del bollo, scadenze IVA mensili e trimestrali con slittamenti di agosto e dei festivi, ritenute, regole di base dei cespiti e codici tributo F24. +- Controlli degli identificativi: IBAN (mod 97 e lunghezza per paese), codici a barre EAN/GTIN, e-mail; partita IVA + italiana, codice fiscale con calcolo, lettura dei dati e omocodia, codice destinatario SDI per azienda, PA, privato + ed estero; `ViesClient` per la verifica delle partite IVA comunitarie (esito *valida*, *non valida* o *servizio + non disponibile*). ## [0.3.0] - 2026-11-11 diff --git a/docs/adr/0025-pacchetto-fiscale-a-funzioni.md b/docs/adr/0025-pacchetto-fiscale-a-funzioni.md index b793a4a..4eda851 100644 --- a/docs/adr/0025-pacchetto-fiscale-a-funzioni.md +++ b/docs/adr/0025-pacchetto-fiscale-a-funzioni.md @@ -2,7 +2,7 @@ - **Stato:** accettata - **Data:** 2026-11-11 -- **Modifica:** SPEC §1.10, §3, §21 (Fiscal); ADR 0007; milestone M4, issue #37 +- **Modifica:** SPEC §1.10, §3, §21 (Fiscal e Validatori); ADR 0007; milestone M4, issue #37 e #40 ## Contesto @@ -30,7 +30,14 @@ un paese fuori dall'UE non ha Intrastat, non ovunque esistono le ritenute d'acco `company_profile.country` (senza distinzione di maiuscole). La composizione in `Hosting/KhaemhatServices.cs` è l'unico file fuori dal pacchetto che nomina `Khaemhat.Fiscal.Italy`: lo verifica `FiscalPackIsolationTests`, che controlla anche che le astrazioni non contengano nomi italiani. -6. **Versione delle specifiche.** `FatturaPaCodeLists.SpecVersion` è **1.9.1** (pubblicata il 31 marzo 2026, in +6. **Identificativi italiani nel pacchetto.** SPEC §21 mette `ItalianVatNumberValidator`, `FiscalCodeValidator`, + `FiscalCodeCalculator` e `SdiRecipientCodeValidator` in `Khaemhat.Core`; il vincolo non negoziabile di SPEC §1.10 + ("tutto ciò che è italiano sta in `Fiscal.Italy`") prevale: stanno nel pacchetto italiano dietro la funzione + `ITaxIdentifierRules`, e la banca da IBAN dietro `IBankDirectory`. In `Core` restano i controlli internazionali: + `IbanValidator` (mod 97 e lunghezza per paese), `EanValidator` (EAN-8, UPC-A, EAN-13, GTIN-14), `EmailValidator`. + Il controllo VIES è `ViesClient` in `Infrastructure` (servizio REST della Commissione europea): un servizio che + non risponde dà *non disponibile*, mai *non valida*. +7. **Versione delle specifiche.** `FatturaPaCodeLists.SpecVersion` è **1.9.1** (pubblicata il 31 marzo 2026, in vigore dal 15 maggio 2026; non cambia le code list della 1.9, che aveva introdotto TD29 e ridefinito TD20). Va ricontrollata sul sito dell'Agenzia delle Entrate a ogni rilascio. diff --git a/src/Khaemhat.Core/Validation/Validators.cs b/src/Khaemhat.Core/Validation/Validators.cs new file mode 100644 index 0000000..23bc7b6 --- /dev/null +++ b/src/Khaemhat.Core/Validation/Validators.cs @@ -0,0 +1,149 @@ +using System.Globalization; +using System.Text; + +namespace Khaemhat.Core.Validation; + +/// +/// International Bank Account Numbers (ISO 13616): country, length of the country and the mod-97 check. Spaces and +/// case do not matter. +/// +public static class IbanValidator +{ + // Lengths of the SEPA countries and their neighbours; other countries are checked for 15-34 characters only. + private static readonly Dictionary Lengths = new(StringComparer.Ordinal) + { + ["AD"] = 24, ["AT"] = 20, ["BE"] = 16, ["BG"] = 22, ["CH"] = 21, ["CY"] = 28, ["CZ"] = 24, ["DE"] = 22, + ["DK"] = 18, ["EE"] = 20, ["ES"] = 24, ["FI"] = 18, ["FR"] = 27, ["GB"] = 22, ["GI"] = 23, ["GR"] = 27, + ["HR"] = 21, ["HU"] = 28, ["IE"] = 22, ["IS"] = 26, ["IT"] = 27, ["LI"] = 21, ["LT"] = 20, ["LU"] = 20, + ["LV"] = 21, ["MC"] = 27, ["MT"] = 31, ["NL"] = 18, ["NO"] = 15, ["PL"] = 28, ["PT"] = 25, ["RO"] = 24, + ["SE"] = 24, ["SI"] = 19, ["SK"] = 24, ["SM"] = 27, ["VA"] = 22, + }; + + /// The IBAN without spaces, in capitals. + /// The IBAN as typed. + /// The compact form, or an empty string. + public static string Normalize(string? iban) => + iban is null ? string.Empty : string.Concat(iban.Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant(); + + /// The IBAN in groups of four characters, as printed. + /// The IBAN. + /// The printed form. + public static string Format(string? iban) + { + var compact = Normalize(iban); + var builder = new StringBuilder(compact.Length + (compact.Length / 4)); + for (var i = 0; i < compact.Length; i++) + { + if (i > 0 && i % 4 == 0) + { + builder.Append(' '); + } + + builder.Append(compact[i]); + } + + return builder.ToString(); + } + + /// Whether an IBAN is well formed and its check digits are right. + /// The IBAN, with or without spaces. + /// for a valid IBAN. + public static bool IsValid(string? iban) + { + var value = Normalize(iban); + if (value.Length is < 15 or > 34 || !char.IsAsciiLetterUpper(value[0]) || !char.IsAsciiLetterUpper(value[1]) + || !char.IsAsciiDigit(value[2]) || !char.IsAsciiDigit(value[3]) || !value.All(char.IsAsciiLetterOrDigit)) + { + return false; + } + + if (Lengths.TryGetValue(value[..2], out var length) && value.Length != length) + { + return false; + } + + // Move the first four characters to the end, turn letters into 10-35 and compute mod 97 digit by digit. + var remainder = 0; + foreach (var c in value[4..] + value[..4]) + { + var digits = char.IsAsciiDigit(c) ? (c - '0').ToString(CultureInfo.InvariantCulture) : (c - 'A' + 10).ToString(CultureInfo.InvariantCulture); + foreach (var d in digits) + { + remainder = ((remainder * 10) + (d - '0')) % 97; + } + } + + return remainder == 1; + } +} + +/// GTIN barcodes: EAN-8, UPC-A (12), EAN-13 and GTIN-14, with the mod-10 check digit. +public static class EanValidator +{ + /// Whether a barcode has a valid length and check digit. + /// The digits of the barcode. + /// for a valid code. + public static bool IsValid(string? code) + { + var value = code?.Trim() ?? string.Empty; + if (value.Length is not (8 or 12 or 13 or 14) || !value.All(char.IsAsciiDigit)) + { + return false; + } + + return CheckDigit(value[..^1]) == value[^1] - '0'; + } + + /// The check digit for the digits of a code without it. + /// The digits before the check digit. + /// The check digit, 0-9. + public static int CheckDigit(string digits) + { + ArgumentNullException.ThrowIfNull(digits); + var sum = 0; + + // Weights 3 and 1 alternate starting from the rightmost digit. + for (var i = 0; i < digits.Length; i++) + { + var digit = digits[digits.Length - 1 - i] - '0'; + sum += i % 2 == 0 ? digit * 3 : digit; + } + + return (10 - (sum % 10)) % 10; + } +} + +/// +/// E-mail addresses as people type them for invoices and reminders: one @, a local part of up to 64 characters +/// and a domain with at least one dot. Quoted local parts and IP literals are refused on purpose. +/// +public static class EmailValidator +{ + private const string LocalSpecials = ".!#$%&'*+/=?^_`{|}~-"; + + /// Whether an address is acceptable. + /// The address. + /// for a valid address. + public static bool IsValid(string? address) + { + var value = address?.Trim() ?? string.Empty; + var at = value.IndexOf('@', StringComparison.Ordinal); + if (value.Length > 254 || at <= 0 || at != value.LastIndexOf('@')) + { + return false; + } + + var local = value[..at]; + var domain = value[(at + 1)..]; + if (local.Length > 64 || local[0] == '.' || local[^1] == '.' || local.Contains("..", StringComparison.Ordinal) + || !local.All(c => char.IsAsciiLetterOrDigit(c) || LocalSpecials.Contains(c, StringComparison.Ordinal))) + { + return false; + } + + var labels = domain.Split('.'); + return labels.Length >= 2 + && labels.All(l => l.Length is > 0 and <= 63 && l[0] != '-' && l[^1] != '-' && l.All(c => char.IsLetterOrDigit(c) || c == '-')) + && labels[^1].Length >= 2 && !labels[^1].All(char.IsAsciiDigit); + } +} diff --git a/src/Khaemhat.Fiscal.Abstractions/Identifiers.cs b/src/Khaemhat.Fiscal.Abstractions/Identifiers.cs new file mode 100644 index 0000000..148a39e --- /dev/null +++ b/src/Khaemhat.Fiscal.Abstractions/Identifiers.cs @@ -0,0 +1,98 @@ +namespace Khaemhat.Fiscal.Abstractions; + +/// The sex written in a personal tax code. +public enum PersonSex +{ + /// Male. + Male = 0, + + /// Female. + Female = 1, +} + +/// What a personal tax code is computed from. +/// The surname. +/// The given name (all given names, as in the registry). +/// The date of birth. +/// The sex. +/// The code of the place of birth (Italy: cadastral code of the municipality, or Z... for a foreign country). +public sealed record PersonalTaxCodeData(string Surname, string GivenName, DateOnly BirthDate, PersonSex Sex, string BirthPlaceCode); + +/// What can be read back from a personal tax code. +/// The date of birth (century guessed from the reference date). +/// The sex. +/// The code of the place of birth. +public sealed record PersonalTaxCodeInfo(DateOnly BirthDate, PersonSex Sex, string BirthPlaceCode); + +/// Who receives an e-invoice, for the recipient code rules. +public enum RecipientKind +{ + /// A business with its own channel, or without (then the default code). + Business = 0, + + /// A public administration (Italy: office code of 6 characters). + PublicAdministration = 1, + + /// A private consumer. + Consumer = 2, + + /// A customer abroad. + Foreign = 3, +} + +/// The country's tax identifiers: VAT number, personal tax code and e-invoice recipient code. +public interface ITaxIdentifierRules +{ + /// The VAT number without spaces and without the country prefix. + /// The number as typed. + /// The compact number. + string NormalizeVatNumber(string? vatNumber); + + /// Whether a domestic VAT number is valid (format and check digit). + /// The number, with or without prefix. + /// when valid. + bool IsValidVatNumber(string? vatNumber); + + /// Whether a personal or company tax code is valid. + /// The code. + /// when valid. + bool IsValidTaxCode(string? taxCode); + + /// Computes the personal tax code of a person. + /// The personal data. + /// The code. + string ComputePersonalTaxCode(PersonalTaxCodeData data); + + /// Reads birth date, sex and place back from a personal tax code. + /// The code. + /// The reference date that decides the century. + /// The data, or if the code is not a valid personal code. + PersonalTaxCodeInfo? DecodePersonalTaxCode(string? taxCode, DateOnly today); + + /// The rules an e-invoice recipient code breaks for a kind of customer; empty when valid. + /// The code. + /// The kind of customer. + /// Errors and warnings with field RecipientCode. + IReadOnlyList CheckRecipientCode(string? recipientCode, RecipientKind kind); + + /// The recipient code to propose for a kind of customer without one. + /// The kind of customer. + /// The default code, or if the customer must give one. + string? DefaultRecipientCode(RecipientKind kind); +} + +/// A bank found from its national code. +/// The national bank code (Italy: ABI). +/// The name of the bank. +/// The BIC, when known. +/// The branch code (Italy: CAB), when the IBAN has one. +public sealed record BankInfo(string BankCode, string Name, string? Bic, string? BranchCode); + +/// The country's directory of banks, to fill bank name and BIC from an IBAN. +public interface IBankDirectory +{ + /// The bank of a domestic IBAN. + /// The IBAN. + /// The bank, or if the IBAN is foreign, invalid or the bank unknown. + BankInfo? FindByIban(string? iban); +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalianIdentifiers.cs b/src/Khaemhat.Fiscal.Italy/ItalianIdentifiers.cs new file mode 100644 index 0000000..3017b53 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/ItalianIdentifiers.cs @@ -0,0 +1,349 @@ +using System.Globalization; +using System.Text; +using Khaemhat.Core.Validation; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy; + +/// +/// Italian VAT numbers (partita IVA): 11 digits, the last a Luhn-like check digit; the first seven (the taxpayer +/// number) cannot be all zeros. +/// +public static class ItalianVatNumberValidator +{ + /// The number without spaces and without the IT prefix. + /// The number as typed. + /// The compact number. + public static string Normalize(string? vatNumber) + { + var compact = string.Concat((vatNumber ?? string.Empty).Where(c => !char.IsWhiteSpace(c) && c != '.' && c != '-')).ToUpperInvariant(); + return compact.StartsWith("IT", StringComparison.Ordinal) ? compact[2..] : compact; + } + + /// Whether a VAT number is valid. + /// The number, with or without prefix. + /// when valid. + public static bool IsValid(string? vatNumber) + { + var value = Normalize(vatNumber); + if (value.Length != 11 || !value.All(char.IsAsciiDigit) || value.StartsWith("0000000", StringComparison.Ordinal)) + { + return false; + } + + return CheckDigit(value[..10]) == value[10] - '0'; + } + + /// The check digit for the first ten digits. + /// Ten digits. + /// The check digit. + public static int CheckDigit(string digits) + { + ArgumentNullException.ThrowIfNull(digits); + var sum = 0; + for (var i = 0; i < digits.Length; i++) + { + var d = digits[i] - '0'; + if (i % 2 == 1) + { + d *= 2; + if (d > 9) + { + d -= 9; + } + } + + sum += d; + } + + return (10 - (sum % 10)) % 10; + } +} + +/// +/// Italian personal tax codes (codice fiscale, DM 23/12/1976): 16 characters for people, with the omocodia +/// substitutions accepted; companies use their 11-digit number. +/// +public static class FiscalCodeValidator +{ + /// Letters that replace digits in omocodic codes: L=0, M=1... V=9. + internal const string OmocodiaLetters = "LMNPQRSTUV"; + + /// Month letters: A=January... T=December. + internal const string MonthLetters = "ABCDEHLMPRST"; + + // Positions (0-based) that hold digits, possibly replaced by omocodia letters. + private static readonly int[] DigitPositions = [6, 7, 9, 10, 12, 13, 14]; + + // Values of characters in odd positions (1st, 3rd... 1-based) for the check character. + private static readonly int[] OddValues = [1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 2, 4, 18, 20, 11, 3, 6, 8, 12, 14, 16, 10, 22, 25, 24, 23]; + + /// The code without spaces, in capitals. + /// The code as typed. + /// The compact code. + public static string Normalize(string? code) => + string.Concat((code ?? string.Empty).Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant(); + + /// Whether a tax code is valid: a 16-character personal code or an 11-digit company code. + /// The code. + /// when valid. + public static bool IsValid(string? code) + { + var value = Normalize(code); + return value.Length == 11 ? ItalianVatNumberValidator.IsValid(value) : IsValidPersonal(value); + } + + /// Whether a 16-character personal code is valid. + /// The code. + /// when valid. + public static bool IsValidPersonal(string? code) + { + var value = Normalize(code); + if (value.Length != 16 || !value.All(char.IsAsciiLetterOrDigit)) + { + return false; + } + + for (var i = 0; i < 16; i++) + { + var isDigitPosition = Array.IndexOf(DigitPositions, i) >= 0; + var c = value[i]; + var ok = isDigitPosition + ? char.IsAsciiDigit(c) || OmocodiaLetters.Contains(c, StringComparison.Ordinal) + : char.IsAsciiLetterUpper(c); + if (!ok) + { + return false; + } + } + + var plain = RemoveOmocodia(value); + var day = int.Parse(plain.AsSpan(9, 2), CultureInfo.InvariantCulture); + return MonthLetters.Contains(value[8], StringComparison.Ordinal) + && day is (>= 1 and <= 31) or (>= 41 and <= 71) + && CheckCharacter(value[..15]) == value[15]; + } + + /// The check character of the first 15 characters. + /// The first 15 characters, in capitals. + /// The check character. + public static char CheckCharacter(string first15) + { + ArgumentNullException.ThrowIfNull(first15); + var sum = 0; + for (var i = 0; i < first15.Length; i++) + { + var c = first15[i]; + var index = char.IsAsciiDigit(c) ? c - '0' : c - 'A'; + sum += i % 2 == 0 ? OddValues[index] : index; + } + + return (char)('A' + (sum % 26)); + } + + /// The code with omocodia letters turned back into digits. + /// A 16-character code. + /// The code with digits in the digit positions. + public static string RemoveOmocodia(string code) + { + ArgumentNullException.ThrowIfNull(code); + var chars = code.ToCharArray(); + foreach (var p in DigitPositions) + { + var i = OmocodiaLetters.IndexOf(chars[p], StringComparison.Ordinal); + if (i >= 0) + { + chars[p] = (char)('0' + i); + } + } + + return new string(chars); + } +} + +/// Computes and decodes Italian personal tax codes. +public static class FiscalCodeCalculator +{ + /// The personal tax code of a person. + /// Surname, name, birth date, sex and cadastral code of the birth place. + /// The 16-character code. + public static string Compute(PersonalTaxCodeData data) + { + ArgumentNullException.ThrowIfNull(data); + var place = FiscalCodeValidator.Normalize(data.BirthPlaceCode); + if (place.Length != 4 || !char.IsAsciiLetterUpper(place[0]) || !place[1..].All(char.IsAsciiDigit)) + { + throw new ArgumentException("The birth place code must be a letter and three digits, such as H501.", nameof(data)); + } + + var day = data.BirthDate.Day + (data.Sex == PersonSex.Female ? 40 : 0); + var first15 = string.Concat( + SurnamePart(data.Surname), + NamePart(data.GivenName), + (data.BirthDate.Year % 100).ToString("00", CultureInfo.InvariantCulture), + FiscalCodeValidator.MonthLetters[data.BirthDate.Month - 1].ToString(), + day.ToString("00", CultureInfo.InvariantCulture), + place); + return first15 + FiscalCodeValidator.CheckCharacter(first15); + } + + /// Reads birth date, sex and place from a personal code. + /// The code. + /// The reference date: a two-digit year after it belongs to the previous century. + /// The data, or for an invalid code. + public static PersonalTaxCodeInfo? Decode(string? code, DateOnly today) + { + if (!FiscalCodeValidator.IsValidPersonal(code)) + { + return null; + } + + var plain = FiscalCodeValidator.RemoveOmocodia(FiscalCodeValidator.Normalize(code)); + var yy = int.Parse(plain.AsSpan(6, 2), CultureInfo.InvariantCulture); + var month = FiscalCodeValidator.MonthLetters.IndexOf(plain[8], StringComparison.Ordinal) + 1; + var day = int.Parse(plain.AsSpan(9, 2), CultureInfo.InvariantCulture); + var sex = day > 40 ? PersonSex.Female : PersonSex.Male; + day = day > 40 ? day - 40 : day; + var year = (today.Year / 100 * 100) + yy; + if (year > today.Year) + { + year -= 100; + } + + return day <= DateTime.DaysInMonth(year, month) + ? new PersonalTaxCodeInfo(new DateOnly(year, month, day), sex, plain[11..15]) + : null; + } + + private static string SurnamePart(string surname) + { + var (consonants, vowels) = Split(surname); + return (consonants + vowels + "XXX")[..3]; + } + + private static string NamePart(string name) + { + var (consonants, vowels) = Split(name); + return consonants.Length >= 4 + ? string.Concat(consonants[0], consonants[2], consonants[3]) + : (consonants + vowels + "XXX")[..3]; + } + + private static (string Consonants, string Vowels) Split(string text) + { + var letters = Letters(text); + return ( + string.Concat(letters.Where(c => !"AEIOU".Contains(c, StringComparison.Ordinal))), + string.Concat(letters.Where(c => "AEIOU".Contains(c, StringComparison.Ordinal)))); + } + + // Letters A-Z only: accents dropped (È -> E), apostrophes and spaces ignored. + private static string Letters(string text) + { + var decomposed = (text ?? string.Empty).Normalize(NormalizationForm.FormD).ToUpperInvariant(); + return string.Concat(decomposed.Where(char.IsAsciiLetterUpper)); + } +} + +/// +/// E-invoice recipient codes (codice destinatario): 7 characters for businesses, 6 for public administrations (IPA +/// office code), 0000000 for consumers and businesses without a channel, XXXXXXX abroad. +/// +public static class SdiRecipientCodeValidator +{ + private const string Field = "RecipientCode"; + + /// The rules a recipient code breaks. + /// The code. + /// The kind of customer. + /// Errors and warnings. + public static IReadOnlyList Check(string? code, RecipientKind kind) + { + var value = FiscalCodeValidator.Normalize(code); + if (value.Length == 0) + { + return kind == RecipientKind.PublicAdministration ? [new(Field, "fiscal.recipient.required")] : []; + } + + if (!value.All(char.IsAsciiLetterOrDigit)) + { + return [new(Field, "fiscal.recipient.characters")]; + } + + return kind switch + { + RecipientKind.PublicAdministration when value.Length != 6 => [new(Field, "fiscal.recipient.pa-length")], + RecipientKind.Foreign when value != FatturaPaCodeLists.RecipientCodeForeign => [new(Field, "fiscal.recipient.foreign")], + RecipientKind.Consumer when value != FatturaPaCodeLists.RecipientCodeNone => [new(Field, "fiscal.recipient.consumer", FiscalProblemSeverity.Warning)], + RecipientKind.Business when value.Length != 7 => [new(Field, "fiscal.recipient.business-length")], + RecipientKind.Business when value == FatturaPaCodeLists.RecipientCodeForeign => [new(Field, "fiscal.recipient.foreign-code-domestic")], + _ => [], + }; + } +} + +/// The Italian tax identifiers as a pack feature. +public sealed class ItalianTaxIdentifierRules : ITaxIdentifierRules +{ + /// + public string NormalizeVatNumber(string? vatNumber) => ItalianVatNumberValidator.Normalize(vatNumber); + + /// + public bool IsValidVatNumber(string? vatNumber) => ItalianVatNumberValidator.IsValid(vatNumber); + + /// + public bool IsValidTaxCode(string? taxCode) => FiscalCodeValidator.IsValid(taxCode); + + /// + public string ComputePersonalTaxCode(PersonalTaxCodeData data) => FiscalCodeCalculator.Compute(data); + + /// + public PersonalTaxCodeInfo? DecodePersonalTaxCode(string? taxCode, DateOnly today) => FiscalCodeCalculator.Decode(taxCode, today); + + /// + public IReadOnlyList CheckRecipientCode(string? recipientCode, RecipientKind kind) => + SdiRecipientCodeValidator.Check(recipientCode, kind); + + /// + public string? DefaultRecipientCode(RecipientKind kind) => kind switch + { + RecipientKind.Foreign => FatturaPaCodeLists.RecipientCodeForeign, + RecipientKind.PublicAdministration => null, + _ => FatturaPaCodeLists.RecipientCodeNone, + }; +} + +/// +/// Italian banks by ABI code, to fill bank name, BIC and CAB from an Italian IBAN +/// (IT + check + CIN + ABI + CAB + account). +/// +public sealed class ItalianBankDirectory : IBankDirectory +{ + private readonly Dictionary _byAbi; + + /// Creates the directory. + /// The banks, one per ABI code. + public ItalianBankDirectory(IEnumerable banks) + { + ArgumentNullException.ThrowIfNull(banks); + _byAbi = banks.GroupBy(b => b.BankCode, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal); + } + + /// How many banks the directory knows. + public int Count => _byAbi.Count; + + /// ABI and CAB of an Italian IBAN. + /// The IBAN. + /// The codes, or for an invalid or foreign IBAN. + public static (string Abi, string Cab)? CodesOf(string? iban) + { + var value = IbanValidator.Normalize(iban); + return IbanValidator.IsValid(value) && value.StartsWith("IT", StringComparison.Ordinal) + ? (value[5..10], value[10..15]) + : null; + } + + /// + public BankInfo? FindByIban(string? iban) => + CodesOf(iban) is { } codes && _byAbi.TryGetValue(codes.Abi, out var bank) ? bank with { BranchCode = codes.Cab } : null; +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs index 64f6dce..1316fce 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -18,6 +18,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase AddFeature(new WithholdingRulesIt()); AddFeature(new FixedAssetRulesIt()); AddFeature(new F24Exporter()); + AddFeature(new ItalianTaxIdentifierRules()); } /// diff --git a/src/Khaemhat.Infrastructure/Http/ViesClient.cs b/src/Khaemhat.Infrastructure/Http/ViesClient.cs new file mode 100644 index 0000000..2ff4066 --- /dev/null +++ b/src/Khaemhat.Infrastructure/Http/ViesClient.cs @@ -0,0 +1,168 @@ +using System.Globalization; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Khaemhat.Infrastructure.Http; + +/// The outcome of a VIES check. +public enum ViesStatus +{ + /// The number is registered for intra-EU operations. + Valid = 0, + + /// The number is not registered (or not active for intra-EU operations). + Invalid = 1, + + /// The service or the member state could not answer; try again later. + Unavailable = 2, + + /// The request was refused as malformed (unknown country, wrong characters). + InvalidInput = 3, +} + +/// The answer of VIES, as saved on the party (SPEC §11.2). +/// The outcome. +/// The member state code asked (Greece is EL). +/// The number asked, without prefix. +/// When VIES answered (or when the call failed), UTC. +/// The registered name, when the member state shares it. +/// The registered address, when shared. +/// The VIES error code for and . +public sealed record ViesResult( + ViesStatus Status, + string CountryCode, + string VatNumber, + DateTimeOffset CheckedAt, + string? Name, + string? Address, + string? Error); + +/// +/// Checks EU VAT numbers with the VIES REST service of the European Commission +/// (GET /taxation_customs/vies/rest-api/ms/{country}/vat/{number}). Network errors and timeouts become +/// : a check that could not be made is never reported as invalid. +/// +public sealed class ViesClient +{ + /// The public service address. + public static readonly Uri DefaultBaseAddress = new("https://ec.europa.eu/taxation_customs/vies/rest-api/"); + + private static readonly HashSet MemberStates = new(StringComparer.Ordinal) + { + "AT", "BE", "BG", "CY", "CZ", "DE", "DK", "EE", "EL", "ES", "FI", "FR", "HR", "HU", "IE", "IT", "LT", "LU", + "LV", "MT", "NL", "PL", "PT", "RO", "SE", "SI", "SK", "XI", + }; + + private readonly HttpClient _http; + private readonly TimeProvider _time; + + /// Creates the client. + /// The HTTP client; its base address defaults to . + /// The clock. + public ViesClient(HttpClient http, TimeProvider time) + { + ArgumentNullException.ThrowIfNull(http); + ArgumentNullException.ThrowIfNull(time); + _http = http; + _http.BaseAddress ??= DefaultBaseAddress; + _time = time; + } + + /// The VIES member state code for an ISO country code (Greece: GR becomes EL). + /// ISO 3166-1 alpha-2 code. + /// The VIES code, or outside the EU. + public static string? MemberStateCode(string? isoCountryCode) + { + var code = isoCountryCode?.Trim().ToUpperInvariant(); + code = code == "GR" ? "EL" : code; + return code is not null && MemberStates.Contains(code) ? code : null; + } + + /// Checks a VAT number. + /// ISO or VIES country code. + /// The number, with or without the country prefix. + /// Cancels the call. + /// The outcome. + public async Task CheckAsync(string countryCode, string vatNumber, CancellationToken cancellationToken) + { + var state = MemberStateCode(countryCode); + var number = string.Concat((vatNumber ?? string.Empty).Where(char.IsAsciiLetterOrDigit)).ToUpperInvariant(); + if (state is not null && number.StartsWith(state, StringComparison.Ordinal)) + { + number = number[state.Length..]; + } + + if (state is null || number.Length == 0) + { + return new ViesResult(ViesStatus.InvalidInput, countryCode ?? string.Empty, number, _time.GetUtcNow(), null, null, "INVALID_INPUT"); + } + + try + { + using var response = await _http.GetAsync(new Uri($"ms/{state}/vat/{Uri.EscapeDataString(number)}", UriKind.Relative), cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + var status = (int)response.StatusCode; + return Failed(state, number, status is >= 400 and < 500 && status != 429 ? ViesStatus.InvalidInput : ViesStatus.Unavailable, + "HTTP_" + status.ToString(CultureInfo.InvariantCulture)); + } + + var answer = await response.Content.ReadFromJsonAsync(cancellationToken).ConfigureAwait(false); + if (answer is null) + { + return Failed(state, number, ViesStatus.Unavailable, "EMPTY_RESPONSE"); + } + + var error = answer.UserError; + if (answer.IsValid) + { + return new ViesResult(ViesStatus.Valid, state, number, answer.RequestDate ?? _time.GetUtcNow(), Clean(answer.Name), Clean(answer.Address), null); + } + + return error is null or "VALID" or "INVALID" + ? new ViesResult(ViesStatus.Invalid, state, number, answer.RequestDate ?? _time.GetUtcNow(), null, null, null) + : Failed(state, number, error == "INVALID_INPUT" ? ViesStatus.InvalidInput : ViesStatus.Unavailable, error); + } + catch (HttpRequestException ex) + { + return Failed(state, number, ViesStatus.Unavailable, ex.HttpRequestError.ToString()); + } + catch (TaskCanceledException) when (!cancellationToken.IsCancellationRequested) + { + return Failed(state, number, ViesStatus.Unavailable, "TIMEOUT"); + } + catch (JsonException) + { + return Failed(state, number, ViesStatus.Unavailable, "BAD_RESPONSE"); + } + } + + private ViesResult Failed(string state, string number, ViesStatus status, string error) => + new(status, state, number, _time.GetUtcNow(), null, null, error); + + // Member states that do not share the data answer with "---". + private static string? Clean(string? value) + { + var text = value?.Trim(); + return string.IsNullOrEmpty(text) || text == "---" ? null : text; + } + + private sealed class ViesAnswer + { + [JsonPropertyName("isValid")] + public bool IsValid { get; set; } + + [JsonPropertyName("requestDate")] + public DateTimeOffset? RequestDate { get; set; } + + [JsonPropertyName("userError")] + public string? UserError { get; set; } + + [JsonPropertyName("name")] + public string? Name { get; set; } + + [JsonPropertyName("address")] + public string? Address { get; set; } + } +} diff --git a/tests/Khaemhat.Core.Tests/Validation/ValidatorsTests.cs b/tests/Khaemhat.Core.Tests/Validation/ValidatorsTests.cs new file mode 100644 index 0000000..b06747a --- /dev/null +++ b/tests/Khaemhat.Core.Tests/Validation/ValidatorsTests.cs @@ -0,0 +1,64 @@ +using Khaemhat.Core.Validation; + +namespace Khaemhat.Core.Tests.Validation; + +[TestClass] +public sealed class IbanValidatorTests +{ + [TestMethod] + [DataRow("IT60 X054 2811 1010 0000 0123 456")] + [DataRow("it60x0542811101000000123456")] + [DataRow("DE89 3704 0044 0532 0130 00")] + [DataRow("GB82 WEST 1234 5698 7654 32")] + [DataRow("FR14 2004 1010 0505 0001 3M02 606")] + public void KnownIbans_AreValid(string iban) => Assert.IsTrue(IbanValidator.IsValid(iban)); + + [TestMethod] + [DataRow("IT61 X054 2811 1010 0000 0123 456")] // wrong check digits + [DataRow("IT60 X054 2811 1010 0000 0123 45")] // Italian IBANs have 27 characters + [DataRow("DE89-3704-0044-0532-0130-00")] + [DataRow("")] + [DataRow(null)] + public void WrongIbans_AreRefused(string? iban) => Assert.IsFalse(IbanValidator.IsValid(iban)); + + [TestMethod] + public void Format_GroupsByFour() => + Assert.AreEqual("IT60 X054 2811 1010 0000 0123 456", IbanValidator.Format("it60x0542811101000000123456")); +} + +[TestClass] +public sealed class EanValidatorTests +{ + [TestMethod] + [DataRow("4006381333931")] + [DataRow("96385074")] + [DataRow("036000291452")] + [DataRow("10012345678902")] + public void KnownBarcodes_AreValid(string code) => Assert.IsTrue(EanValidator.IsValid(code)); + + [TestMethod] + [DataRow("4006381333932")] + [DataRow("400638133393")] + [DataRow("40063813339A1")] + public void WrongBarcodes_AreRefused(string code) => Assert.IsFalse(EanValidator.IsValid(code)); +} + +[TestClass] +public sealed class EmailValidatorTests +{ + [TestMethod] + [DataRow("mario.rossi@example.it")] + [DataRow("fatture+2026@pec.example-azienda.it")] + [DataRow("a@b.co")] + public void UsualAddresses_AreValid(string address) => Assert.IsTrue(EmailValidator.IsValid(address)); + + [TestMethod] + [DataRow("mario.rossi@")] + [DataRow("@example.it")] + [DataRow("mario..rossi@example.it")] + [DataRow("mario@rossi@example.it")] + [DataRow("mario@localhost")] + [DataRow("mario rossi@example.it")] + [DataRow("mario@-example.it")] + public void BrokenAddresses_AreRefused(string address) => Assert.IsFalse(EmailValidator.IsValid(address)); +} diff --git a/tests/Khaemhat.Fiscal.Italy.Tests/ItalianIdentifiersTests.cs b/tests/Khaemhat.Fiscal.Italy.Tests/ItalianIdentifiersTests.cs new file mode 100644 index 0000000..9aae0bc --- /dev/null +++ b/tests/Khaemhat.Fiscal.Italy.Tests/ItalianIdentifiersTests.cs @@ -0,0 +1,140 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy.Tests; + +[TestClass] +public sealed class ItalianVatNumberValidatorTests +{ + [TestMethod] + [DataRow("01234567897")] + [DataRow("IT 01234567897")] + [DataRow("it01234567897")] + public void ValidNumbers_PassWithOrWithoutPrefix(string number) => Assert.IsTrue(ItalianVatNumberValidator.IsValid(number)); + + [TestMethod] + [DataRow("01234567890")] // wrong check digit + [DataRow("1234567897")] // ten digits + [DataRow("00000000000")] // no taxpayer number + [DataRow("0123456789A")] + public void InvalidNumbers_AreRefused(string number) => Assert.IsFalse(ItalianVatNumberValidator.IsValid(number)); +} + +[TestClass] +public sealed class FiscalCodeTests +{ + private static readonly DateOnly Today = new(2026, 11, 11); + + [TestMethod] + public void Compute_GivesTheKnownCode() + { + var code = FiscalCodeCalculator.Compute(new PersonalTaxCodeData("Rossi", "Mario", new DateOnly(1980, 1, 1), PersonSex.Male, "H501")); + + Assert.AreEqual("RSSMRA80A01H501U", code); + Assert.IsTrue(FiscalCodeValidator.IsValid(code)); + } + + [TestMethod] + public void Compute_FollowsTheRulesForNamesAndWomen() + { + var code = FiscalCodeCalculator.Compute(new PersonalTaxCodeData("De Luca", "Giovanna Maria", new DateOnly(1975, 12, 31), PersonSex.Female, "f205")); + + // Surname: consonants D, L, C. Name with four consonants or more: 1st, 3rd and 4th (G, N, N). + StringAssert.StartsWith(code, "DLCGNN75T71F205"); + Assert.IsTrue(FiscalCodeValidator.IsValidPersonal(code)); + } + + [TestMethod] + public void Compute_PadsShortNamesWithVowelsAndX() + { + var code = FiscalCodeCalculator.Compute(new PersonalTaxCodeData("Fo", "Ugo", new DateOnly(2001, 7, 9), PersonSex.Male, "L219")); + + StringAssert.StartsWith(code, "FOXGUO01L09L219"); + } + + [TestMethod] + public void Compute_IgnoresAccentsAndApostrophes() + { + var plain = FiscalCodeCalculator.Compute(new PersonalTaxCodeData("DAMICO", "NICOLO", new DateOnly(1990, 5, 20), PersonSex.Male, "A944")); + var typed = FiscalCodeCalculator.Compute(new PersonalTaxCodeData("D'Amico", "Nicolò", new DateOnly(1990, 5, 20), PersonSex.Male, "A944")); + + Assert.AreEqual(plain, typed); + } + + [TestMethod] + public void Validator_AcceptsOmocodiaAndRefusesAWrongCheckCharacter() + { + // H501 becomes H50M (1 -> M) and the check character is computed again. + var first15 = "RSSMRA80A01H50M"; + var omocodic = first15 + FiscalCodeValidator.CheckCharacter(first15); + + Assert.IsTrue(FiscalCodeValidator.IsValidPersonal(omocodic)); + Assert.IsFalse(FiscalCodeValidator.IsValidPersonal("RSSMRA80A01H501A")); + Assert.IsFalse(FiscalCodeValidator.IsValidPersonal("RSSMRA80Z01H501U")); + } + + [TestMethod] + public void Validator_AcceptsCompanyCodes() => Assert.IsTrue(FiscalCodeValidator.IsValid("01234567897")); + + [TestMethod] + public void Decode_ReadsBirthDateSexAndPlace() + { + var man = FiscalCodeCalculator.Decode("RSSMRA80A01H501U", Today); + var woman = FiscalCodeCalculator.Decode(FiscalCodeCalculator.Compute(new("Bianchi", "Anna", new DateOnly(2010, 3, 15), PersonSex.Female, "F205")), Today); + + Assert.AreEqual(new PersonalTaxCodeInfo(new DateOnly(1980, 1, 1), PersonSex.Male, "H501"), man); + Assert.AreEqual(new DateOnly(2010, 3, 15), woman!.BirthDate); + Assert.AreEqual(PersonSex.Female, woman.Sex); + Assert.IsNull(FiscalCodeCalculator.Decode("RSSMRA80A01H501A", Today)); + } +} + +[TestClass] +public sealed class SdiRecipientCodeTests +{ + [TestMethod] + [DataRow("ABC1234", RecipientKind.Business)] + [DataRow("0000000", RecipientKind.Business)] + [DataRow("UFE3RT", RecipientKind.PublicAdministration)] + [DataRow("0000000", RecipientKind.Consumer)] + [DataRow("", RecipientKind.Consumer)] + [DataRow("XXXXXXX", RecipientKind.Foreign)] + public void ValidCodes_HaveNoProblems(string code, RecipientKind kind) => + Assert.IsEmpty(SdiRecipientCodeValidator.Check(code, kind)); + + [TestMethod] + [DataRow("ABC123", RecipientKind.Business, "fiscal.recipient.business-length")] + [DataRow("XXXXXXX", RecipientKind.Business, "fiscal.recipient.foreign-code-domestic")] + [DataRow("ABC1234", RecipientKind.PublicAdministration, "fiscal.recipient.pa-length")] + [DataRow("", RecipientKind.PublicAdministration, "fiscal.recipient.required")] + [DataRow("0000000", RecipientKind.Foreign, "fiscal.recipient.foreign")] + [DataRow("AB-1234", RecipientKind.Business, "fiscal.recipient.characters")] + public void WrongCodes_SayWhy(string code, RecipientKind kind, string problem) => + Assert.AreEqual(problem, SdiRecipientCodeValidator.Check(code, kind).Single().Code); + + [TestMethod] + public void Defaults_DependOnTheCustomer() + { + var rules = new ItalianTaxIdentifierRules(); + + Assert.AreEqual("XXXXXXX", rules.DefaultRecipientCode(RecipientKind.Foreign)); + Assert.AreEqual("0000000", rules.DefaultRecipientCode(RecipientKind.Consumer)); + Assert.IsNull(rules.DefaultRecipientCode(RecipientKind.PublicAdministration)); + } +} + +[TestClass] +public sealed class ItalianBankDirectoryTests +{ + [TestMethod] + public void FindByIban_ReadsAbiAndCab() + { + var directory = new ItalianBankDirectory([new BankInfo("05428", "Banca di prova", "BPROITMMXXX", null)]); + + var bank = directory.FindByIban("IT60 X054 2811 1010 0000 0123 456"); + + Assert.AreEqual("Banca di prova", bank!.Name); + Assert.AreEqual("11101", bank.BranchCode); + Assert.IsNull(directory.FindByIban("DE89 3704 0044 0532 0130 00")); + Assert.AreEqual(("05428", "11101"), ItalianBankDirectory.CodesOf("IT60X0542811101000000123456")); + } +} diff --git a/tests/Khaemhat.Infrastructure.Tests/ViesClientTests.cs b/tests/Khaemhat.Infrastructure.Tests/ViesClientTests.cs new file mode 100644 index 0000000..d38d731 --- /dev/null +++ b/tests/Khaemhat.Infrastructure.Tests/ViesClientTests.cs @@ -0,0 +1,104 @@ +using System.Net; +using System.Text; +using Khaemhat.Infrastructure.Http; + +namespace Khaemhat.Infrastructure.Tests; + +[TestClass] +public sealed class ViesClientTests +{ + [TestMethod] + public async Task Valid_ReturnsNameAndAddressAndTheUrlUsesTheMemberStateCode() + { + var handler = new StubHandler(HttpStatusCode.OK, + """{"isValid":true,"requestDate":"2026-11-11T10:00:00.000Z","userError":"VALID","name":"ACME SRL","address":"VIA ROMA 1\n00100 ROMA RM","vatNumber":"01234567897"}"""); + var client = Client(handler); + + var result = await client.CheckAsync("IT", "IT 01234567897", CancellationToken.None); + + Assert.AreEqual(ViesStatus.Valid, result.Status); + Assert.AreEqual("ACME SRL", result.Name); + Assert.AreEqual("01234567897", result.VatNumber); + Assert.AreEqual("/taxation_customs/vies/rest-api/ms/IT/vat/01234567897", handler.LastUri!.AbsolutePath); + } + + [TestMethod] + public async Task Greece_IsAskedAsEL() + { + var handler = new StubHandler(HttpStatusCode.OK, """{"isValid":false,"userError":"INVALID"}"""); + + var result = await Client(handler).CheckAsync("GR", "123456789", CancellationToken.None); + + Assert.AreEqual(ViesStatus.Invalid, result.Status); + StringAssert.Contains(handler.LastUri!.AbsolutePath, "/ms/EL/vat/123456789"); + } + + [TestMethod] + public async Task HiddenData_BecomesNull() + { + var result = await Client(new StubHandler(HttpStatusCode.OK, """{"isValid":true,"name":"---","address":"---"}""")) + .CheckAsync("DE", "123456789", CancellationToken.None); + + Assert.IsNull(result.Name); + Assert.IsNull(result.Address); + } + + [TestMethod] + public async Task ServiceErrors_AreUnavailableNeverInvalid() + { + var busy = await Client(new StubHandler(HttpStatusCode.OK, """{"isValid":false,"userError":"MS_UNAVAILABLE"}""")) + .CheckAsync("FR", "12345678901", CancellationToken.None); + var down = await Client(new StubHandler(HttpStatusCode.ServiceUnavailable, "")).CheckAsync("FR", "12345678901", CancellationToken.None); + var offline = await Client(new StubHandler(new HttpRequestException("no route"))).CheckAsync("FR", "12345678901", CancellationToken.None); + + Assert.AreEqual(ViesStatus.Unavailable, busy.Status); + Assert.AreEqual("MS_UNAVAILABLE", busy.Error); + Assert.AreEqual(ViesStatus.Unavailable, down.Status); + Assert.AreEqual(ViesStatus.Unavailable, offline.Status); + } + + [TestMethod] + public async Task CountriesOutsideTheEu_AreRefusedWithoutACall() + { + var handler = new StubHandler(HttpStatusCode.OK, "{}"); + + var result = await Client(handler).CheckAsync("CH", "123", CancellationToken.None); + + Assert.AreEqual(ViesStatus.InvalidInput, result.Status); + Assert.IsNull(handler.LastUri); + } + + private static ViesClient Client(StubHandler handler) => new(new HttpClient(handler), TimeProvider.System); + + private sealed class StubHandler : HttpMessageHandler + { + private readonly HttpStatusCode _status; + private readonly string _body; + private readonly Exception? _error; + + public StubHandler(HttpStatusCode status, string body) + { + _status = status; + _body = body; + } + + public StubHandler(Exception error) + { + _body = string.Empty; + _error = error; + } + + public Uri? LastUri { get; private set; } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + LastUri = request.RequestUri; + if (_error is not null) + { + throw _error; + } + + return Task.FromResult(new HttpResponseMessage(_status) { Content = new StringContent(_body, Encoding.UTF8, "application/json") }); + } + } +}