75 lines
2.4 KiB
C#

using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using gehGassi.Common;
using gehGassi.Core.Interfaces;
using Microsoft.Extensions.Options;
using VatServiceReference;
namespace gehGassi.External.Services
{
/// <summary>
/// Service der EU-UID-Nummern auf deren Gültigkeit prüft
/// </summary>
public class VatValidationService : IVatValidationService
{
private readonly IOptions<VatValidationSettings> _settings;
/// <summary>
/// Erstellt eine Instanz
/// </summary>
/// <param name="settings">Instanz eines IOptions VatValidationSettings</param>
[ExcludeFromCodeCoverage]
public VatValidationService(IOptions<VatValidationSettings> settings)
{
_settings = settings;
}
/// <summary>
/// Prüft eine UID-Nummer auf deren Gültigkeit
/// </summary>
/// <param name="vat">UID-Nummer</param>
/// <param name="countryIso2">ISO-2 Code des Landes</param>
/// <returns>true wenn erfolgreich, false sonst</returns>
public async Task<bool> IsValidAsync(string vat, string countryIso2)
{
if (string.IsNullOrWhiteSpace(vat))
return false;
if (string.IsNullOrWhiteSpace(countryIso2))
return false;
if (!_settings.Value.Enabled)
return true;
var countriesToCheck = _settings.Value.Countries.Split(';');
if (!countriesToCheck.Contains(countryIso2.ToUpper()))
return true;
if (string.IsNullOrWhiteSpace(vat))
return false;
System.Diagnostics.Debug.WriteLine($"VAT Prüfung: {vat} - {countryIso2}");
var proxy = new VatServiceReference.checkVatPortTypeClient();
proxy.Endpoint.Address = new EndpointAddress(_settings.Value.Address);
bool valid;
//Die Landeskennzeichnung wegnehmen
vat = vat.ToUpperInvariant().Replace(countryIso2.ToUpperInvariant(), "");
try
{
var result = await proxy.checkVatAsync(new checkVatRequest(countryIso2, vat));
valid = result.valid;
}
catch
{
valid = false;
}
return valid;
}
}
}