From d9c725dee4e2c28e4355673123094955b6ac768f Mon Sep 17 00:00:00 2001 From: Phil Schneider Date: Mon, 24 Jul 2023 15:44:00 +0200 Subject: [PATCH] feat(bpdm): adjust bpdm service calls to new service structure of bpdm service has changed, therefor the models have been aligned Refs: CPLP-2976 --- .../Bpdm.Library/Bpdm.Library.csproj | 1 + .../Bpdm.Library/BpdmService.cs | 126 +++--- .../Bpdm.Library}/BpnAccess.cs | 48 +-- .../BpdmServiceCollectionExtension.cs | 2 +- .../BpnAccessCollectionExtension.cs | 3 +- .../Bpdm.Library}/IBpnAccess.cs | 5 +- .../Bpdm.Library/Models}/BpdmAddressDto.cs | 16 +- .../Models/BpdmLegalEntityData.cs | 208 +++------- .../Bpdm.Library/Models/BpdmLegalEntityDto.cs | 155 ++++++++ .../Models/BpdmLegalEntityOutputData.cs | 104 +---- .../Models}/FetchBusinessPartnerDto.cs | 2 +- .../ApplicationChecklistExtensions.cs | 1 + .../Bpn/Model/BpdmLegalEntityDto.cs | 105 ----- .../IRegistrationBusinessLogic.cs | 2 +- .../RegistrationBusinessLogic.cs | 61 +-- .../Controllers/RegistrationController.cs | 2 +- .../Registration.Service/Program.cs | 3 +- .../Bpdm.Library/BPNAccessTest.cs | 234 +++++++++++ .../Bpdm.Library/BpdmServiceTests.cs | 40 +- .../BPNAccessTest.cs | 376 ------------------ .../RegistrationBusinessLogicTest.cs | 42 +- 21 files changed, 568 insertions(+), 968 deletions(-) rename src/{registration/Registration.Service/Bpn => externalsystems/Bpdm.Library}/BpnAccess.cs (63%) rename src/externalsystems/Bpdm.Library/{ => DependencyInjection}/BpdmServiceCollectionExtension.cs (96%) rename src/{registration/Registration.Service/Bpn => externalsystems/Bpdm.Library/DependencyInjection}/BpnAccessCollectionExtension.cs (92%) rename src/{registration/Registration.Service/Bpn => externalsystems/Bpdm.Library}/IBpnAccess.cs (80%) rename src/{registration/Registration.Service/Bpn/Model => externalsystems/Bpdm.Library/Models}/BpdmAddressDto.cs (90%) create mode 100644 src/externalsystems/Bpdm.Library/Models/BpdmLegalEntityDto.cs rename src/{registration/Registration.Service/Bpn/Model => externalsystems/Bpdm.Library/Models}/FetchBusinessPartnerDto.cs (99%) delete mode 100644 src/registration/Registration.Service/Bpn/Model/BpdmLegalEntityDto.cs create mode 100644 tests/externalsystems/Bpdm.Library/BPNAccessTest.cs delete mode 100644 tests/registration/Registration.Service.Tests/BPNAccessTest.cs diff --git a/src/externalsystems/Bpdm.Library/Bpdm.Library.csproj b/src/externalsystems/Bpdm.Library/Bpdm.Library.csproj index 260d237f14..7d3e0daf02 100644 --- a/src/externalsystems/Bpdm.Library/Bpdm.Library.csproj +++ b/src/externalsystems/Bpdm.Library/Bpdm.Library.csproj @@ -29,6 +29,7 @@ + diff --git a/src/externalsystems/Bpdm.Library/BpdmService.cs b/src/externalsystems/Bpdm.Library/BpdmService.cs index 30ecf9ea44..fc62f34e3a 100644 --- a/src/externalsystems/Bpdm.Library/BpdmService.cs +++ b/src/externalsystems/Bpdm.Library/BpdmService.cs @@ -22,7 +22,6 @@ using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Models; using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; using Org.Eclipse.TractusX.Portal.Backend.Framework.HttpClientExtensions; -using Org.Eclipse.TractusX.Portal.Backend.Framework.Linq; using Org.Eclipse.TractusX.Portal.Backend.Framework.Token; using System.Net.Http.Json; using System.Text.Json; @@ -37,7 +36,10 @@ public class BpdmService : IBpdmService private static readonly JsonSerializerOptions Options = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - Converters = { new JsonStringEnumConverter(allowIntegerValues: false) } + Converters = + { + new JsonStringEnumConverter(allowIntegerValues: false), + } }; public BpdmService(ITokenService tokenService, IOptions options) @@ -54,75 +56,54 @@ public async Task PutInputLegalEntity(BpdmTransferData data, CancellationT var requestData = new BpdmLegalEntityData[] { new( - data.ExternalId, // ExternalId - null, // Bpn + data.ExternalId, // Index + Enumerable.Repeat(data.CompanyName, 1), // LegalName + data.ShortName, // LegalShortName + null, // LegalForm data.Identifiers.Select(x => new BpdmIdentifier( x.Value, // Value x.BpdmIdentifierId, // Type - null, // IssuingBody - null)), // Status - new BpdmName[] // Names - { - new ( - data.CompanyName, // Value - null, // ShortName - "REGISTERED", // Type - "de") // Language - }, - null, // LegalForm - null, // Status - Enumerable.Empty(), - Enumerable.Empty(), // Types - Enumerable.Empty(), + null)), // IssuingBody + Enumerable.Empty(), // Status + Enumerable.Empty(), // Classifications + Enumerable.Empty(), // Roles new BpdmLegalAddress( - new BpdmAddressVersion( - "WESTERN_LATIN_STANDARD", //CharacterSet - "de"), // Version - null, // CareOf - Enumerable.Empty(),// Contexts - data.AlphaCode2, // Country - data.Region == null - ? Enumerable.Empty() - : new BpdmAdministrativeArea[] { - new ( - data.Region, // Value - null, // ShortName - null, // Fipscode - "COUNTY" // Type - ) - }, - data.ZipCode == null - ? Enumerable.Empty() - : new BpdmPostcode[] { - new ( - data.ZipCode, // Value - "REGULAR") // Type - }, - new BpdmLocality[] { - new ( - data.City, // Value - null, // ShortName - "CITY") // Type - }, - new BpdmThoroughfare[] { - new ( - data.StreetName, // Value - null, // Name - null, // ShortName - data.StreetNumber, // Number - null, // Direction - "STREET") // Type - }, - Enumerable.Empty(), - Enumerable.Empty(), - null, // GeographicCoordinates - Enumerable.Empty() // Types - ) + Enumerable.Empty(), // Name + Enumerable.Empty(), // States + Enumerable.Empty(), // Identifiers + new BpdmAddressPhysicalPostalAddress( // PhysicalPostalAddress + null, // GeographicCoordinates + data.AlphaCode2, // Country + data.ZipCode, // PostalCode + data.City, // City + new BpdmStreet( + null, // NamePrefix + null, // AdditionalNamePrefix + data.StreetName, // Name + null, // NameSuffix + null, // AdditionalNameSuffix + data.StreetNumber, // StreetNumber + null, // Milestone + null // Direction + ), + data.Region, // AdministrativeAreaLevel1 + null, // AdministrativeAreaLevel2 + null, // AdministrativeAreaLevel3 + null, // District + null, // CompanyPostalCode + null, // IndustrialZone + null, // Building + null, // Floor + null // Door + ), + null, // AlternativePostalAddress + Enumerable.Empty() + ) ) }; - await httpClient.PutAsJsonAsync("/api/catena/input/legal-entities", requestData, Options, cancellationToken) + await httpClient.PutAsJsonAsync("/companies/test-company/api/catena/input/legal-entities", requestData, Options, cancellationToken) .CatchingIntoServiceExceptionFor("bpdm-put-legal-entities", HttpAsyncResponseMessageExtension.RecoverOptions.INFRASTRUCTURE).ConfigureAwait(false); return true; } @@ -132,28 +113,19 @@ public async Task FetchInputLegalEntity(string extern var httpClient = await _tokenService.GetAuthorizedClient(_settings, cancellationToken).ConfigureAwait(false); var data = Enumerable.Repeat(externalId, 1); - var result = await httpClient.PostAsJsonAsync("/api/catena/output/legal-entities/search", data, Options, cancellationToken) + var result = await httpClient.PostAsJsonAsync($"/companies/test-company/api/catena/output/legal-entities/search{externalId}", data, Options, cancellationToken) .CatchingIntoServiceExceptionFor("bpdm-search-legal-entities", HttpAsyncResponseMessageExtension.RecoverOptions.INFRASTRUCTURE).ConfigureAwait(false); try { - var paginationResponse = await result.Content - .ReadFromJsonAsync(Options, cancellationToken) + var response = await result.Content + .ReadFromJsonAsync(Options, cancellationToken) .ConfigureAwait(false); - if (paginationResponse?.Content == null || paginationResponse.Errors == null) + if (response?.ExternalId == null) { throw new ServiceException("Access to external system bpdm did not return a valid legal entity response", true); } - paginationResponse.Errors.IfAny(errors => - throw new ServiceException($"The external system bpdm responded with errors {string.Join(";", errors.Select(x => $"ErrorCode: {x.ErrorCode}, ErrorMessage: {x.Message}"))}")); - try - { - return paginationResponse.Content.Single(x => x.ExternalId == externalId); - } - catch (InvalidOperationException) - { - throw new ServiceException("Access to external system bpdm did not return a valid legal entity response", true); - } + return response; } catch (JsonException je) { diff --git a/src/registration/Registration.Service/Bpn/BpnAccess.cs b/src/externalsystems/Bpdm.Library/BpnAccess.cs similarity index 63% rename from src/registration/Registration.Service/Bpn/BpnAccess.cs rename to src/externalsystems/Bpdm.Library/BpnAccess.cs index a5931ecdea..7a21567ea9 100644 --- a/src/registration/Registration.Service/Bpn/BpnAccess.cs +++ b/src/externalsystems/Bpdm.Library/BpnAccess.cs @@ -18,14 +18,15 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ +using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Models; using Org.Eclipse.TractusX.Portal.Backend.Framework.Async; using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; -using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn.Model; using System.Net.Http.Headers; +using System.Net.Http.Json; using System.Runtime.CompilerServices; using System.Text.Json; -namespace Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn; +namespace Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library; public class BpnAccess : IBpnAccess { @@ -58,9 +59,9 @@ public async IAsyncEnumerable FetchBusinessPartner(stri public async Task FetchLegalEntityByBpn(string businessPartnerNumber, string token, CancellationToken cancellationToken) { _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); - var uri = new UriBuilder() + var uri = new UriBuilder { - Path = $"api/catena/legal-entities/{Uri.EscapeDataString(businessPartnerNumber)}", + Path = $"pool/api/catena/legal-entities/{Uri.EscapeDataString(businessPartnerNumber)}", Query = "idType=BPN" }.Uri; var result = await _httpClient.GetAsync(uri.PathAndQuery, cancellationToken).ConfigureAwait(false); @@ -86,43 +87,4 @@ public async Task FetchLegalEntityByBpn(string businessPartn throw new ServiceException($"Access to external system bpdm did not return a valid json response: {je.Message}"); } } - - public async IAsyncEnumerable FetchLegalEntityAddressByBpn(string businessPartnerNumber, string token, [EnumeratorCancellation] CancellationToken cancellationToken) - { - _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); - var uri = new UriBuilder() - { - Path = "api/catena/legal-entities/legal-addresses/search" - }.Uri; - var json = new[] { businessPartnerNumber }; - var result = await _httpClient.PostAsJsonAsync(uri.PathAndQuery, json, cancellationToken).ConfigureAwait(false); - if (result.IsSuccessStatusCode) - { - await using var responseStream = await result.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - - await foreach (var address in JsonSerializer - .DeserializeAsyncEnumerable( - responseStream, - new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }, - cancellationToken: cancellationToken) - .CatchingAsync( - ex => - { - throw new ServiceException($"Access to external system bpdm did not return a valid json response: {ex.Message}"); - }, - cancellationToken) - .ConfigureAwait(false)) - { - if (address?.LegalAddress == null || address.LegalEntity == null) - { - throw new ServiceException("Access to external system bpdm did not return a valid legal entity address response"); - } - yield return address; - } - } - else - { - throw new ServiceException($"Access to external system bpdm failed with Status Code {result.StatusCode}", result.StatusCode); - } - } } diff --git a/src/externalsystems/Bpdm.Library/BpdmServiceCollectionExtension.cs b/src/externalsystems/Bpdm.Library/DependencyInjection/BpdmServiceCollectionExtension.cs similarity index 96% rename from src/externalsystems/Bpdm.Library/BpdmServiceCollectionExtension.cs rename to src/externalsystems/Bpdm.Library/DependencyInjection/BpdmServiceCollectionExtension.cs index 69c2613322..c364267d40 100644 --- a/src/externalsystems/Bpdm.Library/BpdmServiceCollectionExtension.cs +++ b/src/externalsystems/Bpdm.Library/DependencyInjection/BpdmServiceCollectionExtension.cs @@ -25,7 +25,7 @@ using Org.Eclipse.TractusX.Portal.Backend.Framework.HttpClientExtensions; using Org.Eclipse.TractusX.Portal.Backend.Framework.Logging; -namespace Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library; +namespace Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.DependencyInjection; public static class BpdmServiceCollectionExtension { diff --git a/src/registration/Registration.Service/Bpn/BpnAccessCollectionExtension.cs b/src/externalsystems/Bpdm.Library/DependencyInjection/BpnAccessCollectionExtension.cs similarity index 92% rename from src/registration/Registration.Service/Bpn/BpnAccessCollectionExtension.cs rename to src/externalsystems/Bpdm.Library/DependencyInjection/BpnAccessCollectionExtension.cs index 17d624f028..b474de05db 100644 --- a/src/registration/Registration.Service/Bpn/BpnAccessCollectionExtension.cs +++ b/src/externalsystems/Bpdm.Library/DependencyInjection/BpnAccessCollectionExtension.cs @@ -18,9 +18,10 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ +using Microsoft.Extensions.DependencyInjection; using Org.Eclipse.TractusX.Portal.Backend.Framework.Logging; -namespace Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn; +namespace Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.DependencyInjection; public static class BpnAccessCollectionExtension { diff --git a/src/registration/Registration.Service/Bpn/IBpnAccess.cs b/src/externalsystems/Bpdm.Library/IBpnAccess.cs similarity index 80% rename from src/registration/Registration.Service/Bpn/IBpnAccess.cs rename to src/externalsystems/Bpdm.Library/IBpnAccess.cs index 13a73b0e27..8aca010840 100644 --- a/src/registration/Registration.Service/Bpn/IBpnAccess.cs +++ b/src/externalsystems/Bpdm.Library/IBpnAccess.cs @@ -18,13 +18,12 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ -using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn.Model; +using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Models; -namespace Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn; +namespace Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library; public interface IBpnAccess { IAsyncEnumerable FetchBusinessPartner(string bpn, string token, CancellationToken cancellationToken); Task FetchLegalEntityByBpn(string businessPartnerNumber, string token, CancellationToken cancellationToken); - IAsyncEnumerable FetchLegalEntityAddressByBpn(string businessPartnerNumber, string token, CancellationToken cancellationToken); } diff --git a/src/registration/Registration.Service/Bpn/Model/BpdmAddressDto.cs b/src/externalsystems/Bpdm.Library/Models/BpdmAddressDto.cs similarity index 90% rename from src/registration/Registration.Service/Bpn/Model/BpdmAddressDto.cs rename to src/externalsystems/Bpdm.Library/Models/BpdmAddressDto.cs index 9c83532f23..b01e966a0d 100644 --- a/src/registration/Registration.Service/Bpn/Model/BpdmAddressDto.cs +++ b/src/externalsystems/Bpdm.Library/Models/BpdmAddressDto.cs @@ -18,7 +18,7 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ -namespace Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn.Model; +namespace Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Models; public record BpdmLegalEntityAddressDto( string LegalEntity, @@ -37,7 +37,7 @@ public record BpdmLegalAddressDto( IEnumerable Premises, IEnumerable PostalDeliveryPoints, BpdmGeographicCoordinatesDto GeographicCoordinates, - IEnumerable Types + IEnumerable Types ); public record BpdmAddressVersionDto( @@ -49,19 +49,19 @@ public record BpdmAdministrativeAreaDto( string Value, string ShortName, string FipsCode, - BpdmUrlDataDto Type, + BpdmTechnicalKey Type, BpdmDataDto Language ); public record BpdmPostCodeDto( string Value, - BpdmUrlDataDto Type + BpdmTechnicalKey Type ); public record BpdmLocalityDto( string Value, string ShortName, - BpdmUrlDataDto Type, + BpdmTechnicalKey Type, BpdmDataDto Language ); @@ -71,7 +71,7 @@ public record BpdmThoroughfareDto( string ShortName, string Number, string Direction, - BpdmUrlDataDto Type, + BpdmTechnicalKey Type, BpdmDataDto Language ); @@ -79,7 +79,7 @@ public record BpdmPremiseDto( string Value, string ShortName, string Number, - BpdmUrlDataDto Type, + BpdmTechnicalKey Type, BpdmDataDto Language ); @@ -87,7 +87,7 @@ public record BpdmPostalDeliveryPointDto( string Value, string ShortName, string Number, - BpdmUrlDataDto Type, + BpdmTechnicalKey Type, BpdmDataDto Language ); diff --git a/src/externalsystems/Bpdm.Library/Models/BpdmLegalEntityData.cs b/src/externalsystems/Bpdm.Library/Models/BpdmLegalEntityData.cs index 5ebe5c69cb..28274d2a15 100644 --- a/src/externalsystems/Bpdm.Library/Models/BpdmLegalEntityData.cs +++ b/src/externalsystems/Bpdm.Library/Models/BpdmLegalEntityData.cs @@ -24,186 +24,80 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Models; public record BpdmLegalEntityData( string ExternalId, - string? Bpn, - IEnumerable Identifiers, - IEnumerable Names, + IEnumerable LegalNameParts, + string? LegalShortName, string? LegalForm, - BpdmStatus? Status, - IEnumerable ProfileClassifications, - IEnumerable Types, - IEnumerable? BankAccounts, + IEnumerable Identifiers, + IEnumerable States, + IEnumerable Classifications, + IEnumerable Roles, BpdmLegalAddress LegalAddress ); public record BpdmIdentifier( string Value, BpdmIdentifierId Type, - string? IssuingBody, - string? Status -); - -public record BpdmName( - string Value, - string? ShortName, - string Type, - string Language -); - -public record BpdmLegalForm -( - string TechnicalKey, - string Name, - string Url, - string MainAbbreviation, - BpdmLanguage Language, - IEnumerable Categories -); - -public record BpdmLanguage -( - string TechnicalKey, - string Name -); - -public record BpdmCategory -( - string Name, - string Url + string? IssuingBody ); public record BpdmStatus( string OfficialDenotation, DateTimeOffset ValidFrom, DateTimeOffset ValidUntil, - BpdmType Type + string Type ); public record BpdmProfileClassification( string Value, string Code, - BpdmProfileClassificationType Type -); - -public record BpdmProfileClassificationType -( - string Name, - string Url -); - -public record BpdmType -( - string TechnicalKey, - string Name, - string Url -); - -public record BpdmBankAccount( - IEnumerable TrustScores, - BpdmCurrency Currency, - string InternationalBankAccountIdentifier, - string InternationalBankIdentifier, - string NationalBankAccountIdentifier, - string NationalBankIdentifier -); - -public record BpdmCurrency -( - string TechnicalKey, - string Name -); - -public record BpdmRoles -( - string TechnicalKey, - string Name -); - -public record BpdmReations -( - BpdmRelationClass RelationClass, - BpdmRelationType Type, - string StartNode, - string EndNode, - DateTimeOffset StartedAt, - DateTimeOffset EndedAt -); - -public record BpdmRelationClass -( - string TechnicalKey, - string Name -); - -public record BpdmRelationType -( - string TechnicalKey, - string Name -); - -public record BpdmLegalAddress( - BpdmAddressVersion Version, - string? CareOf, - IEnumerable Contexts, - string Country, - IEnumerable AdministrativeAreas, - IEnumerable PostCodes, - IEnumerable Localities, - IEnumerable Thoroughfares, - IEnumerable Premises, - IEnumerable PostalDeliveryPoints, - BpdmGeographicCoordinates? GeographicCoordinates, - IEnumerable Types -); - -public record BpdmAddressVersion( - string CharacterSet, - string Language -); - -public record BpdmAdministrativeArea( - string Value, - string? ShortName, - string? FipsCode, string Type ); -public record BpdmPostcode( - string Value, - string Type -); - -public record BpdmLocality( - string Value, - string? ShortName, - string Type -); - -public record BpdmThoroughfare( - string Value, - string? Name, - string? ShortName, - string? Number, - string? Direction, - string Type -); - -public record BpdmPremise( - string Value, - string? ShortName, - string? Number, +public record BpdmLegalAddress( + IEnumerable NameParts, + IEnumerable States, + IEnumerable Identifiers, + BpdmAddressPhysicalPostalAddress PhysicalPostalAddress, + BpdmAddressAlternativePostalAddress? AlternativePostalAddress, + IEnumerable Roles +); + +public record BpdmAddressState( + string Description, + DateTimeOffset? ValidFrom, + DateTimeOffset? ValidTo, string Type ); -public record BpdmPostalDeliveryPoint( +public record BpdmAddressIdentifier( string Value, - string? ShortName, - string? Number, - string Type + BpdmIdentifierId Type +); + +public record BpdmAddressPhysicalPostalAddress( + BpdmGeographicCoordinatesDto? GeographicCoordinates, + string? Country, + string? PostalCode, + string? City, + BpdmStreet? Street, + string? AdministrativeAreaLevel1, + string? AdministrativeAreaLevel2, + string? AdministrativeAreaLevel3, + string? District, + string? CompanyPostalCode, + string? IndustrialZone, + string? Building, + string? Floor, + string? Door +); + +public record BpdmAddressAlternativePostalAddress( + BpdmGeographicCoordinatesDto? GeographicCoordinates, + string? Country, + string? PostalCode, + string? City, + string? AdministrativeAreaLevel1, + string? DeliveryServiceNumber, + string? DeliveryServiceType, + string? DeliveryServiceQualifier ); - -public record BpdmGeographicCoordinates( - int Longitude, - int Latitude, - int Altitude -); - diff --git a/src/externalsystems/Bpdm.Library/Models/BpdmLegalEntityDto.cs b/src/externalsystems/Bpdm.Library/Models/BpdmLegalEntityDto.cs new file mode 100644 index 0000000000..cc337c73c6 --- /dev/null +++ b/src/externalsystems/Bpdm.Library/Models/BpdmLegalEntityDto.cs @@ -0,0 +1,155 @@ +/******************************************************************************** + * Copyright (c) 2021, 2023 Microsoft and BMW Group AG + * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +using System.Text.Json.Serialization; + +namespace Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Models; + +public record BpdmLegalEntityDto( + [property: JsonPropertyName("bpnl")] string Bpn, + [property: JsonPropertyName("legalName")] string? LegalName, + [property: JsonPropertyName("legalShortName")] string? LegalShortName, + [property: JsonPropertyName("currentness")] DateTimeOffset Currentness, + [property: JsonPropertyName("createdAt")] DateTimeOffset CreatedAt, + [property: JsonPropertyName("updatedAt")] DateTimeOffset UpdatedAt, + IEnumerable Identifiers, + BpdmLegalFormDto? LegalForm, + IEnumerable Status, + IEnumerable ProfileClassifications, + IEnumerable Relations, + BpdmLegalEntityAddress LegalEntityAddress +); + +public record BpdmIdentifierDto( + string Value, + BpdmTechnicalKey Type, + string IssuingBody +); + +public record BpdmLegalFormDto( + string TechnicalKey, + string Name, + string Abbreviation +); + +public record BpdmStatusDto( + string OfficialDenotation, + DateTimeOffset ValidFrom, + DateTimeOffset ValidUntil, + BpdmTechnicalKey Type +); + +public record BpdmProfileClassificationDto( + string Value, + string Code, + BpdmTechnicalKey Type +); + +public record BpdmDataDto( + string TechnicalKey, + string Name +); + +public record BpdmTechnicalKey( + string TechnicalKey, + string Name +); + +public record BpdmRelationDto( + BpdmTechnicalKey Type, + string StartBpn, + string EndBpn, + DateTimeOffset ValidFrom, + DateTimeOffset ValidTo +); + +public record BpdmLegalEntityAddress +( + string Bpnl, + string Name, + string BpnLegalEntity, + string BpnSite, + DateTimeOffset CreatedAt, + DateTimeOffset UpdatedAt, + bool IsLegalAddress, + bool IsMainAddress, + IEnumerable States, + IEnumerable Identifiers, + BpdmPhysicalPostalAddress? PhysicalPostalAddress, + BpdmAlternativePostalAddress? AlternativePostalAddress +); + +public record BpdmLegalEntityAddressState +( + string Description, + DateTimeOffset ValidFrom, + DateTimeOffset ValidTo, + BpdmTechnicalKey Type +); + +public record BpdmLegalEntityAddressIdentifier +( + string Value, + BpdmTechnicalKey Type +); + +public record BpdmPhysicalPostalAddress( + BpdmGeographicCoordinatesDto? GeographicCoordinates, + BpdmCountry? Country, + string? PostalCode, + string? City, + BpdmStreet? Street, + BpdmAdministrativeAreaLevel? AdministrativeAreaLevel1, + string? AdministrativeAreaLevel2, + string? AdministrativeAreaLevel3, + string? District, + string? CompanyPostalCode, + string? IndustrialZone, + string? Building, + string? Floor, + string? Door +); + +public record BpdmAlternativePostalAddress( + BpdmGeographicCoordinatesDto? GeographicCoordinates, + BpdmCountry? Country, + string? PostalCode, + string? City, + BpdmAdministrativeAreaLevel? AdministrativeAreaLevel1, + string? DeliveryServiceNumber, + string? Type, + string? DeliveryServiceQualifier +); + +public record BpdmAdministrativeAreaLevel( + string? Name, + string? RegionCode +); + +public record BpdmStreet( + string? NamePrefix, + string? AdditionalNamePrefix, + string Name, + string? NameSuffix, + string? AdditionalNameSuffix, + string? HouseNumber, + string? Milestone, + string? Direction +); diff --git a/src/externalsystems/Bpdm.Library/Models/BpdmLegalEntityOutputData.cs b/src/externalsystems/Bpdm.Library/Models/BpdmLegalEntityOutputData.cs index 213ce20ae1..0165103730 100644 --- a/src/externalsystems/Bpdm.Library/Models/BpdmLegalEntityOutputData.cs +++ b/src/externalsystems/Bpdm.Library/Models/BpdmLegalEntityOutputData.cs @@ -21,49 +21,33 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Models; public record PageOutputResponseBpdmLegalEntityData( - IEnumerable? Content, - IEnumerable Errors + IEnumerable? Content ); public record BpdmLegalEntityOutputData( - string ExternalId, + string? ExternalId, string? Bpn, + string? LegalShortName, + string? LegalForm, IEnumerable Identifiers, - IEnumerable Names, - BpdmLegalForm? LegalForm, - BpdmStatus? Status, - IEnumerable ProfileClassifications, - IEnumerable Types, - IEnumerable? BankAccounts, - IEnumerable Roles, - IEnumerable Relations, + IEnumerable States, + IEnumerable Classifications, + IEnumerable LegalNameParts, + IEnumerable Roles, BpdmLegalAddressResponse LegalAddress ); public record BpdmLegalAddressResponse( - BpdmAddressVersionResponse Version, - string? CareOf, - IEnumerable Contexts, - BpdmCountry Country, - IEnumerable AdministrativeAreas, - IEnumerable PostCodes, - IEnumerable Localities, - IEnumerable Thoroughfares, - IEnumerable Premises, - IEnumerable PostalDeliveryPoints, - BpdmGeographicCoordinates? GeographicCoordinates, - IEnumerable Types -); - -public record BpdmAddressVersionResponse( - BpdmCharacterSet CharacterSet, - BpdmLanguage Language -); - -public record BpdmCharacterSet -( - string TechnicalKey, - string Name + string ExternalId, + string LegalEntityExternalId, + string SiteExternalId, + string Bpn, + IEnumerable NameParts, + IEnumerable States, + IEnumerable Identifiers, + BpdmAddressPhysicalPostalAddress PhysicalPostalAddress, + BpdmAddressAlternativePostalAddress AlternativePostalAddress, + IEnumerable Roles ); public record BpdmCountry @@ -71,55 +55,3 @@ public record BpdmCountry string TechnicalKey, string Name ); - -public record BpdmAdministrativeAreaResponse( - string Value, - string? ShortName, - string? FipsCode, - BpdmType Type, - BpdmLanguage Language -); - -public record BpdmPostcodeResponse( - string Value, - BpdmType Type -); - -public record BpdmLocalityResponse( - string Value, - string? ShortName, - BpdmType Type, - BpdmLanguage Language -); - -public record BpdmThoroughfareResponse( - string Value, - string? Name, - string? ShortName, - string? Number, - string? Direction, - BpdmType Type, - BpdmLanguage Language -); - -public record BpdmPremiseResponse( - string Value, - string? ShortName, - string? Number, - BpdmType Type, - BpdmLanguage Language -); - -public record BpdmPostalDeliveryPointResponse( - string Value, - string? ShortName, - string? Number, - BpdmType Type, - BpdmLanguage Language -); - -public record BpdmErrorInfo( - string ErrorCode, - string Message, - string EntityKey -); diff --git a/src/registration/Registration.Service/Bpn/Model/FetchBusinessPartnerDto.cs b/src/externalsystems/Bpdm.Library/Models/FetchBusinessPartnerDto.cs similarity index 99% rename from src/registration/Registration.Service/Bpn/Model/FetchBusinessPartnerDto.cs rename to src/externalsystems/Bpdm.Library/Models/FetchBusinessPartnerDto.cs index bd1545044f..1b3fbcac35 100644 --- a/src/registration/Registration.Service/Bpn/Model/FetchBusinessPartnerDto.cs +++ b/src/externalsystems/Bpdm.Library/Models/FetchBusinessPartnerDto.cs @@ -20,7 +20,7 @@ using System.Text.Json.Serialization; -namespace Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn.Model +namespace Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Models { [Obsolete("delete as soon endpoint GET /api/registration/company/{bpn} is being removed")] public class FetchBusinessPartnerDto diff --git a/src/processes/ApplicationChecklist.Config/ApplicationChecklistExtensions.cs b/src/processes/ApplicationChecklist.Config/ApplicationChecklistExtensions.cs index 49d4af95ef..2c4b16fe70 100644 --- a/src/processes/ApplicationChecklist.Config/ApplicationChecklistExtensions.cs +++ b/src/processes/ApplicationChecklist.Config/ApplicationChecklistExtensions.cs @@ -21,6 +21,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library; +using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.DependencyInjection; using Org.Eclipse.TractusX.Portal.Backend.Clearinghouse.Library; using Org.Eclipse.TractusX.Portal.Backend.Custodian.Library; using Org.Eclipse.TractusX.Portal.Backend.Framework.Token; diff --git a/src/registration/Registration.Service/Bpn/Model/BpdmLegalEntityDto.cs b/src/registration/Registration.Service/Bpn/Model/BpdmLegalEntityDto.cs deleted file mode 100644 index a76dc98e6f..0000000000 --- a/src/registration/Registration.Service/Bpn/Model/BpdmLegalEntityDto.cs +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************** - * Copyright (c) 2021, 2023 Microsoft and BMW Group AG - * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation - * - * See the NOTICE file(s) distributed with this work for additional - * information regarding copyright ownership. - * - * This program and the accompanying materials are made available under the - * terms of the Apache License, Version 2.0 which is available at - * https://www.apache.org/licenses/LICENSE-2.0. - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - * SPDX-License-Identifier: Apache-2.0 - ********************************************************************************/ - -namespace Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn.Model; - -public record BpdmLegalEntityDto( - string Bpn, - IEnumerable Identifiers, - IEnumerable Names, - BpdmLegalFormDto LegalForm, - BpdmStatusDto Status, - IEnumerable ProfileClassifications, - IEnumerable Types, - IEnumerable BankAccounts, - IEnumerable Roles, - IEnumerable Relations, - DateTimeOffset Currentness -); - -public record BpdmIdentifierDto( - string Value, - BpdmUrlDataDto Type, - BpdmUrlDataDto IssuingBody, - BpdmDataDto Status -); - -public record BpdmNameDto( - string Value, - string ShortName, - BpdmUrlDataDto Type, - BpdmDataDto Language -); - -public record BpdmLegalFormDto( - string TechnicalKey, - string Name, - string Url, - string MainAbbreviation, - BpdmDataDto Language, - IEnumerable Categories -); - -public record BpdmStatusDto( - string OfficialDenotation, - DateTimeOffset ValidFrom, - DateTimeOffset ValidUntil, - BpdmUrlDataDto Type -); - -public record BpdmProfileClassificationDto( - string Value, - string Code, - BpdmNameUrlDto Type -); - -public record BpdmDataDto( - string TechnicalKey, - string Name -); - -public record BpdmUrlDataDto( - string TechnicalKey, - string Name, - string Url -); - -public record BpdmNameUrlDto( - string Name, - string Url -); - -public record BpdmBankAccountDto( - IEnumerable TrustScores, - BpdmDataDto Currency, - string InternationalBankAccountIdentifier, - string InternationalBankIdentifier, - string NationalBankAccountIdentifier, - string NationalBankIdentifier -); - -public record BpdmRelationDto( - BpdmDataDto RelationClass, - BpdmDataDto Type, - string StartNode, - string EndNode, - DateTimeOffset StartedAt, - DateTimeOffset EndedAt -); diff --git a/src/registration/Registration.Service/BusinessLogic/IRegistrationBusinessLogic.cs b/src/registration/Registration.Service/BusinessLogic/IRegistrationBusinessLogic.cs index 4899e0a30b..71155b47c9 100644 --- a/src/registration/Registration.Service/BusinessLogic/IRegistrationBusinessLogic.cs +++ b/src/registration/Registration.Service/BusinessLogic/IRegistrationBusinessLogic.cs @@ -18,10 +18,10 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ +using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Models; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Models; -using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn.Model; using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Model; namespace Org.Eclipse.TractusX.Portal.Backend.Registration.Service.BusinessLogic diff --git a/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs b/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs index 8d7f4e0901..1dfb3ef447 100644 --- a/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs +++ b/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs @@ -19,6 +19,8 @@ ********************************************************************************/ using Microsoft.Extensions.Options; +using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library; +using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Models; using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; using Org.Eclipse.TractusX.Portal.Backend.Framework.Models.Configuration; using Org.Eclipse.TractusX.Portal.Backend.Framework.Web; @@ -33,8 +35,6 @@ using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Models; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Service; -using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn; -using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn.Model; using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Model; using System.Text.RegularExpressions; @@ -51,7 +51,7 @@ public class RegistrationBusinessLogic : IRegistrationBusinessLogic private readonly ILogger _logger; private readonly IApplicationChecklistCreationService _checklistService; - private static readonly Regex bpnRegex = new Regex(@"(\w|\d){16}", RegexOptions.None, TimeSpan.FromSeconds(1)); + private static readonly Regex bpnRegex = new(@"(\w|\d){16}", RegexOptions.None, TimeSpan.FromSeconds(1)); public RegistrationBusinessLogic( IOptions settings, @@ -103,27 +103,9 @@ private async Task GetCompanyBpdmDetailDataByBusinessPart { throw new ConflictException("Bpdm did return incorrect bpn legal-entity-data"); } - BpdmLegalEntityAddressDto? legalEntityAddress; - try - { - legalEntityAddress = await _bpnAccess.FetchLegalEntityAddressByBpn(businessPartnerNumber, token, cancellationToken).SingleOrDefaultAsync(cancellationToken).ConfigureAwait(false); - } - catch (InvalidOperationException) - { - throw new ConflictException($"bpdm returned more than a single legalEntityAddress for {businessPartnerNumber}"); - } - if (legalEntityAddress == null) - { - throw new ConflictException($"bpdm returned no legalEntityAddress for {businessPartnerNumber}"); - } - if (!businessPartnerNumber.Equals(legalEntityAddress.LegalEntity, StringComparison.OrdinalIgnoreCase)) - { - throw new ConflictException("Bpdm did return incorrect bpn address-data"); - } - - var legalAddress = legalEntityAddress.LegalAddress; - var country = legalAddress.Country.TechnicalKey; + var country = legalEntity.LegalEntityAddress.PhysicalPostalAddress?.Country?.TechnicalKey ?? + throw new ConflictException("Legal-entity-data did not contain a valid country identifier"); var bpdmIdentifiers = ParseBpdmIdentifierDtos(legalEntity.Identifiers).ToList(); var assignedIdentifiersResult = await _portalRepositories.GetInstance() @@ -140,35 +122,18 @@ private async Task GetCompanyBpdmDetailDataByBusinessPart bpdmIdentifier => bpdmIdentifier.BpdmIdentifierId, (countryIdentifier, bpdmIdentifier) => (countryIdentifier.UniqueIdentifierId, bpdmIdentifier.Value)); - TItem? SingleOrDefaultChecked(IEnumerable items, string itemName) - { - try - { - return items.SingleOrDefault(); - } - catch (InvalidOperationException) - { - throw new ConflictException($"bpdm returned more than a single {itemName} in legal entity for {businessPartnerNumber}"); - } - } - - BpdmNameDto? name = SingleOrDefaultChecked(legalEntity.Names, nameof(name)); - string? administrativeArea = SingleOrDefaultChecked(legalAddress.AdministrativeAreas, nameof(administrativeArea))?.Value; - string? postCode = SingleOrDefaultChecked(legalAddress.PostCodes, nameof(postCode))?.Value; - string? locality = SingleOrDefaultChecked(legalAddress.Localities, nameof(locality))?.Value; - BpdmThoroughfareDto? thoroughfare = SingleOrDefaultChecked(legalAddress.Thoroughfares, nameof(thoroughfare)); - + var physicalPostalAddress = legalEntity.LegalEntityAddress.PhysicalPostalAddress; return new CompanyBpdmDetailData( businessPartnerNumber, country, - name?.Value ?? "", - name?.ShortName ?? "", - locality ?? "", - thoroughfare?.Value ?? "", - administrativeArea, + legalEntity.LegalName ?? "", + legalEntity.LegalShortName ?? "", + physicalPostalAddress?.City ?? "", + physicalPostalAddress?.Street?.Name ?? "", + physicalPostalAddress?.AdministrativeAreaLevel1?.RegionCode, null, // TODO clarify how to map from bpdm data - thoroughfare?.Number, - postCode, + physicalPostalAddress?.Street?.HouseNumber, + physicalPostalAddress?.PostalCode, portalIdentifiers.Select(identifier => new CompanyUniqueIdData(identifier.UniqueIdentifierId, identifier.Value)) ); } diff --git a/src/registration/Registration.Service/Controllers/RegistrationController.cs b/src/registration/Registration.Service/Controllers/RegistrationController.cs index 52411cf5d9..607b672aa5 100644 --- a/src/registration/Registration.Service/Controllers/RegistrationController.cs +++ b/src/registration/Registration.Service/Controllers/RegistrationController.cs @@ -20,13 +20,13 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Models; using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling.Library; using Org.Eclipse.TractusX.Portal.Backend.Framework.Models; using Org.Eclipse.TractusX.Portal.Backend.Keycloak.Authentication; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Models; -using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn.Model; using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.BusinessLogic; using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Model; using System.Net; diff --git a/src/registration/Registration.Service/Program.cs b/src/registration/Registration.Service/Program.cs index c1e1b99094..15b4d0a951 100644 --- a/src/registration/Registration.Service/Program.cs +++ b/src/registration/Registration.Service/Program.cs @@ -18,13 +18,14 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ +using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library; +using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.DependencyInjection; using Org.Eclipse.TractusX.Portal.Backend.Framework.Web; using Org.Eclipse.TractusX.Portal.Backend.Mailing.SendMail; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess; using Org.Eclipse.TractusX.Portal.Backend.Processes.ApplicationChecklist.Config.DependencyInjection; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Service; -using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn; using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.BusinessLogic; var VERSION = "v2"; diff --git a/tests/externalsystems/Bpdm.Library/BPNAccessTest.cs b/tests/externalsystems/Bpdm.Library/BPNAccessTest.cs new file mode 100644 index 0000000000..e4eb83e037 --- /dev/null +++ b/tests/externalsystems/Bpdm.Library/BPNAccessTest.cs @@ -0,0 +1,234 @@ +/******************************************************************************** + * Copyright (c) 2021, 2023 Microsoft and BMW Group AG + * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Models; +using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; +using System.Net; +using System.Text.Json; + +namespace Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Tests; + +public class BPNAccessTest +{ + private readonly IFixture _fixture; + + public BPNAccessTest() + { + _fixture = new Fixture().Customize(new AutoFakeItEasyCustomization { ConfigureMembers = true }); + } + + private void ConfigureHttpClientFactoryFixture(HttpResponseMessage httpResponseMessage, Action? setMessage = null) + { + var messageHandler = A.Fake(); + A.CallTo(messageHandler) // mock protected method + .Where(x => x.Method.Name == "SendAsync") + .WithReturnType>() + .ReturnsLazily(call => + { + var message = call.Arguments.Get(0); + setMessage?.Invoke(message); + return Task.FromResult(httpResponseMessage); + }); + var httpClient = new HttpClient(messageHandler) { BaseAddress = new Uri("http://localhost") }; + _fixture.Inject(httpClient); + + var httpClientFactory = _fixture.Freeze>(); + A.CallTo(() => httpClientFactory.FakedObject.CreateClient("bpn")).Returns(httpClient); + } + + [Fact] + public async Task FetchBusinessPartner_Success() + { + var resultSet = _fixture.Create(); + ConfigureHttpClientFactoryFixture(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(JsonSerializer.Serialize(resultSet)) + }); + + var httpClient = _fixture.Create(); + var sut = _fixture.Create(); + + var result = await sut.FetchBusinessPartner("testpbn", "token", CancellationToken.None).ToListAsync().ConfigureAwait(false); + Assert.Equal(resultSet.Bpn, result.First().Bpn); + Assert.Equal("token", httpClient.DefaultRequestHeaders.Authorization?.Parameter); + } + + [Fact] + public async Task FetchBusinessPartner_Failure() + { + ConfigureHttpClientFactoryFixture(new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError }); + + var httpClient = _fixture.Create(); + var sut = _fixture.Create(); + + async Task Act() => await sut.FetchBusinessPartner("testpbn", "token", CancellationToken.None).ToListAsync().ConfigureAwait(false); + + await Assert.ThrowsAsync(Act); + Assert.Equal("token", httpClient.DefaultRequestHeaders.Authorization?.Parameter); + } + + #region FetchLegalEntityByBpns + + [Fact] + public async Task FetchLegalEntityByBpn_Success_ReturnsExpected() + { + //Arrange + HttpRequestMessage? request = null; + + const string json = "{ \"legalName\": \"string\", \"bpnl\": \"string\", \"identifiers\": [ { \"value\": \"string\", \"type\": { \"technicalKey\": \"string\", \"name\": \"string\" }, \"issuingBody\": \"string\" } ], \"legalShortName\": \"string\", \"legalForm\": { \"technicalKey\": \"string\", \"name\": \"string\", \"abbreviation\": \"string\" }, \"states\": [ { \"officialDenotation\": \"string\", \"validFrom\": \"2023-07-24T11:23:20.887Z\", \"validTo\": \"2023-07-24T11:23:20.887Z\", \"type\": { \"technicalKey\": \"ACTIVE\", \"name\": \"string\" } } ], \"classifications\": [ { \"value\": \"string\", \"code\": \"string\", \"type\": { \"technicalKey\": \"NACE\", \"name\": \"string\" } } ], \"relations\": [ { \"type\": { \"technicalKey\": \"CX_LEGAL_SUCCESSOR_OF\", \"name\": \"string\" }, \"startBpn\": \"string\", \"endBpn\": \"string\", \"validFrom\": \"2023-07-24T11:23:20.887Z\", \"validTo\": \"2023-07-24T11:23:20.887Z\" } ], \"currentness\": \"2023-07-24T11:23:20.887Z\", \"createdAt\": \"2023-07-24T11:23:20.887Z\", \"updatedAt\": \"2023-07-24T11:23:20.887Z\", \"legalAddress\": { \"bpna\": \"string\", \"name\": \"string\", \"states\": [ { \"description\": \"string\", \"validFrom\": \"2023-07-24T11:23:20.887Z\", \"validTo\": \"2023-07-24T11:23:20.887Z\", \"type\": { \"technicalKey\": \"ACTIVE\", \"name\": \"string\" } } ], \"identifiers\": [ { \"value\": \"string\", \"type\": { \"technicalKey\": \"string\", \"name\": \"string\" } } ], \"physicalPostalAddress\": { \"geographicCoordinates\": { \"longitude\": 0, \"latitude\": 0, \"altitude\": 0 }, \"country\": { \"technicalKey\": \"UNDEFINED\", \"name\": \"string\" }, \"postalCode\": \"string\", \"city\": \"string\", \"street\": { \"name\": \"string\", \"houseNumber\": \"string\", \"milestone\": \"string\", \"direction\": \"string\" }, \"administrativeAreaLevel1\": { \"name\": \"string\", \"regionCode\": \"string\" }, \"administrativeAreaLevel2\": \"string\", \"administrativeAreaLevel3\": \"string\", \"district\": \"string\", \"companyPostalCode\": \"string\", \"industrialZone\": \"string\", \"building\": \"string\", \"floor\": \"string\", \"door\": \"string\" }, \"alternativePostalAddress\": { \"geographicCoordinates\": { \"longitude\": 0, \"latitude\": 0, \"altitude\": 0 }, \"country\": { \"technicalKey\": \"UNDEFINED\", \"name\": \"string\" }, \"postalCode\": \"string\", \"city\": \"string\", \"administrativeAreaLevel1\": { \"name\": \"string\", \"regionCode\": \"string\" }, \"deliveryServiceNumber\": \"string\", \"type\": \"PO_BOX\", \"deliveryServiceQualifier\": \"string\" }, \"bpnLegalEntity\": \"string\", \"bpnSite\": \"string\", \"createdAt\": \"2023-07-24T11:23:20.887Z\", \"updatedAt\": \"2023-07-24T11:23:20.887Z\", \"isLegalAddress\": true, \"isMainAddress\": true }}"; + + ConfigureHttpClientFactoryFixture(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(json) + }, requestMessage => request = requestMessage); + + var businessPartnerNumber = _fixture.Create(); + var sut = _fixture.Create(); + + //Act + var result = await sut.FetchLegalEntityByBpn(businessPartnerNumber, _fixture.Create(), CancellationToken.None); + + //Assert + request.Should().NotBeNull(); + request!.RequestUri.Should().NotBeNull(); + request.RequestUri.Should().NotBeNull(); + request.RequestUri!.LocalPath.Should().Be($"/pool/api/catena/legal-entities/{businessPartnerNumber}"); + request.RequestUri.Query.Should().Be("?idType=BPN"); + + result.Should().NotBeNull(); + result.Currentness.Should().BeExactly(DateTimeOffset.Parse("2023-07-24T11:23:20.887Z")); + } + + [Fact] + public async Task FetchLegalEntityByBpn_InvalidJsonResponse_Throws() + { + //Arrange + var json = _fixture.Create(); + ConfigureHttpClientFactoryFixture(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(json) + }); + + var sut = _fixture.Create(); + + var Act = () => sut.FetchLegalEntityByBpn(_fixture.Create(), _fixture.Create(), CancellationToken.None); + + //Act + var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); + + //Assert + result.Should().NotBeNull(); + result.Message.Should().StartWith("Access to external system bpdm did not return a valid json response"); + } + + [Fact] + public async Task FetchLegalEntityByBpn_EmptyResponse_Throws() + { + //Arrange + const string json = ""; + ConfigureHttpClientFactoryFixture(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(json) + }); + + var sut = _fixture.Create(); + + var Act = () => sut.FetchLegalEntityByBpn(_fixture.Create(), _fixture.Create(), CancellationToken.None); + + //Act + var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); + + //Assert + result.Should().NotBeNull(); + result.Message.Should().StartWith("Access to external system bpdm did not return a valid json response"); + } + + [Fact] + public async Task FetchLegalEntityByBpn_NoContentResponse_Throws() + { + //Arrange + ConfigureHttpClientFactoryFixture(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + }); + + var sut = _fixture.Create(); + + var Act = () => sut.FetchLegalEntityByBpn(_fixture.Create(), _fixture.Create(), CancellationToken.None); + + //Act + var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); + + //Assert + result.Should().NotBeNull(); + result.Message.Should().StartWith("Access to external system bpdm did not return a valid json response"); + } + + [Fact] + public async Task FetchLegalEntityByBpn_InvalidJsonType_Throws() + { + //Arrange + const string json = "{\"some\": [{\"other\": \"json\"}]}"; + ConfigureHttpClientFactoryFixture(new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(json) + }); + + var sut = _fixture.Create(); + + var Act = () => sut.FetchLegalEntityByBpn(_fixture.Create(), _fixture.Create(), CancellationToken.None); + + //Act + var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); + + //Assert + result.Should().NotBeNull(); + result.Message.Should().StartWith("Access to external system bpdm did not return a valid legal entity response"); + } + + [Fact] + public async Task FetchLegalEntityByBpn_UnsuccessfulCall_Throws() + { + //Arrange + var json = _fixture.Create(); + ConfigureHttpClientFactoryFixture(new HttpResponseMessage + { + StatusCode = HttpStatusCode.BadRequest, + Content = new StringContent(json) + }); + + var sut = _fixture.Create(); + + var Act = () => sut.FetchLegalEntityByBpn(_fixture.Create(), _fixture.Create(), CancellationToken.None); + + //Act + var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); + + //Assert + result.Message.Should().Be($"Access to external system bpdm failed with Status Code {HttpStatusCode.BadRequest}"); + } + + #endregion +} diff --git a/tests/externalsystems/Bpdm.Library/BpdmServiceTests.cs b/tests/externalsystems/Bpdm.Library/BpdmServiceTests.cs index 2ebd12ad88..d33ce6d602 100644 --- a/tests/externalsystems/Bpdm.Library/BpdmServiceTests.cs +++ b/tests/externalsystems/Bpdm.Library/BpdmServiceTests.cs @@ -117,9 +117,8 @@ public async Task FetchInputLegalEntity_WithValidResult_ReturnsExpected() .With(x => x.ExternalId, externalId) .With(x => x.Bpn, "TESTBPN") .Create(); - var pageOutputData = new PageOutputResponseBpdmLegalEntityData( - Enumerable.Repeat(data, 1), - Enumerable.Empty()); + // var pageOutputData = new PageOutputResponseBpdmLegalEntityData( + // Enumerable.Repeat(data, 1)); var options = new System.Text.Json.JsonSerializerOptions { PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase, @@ -128,7 +127,7 @@ public async Task FetchInputLegalEntity_WithValidResult_ReturnsExpected() // Arrange var httpMessageHandlerMock = new HttpMessageHandlerMock( HttpStatusCode.OK, - pageOutputData.ToJsonContent( + data.ToJsonContent( options, "application/json") ); @@ -196,39 +195,6 @@ public async Task FetchInputLegalEntity_WithEmtpyResult_ThrowsServiceException() ex.IsRecoverable.Should().BeFalse(); } - [Fact] - public async Task FetchInputLegalEntity_WithError_ThrowsServiceException() - { - // Arrange - var error = new BpdmErrorInfo("SharingProcessError", "This is a test", "test"); - var pageOutputData = new PageOutputResponseBpdmLegalEntityData( - Enumerable.Empty(), - Enumerable.Repeat(error, 1)); - var options = new System.Text.Json.JsonSerializerOptions - { - PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase, - Converters = { new JsonStringEnumConverter(allowIntegerValues: false) } - }; - var httpMessageHandlerMock = new HttpMessageHandlerMock( - HttpStatusCode.OK, - pageOutputData.ToJsonContent(options, "application/json")); - - var httpClient = new HttpClient(httpMessageHandlerMock) - { - BaseAddress = new Uri("https://base.address.com") - }; - A.CallTo(() => _tokenService.GetAuthorizedClient(_options.Value, A._)).Returns(httpClient); - var sut = new BpdmService(_tokenService, _options); - - // Act - async Task Act() => await sut.FetchInputLegalEntity(_fixture.Create(), CancellationToken.None).ConfigureAwait(false); - - // Assert - var ex = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - ex.Message.Should().StartWith("The external system bpdm responded with errors ErrorCode: SharingProcessError, ErrorMessage: This is a test"); - ex.IsRecoverable.Should().BeFalse(); - } - [Fact] public async Task FetchInputLegalEntity_WithNotFoundResult_ReturnsNull() { diff --git a/tests/registration/Registration.Service.Tests/BPNAccessTest.cs b/tests/registration/Registration.Service.Tests/BPNAccessTest.cs deleted file mode 100644 index 1dd063b043..0000000000 --- a/tests/registration/Registration.Service.Tests/BPNAccessTest.cs +++ /dev/null @@ -1,376 +0,0 @@ -/******************************************************************************** - * Copyright (c) 2021, 2023 Microsoft and BMW Group AG - * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation - * - * See the NOTICE file(s) distributed with this work for additional - * information regarding copyright ownership. - * - * This program and the accompanying materials are made available under the - * terms of the Apache License, Version 2.0 which is available at - * https://www.apache.org/licenses/LICENSE-2.0. - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - * SPDX-License-Identifier: Apache-2.0 - ********************************************************************************/ - -using AutoFixture; -using AutoFixture.AutoFakeItEasy; -using FakeItEasy; -using FluentAssertions; -using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; -using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn; -using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn.Model; -using System.Net; -using System.Text.Json; -using Xunit; - -namespace Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Tests; - -public class BPNAccessTest -{ - private readonly IFixture _fixture; - - public BPNAccessTest() - { - _fixture = new Fixture().Customize(new AutoFakeItEasyCustomization { ConfigureMembers = true }); - } - - private void ConfigureHttpClientFactoryFixture(HttpResponseMessage httpResponseMessage, Action? setMessage = null) - { - var messageHandler = A.Fake(); - A.CallTo(messageHandler) // mock protected method - .Where(x => x.Method.Name == "SendAsync") - .WithReturnType>() - .ReturnsLazily(call => - { - var message = call.Arguments.Get(0); - setMessage?.Invoke(message); - return Task.FromResult(httpResponseMessage); - }); - var httpClient = new HttpClient(messageHandler) { BaseAddress = new Uri("http://localhost") }; - _fixture.Inject(httpClient); - - var httpClientFactory = _fixture.Freeze>(); - A.CallTo(() => httpClientFactory.FakedObject.CreateClient("bpn")).Returns(httpClient); - } - - [Fact] - public async Task FetchBusinessPartner_Success() - { - var resultSet = _fixture.Create(); - ConfigureHttpClientFactoryFixture(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK, - Content = new StringContent(JsonSerializer.Serialize(resultSet)) - }); - - var httpClient = _fixture.Create(); - var sut = _fixture.Create(); - - var result = await sut.FetchBusinessPartner("testpbn", "token", CancellationToken.None).ToListAsync().ConfigureAwait(false); - Assert.Equal(resultSet.Bpn, result.First().Bpn); - Assert.Equal("token", httpClient.DefaultRequestHeaders.Authorization?.Parameter); - } - - [Fact] - public async Task FetchBusinessPartner_Failure() - { - ConfigureHttpClientFactoryFixture(new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError }); - - var httpClient = _fixture.Create(); - var sut = _fixture.Create(); - - async Task Act() => await sut.FetchBusinessPartner("testpbn", "token", CancellationToken.None).ToListAsync().ConfigureAwait(false); - - await Assert.ThrowsAsync(Act); - Assert.Equal("token", httpClient.DefaultRequestHeaders.Authorization?.Parameter); - } - - #region FetchLegalEntityByBpns - - [Fact] - public async Task FetchLegalEntityByBpn_Success_ReturnsExpected() - { - //Arrange - HttpRequestMessage? request = null; - - var json = "{\"bankAccounts\": [{\"currency\": {\"name\": \"string\", \"technicalKey\": \"UNDEFINED\"}, \"internationalBankAccountIdentifier\": \"string\", \"internationalBankIdentifier\": \"string\", \"nationalBankAccountIdentifier\": \"string\", \"nationalBankIdentifier\": \"string\", \"trustScores\": [0]}], \"bpn\": \"string\", \"currentness\": \"2023-01-18T12:52:41.710Z\", \"identifiers\": [{\"issuingBody\": {\"name\": \"string\", \"technicalKey\": \"string\", \"url\": \"string\"}, \"status\": {\"name\": \"string\", \"technicalKey\": \"string\"}, \"type\": {\"name\": \"string\", \"technicalKey\": \"string\", \"url\": \"string\"}, \"value\": \"string\"}], \"legalForm\": {\"categories\": [{\"name\": \"string\", \"url\": \"string\"}], \"language\": {\"name\": \"string\", \"technicalKey\": \"undefined\"}, \"mainAbbreviation\": \"string\", \"name\": \"string\", \"technicalKey\": \"string\", \"url\": \"string\"}, \"names\": [{\"language\": {\"name\": \"string\", \"technicalKey\": \"undefined\"}, \"shortName\": \"string\", \"type\": {\"name\": \"string\", \"technicalKey\": \"ACRONYM\", \"url\": \"string\"}, \"value\": \"string\"}], \"profileClassifications\": [{\"code\": \"string\", \"type\": {\"name\": \"string\", \"url\": \"string\"}, \"value\": \"string\"}], \"relations\": [{\"endedAt\": \"2023-01-18T12:52:41.710Z\", \"endNode\": \"string\", \"relationClass\": {\"name\": \"string\", \"technicalKey\": \"CDQ_HIERARCHY\"}, \"startedAt\": \"2023-01-18T12:52:41.710Z\", \"startNode\": \"string\", \"type\": {\"name\": \"string\", \"technicalKey\": \"CX_LEGAL_SUCCESSOR_OF\"}}], \"roles\": [{\"name\": \"string\", \"technicalKey\": \"string\"}], \"status\": {\"officialDenotation\": \"string\", \"type\": {\"name\": \"string\", \"technicalKey\": \"ACTIVE\", \"url\": \"string\"}, \"validFrom\": \"2023-01-18T12:52:41.709Z\", \"validUntil\": \"2023-01-18T12:52:41.709Z\"}, \"types\": [{\"name\": \"string\", \"technicalKey\": \"BRAND\", \"url\": \"string\"}]}"; - - ConfigureHttpClientFactoryFixture(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK, - Content = new StringContent(json) - }, requestMessage => request = requestMessage); - - var businessPartnerNumber = _fixture.Create(); - var httpClient = _fixture.Create(); - var sut = _fixture.Create(); - - //Act - var result = await sut.FetchLegalEntityByBpn(businessPartnerNumber, _fixture.Create(), CancellationToken.None); - - //Assert - request.Should().NotBeNull(); - request!.RequestUri.Should().NotBeNull(); - request.RequestUri.Should().NotBeNull(); - request.RequestUri!.LocalPath.Should().Be($"/api/catena/legal-entities/{businessPartnerNumber}"); - request.RequestUri.Query.Should().Be("?idType=BPN"); - - result.Should().NotBeNull(); - result.Currentness.Should().BeExactly(DateTimeOffset.Parse("2023-01-18T12:52:41.710Z")); - result.BankAccounts.Should().NotBeNull(); - result.BankAccounts.Should().HaveCount(1); - var account = result.BankAccounts.First(); - account.Currency.Should().NotBeNull(); - account.Currency.TechnicalKey.Should().Be("UNDEFINED"); - } - - [Fact] - public async Task FetchLegalEntityByBpn_InvalidJsonResponse_Throws() - { - //Arrange - var json = _fixture.Create(); - ConfigureHttpClientFactoryFixture(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK, - Content = new StringContent(json) - }); - - var httpClient = _fixture.Create(); - var sut = _fixture.Create(); - - var Act = () => sut.FetchLegalEntityByBpn(_fixture.Create(), _fixture.Create(), CancellationToken.None); - - //Act - var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - - //Assert - result.Should().NotBeNull(); - result.Message.Should().StartWith("Access to external system bpdm did not return a valid json response"); - } - - [Fact] - public async Task FetchLegalEntityByBpn_EmptyResponse_Throws() - { - //Arrange - var json = ""; - ConfigureHttpClientFactoryFixture(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK, - Content = new StringContent(json) - }); - - var httpClient = _fixture.Create(); - var sut = _fixture.Create(); - - var Act = () => sut.FetchLegalEntityByBpn(_fixture.Create(), _fixture.Create(), CancellationToken.None); - - //Act - var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - - //Assert - result.Should().NotBeNull(); - result.Message.Should().StartWith("Access to external system bpdm did not return a valid json response"); - } - - [Fact] - public async Task FetchLegalEntityByBpn_NoContentResponse_Throws() - { - //Arrange - ConfigureHttpClientFactoryFixture(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK, - }); - - var httpClient = _fixture.Create(); - var sut = _fixture.Create(); - - var Act = () => sut.FetchLegalEntityByBpn(_fixture.Create(), _fixture.Create(), CancellationToken.None); - - //Act - var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - - //Assert - result.Should().NotBeNull(); - result.Message.Should().StartWith("Access to external system bpdm did not return a valid json response"); - } - - [Fact] - public async Task FetchLegalEntityByBpn_InvalidJsonType_Throws() - { - //Arrange - var json = "{\"some\": [{\"other\": \"json\"}]}"; - ConfigureHttpClientFactoryFixture(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK, - Content = new StringContent(json) - }); - - var httpClient = _fixture.Create(); - var sut = _fixture.Create(); - - var Act = () => sut.FetchLegalEntityByBpn(_fixture.Create(), _fixture.Create(), CancellationToken.None); - - //Act - var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - - //Assert - result.Should().NotBeNull(); - result.Message.Should().StartWith("Access to external system bpdm did not return a valid legal entity response"); - } - - [Fact] - public async Task FetchLegalEntityByBpn_UnsuccessfulCall_Throws() - { - //Arrange - var json = _fixture.Create(); - ConfigureHttpClientFactoryFixture(new HttpResponseMessage - { - StatusCode = HttpStatusCode.BadRequest, - Content = new StringContent(json) - }); - - var httpClient = _fixture.Create(); - var sut = _fixture.Create(); - - var Act = () => sut.FetchLegalEntityByBpn(_fixture.Create(), _fixture.Create(), CancellationToken.None); - - //Act - var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - - //Assert - result.Message.Should().Be($"Access to external system bpdm failed with Status Code {HttpStatusCode.BadRequest}"); - } - - #endregion - - #region FetchLegalEntityAddressByBpn - - [Fact] - public async Task FetchLegalEntityAddressByBpn_Success_ReturnsExpected() - { - //Arrange - HttpRequestMessage? request = null; - - var json = "[{\"legalAddress\": {\"administrativeAreas\": [], \"careOf\": null, \"contexts\": [], \"country\": {\"name\": \"Germany\", \"technicalKey\": \"DE\"}, \"geographicCoordinates\": null, \"localities\": [{\"language\": {\"name\": \"English\", \"technicalKey\": \"en\"}, \"shortName\": null, \"type\": {\"name\": \"Other\", \"technicalKey\": \"OTHER\", \"url\": \"\"}, \"value\": \"Bremen\"}], \"postalDeliveryPoints\": [], \"postCodes\": [{\"type\": {\"name\": \"Other type\", \"technicalKey\": \"OTHER\", \"url\": \"\"}, \"value\": \"28777\"}], \"premises\": [], \"thoroughfares\": [{\"direction\": null, \"language\": {\"name\": \"English\", \"technicalKey\": \"en\"}, \"name\": null, \"number\": \"30\", \"shortName\": null, \"type\": {\"name\": \"Other type\", \"technicalKey\": \"OTHER\", \"url\": \"\"}, \"value\": \"Heidlerchenstr.\"}], \"types\": [], \"version\": {\"characterSet\": {\"name\": \"Latin\", \"technicalKey\": \"LATIN\"}, \"language\": {\"name\": \"English\", \"technicalKey\": \"en\"}}}, \"legalEntity\": \"BPNL000000055EPN\"}]"; - - ConfigureHttpClientFactoryFixture(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK, - Content = new StringContent(json) - }, requestMessage => request = requestMessage); - - var businessPartnerNumber = "BPNL000000055EPN"; - var httpClient = _fixture.Create(); - var sut = _fixture.Create(); - - //Act - var result = await sut.FetchLegalEntityAddressByBpn(businessPartnerNumber, _fixture.Create(), CancellationToken.None).ToListAsync().ConfigureAwait(false); - - //Assert - request.Should().NotBeNull(); - request!.RequestUri.Should().NotBeNull(); - request.RequestUri.Should().NotBeNull(); - request.RequestUri!.LocalPath.Should().Be($"/api/catena/legal-entities/legal-addresses/search"); - request.RequestUri.Query.Should().Be(""); - - result.Should().NotBeNull(); - result.Should().HaveCount(1); - var legalEntityAddress = result.First(); - legalEntityAddress.Should().NotBeNull(); - legalEntityAddress.LegalEntity.Should().Be(businessPartnerNumber); - var legalAddress = legalEntityAddress.LegalAddress; - legalAddress.Should().NotBeNull(); - legalAddress.Country.Should().NotBeNull(); - legalAddress.Country.TechnicalKey.Should().Be("DE"); - legalAddress.PostCodes.Should().NotBeNull(); - legalAddress.PostCodes.Should().HaveCount(1); - legalAddress.PostCodes.First().Value.Should().Be("28777"); - legalAddress.Localities.Should().NotBeNull(); - legalAddress.Localities.Should().HaveCount(1); - legalAddress.Localities.First().Value.Should().Be("Bremen"); - legalAddress.Thoroughfares.Should().NotBeNull(); - legalAddress.Thoroughfares.Should().HaveCount(1); - var thoroughfare = legalAddress.Thoroughfares.First(); - thoroughfare.Value.Should().Be("Heidlerchenstr."); - thoroughfare.Number.Should().Be("30"); - } - - [Fact] - public async Task FetchLegalEntityAddressByBpn_InvalidJsonResponse_Throws() - { - //Arrange - var json = _fixture.Create(); - ConfigureHttpClientFactoryFixture(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK, - Content = new StringContent(json) - }); - - var httpClient = _fixture.Create(); - var sut = _fixture.Create(); - - var Act = async () => await sut.FetchLegalEntityAddressByBpn(_fixture.Create(), _fixture.Create(), CancellationToken.None).ToListAsync().ConfigureAwait(false); - - //Act - var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - - //Assert - result.Should().NotBeNull(); - result.Message.Should().StartWith("Access to external system bpdm did not return a valid json response"); - } - - [Fact] - public async Task FetchLegalEntityAddressByBpn_InvalidJsonType_Throws() - { - //Arrange - var json = "[{\"some\": [{\"other\": \"json\"}]}]"; - ConfigureHttpClientFactoryFixture(new HttpResponseMessage - { - StatusCode = HttpStatusCode.OK, - Content = new StringContent(json) - }); - - var httpClient = _fixture.Create(); - var sut = _fixture.Create(); - - var Act = async () => await sut.FetchLegalEntityAddressByBpn(_fixture.Create(), _fixture.Create(), CancellationToken.None).ToListAsync().ConfigureAwait(false); - - //Act - var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - - //Assert - result.Should().NotBeNull(); - result.Message.Should().Be("Access to external system bpdm did not return a valid legal entity address response"); - } - - [Fact] - public async Task FetchLegalEntityAddressByBpn_UnsuccessfulCall_Throws() - { - //Arrange - var json = _fixture.Create(); - ConfigureHttpClientFactoryFixture(new HttpResponseMessage - { - StatusCode = HttpStatusCode.BadRequest, - Content = new StringContent(json) - }); - - var httpClient = _fixture.Create(); - var sut = _fixture.Create(); - - var Act = async () => await sut.FetchLegalEntityAddressByBpn(_fixture.Create(), _fixture.Create(), CancellationToken.None).ToListAsync().ConfigureAwait(false); - - //Act - var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - - //Assert - result.Message.Should().Be($"Access to external system bpdm failed with Status Code {HttpStatusCode.BadRequest}"); - } - - #endregion -} diff --git a/tests/registration/Registration.Service.Tests/BusinessLogic/RegistrationBusinessLogicTest.cs b/tests/registration/Registration.Service.Tests/BusinessLogic/RegistrationBusinessLogicTest.cs index 17a66d9426..1e85d32f4d 100644 --- a/tests/registration/Registration.Service.Tests/BusinessLogic/RegistrationBusinessLogicTest.cs +++ b/tests/registration/Registration.Service.Tests/BusinessLogic/RegistrationBusinessLogicTest.cs @@ -24,6 +24,8 @@ using FluentAssertions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library; +using Org.Eclipse.TractusX.Portal.Backend.Bpdm.Library.Models; using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; using Org.Eclipse.TractusX.Portal.Backend.Framework.Models.Configuration; using Org.Eclipse.TractusX.Portal.Backend.Mailing.SendMail; @@ -36,13 +38,13 @@ using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Models; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Service; -using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Bpn; using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.BusinessLogic; using Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Model; using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared; using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared.Extensions; using System.Collections.Immutable; using Xunit; +using Address = Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Address; namespace Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Tests.BusinessLogic; @@ -232,31 +234,29 @@ public async Task GetCompanyBpdmDetailDataByBusinessPartnerNumber_WithValidBpn_R var bpdmIdentifiers = uniqueIdSeed.Select(x => ((string TechnicalKey, string Value))(x.BpdmIdentifierId.ToString(), x.Value)); var validIdentifiers = uniqueIdSeed.Skip(2).Take(2).Select(x => (x.BpdmIdentifierId, x.UniqueIdentifierId)); - var legalEntity = _fixture.Build() + var bpdmAddress = _fixture.Build() + .With(x => x.BpnLegalEntity, name) + .With(x => x.Bpnl, businessPartnerNumber) + .With(x => x.PhysicalPostalAddress, _fixture.Build() + .With(x => x.Country, _fixture.Build().With(x => x.TechnicalKey, country).Create()) + .With(x => x.AdministrativeAreaLevel1, _fixture.Build().With(x => x.RegionCode, region).Create()) + .With(x => x.PostalCode, zipCode) + .With(x => x.City, city) + .With(x => x.Street, _fixture.Build().With(x => x.Name, streetName).With(x => x.HouseNumber, streetNumber).Create()) + .Create()) + .Create(); + var legalEntity = _fixture.Build() .With(x => x.Bpn, businessPartnerNumber) - .With(x => x.Names, new[] { _fixture.Build() - .With(x => x.Value, name) - .With(x => x.ShortName, shortName) - .Create() }) - .With(x => x.Identifiers, bpdmIdentifiers.Select(identifier => _fixture.Build() - .With(x => x.Type, _fixture.Build().With(x => x.TechnicalKey, identifier.TechnicalKey).Create()) + .With(x => x.LegalName, name) + .With(x => x.LegalShortName, shortName) + .With(x => x.Identifiers, bpdmIdentifiers.Select(identifier => _fixture.Build() + .With(x => x.Type, _fixture.Build().With(x => x.TechnicalKey, identifier.TechnicalKey).Create()) .With(x => x.Value, identifier.Value) .Create())) - .Create(); - var bpdmAddress = _fixture.Build() - .With(x => x.LegalEntity, businessPartnerNumber) - .With(x => x.LegalAddress, _fixture.Build() - .With(x => x.Country, _fixture.Build().With(x => x.TechnicalKey, country).Create()) - .With(x => x.AdministrativeAreas, new[] { _fixture.Build().With(x => x.Value, region).Create() }) - .With(x => x.PostCodes, new[] { _fixture.Build().With(x => x.Value, zipCode).Create() }) - .With(x => x.Localities, new[] { _fixture.Build().With(x => x.Value, city).Create() }) - .With(x => x.Thoroughfares, new[] { _fixture.Build().With(x => x.Value, streetName).With(x => x.Number, streetNumber).Create() }) - .Create()) + .With(x => x.LegalEntityAddress, bpdmAddress) .Create(); A.CallTo(() => bpnAccess.FetchLegalEntityByBpn(businessPartnerNumber, token, A._)) .Returns(legalEntity); - A.CallTo(() => bpnAccess.FetchLegalEntityAddressByBpn(businessPartnerNumber, token, A._)) - .Returns(new[] { bpdmAddress }.ToAsyncEnumerable()); A.CallTo(() => _staticDataRepository.GetCountryAssignedIdentifiers(A>.That.Matches>(ids => ids.SequenceEqual(uniqueIdSeed.Select(seed => seed.BpdmIdentifierId))), country)) .Returns((true, validIdentifiers)); @@ -275,8 +275,6 @@ public async Task GetCompanyBpdmDetailDataByBusinessPartnerNumber_WithValidBpn_R A.CallTo(() => bpnAccess.FetchLegalEntityByBpn(businessPartnerNumber, token, A._)) .MustHaveHappenedOnceExactly(); - A.CallTo(() => bpnAccess.FetchLegalEntityAddressByBpn(businessPartnerNumber, token, A._)) - .MustHaveHappenedOnceExactly(); A.CallTo(() => _staticDataRepository.GetCountryAssignedIdentifiers(A>.That.Matches>(ids => ids.SequenceEqual(uniqueIdSeed.Select(seed => seed.BpdmIdentifierId))), country)) .MustHaveHappenedOnceExactly();