Files
Khaemhat/src/Khaemhat.Infrastructure/Http/ViesClient.cs
T
Alby96andClaude Opus 5.5 25f8a7ad30 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>
2026-11-11 21:53:37 +01:00

169 lines
7.0 KiB
C#

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; }
}
}