M4 · Tabelle, anagrafiche, articoli (v0.4.0) #121

Merged
Alby96 merged 12 commits from feat/37-tabelle-anagrafiche into main 2026-11-12 13:03:38 +01:00
10 changed files with 1086 additions and 2 deletions
Showing only changes of commit 25f8a7ad30 - Show all commits

No files matched your search

+4
View File
@@ -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
@@ -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.
+149
View File
@@ -0,0 +1,149 @@
using System.Globalization;
using System.Text;
namespace Khaemhat.Core.Validation;
/// <summary>
/// International Bank Account Numbers (ISO 13616): country, length of the country and the mod-97 check. Spaces and
/// case do not matter.
/// </summary>
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<string, int> 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,
};
/// <summary>The IBAN without spaces, in capitals.</summary>
/// <param name="iban">The IBAN as typed.</param>
/// <returns>The compact form, or an empty string.</returns>
public static string Normalize(string? iban) =>
iban is null ? string.Empty : string.Concat(iban.Where(c => !char.IsWhiteSpace(c))).ToUpperInvariant();
/// <summary>The IBAN in groups of four characters, as printed.</summary>
/// <param name="iban">The IBAN.</param>
/// <returns>The printed form.</returns>
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();
}
/// <summary>Whether an IBAN is well formed and its check digits are right.</summary>
/// <param name="iban">The IBAN, with or without spaces.</param>
/// <returns><see langword="true"/> for a valid IBAN.</returns>
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;
}
}
/// <summary>GTIN barcodes: EAN-8, UPC-A (12), EAN-13 and GTIN-14, with the mod-10 check digit.</summary>
public static class EanValidator
{
/// <summary>Whether a barcode has a valid length and check digit.</summary>
/// <param name="code">The digits of the barcode.</param>
/// <returns><see langword="true"/> for a valid code.</returns>
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';
}
/// <summary>The check digit for the digits of a code without it.</summary>
/// <param name="digits">The digits before the check digit.</param>
/// <returns>The check digit, 0-9.</returns>
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;
}
}
/// <summary>
/// E-mail addresses as people type them for invoices and reminders: one <c>@</c>, 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.
/// </summary>
public static class EmailValidator
{
private const string LocalSpecials = ".!#$%&'*+/=?^_`{|}~-";
/// <summary>Whether an address is acceptable.</summary>
/// <param name="address">The address.</param>
/// <returns><see langword="true"/> for a valid address.</returns>
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);
}
}
@@ -0,0 +1,98 @@
namespace Khaemhat.Fiscal.Abstractions;
/// <summary>The sex written in a personal tax code.</summary>
public enum PersonSex
{
/// <summary>Male.</summary>
Male = 0,
/// <summary>Female.</summary>
Female = 1,
}
/// <summary>What a personal tax code is computed from.</summary>
/// <param name="Surname">The surname.</param>
/// <param name="GivenName">The given name (all given names, as in the registry).</param>
/// <param name="BirthDate">The date of birth.</param>
/// <param name="Sex">The sex.</param>
/// <param name="BirthPlaceCode">The code of the place of birth (Italy: cadastral code of the municipality, or Z... for a foreign country).</param>
public sealed record PersonalTaxCodeData(string Surname, string GivenName, DateOnly BirthDate, PersonSex Sex, string BirthPlaceCode);
/// <summary>What can be read back from a personal tax code.</summary>
/// <param name="BirthDate">The date of birth (century guessed from the reference date).</param>
/// <param name="Sex">The sex.</param>
/// <param name="BirthPlaceCode">The code of the place of birth.</param>
public sealed record PersonalTaxCodeInfo(DateOnly BirthDate, PersonSex Sex, string BirthPlaceCode);
/// <summary>Who receives an e-invoice, for the recipient code rules.</summary>
public enum RecipientKind
{
/// <summary>A business with its own channel, or without (then the default code).</summary>
Business = 0,
/// <summary>A public administration (Italy: office code of 6 characters).</summary>
PublicAdministration = 1,
/// <summary>A private consumer.</summary>
Consumer = 2,
/// <summary>A customer abroad.</summary>
Foreign = 3,
}
/// <summary>The country's tax identifiers: VAT number, personal tax code and e-invoice recipient code.</summary>
public interface ITaxIdentifierRules
{
/// <summary>The VAT number without spaces and without the country prefix.</summary>
/// <param name="vatNumber">The number as typed.</param>
/// <returns>The compact number.</returns>
string NormalizeVatNumber(string? vatNumber);
/// <summary>Whether a domestic VAT number is valid (format and check digit).</summary>
/// <param name="vatNumber">The number, with or without prefix.</param>
/// <returns><see langword="true"/> when valid.</returns>
bool IsValidVatNumber(string? vatNumber);
/// <summary>Whether a personal or company tax code is valid.</summary>
/// <param name="taxCode">The code.</param>
/// <returns><see langword="true"/> when valid.</returns>
bool IsValidTaxCode(string? taxCode);
/// <summary>Computes the personal tax code of a person.</summary>
/// <param name="data">The personal data.</param>
/// <returns>The code.</returns>
string ComputePersonalTaxCode(PersonalTaxCodeData data);
/// <summary>Reads birth date, sex and place back from a personal tax code.</summary>
/// <param name="taxCode">The code.</param>
/// <param name="today">The reference date that decides the century.</param>
/// <returns>The data, or <see langword="null"/> if the code is not a valid personal code.</returns>
PersonalTaxCodeInfo? DecodePersonalTaxCode(string? taxCode, DateOnly today);
/// <summary>The rules an e-invoice recipient code breaks for a kind of customer; empty when valid.</summary>
/// <param name="recipientCode">The code.</param>
/// <param name="kind">The kind of customer.</param>
/// <returns>Errors and warnings with field <c>RecipientCode</c>.</returns>
IReadOnlyList<FiscalProblem> CheckRecipientCode(string? recipientCode, RecipientKind kind);
/// <summary>The recipient code to propose for a kind of customer without one.</summary>
/// <param name="kind">The kind of customer.</param>
/// <returns>The default code, or <see langword="null"/> if the customer must give one.</returns>
string? DefaultRecipientCode(RecipientKind kind);
}
/// <summary>A bank found from its national code.</summary>
/// <param name="BankCode">The national bank code (Italy: ABI).</param>
/// <param name="Name">The name of the bank.</param>
/// <param name="Bic">The BIC, when known.</param>
/// <param name="BranchCode">The branch code (Italy: CAB), when the IBAN has one.</param>
public sealed record BankInfo(string BankCode, string Name, string? Bic, string? BranchCode);
/// <summary>The country's directory of banks, to fill bank name and BIC from an IBAN.</summary>
public interface IBankDirectory
{
/// <summary>The bank of a domestic IBAN.</summary>
/// <param name="iban">The IBAN.</param>
/// <returns>The bank, or <see langword="null"/> if the IBAN is foreign, invalid or the bank unknown.</returns>
BankInfo? FindByIban(string? iban);
}
@@ -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 />
@@ -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;
/// <summary>The outcome of a VIES check.</summary>
public enum ViesStatus
{
/// <summary>The number is registered for intra-EU operations.</summary>
Valid = 0,
/// <summary>The number is not registered (or not active for intra-EU operations).</summary>
Invalid = 1,
/// <summary>The service or the member state could not answer; try again later.</summary>
Unavailable = 2,
/// <summary>The request was refused as malformed (unknown country, wrong characters).</summary>
InvalidInput = 3,
}
/// <summary>The answer of VIES, as saved on the party (SPEC §11.2).</summary>
/// <param name="Status">The outcome.</param>
/// <param name="CountryCode">The member state code asked (Greece is <c>EL</c>).</param>
/// <param name="VatNumber">The number asked, without prefix.</param>
/// <param name="CheckedAt">When VIES answered (or when the call failed), UTC.</param>
/// <param name="Name">The registered name, when the member state shares it.</param>
/// <param name="Address">The registered address, when shared.</param>
/// <param name="Error">The VIES error code for <see cref="ViesStatus.Unavailable"/> and <see cref="ViesStatus.InvalidInput"/>.</param>
public sealed record ViesResult(
ViesStatus Status,
string CountryCode,
string VatNumber,
DateTimeOffset CheckedAt,
string? Name,
string? Address,
string? Error);
/// <summary>
/// Checks EU VAT numbers with the VIES REST service of the European Commission
/// (<c>GET /taxation_customs/vies/rest-api/ms/{country}/vat/{number}</c>). Network errors and timeouts become
/// <see cref="ViesStatus.Unavailable"/>: a check that could not be made is never reported as invalid.
/// </summary>
public sealed class ViesClient
{
/// <summary>The public service address.</summary>
public static readonly Uri DefaultBaseAddress = new("https://ec.europa.eu/taxation_customs/vies/rest-api/");
private static readonly HashSet<string> 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;
/// <summary>Creates the client.</summary>
/// <param name="http">The HTTP client; its base address defaults to <see cref="DefaultBaseAddress"/>.</param>
/// <param name="time">The clock.</param>
public ViesClient(HttpClient http, TimeProvider time)
{
ArgumentNullException.ThrowIfNull(http);
ArgumentNullException.ThrowIfNull(time);
_http = http;
_http.BaseAddress ??= DefaultBaseAddress;
_time = time;
}
/// <summary>The VIES member state code for an ISO country code (Greece: <c>GR</c> becomes <c>EL</c>).</summary>
/// <param name="isoCountryCode">ISO 3166-1 alpha-2 code.</param>
/// <returns>The VIES code, or <see langword="null"/> outside the EU.</returns>
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;
}
/// <summary>Checks a VAT number.</summary>
/// <param name="countryCode">ISO or VIES country code.</param>
/// <param name="vatNumber">The number, with or without the country prefix.</param>
/// <param name="cancellationToken">Cancels the call.</param>
/// <returns>The outcome.</returns>
public async Task<ViesResult> 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<ViesAnswer>(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; }
}
}
@@ -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));
}
@@ -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"));
}
}
@@ -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<HttpResponseMessage> 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") });
}
}
}