Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add more logs for magda geefonderneming #574

Merged
merged 1 commit into from
Dec 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,16 @@ public MagdaGeefVerenigingService(
_logger = logger;
}

public async Task<Result<VerenigingVolgensKbo>> GeefVereniging(KboNummer kboNummer, CommandMetadata metadata, CancellationToken cancellationToken)
public async Task<Result<VerenigingVolgensKbo>> GeefVereniging(
KboNummer kboNummer,
CommandMetadata metadata,
CancellationToken cancellationToken)
{
try
{
var reference = await CreateReference(_magdaCallReferenceRepository, metadata.Initiator, metadata.CorrelationId, kboNummer, cancellationToken);
var reference = await CreateReference(_magdaCallReferenceRepository, metadata.Initiator, metadata.CorrelationId, kboNummer,
cancellationToken);

var magdaResponse = await _magdaFacade.GeefOnderneming(kboNummer, reference);

if (MagdaResponseValidator.HasBlokkerendeUitzonderingen(magdaResponse))
Expand All @@ -70,7 +75,9 @@ public async Task<Result<VerenigingVolgensKbo>> GeefVereniging(KboNummer kboNumm
if (naamOndernemingType is null)
return VerenigingVolgensKboResult.GeenGeldigeVereniging;

var maatschappelijkeZetel = magdaOnderneming.Adressen.SingleOrDefault(a => a.Type.Code.Value == AdresCodes.MaatschappelijkeZetel && IsActiveToday(a.DatumBegin, a.DatumEinde));
var maatschappelijkeZetel =
magdaOnderneming.Adressen.SingleOrDefault(a => a.Type.Code.Value == AdresCodes.MaatschappelijkeZetel &&
IsActiveToday(a.DatumBegin, a.DatumEinde));

return VerenigingVolgensKboResult.GeldigeVereniging(
new VerenigingVolgensKbo
Expand Down Expand Up @@ -198,17 +205,31 @@ private static bool IsActief(Onderneming2_0Type magdaOnderneming)
private static bool IsOnderneming(Onderneming2_0Type magdaOnderneming)
=> magdaOnderneming.OndernemingOfVestiging.Code.Value == OndernemingOfVestigingCodes.Onderneming;

private Result<VerenigingVolgensKbo> HandleUitzonderingen(string kboNummer, ResponseEnvelope<GeefOndernemingResponseBody>? magdaResponse)
private Result<VerenigingVolgensKbo> HandleUitzonderingen(
string kboNummer,
ResponseEnvelope<GeefOndernemingResponseBody>? magdaResponse)
{
var uitzonderingen = magdaResponse?.Body?.GeefOndernemingResponse?.Repliek.Antwoorden.Antwoord.Uitzonderingen;

_logger.LogInformation(
message: "Uitzondering bij het aanroepen van de Magda GeefOnderneming service voor KBO-nummer {KboNummer}: '{Diagnose}'",
"Uitzondering bij het aanroepen van de Magda GeefOnderneming service voor KBO-nummer {KboNummer}: " +
"\nFouten:\n'{Uitzonderingen}'" +
"\nWaarschuwingen:\n'{Waarschuwingen}'" +
"\nInformatie:\n'{Informatie}'",
kboNummer,
magdaResponse?.Body?.GeefOndernemingResponse?.Repliek.Antwoorden.Antwoord.Uitzonderingen.ConcatenateUitzonderingen("\n"));
uitzonderingen?.ConcatenateUitzonderingen(separator: "\n", UitzonderingTypeType.FOUT),
uitzonderingen?.ConcatenateUitzonderingen(separator: "\n", UitzonderingTypeType.WAARSCHUWING),
uitzonderingen?.ConcatenateUitzonderingen(separator: "\n", UitzonderingTypeType.INFORMATIE));

return VerenigingVolgensKboResult.GeenGeldigeVereniging;
}

private static async Task<MagdaCallReference> CreateReference(IMagdaCallReferenceRepository repository, string initiator, Guid correlationId, string opgevraagdOnderwerp, CancellationToken cancellationToken)
private static async Task<MagdaCallReference> CreateReference(
IMagdaCallReferenceRepository repository,
string initiator,
Guid correlationId,
string opgevraagdOnderwerp,
CancellationToken cancellationToken)
{
var magdaCallReference = new MagdaCallReference
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,31 @@
namespace AssociationRegistry.Admin.Api.Magda;

using System;
using System.Linq;
using AssociationRegistry.Magda.Models;
using AssociationRegistry.Magda.Models.GeefOnderneming;
using AssociationRegistry.Magda.Onderneming.GeefOnderneming;
using System;
using System.Linq;

public static class MagdaResponseExtensions
{
public static string ConcatenateUitzonderingen(this UitzonderingType[] source, string separator)
public static string ConcatenateUitzonderingen(
this UitzonderingType[] source,
string separator,
UitzonderingTypeType uitzonderingTypeType)
=> string.Join(
separator,
source.Where(type => type.Type == UitzonderingTypeType.FOUT)
.Select(type => type.Diagnose));
source.Where(type => type.Type == uitzonderingTypeType)
.Select(type => $"{type.Identificatie} - {type.Diagnose} - {type.Omstandigheid}"));

public static bool HasUitzonderingenOfType(this ResponseEnvelope<GeefOndernemingResponseBody>? source, UitzonderingTypeType uitzonderingTypeType)
public static bool HasUitzonderingenOfType(
this ResponseEnvelope<GeefOndernemingResponseBody>? source,
UitzonderingTypeType uitzonderingTypeType)
{
return HasAnyUitzondering(source, type => type.Type == uitzonderingTypeType);
return HasAnyUitzondering(source, predicate: type => type.Type == uitzonderingTypeType);
}

public static bool HasAnyUitzondering(this ResponseEnvelope<GeefOndernemingResponseBody>? source, Func<UitzonderingType, bool> predicate)
public static bool HasAnyUitzondering(
this ResponseEnvelope<GeefOndernemingResponseBody>? source,
Func<UitzonderingType, bool> predicate)
=> source?.Body?.GeefOndernemingResponse?.Repliek?.Antwoorden?.Antwoord?.Uitzonderingen?.Any(predicate) ?? false;
}
40 changes: 25 additions & 15 deletions src/AssociationRegistry.Magda/MagdaFacade.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
namespace AssociationRegistry.Magda;

using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml.Serialization;
using Configuration;
using Framework;
using Microsoft.Extensions.Logging;
using Models;
using Models.GeefOnderneming;
using Models.GeefOndernemingVKBO;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml.Serialization;

public class MagdaFacade : IMagdaFacade
{
Expand All @@ -23,10 +23,12 @@ public MagdaFacade(
_logger = logger;
}

public async Task<ResponseEnvelope<GeefOndernemingVKBOResponseBody>?> GeefOndernemingVKBO(string kbonummer, MagdaCallReference reference)
public async Task<ResponseEnvelope<GeefOndernemingVKBOResponseBody>?> GeefOndernemingVKBO(
string kbonummer,
MagdaCallReference reference)
{
Throw<ArgumentNullException>
.IfNullOrWhiteSpace(_magdaOptions.GeefOndernemingVkboEndpoint, $"{nameof(MagdaOptionsSection.GeefOndernemingVkboEndpoint)}");
.IfNullOrWhiteSpace(_magdaOptions.GeefOndernemingVkboEndpoint, $"{nameof(MagdaOptionsSection.GeefOndernemingVkboEndpoint)}");

var unsignedEnvelope = MakeEnvelope(GeefOndernemingVKBOBody.CreateRequest(kbonummer, reference.Reference, _magdaOptions));
var clientCertificate = GetMagdaClientCertificate(_magdaOptions);
Expand All @@ -38,11 +40,10 @@ public MagdaFacade(
signedEnvelope);
}


public async Task<ResponseEnvelope<GeefOndernemingResponseBody>?> GeefOnderneming(string kbonummer, MagdaCallReference reference)
{
Throw<ArgumentNullException>
.IfNullOrWhiteSpace(_magdaOptions.GeefOndernemingEndpoint, $"{nameof(MagdaOptionsSection.GeefOndernemingEndpoint)}");
.IfNullOrWhiteSpace(_magdaOptions.GeefOndernemingEndpoint, $"{nameof(MagdaOptionsSection.GeefOndernemingEndpoint)}");

var unsignedEnvelope = MakeEnvelope(GeefOndernemingBody.CreateRequest(kbonummer, reference.Reference, _magdaOptions));
var clientCertificate = GetMagdaClientCertificate(_magdaOptions);
Expand All @@ -58,29 +59,36 @@ public MagdaFacade(
{
if (magdaOptionsSection.ClientCertificate is null && magdaOptionsSection.ClientCertificatePassword is null) return null;

var maybeClientCertificate = MagdaClientCertificate.Create(magdaOptionsSection.ClientCertificate!, magdaOptionsSection.ClientCertificatePassword!);
var maybeClientCertificate =
MagdaClientCertificate.Create(magdaOptionsSection.ClientCertificate!, magdaOptionsSection.ClientCertificatePassword!);

if (maybeClientCertificate is not { } clientCertificate)
throw new NullReferenceException("ClientCertificate should never be null");

return clientCertificate;
}

private async Task<ResponseEnvelope<T>?> PerformMagdaRequest<T>(string endpoint, X509Certificate? magdaClientCertificate, string signedEnvelope)
private async Task<ResponseEnvelope<T>?> PerformMagdaRequest<T>(
string endpoint,
X509Certificate? magdaClientCertificate,
string signedEnvelope)
{
using var client = GetMagdaHttpClient(magdaClientCertificate);

try
{
return await SendEnvelopeToendpoint<T>(endpoint, signedEnvelope, client);
}
catch (TaskCanceledException ex)
{
_logger.LogError(ex, "{Message}", ex.Message);
throw new Exception("A timeout occurred when calling the Magda services", ex);
_logger.LogError(ex, message: "{Message}", ex.Message);

throw new Exception(message: "A timeout occurred when calling the Magda services", ex);
}
catch (Exception ex)
{
_logger.LogError(ex, "{Message}", ex.Message);
_logger.LogError(ex, message: "An error occurred when calling the Magda services: {Message}", ex.Message);

throw new Exception(ex.Message, ex);
}
}
Expand All @@ -89,15 +97,16 @@ private HttpClient GetMagdaHttpClient(X509Certificate? magdaClientCertificate)
{
var client = new HttpClient(new MagdaHttpClientHandler(magdaClientCertificate));
client.Timeout = TimeSpan.FromSeconds(_magdaOptions.Timeout);

return client;
}

private async Task<ResponseEnvelope<T>?> SendEnvelopeToendpoint<T>(string endpoint, string signedEnvelope, HttpClient client)
{
var response = await client
.PostAsync(
.PostAsync(
endpoint,
new StringContent(signedEnvelope, Encoding.UTF8, "application/soap+xml"));
new StringContent(signedEnvelope, Encoding.UTF8, mediaType: "application/soap+xml"));

if (!response.IsSuccessStatusCode)
{
Expand All @@ -107,12 +116,13 @@ private HttpClient GetMagdaHttpClient(X509Certificate? magdaClientCertificate)
return null;
}

_logger.LogTrace("GeefOnderneming http response: {@Result}", response);
_logger.LogTrace(message: "GeefOnderneming http response: {@Result}", response);

var serializer = new XmlSerializer(typeof(ResponseEnvelope<T>));

var xml = await response.Content.ReadAsStringAsync();
using var reader = new StringReader(xml);

{
return (ResponseEnvelope<T>?)serializer.Deserialize(reader);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public async Task Then_It_LogsTheUitzondering()
It.Is<LogLevel>(l => l == LogLevel.Information),
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString() ==
$"Uitzondering bij het aanroepen van de Magda GeefOnderneming service voor KBO-nummer {kboNummer}: 'Er is een fout gebeurd\nEr is nog een fout gebeurd'"),
$"Uitzondering bij het aanroepen van de Magda GeefOnderneming service voor KBO-nummer {kboNummer}: \nFouten:\n' - Er is een fout gebeurd - \n - Er is nog een fout gebeurd - '\nWaarschuwingen:\n''\nInformatie:\n''"),
It.IsAny<Exception>(),
It.Is<Func<It.IsAnyType, Exception, string>>((v, t) => true)!),
Times.Once);
Expand Down
Loading