feat: identifier validators and the VIES client (#40)
Parties need their identifiers checked before they reach documents. IBAN, EAN and e-mail checks are international and live in Core. The Italian VAT number, fiscal code (with calculator, decoder and omocodia) and SDI recipient code are Italian, so they sit in the Italian pack behind ITaxIdentifierRules, as the non-negotiable rule of SPEC 1.10 wins over the class list of SPEC 21 (ADR 0025). IBankDirectory reads ABI and CAB from an Italian IBAN; its bank list arrives with the base data. ViesClient calls the VIES REST service and never reports a number as invalid when the service could not answer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
49d2bb166b
commit
25f8a7ad30
10 files changed
+1086
-2
No files matched your search
@@ -0,0 +1,349 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Khaemhat.Core.Validation;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// Italian VAT numbers (partita IVA): 11 digits, the last a Luhn-like check digit; the first seven (the taxpayer
|
||||
/// number) cannot be all zeros.
|
||||
/// </summary>
|
||||
public static class ItalianVatNumberValidator
|
||||
{
|
||||
/// <summary>The number without spaces and without the <c>IT</c> prefix.</summary>
|
||||
/// <param name="vatNumber">The number as typed.</param>
|
||||
/// <returns>The compact number.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Whether a VAT number is valid.</summary>
|
||||
/// <param name="vatNumber">The number, with or without prefix.</param>
|
||||
/// <returns><see langword="true"/> when valid.</returns>
|
||||
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';
|
||||
}
|
||||
|
||||
/// <summary>The check digit for the first ten digits.</summary>
|
||||
/// <param name="digits">Ten digits.</param>
|
||||
/// <returns>The check digit.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class FiscalCodeValidator
|
||||
{
|
||||
/// <summary>Letters that replace digits in omocodic codes: L=0, M=1... V=9.</summary>
|
||||
internal const string OmocodiaLetters = "LMNPQRSTUV";
|
||||
|
||||
/// <summary>Month letters: A=January... T=December.</summary>
|
||||
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];
|
||||
|
||||
/// <summary>The code without spaces, in capitals.</summary>
|
||||
/// <param name="code">The code as typed.</param>
|
||||
/// <returns>The compact code.</returns>
|
||||
public static string Normalize(string? code) =>
|
||||
string.Concat((code ?? string.Empty).Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant();
|
||||
|
||||
/// <summary>Whether a tax code is valid: a 16-character personal code or an 11-digit company code.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns><see langword="true"/> when valid.</returns>
|
||||
public static bool IsValid(string? code)
|
||||
{
|
||||
var value = Normalize(code);
|
||||
return value.Length == 11 ? ItalianVatNumberValidator.IsValid(value) : IsValidPersonal(value);
|
||||
}
|
||||
|
||||
/// <summary>Whether a 16-character personal code is valid.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns><see langword="true"/> when valid.</returns>
|
||||
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];
|
||||
}
|
||||
|
||||
/// <summary>The check character of the first 15 characters.</summary>
|
||||
/// <param name="first15">The first 15 characters, in capitals.</param>
|
||||
/// <returns>The check character.</returns>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>The code with omocodia letters turned back into digits.</summary>
|
||||
/// <param name="code">A 16-character code.</param>
|
||||
/// <returns>The code with digits in the digit positions.</returns>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Computes and decodes Italian personal tax codes.</summary>
|
||||
public static class FiscalCodeCalculator
|
||||
{
|
||||
/// <summary>The personal tax code of a person.</summary>
|
||||
/// <param name="data">Surname, name, birth date, sex and cadastral code of the birth place.</param>
|
||||
/// <returns>The 16-character code.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Reads birth date, sex and place from a personal code.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="today">The reference date: a two-digit year after it belongs to the previous century.</param>
|
||||
/// <returns>The data, or <see langword="null"/> for an invalid code.</returns>
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// E-invoice recipient codes (codice destinatario): 7 characters for businesses, 6 for public administrations (IPA
|
||||
/// office code), <c>0000000</c> for consumers and businesses without a channel, <c>XXXXXXX</c> abroad.
|
||||
/// </summary>
|
||||
public static class SdiRecipientCodeValidator
|
||||
{
|
||||
private const string Field = "RecipientCode";
|
||||
|
||||
/// <summary>The rules a recipient code breaks.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="kind">The kind of customer.</param>
|
||||
/// <returns>Errors and warnings.</returns>
|
||||
public static IReadOnlyList<FiscalProblem> 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")],
|
||||
_ => [],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The Italian tax identifiers as a pack feature.</summary>
|
||||
public sealed class ItalianTaxIdentifierRules : ITaxIdentifierRules
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string NormalizeVatNumber(string? vatNumber) => ItalianVatNumberValidator.Normalize(vatNumber);
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsValidVatNumber(string? vatNumber) => ItalianVatNumberValidator.IsValid(vatNumber);
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsValidTaxCode(string? taxCode) => FiscalCodeValidator.IsValid(taxCode);
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ComputePersonalTaxCode(PersonalTaxCodeData data) => FiscalCodeCalculator.Compute(data);
|
||||
|
||||
/// <inheritdoc />
|
||||
public PersonalTaxCodeInfo? DecodePersonalTaxCode(string? taxCode, DateOnly today) => FiscalCodeCalculator.Decode(taxCode, today);
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<FiscalProblem> CheckRecipientCode(string? recipientCode, RecipientKind kind) =>
|
||||
SdiRecipientCodeValidator.Check(recipientCode, kind);
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? DefaultRecipientCode(RecipientKind kind) => kind switch
|
||||
{
|
||||
RecipientKind.Foreign => FatturaPaCodeLists.RecipientCodeForeign,
|
||||
RecipientKind.PublicAdministration => null,
|
||||
_ => FatturaPaCodeLists.RecipientCodeNone,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Italian banks by ABI code, to fill bank name, BIC and CAB from an Italian IBAN
|
||||
/// (<c>IT</c> + check + CIN + ABI + CAB + account).
|
||||
/// </summary>
|
||||
public sealed class ItalianBankDirectory : IBankDirectory
|
||||
{
|
||||
private readonly Dictionary<string, BankInfo> _byAbi;
|
||||
|
||||
/// <summary>Creates the directory.</summary>
|
||||
/// <param name="banks">The banks, one per ABI code.</param>
|
||||
public ItalianBankDirectory(IEnumerable<BankInfo> banks)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(banks);
|
||||
_byAbi = banks.GroupBy(b => b.BankCode, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>How many banks the directory knows.</summary>
|
||||
public int Count => _byAbi.Count;
|
||||
|
||||
/// <summary>ABI and CAB of an Italian IBAN.</summary>
|
||||
/// <param name="iban">The IBAN.</param>
|
||||
/// <returns>The codes, or <see langword="null"/> for an invalid or foreign IBAN.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public BankInfo? FindByIban(string? iban) =>
|
||||
CodesOf(iban) is { } codes && _byAbi.TryGetValue(codes.Abi, out var bank) ? bank with { BranchCode = codes.Cab } : null;
|
||||
}
|
||||
@@ -18,6 +18,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase
|
||||
AddFeature<IWithholdingRules>(new WithholdingRulesIt());
|
||||
AddFeature<IFixedAssetRules>(new FixedAssetRulesIt());
|
||||
AddFeature<ITaxPaymentFormExporter>(new F24Exporter());
|
||||
AddFeature<ITaxIdentifierRules>(new ItalianTaxIdentifierRules());
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
Reference in new issue
Block a user