From 7b31315de7e5838d163ff81014acdf19235a0c87 Mon Sep 17 00:00:00 2001 From: Nico Koprowski Date: Sun, 7 Apr 2024 12:51:27 +0800 Subject: [PATCH] feat(Golden Record Process): overhaul Orchestrator business partner model --- .../cleaning/service/CleaningServiceDummy.kt | 178 +- .../service/GenericBusinessPartnerMappings.kt | 112 -- .../src/main/resources/application.yml | 5 - .../service/CleaningServiceApiCallsTest.kt | 325 +++- .../service/CleaningServiceDummyTest.kt | 165 -- .../bpdm/cleaning/testdata/CommonValues.kt | 208 --- .../src/test/resources/application-test.yml | 4 + .../OrchestratorTestDataConfiguration.kt | 16 +- .../BusinessPartnerGenericCommonValues.kt | 591 ++----- .../orchestrator/BusinessPartnerHelpers.kt | 90 + .../BusinessPartnerTestDataFactory.kt | 200 +++ .../gate/service/BusinessPartnerService.kt | 10 - .../gate/service/GoldenRecordTaskService.kt | 12 +- .../bpdm/gate/service/OrchestratorMappings.kt | 375 +++-- bpdm-gate/src/main/resources/application.yml | 10 +- .../gate/util/BusinessPartnerGenericValues.kt | 143 -- .../bpdm/gate/util/MockAndAssertUtils.kt | 10 +- .../src/test/resources/application-test.yml | 8 +- .../orchestrator/api/model/AddressStateDto.kt | 31 - .../api/model/AlternativePostalAddressDto.kt | 38 - .../orchestrator/api/model/BpnReference.kt | 37 - .../orchestrator/api/model/BusinessPartner.kt | 282 ++++ .../model/BusinessPartnerClassificationDto.kt | 33 - .../api/model/BusinessPartnerFullDto.kt | 38 - .../api/model/BusinessPartnerGenericDto.kt | 67 - .../api/model/BusinessPartnerIdentifierDto.kt | 30 - .../api/model/BusinessPartnerStateDto.kt | 32 - .../api/model/ConfidenceCriteriaDto.kt | 32 - .../api/model/LegalEntityClassificationDto.kt | 34 - .../orchestrator/api/model/LegalEntityDto.kt | 51 - .../api/model/LegalEntityIdentifierDto.kt | 30 - .../api/model/LegalEntityStateDto.kt | 31 - .../api/model/LogisticAddressDto.kt | 47 - .../api/model/PhysicalPostalAddressDto.kt | 43 - .../api/model/PostalAddressDto.kt | 31 - .../orchestrator/api/model/SiteDto.kt | 40 - .../orchestrator/api/model/SiteStateDto.kt | 31 - .../orchestrator/api/model/StreetDto.kt | 35 - .../api/model/TaskClientStateDto.kt | 2 +- .../api/model/TaskCreateRequest.kt | 2 +- .../api/model/TaskStepReservationEntryDto.kt | 4 +- .../api/model/TaskStepResultEntryDto.kt | 2 +- .../orchestrator/model/GoldenRecordTask.kt | 4 +- .../service/GoldenRecordTaskService.kt | 13 +- .../service/GoldenRecordTaskStateMachine.kt | 3 +- .../src/main/resources/application.yml | 4 - .../GoldenRecordTaskControllerIT.kt | 85 +- .../service/GoldenRecordTaskStateMachineIT.kt | 22 +- .../service/BusinessPartnerBuildService.kt | 4 + .../pool/service/RequestValidationService.kt | 168 -- .../bpdm/pool/service/TaskEntryBpnMapping.kt | 32 +- .../bpdm/pool/service/TaskStepBuildService.kt | 424 +++-- .../service/TaskStepFetchAndReserveService.kt | 46 +- bpdm-pool/src/main/resources/application.yml | 4 - .../pool/service/BusinessPartnerComparator.kt | 163 +- .../pool/service/BusinessPartnerCreator.kt | 210 --- .../TaskStepFetchAndReserveServiceTest.kt | 1488 ++++------------- 57 files changed, 2047 insertions(+), 4088 deletions(-) delete mode 100644 bpdm-cleaning-service-dummy/src/main/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/GenericBusinessPartnerMappings.kt delete mode 100644 bpdm-cleaning-service-dummy/src/test/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/CleaningServiceDummyTest.kt delete mode 100644 bpdm-cleaning-service-dummy/src/test/kotlin/org/eclipse/tractusx/bpdm/cleaning/testdata/CommonValues.kt create mode 100644 bpdm-cleaning-service-dummy/src/test/resources/application-test.yml rename bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/AddressIdentifierDto.kt => bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/config/OrchestratorTestDataConfiguration.kt (67%) create mode 100644 bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/testdata/orchestrator/BusinessPartnerHelpers.kt create mode 100644 bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/testdata/orchestrator/BusinessPartnerTestDataFactory.kt delete mode 100644 bpdm-gate/src/test/kotlin/org/eclipse/tractusx/bpdm/gate/util/BusinessPartnerGenericValues.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/AddressStateDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/AlternativePostalAddressDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BpnReference.kt create mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartner.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerClassificationDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerFullDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerGenericDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerIdentifierDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerStateDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/ConfidenceCriteriaDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityClassificationDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityIdentifierDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityStateDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LogisticAddressDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/PhysicalPostalAddressDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/PostalAddressDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/SiteDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/SiteStateDto.kt delete mode 100644 bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/StreetDto.kt delete mode 100644 bpdm-pool/src/test/kotlin/org/eclipse/tractusx/bpdm/pool/service/BusinessPartnerCreator.kt diff --git a/bpdm-cleaning-service-dummy/src/main/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/CleaningServiceDummy.kt b/bpdm-cleaning-service-dummy/src/main/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/CleaningServiceDummy.kt index 12647e7f2..1515b1a5c 100644 --- a/bpdm-cleaning-service-dummy/src/main/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/CleaningServiceDummy.kt +++ b/bpdm-cleaning-service-dummy/src/main/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/CleaningServiceDummy.kt @@ -22,11 +22,13 @@ package org.eclipse.tractusx.bpdm.cleaning.service import mu.KotlinLogging import org.eclipse.tractusx.bpdm.cleaning.util.toUUID -import org.eclipse.tractusx.bpdm.common.dto.AddressType import org.eclipse.tractusx.orchestrator.api.client.OrchestrationApiClient import org.eclipse.tractusx.orchestrator.api.model.* +import org.eclipse.tractusx.orchestrator.api.model.BpnReferenceType import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Service +import java.time.Instant +import java.time.temporal.ChronoUnit @Service class CleaningServiceDummy( @@ -36,10 +38,18 @@ class CleaningServiceDummy( private val logger = KotlinLogging.logger { } + val dummyConfidenceCriteria = ConfidenceCriteria( + sharedByOwner = false, + numberOfSharingMembers = 1, + checkedByExternalDataSource = false, + lastConfidenceCheckAt = Instant.now(), + nextConfidenceCheckAt = Instant.now().plus (5, ChronoUnit.DAYS), + confidenceLevel = 0 + ) + @Scheduled(cron = "\${bpdm.cleaningService.pollingCron:-}", zone = "UTC") - fun pollForCleaningTasks() { + fun pollForCleanAndSyncTasks() { processPollingTasks(TaskStep.CleanAndSync) - processPollingTasks(TaskStep.Clean) } @@ -69,113 +79,105 @@ class CleaningServiceDummy( } fun processCleaningTask(reservedTask: TaskStepReservationEntryDto): TaskStepResultEntryDto { - val genericBusinessPartner = reservedTask.businessPartner.generic - - val addressPartner = createAddressRepresentation(genericBusinessPartner) - - val addressType = genericBusinessPartner.address.addressType ?: AddressType.AdditionalAddress - - val legalEntityDto = createLegalEntityRepresentation(addressPartner, addressType, genericBusinessPartner) - - val siteDto = createSiteDtoIfNeeded(genericBusinessPartner, addressPartner) - - val addressDto = shouldCreateAddress(addressType, addressPartner) - - val updatedGenericBusinessPartner = genericBusinessPartner.update(addressType, legalEntityDto, siteDto, addressDto) - - return TaskStepResultEntryDto(reservedTask.taskId, BusinessPartnerFullDto(updatedGenericBusinessPartner, legalEntityDto, siteDto, addressDto)) - } + val businessPartner = reservedTask.businessPartner + + val cleanedBusinessPartner = BusinessPartner( + nameParts = businessPartner.nameParts, + uncategorized = businessPartner.uncategorized, + owningCompany = businessPartner.owningCompany, + legalEntity = cleanLegalEntity(businessPartner), + site = cleanSite(businessPartner), + additionalAddress = cleanAdditionalAddress(businessPartner) + ) - private fun shouldCreateAddress( - addressType: AddressType, - addressPartner: LogisticAddressDto - ): LogisticAddressDto? { - val addressDto = if (addressType == AddressType.AdditionalAddress) { - addressPartner - } else { - null - } - return addressDto + return TaskStepResultEntryDto(reservedTask.taskId, cleanedBusinessPartner) } - fun createSiteDtoIfNeeded(businessPartner: BusinessPartnerGenericDto, addressPartner: LogisticAddressDto): SiteDto? { - if (!shouldCreateSite(businessPartner)) return null - - val siteMainAddress = addressPartner.copy(bpnAReference = generateBpnRequestIdentifier(businessPartner.createSiteMainAddressReferenceValue())) - return createSiteRepresentation(businessPartner, siteMainAddress) + private fun cleanLegalEntity(businessPartner: BusinessPartner): LegalEntity { + val addressToClean = businessPartner.legalEntity.legalAddress.takeIf { it != PostalAddress.empty } + ?: businessPartner.uncategorized.address + ?: businessPartner.site?.siteMainAddress + ?: businessPartner.additionalAddress + ?: PostalAddress.empty + + return with(businessPartner.legalEntity){ + copy( + bpnReference = bpnReference.toRequestIfNotBpn(businessPartner.createLegalEntityReferenceValue()), + legalName = legalName ?: businessPartner.uncategorized.nameParts.joinToString(""), + identifiers = identifiers.takeIf { it.isNotEmpty() } ?: businessPartner.uncategorized.identifiers, + states = states.takeIf { it.isNotEmpty() } ?: businessPartner.uncategorized.states, + confidenceCriteria = dummyConfidenceCriteria, + hasChanged = businessPartner.type == GoldenRecordType.LegalEntity, + legalAddress = cleanAddress(addressToClean, businessPartner.createLegalAddressReferenceValue(), true), + ) + } } - fun createLegalEntityRepresentation( - addressPartner: LogisticAddressDto, - addressType: AddressType, - genericPartner: BusinessPartnerGenericDto - ): LegalEntityDto { - val legalAddressBpnReference = genericPartner.legalEntity.legalEntityBpn?.let { BpnReferenceDto(it, BpnReferenceType.Bpn) } - ?: generateBpnRequestIdentifier(genericPartner.createLegalAddressReferenceValue()) - val legalAddress = addressPartner.copy(bpnAReference = legalAddressBpnReference) + private fun cleanSite(businessPartner: BusinessPartner): Site?{ + return businessPartner.site?.let { site -> - val legalEntityBpnReference = genericPartner.legalEntity.legalEntityBpn?.let { BpnReferenceDto(it, BpnReferenceType.Bpn) } - ?: generateBpnRequestIdentifier(genericPartner.createLegalEntityReferenceValue()) - return genericPartner.toLegalEntityDto(legalEntityBpnReference, legalAddress) + val addressToClean = if(site.siteMainIsLegalAddress){ + null + }else { + site.siteMainAddress?.takeIf { it != PostalAddress.empty } + ?: businessPartner.uncategorized.address + ?: businessPartner.additionalAddress + ?: PostalAddress.empty + } + with(site){ + copy( + bpnReference = bpnReference.toRequestIfNotBpn(businessPartner.createSiteReferenceValue()), + confidenceCriteria = dummyConfidenceCriteria, + hasChanged = businessPartner.type == GoldenRecordType.Site, + siteMainAddress = addressToClean?.let { cleanAddress(addressToClean, businessPartner.createSiteMainAddressReferenceValue(), true) } + ) + } + } } - fun createAddressRepresentation(genericPartner: BusinessPartnerGenericDto): LogisticAddressDto { - val bpnReferenceDto = genericPartner.address.addressBpn?.let { BpnReferenceDto(it, BpnReferenceType.Bpn) } - ?: generateBpnRequestIdentifier(genericPartner.createAdditionalAddressReferenceValue()) - return genericPartner.toLogisticAddressDto(bpnReferenceDto) + private fun cleanAdditionalAddress(businessPartner: BusinessPartner): PostalAddress? { + return businessPartner.additionalAddress?.let { + cleanAddress( + it, + businessPartner.createAdditionalAddressReferenceValue(), + businessPartner.type == GoldenRecordType.Address) + } } - fun createSiteRepresentation(genericPartner: BusinessPartnerGenericDto, siteAddressReference: LogisticAddressDto): SiteDto { - val bpnReferenceDto = genericPartner.site.siteBpn?.let { BpnReferenceDto(it, BpnReferenceType.Bpn) } - ?: generateBpnRequestIdentifier(genericPartner.createSiteReferenceValue()) - return genericPartner.toSiteDto(bpnReferenceDto, siteAddressReference) - } - fun shouldCreateSite(genericPartner: BusinessPartnerGenericDto): Boolean { - return genericPartner.ownerBpnL != null && genericPartner.site.name != null + private fun cleanAddress(addressToClean: PostalAddress, requestId: String, hasChanged: Boolean): PostalAddress { + return addressToClean.copy( + bpnReference = addressToClean.bpnReference.toRequestIfNotBpn(requestId), + hasChanged = hasChanged, + confidenceCriteria = dummyConfidenceCriteria + ) } - private fun BusinessPartnerGenericDto.update( - addressType: AddressType, - legalEntityDto: LegalEntityDto, - siteDto: SiteDto?, - logisticAddress: LogisticAddressDto? - ): BusinessPartnerGenericDto { - val relevantAddress = when (addressType) { - AddressType.LegalAndSiteMainAddress -> legalEntityDto.legalAddress!! - AddressType.LegalAddress -> legalEntityDto.legalAddress!! - AddressType.SiteMainAddress -> siteDto!!.mainAddress!! - AddressType.AdditionalAddress -> logisticAddress!! - } + private fun BusinessPartner.createLegalEntityReferenceValue() = + "LEGAL_ENTITY" + (legalEntity.legalName ?: nameParts.joinToString(" ")) - return copy( - legalEntity = legalEntity.copy(legalName = legalEntityDto.legalName, confidenceCriteria = legalEntityDto.confidenceCriteria), - site = site.copy(name = siteDto?.name, confidenceCriteria = siteDto?.confidenceCriteria), - address = address.copy(name = logisticAddress?.name, addressType = addressType, confidenceCriteria = relevantAddress.confidenceCriteria) - ) - } + private fun BusinessPartner.createSiteReferenceValue() = + "SITE" + createLegalEntityReferenceValue() + (site?.siteName ?: "") - private fun BusinessPartnerGenericDto.createLegalEntityReferenceValue() = - "LEGAL_ENTITY" + (legalEntity.legalName ?: nameParts.joinToString(" ")) + private fun BusinessPartner.createSiteMainAddressReferenceValue() = + "SITE_MAIN_ADDRESS" + createSiteReferenceValue() - private fun BusinessPartnerGenericDto.createLegalAddressReferenceValue() = + private fun BusinessPartner.createLegalAddressReferenceValue() = "LEGAL_ADDRESS" + createLegalEntityReferenceValue() - private fun BusinessPartnerGenericDto.createSiteReferenceValue() = - "SITE" + createLegalEntityReferenceValue() + site.name - - private fun BusinessPartnerGenericDto.createSiteMainAddressReferenceValue() = - if (address.addressType == AddressType.LegalAndSiteMainAddress) - createLegalAddressReferenceValue() - else - "SITE_MAIN_ADDRESS" + createSiteReferenceValue() - private fun BusinessPartnerGenericDto.createAdditionalAddressReferenceValue() = - "ADDITIONAL_ADDRESS" + createSiteReferenceValue() + private fun BusinessPartner.createAdditionalAddressReferenceValue() = + "ADDITIONAL_ADDRESS" + (additionalAddress?.addressName ?: "") + createSiteReferenceValue() private fun generateBpnRequestIdentifier(fromString: String) = - BpnReferenceDto(fromString.toUUID().toString(), BpnReferenceType.BpnRequestIdentifier) + BpnReference(fromString.toUUID().toString(), null, BpnReferenceType.BpnRequestIdentifier) + + private fun BpnReference.toRequestIfNotBpn(requestId: String) = + if(referenceType == BpnReferenceType.Bpn) + this + else + generateBpnRequestIdentifier(requestId) } diff --git a/bpdm-cleaning-service-dummy/src/main/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/GenericBusinessPartnerMappings.kt b/bpdm-cleaning-service-dummy/src/main/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/GenericBusinessPartnerMappings.kt deleted file mode 100644 index 050d6978e..000000000 --- a/bpdm-cleaning-service-dummy/src/main/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/GenericBusinessPartnerMappings.kt +++ /dev/null @@ -1,112 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.bpdm.cleaning.service - - -import org.eclipse.tractusx.bpdm.common.dto.AddressType -import org.eclipse.tractusx.orchestrator.api.model.* -import java.time.LocalDateTime - - -val dummyConfidenceCriteria = ConfidenceCriteriaDto( - sharedByOwner = false, - numberOfSharingMembers = 1, - checkedByExternalDataSource = false, - lastConfidenceCheckAt = LocalDateTime.now(), - nextConfidenceCheckAt = LocalDateTime.now().plusDays(5), - confidenceLevel = 0 -) - -fun BusinessPartnerGenericDto.toLegalEntityDto(bpnReferenceDto: BpnReferenceDto, legalAddress: LogisticAddressDto): LegalEntityDto { - return LegalEntityDto( - bpnLReference = bpnReferenceDto, - hasChanged = address.addressType in setOf(AddressType.LegalAddress, AddressType.LegalAndSiteMainAddress), - legalName = nameParts.joinToString(" "), - legalShortName = legalEntity.shortName, - identifiers = identifiers.mapNotNull { it.toLegalEntityIdentifierDto() }, - legalForm = legalEntity.legalForm, - states = states.mapNotNull { it.toLegalEntityState() }.plus(legalEntity.states.mapNotNull { it.toLegalEntityState() }), - legalAddress = legalAddress, - isCatenaXMemberData = ownerBpnL != null, - confidenceCriteria = dummyConfidenceCriteria - ) -} - -fun BusinessPartnerClassificationDto.toLegalEntityClassificationDto(): LegalEntityClassificationDto { - - return LegalEntityClassificationDto(code = code, type = type, value = value) -} - -fun BusinessPartnerIdentifierDto.toLegalEntityIdentifierDto(): LegalEntityIdentifierDto? { - - return value?.let { value -> - type?.let { type -> - LegalEntityIdentifierDto(value = value, type = type, issuingBody = issuingBody) - } - } - -} - -fun BusinessPartnerStateDto.toLegalEntityState(): LegalEntityStateDto? { - - return type?.let { LegalEntityStateDto(validFrom, validTo, it) } -} - -fun BusinessPartnerStateDto.toSiteState(): SiteStateDto? { - - return type?.let { SiteStateDto(validFrom, validTo, it) } -} - -fun BusinessPartnerStateDto.toAddressState(): AddressStateDto? { - - return type?.let { AddressStateDto(validFrom, validTo, it) } -} - -fun BusinessPartnerGenericDto.toLogisticAddressDto(bpnReferenceDto: BpnReferenceDto): - LogisticAddressDto { - - return LogisticAddressDto( - bpnAReference = bpnReferenceDto, - hasChanged = address.addressType == AddressType.AdditionalAddress, - name = address.name, - states = address.states.mapNotNull { it.toAddressState() }, - identifiers = emptyList(), - physicalPostalAddress = address.physicalPostalAddress, - alternativePostalAddress = address.alternativePostalAddress, - confidenceCriteria = dummyConfidenceCriteria - ) -} - -fun BusinessPartnerGenericDto.toSiteDto(bpnReferenceDto: BpnReferenceDto, siteAddressReference: LogisticAddressDto): SiteDto { - - return SiteDto( - bpnSReference = bpnReferenceDto, - hasChanged = address.addressType in setOf(AddressType.SiteMainAddress, AddressType.LegalAndSiteMainAddress), - name = site.name, - states = site.states.mapNotNull { it.toSiteState() }, - mainAddress = siteAddressReference, - confidenceCriteria = dummyConfidenceCriteria - ) -} - - - - - diff --git a/bpdm-cleaning-service-dummy/src/main/resources/application.yml b/bpdm-cleaning-service-dummy/src/main/resources/application.yml index bd95829e7..f595e91ce 100644 --- a/bpdm-cleaning-service-dummy/src/main/resources/application.yml +++ b/bpdm-cleaning-service-dummy/src/main/resources/application.yml @@ -61,11 +61,6 @@ bpdm: server: # The port this application runs on port: 8084 -spring: - profiles: - group: - # BPDM common shortcut to remove all authentication configuration - no-auth: no-orchestrator-auth logging: pattern: # Use BPDM custom log pattern diff --git a/bpdm-cleaning-service-dummy/src/test/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/CleaningServiceApiCallsTest.kt b/bpdm-cleaning-service-dummy/src/test/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/CleaningServiceApiCallsTest.kt index 5962ccee3..01ccc9633 100644 --- a/bpdm-cleaning-service-dummy/src/test/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/CleaningServiceApiCallsTest.kt +++ b/bpdm-cleaning-service-dummy/src/test/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/CleaningServiceApiCallsTest.kt @@ -21,14 +21,16 @@ package org.eclipse.tractusx.bpdm.cleaning.service import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.module.kotlin.readValue +import com.github.tomakehurst.wiremock.admin.model.ServeEventQuery import com.github.tomakehurst.wiremock.client.WireMock.* import com.github.tomakehurst.wiremock.core.WireMockConfiguration import com.github.tomakehurst.wiremock.junit5.WireMockExtension +import com.github.tomakehurst.wiremock.stubbing.StubMapping +import org.assertj.core.api.Assertions.assertThat import org.eclipse.tractusx.bpdm.cleaning.config.OrchestratorConfigProperties -import org.eclipse.tractusx.bpdm.cleaning.testdata.CommonValues.businessPartnerWithBpnA -import org.eclipse.tractusx.bpdm.cleaning.testdata.CommonValues.fixedTaskId +import org.eclipse.tractusx.bpdm.test.testdata.orchestrator.* import org.eclipse.tractusx.orchestrator.api.GoldenRecordTaskApi -import org.eclipse.tractusx.orchestrator.api.client.OrchestrationApiClient import org.eclipse.tractusx.orchestrator.api.model.* import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach @@ -36,6 +38,7 @@ import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest +import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.DynamicPropertyRegistry import org.springframework.test.context.DynamicPropertySource import java.time.Instant @@ -44,10 +47,10 @@ import java.time.Instant webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = ["${OrchestratorConfigProperties.PREFIX}.security-enabled=false"] ) +@ActiveProfiles("test") class CleaningServiceApiCallsTest @Autowired constructor( val cleaningServiceDummy: CleaningServiceDummy, - val jacksonObjectMapper: ObjectMapper, - val orchestrationApiClient: OrchestrationApiClient + val jacksonObjectMapper: ObjectMapper ) { companion object { @@ -68,66 +71,328 @@ class CleaningServiceApiCallsTest @Autowired constructor( } } + val fixedTaskId = "1" + val businessPartnerFactory = BusinessPartnerTestDataFactory() + val defaultBpnRequest = BpnReference("IGNORED", null, BpnReferenceType.BpnRequestIdentifier) + @BeforeEach fun beforeEach() { orchestratorMockApi.resetAll() - this.mockOrchestratorResolveApi() - this.mockOrchestratorReserveApi() } + @Test + fun `Additional Address with Site without BPNs`() { + //Mock Orchestrator responses + val mockedBusinessPartner = businessPartnerFactory.createFullBusinessPartner("test") + .copyWithBpnReferences(BpnReference.empty) + .copyWithLegalAddress(PostalAddress.empty) + .copyWithSiteMainAddress(PostalAddress.empty) + + val resolveMapping = mockOrchestratorResolveApi() + mockOrchestratorReserveApi(mockedBusinessPartner) + + //Create expectations + val expectedResponse = createResultRequest( + mockedBusinessPartner + .copyWithBpnReferences(defaultBpnRequest) + .copyWithLegalAddress(mockedBusinessPartner.uncategorized.address!!) + .copyWithSiteMainAddress(mockedBusinessPartner.uncategorized.address!!) + .copyWithConfidenceCriteria(cleaningServiceDummy.dummyConfidenceCriteria) + .copyWithHasChanged(false, false, true) + ) + + // Call the method under test + cleaningServiceDummy.pollForCleanAndSyncTasks() + val actualResponse = getResolveResult(resolveMapping) + + assertIsEqualIgnoreReferenceValue(actualResponse, expectedResponse) + } + + @Test + fun `Additional Address with Site with BPNs`() { + //Mock Orchestrator responses + val mockedBusinessPartner = businessPartnerFactory.createFullBusinessPartner("test") + .copyWithLegalAddress(PostalAddress.empty) + .copyWithSiteMainAddress(PostalAddress.empty) + + val resolveMapping = mockOrchestratorResolveApi() + mockOrchestratorReserveApi(mockedBusinessPartner) + + //Create expectations + val expectedResponse = createResultRequest( + mockedBusinessPartner + .copyWithLegalAddress(mockedBusinessPartner.uncategorized.address!!) + .copyWithSiteMainAddress(mockedBusinessPartner.uncategorized.address!!) + .copyWithConfidenceCriteria(cleaningServiceDummy.dummyConfidenceCriteria) + .copyWithHasChanged(false, false, true) + ) + + // Call the method under test + cleaningServiceDummy.pollForCleanAndSyncTasks() + val actualResponse = getResolveResult(resolveMapping) + + assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse) + } @Test - fun `pollForCleaningTasks should reserve and resolve tasks from orchestrator`() { + fun `Additional Address without Site without BPNs`() { + //Mock Orchestrator responses + val mockedBusinessPartner = businessPartnerFactory.createFullBusinessPartner("test") + .copyWithBpnReferences(BpnReference.empty) + .copyWithLegalAddress(PostalAddress.empty) + .copy(site = null) + + val resolveMapping = mockOrchestratorResolveApi() + mockOrchestratorReserveApi(mockedBusinessPartner) + + //Create expectations + val expectedResponse = createResultRequest( + mockedBusinessPartner + .copyWithBpnReferences(defaultBpnRequest) + .copyWithLegalAddress(mockedBusinessPartner.uncategorized.address!!) + .copyWithConfidenceCriteria(cleaningServiceDummy.dummyConfidenceCriteria) + .copyWithHasChanged(false, false, true) + ) + // Call the method under test - cleaningServiceDummy.pollForCleaningTasks() + cleaningServiceDummy.pollForCleanAndSyncTasks() + val actualResponse = getResolveResult(resolveMapping) - // Verify that the reserve API was called once (using WireMock) - orchestratorMockApi.verify(postRequestedFor(urlEqualTo(ORCHESTRATOR_RESERVE_TASKS_URL)).withRequestBody(matchingJsonPath("$.amount", equalTo("10")))) + assertIsEqualIgnoreReferenceValue(actualResponse, expectedResponse) + } + + @Test + fun `Additional Address without Site with BPNs`() { + //Mock Orchestrator responses + val mockedBusinessPartner = businessPartnerFactory.createFullBusinessPartner("test") + .copyWithLegalAddress(PostalAddress.empty) + .copy(site = null) + + val resolveMapping = mockOrchestratorResolveApi() + mockOrchestratorReserveApi(mockedBusinessPartner) + + //Create expectations + val expectedResponse = createResultRequest( + mockedBusinessPartner + .copyWithLegalAddress(mockedBusinessPartner.uncategorized.address!!) + .copyWithConfidenceCriteria(cleaningServiceDummy.dummyConfidenceCriteria) + .copyWithHasChanged(false, false, true) + ) - // Verify that the resolve API was called once (using WireMock) - orchestratorMockApi.verify(postRequestedFor(urlEqualTo(ORCHESTRATOR_RESOLVE_TASKS_URL))) + // Call the method under test + cleaningServiceDummy.pollForCleanAndSyncTasks() + val actualResponse = getResolveResult(resolveMapping) + + assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse) } @Test - fun `reserveTasksForStep should return expected response`() { - val expectedResponse = jacksonObjectMapper.writeValueAsString(createSampleTaskStepReservationResponse(businessPartnerWithBpnA)) + fun `Site with Own Main Address and without BPNs`() { + //Mock Orchestrator responses + val mockedBusinessPartner = businessPartnerFactory.createFullBusinessPartner("test") + .copyWithBpnReferences(BpnReference.empty) + .copyWithLegalAddress(PostalAddress.empty) + .copy(additionalAddress = null) + + val resolveMapping = mockOrchestratorResolveApi() + mockOrchestratorReserveApi(mockedBusinessPartner) - val result = orchestrationApiClient.goldenRecordTasks.reserveTasksForStep( - TaskStepReservationRequest(amount = 10, TaskStep.Clean) + //Create expectations + val expectedResponse = createResultRequest( + mockedBusinessPartner + .copyWithBpnReferences(defaultBpnRequest) + .copyWithLegalAddress(mockedBusinessPartner.uncategorized.address!!) + .copyWithConfidenceCriteria(cleaningServiceDummy.dummyConfidenceCriteria) + .copyWithHasChanged(false, true, false) ) - // Assert the expected result - val expectedResult = jacksonObjectMapper.readValue(expectedResponse, result::class.java) // Convert the expected JSON response to your DTO - assertEquals(expectedResult, result) + // Call the method under test + cleaningServiceDummy.pollForCleanAndSyncTasks() + val actualResponse = getResolveResult(resolveMapping) + + assertIsEqualIgnoreReferenceValue(actualResponse, expectedResponse) + } + + @Test + fun `Site With Own Main Address and BPNs`() { + //Mock Orchestrator responses + val mockedBusinessPartner = businessPartnerFactory.createFullBusinessPartner("test") + .copyWithLegalAddress(PostalAddress.empty) + .copy(additionalAddress = null) - orchestrationApiClient.goldenRecordTasks.resolveStepResults( - TaskStepResultRequest(TaskStep.Clean, emptyList()) + val resolveMapping = mockOrchestratorResolveApi() + mockOrchestratorReserveApi(mockedBusinessPartner) + + //Create expectations + val expectedResponse = createResultRequest( + mockedBusinessPartner + .copyWithLegalAddress(mockedBusinessPartner.uncategorized.address!!) + .copyWithConfidenceCriteria(cleaningServiceDummy.dummyConfidenceCriteria) + .copyWithHasChanged(false, true, false) ) + + // Call the method under test + cleaningServiceDummy.pollForCleanAndSyncTasks() + val actualResponse = getResolveResult(resolveMapping) + + assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse) } + @Test + fun `Site With Legal Address As Main Address And Without BPNs`() { + //Mock Orchestrator responses + val mockedBusinessPartner = businessPartnerFactory.createFullBusinessPartner("test") + .copyWithBpnReferences(BpnReference.empty) + .copyWithSiteMainAddress(null) + .copy(additionalAddress = null) + + val resolveMapping = mockOrchestratorResolveApi() + mockOrchestratorReserveApi(mockedBusinessPartner) + + //Create expectations + val expectedResponse = createResultRequest( + mockedBusinessPartner + .copyWithBpnReferences(defaultBpnRequest) + .copyWithConfidenceCriteria(cleaningServiceDummy.dummyConfidenceCriteria) + .copyWithHasChanged(false, true, false) + ) - fun mockOrchestratorReserveApi() { + // Call the method under test + cleaningServiceDummy.pollForCleanAndSyncTasks() + val actualResponse = getResolveResult(resolveMapping) + + assertIsEqualIgnoreReferenceValue(actualResponse, expectedResponse) + } + + @Test + fun `Site With Legal Address As Main Address And With BPNs`() { + //Mock Orchestrator responses + val mockedBusinessPartner = businessPartnerFactory.createFullBusinessPartner("test") + .copyWithSiteMainAddress(null) + .copy(additionalAddress = null) + + val resolveMapping = mockOrchestratorResolveApi() + mockOrchestratorReserveApi(mockedBusinessPartner) + + //Create expectations + val expectedResponse = createResultRequest( + mockedBusinessPartner + .copyWithConfidenceCriteria(cleaningServiceDummy.dummyConfidenceCriteria) + .copyWithHasChanged(false, true, false) + ) + + // Call the method under test + cleaningServiceDummy.pollForCleanAndSyncTasks() + val actualResponse = getResolveResult(resolveMapping) + + assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse) + } + + @Test + fun `Legal Entity without BPNs`() { + //Mock Orchestrator responses + val mockedBusinessPartner = businessPartnerFactory.createFullBusinessPartner("test") + .copyWithBpnReferences(BpnReference.empty) + .copyWithLegalAddress(PostalAddress.empty) + .copy(site = null, additionalAddress = null) + + val resolveMapping = mockOrchestratorResolveApi() + mockOrchestratorReserveApi(mockedBusinessPartner) + + //Create expectations + val expectedResponse = createResultRequest( + mockedBusinessPartner + .copyWithBpnReferences(defaultBpnRequest) + .copyWithLegalAddress(mockedBusinessPartner.uncategorized.address!!) + .copyWithConfidenceCriteria(cleaningServiceDummy.dummyConfidenceCriteria) + .copyWithHasChanged(true, false, false) + ) + + // Call the method under test + cleaningServiceDummy.pollForCleanAndSyncTasks() + val actualResponse = getResolveResult(resolveMapping) + + assertIsEqualIgnoreReferenceValue(actualResponse, expectedResponse) + } + + @Test + fun `Legal Entity with BPNs`() { + //Mock Orchestrator responses + val mockedBusinessPartner = businessPartnerFactory.createFullBusinessPartner("test") + .copyWithLegalAddress(PostalAddress.empty) + .copy(site = null, additionalAddress = null) + + val resolveMapping = mockOrchestratorResolveApi() + mockOrchestratorReserveApi(mockedBusinessPartner) + + //Create expectations + val expectedResponse = createResultRequest( + mockedBusinessPartner + .copyWithLegalAddress(mockedBusinessPartner.uncategorized.address!!) + .copyWithConfidenceCriteria(cleaningServiceDummy.dummyConfidenceCriteria) + .copyWithHasChanged(true, false, false) + ) + + // Call the method under test + cleaningServiceDummy.pollForCleanAndSyncTasks() + val actualResponse = getResolveResult(resolveMapping) + + assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse) + } + + + + fun mockOrchestratorReserveApi(businessPartner: BusinessPartner): StubMapping { // Orchestrator reserve - orchestratorMockApi.stubFor( + return orchestratorMockApi.stubFor( post(urlPathEqualTo(ORCHESTRATOR_RESERVE_TASKS_URL)) .willReturn( - okJson(jacksonObjectMapper.writeValueAsString(createSampleTaskStepReservationResponse(businessPartnerWithBpnA))) + okJson(jacksonObjectMapper.writeValueAsString(createSampleTaskStepReservationResponse(businessPartner))) ) ) } - fun mockOrchestratorResolveApi() { + fun mockOrchestratorResolveApi(): StubMapping { // Orchestrator resolve - orchestratorMockApi.stubFor( + return orchestratorMockApi.stubFor( post(urlPathEqualTo(ORCHESTRATOR_RESOLVE_TASKS_URL)) .willReturn(aResponse().withStatus(200)) ) } // Helper method to create a sample TaskStepReservationResponse - private fun createSampleTaskStepReservationResponse(businessPartnerGenericDto: BusinessPartnerGenericDto): TaskStepReservationResponse { - val fullDto = BusinessPartnerFullDto(businessPartnerGenericDto) - return TaskStepReservationResponse(listOf(TaskStepReservationEntryDto(fixedTaskId, fullDto)), Instant.MIN) + private fun createSampleTaskStepReservationResponse(businessPartner: BusinessPartner): TaskStepReservationResponse { + return TaskStepReservationResponse(listOf(TaskStepReservationEntryDto(fixedTaskId, businessPartner)), Instant.MIN) } + + private fun getResolveResult(stubMapping: StubMapping): TaskStepResultRequest{ + val serveEvents = orchestratorMockApi.getServeEvents(ServeEventQuery.forStubMapping(stubMapping)).requests + assertEquals(serveEvents.size, 1) + val actualRequest = serveEvents.first()!!.request + return jacksonObjectMapper.readValue(actualRequest.body) + } + + private fun assertIsEqualIgnoreReferenceValue(actual: TaskStepResultRequest, expected: TaskStepResultRequest){ + assertThat(actual) + .usingRecursiveComparison() + .ignoringFieldsMatchingRegexes( + ".*.${BpnReference::referenceValue.name}" + ) + .isEqualTo(expected) + } + + private fun createResultRequest(expectedBusinessPartner: BusinessPartner): TaskStepResultRequest { + return TaskStepResultRequest( + TaskStep.CleanAndSync, listOf( + TaskStepResultEntryDto( + fixedTaskId, + expectedBusinessPartner, + emptyList() + ) + ) + ) + } + + } \ No newline at end of file diff --git a/bpdm-cleaning-service-dummy/src/test/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/CleaningServiceDummyTest.kt b/bpdm-cleaning-service-dummy/src/test/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/CleaningServiceDummyTest.kt deleted file mode 100644 index 463a8dfee..000000000 --- a/bpdm-cleaning-service-dummy/src/test/kotlin/org/eclipse/tractusx/bpdm/cleaning/service/CleaningServiceDummyTest.kt +++ /dev/null @@ -1,165 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.bpdm.cleaning.service - -import org.eclipse.tractusx.bpdm.cleaning.config.OrchestratorConfigProperties -import org.eclipse.tractusx.bpdm.cleaning.testdata.CommonValues.businessPartnerWithBpnA -import org.eclipse.tractusx.bpdm.cleaning.testdata.CommonValues.businessPartnerWithBpnLAndBpnAAndLegalAddressType -import org.eclipse.tractusx.bpdm.cleaning.testdata.CommonValues.businessPartnerWithBpnSAndBpnAAndLegalAndSiteMainAddressType -import org.eclipse.tractusx.bpdm.cleaning.testdata.CommonValues.businessPartnerWithEmptyBpnAndSiteMainAddressType -import org.eclipse.tractusx.bpdm.cleaning.testdata.CommonValues.businessPartnerWithEmptyBpnLAndAdditionalAddressType -import org.eclipse.tractusx.bpdm.cleaning.testdata.CommonValues.expectedLegalEntityDto -import org.eclipse.tractusx.bpdm.cleaning.testdata.CommonValues.expectedLogisticAddressDto -import org.eclipse.tractusx.bpdm.cleaning.testdata.CommonValues.expectedSiteDto -import org.eclipse.tractusx.bpdm.test.util.AssertHelpers -import org.eclipse.tractusx.orchestrator.api.model.* -import org.junit.jupiter.api.Test -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.test.context.SpringBootTest -import java.time.Instant -import java.util.* - -@SpringBootTest( - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = ["${OrchestratorConfigProperties.PREFIX}.security-enabled=false"] -) -class CleaningServiceDummyTest @Autowired constructor( - val cleaningServiceDummy: CleaningServiceDummy, - val assertHelpers: AssertHelpers -) { - - - @Test - fun `test processCleaningTask with additional address type`() { - val taskStepReservationEntryDto = createSampleTaskStepReservationResponse(businessPartnerWithBpnA).reservedTasks[0] - - val result = cleaningServiceDummy.processCleaningTask(taskStepReservationEntryDto) - - val resultedAddress = result.businessPartner?.address - val resultedLegalEntity = result.businessPartner?.legalEntity - - val expectedAddress = expectedLogisticAddressDto - val expectedLegalEntity = expectedLegalEntityDto.copy(hasChanged = false, legalAddress = expectedAddress) - - assertLegalEntitiesEqual(resultedLegalEntity, expectedLegalEntity) - assertAddressesEqual(resultedAddress, expectedAddress) - } - - @Test - fun `test processCleaningTask with empty BpnA and additional address type`() { - val taskStepReservationEntryDto = createSampleTaskStepReservationResponse(businessPartnerWithEmptyBpnLAndAdditionalAddressType).reservedTasks[0] - - val result = cleaningServiceDummy.processCleaningTask(taskStepReservationEntryDto) - - val resultedAddress = result.businessPartner?.address - val resultedLegalEntity = result.businessPartner?.legalEntity - - - val expectedAddress = expectedLogisticAddressDto.copy() - val expectedLegalEntity = expectedLegalEntityDto.copy(legalAddress = expectedLogisticAddressDto, hasChanged = false) - - assertLegalEntitiesEqual(resultedLegalEntity, expectedLegalEntity) - assertAddressesEqual(resultedAddress, expectedAddress) - } - - @Test - fun `test processCleaningTask with legal address type`() { - val taskStepReservationEntryDto = createSampleTaskStepReservationResponse(businessPartnerWithBpnLAndBpnAAndLegalAddressType).reservedTasks[0] - - val result = cleaningServiceDummy.processCleaningTask(taskStepReservationEntryDto) - - val resultedLegalEntity = result.businessPartner?.legalEntity - - - val expectedLegalEntity = expectedLegalEntityDto.copy( - legalAddress = expectedLogisticAddressDto.copy( - hasChanged = false, - ) - ) - - assertLegalEntitiesEqual(resultedLegalEntity, expectedLegalEntity) - } - - @Test - fun `test processCleaningTask with legal and site main address type given`() { - val taskStepReservationResponse = createSampleTaskStepReservationResponse(businessPartnerWithBpnSAndBpnAAndLegalAndSiteMainAddressType).reservedTasks[0] - - val result = cleaningServiceDummy.processCleaningTask(taskStepReservationResponse) - - val resultedLegalEntity = result.businessPartner?.legalEntity - - val resultedSite = result.businessPartner?.site - - val expectedLegalEntity = expectedLegalEntityDto.copy( - hasChanged = true, - legalAddress = expectedLogisticAddressDto.copy( - hasChanged = false - ) - ) - - val expectedSite = expectedSiteDto.copy( - hasChanged = true, - mainAddress = expectedLogisticAddressDto.copy(hasChanged = false) - ) - - assertLegalEntitiesEqual(resultedLegalEntity, expectedLegalEntity) - assertSitesEqual(resultedSite, expectedSite) - } - @Test - fun `test processCleaningTask with empty Bpn and site main address type`() { - val taskStepReservationResponse = createSampleTaskStepReservationResponse(businessPartnerWithEmptyBpnAndSiteMainAddressType).reservedTasks[0] - - val result = cleaningServiceDummy.processCleaningTask(taskStepReservationResponse) - - val resultedLegalEntity = result.businessPartner?.legalEntity - val resultedSite = result.businessPartner?.site - - val expectedLegalEntity = expectedLegalEntityDto.copy(legalAddress = expectedLogisticAddressDto.copy(hasChanged = false), hasChanged = false) - val expectedSite = expectedSiteDto.copy(mainAddress = expectedLogisticAddressDto.copy(hasChanged = false), hasChanged = true) - - assertLegalEntitiesEqual(resultedLegalEntity, expectedLegalEntity) - assertSitesEqual(resultedSite, expectedSite) - } - - // Helper method to create a sample TaskStepReservationResponse - private fun createSampleTaskStepReservationResponse(businessPartnerGenericDto: BusinessPartnerGenericDto): TaskStepReservationResponse { - val fullDto = BusinessPartnerFullDto(businessPartnerGenericDto) - return TaskStepReservationResponse(listOf(TaskStepReservationEntryDto(UUID.randomUUID().toString(), fullDto)), Instant.MIN) - } - - - - private fun assertLegalEntitiesEqual(actual: LegalEntityDto?, expected: LegalEntityDto) = - assertHelpers.assertRecursively(actual) - .ignoringFields(LegalEntityDto::bpnLReference.name) - .ignoringFields("${LegalEntityDto::legalAddress.name}.${LogisticAddressDto::bpnAReference.name}") - .isEqualTo(expected) - - private fun assertSitesEqual(actual: SiteDto?, expected: SiteDto) = - assertHelpers.assertRecursively(actual) - .ignoringFields(SiteDto::bpnSReference.name) - .ignoringFields("${SiteDto::mainAddress.name}.${LogisticAddressDto::bpnAReference.name}") - .isEqualTo(expected) - - private fun assertAddressesEqual(actual: LogisticAddressDto?, expected: LogisticAddressDto) = - assertHelpers.assertRecursively(actual) - .ignoringFields(LogisticAddressDto::bpnAReference.name) - .isEqualTo(expected) -} diff --git a/bpdm-cleaning-service-dummy/src/test/kotlin/org/eclipse/tractusx/bpdm/cleaning/testdata/CommonValues.kt b/bpdm-cleaning-service-dummy/src/test/kotlin/org/eclipse/tractusx/bpdm/cleaning/testdata/CommonValues.kt deleted file mode 100644 index bb5a3dee3..000000000 --- a/bpdm-cleaning-service-dummy/src/test/kotlin/org/eclipse/tractusx/bpdm/cleaning/testdata/CommonValues.kt +++ /dev/null @@ -1,208 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.bpdm.cleaning.testdata - -import com.neovisionaries.i18n.CountryCode -import org.eclipse.tractusx.bpdm.cleaning.service.dummyConfidenceCriteria -import org.eclipse.tractusx.bpdm.cleaning.service.toLegalEntityIdentifierDto -import org.eclipse.tractusx.bpdm.cleaning.service.toLegalEntityState -import org.eclipse.tractusx.bpdm.cleaning.service.toSiteState -import org.eclipse.tractusx.bpdm.common.dto.AddressType -import org.eclipse.tractusx.bpdm.common.dto.BusinessPartnerRole -import org.eclipse.tractusx.bpdm.common.dto.GeoCoordinateDto -import org.eclipse.tractusx.bpdm.common.model.BusinessStateType -import org.eclipse.tractusx.bpdm.common.model.ClassificationType -import org.eclipse.tractusx.orchestrator.api.model.* -import java.time.LocalDateTime - -/** - * Contains simple test values used to create more complex test values such as DTOs - */ -object CommonValues { - - const val fixedTaskId = "taskid-123123" - - private val nameParts = listOf("Part1", "Part2") - private val siteName = "Site Name" - private val addressName = "Address Name" - private const val shortName = "ShortName" - private val identifiers = listOf( - BusinessPartnerIdentifierDto( - type = "Type1", - value = "Value1", - issuingBody = "IssuingBody1" - ) - ) - private const val legalForm = "LegalForm" - private val states = listOf( - BusinessPartnerStateDto( - validFrom = LocalDateTime.now(), - validTo = LocalDateTime.now().plusDays(10), - type = BusinessStateType.ACTIVE - ) - ) - private val classifications = listOf( - BusinessPartnerClassificationDto( - type = ClassificationType.NACE, - code = "Code1", - value = "Value1" - ) - ) - private val roles = listOf(BusinessPartnerRole.SUPPLIER, BusinessPartnerRole.CUSTOMER) - private val physicalPostalAddress = PhysicalPostalAddressDto( - geographicCoordinates = GeoCoordinateDto(longitude = 12.34f, latitude = 56.78f), - country = CountryCode.PT, - administrativeAreaLevel1 = "AdminArea1", - administrativeAreaLevel2 = "AdminArea2", - administrativeAreaLevel3 = "AdminArea3", - postalCode = "PostalCode", - city = "City", - district = "District", - street = StreetDto("StreetName", houseNumberSupplement = "House Number Supplement"), - companyPostalCode = "CompanyPostalCode", - industrialZone = "IndustrialZone", - building = "Building", - floor = "Floor", - door = "Door" - ) - - private val postalAddressForLegalAndSite = PostalAddressDto( - addressType = AddressType.LegalAndSiteMainAddress, - physicalPostalAddress = physicalPostalAddress - ) - private val postalAddressForLegal = PostalAddressDto( - addressType = AddressType.LegalAddress, - physicalPostalAddress = physicalPostalAddress - ) - private val postalAddressForSite = PostalAddressDto( - addressType = AddressType.SiteMainAddress, - physicalPostalAddress = physicalPostalAddress - ) - private val postalAddressForAdditional = PostalAddressDto( - addressType = AddressType.AdditionalAddress, - physicalPostalAddress = physicalPostalAddress - ) - - private val businessPartnerWithEmptyBpns = BusinessPartnerGenericDto( - nameParts = nameParts, - identifiers = identifiers, - states = states, - roles = roles, - ownerBpnL = "ownerBpnL2", - legalEntity = LegalEntityRepresentation( - shortName = shortName, - legalForm = legalForm, - confidenceCriteria = dummyConfidenceCriteria - ), - site = SiteRepresentation(name = siteName, states = states), - address = AddressRepresentation(name = addressName) - ) - - - val businessPartnerWithBpnA = with(businessPartnerWithEmptyBpns) { - copy( - address = address.copy( - addressBpn = "FixedBPNA", - addressType = postalAddressForAdditional.addressType, - physicalPostalAddress = postalAddressForAdditional.physicalPostalAddress, - alternativePostalAddress = postalAddressForAdditional.alternativePostalAddress - ) - ) - } - - - val businessPartnerWithBpnLAndBpnAAndLegalAddressType = with(businessPartnerWithEmptyBpns) { - copy( - address = address.copy( - addressBpn = "FixedBPNA", - addressType = postalAddressForLegal.addressType, - physicalPostalAddress = postalAddressForLegal.physicalPostalAddress, - alternativePostalAddress = postalAddressForLegal.alternativePostalAddress - ), - legalEntity = legalEntity.copy( - legalEntityBpn = "FixedBPNL" - ) - ) - } - - val businessPartnerWithEmptyBpnLAndAdditionalAddressType = with(businessPartnerWithEmptyBpns) { - copy( - address = address.copy( - addressType = postalAddressForAdditional.addressType, - physicalPostalAddress = postalAddressForAdditional.physicalPostalAddress, - alternativePostalAddress = postalAddressForAdditional.alternativePostalAddress - ) - ) - } - - val businessPartnerWithBpnSAndBpnAAndLegalAndSiteMainAddressType = with(businessPartnerWithEmptyBpns) { - copy( - address = address.copy( - addressBpn = "FixedBPNA", - addressType = postalAddressForLegalAndSite.addressType, - physicalPostalAddress = postalAddressForLegalAndSite.physicalPostalAddress, - alternativePostalAddress = postalAddressForLegalAndSite.alternativePostalAddress - ), - site = site.copy( - siteBpn = "FixedBPNS" - ) - ) - } - - val businessPartnerWithEmptyBpnAndSiteMainAddressType = with(businessPartnerWithEmptyBpns) { - copy( - address = address.copy( - addressType = postalAddressForSite.addressType, - physicalPostalAddress = postalAddressForSite.physicalPostalAddress, - alternativePostalAddress = postalAddressForSite.alternativePostalAddress - ) - ) - } - - val expectedLegalEntityDto = LegalEntityDto( - hasChanged = true, - legalName = nameParts.joinToString(" "), - legalShortName = shortName, - identifiers = identifiers.mapNotNull { it.toLegalEntityIdentifierDto() }, - legalForm = legalForm, - states = states.mapNotNull { it.toLegalEntityState() }, - isCatenaXMemberData = true, - confidenceCriteria = dummyConfidenceCriteria - ) - - val expectedSiteDto = SiteDto( - hasChanged = true, - name = siteName, - states = states.mapNotNull { it.toSiteState() }, - confidenceCriteria = dummyConfidenceCriteria - ) - - val expectedLogisticAddressDto = LogisticAddressDto( - - hasChanged = true, - name = addressName, - states = emptyList(), - identifiers = emptyList(), - physicalPostalAddress = physicalPostalAddress, - confidenceCriteria = dummyConfidenceCriteria - ) - - -} \ No newline at end of file diff --git a/bpdm-cleaning-service-dummy/src/test/resources/application-test.yml b/bpdm-cleaning-service-dummy/src/test/resources/application-test.yml new file mode 100644 index 000000000..ce4cf4f84 --- /dev/null +++ b/bpdm-cleaning-service-dummy/src/test/resources/application-test.yml @@ -0,0 +1,4 @@ +bpdm: + cleaningService: + # When and how often the cleaning service should poll for golden record tasks in the orchestrator + pollingCron: "-" \ No newline at end of file diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/AddressIdentifierDto.kt b/bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/config/OrchestratorTestDataConfiguration.kt similarity index 67% rename from bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/AddressIdentifierDto.kt rename to bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/config/OrchestratorTestDataConfiguration.kt index b758e36b1..617c9815c 100644 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/AddressIdentifierDto.kt +++ b/bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/config/OrchestratorTestDataConfiguration.kt @@ -17,13 +17,17 @@ * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ -package org.eclipse.tractusx.orchestrator.api.model +package org.eclipse.tractusx.bpdm.test.config -import org.eclipse.tractusx.bpdm.common.dto.IAddressIdentifierDto +import org.eclipse.tractusx.bpdm.test.testdata.orchestrator.BusinessPartnerTestDataFactory +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration -data class AddressIdentifierDto( +@Configuration +class OrchestratorTestDataConfiguration { - override val value: String, - override val type: String + @Bean + fun orchestratorTestdataFactory(): BusinessPartnerTestDataFactory = + BusinessPartnerTestDataFactory() -) : IAddressIdentifierDto +} \ No newline at end of file diff --git a/bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/testdata/gate/BusinessPartnerGenericCommonValues.kt b/bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/testdata/gate/BusinessPartnerGenericCommonValues.kt index f822c660f..721ad0c8e 100644 --- a/bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/testdata/gate/BusinessPartnerGenericCommonValues.kt +++ b/bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/testdata/gate/BusinessPartnerGenericCommonValues.kt @@ -20,514 +20,133 @@ package org.eclipse.tractusx.bpdm.test.testdata.gate import com.neovisionaries.i18n.CountryCode -import org.eclipse.tractusx.bpdm.common.dto.AddressType -import org.eclipse.tractusx.bpdm.common.dto.BusinessPartnerRole -import org.eclipse.tractusx.bpdm.common.dto.GeoCoordinateDto import org.eclipse.tractusx.bpdm.common.model.BusinessStateType import org.eclipse.tractusx.bpdm.common.model.DeliveryServiceType import org.eclipse.tractusx.orchestrator.api.model.* import java.time.LocalDateTime +import java.time.ZoneOffset object BusinessPartnerGenericCommonValues { - //Business Partner with two entries in every collection - val businessPartner1 = BusinessPartnerGenericDto( - nameParts = listOf("part-cleaned-1", "name-cleaned-2"), - identifiers = listOf( - BusinessPartnerIdentifierDto( - type = "identifier-type-1-cleaned", - value = "identifier-value-1-cleaned", - issuingBody = "issuingBody-1-cleaned" - ), - BusinessPartnerIdentifierDto( - type = "identifier-type-2-cleaned", - value = "identifier-value-2-cleaned", - issuingBody = "issuingBody-2-cleaned" - ), + val address = PostalAddress( + bpnReference = BpnReference("000000123CCC333", null, BpnReferenceType.BpnRequestIdentifier), + hasChanged = true, + addressName = "Address Name", + physicalAddress = PhysicalAddress( + geographicCoordinates = GeoCoordinate(0.5f, 0.5f, 0.5f), + country = CountryCode.PT.alpha2, + administrativeAreaLevel1 = "PT-PT", + administrativeAreaLevel2 = "pt-admin-level-2-cleaned", + administrativeAreaLevel3 = "pt-admin-level-3-cleaned", + postalCode = "phys-postal-code-cleaned", + city = "city", + district = "district", + street = Street( + name = "name", + houseNumber = "house-number", + houseNumberSupplement = "house-number-supplement", + milestone = "milestone", + direction = "direction", + namePrefix = "name-prefix", + additionalNamePrefix = "add-name-prefix", + nameSuffix = "name-suffix", + additionalNameSuffix = "add-name-suffix" + + ), + companyPostalCode = "comp-postal-code", + industrialZone = "industrial-zone", + building = "building", + floor = "floor", + door = "door" + ), + alternativeAddress = AlternativeAddress( + geographicCoordinates = GeoCoordinate(0.6f, 0.6f, 0.6f), + country = CountryCode.PT.alpha2, + administrativeAreaLevel1 = "PT-PT", + postalCode = "postal-code-cleaned", + city = "alt-city-cleaned", + deliveryServiceNumber = "delivery-service-number-cleaned", + deliveryServiceQualifier = "delivery-service-qualifier-cleaned", + deliveryServiceType = DeliveryServiceType.PO_BOX + ), + confidenceCriteria = ConfidenceCriteria( + sharedByOwner = false, + checkedByExternalDataSource = true, + numberOfSharingMembers = 4, + lastConfidenceCheckAt = LocalDateTime.of(2020, 4, 3, 2, 1).toInstant(ZoneOffset.UTC), + nextConfidenceCheckAt = LocalDateTime.of(2028, 4, 3, 2, 1).toInstant(ZoneOffset.UTC), + confidenceLevel = 5 ), - states = listOf( - BusinessPartnerStateDto( - validFrom = LocalDateTime.of(2020, 9, 22, 15, 50), - validTo = LocalDateTime.of(2023, 10, 23, 16, 40), - type = BusinessStateType.INACTIVE + identifiers = emptyList(), + states = emptyList() + ) + + //Business Partner with two entries in every collection + val businessPartner1 = BusinessPartner( + nameParts = emptyList(), + uncategorized = UncategorizedProperties( + nameParts = listOf("part-cleaned-1", "name-cleaned-2"), + identifiers = listOf( + Identifier( + type = "identifier-type-1-cleaned", + value = "identifier-value-1-cleaned", + issuingBody = "issuingBody-1-cleaned" + ), + Identifier( + type = "identifier-type-2-cleaned", + value = "identifier-value-2-cleaned", + issuingBody = "issuingBody-2-cleaned" + ) + ), + states = listOf( + BusinessState( + validFrom = LocalDateTime.of(2020, 9, 22, 15, 50).toInstant(ZoneOffset.UTC), + validTo = LocalDateTime.of(2023, 10, 23, 16, 40).toInstant(ZoneOffset.UTC), + type = BusinessStateType.INACTIVE + ), + BusinessState( + validFrom = LocalDateTime.of(2000, 8, 21, 14, 30).toInstant(ZoneOffset.UTC), + validTo = LocalDateTime.of(2020, 9, 22, 15, 50).toInstant(ZoneOffset.UTC), + type = BusinessStateType.ACTIVE + ) ), - BusinessPartnerStateDto( - validFrom = LocalDateTime.of(2000, 8, 21, 14, 30), - validTo = LocalDateTime.of(2020, 9, 22, 15, 50), - type = BusinessStateType.ACTIVE - ) - ), - roles = listOf( - BusinessPartnerRole.CUSTOMER, - BusinessPartnerRole.SUPPLIER + address = address ), - ownerBpnL = "BPNL_CLEANED_VALUES", - legalEntity = LegalEntityRepresentation( - legalEntityBpn = "000000123AAA123", + owningCompany = "BPNL_CLEANED_VALUES", + legalEntity = LegalEntity( + bpnReference = BpnReference("000000123AAA123", null, BpnReferenceType.BpnRequestIdentifier), legalName = "legal-name-cleaned", - shortName = "shot-name-cleaned", + legalShortName = "shot-name-cleaned", legalForm = "legal-form-cleaned", - confidenceCriteria = ConfidenceCriteriaDto( + confidenceCriteria = ConfidenceCriteria( sharedByOwner = true, checkedByExternalDataSource = true, numberOfSharingMembers = 7, - lastConfidenceCheckAt = LocalDateTime.of(2022, 4, 3, 2, 1), - nextConfidenceCheckAt = LocalDateTime.of(2026, 4, 3, 2, 1), + lastConfidenceCheckAt = LocalDateTime.of(2022, 4, 3, 2, 1).toInstant(ZoneOffset.UTC), + nextConfidenceCheckAt = LocalDateTime.of(2026, 4, 3, 2, 1).toInstant(ZoneOffset.UTC), confidenceLevel = 1 - ) + ), + identifiers = emptyList(), + states = emptyList(), + isCatenaXMemberData = false, + hasChanged = true, + legalAddress = address ), - site = SiteRepresentation( - siteBpn = "000000123BBB222", - name = "Site Name", - confidenceCriteria = ConfidenceCriteriaDto( + site = Site( + bpnReference = BpnReference("000000123BBB222", null, BpnReferenceType.BpnRequestIdentifier), + siteName = "Site Name", + confidenceCriteria = ConfidenceCriteria( sharedByOwner = false, checkedByExternalDataSource = false, numberOfSharingMembers = 8, - lastConfidenceCheckAt = LocalDateTime.of(2023, 4, 3, 2, 1), - nextConfidenceCheckAt = LocalDateTime.of(2024, 4, 3, 2, 1), + lastConfidenceCheckAt = LocalDateTime.of(2023, 4, 3, 2, 1).toInstant(ZoneOffset.UTC), + nextConfidenceCheckAt = LocalDateTime.of(2024, 4, 3, 2, 1).toInstant(ZoneOffset.UTC), confidenceLevel = 2 - ) - ), - address = AddressRepresentation( - addressBpn = "000000123CCC333", - name = "Address Name", - addressType = AddressType.AdditionalAddress, - physicalPostalAddress = PhysicalPostalAddressDto( - geographicCoordinates = GeoCoordinateDto(0.5f, 0.5f, 0.5f), - country = CountryCode.PT, - administrativeAreaLevel1 = "PT-PT", - administrativeAreaLevel2 = "pt-admin-level-2-cleaned", - administrativeAreaLevel3 = "pt-admin-level-3-cleaned", - postalCode = "phys-postal-code-cleaned", - city = "city", - district = "district", - street = StreetDto( - name = "name", - houseNumber = "house-number", - houseNumberSupplement = "house-number-supplement", - milestone = "milestone", - direction = "direction", - namePrefix = "name-prefix", - additionalNamePrefix = "add-name-prefix", - nameSuffix = "name-suffix", - additionalNameSuffix = "add-name-suffix" - - ), - companyPostalCode = "comp-postal-code", - industrialZone = "industrial-zone", - building = "building", - floor = "floor", - door = "door" - ), - alternativePostalAddress = AlternativePostalAddressDto( - geographicCoordinates = GeoCoordinateDto(0.6f, 0.6f, 0.6f), - country = CountryCode.PT, - administrativeAreaLevel1 = "PT-PT", - postalCode = "postal-code-cleaned", - city = "alt-city-cleaned", - deliveryServiceNumber = "delivery-service-number-cleaned", - deliveryServiceQualifier = "delivery-service-qualifier-cleaned", - deliveryServiceType = DeliveryServiceType.PO_BOX - ), - confidenceCriteria = ConfidenceCriteriaDto( - sharedByOwner = false, - checkedByExternalDataSource = true, - numberOfSharingMembers = 4, - lastConfidenceCheckAt = LocalDateTime.of(2020, 4, 3, 2, 1), - nextConfidenceCheckAt = LocalDateTime.of(2028, 4, 3, 2, 1), - confidenceLevel = 5 - ) - ) - ) - - //Business Partner with single entry in every collection - val businessPartner2 = BusinessPartnerGenericDto( - nameParts = listOf("name-part-2"), - identifiers = listOf( - BusinessPartnerIdentifierDto( - type = "identifier-type-2", - value = "identifier-value-2", - issuingBody = "issuingBody-2" - ) - ), - states = listOf( - BusinessPartnerStateDto( - validFrom = LocalDateTime.of(1988, 10, 4, 22, 30), - validTo = LocalDateTime.of(2023, 1, 1, 10, 10), - type = BusinessStateType.ACTIVE - ) - ), - roles = listOf( - BusinessPartnerRole.CUSTOMER - ), - legalEntity = LegalEntityRepresentation( - legalEntityBpn = "BPNLTEST-2", - legalName = "legal-name-2", - shortName = "shortname-2", - legalForm = "legal-form-2", - confidenceCriteria = ConfidenceCriteriaDto( - sharedByOwner = true, - checkedByExternalDataSource = true, - numberOfSharingMembers = 7, - lastConfidenceCheckAt = LocalDateTime.of(2022, 4, 3, 2, 1), - nextConfidenceCheckAt = LocalDateTime.of(2026, 4, 3, 2, 1), - confidenceLevel = 1 - ) - ), - site = SiteRepresentation( - siteBpn = "BPNSTEST-2", - name = "site name 2", - confidenceCriteria = ConfidenceCriteriaDto( - sharedByOwner = true, - checkedByExternalDataSource = true, - numberOfSharingMembers = 7, - lastConfidenceCheckAt = LocalDateTime.of(2022, 4, 3, 2, 1), - nextConfidenceCheckAt = LocalDateTime.of(2026, 4, 3, 2, 1), - confidenceLevel = 1 - ) - ), - address = AddressRepresentation( - addressBpn = "BPNATEST-2", - name = "address name 2", - addressType = AddressType.LegalAddress, - physicalPostalAddress = PhysicalPostalAddressDto( - geographicCoordinates = GeoCoordinateDto(0.4f, 0.4f, 0.4f), - country = CountryCode.FR, - administrativeAreaLevel1 = "FR-ARA", - administrativeAreaLevel2 = "fr-admin-level-2", - administrativeAreaLevel3 = "fr-admin-level-3", - postalCode = "phys-postal-code-2", - city = "city-2", - district = "district-2", - street = StreetDto( - name = "name-2", - houseNumber = "house-number-2", - houseNumberSupplement = "house-number-supplement-2", - milestone = "milestone-2", - direction = "direction-2", - namePrefix = "name-prefix-2", - additionalNamePrefix = "add-name-prefix-2", - nameSuffix = "name-suffix-2", - additionalNameSuffix = "add-name-suffix-2" - - ), - companyPostalCode = "comp-postal-code-2", - industrialZone = "industrial-zone-2", - building = "building-2", - floor = "floor-2", - door = "door-2" - ), - alternativePostalAddress = AlternativePostalAddressDto( - geographicCoordinates = GeoCoordinateDto(0.2f, 0.2f, 0.2f), - country = CountryCode.FR, - administrativeAreaLevel1 = "FR-BFC", - postalCode = "alt-post-code-2", - city = "alt-city-2", - deliveryServiceNumber = "delivery-service-number-2", - deliveryServiceQualifier = "delivery-service-qualifier-2", - deliveryServiceType = DeliveryServiceType.BOITE_POSTALE ), - confidenceCriteria = ConfidenceCriteriaDto( - sharedByOwner = true, - checkedByExternalDataSource = true, - numberOfSharingMembers = 7, - lastConfidenceCheckAt = LocalDateTime.of(2022, 4, 3, 2, 1), - nextConfidenceCheckAt = LocalDateTime.of(2026, 4, 3, 2, 1), - confidenceLevel = 1 - ) + states = emptyList(), + hasChanged = true, + siteMainAddress = address ), - ownerBpnL = "BPNL_OWNER_TEST_2" + additionalAddress = address ) - - - val logisticAddress1 = LogisticAddressDto( - name = "Address Name 1", - states = listOf( - AddressStateDto( - validFrom = LocalDateTime.of(1970, 4, 4, 4, 4), - validTo = LocalDateTime.of(1975, 5, 5, 5, 5), - type = BusinessStateType.ACTIVE - ), - AddressStateDto( - validFrom = LocalDateTime.of(1975, 5, 5, 5, 5), - validTo = null, - type = BusinessStateType.INACTIVE - ), - ), - identifiers = listOf( - AddressIdentifierDto( - value = "Address Identifier Value 1", - type = "Address Identifier Type 1" - ), - AddressIdentifierDto( - value = "Address Identifier Value 2", - type = "Address Identifier Type 2" - ) - ), - physicalPostalAddress = PhysicalPostalAddressDto( - geographicCoordinates = GeoCoordinateDto(0.12f, 0.12f, 0.12f), - country = CountryCode.AD, - administrativeAreaLevel1 = "AD-07", - administrativeAreaLevel2 = "Admin-Level 2-1", - administrativeAreaLevel3 = "Admin-Level 3-1", - postalCode = "Postal Code 1", - city = "City 1", - district = "District 1", - street = StreetDto( - name = "Street Name 1", - houseNumber = "House Number 1", - houseNumberSupplement = "house-number-supplement-1", - milestone = "Milestone 1", - direction = "Direction 1", - namePrefix = "Name Prefix 1", - additionalNameSuffix = "Additional Name Suffix 1", - additionalNamePrefix = "Additional Name Prefix 1", - nameSuffix = "Name Suffix 1" - ), - companyPostalCode = "Company Postal Code 1", - industrialZone = "Industrial Zone 1", - building = "Building 1", - floor = "Floor 1", - door = "Door 1" - ), - alternativePostalAddress = AlternativePostalAddressDto( - geographicCoordinates = GeoCoordinateDto(0.23f, 0.23f, 0.23f), - country = CountryCode.AD, - administrativeAreaLevel1 = "AD-08", - postalCode = "Postal Code Alt 1", - city = "City Alt 1", - deliveryServiceType = DeliveryServiceType.PRIVATE_BAG, - deliveryServiceQualifier = "Delivery Service Qualifier 1", - deliveryServiceNumber = "Delivery Service Number 1" - ), - bpnAReference = BpnReferenceDto( - referenceType = BpnReferenceType.Bpn, - referenceValue = "BPNATEST-1" - ), - hasChanged = true, - confidenceCriteria = ConfidenceCriteriaDto( - sharedByOwner = true, - checkedByExternalDataSource = true, - numberOfSharingMembers = 7, - lastConfidenceCheckAt = LocalDateTime.of(2022, 4, 3, 2, 1), - nextConfidenceCheckAt = LocalDateTime.of(2026, 4, 3, 2, 1), - confidenceLevel = 1 - ) - ) - - val logisticAddress2 = LogisticAddressDto( - name = "Address Name 2", - states = listOf( - AddressStateDto( - validFrom = LocalDateTime.of(1971, 4, 4, 4, 4), - validTo = null, - type = BusinessStateType.ACTIVE - ) - ), - identifiers = listOf( - AddressIdentifierDto( - value = "Address Identifier Value 2-1", - type = "Address Identifier Type 2-1" - ) - ), - physicalPostalAddress = PhysicalPostalAddressDto( - geographicCoordinates = GeoCoordinateDto(0.45f, 0.46f, 0.47f), - country = CountryCode.AD, - administrativeAreaLevel1 = "AD-07", - administrativeAreaLevel2 = "Admin-Level 2-2", - administrativeAreaLevel3 = "Admin-Level 3-2", - postalCode = "Postal Code 2", - city = "City 2", - district = "District 2", - street = StreetDto( - name = "Street Name 2", - houseNumber = "House Number 2", - houseNumberSupplement = "house-number-supplement-2", - milestone = "Milestone 2", - direction = "Direction 2", - namePrefix = "Name Prefix 2", - additionalNameSuffix = "Additional Name Suffix 2", - additionalNamePrefix = "Additional Name Prefix 2", - nameSuffix = "Name Suffix 2" - ), - companyPostalCode = "Company Postal Code 2", - industrialZone = "Industrial Zone 2", - building = "Building 2", - floor = "Floor 2", - door = "Door 2" - ), - alternativePostalAddress = AlternativePostalAddressDto( - geographicCoordinates = GeoCoordinateDto(0.01f, 0.02f, 0.03f), - country = CountryCode.AD, - administrativeAreaLevel1 = "AD-08", - postalCode = "Postal Code Alt 2", - city = "City Alt 2", - deliveryServiceType = DeliveryServiceType.PO_BOX, - deliveryServiceQualifier = "Delivery Service Qualifier 2", - deliveryServiceNumber = "Delivery Service Number 2" - ), - bpnAReference = BpnReferenceDto( - referenceType = BpnReferenceType.BpnRequestIdentifier, - referenceValue = "BPN_REQUEST_ID_TEST" - ), - hasChanged = true, - confidenceCriteria = ConfidenceCriteriaDto( - sharedByOwner = false, - checkedByExternalDataSource = false, - numberOfSharingMembers = 2, - lastConfidenceCheckAt = LocalDateTime.of(2023, 5, 6, 7, 8), - nextConfidenceCheckAt = LocalDateTime.of(2026, 5, 6, 7, 8), - confidenceLevel = 2 - ) - ) - - val legalEntity1 = LegalEntityDto( - legalName = "Legal Entity Name 1", - legalShortName = "Legal Short Name 1", - identifiers = listOf( - LegalEntityIdentifierDto( - value = "Legal Identifier Value 1", - type = "Legal Identifier Type 1", - issuingBody = "Legal Issuing Body 1" - ), - LegalEntityIdentifierDto( - value = "Legal Identifier Value 2", - type = "Legal Identifier Type 2", - issuingBody = "Legal Issuing Body 2" - ), - ), - legalForm = "Legal Form 1", - states = listOf( - LegalEntityStateDto( - validFrom = LocalDateTime.of(1995, 2, 2, 3, 3), - validTo = LocalDateTime.of(2000, 3, 3, 4, 4), - type = BusinessStateType.ACTIVE - ), - LegalEntityStateDto( - validFrom = LocalDateTime.of(2000, 3, 3, 4, 4), - validTo = null, - type = BusinessStateType.INACTIVE - ), - ), - legalAddress = logisticAddress1, - bpnLReference = BpnReferenceDto( - referenceValue = "BPNL1-TEST", - referenceType = BpnReferenceType.Bpn - ), - hasChanged = false, - confidenceCriteria = ConfidenceCriteriaDto( - sharedByOwner = false, - checkedByExternalDataSource = false, - numberOfSharingMembers = 2, - lastConfidenceCheckAt = LocalDateTime.of(2023, 5, 6, 7, 8), - nextConfidenceCheckAt = LocalDateTime.of(2026, 5, 6, 7, 8), - confidenceLevel = 3 - ), - isCatenaXMemberData = false - ) - - val legalEntity2 = LegalEntityDto( - legalName = "Legal Entity Name 2", - legalShortName = "Legal Short Name 2", - identifiers = listOf( - LegalEntityIdentifierDto( - value = "Legal Identifier Value 2", - type = "Legal Identifier Type 2", - issuingBody = "Legal Issuing Body 2" - ) - ), - legalForm = "Legal Form 2", - states = listOf( - LegalEntityStateDto( - validFrom = LocalDateTime.of(1900, 5, 5, 5, 5), - validTo = null, - type = BusinessStateType.ACTIVE - ) - ), - legalAddress = logisticAddress2, - bpnLReference = BpnReferenceDto( - referenceValue = "BPNL-REQUEST_ID_TEST", - referenceType = BpnReferenceType.BpnRequestIdentifier - ), - hasChanged = false, - confidenceCriteria = ConfidenceCriteriaDto( - sharedByOwner = false, - checkedByExternalDataSource = false, - numberOfSharingMembers = 2, - lastConfidenceCheckAt = LocalDateTime.of(2023, 5, 6, 7, 8), - nextConfidenceCheckAt = LocalDateTime.of(2026, 5, 6, 7, 8), - confidenceLevel = 4 - ), - isCatenaXMemberData = false - ) - - val site1 = SiteDto( - name = "Site Name 1", - states = listOf( - SiteStateDto( - validFrom = LocalDateTime.of(1991, 10, 10, 10, 10), - validTo = LocalDateTime.of(2001, 11, 11, 11, 11), - type = BusinessStateType.ACTIVE - ), - SiteStateDto( - validFrom = LocalDateTime.of(2001, 11, 11, 11, 11), - validTo = null, - type = BusinessStateType.INACTIVE - ) - ), - mainAddress = logisticAddress1, - bpnSReference = BpnReferenceDto( - referenceValue = "BPNS_TEST", - referenceType = BpnReferenceType.Bpn - ), - hasChanged = false, - confidenceCriteria = ConfidenceCriteriaDto( - sharedByOwner = false, - checkedByExternalDataSource = false, - numberOfSharingMembers = 2, - lastConfidenceCheckAt = LocalDateTime.of(2023, 5, 6, 7, 8), - nextConfidenceCheckAt = LocalDateTime.of(2026, 5, 6, 7, 8), - confidenceLevel = 5 - ) - ) - - val site2 = SiteDto( - name = "Site Name 2", - states = listOf( - SiteStateDto( - validFrom = LocalDateTime.of(1997, 12, 12, 12, 12), - validTo = null, - type = BusinessStateType.ACTIVE - ) - ), - mainAddress = logisticAddress2, - bpnSReference = BpnReferenceDto( - referenceValue = "BPNS_REQUEST_ID_TEST", - referenceType = BpnReferenceType.BpnRequestIdentifier - ), - hasChanged = true, - confidenceCriteria = ConfidenceCriteriaDto( - sharedByOwner = false, - checkedByExternalDataSource = false, - numberOfSharingMembers = 2, - lastConfidenceCheckAt = LocalDateTime.of(2023, 5, 6, 7, 8), - nextConfidenceCheckAt = LocalDateTime.of(2026, 5, 6, 7, 8), - confidenceLevel = 6 - ) - ) - - val businessPartner1Full = BusinessPartnerFullDto( - generic = businessPartner1, - legalEntity = legalEntity1, - site = site1, - address = logisticAddress1 - ) - - val businessPartner2Full = BusinessPartnerFullDto( - generic = businessPartner2, - legalEntity = legalEntity2, - site = site2, - address = logisticAddress2 - ) - } \ No newline at end of file diff --git a/bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/testdata/orchestrator/BusinessPartnerHelpers.kt b/bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/testdata/orchestrator/BusinessPartnerHelpers.kt new file mode 100644 index 000000000..7d38a46bb --- /dev/null +++ b/bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/testdata/orchestrator/BusinessPartnerHelpers.kt @@ -0,0 +1,90 @@ +/******************************************************************************* + * Copyright (c) 2021,2024 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 + ******************************************************************************/ + +package org.eclipse.tractusx.bpdm.test.testdata.orchestrator + +import org.eclipse.tractusx.orchestrator.api.model.* + +fun BusinessPartner.copyWithLegalEntityIdentifiers(identifiers: List) = + copy( + legalEntity = legalEntity.copy( + identifiers = identifiers + ) + ) + +fun BusinessPartner.copyWithBpnReferences(bpnReference: BpnReference) = + copy( + legalEntity = legalEntity.copy(bpnReference = bpnReference), + site = site?.copy(bpnReference = bpnReference), + additionalAddress = additionalAddress?.copy(bpnReference = bpnReference) + ) + +fun BusinessPartner.copyWithConfidenceCriteria(confidenceCriteria: ConfidenceCriteria) = + copy( + legalEntity = legalEntity.copy( + confidenceCriteria = confidenceCriteria, + legalAddress = legalEntity.legalAddress.copy(confidenceCriteria = confidenceCriteria) + ), + site = site?.let { + it.copy( + confidenceCriteria = confidenceCriteria, + siteMainAddress = it.siteMainAddress?.copy(confidenceCriteria = confidenceCriteria) + ) + } , + additionalAddress = additionalAddress?.copy(confidenceCriteria = confidenceCriteria) + ) + +fun BusinessPartner.copyWithAddress(overWriteAddress: PostalAddress = PostalAddress.empty, applyToLegalAddress: Boolean, applyToSiteMainAddress: Boolean, applyToAdditionalAddress: Boolean) = + copy( + legalEntity = legalEntity.copy( + legalAddress = if(applyToLegalAddress) overWriteAddress else legalEntity.legalAddress + ), + site = site?.copy( + siteMainAddress = if(applyToSiteMainAddress) overWriteAddress else site?.siteMainAddress + ), + additionalAddress = if(applyToAdditionalAddress) overWriteAddress else additionalAddress + ) + +fun BusinessPartner.copyWithLegalAddress(postalAddress: PostalAddress) = + copy( + legalEntity = legalEntity.copy( + legalAddress = postalAddress + ) + ) + +fun BusinessPartner.copyWithSiteMainAddress(postalAddress: PostalAddress?) = + copy( + site = site?.copy( + siteMainAddress = postalAddress + ) + ) + +fun BusinessPartner.copyWithHasChanged(legalEntityChanged: Boolean = false, siteChanged: Boolean = false, additionalAddressChanged: Boolean = false) = + copy( + legalEntity = legalEntity.copy(hasChanged = legalEntityChanged), + site = site?.copy(hasChanged = siteChanged), + additionalAddress = additionalAddress?.copy(hasChanged = additionalAddressChanged) + ) + +fun BusinessPartner.copyWithBpnRequests() = + copy( + legalEntity = legalEntity.copy(bpnReference = legalEntity.bpnReference.copy(referenceType = BpnReferenceType.BpnRequestIdentifier)), + site = site?.copy(bpnReference = site!!.bpnReference.copy(referenceType = BpnReferenceType.BpnRequestIdentifier)), + additionalAddress = additionalAddress?.copy(bpnReference = additionalAddress!!.bpnReference.copy(referenceType = BpnReferenceType.BpnRequestIdentifier)) + ) \ No newline at end of file diff --git a/bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/testdata/orchestrator/BusinessPartnerTestDataFactory.kt b/bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/testdata/orchestrator/BusinessPartnerTestDataFactory.kt new file mode 100644 index 000000000..11872146c --- /dev/null +++ b/bpdm-common-test/src/main/kotlin/org/eclipse/tractusx/bpdm/test/testdata/orchestrator/BusinessPartnerTestDataFactory.kt @@ -0,0 +1,200 @@ +/******************************************************************************* + * Copyright (c) 2021,2024 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 + ******************************************************************************/ + +package org.eclipse.tractusx.bpdm.test.testdata.orchestrator + +import com.neovisionaries.i18n.CountryCode +import org.eclipse.tractusx.bpdm.common.model.BusinessStateType +import org.eclipse.tractusx.bpdm.common.model.DeliveryServiceType +import org.eclipse.tractusx.orchestrator.api.model.* +import java.time.Instant +import java.time.temporal.ChronoUnit +import kotlin.random.Random + + + + +class BusinessPartnerTestDataFactory( + val metadata: TestMetadataReferences? = null +){ + + //Business Partner with maximal fields filled + fun createFullBusinessPartner(seed: String = "Test"): BusinessPartner { + val longSeed = seed.hashCode().toLong() + val random = Random(longSeed) + + return BusinessPartner( + nameParts = listOf( + NamePart("Legal Name $seed", NamePartType.LegalName), + NamePart("Site Name $seed", NamePartType.SiteName), + NamePart("Address Name $seed", NamePartType.AddressName), + NamePart("Legal Short Name $seed", NamePartType.ShortName), + NamePart("Legal Form $seed", NamePartType.LegalForm) + ), + owningCompany = "Owner Company BPNL $seed", + uncategorized = UncategorizedProperties( + nameParts = 1.rangeTo(random.nextInt(2, 5)).map { index -> "$seed Uncategorized Name Part $index" }, + identifiers = 1.rangeTo(random.nextInt(2, 5)).map { index -> createIdentifier(seed, index, null) }, + states = 1.rangeTo(random.nextInt(2, 5)).map { _ -> createState(random) }, + address = createAddress("Uncategorized Address $seed") + ), + legalEntity = createLegalEntity(seed), + site = createSite(seed), + additionalAddress = createAddress("Additional Address $seed") + ) + } + + fun createLegalEntityBusinessPartner(seed: String = "Test"): BusinessPartner { + return BusinessPartner.empty.copy(legalEntity = createLegalEntity(seed)) + } + + fun createSiteBusinessPartner(seed: String = "Test"): BusinessPartner { + return BusinessPartner.empty.copy( + legalEntity = createLegalEntity(seed), + site = createSite(seed) + ) + } + + fun createLegalEntity(seed: String = "Test"): LegalEntity { + val random = seed.toRandom() + return LegalEntity( + bpnReference = createBpnReference(seed, "BPNL"), + legalName = "Legal Name $seed", + legalShortName = "Legal Short Name $seed", + legalForm = metadata?.legalForms?.random(random) ?: "Legal Form $seed", + identifiers = createIdentifiers(seed, random, metadata?.legalEntityIdentifierTypes), + states = createStates(seed, random.nextInt(2, 5), random), + confidenceCriteria = createConfidenceCriteria(random), + isCatenaXMemberData = random.nextBoolean(), + hasChanged = true, + legalAddress = createAddress("Legal Address $seed") + ) + } + + fun createSite(seed: String = "Test"): Site { + val random = seed.toRandom() + return Site( + bpnReference = createBpnReference(seed, "BPNS"), + siteName = "Site Name $seed", + states = createStates(seed, 5, random), + confidenceCriteria = createConfidenceCriteria(random), + hasChanged = true, + siteMainAddress = createAddress("Site Main Address $seed") + ) + } + + fun createAddress(seed: String = "Test"): PostalAddress { + val random = seed.toRandom() + return PostalAddress( + bpnReference = createBpnReference(seed, "$seed BPNA"), + hasChanged = true, + addressName = "$seed Address Name", + identifiers = createIdentifiers(seed, random, metadata?.addressIdentifierTypes), + states = createStates(seed, 5, random), + confidenceCriteria = createConfidenceCriteria(random), + physicalAddress = PhysicalAddress( + geographicCoordinates = GeoCoordinate(longitude = random.nextFloat(), latitude = random.nextFloat(), altitude = random.nextFloat()), + country = CountryCode.entries.toTypedArray().random(random).alpha2, + administrativeAreaLevel1 = metadata?.adminAreas?.random(random) ?: "Admin Level 1 $seed", + administrativeAreaLevel2 = "Admin Level 2 $seed", + administrativeAreaLevel3 = "Admin Level 3 $seed", + postalCode = "Postal Code $seed", + city = "City $seed", + district = "District $seed", + street = Street( + name = "Street Name $seed", + houseNumber = "House Number $seed", + houseNumberSupplement = "House Number Supplement $seed", + milestone = "Milestone $seed", + direction = "Direction $seed", + namePrefix = "Name Prefix $seed", + nameSuffix = "Name Suffix $seed", + additionalNamePrefix = "Additional Name Prefix $seed", + additionalNameSuffix = "Additional Name Suffix $seed" + ), + companyPostalCode = "Company Postal Code $seed", + industrialZone = "Industrial Zone $seed", + building = "Building $seed", + floor = "Floor $seed", + door = "Door $seed" + ), + alternativeAddress = AlternativeAddress( + geographicCoordinates = GeoCoordinate(longitude = random.nextFloat(), latitude = random.nextFloat(), altitude = random.nextFloat()), + country = CountryCode.entries.toTypedArray().random(random).alpha2, + administrativeAreaLevel1 = metadata?.adminAreas?.random(random) ?: "Alt Admin Level 1 $seed", + postalCode = "Alt Postal Code $seed", + city = "Alt City $seed", + deliveryServiceNumber = "Delivery Service Number $seed", + deliveryServiceType = DeliveryServiceType.entries.random(random), + deliveryServiceQualifier = "Delivery Service Qualifier $seed" + ) + ) + } + + private fun createBpnReference(seed: String, bpn: String): BpnReference { + return BpnReference( + referenceValue = "$bpn Reference Value $seed", + desiredBpn = "Desired $bpn $seed", + referenceType = BpnReferenceType.Bpn + ) + } + + private fun createConfidenceCriteria(random: Random) : ConfidenceCriteria { + val lastConfidenceCheck = random.nextInstant() + return ConfidenceCriteria( + sharedByOwner = random.nextBoolean(), + checkedByExternalDataSource = random.nextBoolean(), + numberOfSharingMembers = random.nextInt(0, 5), + lastConfidenceCheckAt = lastConfidenceCheck, + nextConfidenceCheckAt = lastConfidenceCheck.plus(10, ChronoUnit.DAYS), + confidenceLevel = random.nextInt(0, 10) + ) + } + + private fun createIdentifiers(seed: String, random: Random, availableIdentifiers: List?): List { + return 1.rangeTo(random.nextInt(2, 5)).map { index -> createIdentifier(seed, index, availableIdentifiers?.random(random)) } + } + + private fun createIdentifier(seed: String, index: Int, identifierType: String?): Identifier { + return Identifier("$seed Id Value $index", identifierType ?: "$seed Id Type $index", "$seed Issuing Body $index") + } + + private fun createStates(seed: String, count: Int, random: Random): List { + return 1.rangeTo(count).map { _ -> createState(random) } + } + + private fun createState(random: Random): BusinessState { + val validFrom = random.nextInstant() + return BusinessState(validFrom = validFrom, validTo = validFrom.plus(10, ChronoUnit.DAYS), BusinessStateType.entries.random()) + } + + private fun String.toRandom() = Random(hashCode().toLong()) + + + + private fun Random.nextInstant() = Instant.ofEpochSecond(nextLong(0, 365241780471)) + + + data class TestMetadataReferences( + val legalForms: List, + val legalEntityIdentifierTypes: List, + val addressIdentifierTypes: List, + val adminAreas: List + ) +} diff --git a/bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/service/BusinessPartnerService.kt b/bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/service/BusinessPartnerService.kt index c242d816e..d65947b31 100644 --- a/bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/service/BusinessPartnerService.kt +++ b/bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/service/BusinessPartnerService.kt @@ -38,7 +38,6 @@ import org.eclipse.tractusx.bpdm.gate.repository.SharingStateRepository import org.eclipse.tractusx.bpdm.gate.repository.generic.BusinessPartnerRepository import org.eclipse.tractusx.bpdm.gate.util.getCurrentUserBpn import org.eclipse.tractusx.orchestrator.api.client.OrchestrationApiClient -import org.eclipse.tractusx.orchestrator.api.model.BusinessPartnerGenericDto import org.eclipse.tractusx.orchestrator.api.model.TaskCreateRequest import org.eclipse.tractusx.orchestrator.api.model.TaskCreateResponse import org.eclipse.tractusx.orchestrator.api.model.TaskMode @@ -281,13 +280,4 @@ class BusinessPartnerService( alternativePostalAddress = fromPostalAddress.alternativePostalAddress } - - private fun createGoldenRecordTasks(mode: TaskMode, orchestratorBusinessPartnersDto: List): TaskCreateResponse { - return orchestrationApiClient.goldenRecordTasks.createTasks( - TaskCreateRequest( - mode, orchestratorBusinessPartnersDto - ) - ) - } - } diff --git a/bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/service/GoldenRecordTaskService.kt b/bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/service/GoldenRecordTaskService.kt index 76e67df3f..135edaaa2 100644 --- a/bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/service/GoldenRecordTaskService.kt +++ b/bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/service/GoldenRecordTaskService.kt @@ -34,6 +34,7 @@ import org.eclipse.tractusx.bpdm.pool.api.model.ChangelogType import org.eclipse.tractusx.bpdm.pool.api.model.request.ChangelogSearchRequest import org.eclipse.tractusx.orchestrator.api.client.OrchestrationApiClient import org.eclipse.tractusx.orchestrator.api.model.* +import org.eclipse.tractusx.orchestrator.api.model.BusinessPartner import org.springframework.data.domain.Pageable import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -63,7 +64,7 @@ class GoldenRecordTaskService( val partners = businessPartnerRepository.findByStageAndExternalIdIn(StageType.Input, foundStates.map { it.externalId }) - val orchestratorBusinessPartnersDto = partners.map { orchestratorMappings.toBusinessPartnerGenericDto(it) } + val orchestratorBusinessPartnersDto = partners.map { orchestratorMappings.toOrchestratorDto(it) } val createdTasks = createGoldenRecordTasks(TaskMode.UpdateFromSharingMember, orchestratorBusinessPartnersDto) @@ -96,10 +97,13 @@ class GoldenRecordTaskService( .map { Pair(it, sharingStateMap[it.taskId]!!) } .groupBy { (task, _) -> task.processingState.resultState } + val businessPartnerInput = taskStatesByResult[ResultState.Success]?.let { businessPartnerRepository.findByStageAndExternalIdIn(StageType.Input, it.map { (_, sharingState) -> sharingState.externalId }) } ?: emptyList() + val inputByExternalId = businessPartnerInput.associateBy { it.externalId } + val sharingStatesWithoutTasks = sharingStates.filter { it.taskId !in tasks.map { task -> task.taskId } } val businessPartnersToUpsert = taskStatesByResult[ResultState.Success]?.map { (task, sharingState) -> - orchestratorMappings.toBusinessPartner(task.businessPartnerResult!!, sharingState.externalId,sharingState.associatedOwnerBpnl) + orchestratorMappings.toBusinessPartner(task.businessPartnerResult, sharingState.externalId, sharingState.associatedOwnerBpnl, inputByExternalId[sharingState.externalId]?.roles?.toSortedSet() ?: sortedSetOf() ) } ?: emptyList() businessPartnerService.upsertBusinessPartnersOutputFromCandidates(businessPartnersToUpsert) @@ -146,7 +150,7 @@ class GoldenRecordTaskService( val gateOutputEntries = businessPartnerRepository.findByStageAndBpnLInOrBpnSInOrBpnAIn(StageType.Output, bpnL, bpnS, bpnA) val businessPartnerGenericDtoList = gateOutputEntries.map { bp -> - orchestratorMappings.toBusinessPartnerGenericDto(bp) + orchestratorMappings.toOrchestratorDto(bp) } val tasks = createGoldenRecordTasks(TaskMode.UpdateFromPool, businessPartnerGenericDtoList) @@ -168,7 +172,7 @@ class GoldenRecordTaskService( logger.info { "Created ${tasks.size} new golden record tasks from pool updates" } } - private fun createGoldenRecordTasks(mode: TaskMode, orchestratorBusinessPartnersDto: List): List { + private fun createGoldenRecordTasks(mode: TaskMode, orchestratorBusinessPartnersDto: List): List { if (orchestratorBusinessPartnersDto.isEmpty()) return emptyList() diff --git a/bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/service/OrchestratorMappings.kt b/bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/service/OrchestratorMappings.kt index 399d39ed7..19b4f7f83 100644 --- a/bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/service/OrchestratorMappings.kt +++ b/bpdm-gate/src/main/kotlin/org/eclipse/tractusx/bpdm/gate/service/OrchestratorMappings.kt @@ -19,11 +19,13 @@ package org.eclipse.tractusx.bpdm.gate.service +import com.neovisionaries.i18n.CountryCode import mu.KotlinLogging +import org.eclipse.tractusx.bpdm.common.dto.AddressType +import org.eclipse.tractusx.bpdm.common.dto.BusinessPartnerRole import org.eclipse.tractusx.bpdm.common.dto.BusinessPartnerType -import org.eclipse.tractusx.bpdm.common.dto.GeoCoordinateDto +import org.eclipse.tractusx.bpdm.common.exception.BpdmNullMappingException import org.eclipse.tractusx.bpdm.common.model.StageType -import org.eclipse.tractusx.bpdm.gate.api.model.SharingStateType import org.eclipse.tractusx.bpdm.gate.config.BpnConfigProperties import org.eclipse.tractusx.bpdm.gate.entity.AlternativePostalAddressDb import org.eclipse.tractusx.bpdm.gate.entity.GeographicCoordinateDb @@ -31,7 +33,10 @@ import org.eclipse.tractusx.bpdm.gate.entity.PhysicalPostalAddressDb import org.eclipse.tractusx.bpdm.gate.entity.StreetDb import org.eclipse.tractusx.bpdm.gate.entity.generic.* import org.eclipse.tractusx.orchestrator.api.model.* +import org.eclipse.tractusx.orchestrator.api.model.BpnReferenceType import org.springframework.stereotype.Service +import java.time.ZoneOffset +import java.util.SortedSet @Service class OrchestratorMappings( @@ -39,187 +44,231 @@ class OrchestratorMappings( ) { private val logger = KotlinLogging.logger { } - fun toBusinessPartnerGenericDto(entity: BusinessPartnerDb) = BusinessPartnerGenericDto( - nameParts = entity.nameParts, - identifiers = entity.identifiers.map { toIdentifierDto(it) }, - states = entity.states.map { toStateDto(it) }, - roles = entity.roles, - ownerBpnL = getOwnerBpnL(entity), - legalEntity = toLegalEntityComponentDto(entity), - site = toSiteComponentDto(entity), - address = toAddressComponentDto(entity) + fun toOrchestratorDto(entity: BusinessPartnerDb): BusinessPartner { + val postalAddress = toPostalAddress(entity) - ) - - private fun toLegalEntityComponentDto(entity: BusinessPartnerDb) = LegalEntityRepresentation( - legalEntityBpn = entity.bpnL, - legalName = entity.legalName, - shortName = entity.shortName, - legalForm = entity.legalForm, - confidenceCriteria = entity.legalEntityConfidence?.let { toConfidenceCriteria(it) }, - states = entity.states.filter { it.businessPartnerTyp == BusinessPartnerType.LEGAL_ENTITY }.map(::toStateDto) - ) - - private fun toSiteComponentDto(entity: BusinessPartnerDb) = SiteRepresentation( - siteBpn = entity.bpnS, - name = entity.siteName, - confidenceCriteria = entity.siteConfidence?.let { toConfidenceCriteria(it) }, - states = entity.states.filter { it.businessPartnerTyp == BusinessPartnerType.SITE }.map(::toStateDto) - ) - - private fun toAddressComponentDto(entity: BusinessPartnerDb) = AddressRepresentation( - addressBpn = entity.bpnA, - name = entity.addressName, - addressType = entity.postalAddress.addressType, - physicalPostalAddress = entity.postalAddress.physicalPostalAddress?.let(::toPhysicalPostalAddressDto), - alternativePostalAddress = entity.postalAddress.alternativePostalAddress?.let(this::toAlternativePostalAddressDto), - confidenceCriteria = entity.addressConfidence?.let { toConfidenceCriteria(it) }, - states = entity.states.filter { it.businessPartnerTyp == BusinessPartnerType.ADDRESS }.map(::toStateDto) - ) - - private fun toClassificationDto(entity: ClassificationDb) = - BusinessPartnerClassificationDto(type = entity.type, code = entity.code, value = entity.value) - - private fun toPostalAddressDto(entity: PostalAddressDb) = - PostalAddressDto( - addressType = entity.addressType, - physicalPostalAddress = entity.physicalPostalAddress?.let(::toPhysicalPostalAddressDto), - alternativePostalAddress = entity.alternativePostalAddress?.let(this::toAlternativePostalAddressDto) + return BusinessPartner( + nameParts = emptyList(), + uncategorized = UncategorizedProperties( + nameParts = entity.nameParts, + identifiers = entity.identifiers.map { Identifier(it.value, it.type, it.issuingBody) }, + states = entity.states.filter { it.businessPartnerTyp == BusinessPartnerType.GENERIC }.map { toState(it) }, + address = postalAddress.takeIf { entity.postalAddress.addressType == null } + ), + owningCompany = getOwnerBpnL(entity), + legalEntity = LegalEntity( + bpnReference = toBpnReference(entity.bpnL), + legalName = entity.legalName, + legalForm = entity.legalForm, + legalShortName = entity.shortName, + identifiers = emptyList(), + states = entity.states.filter { it.businessPartnerTyp == BusinessPartnerType.LEGAL_ENTITY }.map { toState(it) }, + confidenceCriteria = toConfidenceCriteria(entity.legalEntityConfidence), + isCatenaXMemberData = null, + hasChanged = true, + legalAddress = postalAddress.takeIf { entity.postalAddress.addressType == AddressType.LegalAddress || entity.postalAddress.addressType == AddressType.LegalAndSiteMainAddress } ?: PostalAddress.empty + ), + site = Site( + bpnReference = toBpnReference(entity.bpnS), + siteName = entity.siteName, + states = entity.states.filter { it.businessPartnerTyp == BusinessPartnerType.SITE }.map { toState(it) }, + confidenceCriteria = toConfidenceCriteria(entity.siteConfidence), + hasChanged = true, + siteMainAddress = postalAddress.takeIf { entity.postalAddress.addressType == AddressType.SiteMainAddress } + ).takeIf { entity.bpnS != null || entity.siteName != null }, + additionalAddress = postalAddress.takeIf { entity.postalAddress.addressType == AddressType.AdditionalAddress } ) + } - private fun toPhysicalPostalAddressDto(entity: PhysicalPostalAddressDb) = - PhysicalPostalAddressDto( - geographicCoordinates = entity.geographicCoordinates?.let(::toGeoCoordinateDto), - country = entity.country, - administrativeAreaLevel1 = entity.administrativeAreaLevel1, - administrativeAreaLevel2 = entity.administrativeAreaLevel2, - administrativeAreaLevel3 = entity.administrativeAreaLevel3, - postalCode = entity.postalCode, - city = entity.city, - district = entity.district, - street = entity.street?.let(::toStreetDto), - companyPostalCode = entity.companyPostalCode, - industrialZone = entity.industrialZone, - building = entity.building, - floor = entity.floor, - door = entity.door + private fun toPostalAddress(entity: BusinessPartnerDb): PostalAddress { + return PostalAddress( + bpnReference = toBpnReference(entity.bpnA), + addressName = entity.addressName, + identifiers = emptyList(), + states = entity.states.filter { it.businessPartnerTyp == BusinessPartnerType.ADDRESS }.map { toState(it) }, + confidenceCriteria = toConfidenceCriteria(entity.addressConfidence), + physicalAddress = entity.postalAddress.physicalPostalAddress?.let { + with(it) { + PhysicalAddress( + geographicCoordinates = toGeographicCoordinates(geographicCoordinates), + country = country?.alpha2, + administrativeAreaLevel1 = administrativeAreaLevel1, + administrativeAreaLevel2 = administrativeAreaLevel2, + administrativeAreaLevel3 = administrativeAreaLevel3, + postalCode = postalCode, + city = city, + district = district, + street = street?.let { + with(it) { + Street( + name = name, + houseNumber = houseNumber, + houseNumberSupplement = houseNumberSupplement, + milestone = milestone, + direction = direction, + namePrefix = namePrefix, + additionalNamePrefix = additionalNamePrefix, + nameSuffix = nameSuffix, + additionalNameSuffix = additionalNameSuffix + ) + } + } ?: Street.empty, + companyPostalCode = companyPostalCode, + industrialZone = industrialZone, + building = building, + floor = floor, + door = door + ) + } + } ?: PhysicalAddress.empty, + alternativeAddress = entity.postalAddress.alternativePostalAddress?.let { + with(it) { + AlternativeAddress( + geographicCoordinates = toGeographicCoordinates(geographicCoordinates), + country = country?.alpha2, + administrativeAreaLevel1, + postalCode, + city, + deliveryServiceType, + deliveryServiceQualifier, + deliveryServiceNumber + ) + } + } ?: AlternativeAddress.empty, + hasChanged = null ) + } - private fun toAlternativePostalAddressDto(entity: AlternativePostalAddressDb): AlternativePostalAddressDto = - AlternativePostalAddressDto( - geographicCoordinates = entity.geographicCoordinates?.let(::toGeoCoordinateDto), - country = entity.country, - administrativeAreaLevel1 = entity.administrativeAreaLevel1, - postalCode = entity.postalCode, - city = entity.city, - deliveryServiceType = entity.deliveryServiceType, - deliveryServiceQualifier = entity.deliveryServiceQualifier, - deliveryServiceNumber = entity.deliveryServiceNumber - ) - private fun toStreetDto(entity: StreetDb) = - StreetDto( - name = entity.name, - houseNumber = entity.houseNumber, - houseNumberSupplement = entity.houseNumberSupplement, - milestone = entity.milestone, - direction = entity.direction, - namePrefix = entity.namePrefix, - additionalNamePrefix = entity.additionalNamePrefix, - nameSuffix = entity.nameSuffix, - additionalNameSuffix = entity.additionalNameSuffix - ) + private fun toGeographicCoordinates(geoCoordinate: GeographicCoordinateDb?): GeoCoordinate { + return geoCoordinate?.let { with(it) { + GeoCoordinate(longitude, latitude, altitude) + } + } ?: GeoCoordinate.empty + } - private fun toStateDto(entity: StateDb) = - BusinessPartnerStateDto(type = entity.type, validFrom = entity.validFrom, validTo = entity.validTo) - private fun toIdentifierDto(entity: IdentifierDb) = - BusinessPartnerIdentifierDto(type = entity.type, value = entity.value, issuingBody = entity.issuingBody) + private fun toConfidenceCriteria(confidenceCriteria: ConfidenceCriteriaDb?): ConfidenceCriteria { + return confidenceCriteria?.let { + with(it){ + ConfidenceCriteria( + sharedByOwner, + checkedByExternalDataSource, + numberOfBusinessPartners, + lastConfidenceCheckAt.toInstant(ZoneOffset.UTC), + nextConfidenceCheckAt.toInstant(ZoneOffset.UTC), + confidenceLevel + ) + } + } ?: ConfidenceCriteria.empty + } - private fun toGeoCoordinateDto(entity: GeographicCoordinateDb) = - GeoCoordinateDto(latitude = entity.latitude, longitude = entity.longitude, altitude = entity.altitude) + private fun toState(state: StateDb): BusinessState { + return BusinessState(state.validFrom?.toInstant(ZoneOffset.UTC), state.validTo?.toInstant(ZoneOffset.UTC), state.type) + } + + private fun toBpnReference(value: String?) = + value?.let { + BpnReference( + referenceValue = value, + desiredBpn = null, + referenceType = BpnReferenceType.Bpn + ) + } ?: BpnReference.empty private fun getOwnerBpnL(entity: BusinessPartnerDb): String? { - return if (entity.isOwnCompanyData) bpnConfigProperties.ownerBpnL else { + return if(entity.associatedOwnerBpnl != null){ + entity.associatedOwnerBpnl + }else if (entity.isOwnCompanyData) { + bpnConfigProperties.ownerBpnL + } + else { logger.warn { "Owner BPNL property is not configured" } null } } - private fun toConfidenceCriteria(entity: ConfidenceCriteriaDb) = - ConfidenceCriteriaDto( - sharedByOwner = entity.sharedByOwner, - checkedByExternalDataSource = entity.checkedByExternalDataSource, - numberOfSharingMembers = entity.numberOfBusinessPartners, - lastConfidenceCheckAt = entity.lastConfidenceCheckAt, - nextConfidenceCheckAt = entity.nextConfidenceCheckAt, - confidenceLevel = entity.confidenceLevel - ) - fun toSharingStateType(resultState: ResultState) = when (resultState) { - ResultState.Pending -> SharingStateType.Pending - ResultState.Success -> SharingStateType.Success - ResultState.Error -> SharingStateType.Error + //Mapping from orchestrator model to entity + fun toBusinessPartner(dto: BusinessPartner, externalId: String, associatedOwnerBpnl: String?, roles: SortedSet): BusinessPartnerDb{ + val addressType = when(dto.type){ + GoldenRecordType.LegalEntity -> AddressType.LegalAddress + GoldenRecordType.Site -> if(dto.site!!.siteMainIsLegalAddress) AddressType.LegalAndSiteMainAddress else AddressType.SiteMainAddress + GoldenRecordType.Address -> AddressType.AdditionalAddress + null -> throw BpdmNullMappingException(BusinessPartner::class, BusinessPartnerDb::class, BusinessPartner::type) + } + + val postalAddress = when(addressType){ + AddressType.LegalAndSiteMainAddress -> dto.legalEntity.legalAddress + AddressType.LegalAddress -> dto.legalEntity.legalAddress + AddressType.SiteMainAddress -> dto.site!!.siteMainAddress!! + AddressType.AdditionalAddress -> dto.additionalAddress!! + } + + return with(dto) { + BusinessPartnerDb( + externalId = externalId, + nameParts = uncategorized.nameParts.toMutableList(), + shortName = legalEntity.legalShortName, + identifiers = uncategorized.identifiers + .plus(legalEntity.identifiers) + .plus(postalAddress.identifiers) + .mapNotNull { toIdentifier(it) }.toSortedSet(), + legalName = legalEntity.legalName, + siteName = site?.siteName, + addressName = postalAddress.addressName, + legalForm = legalEntity.legalForm, + states = uncategorized.states.asSequence().mapNotNull { toState(it, BusinessPartnerType.GENERIC) } + .plus(legalEntity.states.mapNotNull{ toState(it, BusinessPartnerType.LEGAL_ENTITY) }) + .plus(site?.states?.mapNotNull{ toState(it, BusinessPartnerType.SITE) } ?: emptyList()) + .plus(postalAddress.states.mapNotNull{ toState(it, BusinessPartnerType.ADDRESS)} ) + .toSortedSet(), + roles = roles, + postalAddress = PostalAddressDb( + addressType = addressType, + physicalPostalAddress = toPhysicalPostalAddress(postalAddress.physicalAddress), + alternativePostalAddress = postalAddress.alternativeAddress?.let(::toAlternativePostalAddress) + ), + bpnL = legalEntity.bpnReference.referenceValue!!, + bpnS = site?.bpnReference?.referenceValue, + bpnA = postalAddress.bpnReference.referenceValue!!, + stage = StageType.Output, + legalEntityConfidence = legalEntity.confidenceCriteria?.let { toConfidenceCriteria(it) }, + siteConfidence = site?.confidenceCriteria?.let { toConfidenceCriteria(it) }, + addressConfidence = postalAddress.confidenceCriteria?.let { toConfidenceCriteria(it) }, + associatedOwnerBpnl = associatedOwnerBpnl + ) + } } - //Mapping BusinessPartnerGenericDto from to BusinessPartner - fun toBusinessPartner(dto: BusinessPartnerGenericDto, externalId: String, associatedOwnerBpnl: String?) = BusinessPartnerDb( - externalId = externalId, - nameParts = dto.nameParts.toMutableList(), - shortName = dto.legalEntity.shortName, - identifiers = dto.identifiers.mapNotNull { toIdentifier(it) }.toSortedSet(), - legalName = dto.legalEntity.legalName, - siteName = dto.site.name, - addressName = dto.address.name, - legalForm = dto.legalEntity.legalForm, - states = dto.states.mapNotNull { toState(it, BusinessPartnerType.GENERIC) } - .plus(dto.legalEntity.states.mapNotNull{ toState(it, BusinessPartnerType.LEGAL_ENTITY) }) - .plus(dto.site.states.mapNotNull{ toState(it, BusinessPartnerType.SITE) }) - .plus(dto.address.states.mapNotNull{ toState(it, BusinessPartnerType.ADDRESS) }) - .toSortedSet(), - roles = dto.roles.toSortedSet(), - postalAddress = toPostalAddress(dto.address), - bpnL = dto.legalEntity.legalEntityBpn, - bpnS = dto.site.siteBpn, - bpnA = dto.address.addressBpn, - stage = StageType.Output, - legalEntityConfidence = dto.legalEntity.confidenceCriteria?.let { toConfidenceCriteria(it) }, - siteConfidence = dto.site.confidenceCriteria?.let { toConfidenceCriteria(it) }, - addressConfidence = dto.address.confidenceCriteria?.let { toConfidenceCriteria(it) }, - associatedOwnerBpnl = associatedOwnerBpnl - ) - private fun toIdentifier(dto: BusinessPartnerIdentifierDto) = + private fun toIdentifier(dto: Identifier) = dto.type?.let { type -> dto.value?.let { value -> IdentifierDb(type = type, value = value, issuingBody = dto.issuingBody) } } - private fun toState(dto: BusinessPartnerStateDto, businessPartnerType: BusinessPartnerType) = - dto.type?.let { StateDb(type = it, validFrom = dto.validFrom, validTo = dto.validTo, businessPartnerTyp = businessPartnerType) } - - private fun toClassification(dto: BusinessPartnerClassificationDto) = - ClassificationDb(type = dto.type, code = dto.code, value = dto.value) + private fun toState(dto: BusinessState, businessPartnerType: BusinessPartnerType) = + dto.type?.let { StateDb( + type = it, + validFrom = dto.validFrom?.atZone(ZoneOffset.UTC)?.toLocalDateTime(), + validTo = dto.validTo?.atZone(ZoneOffset.UTC)?.toLocalDateTime(), + businessPartnerTyp = businessPartnerType) + } - private fun toPostalAddress(dto: AddressRepresentation) = - PostalAddressDb( - addressType = dto.addressType, - physicalPostalAddress = dto.physicalPostalAddress?.let(::toPhysicalPostalAddress), - alternativePostalAddress = dto.alternativePostalAddress?.let(this::toAlternativePostalAddress) - ) - private fun toPhysicalPostalAddress(dto: PhysicalPostalAddressDto) = + private fun toPhysicalPostalAddress(dto: PhysicalAddress) = PhysicalPostalAddressDb( - geographicCoordinates = dto.geographicCoordinates?.let(::toGeographicCoordinate), - country = dto.country, + geographicCoordinates = toGeographicCoordinate(dto.geographicCoordinates), + country = CountryCode.getByAlpha2Code(dto.country), administrativeAreaLevel1 = dto.administrativeAreaLevel1, administrativeAreaLevel2 = dto.administrativeAreaLevel2, administrativeAreaLevel3 = dto.administrativeAreaLevel3, postalCode = dto.postalCode, city = dto.city, district = dto.district, - street = dto.street?.let(::toStreet), + street = toStreet(dto.street), companyPostalCode = dto.companyPostalCode, industrialZone = dto.industrialZone, building = dto.building, @@ -227,10 +276,10 @@ class OrchestratorMappings( door = dto.door ) - private fun toAlternativePostalAddress(dto: AlternativePostalAddressDto) = + private fun toAlternativePostalAddress(dto: AlternativeAddress) = AlternativePostalAddressDb( - geographicCoordinates = dto.geographicCoordinates?.let(::toGeographicCoordinate), - country = dto.country, + geographicCoordinates = toGeographicCoordinate(dto.geographicCoordinates), + country = CountryCode.getByAlpha2Code(dto.country), administrativeAreaLevel1 = dto.administrativeAreaLevel1, postalCode = dto.postalCode, city = dto.city, @@ -239,7 +288,7 @@ class OrchestratorMappings( deliveryServiceNumber = dto.deliveryServiceNumber ) - private fun toStreet(dto: StreetDto) = + private fun toStreet(dto: Street) = StreetDb( name = dto.name, houseNumber = dto.houseNumber, @@ -252,16 +301,20 @@ class OrchestratorMappings( additionalNameSuffix = dto.additionalNameSuffix ) - private fun toGeographicCoordinate(dto: GeoCoordinateDto) = - GeographicCoordinateDb(latitude = dto.latitude, longitude = dto.longitude, altitude = dto.altitude) + private fun toGeographicCoordinate(dto: GeoCoordinate) = + dto.latitude?.let { lat -> + dto.longitude?.let { lon -> + GeographicCoordinateDb(latitude = lat, longitude = lon, altitude = dto.altitude) + } + } - private fun toConfidenceCriteria(dto: ConfidenceCriteriaDto) = + private fun toConfidenceCriteria(dto: ConfidenceCriteria) = ConfidenceCriteriaDb( - sharedByOwner = dto.sharedByOwner, - checkedByExternalDataSource = dto.checkedByExternalDataSource, - numberOfBusinessPartners = dto.numberOfSharingMembers, - lastConfidenceCheckAt = dto.lastConfidenceCheckAt, - nextConfidenceCheckAt = dto.nextConfidenceCheckAt, - confidenceLevel = dto.confidenceLevel + sharedByOwner = dto.sharedByOwner!!, + checkedByExternalDataSource = dto.checkedByExternalDataSource!!, + numberOfBusinessPartners = dto.numberOfSharingMembers!!, + lastConfidenceCheckAt = dto.lastConfidenceCheckAt!!.atZone(ZoneOffset.UTC).toLocalDateTime(), + nextConfidenceCheckAt = dto.nextConfidenceCheckAt!!.atZone(ZoneOffset.UTC).toLocalDateTime(), + confidenceLevel = dto.confidenceLevel!! ) } \ No newline at end of file diff --git a/bpdm-gate/src/main/resources/application.yml b/bpdm-gate/src/main/resources/application.yml index 3971d08f8..0320f4ec9 100644 --- a/bpdm-gate/src/main/resources/application.yml +++ b/bpdm-gate/src/main/resources/application.yml @@ -50,10 +50,10 @@ bpdm: # Up to how many golden record tasks can be created when checking batchSize: 100 fromPool: - # When and how often the Gate checks for golden record updates from the Pool - batchSize: 100 # Up to how many golden record tasks can be created when checking - cron: '*/30 * * * * *' + batchSize: 100 + # When and how often the Gate checks for golden record updates from the Pool + cron: '-' check: batchSize: 100 cron: '*/30 * * * * *' @@ -159,10 +159,6 @@ management: # Include readiness state in health response (ready to accept traffic) enabled: true spring: - profiles: - group: - # BPDM common shortcut to remove all authentication configuration - no-auth: no-api-auth, no-orchestrator-auth, no-pool-auth security: oauth2: resourceserver: diff --git a/bpdm-gate/src/test/kotlin/org/eclipse/tractusx/bpdm/gate/util/BusinessPartnerGenericValues.kt b/bpdm-gate/src/test/kotlin/org/eclipse/tractusx/bpdm/gate/util/BusinessPartnerGenericValues.kt deleted file mode 100644 index 16d3e8029..000000000 --- a/bpdm-gate/src/test/kotlin/org/eclipse/tractusx/bpdm/gate/util/BusinessPartnerGenericValues.kt +++ /dev/null @@ -1,143 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.bpdm.gate.util - -import com.neovisionaries.i18n.CountryCode -import org.eclipse.tractusx.bpdm.common.dto.AddressType -import org.eclipse.tractusx.bpdm.common.dto.BusinessPartnerRole -import org.eclipse.tractusx.bpdm.common.dto.GeoCoordinateDto -import org.eclipse.tractusx.bpdm.common.model.BusinessStateType -import org.eclipse.tractusx.bpdm.common.model.DeliveryServiceType -import org.eclipse.tractusx.orchestrator.api.model.* -import java.time.LocalDateTime - -object BusinessPartnerGenericValues { - - //Business Partner with two entries in every collection - val businessPartner1 = BusinessPartnerGenericDto( - nameParts = listOf("part-cleaned-1", "name-cleaned-2"), - identifiers = listOf( - BusinessPartnerIdentifierDto( - type = "identifier-type-1-cleaned", - value = "identifier-value-1-cleaned", - issuingBody = "issuingBody-1-cleaned" - ), - BusinessPartnerIdentifierDto( - type = "identifier-type-2-cleaned", - value = "identifier-value-2-cleaned", - issuingBody = "issuingBody-2-cleaned" - ), - ), - states = listOf( - BusinessPartnerStateDto( - validFrom = LocalDateTime.of(2020, 9, 22, 15, 50), - validTo = LocalDateTime.of(2023, 10, 23, 16, 40), - type = BusinessStateType.INACTIVE - ), - BusinessPartnerStateDto( - validFrom = LocalDateTime.of(2000, 8, 21, 14, 30), - validTo = LocalDateTime.of(2020, 9, 22, 15, 50), - type = BusinessStateType.ACTIVE - ) - ), - roles = listOf( - BusinessPartnerRole.CUSTOMER, - BusinessPartnerRole.SUPPLIER - ), - ownerBpnL = "BPNL_CLEANED_VALUES", - legalEntity = LegalEntityRepresentation( - legalEntityBpn = "000000123AAA123", - legalName = "legal-name-cleaned", - shortName = "shot-name-cleaned", - legalForm = "legal-form-cleaned", - confidenceCriteria = ConfidenceCriteriaDto( - sharedByOwner = true, - checkedByExternalDataSource = true, - numberOfSharingMembers = 7, - lastConfidenceCheckAt = LocalDateTime.of(2022, 4, 3, 2, 1), - nextConfidenceCheckAt = LocalDateTime.of(2026, 4, 3, 2, 1), - confidenceLevel = 1 - ) - ), - site = SiteRepresentation( - siteBpn = "000000123BBB222", - name = "Site Name", - confidenceCriteria = ConfidenceCriteriaDto( - sharedByOwner = false, - checkedByExternalDataSource = false, - numberOfSharingMembers = 8, - lastConfidenceCheckAt = LocalDateTime.of(2023, 4, 3, 2, 1), - nextConfidenceCheckAt = LocalDateTime.of(2024, 4, 3, 2, 1), - confidenceLevel = 2 - ) - ), - address = AddressRepresentation( - addressBpn = "000000123CCC333", - name = "Address Name", - addressType = AddressType.AdditionalAddress, - physicalPostalAddress = PhysicalPostalAddressDto( - geographicCoordinates = GeoCoordinateDto(0.5f, 0.5f, 0.5f), - country = CountryCode.PT, - administrativeAreaLevel1 = "PT-PT", - administrativeAreaLevel2 = "pt-admin-level-2-cleaned", - administrativeAreaLevel3 = "pt-admin-level-3-cleaned", - postalCode = "phys-postal-code-cleaned", - city = "city", - district = "district", - street = StreetDto( - name = "name", - houseNumber = "house-number", - houseNumberSupplement = "house-number-supplement", - milestone = "milestone", - direction = "direction", - namePrefix = "name-prefix", - additionalNamePrefix = "add-name-prefix", - nameSuffix = "name-suffix", - additionalNameSuffix = "add-name-suffix" - - ), - companyPostalCode = "comp-postal-code", - industrialZone = "industrial-zone", - building = "building", - floor = "floor", - door = "door" - ), - alternativePostalAddress = AlternativePostalAddressDto( - geographicCoordinates = GeoCoordinateDto(0.6f, 0.6f, 0.6f), - country = CountryCode.PT, - administrativeAreaLevel1 = "PT-PT", - postalCode = "postal-code-cleaned", - city = "alt-city-cleaned", - deliveryServiceNumber = "delivery-service-number-cleaned", - deliveryServiceQualifier = "delivery-service-qualifier-cleaned", - deliveryServiceType = DeliveryServiceType.PO_BOX - ), - confidenceCriteria = ConfidenceCriteriaDto( - sharedByOwner = false, - checkedByExternalDataSource = true, - numberOfSharingMembers = 4, - lastConfidenceCheckAt = LocalDateTime.of(2020, 4, 3, 2, 1), - nextConfidenceCheckAt = LocalDateTime.of(2028, 4, 3, 2, 1), - confidenceLevel = 5 - ) - ) - ) - -} \ No newline at end of file diff --git a/bpdm-gate/src/test/kotlin/org/eclipse/tractusx/bpdm/gate/util/MockAndAssertUtils.kt b/bpdm-gate/src/test/kotlin/org/eclipse/tractusx/bpdm/gate/util/MockAndAssertUtils.kt index 47f4260b1..7d02934b8 100644 --- a/bpdm-gate/src/test/kotlin/org/eclipse/tractusx/bpdm/gate/util/MockAndAssertUtils.kt +++ b/bpdm-gate/src/test/kotlin/org/eclipse/tractusx/bpdm/gate/util/MockAndAssertUtils.kt @@ -63,7 +63,7 @@ class MockAndAssertUtils @Autowired constructor( listOf( TaskClientStateDto( taskId = "0", - businessPartnerResult = null, + businessPartnerResult = BusinessPartnerGenericCommonValues.businessPartner1, processingState = TaskProcessingStateDto( resultState = ResultState.Pending, step = TaskStep.CleanAndSync, @@ -76,7 +76,7 @@ class MockAndAssertUtils @Autowired constructor( ), TaskClientStateDto( taskId = "1", - businessPartnerResult = null, + businessPartnerResult = BusinessPartnerGenericCommonValues.businessPartner1, processingState = TaskProcessingStateDto( resultState = ResultState.Pending, step = TaskStep.CleanAndSync, @@ -89,7 +89,7 @@ class MockAndAssertUtils @Autowired constructor( ), TaskClientStateDto( taskId = "2", - businessPartnerResult = null, + businessPartnerResult = BusinessPartnerGenericCommonValues.businessPartner1, processingState = TaskProcessingStateDto( resultState = ResultState.Pending, step = TaskStep.CleanAndSync, @@ -102,7 +102,7 @@ class MockAndAssertUtils @Autowired constructor( ), TaskClientStateDto( taskId = "3", - businessPartnerResult = null, + businessPartnerResult = BusinessPartnerGenericCommonValues.businessPartner1, processingState = TaskProcessingStateDto( resultState = ResultState.Pending, step = TaskStep.CleanAndSync, @@ -144,7 +144,7 @@ class MockAndAssertUtils @Autowired constructor( ), TaskClientStateDto( taskId = "1", - businessPartnerResult = null, + businessPartnerResult = BusinessPartnerGenericCommonValues.businessPartner1, processingState = TaskProcessingStateDto( resultState = ResultState.Error, step = TaskStep.CleanAndSync, diff --git a/bpdm-gate/src/test/resources/application-test.yml b/bpdm-gate/src/test/resources/application-test.yml index 641fc51d8..8f2784d3d 100644 --- a/bpdm-gate/src/test/resources/application-test.yml +++ b/bpdm-gate/src/test/resources/application-test.yml @@ -19,4 +19,10 @@ bpdm: bpn: - owner-bpn-l: BPNL000000000010 \ No newline at end of file + owner-bpn-l: BPNL000000000010 + tasks: + creation: + fromSharingMember: + cron: '-' + check: + cron: '-' \ No newline at end of file diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/AddressStateDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/AddressStateDto.kt deleted file mode 100644 index f5756536e..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/AddressStateDto.kt +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import org.eclipse.tractusx.bpdm.common.dto.IAddressStateDto -import org.eclipse.tractusx.bpdm.common.model.BusinessStateType -import java.time.LocalDateTime - -data class AddressStateDto( - override val validFrom: LocalDateTime?, - override val validTo: LocalDateTime?, - override val type: BusinessStateType - -) : IAddressStateDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/AlternativePostalAddressDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/AlternativePostalAddressDto.kt deleted file mode 100644 index a751b6925..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/AlternativePostalAddressDto.kt +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import com.neovisionaries.i18n.CountryCode -import org.eclipse.tractusx.bpdm.common.dto.GeoCoordinateDto -import org.eclipse.tractusx.bpdm.common.dto.IBaseAlternativePostalAddressDto -import org.eclipse.tractusx.bpdm.common.model.DeliveryServiceType - -data class AlternativePostalAddressDto( - - override val geographicCoordinates: GeoCoordinateDto? = null, - override val country: CountryCode? = null, - override val administrativeAreaLevel1: String? = null, - override val postalCode: String? = null, - override val city: String? = null, - override val deliveryServiceType: DeliveryServiceType? = null, - override val deliveryServiceQualifier: String? = null, - override val deliveryServiceNumber: String? = null - -) : IBaseAlternativePostalAddressDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BpnReference.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BpnReference.kt deleted file mode 100644 index b0bdd01dd..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BpnReference.kt +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import io.swagger.v3.oas.annotations.media.Schema - -@Schema(description = "A reference to the BPN of a business partner. Either by the BPN value itself or a BPN request identifier") -data class BpnReferenceDto( - - @get:Schema(description = "The value by which the BPN is referenced") - val referenceValue: String, - - @get:Schema(description = "The type by which to reference the BPN with") - val referenceType: BpnReferenceType -) - -enum class BpnReferenceType { - Bpn, - BpnRequestIdentifier -} diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartner.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartner.kt new file mode 100644 index 000000000..957d15667 --- /dev/null +++ b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartner.kt @@ -0,0 +1,282 @@ +/******************************************************************************* + * Copyright (c) 2021,2024 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 + ******************************************************************************/ + +package org.eclipse.tractusx.orchestrator.api.model + +import org.eclipse.tractusx.bpdm.common.model.BusinessStateType +import org.eclipse.tractusx.bpdm.common.model.DeliveryServiceType +import java.time.Instant + + +data class BusinessPartner( + val nameParts: List, + val owningCompany: String?, + val uncategorized: UncategorizedProperties, + val legalEntity: LegalEntity, + val site: Site?, + val additionalAddress: PostalAddress?, +){ + companion object{ + val empty = BusinessPartner( + nameParts = emptyList(), + owningCompany = null, + uncategorized = UncategorizedProperties.empty, + legalEntity = LegalEntity.empty, + site = null, + additionalAddress = null + ) + } + + val type: GoldenRecordType? = when{ + additionalAddress != null -> GoldenRecordType.Address + site != null -> GoldenRecordType.Site + legalEntity != LegalEntity.empty -> GoldenRecordType.LegalEntity + else -> null + } +} + +data class NamePart( + val name: String, + val type: NamePartType +) + +data class Identifier( + val value: String?, + val type: String?, + val issuingBody: String? +) + +data class BusinessState( + val validFrom: Instant?, + val validTo: Instant?, + val type: BusinessStateType? +) + +data class BpnReference( + val referenceValue: String?, + val desiredBpn: String?, + val referenceType: BpnReferenceType? +){ + companion object{ + val empty = BpnReference(null, null, null) + } +} + +data class PostalAddress( + val bpnReference: BpnReference, + val addressName: String?, + val identifiers: List, + val states: List, + val confidenceCriteria: ConfidenceCriteria, + val physicalAddress: PhysicalAddress, + val alternativeAddress: AlternativeAddress?, + val hasChanged: Boolean? +){ + companion object{ + val empty = PostalAddress( + bpnReference = BpnReference.empty, + addressName = null, + identifiers = emptyList(), + states = emptyList(), + confidenceCriteria = ConfidenceCriteria.empty, + physicalAddress = PhysicalAddress.empty, + alternativeAddress = null, + hasChanged = null + ) + } +} + +data class PhysicalAddress( + val geographicCoordinates: GeoCoordinate, + val country: String?, + val administrativeAreaLevel1: String?, + val administrativeAreaLevel2: String?, + val administrativeAreaLevel3: String?, + val postalCode: String?, + val city: String?, + val district: String?, + val street: Street, + val companyPostalCode: String?, + val industrialZone: String?, + val building: String?, + val floor: String?, + val door: String? +){ + companion object { + val empty: PhysicalAddress = PhysicalAddress( + GeoCoordinate.empty, null, null, null, + null, null, null, null, Street.empty, null, null, + null, null, null ) + } +} + +data class AlternativeAddress( + val geographicCoordinates: GeoCoordinate, + val country: String?, + val administrativeAreaLevel1: String?, + val postalCode: String?, + val city: String?, + val deliveryServiceType: DeliveryServiceType?, + val deliveryServiceQualifier: String?, + val deliveryServiceNumber: String? +){ + companion object{ + val empty: AlternativeAddress = AlternativeAddress( + GeoCoordinate.empty, null, null, + null, null, null, null, null) + } +} + +data class GeoCoordinate( + val longitude: Float?, + val latitude: Float?, + val altitude: Float? +){ + companion object{ + val empty: GeoCoordinate = GeoCoordinate(null, null, null) + } +} + +data class Street( + val name: String?, + val houseNumber: String?, + val houseNumberSupplement: String?, + val milestone: String?, + val direction: String?, + val namePrefix: String?, + val additionalNamePrefix: String?, + val nameSuffix: String?, + val additionalNameSuffix: String?, +){ + companion object{ + val empty: Street = Street(null, null, null, null, null, null, null, null, null) + } +} + +data class ConfidenceCriteria( + val sharedByOwner: Boolean?, + val checkedByExternalDataSource: Boolean?, + val numberOfSharingMembers: Int?, + val lastConfidenceCheckAt: Instant?, + val nextConfidenceCheckAt: Instant?, + val confidenceLevel: Int? +){ + companion object{ + val empty = ConfidenceCriteria( + sharedByOwner = null, + checkedByExternalDataSource = null, + numberOfSharingMembers = null, + lastConfidenceCheckAt = null, + nextConfidenceCheckAt = null, + confidenceLevel = null + ) + } +} + +data class AdditionalAddress( + val addressBpn: BpnReference, + val hasChanged: Boolean?, + val postalProperties: PostalAddress +) + +data class LegalEntity( + val bpnReference: BpnReference, + val legalName: String?, + val legalShortName: String?, + val legalForm: String?, + val identifiers: List, + val states: List, + val confidenceCriteria: ConfidenceCriteria, + val isCatenaXMemberData: Boolean?, + val hasChanged: Boolean?, + val legalAddress: PostalAddress +){ + companion object{ + val empty = LegalEntity( + bpnReference = BpnReference.empty, + legalName = null, + legalShortName = null, + legalForm = null, + identifiers = emptyList(), + states = emptyList(), + confidenceCriteria = ConfidenceCriteria.empty, + isCatenaXMemberData = null, + hasChanged = null, + legalAddress = PostalAddress.empty + ) + } +} + +data class Site( + val bpnReference: BpnReference, + val siteName: String?, + val states: List, + val confidenceCriteria: ConfidenceCriteria, + val hasChanged: Boolean?, + val siteMainAddress: PostalAddress? +){ + companion object{ + val empty = Site( + bpnReference = BpnReference.empty, + siteName = null, + states = emptyList(), + confidenceCriteria = ConfidenceCriteria.empty, + hasChanged = null, + siteMainAddress = PostalAddress.empty + ) + } + + val siteMainIsLegalAddress = siteMainAddress == null +} + + +data class UncategorizedProperties( + val nameParts: List, + val identifiers: List, + val states: List, + val address: PostalAddress? +){ + companion object{ + val empty = UncategorizedProperties( + nameParts = emptyList(), + identifiers = emptyList(), + states = emptyList(), + address = null + ) + } +} + +enum class NamePartType{ + LegalName, + ShortName, + LegalForm, + SiteName, + AddressName +} + +enum class GoldenRecordType{ + LegalEntity, + Site, + Address +} + +enum class BpnReferenceType { + Bpn, + BpnRequestIdentifier +} \ No newline at end of file diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerClassificationDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerClassificationDto.kt deleted file mode 100644 index a0b8fad56..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerClassificationDto.kt +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import io.swagger.v3.oas.annotations.media.Schema -import org.eclipse.tractusx.bpdm.common.dto.IBusinessPartnerClassificationDto -import org.eclipse.tractusx.bpdm.common.model.ClassificationType - -@Schema(requiredProperties = ["type"]) -data class BusinessPartnerClassificationDto( - - override val type: ClassificationType, - override val code: String?, - override val value: String? - -) : IBusinessPartnerClassificationDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerFullDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerFullDto.kt deleted file mode 100644 index f1efff586..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerFullDto.kt +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import io.swagger.v3.oas.annotations.media.Schema - -@Schema(description = "Business partner data in full representation, consisting of generic data as well as its L/S/A representation.") -data class BusinessPartnerFullDto( - - @get:Schema(description = "The business partner data in generic representation", required = true) - val generic: BusinessPartnerGenericDto, - - @get:Schema(description = "The legal entity part of this business partner data") - val legalEntity: LegalEntityDto? = null, - - @get:Schema(description = "The site part of this business partner data") - val site: SiteDto? = null, - - @get:Schema(description = "The address part of this business partner data") - val address: LogisticAddressDto? = null -) diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerGenericDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerGenericDto.kt deleted file mode 100644 index d0dcf5ea5..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerGenericDto.kt +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import io.swagger.v3.oas.annotations.media.Schema -import org.eclipse.tractusx.bpdm.common.dto.* - - -@Schema( - description = "Generic business partner with external id" -) -data class BusinessPartnerGenericDto( - override val nameParts: List = emptyList(), - override val identifiers: Collection = emptyList(), - override val states: Collection = emptyList(), - override val roles: Collection = emptyList(), - override val legalEntity: LegalEntityRepresentation = LegalEntityRepresentation(), - override val site: SiteRepresentation = SiteRepresentation(), - override val address: AddressRepresentation = AddressRepresentation(), - @get:Schema(description = "The BPNL of the company sharing and claiming this business partner as its own") - val ownerBpnL: String? = null -) : IBaseBusinessPartnerDto - -data class LegalEntityRepresentation( - override val legalEntityBpn: String? = null, - override val legalName: String? = null, - override val shortName: String? = null, - override val legalForm: String? = null, - val confidenceCriteria: ConfidenceCriteriaDto? = null, - override val states: Collection = emptyList() -) : IBaseLegalEntityRepresentation - -data class SiteRepresentation( - override val siteBpn: String? = null, - override val name: String? = null, - val confidenceCriteria: ConfidenceCriteriaDto? = null, - override val states: Collection = emptyList() -) : IBaseSiteRepresentation - -data class AddressRepresentation( - override val addressBpn: String? = null, - override val name: String? = null, - override val addressType: AddressType? = null, - override val physicalPostalAddress: PhysicalPostalAddressDto? = null, - override val alternativePostalAddress: AlternativePostalAddressDto? = null, - val confidenceCriteria: ConfidenceCriteriaDto? = null, - override val states: Collection = emptyList() -) : IBaseAddressRepresentation - - diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerIdentifierDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerIdentifierDto.kt deleted file mode 100644 index 2db46ece0..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerIdentifierDto.kt +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import org.eclipse.tractusx.bpdm.common.dto.IBusinessPartnerIdentifierDto - -data class BusinessPartnerIdentifierDto( - - override val type: String?, - override val value: String?, - override val issuingBody: String? - -) : IBusinessPartnerIdentifierDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerStateDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerStateDto.kt deleted file mode 100644 index 59133f8ca..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/BusinessPartnerStateDto.kt +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import org.eclipse.tractusx.bpdm.common.dto.IBusinessPartnerStateDto -import org.eclipse.tractusx.bpdm.common.model.BusinessStateType -import java.time.LocalDateTime - -data class BusinessPartnerStateDto( - - override val validFrom: LocalDateTime?, - override val validTo: LocalDateTime?, - override val type: BusinessStateType? - -) : IBusinessPartnerStateDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/ConfidenceCriteriaDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/ConfidenceCriteriaDto.kt deleted file mode 100644 index b9bf8cac9..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/ConfidenceCriteriaDto.kt +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import org.eclipse.tractusx.bpdm.common.dto.IConfidenceCriteriaDto -import java.time.LocalDateTime - -data class ConfidenceCriteriaDto( - override val sharedByOwner: Boolean, - override val checkedByExternalDataSource: Boolean, - override val numberOfSharingMembers: Int, - override val lastConfidenceCheckAt: LocalDateTime, - override val nextConfidenceCheckAt: LocalDateTime, - override val confidenceLevel: Int -) : IConfidenceCriteriaDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityClassificationDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityClassificationDto.kt deleted file mode 100644 index 2fe266cd6..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityClassificationDto.kt +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import io.swagger.v3.oas.annotations.media.Schema -import org.eclipse.tractusx.bpdm.common.dto.ILegalEntityClassificationDto -import org.eclipse.tractusx.bpdm.common.dto.openapidescription.ClassificationDescription -import org.eclipse.tractusx.bpdm.common.model.ClassificationType - -@Schema(description = ClassificationDescription.header) -data class LegalEntityClassificationDto( - - override val type: ClassificationType, - override val code: String?, - override val value: String? - -) : ILegalEntityClassificationDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityDto.kt deleted file mode 100644 index a26ab8812..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityDto.kt +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import io.swagger.v3.oas.annotations.media.Schema -import org.eclipse.tractusx.bpdm.common.dto.IBaseLegalEntityDto -import org.eclipse.tractusx.bpdm.common.dto.openapidescription.LegalEntityDescription - -data class LegalEntityDto( - - @get:Schema(description = "A reference to the BPNL of this legal entity. Either by the BPN value itself or a BPN request identifier.") - val bpnLReference: BpnReferenceDto? = null, - - @get:Schema(description = "Whether this legal entity data is different from its golden record counterpart in the Pool") - val hasChanged: Boolean? = null, - - @get:Schema(description = LegalEntityDescription.legalName) - val legalName: String? = null, - - override val legalShortName: String? = null, - - override val identifiers: Collection = emptyList(), - - override val legalForm: String? = null, - - override val states: Collection = emptyList(), - - val legalAddress: LogisticAddressDto? = null, - - override val confidenceCriteria: ConfidenceCriteriaDto? = null, - - override val isCatenaXMemberData: Boolean - -) : IBaseLegalEntityDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityIdentifierDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityIdentifierDto.kt deleted file mode 100644 index 898c4f5b3..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityIdentifierDto.kt +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import org.eclipse.tractusx.bpdm.common.dto.ILegalEntityIdentifierDto - -data class LegalEntityIdentifierDto( - - override val value: String, - override val type: String, - override val issuingBody: String? - -) : ILegalEntityIdentifierDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityStateDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityStateDto.kt deleted file mode 100644 index 9e4fb3723..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LegalEntityStateDto.kt +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import org.eclipse.tractusx.bpdm.common.dto.ILegalEntityStateDto -import org.eclipse.tractusx.bpdm.common.model.BusinessStateType -import java.time.LocalDateTime - -data class LegalEntityStateDto( - override val validFrom: LocalDateTime?, - override val validTo: LocalDateTime?, - override val type: BusinessStateType - -) : ILegalEntityStateDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LogisticAddressDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LogisticAddressDto.kt deleted file mode 100644 index f922207a4..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/LogisticAddressDto.kt +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import io.swagger.v3.oas.annotations.media.Schema -import org.eclipse.tractusx.bpdm.common.dto.IBaseLogisticAddressDto -import org.eclipse.tractusx.bpdm.common.dto.openapidescription.LogisticAddressDescription - -data class LogisticAddressDto( - - @get:Schema(description = "A reference to the BPNA of this address. Either by the BPN value itself or a BPN request identifier.") - val bpnAReference: BpnReferenceDto? = null, - - @get:Schema(description = "Whether this address data is different from its golden record counterpart in the Pool") - val hasChanged: Boolean? = null, - - @get:Schema(description = LogisticAddressDescription.name) - val name: String? = null, - - override val states: Collection = emptyList(), - - override val identifiers: Collection = emptyList(), - - override val physicalPostalAddress: PhysicalPostalAddressDto? = null, - - override val alternativePostalAddress: AlternativePostalAddressDto? = null, - - override val confidenceCriteria: ConfidenceCriteriaDto? = null - -) : IBaseLogisticAddressDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/PhysicalPostalAddressDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/PhysicalPostalAddressDto.kt deleted file mode 100644 index a73245014..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/PhysicalPostalAddressDto.kt +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import com.neovisionaries.i18n.CountryCode -import org.eclipse.tractusx.bpdm.common.dto.GeoCoordinateDto -import org.eclipse.tractusx.bpdm.common.dto.IBasePhysicalPostalAddressDto - -data class PhysicalPostalAddressDto( - - override val geographicCoordinates: GeoCoordinateDto? = null, - override val country: CountryCode? = null, - override val administrativeAreaLevel1: String? = null, - override val administrativeAreaLevel2: String? = null, - override val administrativeAreaLevel3: String? = null, - override val postalCode: String? = null, - override val city: String? = null, - override val district: String? = null, - override val street: StreetDto? = null, - override val companyPostalCode: String? = null, - override val industrialZone: String? = null, - override val building: String? = null, - override val floor: String? = null, - override val door: String? = null - -) : IBasePhysicalPostalAddressDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/PostalAddressDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/PostalAddressDto.kt deleted file mode 100644 index ca80238dc..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/PostalAddressDto.kt +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import org.eclipse.tractusx.bpdm.common.dto.AddressType -import org.eclipse.tractusx.bpdm.common.dto.IBaseBusinessPartnerPostalAddressDto - -data class PostalAddressDto( - - override val addressType: AddressType? = null, - override val physicalPostalAddress: PhysicalPostalAddressDto? = null, - override val alternativePostalAddress: AlternativePostalAddressDto? = null - -) : IBaseBusinessPartnerPostalAddressDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/SiteDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/SiteDto.kt deleted file mode 100644 index 54d4c26b0..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/SiteDto.kt +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import io.swagger.v3.oas.annotations.media.Schema -import org.eclipse.tractusx.bpdm.common.dto.IBaseSiteDto - -data class SiteDto( - - @get:Schema(description = "A reference to the BPNS of this site. Either by the BPN value itself or a BPN request identifier.") - val bpnSReference: BpnReferenceDto? = null, - - @get:Schema(description = "Whether this site data is different from its golden record counterpart in the Pool") - val hasChanged: Boolean? = null, - - override val name: String? = null, - override val states: Collection = emptyList(), - - val mainAddress: LogisticAddressDto? = null, - - override val confidenceCriteria: ConfidenceCriteriaDto? = null - -) : IBaseSiteDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/SiteStateDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/SiteStateDto.kt deleted file mode 100644 index cfec29981..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/SiteStateDto.kt +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import org.eclipse.tractusx.bpdm.common.dto.ISiteStateDto -import org.eclipse.tractusx.bpdm.common.model.BusinessStateType -import java.time.LocalDateTime - -data class SiteStateDto( - override val validFrom: LocalDateTime?, - override val validTo: LocalDateTime?, - override val type: BusinessStateType - -) : ISiteStateDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/StreetDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/StreetDto.kt deleted file mode 100644 index 4cab8bf2a..000000000 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/StreetDto.kt +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.orchestrator.api.model - -import org.eclipse.tractusx.bpdm.common.dto.IStreetDetailedDto - -data class StreetDto( - override val name: String? = null, - override val houseNumber: String? = null, - override val houseNumberSupplement: String? = null, - override val milestone: String? = null, - override val direction: String? = null, - override val namePrefix: String? = null, - override val additionalNamePrefix: String? = null, - override val nameSuffix: String? = null, - override val additionalNameSuffix: String? = null, - -) : IStreetDetailedDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskClientStateDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskClientStateDto.kt index e5fe90f3f..99365a0b6 100644 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskClientStateDto.kt +++ b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskClientStateDto.kt @@ -28,7 +28,7 @@ data class TaskClientStateDto( @get:Schema(required = true) val taskId: String, - val businessPartnerResult: BusinessPartnerGenericDto?, + val businessPartnerResult: BusinessPartner, @get:Schema(required = true) val processingState: TaskProcessingStateDto diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskCreateRequest.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskCreateRequest.kt index 2b2701168..f4e7280e2 100644 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskCreateRequest.kt +++ b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskCreateRequest.kt @@ -29,5 +29,5 @@ data class TaskCreateRequest( val mode: TaskMode, @get:ArraySchema(arraySchema = Schema(description = "The list of business partner data to be processed")) - val businessPartners: List + val businessPartners: List ) diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskStepReservationEntryDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskStepReservationEntryDto.kt index 89bffc51e..a67baf2e8 100644 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskStepReservationEntryDto.kt +++ b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskStepReservationEntryDto.kt @@ -29,9 +29,9 @@ data class TaskStepReservationEntryDto( val taskId: String, @get:Schema(description = "The business partner data to process") - val businessPartner: BusinessPartnerFullDto + val businessPartner: BusinessPartner ) : RequestWithKey { - override fun getRequestKey(): String? { + override fun getRequestKey(): String { return taskId } } diff --git a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskStepResultEntryDto.kt b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskStepResultEntryDto.kt index 7564e7137..76ff96fbd 100644 --- a/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskStepResultEntryDto.kt +++ b/bpdm-orchestrator-api/src/main/kotlin/org/eclipse/tractusx/orchestrator/api/model/TaskStepResultEntryDto.kt @@ -30,7 +30,7 @@ data class TaskStepResultEntryDto( val taskId: String, @get:Schema(description = "The actual result in form of business partner data. Maybe null if an error occurred during processing of this task.") - val businessPartner: BusinessPartnerFullDto? = null, + val businessPartner: BusinessPartner, @get:ArraySchema(arraySchema = Schema(description = "Errors that occurred during processing of this task")) val errors: List = emptyList() diff --git a/bpdm-orchestrator/src/main/kotlin/org/eclipse/tractusx/bpdm/orchestrator/model/GoldenRecordTask.kt b/bpdm-orchestrator/src/main/kotlin/org/eclipse/tractusx/bpdm/orchestrator/model/GoldenRecordTask.kt index ac534e070..0bdbd58ca 100644 --- a/bpdm-orchestrator/src/main/kotlin/org/eclipse/tractusx/bpdm/orchestrator/model/GoldenRecordTask.kt +++ b/bpdm-orchestrator/src/main/kotlin/org/eclipse/tractusx/bpdm/orchestrator/model/GoldenRecordTask.kt @@ -19,10 +19,10 @@ package org.eclipse.tractusx.bpdm.orchestrator.model -import org.eclipse.tractusx.orchestrator.api.model.BusinessPartnerFullDto +import org.eclipse.tractusx.orchestrator.api.model.BusinessPartner data class GoldenRecordTask( val taskId: String, - var businessPartner: BusinessPartnerFullDto, + var businessPartner: BusinessPartner, val processingState: TaskProcessingState ) diff --git a/bpdm-orchestrator/src/main/kotlin/org/eclipse/tractusx/bpdm/orchestrator/service/GoldenRecordTaskService.kt b/bpdm-orchestrator/src/main/kotlin/org/eclipse/tractusx/bpdm/orchestrator/service/GoldenRecordTaskService.kt index 290093bf6..6f936cb01 100644 --- a/bpdm-orchestrator/src/main/kotlin/org/eclipse/tractusx/bpdm/orchestrator/service/GoldenRecordTaskService.kt +++ b/bpdm-orchestrator/src/main/kotlin/org/eclipse/tractusx/bpdm/orchestrator/service/GoldenRecordTaskService.kt @@ -26,6 +26,7 @@ import org.eclipse.tractusx.bpdm.orchestrator.exception.BpdmTaskNotFoundExceptio import org.eclipse.tractusx.bpdm.orchestrator.model.GoldenRecordTask import org.eclipse.tractusx.bpdm.orchestrator.model.TaskProcessingState import org.eclipse.tractusx.orchestrator.api.model.* +import org.eclipse.tractusx.orchestrator.api.model.BusinessPartner import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Service import java.time.Instant @@ -141,24 +142,18 @@ class GoldenRecordTaskService( private fun initTask( createRequest: TaskCreateRequest, - businessPartnerGeneric: BusinessPartnerGenericDto + businessPartner: BusinessPartner ) = GoldenRecordTask( taskId = UUID.randomUUID().toString(), - businessPartner = BusinessPartnerFullDto( - generic = businessPartnerGeneric - ), + businessPartner = businessPartner, processingState = goldenRecordTaskStateMachine.initProcessingState(createRequest.mode) ) private fun toTaskClientStateDto(task: GoldenRecordTask): TaskClientStateDto { - val businessPartnerResult = when (task.processingState.resultState) { - ResultState.Success -> task.businessPartner.generic - else -> null - } return TaskClientStateDto( taskId = task.taskId, processingState = toTaskProcessingStateDto(task.processingState), - businessPartnerResult = businessPartnerResult + businessPartnerResult = task.businessPartner ) } diff --git a/bpdm-orchestrator/src/main/kotlin/org/eclipse/tractusx/bpdm/orchestrator/service/GoldenRecordTaskStateMachine.kt b/bpdm-orchestrator/src/main/kotlin/org/eclipse/tractusx/bpdm/orchestrator/service/GoldenRecordTaskStateMachine.kt index 5c9dda112..3220cbf09 100644 --- a/bpdm-orchestrator/src/main/kotlin/org/eclipse/tractusx/bpdm/orchestrator/service/GoldenRecordTaskStateMachine.kt +++ b/bpdm-orchestrator/src/main/kotlin/org/eclipse/tractusx/bpdm/orchestrator/service/GoldenRecordTaskStateMachine.kt @@ -25,6 +25,7 @@ import org.eclipse.tractusx.bpdm.orchestrator.exception.BpdmIllegalStateExceptio import org.eclipse.tractusx.bpdm.orchestrator.model.GoldenRecordTask import org.eclipse.tractusx.bpdm.orchestrator.model.TaskProcessingState import org.eclipse.tractusx.orchestrator.api.model.* +import org.eclipse.tractusx.orchestrator.api.model.BusinessPartner import org.springframework.stereotype.Service import java.time.Instant @@ -70,7 +71,7 @@ class GoldenRecordTaskStateMachine( state.taskModifiedAt = now } - fun doResolveTaskToSuccess(task: GoldenRecordTask, step: TaskStep, resultBusinessPartner: BusinessPartnerFullDto) { + fun doResolveTaskToSuccess(task: GoldenRecordTask, step: TaskStep, resultBusinessPartner: BusinessPartner) { logger.debug { "Executing doResolveTaskToSuccess() with parameters $task // $step and $resultBusinessPartner" } val state = task.processingState val now = Instant.now() diff --git a/bpdm-orchestrator/src/main/resources/application.yml b/bpdm-orchestrator/src/main/resources/application.yml index 0b8dc7133..51be8b3bc 100644 --- a/bpdm-orchestrator/src/main/resources/application.yml +++ b/bpdm-orchestrator/src/main/resources/application.yml @@ -86,10 +86,6 @@ server: # Change default port to avoid clash with other BPDM applications port: 8085 spring: - profiles: - group: - # BPDM common shortcut to remove all authentication configuration - no-auth: no-api-auth security: oauth2: resourceserver: diff --git a/bpdm-orchestrator/src/test/kotlin/org/eclipse/tractusx/bpdm/orchestrator/controller/GoldenRecordTaskControllerIT.kt b/bpdm-orchestrator/src/test/kotlin/org/eclipse/tractusx/bpdm/orchestrator/controller/GoldenRecordTaskControllerIT.kt index a50db0715..5f59bdbb9 100644 --- a/bpdm-orchestrator/src/test/kotlin/org/eclipse/tractusx/bpdm/orchestrator/controller/GoldenRecordTaskControllerIT.kt +++ b/bpdm-orchestrator/src/test/kotlin/org/eclipse/tractusx/bpdm/orchestrator/controller/GoldenRecordTaskControllerIT.kt @@ -24,9 +24,10 @@ import org.assertj.core.api.ThrowableAssert import org.assertj.core.data.TemporalUnitOffset import org.eclipse.tractusx.bpdm.orchestrator.config.TaskConfigProperties import org.eclipse.tractusx.bpdm.orchestrator.service.GoldenRecordTaskStorage -import org.eclipse.tractusx.bpdm.test.testdata.gate.BusinessPartnerGenericCommonValues +import org.eclipse.tractusx.bpdm.test.testdata.orchestrator.BusinessPartnerTestDataFactory import org.eclipse.tractusx.orchestrator.api.client.OrchestrationApiClient import org.eclipse.tractusx.orchestrator.api.model.* +import org.eclipse.tractusx.orchestrator.api.model.BusinessPartner import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired @@ -54,6 +55,10 @@ class GoldenRecordTaskControllerIT @Autowired constructor( val goldenRecordTaskStorage: GoldenRecordTaskStorage ) { + private val testDataFactory = BusinessPartnerTestDataFactory() + private val defaultBusinessPartner1 = testDataFactory.createFullBusinessPartner("BP1") + private val defaultBusinessPartner2 = testDataFactory.createFullBusinessPartner("BP2") + @BeforeEach fun cleanUp() { goldenRecordTaskStorage.clear() @@ -76,7 +81,6 @@ class GoldenRecordTaskControllerIT @Autowired constructor( assertThat(createdTasks[0].taskId).isNotEqualTo(createdTasks[1].taskId) createdTasks.forEach { stateDto -> - assertThat(stateDto.businessPartnerResult).isNull() val processingState = stateDto.processingState assertProcessingStateDto(processingState, ResultState.Pending, TaskStep.CleanAndSync, StepState.Queued) assertThat(processingState.errors).isEqualTo(emptyList()) @@ -129,11 +133,8 @@ class GoldenRecordTaskControllerIT @Autowired constructor( assertThat(reservedTasks.map { it.taskId }).isEqualTo(createdTasks.map { it.taskId }) // ...and with the correct business partner information - assertThat(reservedTasks[0].businessPartner.generic).isEqualTo(BusinessPartnerGenericCommonValues.businessPartner1) - assertThat(reservedTasks[1].businessPartner.generic).isEqualTo(BusinessPartnerGenericCommonValues.businessPartner2) - assertThat(reservedTasks[1].businessPartner.legalEntity).isNull() - assertThat(reservedTasks[1].businessPartner.site).isNull() - assertThat(reservedTasks[1].businessPartner.address).isNull() + assertThat(reservedTasks[0].businessPartner).isEqualTo(defaultBusinessPartner1) + assertThat(reservedTasks[1].businessPartner).isEqualTo(defaultBusinessPartner2) // trying to reserve more tasks returns no additional entries val reservationResponse2 = reserveTasks(TaskStep.CleanAndSync) @@ -143,7 +144,6 @@ class GoldenRecordTaskControllerIT @Autowired constructor( val statesResponse = searchTaskStates(reservedTasks.map { it.taskId }) assertThat(statesResponse.tasks.size).isEqualTo(2) statesResponse.tasks.forEach { stateDto -> - assertThat(stateDto.businessPartnerResult).isNull() val processingState = stateDto.processingState // stepState should have changed to Reserved assertProcessingStateDto(processingState, ResultState.Pending, TaskStep.CleanAndSync, StepState.Reserved) @@ -187,7 +187,7 @@ class GoldenRecordTaskControllerIT @Autowired constructor( // reserve task for step==CleanAndSync val reservedTasks1 = reserveTasks(TaskStep.CleanAndSync, 1).reservedTasks val taskId = reservedTasks1.single().taskId - assertThat(reservedTasks1[0].businessPartner.generic).isEqualTo(BusinessPartnerGenericCommonValues.businessPartner1) + assertThat(reservedTasks1[0].businessPartner).isEqualTo(defaultBusinessPartner1) // now in stepState==Reserved assertProcessingStateDto( @@ -196,10 +196,10 @@ class GoldenRecordTaskControllerIT @Autowired constructor( ) // resolve task - val businessPartnerFull1 = BusinessPartnerGenericCommonValues.businessPartner2Full + val businessPartnerResolved1 = testDataFactory.createFullBusinessPartner("Resolved BP1") val resultEntry1 = TaskStepResultEntryDto( taskId = taskId, - businessPartner = businessPartnerFull1 + businessPartner = businessPartnerResolved1 ) resolveTasks(TaskStep.CleanAndSync, listOf(resultEntry1)) @@ -212,7 +212,7 @@ class GoldenRecordTaskControllerIT @Autowired constructor( // reserve task for step==PoolSync val reservedTasks2 = reserveTasks(TaskStep.PoolSync, 3).reservedTasks assertThat(reservedTasks2.size).isEqualTo(1) - assertThat(reservedTasks2.single().businessPartner).isEqualTo(businessPartnerFull1) + assertThat(reservedTasks2.single().businessPartner).isEqualTo(businessPartnerResolved1) // now in stepState==Queued val stateDto = searchTaskStates(listOf(taskId)).tasks.single() @@ -220,19 +220,12 @@ class GoldenRecordTaskControllerIT @Autowired constructor( stateDto.processingState, ResultState.Pending, TaskStep.PoolSync, StepState.Reserved ) - assertThat(stateDto.businessPartnerResult).isNull() // resolve task again - val businessPartnerFull2 = businessPartnerFull1.copy( - generic = with(businessPartnerFull1.generic) { - copy( - legalEntity = legalEntity.copy(legalEntityBpn = "BPNL-test") - ) - } - ) + val businessPartnerResolved2 = with(businessPartnerResolved1){ copy(legalEntity = with(legalEntity){ copy(bpnReference = bpnReference.copy(referenceValue = "BPNL-test" )) }) } val resultEntry2 = TaskStepResultEntryDto( taskId = taskId, - businessPartner = businessPartnerFull2 + businessPartner = businessPartnerResolved2 ) resolveTasks(TaskStep.PoolSync, listOf(resultEntry2)) @@ -243,7 +236,7 @@ class GoldenRecordTaskControllerIT @Autowired constructor( ResultState.Success, TaskStep.PoolSync, StepState.Success ) // check returned BP - assertThat(finalStateDto.businessPartnerResult).isEqualTo(businessPartnerFull2.generic) + assertThat(finalStateDto.businessPartnerResult).isEqualTo(businessPartnerResolved2) } /** @@ -267,6 +260,7 @@ class GoldenRecordTaskControllerIT @Autowired constructor( val errorDto = TaskErrorDto(TaskErrorType.Unspecified, "Unfortunate event") val resultEntry = TaskStepResultEntryDto( taskId = taskId, + businessPartner = defaultBusinessPartner1, errors = listOf(errorDto) ) resolveTasks(TaskStep.CleanAndSync, listOf(resultEntry)) @@ -277,7 +271,7 @@ class GoldenRecordTaskControllerIT @Autowired constructor( stateDto.processingState, ResultState.Error, TaskStep.CleanAndSync, StepState.Error ) - assertThat(stateDto.businessPartnerResult).isNull() + // expect error in response assertThat(stateDto.processingState.errors.single()).isEqualTo(errorDto) } @@ -290,10 +284,10 @@ class GoldenRecordTaskControllerIT @Autowired constructor( fun `expect exception on requesting too many cleaning tasks`() { // Create entries above the upsert limit of 3 val businessPartners = listOf( - BusinessPartnerGenericCommonValues.businessPartner1, - BusinessPartnerGenericCommonValues.businessPartner1, - BusinessPartnerGenericCommonValues.businessPartner1, - BusinessPartnerGenericCommonValues.businessPartner1 + testDataFactory.createFullBusinessPartner("BP1"), + testDataFactory.createFullBusinessPartner("BP2"), + testDataFactory.createFullBusinessPartner("BP3"), + testDataFactory.createFullBusinessPartner("BP4") ) assertBadRequestException { @@ -321,7 +315,7 @@ class GoldenRecordTaskControllerIT @Autowired constructor( fun `expect exception on posting too many task results`() { val validResultEntry = TaskStepResultEntryDto( taskId = "0", - businessPartner = null, + businessPartner = defaultBusinessPartner1, errors = listOf(TaskErrorDto(type = TaskErrorType.Unspecified, description = "Description")) ) @@ -362,19 +356,8 @@ class GoldenRecordTaskControllerIT @Autowired constructor( TaskStep.CleanAndSync, listOf( TaskStepResultEntryDto( - taskId = "WRONG-ID" - ) - ) - ) - } - - // post correct task id but empty content - assertBadRequestException { - resolveTasks( - TaskStep.CleanAndSync, - listOf( - TaskStepResultEntryDto( - taskId = tasksIds[0] + taskId = "WRONG-ID", + businessPartner = defaultBusinessPartner1 ) ) ) @@ -387,7 +370,7 @@ class GoldenRecordTaskControllerIT @Autowired constructor( listOf( TaskStepResultEntryDto( taskId = tasksIds[0], - businessPartner = BusinessPartnerGenericCommonValues.businessPartner1Full + businessPartner = defaultBusinessPartner1 ) ) ) @@ -399,7 +382,7 @@ class GoldenRecordTaskControllerIT @Autowired constructor( listOf( TaskStepResultEntryDto( taskId = tasksIds[0], - businessPartner = BusinessPartnerGenericCommonValues.businessPartner1Full + businessPartner = defaultBusinessPartner1 ) ) ) @@ -411,7 +394,7 @@ class GoldenRecordTaskControllerIT @Autowired constructor( listOf( TaskStepResultEntryDto( taskId = tasksIds[0], - businessPartner = BusinessPartnerGenericCommonValues.businessPartner1Full + businessPartner = defaultBusinessPartner1 ) ) ) @@ -422,8 +405,10 @@ class GoldenRecordTaskControllerIT @Autowired constructor( TaskStep.CleanAndSync, listOf( TaskStepResultEntryDto( - tasksIds[1], errors = listOf( - TaskErrorDto(type = TaskErrorType.Unspecified, "ERROR") + tasksIds[1], + businessPartner = defaultBusinessPartner1, + errors = listOf( + TaskErrorDto(type = TaskErrorType.Unspecified, description = "ERROR") ) ) ) @@ -469,7 +454,7 @@ class GoldenRecordTaskControllerIT @Autowired constructor( @Test fun `wait for task retention timeout after success`() { // create single task in UpdateFromPool mode (only one step) - createTasks(TaskMode.UpdateFromPool, listOf(BusinessPartnerGenericCommonValues.businessPartner1)) + createTasks(TaskMode.UpdateFromPool, listOf(defaultBusinessPartner1)) // reserve task val reservedTask = reserveTasks(TaskStep.Clean).reservedTasks.single() @@ -502,7 +487,7 @@ class GoldenRecordTaskControllerIT @Autowired constructor( @Test fun `wait for task retention timeout after error`() { // create single task in UpdateFromPool mode (only one step) - createTasks(TaskMode.UpdateFromPool, listOf(BusinessPartnerGenericCommonValues.businessPartner1)) + createTasks(TaskMode.UpdateFromPool, listOf(defaultBusinessPartner1)) // reserve task val reservedTask = reserveTasks(TaskStep.Clean).reservedTasks.single() @@ -533,11 +518,11 @@ class GoldenRecordTaskControllerIT @Autowired constructor( assertThat(foundTasks.size).isZero() } - private fun createTasks(mode: TaskMode = TaskMode.UpdateFromSharingMember, businessPartners: List? = null): TaskCreateResponse = + private fun createTasks(mode: TaskMode = TaskMode.UpdateFromSharingMember, businessPartners: List? = null): TaskCreateResponse = orchestratorClient.goldenRecordTasks.createTasks( TaskCreateRequest( mode = mode, - businessPartners = businessPartners ?: listOf(BusinessPartnerGenericCommonValues.businessPartner1, BusinessPartnerGenericCommonValues.businessPartner2) + businessPartners = businessPartners ?: listOf(defaultBusinessPartner1, defaultBusinessPartner2) ) ) diff --git a/bpdm-orchestrator/src/test/kotlin/org/eclipse/tractusx/bpdm/orchestrator/service/GoldenRecordTaskStateMachineIT.kt b/bpdm-orchestrator/src/test/kotlin/org/eclipse/tractusx/bpdm/orchestrator/service/GoldenRecordTaskStateMachineIT.kt index d6141964c..ec004b36e 100644 --- a/bpdm-orchestrator/src/test/kotlin/org/eclipse/tractusx/bpdm/orchestrator/service/GoldenRecordTaskStateMachineIT.kt +++ b/bpdm-orchestrator/src/test/kotlin/org/eclipse/tractusx/bpdm/orchestrator/service/GoldenRecordTaskStateMachineIT.kt @@ -27,7 +27,7 @@ import org.eclipse.tractusx.bpdm.orchestrator.config.TaskConfigProperties import org.eclipse.tractusx.bpdm.orchestrator.exception.BpdmIllegalStateException import org.eclipse.tractusx.bpdm.orchestrator.model.GoldenRecordTask import org.eclipse.tractusx.bpdm.orchestrator.model.TaskProcessingState -import org.eclipse.tractusx.bpdm.test.testdata.gate.BusinessPartnerGenericCommonValues +import org.eclipse.tractusx.bpdm.test.testdata.orchestrator.BusinessPartnerTestDataFactory import org.eclipse.tractusx.orchestrator.api.model.* import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired @@ -50,6 +50,10 @@ class GoldenRecordTaskStateMachineIT @Autowired constructor( val taskConfigProperties: TaskConfigProperties ) { + private val testDataFactory = BusinessPartnerTestDataFactory() + + private val businessPartnerFull = testDataFactory.createFullBusinessPartner("full") + /** * WHEN creating an initial TaskProcessingState * THEN expect the correct content @@ -94,12 +98,12 @@ class GoldenRecordTaskStateMachineIT @Autowired constructor( }.isInstanceOf(BpdmIllegalStateException::class.java) // 1st resolve - goldenRecordTaskStateMachine.doResolveTaskToSuccess(task, TaskStep.CleanAndSync, BusinessPartnerGenericCommonValues.businessPartner1Full) + goldenRecordTaskStateMachine.doResolveTaskToSuccess(task, TaskStep.CleanAndSync, businessPartnerFull) assertProcessingStateDto(task.processingState, ResultState.Pending, TaskStep.PoolSync, StepState.Queued) // Can't resolve again! assertThatThrownBy { - goldenRecordTaskStateMachine.doResolveTaskToSuccess(task, TaskStep.CleanAndSync, BusinessPartnerGenericCommonValues.businessPartner1Full) + goldenRecordTaskStateMachine.doResolveTaskToSuccess(task, TaskStep.CleanAndSync, businessPartnerFull) }.isInstanceOf(BpdmIllegalStateException::class.java) // 2nd reserve @@ -108,14 +112,14 @@ class GoldenRecordTaskStateMachineIT @Autowired constructor( // Can't resolve with wrong step (CleanAndSync)! assertThatThrownBy { - goldenRecordTaskStateMachine.doResolveTaskToSuccess(task, TaskStep.CleanAndSync, BusinessPartnerGenericCommonValues.businessPartner1Full) + goldenRecordTaskStateMachine.doResolveTaskToSuccess(task, TaskStep.CleanAndSync, businessPartnerFull) }.isInstanceOf(BpdmIllegalStateException::class.java) // taskPendingTimeout is still the same assertThat(task.processingState.taskPendingTimeout).isEqualTo(taskPendingTimeout) // 2nd and final resolve - goldenRecordTaskStateMachine.doResolveTaskToSuccess(task, TaskStep.PoolSync, BusinessPartnerGenericCommonValues.businessPartner1Full) + goldenRecordTaskStateMachine.doResolveTaskToSuccess(task, TaskStep.PoolSync, businessPartnerFull) assertProcessingStateDto(task.processingState, ResultState.Success, TaskStep.PoolSync, StepState.Success) // taskRetentionTimeout has been set; taskPendingTimeout has been reset @@ -157,7 +161,7 @@ class GoldenRecordTaskStateMachineIT @Autowired constructor( Thread.sleep(10) // resolve - goldenRecordTaskStateMachine.doResolveTaskToSuccess(task, TaskStep.Clean, BusinessPartnerGenericCommonValues.businessPartner1Full) + goldenRecordTaskStateMachine.doResolveTaskToSuccess(task, TaskStep.Clean, businessPartnerFull) assertProcessingStateDto(task.processingState, ResultState.Success, TaskStep.Clean, StepState.Success) val modified2 = task.processingState.taskModifiedAt assertThat(modified2).isAfter(modified1) @@ -211,7 +215,7 @@ class GoldenRecordTaskStateMachineIT @Autowired constructor( // Can't resolve now! assertThatThrownBy { - goldenRecordTaskStateMachine.doResolveTaskToSuccess(task, TaskStep.Clean, BusinessPartnerGenericCommonValues.businessPartner1Full) + goldenRecordTaskStateMachine.doResolveTaskToSuccess(task, TaskStep.Clean, businessPartnerFull) }.isInstanceOf(BpdmIllegalStateException::class.java) } @@ -224,9 +228,7 @@ class GoldenRecordTaskStateMachineIT @Autowired constructor( private fun initTask(mode: TaskMode = TaskMode.UpdateFromSharingMember) = GoldenRecordTask( taskId = TASK_ID, - businessPartner = BusinessPartnerFullDto( - generic = BusinessPartnerGenericCommonValues.businessPartner1 - ), + businessPartner = businessPartnerFull, processingState = goldenRecordTaskStateMachine.initProcessingState(mode) ) } diff --git a/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/BusinessPartnerBuildService.kt b/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/BusinessPartnerBuildService.kt index 9e759b1dc..b30bf9684 100644 --- a/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/BusinessPartnerBuildService.kt +++ b/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/BusinessPartnerBuildService.kt @@ -114,6 +114,10 @@ class BusinessPartnerBuildService( val createdSites = requests.zip(bpnSs).map { (siteRequest, bpnS) -> val legalEntityParent = legalEntitiesByBpn[siteRequest.bpnLParent] ?: throw BpdmValidationException("Parent ${siteRequest.bpnLParent} not found for site to create") + + if(legalEntityParent.legalAddress.site != null) + throw BpdmValidationException("Can't create site for legal entity ${siteRequest.bpnLParent} with legal address as site main address: Legal address already belongs to site ${legalEntityParent.legalAddress.site!!.bpn}") + createSite(siteRequest, bpnS, legalEntityParent) .apply { mainAddress = legalEntityParent.legalAddress } .apply { mainAddress.site = this } diff --git a/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/RequestValidationService.kt b/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/RequestValidationService.kt index b1a8a39b7..e3ca3cad8 100644 --- a/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/RequestValidationService.kt +++ b/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/RequestValidationService.kt @@ -29,10 +29,6 @@ import org.eclipse.tractusx.bpdm.pool.api.model.request.* import org.eclipse.tractusx.bpdm.pool.api.model.response.* import org.eclipse.tractusx.bpdm.pool.dto.LegalEntityMetadataDto import org.eclipse.tractusx.bpdm.pool.repository.* -import org.eclipse.tractusx.bpdm.pool.service.TaskStepBuildService.CleaningError.LEGAL_ENTITY_IS_NULL -import org.eclipse.tractusx.orchestrator.api.model.BusinessPartnerFullDto -import org.eclipse.tractusx.orchestrator.api.model.LogisticAddressDto -import org.eclipse.tractusx.orchestrator.api.model.TaskStepReservationEntryDto import org.springframework.stereotype.Service @Service @@ -46,170 +42,6 @@ class RequestValidationService( private val metadataService: MetadataService ) { - fun validateTasksFromOrchestrator( - taskEntries: List, requestMappings: TaskEntryBpnMapping - ): Map>> { - - val result = mergeMapsWithCollectionInValue( - validateLegalEntitiesFromOrchestrator(taskEntries, requestMappings), - validateSitesFromOrchestrator(taskEntries, requestMappings), - validateAddressesFromOrchestrator(taskEntries, requestMappings) - ) - - // remove possible duplicated entries - return result.mapValues { - it.value.distinct() - }.toMap() - } - - private fun isSiteUpdate(businessPartner: BusinessPartnerFullDto, requestMappings: TaskEntryBpnMapping) = - businessPartner.site != null && requestMappings.hasBpnFor(businessPartner.site?.bpnSReference) - - private fun isLegalEntityUpdate(businessPartner: BusinessPartnerFullDto, requestMappings: TaskEntryBpnMapping) = - (requestMappings.hasBpnFor(businessPartner.legalEntity?.bpnLReference)) - - private fun isLegalEntityCreate(businessPartner: BusinessPartnerFullDto, requestMappings: TaskEntryBpnMapping) = - !requestMappings.hasBpnFor(businessPartner.legalEntity?.bpnLReference) - - private fun validateLegalEntitiesFromOrchestrator( - taskEntries: List, - requestMappings: TaskEntryBpnMapping - ): Map>> { - - val (faultyRequestsWithLegalEntityNull, validLegalEntities) = taskEntries - .partition { it.businessPartner.legalEntity == null || it.businessPartner.legalEntity?.bpnLReference == null } - - val legalEntitiesToCreate = validLegalEntities - .filter { - isLegalEntityCreate(it.businessPartner, requestMappings) - } - val legalEntitiesToUpdate = validLegalEntities - .filter { - isLegalEntityUpdate(it.businessPartner, requestMappings) - } - - val legalEntityEmptyErrorsByRequest = faultyRequestsWithLegalEntityNull.associateWith { - listOf(ErrorInfo(LegalEntityCreateError.LegalEntityIdentifierNotFound, LEGAL_ENTITY_IS_NULL.message, it.getRequestKey())) - } - val createBridges = legalEntitiesToCreate.map { - LegalEntityBridge(legalEntity = it.businessPartner.legalEntity!!, request = it, bpnL = null) - } - val updateBridges = legalEntitiesToUpdate.map { - LegalEntityBridge( - legalEntity = it.businessPartner.legalEntity!!, request = it, bpnL = requestMappings.getBpn(it.businessPartner.legalEntity?.bpnLReference!!)!! - ) - } - - val leCreateErrorsByRequest = validateLegalEntitiesToCreate(createBridges) - val leUpdateErrorsByRequest = validateLegalEntitiesToUpdate(updateBridges) - val duplicateValidationsByRequest = validateLegalEntityDuplicates(createBridges + updateBridges) - return mergeMapsWithCollectionInValue(leCreateErrorsByRequest, leUpdateErrorsByRequest, duplicateValidationsByRequest, legalEntityEmptyErrorsByRequest) - } - - private fun validateSitesFromOrchestrator( - taskEntries: List, - requestMappings: TaskEntryBpnMapping - ): Map>> { - - // sites to create are not validated, because the check for the parent legal entities is already done in the legal entity validation - - val sitesToUpdate = taskEntries - .filter { - isSiteUpdate(it.businessPartner, requestMappings) - } - - return validateSitesToUpdate(sitesToUpdate.map { - SiteUpdateBridge(request = it, bpnS = requestMappings.getBpn(it.businessPartner.site?.bpnSReference!!)!!) - }) - } - - private fun validateAddressesFromOrchestrator( - taskEntries: List, - requestMappings: TaskEntryBpnMapping - ): Map>> { - - val (faultyTasksWithLegalAddressNull, validLegalEntityTasks) = taskEntries - .partition { it.businessPartner.legalEntity?.legalAddress?.bpnAReference == null } - val legalAddressEmptyErrorsByTask = faultyTasksWithLegalAddressNull.associateWith { - listOf( - ErrorInfo( - LegalEntityCreateError.LegalAddressIdentifierNotFound, - "Legal address or BpnA Reference of legal entity is Empty", - it.getRequestKey() - ) - ) - } - - val (faultyTasksWithMainAddressNull, validLegalEntityAndSiteTasks) = validLegalEntityTasks - .partition { it.businessPartner.site != null && it.businessPartner.site?.mainAddress?.bpnAReference == null } - val mainAddressEmptyErrorsByTask = faultyTasksWithMainAddressNull.associateWith { - listOf( - ErrorInfo( - SiteCreateError.MainAddressIdentifierNotFound, - "Site main address or BpnA Reference is Empty", - it.getRequestKey() - ) - ) - } - - val addressBridges = validLegalEntityAndSiteTasks.flatMap { getAddressBridges(it, requestMappings) } - - return mergeMapsWithCollectionInValue( - legalAddressEmptyErrorsByTask, - mainAddressEmptyErrorsByTask, - validateAddresses(addressBridges, orchestratorMessages), - validateAddressDuplicates(addressBridges) - ) - } - - fun getAddressBridges(task: TaskStepReservationEntryDto, requestMappings: TaskEntryBpnMapping): List { - - val allAddresses: MutableList = mutableListOf() - val businessPartner = task.businessPartner - - businessPartner.legalEntity?.let { legalEntity -> - allAddresses.add(createAddressBridge(legalEntity.legalAddress!!, task, requestMappings)) - } - businessPartner.site?.let { site -> - allAddresses.add(createAddressBridge(site.mainAddress!!, task, requestMappings)) - } - businessPartner.address?.let { address -> - allAddresses.add(createAddressBridge(address, task, requestMappings)) - } - - return allAddresses - } - - private fun createAddressBridge( - address: LogisticAddressDto, - task: TaskStepReservationEntryDto, - requestMappings: TaskEntryBpnMapping - ) = AddressBridge( - address = address, - request = task, - bpnA = requestMappings.getBpn(address.bpnAReference) - ) - - fun validateLegalEntityDuplicates(requestBridges: List): Map>> { - - val legalEntityDtos = requestBridges.map { it.legalEntity } - val duplicatesValidator = ValidateLegalEntityIdentifiersDuplicated(legalEntityDtos, LegalEntityCreateError.LegalEntityDuplicateIdentifier) - - return requestBridges.associate { - it.request to duplicatesValidator.validate(it.legalEntity, it.request, it.bpnL) - }.filterValues { it.isNotEmpty() } - } - - fun validateAddressDuplicates(requestBridges: List): Map>> { - - val addressDtos = requestBridges.map { it.address } - val duplicatesValidator = ValidateAddressIdentifiersDuplicated(addressDtos, OrchestratorError.AddressDuplicateIdentifier) - - return requestBridges.associate { - it.request to duplicatesValidator.validate(it.address, it.request, it.bpnA) - }.filterValues { it.isNotEmpty() } - } - fun validateLegalEntitiesToCreateFromController(leCreateRequests: Collection): Map>> { val leErrorsByRequest = validateLegalEntitiesToCreate(leCreateRequests.map { diff --git a/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskEntryBpnMapping.kt b/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskEntryBpnMapping.kt index bb5eb9504..e60ea1adc 100644 --- a/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskEntryBpnMapping.kt +++ b/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskEntryBpnMapping.kt @@ -21,9 +21,9 @@ package org.eclipse.tractusx.bpdm.pool.service import org.eclipse.tractusx.bpdm.pool.entity.BpnRequestIdentifierMappingDb import org.eclipse.tractusx.bpdm.pool.repository.BpnRequestIdentifierRepository -import org.eclipse.tractusx.orchestrator.api.model.BpnReferenceDto import org.eclipse.tractusx.orchestrator.api.model.BpnReferenceType import org.eclipse.tractusx.orchestrator.api.model.TaskStepReservationEntryDto +import org.eclipse.tractusx.orchestrator.api.model.BpnReference class TaskEntryBpnMapping(taskEntries: List, bpnRequestIdentifierRepository: BpnRequestIdentifierRepository) { @@ -36,20 +36,23 @@ class TaskEntryBpnMapping(taskEntries: List, bpnReq private fun readRequestMappings(taskEntries: List, bpnRequestIdentifierRepository: BpnRequestIdentifierRepository ): MutableMap { - val references = taskEntries.mapNotNull { it.businessPartner.legalEntity?.bpnLReference } + - taskEntries.mapNotNull { it.businessPartner.legalEntity?.legalAddress?.bpnAReference } + - taskEntries.mapNotNull { it.businessPartner.site?.bpnSReference } + - taskEntries.mapNotNull { it.businessPartner.site?.mainAddress?.bpnAReference } + - taskEntries.mapNotNull { it.businessPartner.address?.bpnAReference } + val references = taskEntries.map { it.businessPartner.legalEntity.bpnReference } + + taskEntries.map { it.businessPartner.legalEntity.legalAddress.bpnReference } + + taskEntries.mapNotNull { it.businessPartner.site?.bpnReference } + + taskEntries.mapNotNull { it.businessPartner.site?.siteMainAddress?.bpnReference } + + taskEntries.mapNotNull { it.businessPartner.additionalAddress?.bpnReference } + .filter { it.referenceValue == null || it.referenceType == null } - val usedRequestIdentifiers: Collection = references.map { it.referenceValue } + val usedRequestIdentifiers: Collection = references + .filter { it.referenceType == BpnReferenceType.BpnRequestIdentifier } + .map { it.referenceValue!! } val mappings = bpnRequestIdentifierRepository.findDistinctByRequestIdentifierIn(usedRequestIdentifiers) val bpnByRequestIdentifier = mappings.associate { it.requestIdentifier to it.bpn } return bpnByRequestIdentifier.toMutableMap() } - fun getBpn(bpnReference: BpnReferenceDto?): String? { + fun getBpn(bpnReference: BpnReference?): String? { return if(bpnReference == null) { null @@ -60,7 +63,7 @@ class TaskEntryBpnMapping(taskEntries: List, bpnReq } } - fun hasBpnFor(bpnReference: BpnReferenceDto?): Boolean { + fun hasBpnFor(bpnReference: BpnReference?): Boolean { return bpnReference != null && (bpnReference.referenceType == BpnReferenceType.Bpn || (bpnReference.referenceType == BpnReferenceType.BpnRequestIdentifier @@ -68,10 +71,13 @@ class TaskEntryBpnMapping(taskEntries: List, bpnReq } - fun addMapping(bpnLReference: BpnReferenceDto, bpn: String) { - - createdBpnByRequestIdentifier[bpnLReference.referenceValue] = bpn - bpnByRequestIdentifier[bpnLReference.referenceValue] = bpn + fun addMapping(bpnReference: BpnReference, bpn: String) { + bpnReference.takeIf { it.referenceType == BpnReferenceType.BpnRequestIdentifier} + ?.referenceValue?.takeIf { it.isNotEmpty() } + ?.let { + createdBpnByRequestIdentifier[it] = bpn + bpnByRequestIdentifier[it] = bpn + } } fun writeCreatedMappingsToDb(bpnRequestIdentifierRepository: BpnRequestIdentifierRepository) { diff --git a/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskStepBuildService.kt b/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskStepBuildService.kt index 85be866de..85f7c730c 100644 --- a/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskStepBuildService.kt +++ b/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskStepBuildService.kt @@ -19,27 +19,25 @@ package org.eclipse.tractusx.bpdm.pool.service +import com.neovisionaries.i18n.CountryCode import jakarta.transaction.Transactional import org.eclipse.tractusx.bpdm.common.dto.GeoCoordinateDto import org.eclipse.tractusx.bpdm.common.dto.PaginationRequest import org.eclipse.tractusx.bpdm.pool.api.model.AddressIdentifierDto import org.eclipse.tractusx.bpdm.pool.api.model.AddressStateDto +import org.eclipse.tractusx.bpdm.pool.api.model.LegalEntityDto import org.eclipse.tractusx.bpdm.pool.api.model.LegalEntityIdentifierDto import org.eclipse.tractusx.bpdm.pool.api.model.LegalEntityStateDto +import org.eclipse.tractusx.bpdm.pool.api.model.LogisticAddressDto +import org.eclipse.tractusx.bpdm.pool.api.model.SiteDto import org.eclipse.tractusx.bpdm.pool.api.model.SiteStateDto import org.eclipse.tractusx.bpdm.pool.api.model.StreetDto import org.eclipse.tractusx.bpdm.pool.api.model.request.* -import org.eclipse.tractusx.bpdm.pool.api.model.response.ErrorCode -import org.eclipse.tractusx.bpdm.pool.api.model.response.ErrorInfo import org.eclipse.tractusx.bpdm.pool.exception.BpdmValidationException import org.eclipse.tractusx.orchestrator.api.model.* -import org.eclipse.tractusx.orchestrator.api.model.AlternativePostalAddressDto -import org.eclipse.tractusx.orchestrator.api.model.ConfidenceCriteriaDto -import org.eclipse.tractusx.orchestrator.api.model.LegalEntityDto -import org.eclipse.tractusx.orchestrator.api.model.LogisticAddressDto -import org.eclipse.tractusx.orchestrator.api.model.PhysicalPostalAddressDto -import org.eclipse.tractusx.orchestrator.api.model.SiteDto import org.springframework.stereotype.Service +import java.time.Instant +import java.time.ZoneOffset import org.eclipse.tractusx.bpdm.pool.api.model.AlternativePostalAddressDto as AlternativePostalAddressPoolDto import org.eclipse.tractusx.bpdm.pool.api.model.ConfidenceCriteriaDto as ConfidenceCriteriaPoolDto import org.eclipse.tractusx.bpdm.pool.api.model.LegalEntityDto as LegalEntityPoolDto @@ -87,326 +85,288 @@ class TaskStepBuildService( fun upsertBusinessPartner(taskEntry: TaskStepReservationEntryDto, taskEntryBpnMapping: TaskEntryBpnMapping): TaskStepResultEntryDto { val businessPartnerDto = taskEntry.businessPartner - val legalEntityResult = upsertLegalEntity( - businessPartnerDto.legalEntity, - taskEntryBpnMapping) + val legalEntityBpns = upsertLegalEntity(businessPartnerDto, taskEntryBpnMapping) + val siteBpns = businessPartnerDto.site?.let { upsertSite(businessPartnerDto, legalEntityBpns.legalEntityBpn, taskEntryBpnMapping) } + val addressBpn = businessPartnerDto.additionalAddress?.let { upsertAdditionalAddress(businessPartnerDto, legalEntityBpns.legalEntityBpn, siteBpns?.siteBpn, taskEntryBpnMapping) } - - val siteResult = if (legalEntityResult.errors.isEmpty() && businessPartnerDto.site != null) { - upsertSite( - businessPartnerDto.site, - legalEntityResult.legalEntityBpn!!, - businessPartnerDto.legalEntity?.legalAddress?.bpnAReference, - taskEntryBpnMapping - ) - } else { - null - } - - val addressResult = if (legalEntityResult.errors.isEmpty() && siteResult?.errors?.isEmpty() != false && businessPartnerDto.address != null) - upsertLogisticAddress( - businessPartnerDto.address, - legalEntityResult.legalEntityBpn!!, - siteResult?.siteBpn, - taskEntryBpnMapping - ) - else - null - - val taskErrors = legalEntityResult.errors - .plus(siteResult?.errors ?: emptyList()) - .plus(addressResult?.errors ?: emptyList()) - .map { TaskErrorDto(TaskErrorType.Unspecified, it.message) } - - val bpna = addressResult?.addressBpn ?: siteResult?.mainAddressBpn ?: legalEntityResult.legalAddressBpn - val genericWithBpn = with(businessPartnerDto.generic) { + val businessPartnerWithBpns = with(businessPartnerDto){ copy( - legalEntity = this.legalEntity.copy(legalEntityBpn = legalEntityResult.legalEntityBpn), - site = this.site.copy(siteBpn = siteResult?.siteBpn), - address = this.address.copy(addressBpn = bpna) - ) - } - - val legalEntityWithBpn = with(businessPartnerDto.legalEntity) { - this?.let { - copy( - bpnLReference = toBpnReference(legalEntityResult.legalEntityBpn), - legalAddress = legalAddress!!.copy(bpnAReference = toBpnReference(legalEntityResult.legalAddressBpn)) - ) - } - } - - val siteWithBpn = with(businessPartnerDto.site) { - this?.let { - copy( - bpnSReference = toBpnReference(siteResult?.siteBpn), - mainAddress = mainAddress!!.copy(bpnAReference = toBpnReference(siteResult?.mainAddressBpn)) + legalEntity = legalEntity.copy( + bpnReference = toBpnReference(legalEntityBpns.legalEntityBpn), + legalAddress = legalEntity.legalAddress.copy( + bpnReference = toBpnReference(legalEntityBpns.legalAddressBpn) + ) + ), + site = siteBpns?.let { site?.copy( + bpnReference = toBpnReference(siteBpns.siteBpn), + siteMainAddress = site!!.siteMainAddress?.copy(bpnReference = toBpnReference(siteBpns.mainAddressBpn)) + ) }, + additionalAddress = addressBpn?.let { additionalAddress?.copy(bpnReference = toBpnReference(addressBpn)) } ) - } - } - - val addressWithBpn = with(businessPartnerDto.address) { - this?.let { - copy(bpnAReference = toBpnReference(addressResult?.addressBpn)) - } } return TaskStepResultEntryDto( taskId = taskEntry.taskId, - businessPartner = BusinessPartnerFullDto( - generic = genericWithBpn, - legalEntity = legalEntityWithBpn, - site = siteWithBpn, - address = addressWithBpn - ), - errors = taskErrors + businessPartner = businessPartnerWithBpns, + errors = emptyList() ) } fun upsertLegalEntity( - legalEntityDto: LegalEntityDto?, taskEntryBpnMapping: TaskEntryBpnMapping + businessPartner: BusinessPartner, taskEntryBpnMapping: TaskEntryBpnMapping ): LegalEntityUpsertResponse { - val bpnLReference = legalEntityDto?.bpnLReference ?: throw BpdmValidationException(CleaningError.LEGAL_ENTITY_IS_NULL.message) - - val bpn = taskEntryBpnMapping.getBpn(bpnLReference) - val bpnWithError = if (bpn == null) { - createLegalEntity(legalEntityDto, taskEntryBpnMapping) - } else if(legalEntityDto.hasChanged == false) { - businessPartnerFetchService.fetchByBpns(listOf(bpn)) + val legalEntity = businessPartner.legalEntity + val legalAddress = legalEntity.legalAddress + val bpnLReference = legalEntity.bpnReference + val bpnL = taskEntryBpnMapping.getBpn(bpnLReference) + + val poolLegalEntity = toPoolDto(legalEntity) + val poolLegalAddress = toPoolDto(legalAddress) + + val bpnResults = if (bpnL == null) { + createLegalEntity(poolLegalEntity, poolLegalAddress) + } else if(legalEntity.hasChanged == false) { + businessPartnerFetchService.fetchByBpns(listOf(bpnL)) .firstOrNull() - ?.let { LegalEntityUpsertResponse(it.bpn, it.legalAddress.bpn, emptyList()) } ?: - throw BpdmValidationException(CleaningError.LEGAL_ADDRESS_IS_NULL.message) + ?.let { LegalEntityUpsertResponse(it.bpn, it.legalAddress.bpn) } ?: + throw BpdmValidationException("Legal entity with specified BPNL ${bpnL} not found") } else{ - updateLegalEntity(bpn, legalEntityDto) + updateLegalEntity(bpnL, poolLegalEntity, poolLegalAddress) } - return bpnWithError + taskEntryBpnMapping.addMapping(bpnLReference, bpnResults.legalEntityBpn) + taskEntryBpnMapping.addMapping(legalAddress.bpnReference, bpnResults.legalAddressBpn) + + return bpnResults } - private fun createLegalEntity( - legalEntityDto: LegalEntityDto, taskEntryBpnMapping: TaskEntryBpnMapping - ): LegalEntityUpsertResponse { - val legalAddress = legalEntityDto.legalAddress ?: throw BpdmValidationException(CleaningError.LEGAL_ADDRESS_IS_NULL.message) - val bpnAReference = - legalEntityDto.legalAddress?.bpnAReference ?: throw BpdmValidationException(CleaningError.LEGAL_ADDRESS_BPN_REFERENCE_MISSING.message) + private fun createLegalEntity(legalEntityDto: LegalEntityPoolDto, legalAddressDto: LogisticAddressPoolDto): LegalEntityUpsertResponse { val createRequest = LegalEntityPartnerCreateRequest( - legalEntity = toPoolDto(legalEntityDto), - legalAddress = toPoolDto(legalAddress), + legalEntity = legalEntityDto, + legalAddress = legalAddressDto, index = "" ) val result = businessPartnerBuildService.createLegalEntities(listOf(createRequest)) - val legalEntityResult = result.entities.firstOrNull() - val bpnL = legalEntityResult?.legalEntity?.bpnl - val legalAddressBpnA = legalEntityResult?.legalAddress?.bpna + if(result.errors.isNotEmpty()) + throw BpdmValidationException("Errors on creating Legal Entity: ${result.errors.joinToString()}") + + val legalEntityResult = result.entities.firstOrNull() ?: throw BpdmValidationException("Unknown error when trying to create legal entity") - bpnL?.run { taskEntryBpnMapping.addMapping(legalEntityDto.bpnLReference!!, bpnL) } - legalAddressBpnA?.run { taskEntryBpnMapping.addMapping(bpnAReference, legalAddressBpnA) } + val bpnL = legalEntityResult.legalEntity.bpnl + val legalAddressBpnA = legalEntityResult.legalAddress.bpna - return LegalEntityUpsertResponse(bpnL, legalAddressBpnA, result.errors) + return LegalEntityUpsertResponse(bpnL, legalAddressBpnA) } private fun updateLegalEntity( bpnL: String, - legalEntityDto: LegalEntityDto + legalEntityDto: LegalEntityDto, + legalAddressDto: LogisticAddressDto ): LegalEntityUpsertResponse { - val legalAddress = legalEntityDto.legalAddress ?: throw BpdmValidationException(CleaningError.LEGAL_ADDRESS_IS_NULL.message) - val updateRequest = LegalEntityPartnerUpdateRequest( bpnl = bpnL, - legalEntity = toPoolDto(legalEntityDto), - legalAddress = toPoolDto(legalAddress) + legalEntity = legalEntityDto, + legalAddress = legalAddressDto ) val result = businessPartnerBuildService.updateLegalEntities(listOf(updateRequest)) - val legalEntityResult = result.entities.firstOrNull() - return LegalEntityUpsertResponse(legalEntityResult?.legalEntity?.bpnl, legalEntityResult?.legalAddress?.bpna, result.errors) + if(result.errors.isNotEmpty()) + throw BpdmValidationException("Errors on updating Legal Entity: ${result.errors.joinToString()}") + + val legalEntityResult = result.entities.firstOrNull() ?: throw BpdmValidationException("Unknown error when trying to update legal entity") + + return LegalEntityUpsertResponse(legalEntityResult.legalEntity.bpnl, legalEntityResult.legalAddress.bpna) } private fun upsertSite( - siteDto: SiteDto?, + businessPartner: BusinessPartner, legalEntityBpn: String, - legalAddressReference: BpnReferenceDto?, taskEntryBpnMapping: TaskEntryBpnMapping ): SiteUpsertResponse { - val bpnSReference = siteDto?.bpnSReference ?: throw BpdmValidationException(CleaningError.BPNS_IS_NULL.message) - val bpn = taskEntryBpnMapping.getBpn(bpnSReference) + val site = businessPartner.site + val siteMainAddress = site?.siteMainAddress ?: businessPartner.legalEntity.legalAddress - val upsertSite = if (bpn == null) { - createSite(siteDto, legalEntityBpn, legalAddressReference, taskEntryBpnMapping) - } else if(siteDto.hasChanged == false){ - siteService.searchSites(SiteService.SiteSearchRequest(siteBpns = listOf(bpn), null, null, null), PaginationRequest(0, 1)) + val bpnSReference = site?.bpnReference ?: throw BpdmValidationException(CleaningError.BPNS_IS_NULL.message) + val bpnS = taskEntryBpnMapping.getBpn(bpnSReference) + + val poolSite = toPoolDto(site, siteMainAddress) + + val bpnResults = if (bpnS == null) { + createSite(poolSite, legalEntityBpn, site.siteMainAddress == null) + } else if(site.hasChanged == false){ + siteService.searchSites(SiteService.SiteSearchRequest(siteBpns = listOf(bpnS), null, null, null), PaginationRequest(0, 1)) .content.firstOrNull() - ?.let { SiteUpsertResponse(it.site.bpns, it.mainAddress.bpna, emptyList()) } + ?.let { SiteUpsertResponse(it.site.bpns, it.mainAddress.bpna) } ?: throw BpdmValidationException(CleaningError.MAINE_ADDRESS_IS_NULL.message) } else { - updateSite(bpn, siteDto) + updateSite(bpnS, poolSite) } - return upsertSite + + taskEntryBpnMapping.addMapping(bpnSReference, bpnResults.siteBpn) + taskEntryBpnMapping.addMapping(siteMainAddress.bpnReference, bpnResults.mainAddressBpn) + + return bpnResults } private fun createSite( - siteDto: SiteDto, + poolSite: SiteDto, legalEntityBpn: String, - legalAddressReference: BpnReferenceDto?, - taskEntryBpnMapping: TaskEntryBpnMapping + isSiteMainAndLegalAddress: Boolean ): SiteUpsertResponse { - val mainAddressReference = siteDto.mainAddress?.bpnAReference ?: throw BpdmValidationException(CleaningError.MAIN_ADDRESS_BPN_REFERENCE_MISSING.message) - val result = if (mainAddressReference.referenceValue == legalAddressReference?.referenceValue) { + val result = if(isSiteMainAndLegalAddress){ val createRequest = BusinessPartnerBuildService.SiteCreateRequestWithLegalAddressAsMain( - name = siteDto.name ?: throw BpdmValidationException(CleaningError.SITE_NAME_MISSING.message), - states = siteDto.states.map { SiteStateDto(it.validFrom, it.validTo, it.type) }, - confidenceCriteria = siteDto.confidenceCriteria?.let { toPoolDto(it) } - ?: throw BpdmValidationException(CleaningError.SITE_CONFIDENCE_CRITERIA_MISSING.message), + name = poolSite.name, + states = poolSite.states, + confidenceCriteria = poolSite.confidenceCriteria, bpnLParent = legalEntityBpn ) businessPartnerBuildService.createSitesWithLegalAddressAsMain(listOf(createRequest)) - } else { + }else{ val createRequest = SitePartnerCreateRequest( bpnlParent = legalEntityBpn, - site = toPoolDto(siteDto), + site = poolSite, index = "" ) businessPartnerBuildService.createSitesWithMainAddress(listOf(createRequest)) } - val siteResult = result.entities.firstOrNull() - val bpnS = siteResult?.site?.bpns - val mainAddressBpnA = siteResult?.mainAddress?.bpna + if(result.errors.isNotEmpty()) + throw BpdmValidationException("Errors on creating Site: ${result.errors.joinToString()}") - bpnS?.run { taskEntryBpnMapping.addMapping(siteDto.bpnSReference!!, bpnS) } - mainAddressBpnA?.run { taskEntryBpnMapping.addMapping(mainAddressReference, mainAddressBpnA) } + val siteResult = result.entities.firstOrNull() ?: throw BpdmValidationException("Unknown error when trying to creating site") - return SiteUpsertResponse(bpnS, mainAddressBpnA, result.errors) + return SiteUpsertResponse(siteResult.site.bpns, siteResult.mainAddress.bpna) } private fun updateSite( bpnS: String, - siteDto: SiteDto + poolSite: SiteDto, ): SiteUpsertResponse { val updateRequest = SitePartnerUpdateRequest( bpns = bpnS, - site = toPoolDto(siteDto) + site = poolSite ) val result = businessPartnerBuildService.updateSites(listOf(updateRequest)) - val siteResult = result.entities.firstOrNull() + if(result.errors.isNotEmpty()) + throw BpdmValidationException("Errors on updating Site: ${result.errors.joinToString()}") + + val siteResult = result.entities.firstOrNull() ?: throw BpdmValidationException("Unknown error when trying to updating site") - return SiteUpsertResponse(siteResult?.site?.bpns, siteResult?.mainAddress?.bpna, result.errors) + return SiteUpsertResponse(siteResult.site.bpns, siteResult.mainAddress.bpna) } - private fun upsertLogisticAddress( - addressDto: LogisticAddressDto?, + private fun upsertAdditionalAddress( + businessPartner: BusinessPartner, legalEntityBpn: String, siteBpn: String?, taskEntryBpnMapping: TaskEntryBpnMapping - ): AddressUpsertResponse { - val bpnAReference = addressDto?.bpnAReference ?: throw BpdmValidationException(CleaningError.BPNA_IS_NULL.message) - val bpn = taskEntryBpnMapping.getBpn(bpnAReference) - - val upsertAddress = if (bpn == null) { - createLogisticAddress(addressDto, legalEntityBpn, siteBpn, taskEntryBpnMapping) - } else if(addressDto.hasChanged == false){ - addressService.searchAddresses(AddressService.AddressSearchRequest(addressBpns = listOf(bpn), null, null, null, null), PaginationRequest(0, 1)) - .content.firstOrNull() - ?.let { AddressUpsertResponse(it.bpna, emptyList()) } - ?: throw BpdmValidationException(CleaningError.PHYSICAL_ADDRESS_IS_NULL.message) + ): String { + val postalAddress = businessPartner.additionalAddress + + val bpnAReference = postalAddress?.bpnReference ?: throw BpdmValidationException(CleaningError.BPNA_IS_NULL.message) + val bpnA = taskEntryBpnMapping.getBpn(bpnAReference) + + val poolAddress = toPoolDto(postalAddress) + + val addressBpn = if (bpnA == null) { + createLogisticAddress(poolAddress, legalEntityBpn, siteBpn) + } else if(postalAddress.hasChanged == false){ + addressService.searchAddresses(AddressService.AddressSearchRequest(addressBpns = listOf(bpnA), null, null, null, null), PaginationRequest(0, 1)) + .content.firstOrNull()?.bpna + ?: throw BpdmValidationException(CleaningError.BPNA_IS_NULL.message) } else { - updateLogisticAddress(bpn, addressDto) + updateLogisticAddress(bpnA, poolAddress) } - return upsertAddress + taskEntryBpnMapping.addMapping(bpnAReference, addressBpn) + + return addressBpn } private fun createLogisticAddress( - addressDto: LogisticAddressDto, + poolAddress: LogisticAddressDto, legalEntityBpn: String, - siteBpn: String?, - taskEntryBpnMapping: TaskEntryBpnMapping - ): AddressUpsertResponse { + siteBpn: String? + ): String { val addressCreateRequest = AddressPartnerCreateRequest( bpnParent = siteBpn ?: legalEntityBpn, index = "", - address = toPoolDto(addressDto) + address = poolAddress ) val result = businessPartnerBuildService.createAddresses(listOf(addressCreateRequest)) - val bpna = result.entities.firstOrNull()?.address?.bpna - bpna?.run { taskEntryBpnMapping.addMapping(addressDto.bpnAReference!!, bpna) } - return AddressUpsertResponse(bpna, result.errors) + if(result.errors.isNotEmpty()) + throw BpdmValidationException("Errors on creating Address: ${result.errors.joinToString()}") + + val addressResult = result.entities.firstOrNull() ?: throw BpdmValidationException("Unknown error when trying to creating address") + + return addressResult.address.bpna } private fun updateLogisticAddress( bpnA: String, - addressDto: LogisticAddressDto - ): AddressUpsertResponse { + poolAddress: LogisticAddressDto, + ): String { val addressUpdateRequest = AddressPartnerUpdateRequest( bpna = bpnA, - address = toPoolDto(addressDto) + address = poolAddress ) val result = businessPartnerBuildService.updateAddresses(listOf(addressUpdateRequest)) - return AddressUpsertResponse(result.entities.firstOrNull()?.bpna, result.errors) + if(result.errors.isNotEmpty()) + throw BpdmValidationException("Errors on updating Address: ${result.errors.joinToString()}") + + val addressResult = result.entities.firstOrNull() ?: throw BpdmValidationException("Unknown error when trying to updating address") + + return addressResult.bpna } - private fun toPoolDto(legalEntity: LegalEntityDto) = + private fun toPoolDto(legalEntity: LegalEntity) = with(legalEntity) { LegalEntityPoolDto( legalName = legalName ?: throw BpdmValidationException(CleaningError.LEGAL_NAME_IS_NULL.message), legalShortName = legalShortName, legalForm = legalForm, - identifiers = identifiers.map { LegalEntityIdentifierDto(it.value, it.type, it.issuingBody) }, - states = states.map { LegalEntityStateDto(it.validFrom, it.validTo, it.type) }, - confidenceCriteria = confidenceCriteria?.let { toPoolDto(it) } - ?: throw BpdmValidationException(CleaningError.LEGAL_ENTITY_CONFIDENCE_CRITERIA_MISSING.message), - isCatenaXMemberData = isCatenaXMemberData + identifiers = identifiers.map { assertNotNull(it).let { LegalEntityIdentifierDto(it.value!!, it.type!!, it.issuingBody) } }, + states = states.map { assertNotNull(it).let { LegalEntityStateDto(it.validFrom.toLocalDateTime(), it.validTo.toLocalDateTime(), it.type!!) } }, + confidenceCriteria = toPoolDto(confidenceCriteria, CleaningError.LEGAL_ENTITY_CONFIDENCE_CRITERIA_MISSING), + isCatenaXMemberData = isCatenaXMemberData ?: false ) } - private fun toPoolDto(site: SiteDto) = + private fun toPoolDto(site: Site, siteMainAddress: PostalAddress) = with(site) { SitePoolDto( - name = name ?: throw BpdmValidationException(CleaningError.SITE_NAME_MISSING.message), - states = states.map { SiteStateDto(it.validFrom, it.validTo, it.type) }, - mainAddress = mainAddress?.let { toPoolDto(it) } ?: throw BpdmValidationException(CleaningError.MAINE_ADDRESS_IS_NULL.message), - confidenceCriteria = confidenceCriteria?.let { toPoolDto(it) } - ?: throw BpdmValidationException(CleaningError.SITE_CONFIDENCE_CRITERIA_MISSING.message) + name = site.siteName ?: throw BpdmValidationException(CleaningError.SITE_NAME_MISSING.message), + states = states.map { assertNotNull(it).let { SiteStateDto(it.validFrom.toLocalDateTime(), it.validTo.toLocalDateTime(), it.type!!) }}, + mainAddress = toPoolDto(siteMainAddress), + confidenceCriteria = toPoolDto(confidenceCriteria, CleaningError.SITE_CONFIDENCE_CRITERIA_MISSING) ) } - private fun toPoolDto(logisticAddress: LogisticAddressDto) = + private fun toPoolDto(logisticAddress: PostalAddress) = with(logisticAddress) { LogisticAddressPoolDto( - name = name, - states = states.map { AddressStateDto(it.validFrom, it.validTo, it.type) }, - identifiers = identifiers.map { AddressIdentifierDto(it.value, it.type) }, - physicalPostalAddress = physicalPostalAddress?.let { toPoolDto(it) } - ?: throw BpdmValidationException(CleaningError.PHYSICAL_ADDRESS_IS_NULL.message), - alternativePostalAddress = alternativePostalAddress?.let { toPoolDto(it) }, - confidenceCriteria = with(confidenceCriteria) { - this?.let { - ConfidenceCriteriaPoolDto( - sharedByOwner, - checkedByExternalDataSource, - numberOfSharingMembers, - lastConfidenceCheckAt, - nextConfidenceCheckAt, - confidenceLevel - ) - } - } ?: throw BpdmValidationException(CleaningError.ADDRESS_CONFIDENCE_CRITERIA_MISSING.message) + name = addressName, + states = states.map { assertNotNull(it).let { AddressStateDto(it.validFrom.toLocalDateTime(), it.validTo.toLocalDateTime(), it.type!!)} }, + identifiers = identifiers.map { assertNotNull(it).let { AddressIdentifierDto(it.value!!, it.type!!) } }, + physicalPostalAddress = toPoolDto(physicalAddress), + alternativePostalAddress = alternativeAddress?.let { toPoolDto(it) }, + confidenceCriteria = toPoolDto(confidenceCriteria, CleaningError.ADDRESS_CONFIDENCE_CRITERIA_MISSING) ) } - private fun toPoolDto(physicalPostalAddressDto: PhysicalPostalAddressDto) = + private fun toPoolDto(physicalPostalAddressDto: PhysicalAddress) = with(physicalPostalAddressDto) { PhysicalPostalAddressPoolDto( - geographicCoordinates = with(geographicCoordinates) { this?.let { GeoCoordinateDto(longitude, latitude, altitude) } }, - country = country ?: throw BpdmValidationException(CleaningError.PHYSICAL_ADDRESS_COUNTRY_MISSING.message), + geographicCoordinates = with(geographicCoordinates) { longitude?.let { lon -> latitude?.let { lat -> GeoCoordinateDto(lon, lat, altitude) } } }, + country = country?.let { toCountryCode(it) } ?: throw BpdmValidationException(CleaningError.PHYSICAL_ADDRESS_COUNTRY_MISSING.message), administrativeAreaLevel1 = administrativeAreaLevel1, administrativeAreaLevel2 = administrativeAreaLevel2, administrativeAreaLevel3 = administrativeAreaLevel3, @@ -419,7 +379,6 @@ class TaskStepBuildService( floor = floor, door = door, street = with(street) { - this?.let { StreetDto( name, houseNumber, @@ -431,16 +390,15 @@ class TaskStepBuildService( nameSuffix, additionalNameSuffix ) - } } ) } - private fun toPoolDto(alternativeAddress: AlternativePostalAddressDto) = + private fun toPoolDto(alternativeAddress: AlternativeAddress) = with(alternativeAddress) { AlternativePostalAddressPoolDto( - geographicCoordinates = with(geographicCoordinates) { this?.let { GeoCoordinateDto(longitude, latitude, altitude) } }, - country = country ?: throw BpdmValidationException(CleaningError.ALTERNATIVE_ADDRESS_COUNTRY_MISSING.message), + geographicCoordinates = with(geographicCoordinates) { longitude?.let { lon -> latitude?.let { lat -> GeoCoordinateDto(lon, lat, altitude) } } }, + country = country?.let { toCountryCode(it) } ?: throw BpdmValidationException(CleaningError.ALTERNATIVE_ADDRESS_COUNTRY_MISSING.message), administrativeAreaLevel1 = administrativeAreaLevel1, postalCode = postalCode, city = city ?: throw BpdmValidationException(CleaningError.ALTERNATIVE_ADDRESS_CITY_MISSING.message), @@ -452,35 +410,51 @@ class TaskStepBuildService( ) } - private fun toPoolDto(confidenceCriteria: ConfidenceCriteriaDto) = + private fun toPoolDto(confidenceCriteria: ConfidenceCriteria, cleaningError: CleaningError) = with(confidenceCriteria) { ConfidenceCriteriaPoolDto( - sharedByOwner, - checkedByExternalDataSource, - numberOfSharingMembers, - lastConfidenceCheckAt, - nextConfidenceCheckAt, - confidenceLevel + sharedByOwner ?: throw BpdmValidationException(cleaningError.message), + checkedByExternalDataSource ?: throw BpdmValidationException(cleaningError.message), + numberOfSharingMembers ?: throw BpdmValidationException(cleaningError.message), + lastConfidenceCheckAt?.atZone(ZoneOffset.UTC)?.toLocalDateTime() ?: throw BpdmValidationException(cleaningError.message), + nextConfidenceCheckAt?.atZone(ZoneOffset.UTC)?.toLocalDateTime() ?: throw BpdmValidationException(cleaningError.message), + confidenceLevel ?: throw BpdmValidationException(cleaningError.message) ) } - private fun toBpnReference(bpn: String?) = - bpn?.let { BpnReferenceDto(bpn, BpnReferenceType.Bpn) } + + private fun assertNotNull(identifier: Identifier): Identifier { + identifier.value ?: throw BpdmValidationException("Identifier value is null") + identifier.type ?: throw BpdmValidationException("Identifier type is null") + + return identifier + } + + private fun assertNotNull(state: BusinessState): BusinessState { + state.type ?: throw BpdmValidationException("Business Partner state type is null") + return state + } + + private fun toBpnReference(bpn: String) = BpnReference(bpn, null, BpnReferenceType.Bpn) + + private fun Instant?.toLocalDateTime() = + this?.atZone(ZoneOffset.UTC)?.toLocalDateTime() + + private fun toCountryCode(code: String): CountryCode{ + try{ + return CountryCode.getByAlpha2Code(code) + }catch (e: IllegalArgumentException){ + throw BpdmValidationException("Country Code not recognized") + } + } data class LegalEntityUpsertResponse( - val legalEntityBpn: String?, - val legalAddressBpn: String?, - val errors: Collection> + val legalEntityBpn: String, + val legalAddressBpn: String ) data class SiteUpsertResponse( - val siteBpn: String?, - val mainAddressBpn: String?, - val errors: Collection> - ) - - data class AddressUpsertResponse( - val addressBpn: String?, - val errors: Collection> + val siteBpn: String, + val mainAddressBpn: String ) } \ No newline at end of file diff --git a/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskStepFetchAndReserveService.kt b/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskStepFetchAndReserveService.kt index a6248c1ff..006898b56 100644 --- a/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskStepFetchAndReserveService.kt +++ b/bpdm-pool/src/main/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskStepFetchAndReserveService.kt @@ -58,20 +58,13 @@ class TaskStepFetchAndReserveService( } catch (ex: Throwable) { logger.error(ex) { "Error while processing cleaning task" } } - } fun upsertGoldenRecordIntoPool(taskEntries: List): List { val taskEntryBpnMapping = TaskEntryBpnMapping(taskEntries, bpnRequestIdentifierRepository) - val invalidTaskResultsByTaskEntry = validateTasks(taskEntries, taskEntryBpnMapping) - - val taskResults = taskEntries.map { - - val invalidTaskResult = invalidTaskResultsByTaskEntry[it] - invalidTaskResult ?: businessPartnerTaskResult(it, taskEntryBpnMapping) - } + val taskResults = taskEntries.map { businessPartnerTaskResult(it, taskEntryBpnMapping) } taskEntryBpnMapping.writeCreatedMappingsToDb(bpnRequestIdentifierRepository) return taskResults } @@ -88,7 +81,8 @@ class TaskStepFetchAndReserveService( type = TaskErrorType.Unspecified, description = ex.message ?: "" ) - ) + ), + businessPartner = taskStep.businessPartner ) } catch (ex: Throwable) { logger.error(ex) { "An unexpected error occurred during golden record task processing" } @@ -99,40 +93,10 @@ class TaskStepFetchAndReserveService( type = TaskErrorType.Unspecified, description = "An unexpected error occurred during Pool update" ) - ) + ), + businessPartner = taskStep.businessPartner ) } } - private fun validateTasks( taskEntries: List, requestMappings: TaskEntryBpnMapping - ): Map { - - val validationErrorsByTaskEntry = requestValidationService.validateTasksFromOrchestrator(taskEntries, requestMappings) - - val taskResultsByTaskEntry = taskEntries - .associateWith { taskEntry -> - taskStepResultEntryDtoOnExistingError(taskEntry, validationErrorsByTaskEntry) - } - .filterValues { it != null } - return taskResultsByTaskEntry - } - - private fun taskStepResultEntryDtoOnExistingError( - taskEntry: TaskStepReservationEntryDto, - validationErrorsByTaskEntry: Map>> - ): TaskStepResultEntryDto? { - - val errors = validationErrorsByTaskEntry[taskEntry] - return if (errors != null) { - taskStepResultEntryDto(taskEntry.taskId, errors) - } else { - null - } - } - - private fun taskStepResultEntryDto(taskId: String, errors: Collection>): TaskStepResultEntryDto { - - return TaskStepResultEntryDto(taskId = taskId, errors = errors.map { TaskErrorDto(type = TaskErrorType.Unspecified, description = it.message) }) - } - } \ No newline at end of file diff --git a/bpdm-pool/src/main/resources/application.yml b/bpdm-pool/src/main/resources/application.yml index c38ae1306..64e149875 100644 --- a/bpdm-pool/src/main/resources/application.yml +++ b/bpdm-pool/src/main/resources/application.yml @@ -151,10 +151,6 @@ management: # Include readiness state in health response (ready to accept traffic) enabled: true spring: - profiles: - group: - # BPDM common shortcut to remove all authentication configuration - no-auth: no-api-auth, no-orchestrator-auth security: oauth2: resourceserver: diff --git a/bpdm-pool/src/test/kotlin/org/eclipse/tractusx/bpdm/pool/service/BusinessPartnerComparator.kt b/bpdm-pool/src/test/kotlin/org/eclipse/tractusx/bpdm/pool/service/BusinessPartnerComparator.kt index 2bd635dbf..de06b1f26 100644 --- a/bpdm-pool/src/test/kotlin/org/eclipse/tractusx/bpdm/pool/service/BusinessPartnerComparator.kt +++ b/bpdm-pool/src/test/kotlin/org/eclipse/tractusx/bpdm/pool/service/BusinessPartnerComparator.kt @@ -20,111 +20,126 @@ package org.eclipse.tractusx.bpdm.pool.service import org.assertj.core.api.Assertions +import org.assertj.core.api.Assertions.assertThat import org.eclipse.tractusx.bpdm.common.dto.AddressType -import org.eclipse.tractusx.bpdm.common.dto.ILegalEntityStateDto -import org.eclipse.tractusx.bpdm.common.dto.ISiteStateDto import org.eclipse.tractusx.bpdm.pool.api.model.* import org.eclipse.tractusx.bpdm.pool.api.model.response.LegalEntityWithLegalAddressVerboseDto import org.eclipse.tractusx.bpdm.pool.api.model.response.SiteWithMainAddressVerboseDto -import org.eclipse.tractusx.orchestrator.api.model.AddressIdentifierDto -import org.eclipse.tractusx.orchestrator.api.model.AddressStateDto -import org.eclipse.tractusx.orchestrator.api.model.LegalEntityClassificationDto -import org.eclipse.tractusx.orchestrator.api.model.LegalEntityDto -import org.eclipse.tractusx.orchestrator.api.model.LegalEntityIdentifierDto -import org.eclipse.tractusx.orchestrator.api.model.LogisticAddressDto -import org.eclipse.tractusx.orchestrator.api.model.SiteDto +import org.eclipse.tractusx.orchestrator.api.model.* +import java.time.Instant import java.time.LocalDateTime +import java.time.ZoneOffset import java.time.temporal.ChronoUnit import java.util.function.BiPredicate -fun compareLegalEntity(verboseRequest: LegalEntityWithLegalAddressVerboseDto, legalEntity: LegalEntityDto?) { +fun compareLegalEntity(verboseRequest: LegalEntityWithLegalAddressVerboseDto, legalEntity: LegalEntity?) { val verboseLegalEntity = verboseRequest.legalEntity - Assertions.assertThat(verboseLegalEntity.legalShortName).isEqualTo(legalEntity?.legalShortName) - Assertions.assertThat(verboseLegalEntity.legalFormVerbose?.technicalKey).isEqualTo(legalEntity?.legalForm) + assertThat(verboseLegalEntity.legalShortName).isEqualTo(legalEntity?.legalShortName) + assertThat(verboseLegalEntity.legalFormVerbose?.technicalKey).isEqualTo(legalEntity?.legalForm) compareStates(verboseLegalEntity.states, legalEntity?.states) compareIdentifiers(verboseLegalEntity.identifiers, legalEntity?.identifiers) val verboseLegalAddress = verboseRequest.legalAddress - Assertions.assertThat(verboseLegalAddress.bpnLegalEntity).isEqualTo(legalEntity?.bpnLReference?.referenceValue) - Assertions.assertThat(verboseLegalAddress.addressType == AddressType.LegalAddress || verboseLegalAddress.addressType == AddressType.LegalAndSiteMainAddress ).isTrue() + assertThat(verboseLegalAddress.bpnLegalEntity).isEqualTo(legalEntity?.bpnReference?.referenceValue) + assertThat(verboseLegalAddress.addressType == AddressType.LegalAddress).isTrue() + compareLogisticAddress(verboseLegalAddress, legalEntity?.legalAddress) } -fun compareSite(verboseRequest: SiteWithMainAddressVerboseDto, site: SiteDto?) { +fun compareSite(verboseRequest: SiteWithMainAddressVerboseDto, site: Site?) { val verboseSite = verboseRequest.site - Assertions.assertThat(verboseSite.name).isEqualTo(site?.name) - Assertions.assertThat(verboseSite.bpns).isEqualTo(site?.bpnSReference?.referenceValue) + assertThat(verboseSite.name).isEqualTo(site?.siteName) + assertThat(verboseSite.bpns).isEqualTo(site?.bpnReference?.referenceValue) compareSiteStates(verboseSite.states, site?.states) val verboseMainAddress = verboseRequest.mainAddress - Assertions.assertThat(verboseMainAddress.bpnSite).isEqualTo(site?.bpnSReference?.referenceValue) - val mainAddress = site?.mainAddress - Assertions.assertThat(verboseMainAddress.addressType == AddressType.SiteMainAddress || verboseMainAddress.addressType == AddressType.LegalAndSiteMainAddress).isTrue() + assertThat(verboseMainAddress.bpnSite).isEqualTo(site?.bpnReference?.referenceValue) + val mainAddress = site?.siteMainAddress + assertThat(verboseMainAddress.addressType == AddressType.SiteMainAddress).isTrue() compareLogisticAddress(verboseMainAddress, mainAddress) } -fun compareLogisticAddress(verboseAddress: LogisticAddressVerboseDto, address: LogisticAddressDto?) { +fun compareLogisticAddress(verboseAddress: LogisticAddressVerboseDto, address: PostalAddress?) { - Assertions.assertThat(verboseAddress.name).isEqualTo(address?.name) + assertThat(verboseAddress.name).isEqualTo(address?.addressName) compareAddressStates(verboseAddress.states, address?.states) compareAddressIdentifiers(verboseAddress.identifiers, address?.identifiers) val verbosePhysicalAddress = verboseAddress.physicalPostalAddress - val physicalAddress = address?.physicalPostalAddress - Assertions.assertThat(verbosePhysicalAddress).usingRecursiveComparison() - .ignoringFields(PhysicalPostalAddressVerboseDto::countryVerbose.name, PhysicalPostalAddressVerboseDto::administrativeAreaLevel1Verbose.name) + val physicalAddress = address?.physicalAddress + assertThat(verbosePhysicalAddress).usingRecursiveComparison() + .ignoringFields( + PhysicalPostalAddressVerboseDto::countryVerbose.name, + PhysicalPostalAddressVerboseDto::administrativeAreaLevel1Verbose.name, + PhysicalPostalAddressVerboseDto::geographicCoordinates.name, + PhysicalPostalAddressVerboseDto::street.name + ) .isEqualTo(physicalAddress) - Assertions.assertThat(verbosePhysicalAddress.country.name).isEqualTo(physicalAddress?.country?.name) - Assertions.assertThat(verbosePhysicalAddress.administrativeAreaLevel1).isEqualTo(physicalAddress?.administrativeAreaLevel1) + + + if(verbosePhysicalAddress.geographicCoordinates == null) { + assertThat(address?.physicalAddress?.geographicCoordinates).isEqualTo(GeoCoordinate.empty) + }else{ + assertThat(verbosePhysicalAddress.geographicCoordinates).usingRecursiveComparison().isEqualTo(address?.physicalAddress?.geographicCoordinates) + } + + if(verbosePhysicalAddress.street == null) { + assertThat(address?.physicalAddress?.street).isEqualTo(Street.empty) + }else{ + assertThat(verbosePhysicalAddress.street).usingRecursiveComparison().isEqualTo(address?.physicalAddress?.street) + } + + assertThat(verbosePhysicalAddress.country.name).isEqualTo(physicalAddress?.country) + assertThat(verbosePhysicalAddress.administrativeAreaLevel1).isEqualTo(physicalAddress?.administrativeAreaLevel1) val verboseAlternAddress = verboseAddress.alternativePostalAddress - val alternAddress = address?.alternativePostalAddress - Assertions.assertThat(verboseAlternAddress).usingRecursiveComparison() + val alternAddress = address?.alternativeAddress + assertThat(verboseAlternAddress).usingRecursiveComparison() .ignoringFields(AlternativePostalAddressVerboseDto::countryVerbose.name, AlternativePostalAddressVerboseDto::administrativeAreaLevel1Verbose.name) .isEqualTo(alternAddress) - Assertions.assertThat(verboseAlternAddress?.country?.name).isEqualTo(alternAddress?.country?.name) - Assertions.assertThat(verboseAlternAddress?.administrativeAreaLevel1).isEqualTo(alternAddress?.administrativeAreaLevel1) + assertThat(verboseAlternAddress?.country?.name).isEqualTo(alternAddress?.country) + assertThat(verboseAlternAddress?.administrativeAreaLevel1).isEqualTo(alternAddress?.administrativeAreaLevel1) } -fun compareAddressStates(statesVerbose: Collection, states: Collection?) { +fun compareAddressStates(statesVerbose: Collection, states: Collection?) { - Assertions.assertThat(statesVerbose.size).isEqualTo(states?.size ?: 0) + assertThat(statesVerbose.size).isEqualTo(states?.size ?: 0) val sortedVerboseStates = statesVerbose.sortedBy { it.validFrom } val sortedStates = states?.sortedBy { it.validFrom } sortedVerboseStates.indices.forEach { - Assertions.assertThat(sortedVerboseStates[it].typeVerbose.technicalKey.name).isEqualTo(sortedStates!![it].type.name) - Assertions.assertThat(sortedVerboseStates[it]).usingRecursiveComparison() + assertThat(sortedVerboseStates[it].typeVerbose.technicalKey.name).isEqualTo(sortedStates!![it].type?.name) + assertThat(sortedVerboseStates[it]).usingRecursiveComparison() .withEqualsForFields(isEqualToIgnoringMilliseconds(), AddressStateVerboseDto::validTo.name) .withEqualsForFields(isEqualToIgnoringMilliseconds(), AddressStateVerboseDto::validFrom.name) .ignoringFields(AddressStateVerboseDto::typeVerbose.name).isEqualTo(sortedStates[it]) } } -fun compareAddressIdentifiers(identifiersVerbose: Collection, identifiers: Collection?) { +fun compareAddressIdentifiers(identifiersVerbose: Collection, identifiers: Collection?) { - Assertions.assertThat(identifiersVerbose.size).isEqualTo(identifiers?.size ?: 0) - val sortedVerboseIdentifiers = identifiersVerbose.sortedBy { it.typeVerbose.name } - val sortedIdentifiers = identifiers!!.sortedBy { it.type } + assertThat(identifiersVerbose.size).isEqualTo(identifiers?.size ?: 0) + val sortedVerboseIdentifiers = identifiersVerbose.sortedWith( compareBy( {it.value}, {it.typeVerbose.name }) ) + val sortedIdentifiers = identifiers!!.sortedWith(compareBy({it.value}, { it.type })) sortedVerboseIdentifiers.indices.forEach { - Assertions.assertThat(sortedVerboseIdentifiers[it].typeVerbose.technicalKey).isEqualTo(sortedIdentifiers[it].type) - Assertions.assertThat(sortedVerboseIdentifiers[it]).usingRecursiveComparison() + assertThat(sortedVerboseIdentifiers[it].typeVerbose.technicalKey).isEqualTo(sortedIdentifiers[it].type) + assertThat(sortedVerboseIdentifiers[it]).usingRecursiveComparison() .ignoringFields(AddressIdentifierVerboseDto::typeVerbose.name) .isEqualTo(sortedIdentifiers[it]) } } -fun compareStates(statesVerbose: Collection, states: Collection?) { +fun compareStates(statesVerbose: Collection, states: Collection?) { - Assertions.assertThat(statesVerbose.size).isEqualTo(states?.size ?: 0) + assertThat(statesVerbose.size).isEqualTo(states?.size ?: 0) val sortedVerboseStates = statesVerbose.sortedBy { it.validFrom } val sortedStates = states!!.sortedBy { it.validFrom } sortedVerboseStates.indices.forEach { - Assertions.assertThat(sortedVerboseStates[it].typeVerbose.technicalKey.name).isEqualTo(sortedStates[it].type.name) - Assertions.assertThat(sortedVerboseStates[it]).usingRecursiveComparison() + assertThat(sortedVerboseStates[it].typeVerbose.technicalKey.name).isEqualTo(sortedStates[it].type?.name) + assertThat(sortedVerboseStates[it]).usingRecursiveComparison() .withEqualsForFields(isEqualToIgnoringMilliseconds(), LegalEntityStateVerboseDto::validTo.name ) .withEqualsForFields(isEqualToIgnoringMilliseconds(), LegalEntityStateVerboseDto::validFrom.name) .ignoringFields(LegalEntityStateVerboseDto::typeVerbose.name) @@ -132,13 +147,33 @@ fun compareStates(statesVerbose: Collection, states: } } -fun compareSiteStates(statesVerbose: Collection, states: Collection?) { +fun isEqualToIgnoringMilliseconds(): BiPredicate { + return BiPredicate { d1, d2 -> + (d1 == null && d2 == null) + || d1.toInstant(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS).equals(d2.truncatedTo(ChronoUnit.SECONDS)) + } +} + +fun compareIdentifiers(identifiersVerbose: Collection, identifiers: Collection?) { + + assertThat(identifiersVerbose.size).isEqualTo(identifiers?.size ?: 0) + + val sortedVerboseIdentifiers = identifiersVerbose.sortedWith( compareBy( {it.value}, {it.typeVerbose.name }) ) + val sortedIdentifiers = identifiers!!.sortedWith(compareBy({it.value}, { it.type })) + sortedVerboseIdentifiers.indices.forEach { + assertThat(sortedVerboseIdentifiers[it].typeVerbose.technicalKey).isEqualTo(sortedIdentifiers[it].type) + assertThat(sortedVerboseIdentifiers[it]).usingRecursiveComparison() + .ignoringFields(LegalEntityIdentifierVerboseDto::typeVerbose.name).isEqualTo(sortedIdentifiers[it]) + } +} + +fun compareSiteStates(statesVerbose: Collection, states: Collection?) { Assertions.assertThat(statesVerbose.size).isEqualTo(states?.size ?: 0) val sortedVerboseStates = statesVerbose.sortedBy { it.validFrom } val sortedStates = states!!.sortedBy { it.validFrom } sortedVerboseStates.indices.forEach { - Assertions.assertThat(sortedVerboseStates[it].typeVerbose.technicalKey.name).isEqualTo(sortedStates[it].type.name) + Assertions.assertThat(sortedVerboseStates[it].typeVerbose.technicalKey.name).isEqualTo(sortedStates[it].type?.name) Assertions.assertThat(sortedVerboseStates[it]).usingRecursiveComparison() .withEqualsForFields(isEqualToIgnoringMilliseconds(), SiteStateVerboseDto::validTo.name) .withEqualsForFields(isEqualToIgnoringMilliseconds(), SiteStateVerboseDto::validFrom.name) @@ -147,37 +182,3 @@ fun compareSiteStates(statesVerbose: Collection, states: Co } } -fun isEqualToIgnoringMilliseconds(): BiPredicate { - return BiPredicate { d1, d2 -> - (d1 == null && d2 == null) - || d1.truncatedTo(ChronoUnit.SECONDS).equals(d2.truncatedTo(ChronoUnit.SECONDS)) - } -} - -fun compareClassifications( - classificationsVerbose: Collection, - classifications: Collection? -) { - - Assertions.assertThat(classificationsVerbose.size).isEqualTo(classifications?.size ?: 0) - val sortedVerboseClassifications = classificationsVerbose.sortedBy { it.typeVerbose.name } - val sortedClassifications = classifications!!.sortedBy { it.type.name } - sortedVerboseClassifications.indices.forEach { - Assertions.assertThat(sortedVerboseClassifications[it].typeVerbose.technicalKey.name).isEqualTo(sortedClassifications[it].type.name) - Assertions.assertThat(sortedVerboseClassifications[it]).usingRecursiveComparison() - .ignoringFields(LegalEntityClassificationVerboseDto::typeVerbose.name) - .isEqualTo(sortedClassifications[it]) - } -} - -fun compareIdentifiers(identifiersVerbose: Collection, identifiers: Collection?) { - - Assertions.assertThat(identifiersVerbose.size).isEqualTo(identifiers?.size ?: 0) - val sortedVerboseIdentifiers = identifiersVerbose.sortedBy { it.typeVerbose.name } - val sortedIdentifiers = identifiers!!.sortedBy { it.type } - sortedVerboseIdentifiers.indices.forEach { - Assertions.assertThat(sortedVerboseIdentifiers[it].typeVerbose.technicalKey).isEqualTo(sortedIdentifiers[it].type) - Assertions.assertThat(sortedVerboseIdentifiers[it]).usingRecursiveComparison() - .ignoringFields(LegalEntityIdentifierVerboseDto::typeVerbose.name).isEqualTo(sortedIdentifiers[it]) - } -} diff --git a/bpdm-pool/src/test/kotlin/org/eclipse/tractusx/bpdm/pool/service/BusinessPartnerCreator.kt b/bpdm-pool/src/test/kotlin/org/eclipse/tractusx/bpdm/pool/service/BusinessPartnerCreator.kt deleted file mode 100644 index f0320c2ae..000000000 --- a/bpdm-pool/src/test/kotlin/org/eclipse/tractusx/bpdm/pool/service/BusinessPartnerCreator.kt +++ /dev/null @@ -1,210 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021,2024 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 - ******************************************************************************/ - -package org.eclipse.tractusx.bpdm.pool.service - -import com.neovisionaries.i18n.CountryCode -import org.eclipse.tractusx.bpdm.common.dto.GeoCoordinateDto -import org.eclipse.tractusx.bpdm.common.dto.TypeKeyNameVerboseDto -import org.eclipse.tractusx.bpdm.common.model.BusinessStateType -import org.eclipse.tractusx.bpdm.common.model.ClassificationType -import org.eclipse.tractusx.bpdm.common.model.DeliveryServiceType -import org.eclipse.tractusx.bpdm.test.testdata.pool.BusinessPartnerNonVerboseValues -import org.eclipse.tractusx.bpdm.test.testdata.pool.BusinessPartnerVerboseValues -import org.eclipse.tractusx.orchestrator.api.model.* -import java.time.LocalDateTime - -fun minFullBusinessPartner(): BusinessPartnerFullDto { - - return BusinessPartnerFullDto(generic = BusinessPartnerGenericDto()) -} - -fun emptyLegalEntity(): LegalEntityDto { - - return LegalEntityDto(isCatenaXMemberData = false) -} - -fun minValidLegalEntity(bpnLReference: BpnReferenceDto, bpnAReference: BpnReferenceDto): LegalEntityDto { - - return LegalEntityDto( - bpnLReference = bpnLReference, - legalName = "legalName_" + bpnLReference.referenceValue, - isCatenaXMemberData = false, - legalAddress = minLogisticAddress(bpnAReference = bpnAReference) - ) -} - -fun fullValidLegalEntity(bpnLReference: BpnReferenceDto, bpnAReference: BpnReferenceDto): LegalEntityDto { - - return LegalEntityDto( - bpnLReference = bpnLReference, - legalName = "legalName_" + bpnLReference.referenceValue, - legalShortName = "shortName_" + bpnLReference.referenceValue, - legalForm = BusinessPartnerVerboseValues.legalForm1.technicalKey, - identifiers = listOf( - legalEntityIdentifierDto(bpnLReference.referenceValue, 1L, BusinessPartnerVerboseValues.identifierType1), - legalEntityIdentifierDto(bpnLReference.referenceValue, 2L, BusinessPartnerVerboseValues.identifierType2) - ), - states = listOf( - legalEntityState(bpnLReference.referenceValue, 1L, BusinessStateType.ACTIVE), - legalEntityState(bpnLReference.referenceValue, 2L, BusinessStateType.INACTIVE) - ), - isCatenaXMemberData = false, - legalAddress = fullLogisticAddressDto(bpnAReference) - ) -} - -fun legalEntityIdentifierDto(name: String, id: Long, type: TypeKeyNameVerboseDto): LegalEntityIdentifierDto { - - return LegalEntityIdentifierDto( - value = "value_" + name + "_" + id, - issuingBody = "issuingBody_" + name + "_" + id, - type = type.technicalKey - ) -} - -fun addressIdentifierDto(name: String, id: Long, type: TypeKeyNameVerboseDto): AddressIdentifierDto { - - return AddressIdentifierDto( - value = "value_" + name + "_" + id, - type = type.technicalKey - ) -} - -fun legalEntityState(name: String, id: Long, type: BusinessStateType): LegalEntityStateDto { - - return LegalEntityStateDto( - validFrom = LocalDateTime.now().plusDays(id), - validTo = LocalDateTime.now().plusDays(id + 2), - type = type - ) -} - -fun siteState(name: String, id: Long, type: BusinessStateType): SiteStateDto { - - return SiteStateDto( - validFrom = LocalDateTime.now().plusDays(id), - validTo = LocalDateTime.now().plusDays(id + 2), - type = type - ) -} - -fun addressState(name: String, id: Long, type: BusinessStateType): AddressStateDto { - - return AddressStateDto( - validFrom = LocalDateTime.now().plusDays(id), - validTo = LocalDateTime.now().plusDays(id + 2), - type = type - ) -} - - -fun classificationDto(name: String, id: Long, type: ClassificationType): LegalEntityClassificationDto { - - return LegalEntityClassificationDto( - code = "code_" + name + "_" + id, - value = "value_" + name + "_" + id, - type = type - ) -} - -fun minLogisticAddress(bpnAReference: BpnReferenceDto): LogisticAddressDto { - - return LogisticAddressDto( - bpnAReference = bpnAReference, - physicalPostalAddress = minPhysicalPostalAddressDto(bpnAReference) - ) -} - -fun minPhysicalPostalAddressDto(bpnAReference: BpnReferenceDto) = PhysicalPostalAddressDto( - country = CountryCode.DE, - city = "City_" + bpnAReference.referenceValue -) - -fun fullLogisticAddressDto(bpnAReference: BpnReferenceDto): LogisticAddressDto { - - return LogisticAddressDto( - bpnAReference = bpnAReference, - name = "name_" + bpnAReference.referenceValue, - identifiers = listOf( - addressIdentifierDto(bpnAReference.referenceValue, 1L, TypeKeyNameVerboseDto(BusinessPartnerNonVerboseValues.addressIdentifierTypeDto1.technicalKey, "")), - addressIdentifierDto(bpnAReference.referenceValue, 2L, TypeKeyNameVerboseDto(BusinessPartnerNonVerboseValues.addressIdentifierTypeDto2.technicalKey, "")) - ), - states = listOf( - addressState(bpnAReference.referenceValue, 1L, BusinessStateType.ACTIVE), - addressState(bpnAReference.referenceValue, 2L, BusinessStateType.INACTIVE) - ), - physicalPostalAddress = PhysicalPostalAddressDto( - geographicCoordinates = GeoCoordinateDto(longitude = 1.1f, latitude = 2.2f, altitude = 3.3f), - country = CountryCode.DE, - administrativeAreaLevel1 = "AD-07", - administrativeAreaLevel2 = "adminArea2_" + bpnAReference.referenceValue, - administrativeAreaLevel3 = "adminArea3_" + bpnAReference.referenceValue, - postalCode = "postalCode_" + bpnAReference.referenceValue, - city = "city_" + bpnAReference.referenceValue, - street = StreetDto( - name = "name_" + bpnAReference.referenceValue, - houseNumber = "houseNumber_" + bpnAReference.referenceValue, - milestone = "milestone_" + bpnAReference.referenceValue, - direction = "direction_" + bpnAReference.referenceValue, - namePrefix = "namePrefix_" + bpnAReference.referenceValue, - additionalNamePrefix = "additionalNamePrefix_" + bpnAReference.referenceValue, - nameSuffix = "nameSuffix_" + bpnAReference.referenceValue, - additionalNameSuffix = "additionalNameSuffix_" + bpnAReference.referenceValue, - ), - district = "district_" + bpnAReference.referenceValue, - companyPostalCode = "companyPostalCode_" + bpnAReference.referenceValue, - industrialZone = "industrialZone_" + bpnAReference.referenceValue, - building = "building_" + bpnAReference.referenceValue, - floor = "floor_" + bpnAReference.referenceValue, - door = "door_" + bpnAReference.referenceValue, - ), - alternativePostalAddress = AlternativePostalAddressDto( - geographicCoordinates = GeoCoordinateDto(longitude = 12.3f, latitude = 4.56f, altitude = 7.89f), - country = CountryCode.DE, - administrativeAreaLevel1 = "DE-BW", - postalCode = "alternate_postalCode_" + bpnAReference.referenceValue, - city = "alternate_city_" + bpnAReference.referenceValue, - deliveryServiceType = DeliveryServiceType.PO_BOX, - deliveryServiceQualifier = "deliveryServiceQualifier_" + bpnAReference.referenceValue, - deliveryServiceNumber = "deliveryServiceNumber_" + bpnAReference.referenceValue, - ) - ) -} - -fun minValidSite(bpnSReference: BpnReferenceDto, bpnAReference: BpnReferenceDto): SiteDto { - - return SiteDto( - bpnSReference = bpnSReference, - name = "siteName_" + bpnSReference.referenceValue, - mainAddress = minLogisticAddress(bpnAReference = bpnAReference) - ) -} - -fun fullValidSite(bpnSReference: BpnReferenceDto, bpnAReference: BpnReferenceDto): SiteDto { - - return SiteDto( - bpnSReference = bpnSReference, - name = "siteName_" + bpnSReference.referenceValue, - states = listOf( - siteState(bpnSReference.referenceValue, 1L, BusinessStateType.ACTIVE), siteState(bpnSReference.referenceValue, 2L, BusinessStateType.INACTIVE) - ), - mainAddress = fullLogisticAddressDto(bpnAReference) - ) -} diff --git a/bpdm-pool/src/test/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskStepFetchAndReserveServiceTest.kt b/bpdm-pool/src/test/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskStepFetchAndReserveServiceTest.kt index aa26a3369..8c3e17078 100644 --- a/bpdm-pool/src/test/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskStepFetchAndReserveServiceTest.kt +++ b/bpdm-pool/src/test/kotlin/org/eclipse/tractusx/bpdm/pool/service/TaskStepFetchAndReserveServiceTest.kt @@ -22,47 +22,26 @@ package org.eclipse.tractusx.bpdm.pool.service import com.neovisionaries.i18n.CountryCode import org.assertj.core.api.Assertions.assertThat import org.eclipse.tractusx.bpdm.common.dto.* -import org.eclipse.tractusx.bpdm.common.model.BusinessStateType -import org.eclipse.tractusx.bpdm.common.model.ClassificationType -import org.eclipse.tractusx.bpdm.common.model.DeliveryServiceType import org.eclipse.tractusx.bpdm.pool.Application -import org.eclipse.tractusx.bpdm.pool.api.client.PoolClientImpl -import org.eclipse.tractusx.bpdm.pool.api.model.* -import org.eclipse.tractusx.bpdm.pool.api.model.response.LegalEntityWithLegalAddressVerboseDto -import org.eclipse.tractusx.bpdm.pool.api.model.response.SiteWithMainAddressVerboseDto +import org.eclipse.tractusx.bpdm.pool.api.client.PoolApiClient import org.eclipse.tractusx.bpdm.pool.repository.BpnRequestIdentifierRepository import org.eclipse.tractusx.bpdm.pool.service.TaskStepBuildService.CleaningError import org.eclipse.tractusx.bpdm.test.containers.PostgreSQLContextInitializer -import org.eclipse.tractusx.bpdm.test.testdata.pool.BusinessPartnerNonVerboseValues.addressIdentifierTypeDto1 -import org.eclipse.tractusx.bpdm.test.testdata.pool.BusinessPartnerNonVerboseValues.addressIdentifierTypeDto2 -import org.eclipse.tractusx.bpdm.test.testdata.pool.BusinessPartnerVerboseValues +import org.eclipse.tractusx.bpdm.test.testdata.orchestrator.* +import org.eclipse.tractusx.bpdm.test.testdata.pool.PoolDataHelper +import org.eclipse.tractusx.bpdm.test.testdata.pool.TestDataEnvironment import org.eclipse.tractusx.bpdm.test.util.DbTestHelpers -import org.eclipse.tractusx.bpdm.test.util.PoolDataHelpers import org.eclipse.tractusx.orchestrator.api.model.* -import org.eclipse.tractusx.orchestrator.api.model.AddressIdentifierDto -import org.eclipse.tractusx.orchestrator.api.model.AddressStateDto -import org.eclipse.tractusx.orchestrator.api.model.AlternativePostalAddressDto import org.eclipse.tractusx.orchestrator.api.model.BpnReferenceType.Bpn import org.eclipse.tractusx.orchestrator.api.model.BpnReferenceType.BpnRequestIdentifier -import org.eclipse.tractusx.orchestrator.api.model.ConfidenceCriteriaDto -import org.eclipse.tractusx.orchestrator.api.model.LegalEntityClassificationDto -import org.eclipse.tractusx.orchestrator.api.model.LegalEntityDto -import org.eclipse.tractusx.orchestrator.api.model.LegalEntityIdentifierDto -import org.eclipse.tractusx.orchestrator.api.model.LegalEntityStateDto -import org.eclipse.tractusx.orchestrator.api.model.LogisticAddressDto -import org.eclipse.tractusx.orchestrator.api.model.PhysicalPostalAddressDto -import org.eclipse.tractusx.orchestrator.api.model.SiteDto -import org.eclipse.tractusx.orchestrator.api.model.SiteStateDto -import org.eclipse.tractusx.orchestrator.api.model.StreetDto import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.ContextConfiguration -import java.time.LocalDateTime +import java.time.Instant import java.time.temporal.ChronoUnit -import java.util.function.BiPredicate @SpringBootTest( @@ -73,40 +52,47 @@ import java.util.function.BiPredicate class TaskStepFetchAndReserveServiceTest @Autowired constructor( val cleaningStepService: TaskStepFetchAndReserveService, val bpnRequestIdentifierRepository: BpnRequestIdentifierRepository, - val poolClient: PoolClientImpl, + val poolClient: PoolApiClient, val dbTestHelpers: DbTestHelpers, - val poolDataHelpers: PoolDataHelpers, + val poolDataHelper: PoolDataHelper ) { + private lateinit var orchTestDataFactory: BusinessPartnerTestDataFactory + private lateinit var testDataEnvironment: TestDataEnvironment @BeforeEach fun beforeEach() { dbTestHelpers.truncateDbTables() - poolDataHelpers.createPoolMetadata() + + testDataEnvironment = poolDataHelper.createTestDataEnvironment() + orchTestDataFactory = BusinessPartnerTestDataFactory( + BusinessPartnerTestDataFactory.TestMetadataReferences( + legalForms = testDataEnvironment.metadata.legalForms.map { it.technicalKey }, + legalEntityIdentifierTypes = testDataEnvironment.metadata.legalEntityIdentifierTypes.map { it.technicalKey }, + addressIdentifierTypes = testDataEnvironment.metadata.addressIdentifierTypes.map { it.technicalKey }, + adminAreas = testDataEnvironment.metadata.adminAreas.map { it.code } + ) + ) } @Test fun `create empty legal entity`() { - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = emptyLegalEntity() + val createLegalEntityRequest = BusinessPartner.empty.copy( + legalEntity = LegalEntity.empty ) val result = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(result[0].taskId).isEqualTo("TASK_1") - assertThat(result[0].errors.size).isEqualTo(2) - assertThat(result[0].errors[0].description).isEqualTo(CleaningError.LEGAL_ENTITY_IS_NULL.message) + assertThat(result[0].errors.size).isEqualTo(1) } @Test fun `create legal entity without legal name`() { - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = emptyLegalEntity().copy( - bpnLReference = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier), - legalAddress = minLogisticAddress(BpnReferenceDto(referenceValue = "A777", referenceType = BpnRequestIdentifier)) - ) - ) + val createLegalEntityRequest = with(minValidLegalEntity()){ + copy(legalEntity = legalEntity.copy(legalName = null)) + } val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertTaskError(createResult[0], "TASK_1", CleaningError.LEGAL_NAME_IS_NULL) @@ -117,12 +103,9 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( val leRefValue = "123" val leAddressRefValue = "222" - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = leRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = leAddressRefValue, referenceType = BpnRequestIdentifier) - ) - ) + val createLegalEntityRequest = minValidLegalEntity() + .withLegalReferences(leRefValue.toBpnRequest(), leAddressRefValue.toBpnRequest()) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors.size).isEqualTo(0) @@ -130,10 +113,10 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( val bpnMappings = bpnRequestIdentifierRepository.findDistinctByRequestIdentifierIn(listOf(leRefValue, leAddressRefValue)) assertThat(bpnMappings.size).isEqualTo(2) - val createdLegalEntity = poolClient.legalEntities.getLegalEntity(createResult[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) + val createdLegalEntity = poolClient.legalEntities.getLegalEntity(createResult[0].businessPartner.legalEntity.bpnReference.referenceValue!!) assertThat(createdLegalEntity.legalAddress.bpnLegalEntity).isNotNull() - assertThat(createResult[0].businessPartner?.generic?.legalEntity?.legalEntityBpn).isEqualTo(createdLegalEntity.legalEntity.bpnl) - compareLegalEntity(createdLegalEntity, createResult[0].businessPartner?.legalEntity) + assertThat(createResult[0].businessPartner.legalEntity.bpnReference.referenceValue).isEqualTo(createdLegalEntity.legalEntity.bpnl) + compareLegalEntity(createdLegalEntity, createResult[0].businessPartner.legalEntity) } @Test @@ -141,12 +124,10 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( val leRefValue = "123" val leAddressRefValue = "222" - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = fullValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = leRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = leAddressRefValue, referenceType = BpnRequestIdentifier) - ) - ) + val createLegalEntityRequest = orchTestDataFactory.createFullBusinessPartner("test") + .withLegalReferences(leRefValue.toBpnRequest(), leAddressRefValue.toBpnRequest()) + .copy(site = null, additionalAddress = null) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors.size).isEqualTo(0) @@ -154,10 +135,10 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( val bpnMappings = bpnRequestIdentifierRepository.findDistinctByRequestIdentifierIn(listOf(leRefValue, leAddressRefValue)) assertThat(bpnMappings.size).isEqualTo(2) - val createdLegalEntity = poolClient.legalEntities.getLegalEntity(createResult[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) + val createdLegalEntity = poolClient.legalEntities.getLegalEntity(createResult[0].businessPartner.legalEntity.bpnReference?.referenceValue!!) assertThat(createdLegalEntity.legalAddress.bpnLegalEntity).isNotNull() - assertThat(createResult[0].businessPartner?.generic?.legalEntity?.legalEntityBpn).isEqualTo(createdLegalEntity.legalEntity.bpnl) - compareLegalEntity(createdLegalEntity, createResult[0].businessPartner?.legalEntity) + assertThat(createResult[0].businessPartner.legalEntity.bpnReference.referenceValue).isEqualTo(createdLegalEntity.legalEntity.bpnl) + compareLegalEntity(createdLegalEntity, createResult[0].businessPartner.legalEntity) } @@ -167,13 +148,11 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( val leRefValue = "123" val leAddressRefValue = "222" val additionalAddressRefValue = "333" - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = leRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = leAddressRefValue, referenceType = BpnRequestIdentifier) - ), - address = minLogisticAddress(BpnReferenceDto(referenceValue = additionalAddressRefValue, referenceType = BpnRequestIdentifier)) - ) + val createLegalEntityRequest = orchTestDataFactory.createFullBusinessPartner("test") + .withLegalReferences(leRefValue.toBpnRequest(), leAddressRefValue.toBpnRequest()) + .withAdditionalAddressReference(additionalAddressRefValue.toBpnRequest()) + .copy(site = null) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors.size).isEqualTo(0) @@ -181,12 +160,12 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( val bpnMappings = bpnRequestIdentifierRepository.findDistinctByRequestIdentifierIn(listOf(leRefValue, leAddressRefValue, additionalAddressRefValue)) assertThat(bpnMappings.size).isEqualTo(3) - val createdLegalEntity = poolClient.legalEntities.getLegalEntity(createResult[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) + val createdLegalEntity = poolClient.legalEntities.getLegalEntity(createResult[0].businessPartner.legalEntity.bpnReference.referenceValue!!) assertThat(createdLegalEntity.legalAddress.bpnLegalEntity).isEqualTo(createdLegalEntity.legalEntity.bpnl) assertThat(createdLegalEntity.legalAddress.addressType == AddressType.LegalAddress).isTrue() - assertThat(createResult[0].businessPartner?.generic?.legalEntity?.legalEntityBpn).isEqualTo(createdLegalEntity.legalEntity.bpnl) - compareLegalEntity(createdLegalEntity, createResult[0].businessPartner?.legalEntity) - val createdAdditionalAddress = poolClient.addresses.getAddress(createResult[0].businessPartner?.address?.bpnAReference?.referenceValue!!) + assertThat(createResult[0].businessPartner.legalEntity.bpnReference.referenceValue).isEqualTo(createdLegalEntity.legalEntity.bpnl) + compareLegalEntity(createdLegalEntity, createResult[0].businessPartner.legalEntity) + val createdAdditionalAddress = poolClient.addresses.getAddress(createResult[0].businessPartner.additionalAddress?.bpnReference?.referenceValue!!) assertThat(createdAdditionalAddress.bpnLegalEntity).isEqualTo(createdLegalEntity.legalEntity.bpnl) assertThat(createdAdditionalAddress.addressType == AddressType.AdditionalAddress).isTrue() } @@ -194,164 +173,151 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( @Test fun `create legal entity with invalid identifiers`() { - val leRef = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier) - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = leRef, - bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - ).copy( - identifiers = listOf( - legalEntityIdentifierDto(leRef.referenceValue, 1L, BusinessPartnerVerboseValues.identifierType1), - legalEntityIdentifierDto(leRef.referenceValue, 2L, TypeKeyNameVerboseDto("Invalid", "Invalid")) + val existingIdentifierType = testDataEnvironment.metadata.legalEntityIdentifierTypes.first().technicalKey + + val createLegalEntityRequest = with(minValidLegalEntity()){ + copy( + legalEntity = legalEntity.copy( + identifiers = listOf( + Identifier("same", existingIdentifierType, null), + Identifier("same", "Invalid", null) + ) ) ) - ) + }.withLegalReferences("123".toBpnRequest(), "222".toBpnRequest()) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors[0].type).isEqualTo(TaskErrorType.Unspecified) - assertThat(createResult[0].errors[0].description).isEqualTo("Legal Entity Identifier Type 'Invalid' does not exist") } @Test fun `create legal entity with invalid legal form`() { + val createLegalEntityRequest = with(minValidLegalEntity()){ copy( legalEntity = legalEntity.copy(legalForm = "Invalid Form")) } + .withLegalReferences("123".toBpnRequest(), "222".toBpnRequest()) - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - ).copy( - legalForm = "Invalid Form" - ) - ) val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors[0].type).isEqualTo(TaskErrorType.Unspecified) - assertThat(createResult[0].errors[0].description).isEqualTo("Legal Form 'Invalid Form' does not exist") } @Test fun `create legal entity with invalid duplicate identifier`() { - val leRef = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier) - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = leRef, - bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - ).copy( - identifiers = listOf( - legalEntityIdentifierDto(leRef.referenceValue, 1L, BusinessPartnerVerboseValues.identifierType1), - legalEntityIdentifierDto(leRef.referenceValue, 1L, BusinessPartnerVerboseValues.identifierType1) - ), + val identifierValue = "123" + val existingIdentifierType = testDataEnvironment.metadata.legalEntityIdentifierTypes.first().technicalKey + + val createLegalEntityRequest = with(minValidLegalEntity()){ + copy( + legalEntity = legalEntity.copy( + identifiers = listOf( + Identifier(identifierValue, existingIdentifierType, null), + Identifier(identifierValue, existingIdentifierType, null) + ) + ) ) - ) + }.withLegalReferences("123".toBpnRequest(), "222".toBpnRequest()) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors[0].type).isEqualTo(TaskErrorType.Unspecified) - assertThat(createResult[0].errors[0].description).isEqualTo("Duplicate Legal Entity Identifier: Value 'value_123_1' of type 'VAT_DE'") } @Test fun `create 2 legal entities with invalid duplicate identifier`() { - val leRef1 = BpnReferenceDto(referenceValue = "111", referenceType = BpnRequestIdentifier) - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = leRef1, - bpnAReference = BpnReferenceDto(referenceValue = "444", referenceType = BpnRequestIdentifier) - ).copy( - identifiers = listOf( - legalEntityIdentifierDto(leRef1.referenceValue, 1L, BusinessPartnerVerboseValues.identifierType1), - legalEntityIdentifierDto(leRef1.referenceValue, 2L, BusinessPartnerVerboseValues.identifierType2) - ), + val identifierValue = "123" + val existingIdentifierType = testDataEnvironment.metadata.legalEntityIdentifierTypes.first().technicalKey + + val createLegalEntityRequest = with(minValidLegalEntity()){ + copy( + legalEntity = legalEntity.copy( + identifiers = listOf( + Identifier(identifierValue, existingIdentifierType, null) + ) + ) ) - ) + }.withLegalReferences("123".toBpnRequest(), "222".toBpnRequest()) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors.size).isEqualTo(0) - val leRef2 = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - val createLegalEntityRequest2 = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = leRef2, - bpnAReference = BpnReferenceDto(referenceValue = "333", referenceType = BpnRequestIdentifier) - ).copy( - identifiers = listOf( - legalEntityIdentifierDto(leRef1.referenceValue, 1L, BusinessPartnerVerboseValues.identifierType1), - ), + val createLegalEntityRequest2 = with(minValidLegalEntity()){ + copy( + legalEntity = legalEntity.copy( + identifiers = listOf( + Identifier(identifierValue, existingIdentifierType, null) + ) + ) ) - ) + }.withLegalReferences("987".toBpnRequest(), "654".toBpnRequest()) + val resultSteps2 = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = createLegalEntityRequest2) assertThat(resultSteps2[0].taskId).isEqualTo("TASK_2") assertThat(resultSteps2[0].errors.size).isEqualTo(1) - assertThat(resultSteps2[0].errors[0].description).isEqualTo("Duplicate Legal Entity Identifier: Value 'value_111_1' of type 'VAT_DE'") } @Test fun `create legal entity with invalid address administrativeAreaLevel1`() { - val bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier), - bpnAReference = bpnAReference - ).copy( - legalAddress = minLogisticAddress(bpnAReference).copy( - physicalPostalAddress = minPhysicalPostalAddressDto(bpnAReference).copy( - administrativeAreaLevel1 = "Invalid" + val createLegalEntityRequest = with(minValidLegalEntity()){ + copy( + legalEntity = legalEntity.copy( + legalAddress = legalEntity.legalAddress.copy( + physicalAddress = legalEntity.legalAddress.physicalAddress.copy( + administrativeAreaLevel1 = "Invalid" + ) ) ) ) - ) + }.withLegalReferences("987".toBpnRequest(), "654".toBpnRequest()) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors[0].type).isEqualTo(TaskErrorType.Unspecified) - assertThat(createResult[0].errors[0].description).isEqualTo("Address administrative area level1 'Invalid' does not exist") } @Test fun `create legal entity with invalid address identifier`() { - val bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier), - bpnAReference = bpnAReference - ).copy( - legalAddress = minLogisticAddress(bpnAReference).copy( - identifiers = listOf( - addressIdentifierDto(bpnAReference.referenceValue, 1L, TypeKeyNameVerboseDto(addressIdentifierTypeDto1.technicalKey, "")), - addressIdentifierDto(bpnAReference.referenceValue, 2L, TypeKeyNameVerboseDto("Invalid Ident", "")) - ), + val createLegalEntityRequest = with(minValidLegalEntity()){ + copy( + legalEntity = legalEntity.copy( + legalAddress = legalEntity.legalAddress.copy( + identifiers = listOf(Identifier("value", "Invalid Ident", null) ) + ) ) ) - ) + }.withLegalReferences("987".toBpnRequest(), "654".toBpnRequest()) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors[0].type).isEqualTo(TaskErrorType.Unspecified) - assertThat(createResult[0].errors[0].description).isEqualTo("Address Identifier Type 'Invalid Ident' does not exist") } @Test fun `create legal entity with invalid duplicated address identifier`() { - val bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier), - bpnAReference = bpnAReference - ).copy( - legalAddress = minLogisticAddress(bpnAReference).copy( - identifiers = listOf( - addressIdentifierDto(bpnAReference.referenceValue, 1L, TypeKeyNameVerboseDto(addressIdentifierTypeDto1.technicalKey, "")), - addressIdentifierDto(bpnAReference.referenceValue, 1L, TypeKeyNameVerboseDto(addressIdentifierTypeDto1.technicalKey, "")) - ), + val availableIdentifierType = testDataEnvironment.metadata.addressIdentifierTypes.first().technicalKey + val sameIdentifier = Identifier("same value", availableIdentifierType, "Issuing Body 1") + val createLegalEntityRequest = with(minValidLegalEntity()){ + copy( + legalEntity = legalEntity.copy( + legalAddress = legalEntity.legalAddress.copy( + identifiers = listOf( + sameIdentifier, + sameIdentifier + ) + ) ) - ) - ) + ).copyWithBpnRequests() + } + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors[0].type).isEqualTo(TaskErrorType.Unspecified) - assertThat(createResult[0].errors[0].description).isEqualTo("Duplicate Address Identifier: Value 'value_222_1' of type 'ADDR_KEY_ONE'") + assertThat(createResult[0].errors).hasSize(1) } @@ -360,21 +326,18 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( val leRefValue = "123" val leAddressRefValue = "222" - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = leRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = leAddressRefValue, referenceType = BpnRequestIdentifier) - ) - ) + val createLegalEntityRequest = minValidLegalEntity() + .withLegalReferences(leRefValue.toBpnRequest(), leAddressRefValue.toBpnRequest()) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors.size).isEqualTo(0) - val createdLegalEntity1 = poolClient.legalEntities.getLegalEntity(createResult[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) + val createdLegalEntity1 = poolClient.legalEntities.getLegalEntity(createResult[0].businessPartner.legalEntity.bpnReference.referenceValue!!) val resultSteps2 = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = createLegalEntityRequest) assertThat(resultSteps2[0].taskId).isEqualTo("TASK_2") assertThat(resultSteps2[0].errors.size).isEqualTo(0) - assertThat(createdLegalEntity1.legalEntity.bpnl).isEqualTo(resultSteps2[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) + assertThat(createdLegalEntity1.legalEntity.bpnl).isEqualTo(resultSteps2[0].businessPartner.legalEntity.bpnReference.referenceValue!!) } @Test @@ -382,25 +345,18 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( val leRefValue = "123" val leAddressRefValue = "222" - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = leRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = leAddressRefValue, referenceType = BpnRequestIdentifier) - ) - ) + val createLegalEntityRequest = minValidLegalEntity() + .withLegalReferences(leRefValue.toBpnRequest(), leAddressRefValue.toBpnRequest()) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors.size).isEqualTo(0) - val createdLegalEntity1 = poolClient.legalEntities.getLegalEntity(createResult[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) + val createdLegalEntity1 = poolClient.legalEntities.getLegalEntity(createResult[0].businessPartner.legalEntity.bpnReference.referenceValue!!) val leRefValue2 = "diffenrentBpnL" val leAddressRefValue2 = "diffenrentBpnA" - val createLegalEntityRequest2 = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = leRefValue2, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = leAddressRefValue2, referenceType = BpnRequestIdentifier) - ) - ) + val createLegalEntityRequest2 = minValidLegalEntity() + .withLegalReferences(leRefValue2.toBpnRequest(), leAddressRefValue2.toBpnRequest()) val resultSteps2 = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = createLegalEntityRequest2) val bpnMappings = @@ -409,9 +365,9 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( assertThat(resultSteps2[0].taskId).isEqualTo("TASK_2") assertThat(resultSteps2[0].errors.size).isEqualTo(0) - assertThat(createdLegalEntity1.legalEntity.bpnl).isNotEqualTo(resultSteps2[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) - val createdLegalEntity2 = poolClient.legalEntities.getLegalEntity(resultSteps2[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) - assertThat(resultSteps2[0].businessPartner?.generic?.legalEntity?.legalEntityBpn).isEqualTo(createdLegalEntity2.legalEntity.bpnl) + assertThat(createdLegalEntity1.legalEntity.bpnl).isNotEqualTo(resultSteps2[0].businessPartner.legalEntity.bpnReference.referenceValue!!) + val createdLegalEntity2 = poolClient.legalEntities.getLegalEntity(resultSteps2[0].businessPartner.legalEntity.bpnReference.referenceValue!!) + assertThat(resultSteps2[0].businessPartner.legalEntity.bpnReference.referenceValue).isEqualTo(createdLegalEntity2.legalEntity.bpnl) } @Test @@ -419,33 +375,26 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( val leRefValue = "123" val leAddressRefValue = "222" - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = fullValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = leRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = leAddressRefValue, referenceType = BpnRequestIdentifier) - ) - ) + val createLegalEntityRequest = orchTestDataFactory.createFullBusinessPartner("create") + .withLegalReferences(leRefValue.toBpnRequest(), leAddressRefValue.toBpnRequest()) + .copy(site = null, additionalAddress = null) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors.size).isEqualTo(0) - val updateLegalEntityRequest = createResult[0].businessPartner?.copy( - legalEntity = createResult[0].businessPartner?.legalEntity?.copy( - hasChanged = true, - legalName = "Changed Legal Entity", - legalAddress = createResult[0].businessPartner?.legalEntity?.legalAddress?.copy( - hasChanged = true, - name = "Changed Address Name" - ) - ) - ) - val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = updateLegalEntityRequest!!) + val createdLegalEntity = createResult.first().businessPartner.legalEntity + val updateLegalEntityRequest = orchTestDataFactory.createFullBusinessPartner("update") + .withLegalReferences(createdLegalEntity.bpnReference, createdLegalEntity.legalAddress.bpnReference) + .copy(site = null, additionalAddress = null) + + val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = updateLegalEntityRequest) assertThat(updateResult[0].taskId).isEqualTo("TASK_2") assertThat(updateResult[0].errors.size).isEqualTo(0) - val updatedLegalEntity = poolClient.legalEntities.getLegalEntity(updateResult[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) - assertThat(updatedLegalEntity.legalEntity.legalName).isEqualTo("Changed Legal Entity") - compareLegalEntity(updatedLegalEntity, updateResult[0].businessPartner?.legalEntity) + val updatedLegalEntity = poolClient.legalEntities.getLegalEntity(updateResult[0].businessPartner.legalEntity.bpnReference.referenceValue!!) + assertThat(updatedLegalEntity.legalEntity.legalName).isEqualTo(updateLegalEntityRequest.legalEntity.legalName) + compareLegalEntity(updatedLegalEntity, updateResult[0].businessPartner.legalEntity) } @Test @@ -453,285 +402,133 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( val leRefValue = "123" val leAddressRefValue = "222" - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = fullValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = leRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = leAddressRefValue, referenceType = BpnRequestIdentifier) - ) - ) + val createLegalEntityRequest = orchTestDataFactory.createFullBusinessPartner("create") + .withLegalReferences(leRefValue.toBpnRequest(), leAddressRefValue.toBpnRequest()) + .copy(site = null, additionalAddress = null) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors.size).isEqualTo(0) // Update legal entity with same BpnRequestIdentifier - val updateLegalEntityRequest = createLegalEntityRequest.copy( - legalEntity = createLegalEntityRequest.legalEntity?.copy( - hasChanged = true, - legalName = "Changed Legal Entity", - legalAddress = createLegalEntityRequest.legalEntity?.legalAddress?.copy( - hasChanged = true, - name = "Changed Address Name" - ) - ) - ) + val updateLegalEntityRequest = orchTestDataFactory.createFullBusinessPartner("update") + .withLegalReferences(leRefValue.toBpnRequest(), leAddressRefValue.toBpnRequest()) + .copy(site = null, additionalAddress = null) + val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = updateLegalEntityRequest) assertThat(updateResult[0].taskId).isEqualTo("TASK_2") assertThat(updateResult[0].errors.size).isEqualTo(0) - val updatedLegalEntity = poolClient.legalEntities.getLegalEntity(updateResult[0].businessPartner?.legalEntity?.bpnLReference?.referenceValue!!) - assertThat(updatedLegalEntity.legalEntity.legalName).isEqualTo("Changed Legal Entity") - compareLegalEntity(updatedLegalEntity, updateResult[0].businessPartner?.legalEntity) + val updatedLegalEntity = poolClient.legalEntities.getLegalEntity(updateResult[0].businessPartner.legalEntity.bpnReference.referenceValue!!) + assertThat(updatedLegalEntity.legalEntity.legalName).isEqualTo(updateLegalEntityRequest.legalEntity.legalName) + compareLegalEntity(updatedLegalEntity, updateResult[0].businessPartner.legalEntity) } @Test fun `update legal entity invalid identifier type `() { - val leRef = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier) - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = leRef, - bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - ) - ) + val legalEntityRequest = "123" + val legalAddressRequest = "234" + val createLegalEntityRequest = orchTestDataFactory.createLegalEntityBusinessPartner("create") + .withLegalReferences(legalEntityRequest.toBpnRequest(), legalAddressRequest.toBpnRequest()) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].errors.size).isEqualTo(0) - val updateLegalEntityRequest = createResult[0].businessPartner?.copy( - legalEntity = createResult[0].businessPartner?.legalEntity?.copy( - hasChanged = true, - legalName = "Changed Legal Entity", - identifiers = listOf( - legalEntityIdentifierDto(leRef.referenceValue, 1L, BusinessPartnerVerboseValues.identifierType1), - legalEntityIdentifierDto(leRef.referenceValue, 2L, TypeKeyNameVerboseDto("Invalid", "Invalid")) - ), - legalAddress = createResult[0].businessPartner?.legalEntity?.legalAddress?.copy( - hasChanged = true, - name = "Changed Address Name" - ) + val updateLegalEntityRequest = orchTestDataFactory.createLegalEntityBusinessPartner("update") + .withLegalReferences(legalEntityRequest.toBpnRequest(), legalAddressRequest.toBpnRequest()) + .copyWithLegalEntityIdentifiers( + listOf(Identifier("value", "Invalid", null) ) ) - ) - val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = updateLegalEntityRequest!!) + + val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = updateLegalEntityRequest) + assertThat(updateResult[0].taskId).isEqualTo("TASK_2") assertThat(updateResult[0].errors.size).isEqualTo(1) assertThat(updateResult[0].errors[0].type).isEqualTo(TaskErrorType.Unspecified) - assertThat(updateResult[0].errors[0].description).isEqualTo("Legal Entity Identifier Type 'Invalid' does not exist") } @Test fun `update legal entity invalid legal form `() { - val leRef = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier) - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = leRef, - bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - ) - ) + val legalEntityRequest = "123" + val legalAddressRequest = "234" + val createLegalEntityRequest = orchTestDataFactory.createLegalEntityBusinessPartner("create") + .withLegalReferences(legalEntityRequest.toBpnRequest(), legalAddressRequest.toBpnRequest()) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].errors.size).isEqualTo(0) - val updateLegalEntityRequest = createResult[0].businessPartner?.copy( - legalEntity = createResult[0].businessPartner?.legalEntity?.copy( - hasChanged = true, - legalName = "Changed Legal Entity", - legalForm = "Invalid Form", - legalAddress = createResult[0].businessPartner?.legalEntity?.legalAddress?.copy( - hasChanged = true, - name = "Changed Address Name" - ) - ) - ) + val updateLegalEntityRequest = with(orchTestDataFactory.createLegalEntityBusinessPartner("update")){ + copy(legalEntity = legalEntity.copy(legalForm = "Invalid Form")) + }.withLegalReferences(legalEntityRequest.toBpnRequest(), legalAddressRequest.toBpnRequest()) + val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = updateLegalEntityRequest!!) assertThat(updateResult[0].taskId).isEqualTo("TASK_2") assertThat(updateResult[0].errors.size).isEqualTo(1) assertThat(updateResult[0].errors[0].type).isEqualTo(TaskErrorType.Unspecified) - assertThat(updateResult[0].errors[0].description).isEqualTo("Legal Form 'Invalid Form' does not exist") } @Test fun `update legal entity not existing bpn `() { - val leRef = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier) - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = leRef, - bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - ) - ) - val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) - assertThat(createResult[0].errors.size).isEqualTo(0) - - val updateLegalEntityRequest = createResult[0].businessPartner?.copy( - legalEntity = createResult[0].businessPartner?.legalEntity?.copy( - bpnLReference = BpnReferenceDto(referenceValue = "InvalidBPN", referenceType = Bpn), - hasChanged = true, - legalName = "Changed Legal Entity", - legalAddress = createResult[0].businessPartner?.legalEntity?.legalAddress?.copy( - hasChanged = true, - name = "Changed Address Name" - ) - ) - ) - val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = updateLegalEntityRequest!!) - assertThat(updateResult[0].taskId).isEqualTo("TASK_2") - assertThat(updateResult[0].errors.size).isEqualTo(1) - assertThat(updateResult[0].errors[0].type).isEqualTo(TaskErrorType.Unspecified) - assertThat(updateResult[0].errors[0].description).isEqualTo("Business Partner with BPN 'InvalidBPN' can't be updated as it doesn't exist") - } + val createLegalEntityRequest = orchTestDataFactory.createLegalEntityBusinessPartner("create") + .withLegalReferences("123".toBpnRequest(), "345".toBpnRequest()) - @Test - fun `update legal entity with changed identifiers `() { - - val leRef = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier) - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = leRef, - bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier), - ).copy( - identifiers = listOf( - legalEntityIdentifierDto(leRef.referenceValue, 1L, BusinessPartnerVerboseValues.identifierType1), - legalEntityIdentifierDto(leRef.referenceValue, 2L, BusinessPartnerVerboseValues.identifierType2) - ) - ) - ) val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) assertThat(createResult[0].errors.size).isEqualTo(0) - val updateLegalEntityRequest = createResult[0].businessPartner?.copy( - legalEntity = createResult[0].businessPartner?.legalEntity?.copy( - identifiers = listOf( - legalEntityIdentifierDto(leRef.referenceValue, 3L, BusinessPartnerVerboseValues.identifierType3), - legalEntityIdentifierDto(leRef.referenceValue, 2L, BusinessPartnerVerboseValues.identifierType2) - ), - hasChanged = true, - legalName = "Changed Legal Entity", - legalAddress = createResult[0].businessPartner?.legalEntity?.legalAddress?.copy( - hasChanged = true, - name = "Changed Address Name" + val updateLegalEntityRequest = orchTestDataFactory.createLegalEntityBusinessPartner("update") + .run { + copy( + legalEntity = legalEntity.copy(bpnReference = BpnReference("InvalidBPN", null, Bpn)) ) - ) - ) - val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = updateLegalEntityRequest!!) - assertThat(updateResult[0].taskId).isEqualTo("TASK_2") - assertThat(updateResult[0].errors.size).isEqualTo(0) - } - - @Test - fun `update legal entity by reference value with invalid identifier type `() { + } - val leRef = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier) - val createLegalEntityRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = leRef, - bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - ) - ) - val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntityRequest) - assertThat(createResult[0].errors.size).isEqualTo(0) - - val updateLegalEntityRequest = createLegalEntityRequest.copy( - legalEntity = createLegalEntityRequest.legalEntity?.copy( - hasChanged = true, - legalName = "Changed Legal Entity", - identifiers = listOf( - legalEntityIdentifierDto(leRef.referenceValue, 1L, BusinessPartnerVerboseValues.identifierType1), - legalEntityIdentifierDto(leRef.referenceValue, 2L, TypeKeyNameVerboseDto("Invalid", "Invalid")) - ), - legalAddress = createLegalEntityRequest.legalEntity?.legalAddress?.copy( - hasChanged = true, - name = "Changed Address Name" - ) - ) - ) val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = updateLegalEntityRequest) assertThat(updateResult[0].taskId).isEqualTo("TASK_2") - assertThat(updateResult[0].errors).hasSize(1) + assertThat(updateResult[0].errors.size).isEqualTo(1) assertThat(updateResult[0].errors[0].type).isEqualTo(TaskErrorType.Unspecified) - assertThat(updateResult[0].errors[0].description).isEqualTo("Legal Entity Identifier Type 'Invalid' does not exist") } @Test fun `create Site with minimal fields`() { - - val leRefValue = "123" - val leAddressRefValue = "222" - val siteRefValue = "siteRefValue" - val mainAddressRefValue = "mainAddressRefValue" - val createSiteRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = leRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = leAddressRefValue, referenceType = BpnRequestIdentifier) - ), - site = minValidSite( - bpnSReference = BpnReferenceDto(referenceValue = siteRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = mainAddressRefValue, referenceType = BpnRequestIdentifier) - ) - ) + val createSiteRequest = minValidSite() val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createSiteRequest) - val createdSite = poolClient.sites.getSite(createResult[0].businessPartner?.site?.bpnSReference?.referenceValue!!) + val createdSite = poolClient.sites.getSite(createResult[0].businessPartner.site?.bpnReference?.referenceValue!!) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors).hasSize(0) - assertThat(createdSite.site.name).isEqualTo(createSiteRequest.site?.name) + assertThat(createdSite.site.name).isEqualTo(createSiteRequest.site?.siteName) } @Test fun `create Site with all fields`() { - - val leRefValue = "123" - val leAddressRefValue = "222" - val siteRefValue = "siteRefValue" - val mainAddressRefValue = "mainAddressRefValue" - val createSiteRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = leRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = leAddressRefValue, referenceType = BpnRequestIdentifier) - ), - site = fullValidSite( - bpnSReference = BpnReferenceDto(referenceValue = siteRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = mainAddressRefValue, referenceType = BpnRequestIdentifier) - ) - ) + val createSiteRequest = orchTestDataFactory.createSiteBusinessPartner("create") + .copyWithBpnRequests() val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createSiteRequest) - val createdSite = poolClient.sites.getSite(createResult[0].businessPartner?.site?.bpnSReference?.referenceValue!!) + val createdSite = poolClient.sites.getSite(createResult[0].businessPartner.site?.bpnReference?.referenceValue!!) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors).hasSize(0) - assertThat(createdSite.site.name).isEqualTo(createSiteRequest.site?.name) - compareSite(createdSite, createResult[0].businessPartner?.site) + assertThat(createdSite.site.name).isEqualTo(createSiteRequest.site?.siteName) + compareSite(createdSite, createResult[0].businessPartner.site) } @Test fun `create site with additional address`() { - - val leRefValue = "123" - val leAddressRefValue = "222" - val siteRefValue = "siteRefValue" - val mainAddressRefValue = "mainAddressRefValue" - val additionalAddressRefValue = "77" - val createSiteRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = leRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = leAddressRefValue, referenceType = BpnRequestIdentifier) - ), - site = minValidSite( - bpnSReference = BpnReferenceDto(referenceValue = siteRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = mainAddressRefValue, referenceType = BpnRequestIdentifier) - ), - address = minLogisticAddress( - bpnAReference = BpnReferenceDto(referenceValue = additionalAddressRefValue, referenceType = BpnRequestIdentifier), - ) - ) + val createSiteRequest = orchTestDataFactory.createFullBusinessPartner("create") + .copyWithBpnRequests() val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createSiteRequest) - val createdLeAddress = poolClient.addresses.getAddress(createResult[0].businessPartner?.legalEntity?.legalAddress?.bpnAReference?.referenceValue!!) - val createdAdditionalAddress = poolClient.addresses.getAddress(createResult[0].businessPartner?.address?.bpnAReference?.referenceValue!!) + val createdLeAddress = poolClient.addresses.getAddress(createResult[0].businessPartner.legalEntity.legalAddress.bpnReference.referenceValue!!) + val createdAdditionalAddress = poolClient.addresses.getAddress(createResult[0].businessPartner.additionalAddress?.bpnReference?.referenceValue!!) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors).hasSize(0) - assertThat(createdLeAddress.name).isEqualTo(createSiteRequest.address?.name) - compareLogisticAddress(createdAdditionalAddress, createResult[0].businessPartner?.address) + assertThat(createdLeAddress.name).isEqualTo(createSiteRequest.legalEntity.legalAddress.addressName) + compareLogisticAddress(createdAdditionalAddress, createResult[0].businessPartner.additionalAddress) assertThat(createdAdditionalAddress.bpnLegalEntity).isNull() - assertThat(createdAdditionalAddress.bpnSite).isEqualTo(createResult[0].businessPartner?.site?.bpnSReference?.referenceValue) + assertThat(createdAdditionalAddress.bpnSite).isEqualTo(createResult[0].businessPartner.site?.bpnReference?.referenceValue) assertThat(createdAdditionalAddress.addressType == AddressType.AdditionalAddress).isTrue() } @@ -739,343 +536,182 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( @Test fun `create Site without main address`() { - val createSiteRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - ), - site = fullValidSite( - bpnSReference = BpnReferenceDto(referenceValue = "siteRefValue", referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = "mainAddressRefValue", referenceType = BpnRequestIdentifier) - ).copy( - mainAddress = null - ) - ) + val createSiteRequest = orchTestDataFactory.createSiteBusinessPartner("create") + .copyWithSiteMainAddress(null) + .copyWithBpnRequests() val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createSiteRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") - assertThat(createResult[0].errors).hasSize(1) - assertThat(createResult[0].errors[0].description).isEqualTo("Site main address or BpnA Reference is Empty") + assertThat(createResult[0].errors).hasSize(0) } @Test fun `create Site with invalid addresses administration level 1 and invalid identifier`() { - val bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - val additionalReference = BpnReferenceDto(referenceValue = "additionalRef", referenceType = BpnRequestIdentifier) - val createSiteRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - ), - site = fullValidSite( - bpnSReference = BpnReferenceDto(referenceValue = "siteRefValue", referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = "mainAddressRefValue", referenceType = BpnRequestIdentifier) - ).copy( - mainAddress = minLogisticAddress(bpnAReference).copy( - physicalPostalAddress = minPhysicalPostalAddressDto(bpnAReference).copy( - administrativeAreaLevel1 = "Invalid" - ), - identifiers = listOf( - addressIdentifierDto(bpnAReference.referenceValue, 1L, TypeKeyNameVerboseDto("InvalidKey1", "InvalidName1")), + val createSiteRequest = with(orchTestDataFactory.createSiteBusinessPartner("create") ){ + copy( + site = site!!.copy( + siteMainAddress = site!!.siteMainAddress!!.copy( + identifiers = listOf(Identifier("value", "Invalid", null)), + physicalAddress = site!!.siteMainAddress!!.physicalAddress.copy(administrativeAreaLevel1 = "Invalid") ) ) - ), - address = minLogisticAddress(additionalReference).copy( - physicalPostalAddress = minPhysicalPostalAddressDto(additionalReference).copy( - administrativeAreaLevel1 = "InvalidAdditional" - ), - identifiers = listOf( - addressIdentifierDto(additionalReference.referenceValue, 2L, TypeKeyNameVerboseDto("InvalidKey2", "InvalidName2")), - ) - ), - ) + }.copyWithBpnRequests() val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createSiteRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") - val errorDescriptions = createResult[0].errors.map { it.description } - assertThat(errorDescriptions).containsExactlyInAnyOrder( - "Address administrative area level1 'Invalid' does not exist", - "Address administrative area level1 'InvalidAdditional' does not exist", - "Address Identifier Type 'InvalidKey1' does not exist", - "Address Identifier Type 'InvalidKey2' does not exist" - ) + assertThat(createResult[0].errors).isNotEmpty } @Test fun `create Site with same identifier in main address and additional address`() { - val bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - val additionalReference = BpnReferenceDto(referenceValue = "additionalRef", referenceType = BpnRequestIdentifier) - val sameIdentifier = addressIdentifierDto(bpnAReference.referenceValue, 1L, TypeKeyNameVerboseDto(addressIdentifierTypeDto1.technicalKey, "")) - val createSiteRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - ), - site = minValidSite( - bpnSReference = BpnReferenceDto(referenceValue = "siteRefValue", referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = "mainAddressRefValue", referenceType = BpnRequestIdentifier) - ).copy( - mainAddress = minLogisticAddress(bpnAReference).copy( - identifiers = listOf( - sameIdentifier, + val sameIdentifier = Identifier("value", testDataEnvironment.metadata.legalEntityIdentifierTypes.first().technicalKey, null) + val createSiteRequest = with(orchTestDataFactory.createFullBusinessPartner()){ + copy( + site = site!!.copy( + siteMainAddress = site!!.siteMainAddress!!.copy( + identifiers = listOf(sameIdentifier) ) + ), + additionalAddress = additionalAddress!!.copy( + identifiers = listOf(sameIdentifier) ) - ), - address = minLogisticAddress(additionalReference).copy( - identifiers = listOf( - sameIdentifier, - ) - ), - ) + ) + }.copyWithBpnRequests() val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createSiteRequest) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors).hasSize(1) - assertThat(createResult[0].errors[0].description).isEqualTo("Duplicate Address Identifier: Value 'value_222_1' of type 'ADDR_KEY_ONE'") } @Test - fun `update Site with minimal fields`() { - - val leRefValue = "123" - val leAddressRefValue = "222" - val siteRefValue = "siteRefValue" - val mainAddressRefValue = "mainAddressRefValue" - val createSiteRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = leRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = leAddressRefValue, referenceType = BpnRequestIdentifier) - ), - site = minValidSite( - bpnSReference = BpnReferenceDto(referenceValue = siteRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = mainAddressRefValue, referenceType = BpnRequestIdentifier) - ) - ) + fun `update Site`() { + val createSiteRequest = orchTestDataFactory.createSiteBusinessPartner("create").copyWithBpnRequests() val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createSiteRequest) - val createdSite = poolClient.sites.getSite(createResult[0].businessPartner?.site?.bpnSReference?.referenceValue!!) - assertThat(createdSite.site.name).isEqualTo(createSiteRequest.site?.name) - val updateSiteRequest = createResult[0].businessPartner?.copy( - site = createResult[0].businessPartner?.site?.copy(name = "ChangedName", hasChanged = true) - ) - val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = updateSiteRequest!!) - val updatedSite = poolClient.sites.getSite(updateResult[0].businessPartner?.site?.bpnSReference?.referenceValue!!) - compareSite(updatedSite, updateResult[0].businessPartner?.site) + val updateSiteRequest = with(createResult.first().businessPartner){ + orchTestDataFactory.createSiteBusinessPartner("update") + .withLegalReferences(legalEntity.bpnReference, legalEntity.legalAddress.bpnReference) + .withSiteReferences(site!!.bpnReference, site!!.siteMainAddress!!.bpnReference) + } + + val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = updateSiteRequest) + val updatedSite = poolClient.sites.getSite(updateResult[0].businessPartner.site?.bpnReference?.referenceValue!!) + compareSite(updatedSite, updateResult[0].businessPartner.site) } @Test fun `update Site with invalid bpnS`() { - val siteRefValue = "siteRefValue" - val mainAddressRefValue = "mainAddressRefValue" - val createSiteRquest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - ), - site = minValidSite( - bpnSReference = BpnReferenceDto(referenceValue = siteRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = mainAddressRefValue, referenceType = BpnRequestIdentifier) - ) - ) + val createSiteRequest = orchTestDataFactory.createSiteBusinessPartner("create").copyWithBpnRequests() - val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createSiteRquest) - val createdSite = poolClient.sites.getSite(createResult[0].businessPartner?.site?.bpnSReference?.referenceValue!!) - assertThat(createdSite.site.name).isEqualTo(createSiteRquest.site?.name) + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createSiteRequest) + + val updateSiteRequest = with(createResult.first().businessPartner){ + orchTestDataFactory.createSiteBusinessPartner("update") + .withLegalReferences(legalEntity.bpnReference, legalEntity.legalAddress.bpnReference) + .withSiteReferences(BpnReference("InvalidBPN", null, Bpn), site!!.siteMainAddress!!.bpnReference) + } - val updateSiteRequest = createSiteRquest.copy( - site = createSiteRquest.site?.copy( - name = "ChangedName", - hasChanged = true, - bpnSReference = BpnReferenceDto(referenceValue = "InvalidBPN", referenceType = Bpn), - ) - ) val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = updateSiteRequest) assertThat(updateResult[0].errors).hasSize(1) - assertThat(updateResult[0].errors[0].description).isEqualTo("Business Partner with BPN 'InvalidBPN' can't be updated as it doesn't exist") } @Test fun `update Site with invalid address administration level 1 and invalid identifier`() { - val bpnASiteReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - val additionalReference = BpnReferenceDto(referenceValue = "7777", referenceType = BpnRequestIdentifier) - val siteRefValue = "siteRefValue" - val createSiteReuqest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = "123", referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = "222", referenceType = BpnRequestIdentifier) - ), - site = minValidSite( - bpnSReference = BpnReferenceDto(referenceValue = siteRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = bpnASiteReference - ) - ) + val createSiteRequest = orchTestDataFactory.createSiteBusinessPartner("create").copyWithBpnRequests() - val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createSiteReuqest) - val createdSite = poolClient.sites.getSite(createResult[0].businessPartner?.site?.bpnSReference?.referenceValue!!) - assertThat(createdSite.site.name).isEqualTo(createSiteReuqest.site?.name) - - val updateSiteRequest = createResult[0].businessPartner?.copy( - site = createResult[0].businessPartner?.site?.copy( - name = "Changed Site", - hasChanged = true, - mainAddress = createResult[0].businessPartner?.site?.mainAddress?.copy( - physicalPostalAddress = minPhysicalPostalAddressDto(bpnASiteReference).copy( - administrativeAreaLevel1 = "Invalid" - ), - identifiers = listOf( - addressIdentifierDto(bpnASiteReference.referenceValue, 1L, TypeKeyNameVerboseDto("InvalidKey1", "InvalidName1")), + val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createSiteRequest) + + val updateSiteRequest = with(createResult.first().businessPartner){ + orchTestDataFactory.createSiteBusinessPartner("update") + .withLegalReferences(legalEntity.bpnReference, legalEntity.legalAddress.bpnReference) + .withSiteReferences(site!!.bpnReference, site!!.siteMainAddress!!.bpnReference) + }.run{ + copy( + site = site!!.copy( + siteMainAddress = site!!.siteMainAddress!!.copy( + identifiers = listOf(Identifier("value", "Invalid", null)), + physicalAddress = site!!.siteMainAddress!!.physicalAddress.copy(administrativeAreaLevel1 = "Invalid") ) ) - ), - address = minLogisticAddress(additionalReference).copy( - physicalPostalAddress = minPhysicalPostalAddressDto(additionalReference).copy( - administrativeAreaLevel1 = "InvalidAdditional" - ), - identifiers = listOf( - addressIdentifierDto(additionalReference.referenceValue, 2L, TypeKeyNameVerboseDto("InvalidKey2", "InvalidName2")), - ) - ), - ) + ) + } + val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = updateSiteRequest!!) assertThat(updateResult[0].taskId).isEqualTo("TASK_2") - val errorDescriptions = updateResult[0].errors.map { it.description } - assertThat(errorDescriptions).containsExactlyInAnyOrder( - "Address administrative area level1 'Invalid' does not exist", - "Address administrative area level1 'InvalidAdditional' does not exist", - "Address Identifier Type 'InvalidKey1' does not exist", - "Address Identifier Type 'InvalidKey2' does not exist" - ) + assertThat(updateResult[0].errors).isNotEmpty } @Test fun `update Site with same address identifiers in main address and additional address`() { - - val mainAddressRefValue = BpnReferenceDto(referenceValue = "A222", referenceType = BpnRequestIdentifier) - val additionalAddressReference = BpnReferenceDto(referenceValue = "A333", referenceType = BpnRequestIdentifier) - val sameAddressIdentifier = addressIdentifierDto(additionalAddressReference.referenceValue, 2L, TypeKeyNameVerboseDto(addressIdentifierTypeDto2.technicalKey, "")) - val createSiteRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = "LE123", referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = "A111LE", referenceType = BpnRequestIdentifier) - ), - site = minValidSite( - bpnSReference = BpnReferenceDto(referenceValue = "siteRefValue", referenceType = BpnRequestIdentifier), - bpnAReference = mainAddressRefValue - ).copy( - mainAddress = minLogisticAddress(mainAddressRefValue).copy( - identifiers = listOf( - addressIdentifierDto(mainAddressRefValue.referenceValue, 1L, TypeKeyNameVerboseDto(addressIdentifierTypeDto1.technicalKey, "")), - ) - ) - ), - address = minLogisticAddress( - bpnAReference = additionalAddressReference, - ).copy( - identifiers = listOf( - sameAddressIdentifier, - ) - ) - ) + val createSiteRequest = orchTestDataFactory.createFullBusinessPartner("create").copyWithBpnRequests() val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createSiteRequest) - val createdSite = poolClient.sites.getSite(createResult[0].businessPartner?.site?.bpnSReference?.referenceValue!!) - assertThat(createdSite.site.name).isEqualTo(createSiteRequest.site?.name) - - val updateCopy = createResult[0].businessPartner?.copy( - site = createResult[0].businessPartner?.site?.copy( - name = "ChangedName", - hasChanged = true, - mainAddress = createResult[0].businessPartner?.site?.mainAddress?.copy( - identifiers = listOf( - addressIdentifierDto(mainAddressRefValue.referenceValue, 1L, TypeKeyNameVerboseDto(addressIdentifierTypeDto1.technicalKey, "")), - sameAddressIdentifier, + + val sameIdentifier = Identifier("value", testDataEnvironment.metadata.legalEntityIdentifierTypes.first().technicalKey, null) + val updateSiteRequest = with(createResult.first().businessPartner){ + orchTestDataFactory.createFullBusinessPartner("update") + .withLegalReferences(legalEntity.bpnReference, legalEntity.legalAddress.bpnReference) + .withSiteReferences(site!!.bpnReference, site!!.siteMainAddress!!.bpnReference) + }.run{ + copy( + site = site!!.copy( + siteMainAddress = site!!.siteMainAddress!!.copy( + identifiers = listOf(sameIdentifier) ) + ), + additionalAddress = additionalAddress!!.copy( + identifiers = listOf(sameIdentifier) ) - ), - ) - val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = updateCopy!!) + } + + val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = updateSiteRequest) assertThat(updateResult[0].errors).hasSize(1) - assertThat(updateResult[0].errors[0].description).isEqualTo("Duplicate Address Identifier: Value 'value_A333_2' of type 'ADDR_KEY_TWO'") } @Test fun `update Site with same reference value`() { - - val mainAddressRefValue = BpnReferenceDto(referenceValue = "A222", referenceType = BpnRequestIdentifier) - val additionalAddressReference = BpnReferenceDto(referenceValue = "A333", referenceType = BpnRequestIdentifier) - val createSiteRequest = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = "LE123", referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = "A111LE", referenceType = BpnRequestIdentifier) - ), - site = minValidSite( - bpnSReference = BpnReferenceDto(referenceValue = "siteRefValue", referenceType = BpnRequestIdentifier), - bpnAReference = mainAddressRefValue - ).copy( - mainAddress = minLogisticAddress(mainAddressRefValue).copy( - identifiers = listOf( - addressIdentifierDto(mainAddressRefValue.referenceValue, 1L, TypeKeyNameVerboseDto(addressIdentifierTypeDto1.technicalKey, "")), - ) - ) - ), - address = minLogisticAddress( - bpnAReference = additionalAddressReference, - ).copy( - identifiers = listOf( - addressIdentifierDto(mainAddressRefValue.referenceValue, 2L, TypeKeyNameVerboseDto(addressIdentifierTypeDto2.technicalKey, "")), - ) - ) - ) + val siteRef = "123" + val createSiteRequest = orchTestDataFactory.createSiteBusinessPartner("create") + .copyWithBpnRequests() + .withSiteReferences(siteRef.toBpnRequest(), "345".toBpnRequest()) val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createSiteRequest) - val createdSite = poolClient.sites.getSite(createResult[0].businessPartner?.site?.bpnSReference?.referenceValue!!) - assertThat(createdSite.site.name).isEqualTo(createSiteRequest.site?.name) - - // use create request for update to have same identifier - val updateCopy = createSiteRequest.copy( - site = createSiteRequest.site?.copy( - name = "ChangedName", - hasChanged = true, - ), - ) - val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = updateCopy) + + val updateSiteRequest = with(createResult.first().businessPartner){ + orchTestDataFactory.createSiteBusinessPartner("update") + .withLegalReferences(legalEntity.bpnReference, legalEntity.legalAddress.bpnReference) + .withSiteReferences(siteRef.toBpnRequest(),"345".toBpnRequest()) + } + + val updateResult = upsertGoldenRecordIntoPool(taskId = "TASK_2", businessPartner = updateSiteRequest) assertThat(updateResult[0].errors).hasSize(0) } @Test fun `create address with all fields`() { - val leRefValue = "123" - val leAddressRefValue = "222" - val additionalAddressRefValue = "77" - val fullBpWithAddress = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = leRefValue, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = leAddressRefValue, referenceType = BpnRequestIdentifier) - ), - address = fullLogisticAddressDto( - bpnAReference = BpnReferenceDto(referenceValue = additionalAddressRefValue, referenceType = BpnRequestIdentifier) - ) - ) + val fullBpWithAddress = orchTestDataFactory.createFullBusinessPartner() + .copy(site = null) + .copyWithBpnRequests() val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = fullBpWithAddress) - val createdLeAddress = poolClient.addresses.getAddress(createResult[0].businessPartner?.legalEntity?.legalAddress?.bpnAReference?.referenceValue!!) - val createdAdditionalAddress = poolClient.addresses.getAddress(createResult[0].businessPartner?.address?.bpnAReference?.referenceValue!!) + val createdLeAddress = poolClient.addresses.getAddress(createResult[0].businessPartner.legalEntity.legalAddress.bpnReference.referenceValue!!) + val createdAdditionalAddress = poolClient.addresses.getAddress(createResult[0].businessPartner.additionalAddress?.bpnReference?.referenceValue!!) assertThat(createResult[0].taskId).isEqualTo("TASK_1") assertThat(createResult[0].errors).hasSize(0) assertThat(createdLeAddress.addressType == AddressType.LegalAddress).isTrue() assertThat(createdAdditionalAddress.addressType == AddressType.AdditionalAddress).isTrue() - compareLogisticAddress(createdAdditionalAddress, createResult[0].businessPartner?.address) + compareLogisticAddress(createdAdditionalAddress, createResult[0].businessPartner.additionalAddress) } @Test @@ -1084,12 +720,7 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( val numberOfEntitiesToTest = 100 val referenceIds = (1..numberOfEntitiesToTest).toList() val fullBpWithLegalEntity = referenceIds.map { - minFullBusinessPartner().copy( - legalEntity = fullValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = "" + it, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = "address" + it, referenceType = BpnRequestIdentifier) - ) - ) + orchTestDataFactory.createLegalEntityBusinessPartner("Legal Entity $it").copyWithBpnRequests() } val taskSteps = multipleTaskStep(fullBpWithLegalEntity) @@ -1100,136 +731,15 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( val updateResults = cleaningStepService.upsertGoldenRecordIntoPool(taskSteps) assertThat(updateResults).hasSize(numberOfEntitiesToTest) assertThat(updateResults.filter { it.errors.isNotEmpty() }).hasSize(0) - - val referenceIds2 = ((numberOfEntitiesToTest + 1)..(2 * numberOfEntitiesToTest)).toList() - val fullBpWithLegalEntity2 = referenceIds2.map { - minFullBusinessPartner().copy( - legalEntity = fullValidLegalEntity( - bpnLReference = BpnReferenceDto(referenceValue = "" + it, referenceType = BpnRequestIdentifier), - bpnAReference = BpnReferenceDto(referenceValue = "address" + it, referenceType = BpnRequestIdentifier) - ) - ) - } - val taskSteps2 = multipleTaskStep(fullBpWithLegalEntity2) - val createResults2 = cleaningStepService.upsertGoldenRecordIntoPool(taskSteps2) - assertThat(createResults2).hasSize(numberOfEntitiesToTest) - assertThat(createResults2.filter { it.errors.isNotEmpty() }).hasSize(0) - } - - @Test - fun `update legal entity and create legal entity in one request with duplicated identifier`() { - - val leCreateRef1 = BpnReferenceDto(referenceValue = "LE111", referenceType = BpnRequestIdentifier) - val leCreateAddressRef1 = BpnReferenceDto(referenceValue = "LE111A22", referenceType = BpnRequestIdentifier) - val createLegalEntity1 = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity(bpnLReference = leCreateRef1, bpnAReference = leCreateAddressRef1).copy( - identifiers = listOf( - legalEntityIdentifierDto(leCreateRef1.referenceValue, 1L, BusinessPartnerVerboseValues.identifierType1), - legalEntityIdentifierDto(leCreateRef1.referenceValue, 2L, BusinessPartnerVerboseValues.identifierType2) - ) - ) - ) - val createResult = upsertGoldenRecordIntoPool(taskId = "TASK_1", businessPartner = createLegalEntity1) - assertThat(createResult[0].errors.size).isEqualTo(0) - - val legalEntityUpdateIdentifier = legalEntityIdentifierDto(leCreateRef1.referenceValue, 3L, BusinessPartnerVerboseValues.identifierType3) - val updatedFullBpLegalEntity = createResult[0].businessPartner?.copy( - legalEntity = createResult[0].businessPartner?.legalEntity?.copy( - identifiers = listOf( - legalEntityUpdateIdentifier, // use identifier in update - legalEntityIdentifierDto(leCreateRef1.referenceValue, 2L, BusinessPartnerVerboseValues.identifierType2) - ), - hasChanged = true, - legalName = "Changed Legal Entity" - ) - ) - val leCreateRef2 = BpnReferenceDto(referenceValue = "LE222", referenceType = BpnRequestIdentifier) - val leCreateAddressRef2 = BpnReferenceDto(referenceValue = "LE222A333", referenceType = BpnRequestIdentifier) - val createLegalEntity2 = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity(bpnLReference = leCreateRef2, bpnAReference = leCreateAddressRef2).copy( - identifiers = listOf( - legalEntityUpdateIdentifier, // use same identifier in create - legalEntityIdentifierDto(leCreateRef2.referenceValue, 1L, BusinessPartnerVerboseValues.identifierType1) - ) - ) - ) - val updateTask = TaskStepReservationEntryDto(taskId = "TASK_2", businessPartner = updatedFullBpLegalEntity!!) - val createTask2 = TaskStepReservationEntryDto(taskId = "TASK_3", businessPartner = createLegalEntity2) - val createUpdateResult = cleaningStepService.upsertGoldenRecordIntoPool(listOf(updateTask, createTask2)) - - assertThat(createUpdateResult[0].taskId).isEqualTo("TASK_2") - assertThat(createUpdateResult[1].taskId).isEqualTo("TASK_3") - assertThat(createUpdateResult[0].errors.size).isEqualTo(1) - assertThat(createUpdateResult[1].errors.size).isEqualTo(1) - assertThat(createUpdateResult[0].errors[0].description).isEqualTo("Duplicate Legal Entity Identifier: Value 'value_LE111_3' of type 'VAT_FR'") - } - - @Test - fun `create legal entity and create site in one request with duplicated identifier`() { - - val leCreateRef1 = BpnReferenceDto(referenceValue = "LE111", referenceType = BpnRequestIdentifier) - val leCreateAddressRef1 = BpnReferenceDto(referenceValue = "LE111A11", referenceType = BpnRequestIdentifier) - val additionalAddressLeRef1 = BpnReferenceDto(referenceValue = "LE111A33", referenceType = BpnRequestIdentifier) - val duplicatIdentifier = addressIdentifierDto(leCreateAddressRef1.referenceValue, 1L, TypeKeyNameVerboseDto(addressIdentifierTypeDto1.technicalKey, "")) - val createLegalEntity1 = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity(bpnLReference = leCreateRef1, bpnAReference = leCreateAddressRef1).copy( - legalAddress = minLogisticAddress(leCreateAddressRef1).copy( - identifiers = listOf( - duplicatIdentifier, - ) - ) - ), - address = minLogisticAddress(additionalAddressLeRef1).copy( - identifiers = listOf( - addressIdentifierDto(additionalAddressLeRef1.referenceValue, 2L, TypeKeyNameVerboseDto(addressIdentifierTypeDto1.technicalKey, "")), - ) - ) - ) - - val leCreateRef2 = BpnReferenceDto(referenceValue = "LE222", referenceType = BpnRequestIdentifier) - val leCreateAddressRef2 = BpnReferenceDto(referenceValue = "LE222A22", referenceType = BpnRequestIdentifier) - val createSiteRef2 = BpnReferenceDto(referenceValue = "SE333", referenceType = BpnRequestIdentifier) - val mainAddressRef2 = BpnReferenceDto(referenceValue = "SE333A66", referenceType = BpnRequestIdentifier) - val additionalAddressSiteRef2 = BpnReferenceDto(referenceValue = "SE333A88", referenceType = BpnRequestIdentifier) - val createSite1 = minFullBusinessPartner().copy( - legalEntity = minValidLegalEntity(bpnLReference = leCreateRef2, bpnAReference = leCreateAddressRef2).copy( - legalAddress = minLogisticAddress(leCreateAddressRef2).copy( - identifiers = listOf( - addressIdentifierDto(leCreateAddressRef2.referenceValue, 3L, TypeKeyNameVerboseDto(addressIdentifierTypeDto1.technicalKey, "")), - ) - ) - ), - site = minValidSite(bpnSReference = createSiteRef2, bpnAReference = mainAddressRef2).copy( - mainAddress = minLogisticAddress(mainAddressRef2).copy( - identifiers = listOf( - addressIdentifierDto(mainAddressRef2.referenceValue, 4L, TypeKeyNameVerboseDto(addressIdentifierTypeDto1.technicalKey, "")), - ) - ) - ), - address = minLogisticAddress(additionalAddressSiteRef2).copy( - identifiers = listOf( - duplicatIdentifier, - ) - ) - ) - - val createLegalEntityTask = TaskStepReservationEntryDto(taskId = "TASK_1", businessPartner = createLegalEntity1) - val createSiteTask = TaskStepReservationEntryDto(taskId = "TASK_2", businessPartner = createSite1) - val createResult = cleaningStepService.upsertGoldenRecordIntoPool(listOf(createLegalEntityTask, createSiteTask)) - assertThat(createResult[0].taskId).isEqualTo("TASK_1") - assertThat(createResult[1].taskId).isEqualTo("TASK_2") - assertThat(createResult[0].errors.size).isEqualTo(1) - assertThat(createResult[1].errors.size).isEqualTo(1) - assertThat(createResult[0].errors[0].description).isEqualTo("Duplicate Address Identifier: Value 'value_LE111A11_1' of type 'ADDR_KEY_ONE'") } - fun upsertGoldenRecordIntoPool(taskId: String, businessPartner: BusinessPartnerFullDto): List { + fun upsertGoldenRecordIntoPool(taskId: String, businessPartner: BusinessPartner): List { val taskStep = singleTaskStep(taskId = taskId, businessPartner = businessPartner) return cleaningStepService.upsertGoldenRecordIntoPool(taskStep) } - fun singleTaskStep(taskId: String, businessPartner: BusinessPartnerFullDto): List { + fun singleTaskStep(taskId: String, businessPartner: BusinessPartner): List { return listOf( TaskStepReservationEntryDto( @@ -1239,365 +749,97 @@ class TaskStepFetchAndReserveServiceTest @Autowired constructor( ) } - fun multipleTaskStep(businessPartners: List): List { + fun multipleTaskStep(businessPartners: List): List { return businessPartners.map { TaskStepReservationEntryDto( - taskId = it.legalEntity?.bpnLReference?.referenceValue!!, + taskId = it.legalEntity.bpnReference.referenceValue!!, businessPartner = it ) } } - - fun minFullBusinessPartner(): BusinessPartnerFullDto { - - return BusinessPartnerFullDto(generic = BusinessPartnerGenericDto()) - } - - fun emptyLegalEntity(): LegalEntityDto { - - return LegalEntityDto(isCatenaXMemberData = false) - } - - fun minValidLegalEntity(bpnLReference: BpnReferenceDto, bpnAReference: BpnReferenceDto): LegalEntityDto { - - return LegalEntityDto( - bpnLReference = bpnLReference, - legalName = "legalName_" + bpnLReference.referenceValue, - legalAddress = minLogisticAddress(bpnAReference = bpnAReference), - isCatenaXMemberData = false, - confidenceCriteria = fullConfidenceCriteria() - ) - } - - fun fullValidLegalEntity(bpnLReference: BpnReferenceDto, bpnAReference: BpnReferenceDto): LegalEntityDto { - - return LegalEntityDto( - bpnLReference = bpnLReference, - legalName = "legalName_" + bpnLReference.referenceValue, - legalShortName = "shortName_" + bpnLReference.referenceValue, - legalForm = BusinessPartnerVerboseValues.legalForm1.technicalKey, - identifiers = listOf( - legalEntityIdentifierDto(bpnLReference.referenceValue, 1L, BusinessPartnerVerboseValues.identifierType1), - legalEntityIdentifierDto(bpnLReference.referenceValue, 2L, BusinessPartnerVerboseValues.identifierType2) - ), - states = listOf( - legalEntityState(bpnLReference.referenceValue, 1L, BusinessStateType.ACTIVE), - legalEntityState(bpnLReference.referenceValue, 2L, BusinessStateType.INACTIVE) - ), - legalAddress = fullLogisticAddressDto(bpnAReference), - isCatenaXMemberData = false, - confidenceCriteria = fullConfidenceCriteria() - ) - } - - fun legalEntityIdentifierDto(name: String, id: Long, type: TypeKeyNameVerboseDto): LegalEntityIdentifierDto { - - return LegalEntityIdentifierDto( - value = "value_" + name + "_" + id, - issuingBody = "issuingBody_" + name + "_" + id, - type = type.technicalKey - ) - } - - fun addressIdentifierDto(name: String, id: Long, type: TypeKeyNameVerboseDto): AddressIdentifierDto { - - return AddressIdentifierDto( - value = "value_" + name + "_" + id, - type = type.technicalKey - ) + fun BusinessPartner.withAdditionalAddressReference(postalAddressBpn: BpnReference): BusinessPartner { + return copy(additionalAddress = additionalAddress?.copy(bpnReference = postalAddressBpn)) } - fun legalEntityState(name: String, id: Long, type: BusinessStateType): LegalEntityStateDto { - - return LegalEntityStateDto( - validFrom = LocalDateTime.now().plusDays(id), - validTo = LocalDateTime.now().plusDays(id + 2), - type = type - ) - } - fun siteState(name: String, id: Long, type: BusinessStateType): SiteStateDto { - - return SiteStateDto( - validFrom = LocalDateTime.now().plusDays(id), - validTo = LocalDateTime.now().plusDays(id + 2), - type = type + fun BusinessPartner.withSiteReferences(siteBpn: BpnReference, siteMainAddressBpn: BpnReference): BusinessPartner { + return copy( + site = site?.copy( + bpnReference = siteBpn, + siteMainAddress = site!!.siteMainAddress!!.copy(bpnReference = siteMainAddressBpn) + ) ) } - fun addressState(name: String, id: Long, type: BusinessStateType): AddressStateDto { - - return AddressStateDto( - validFrom = LocalDateTime.now().plusDays(id), - validTo = LocalDateTime.now().plusDays(id + 2), - type = type + fun BusinessPartner.withLegalReferences(legalEntityBpn: BpnReference, legalAddressBpn: BpnReference): BusinessPartner { + return copy( + legalEntity = legalEntity.copy( + bpnReference = legalEntityBpn, + legalAddress = legalEntity.legalAddress.copy( + bpnReference = legalAddressBpn + ) + ) ) } - - fun classificationDto(name: String, id: Long, type: ClassificationType): LegalEntityClassificationDto { - - return LegalEntityClassificationDto( - code = "code_" + name + "_" + id, - value = "value_" + name + "_" + id, - type = type + private fun minValidLegalEntity(): BusinessPartner { + return with(BusinessPartner.empty) { + copy( + legalEntity = legalEntity.copy( + bpnReference = BpnReference(referenceValue = "BPNL REQUEST ID", null, referenceType = BpnRequestIdentifier), + legalName = "Legal Name", + confidenceCriteria = fullConfidenceCriteria(), + legalAddress = minValidAddress().copy(confidenceCriteria = fullConfidenceCriteria()) + ) ) + } } - fun minLogisticAddress(bpnAReference: BpnReferenceDto): LogisticAddressDto { - - return LogisticAddressDto( - bpnAReference = bpnAReference, - physicalPostalAddress = minPhysicalPostalAddressDto(bpnAReference), - confidenceCriteria = fullConfidenceCriteria() - ) + private fun minValidSite(): BusinessPartner { + return with(BusinessPartner.empty) { + copy( + legalEntity = minValidLegalEntity().legalEntity, + site = Site.empty.copy( + bpnReference = BpnReference(referenceValue = "BPNS REQUEST ID", null, referenceType = BpnRequestIdentifier), + siteName = "Site Name", + confidenceCriteria = fullConfidenceCriteria(), + siteMainAddress = minValidAddress() + ) + ) + } } - private fun minPhysicalPostalAddressDto(bpnAReference: BpnReferenceDto) = PhysicalPostalAddressDto( - country = CountryCode.DE, - city = "City_" + bpnAReference.referenceValue - ) - - fun fullLogisticAddressDto(bpnAReference: BpnReferenceDto): LogisticAddressDto { - - return LogisticAddressDto( - bpnAReference = bpnAReference, - name = "name_" + bpnAReference.referenceValue, - identifiers = listOf( - addressIdentifierDto(bpnAReference.referenceValue, 1L, TypeKeyNameVerboseDto(addressIdentifierTypeDto1.technicalKey, "")), - addressIdentifierDto(bpnAReference.referenceValue, 2L, TypeKeyNameVerboseDto(addressIdentifierTypeDto2.technicalKey, "")) - ), - states = listOf( - addressState(bpnAReference.referenceValue, 1L, BusinessStateType.ACTIVE), - addressState(bpnAReference.referenceValue, 2L, BusinessStateType.INACTIVE) - ), - physicalPostalAddress = PhysicalPostalAddressDto( - geographicCoordinates = GeoCoordinateDto(longitude = 1.1f, latitude = 2.2f, altitude = 3.3f), - country = CountryCode.DE, - administrativeAreaLevel1 = "AD-07", - administrativeAreaLevel2 = "adminArea2_" + bpnAReference.referenceValue, - administrativeAreaLevel3 = "adminArea3_" + bpnAReference.referenceValue, - postalCode = "postalCode_" + bpnAReference.referenceValue, - city = "city_" + bpnAReference.referenceValue, - street = StreetDto( - name = "name_" + bpnAReference.referenceValue, - houseNumber = "houseNumber_" + bpnAReference.referenceValue, - houseNumberSupplement = "houseNumberSupplement_" + bpnAReference.referenceValue, - milestone = "milestone_" + bpnAReference.referenceValue, - direction = "direction_" + bpnAReference.referenceValue, - namePrefix = "namePrefix_" + bpnAReference.referenceValue, - additionalNamePrefix = "additionalNamePrefix_" + bpnAReference.referenceValue, - nameSuffix = "nameSuffix_" + bpnAReference.referenceValue, - additionalNameSuffix = "additionalNameSuffix_" + bpnAReference.referenceValue, - ), - district = "district_" + bpnAReference.referenceValue, - companyPostalCode = "companyPostalCode_" + bpnAReference.referenceValue, - industrialZone = "industrialZone_" + bpnAReference.referenceValue, - building = "building_" + bpnAReference.referenceValue, - floor = "floor_" + bpnAReference.referenceValue, - door = "door_" + bpnAReference.referenceValue, - ), - alternativePostalAddress = AlternativePostalAddressDto( - geographicCoordinates = GeoCoordinateDto(longitude = 12.3f, latitude = 4.56f, altitude = 7.89f), - country = CountryCode.DE, - administrativeAreaLevel1 = "DE-BW", - postalCode = "alternate_postalCode_" + bpnAReference.referenceValue, - city = "alternate_city_" + bpnAReference.referenceValue, - deliveryServiceType = DeliveryServiceType.PO_BOX, - deliveryServiceQualifier = "deliveryServiceQualifier_" + bpnAReference.referenceValue, - deliveryServiceNumber = "deliveryServiceNumber_" + bpnAReference.referenceValue, - ), - confidenceCriteria = fullConfidenceCriteria() - ) + private fun minValidAddress(): PostalAddress { + return with(PostalAddress.empty){ + copy( + confidenceCriteria = fullConfidenceCriteria(), + physicalAddress = physicalAddress.copy( + country = CountryCode.DE.alpha2, + city = "Stuttgart" + ) + ) + } } - fun minValidSite(bpnSReference: BpnReferenceDto, bpnAReference: BpnReferenceDto): SiteDto { + fun assertTaskError(step: TaskStepResultEntryDto, taskId: String, error: CleaningError) { - return SiteDto( - bpnSReference = bpnSReference, - name = "siteName_" + bpnSReference.referenceValue, - mainAddress = minLogisticAddress(bpnAReference = bpnAReference), - confidenceCriteria = fullConfidenceCriteria() - ) + assertThat(step.taskId).isEqualTo(taskId) + assertThat(step.errors.size).isEqualTo(1) + assertThat(step.errors[0].description).isEqualTo(error.message) } - fun fullValidSite(bpnSReference: BpnReferenceDto, bpnAReference: BpnReferenceDto): SiteDto { - - return SiteDto( - bpnSReference = bpnSReference, - name = "siteName_" + bpnSReference.referenceValue, - states = listOf( - siteState(bpnSReference.referenceValue, 1L, BusinessStateType.ACTIVE), siteState(bpnSReference.referenceValue, 2L, BusinessStateType.INACTIVE) - ), - mainAddress = fullLogisticAddressDto(bpnAReference), - confidenceCriteria = fullConfidenceCriteria() - ) - } + private fun String.toBpnRequest() = BpnReference(this, null, BpnRequestIdentifier) - fun fullConfidenceCriteria() = - ConfidenceCriteriaDto( + private fun fullConfidenceCriteria() = + ConfidenceCriteria( sharedByOwner = true, numberOfSharingMembers = 1, checkedByExternalDataSource = true, - lastConfidenceCheckAt = LocalDateTime.now(), - nextConfidenceCheckAt = LocalDateTime.now().plusDays(1), + lastConfidenceCheckAt = Instant.now(), + nextConfidenceCheckAt = Instant.now().plus(1, ChronoUnit.DAYS), confidenceLevel = 10 ) - - fun assertTaskError(step: TaskStepResultEntryDto, taskId: String, error: CleaningError) { - - assertThat(step.taskId).isEqualTo(taskId) - assertThat(step.errors.size).isEqualTo(1) - assertThat(step.errors[0].description).isEqualTo(error.message) - - } - - fun compareLegalEntity(verboseRequest: LegalEntityWithLegalAddressVerboseDto, legalEntity: LegalEntityDto?) { - - val verboseLegalEntity = verboseRequest.legalEntity - - assertThat(verboseLegalEntity.legalShortName).isEqualTo(legalEntity?.legalShortName) - assertThat(verboseLegalEntity.legalFormVerbose?.technicalKey).isEqualTo(legalEntity?.legalForm) - compareStates(verboseLegalEntity.states, legalEntity?.states) - compareIdentifiers(verboseLegalEntity.identifiers, legalEntity?.identifiers) - - val verboseLegalAddress = verboseRequest.legalAddress - assertThat(verboseLegalAddress.bpnLegalEntity).isEqualTo(legalEntity?.bpnLReference?.referenceValue) - assertThat(verboseLegalAddress.addressType == AddressType.LegalAddress).isTrue() - compareLogisticAddress(verboseLegalAddress, legalEntity?.legalAddress) - } - - fun compareSite(verboseRequest: SiteWithMainAddressVerboseDto, site: SiteDto?) { - - val verboseSite = verboseRequest.site - - assertThat(verboseSite.name).isEqualTo(site?.name) - assertThat(verboseSite.bpns).isEqualTo(site?.bpnSReference?.referenceValue) - compareSiteStates(verboseSite.states, site?.states) - - val verboseMainAddress = verboseRequest.mainAddress - assertThat(verboseMainAddress.bpnSite).isEqualTo(site?.bpnSReference?.referenceValue) - val mainAddress = site?.mainAddress - assertThat(verboseMainAddress.addressType == AddressType.SiteMainAddress).isTrue() - compareLogisticAddress(verboseMainAddress, mainAddress) - } - - private fun compareLogisticAddress(verboseAddress: LogisticAddressVerboseDto, address: LogisticAddressDto?) { - - assertThat(verboseAddress.name).isEqualTo(address?.name) - compareAddressStates(verboseAddress.states, address?.states) - compareAddressIdentifiers(verboseAddress.identifiers, address?.identifiers) - - - val verbosePhysicalAddress = verboseAddress.physicalPostalAddress - val physicalAddress = address?.physicalPostalAddress - assertThat(verbosePhysicalAddress).usingRecursiveComparison() - .ignoringFields(PhysicalPostalAddressVerboseDto::countryVerbose.name, PhysicalPostalAddressVerboseDto::administrativeAreaLevel1Verbose.name) - .isEqualTo(physicalAddress) - assertThat(verbosePhysicalAddress.country.name).isEqualTo(physicalAddress?.country?.name) - assertThat(verbosePhysicalAddress.administrativeAreaLevel1).isEqualTo(physicalAddress?.administrativeAreaLevel1) - val verboseAlternAddress = verboseAddress.alternativePostalAddress - val alternAddress = address?.alternativePostalAddress - assertThat(verboseAlternAddress).usingRecursiveComparison() - .ignoringFields(AlternativePostalAddressVerboseDto::countryVerbose.name, AlternativePostalAddressVerboseDto::administrativeAreaLevel1Verbose.name) - .isEqualTo(alternAddress) - assertThat(verboseAlternAddress?.country?.name).isEqualTo(alternAddress?.country?.name) - assertThat(verboseAlternAddress?.administrativeAreaLevel1).isEqualTo(alternAddress?.administrativeAreaLevel1) - } - - fun compareAddressStates(statesVerbose: Collection, states: Collection?) { - - assertThat(statesVerbose.size).isEqualTo(states?.size ?: 0) - val sortedVerboseStates = statesVerbose.sortedBy { it.validFrom } - val sortedStates = states?.sortedBy { it.validFrom } - sortedVerboseStates.indices.forEach { - assertThat(sortedVerboseStates[it].typeVerbose.technicalKey.name).isEqualTo(sortedStates!![it].type.name) - assertThat(sortedVerboseStates[it]).usingRecursiveComparison() - .withEqualsForFields(isEqualToIgnoringMilliseconds(), AddressStateVerboseDto::validTo.name) - .withEqualsForFields(isEqualToIgnoringMilliseconds(), AddressStateVerboseDto::validFrom.name) - .ignoringFields(AddressStateVerboseDto::typeVerbose.name).isEqualTo(sortedStates[it]) - } - } - - fun compareAddressIdentifiers(identifiersVerbose: Collection, identifiers: Collection?) { - - assertThat(identifiersVerbose.size).isEqualTo(identifiers?.size ?: 0) - val sortedVerboseIdentifiers = identifiersVerbose.sortedBy { it.typeVerbose.name } - val sortedIdentifiers = identifiers!!.sortedBy { it.type } - sortedVerboseIdentifiers.indices.forEach { - assertThat(sortedVerboseIdentifiers[it].typeVerbose.technicalKey).isEqualTo(sortedIdentifiers[it].type) - assertThat(sortedVerboseIdentifiers[it]).usingRecursiveComparison() - .ignoringFields(AddressIdentifierVerboseDto::typeVerbose.name) - .isEqualTo(sortedIdentifiers[it]) - } - } - - fun compareStates(statesVerbose: Collection, states: Collection?) { - - assertThat(statesVerbose.size).isEqualTo(states?.size ?: 0) - val sortedVerboseStates = statesVerbose.sortedBy { it.validFrom } - val sortedStates = states!!.sortedBy { it.validFrom } - sortedVerboseStates.indices.forEach { - assertThat(sortedVerboseStates[it].typeVerbose.technicalKey.name).isEqualTo(sortedStates[it].type.name) - assertThat(sortedVerboseStates[it]).usingRecursiveComparison() - .withEqualsForFields(isEqualToIgnoringMilliseconds(), LegalEntityStateVerboseDto::validTo.name ) - .withEqualsForFields(isEqualToIgnoringMilliseconds(), LegalEntityStateVerboseDto::validFrom.name) - .ignoringFields(LegalEntityStateVerboseDto::typeVerbose.name) - .isEqualTo(sortedStates[it]) - } - } - - fun compareSiteStates(statesVerbose: Collection, states: Collection?) { - - assertThat(statesVerbose.size).isEqualTo(states?.size ?: 0) - val sortedVerboseStates = statesVerbose.sortedBy { it.validFrom } - val sortedStates = states!!.sortedBy { it.validFrom } - sortedVerboseStates.indices.forEach { - assertThat(sortedVerboseStates[it].typeVerbose.technicalKey.name).isEqualTo(sortedStates[it].type.name) - assertThat(sortedVerboseStates[it]).usingRecursiveComparison() - .withEqualsForFields(isEqualToIgnoringMilliseconds(), SiteStateVerboseDto::validTo.name) - .withEqualsForFields(isEqualToIgnoringMilliseconds(), SiteStateVerboseDto::validFrom.name) - .ignoringFields(SiteStateVerboseDto::typeVerbose.name) - .isEqualTo(sortedStates[it]) - } - } - - fun isEqualToIgnoringMilliseconds(): BiPredicate { - return BiPredicate { d1, d2 -> - (d1 == null && d2 == null) - || d1.truncatedTo(ChronoUnit.SECONDS).equals(d2.truncatedTo(ChronoUnit.SECONDS)) - } - } - - fun compareClassifications( - classificationsVerbose: Collection, - classifications: Collection? - ) { - - assertThat(classificationsVerbose.size).isEqualTo(classifications?.size ?: 0) - val sortedVerboseClassifications = classificationsVerbose.sortedBy { it.typeVerbose.name } - val sortedClassifications = classifications!!.sortedBy { it.type.name } - sortedVerboseClassifications.indices.forEach { - assertThat(sortedVerboseClassifications[it].typeVerbose.technicalKey.name).isEqualTo(sortedClassifications[it].type.name) - assertThat(sortedVerboseClassifications[it]).usingRecursiveComparison() - .ignoringFields(LegalEntityClassificationVerboseDto::typeVerbose.name) - .isEqualTo(sortedClassifications[it]) - } - } - - fun compareIdentifiers(identifiersVerbose: Collection, identifiers: Collection?) { - - assertThat(identifiersVerbose.size).isEqualTo(identifiers?.size ?: 0) - val sortedVerboseIdentifiers = identifiersVerbose.sortedBy { it.typeVerbose.name } - val sortedIdentifiers = identifiers!!.sortedBy { it.type } - sortedVerboseIdentifiers.indices.forEach { - assertThat(sortedVerboseIdentifiers[it].typeVerbose.technicalKey).isEqualTo(sortedIdentifiers[it].type) - assertThat(sortedVerboseIdentifiers[it]).usingRecursiveComparison() - .ignoringFields(LegalEntityIdentifierVerboseDto::typeVerbose.name).isEqualTo(sortedIdentifiers[it]) - } - } - }