diff --git a/app/src/main/resources/config/core-config.properties b/app/src/main/resources/config/core-config.properties index fcab7975e..8f8e3dd78 100644 --- a/app/src/main/resources/config/core-config.properties +++ b/app/src/main/resources/config/core-config.properties @@ -17,8 +17,6 @@ mscore.mail-template.placeholders.onboarding.notificationProductName = productNa scheduler.threads.max-number=${THREADS_SCHEDULE_MAX_NUMBER:1} scheduler.fixed-delay.delay=${SCHEDULER_FIXED_DELAY:20000} -scheduler.regenerate-kafka-queue-config.name=${SCHEDULER_REGENERATE_KAFKA_QUEUE_CONFIG_NAME:KafkaScheduler} -scheduler.regenerate-kafka-queue.enabled=${SCHEDULER_REGENERATE_KAFKA_QUEUE_ENABLED:false} mscore.blob-storage.container-product=${PRODUCT_STORAGE_CONTAINER:selc-d-product} mscore.blob-storage.filepath-product = products.json diff --git a/app/src/main/resources/config/kafka.properties b/app/src/main/resources/config/kafka.properties deleted file mode 100644 index 9a38ebc7f..000000000 --- a/app/src/main/resources/config/kafka.properties +++ /dev/null @@ -1,7 +0,0 @@ -kafka-manager.datalake-contracts-sasl-jaas-config = ${KAFKA_CONTRACTS_SELFCARE_WO_SASL_JAAS_CONFIG} -kafka-manager.users-sasl-jaas-config = ${KAFKA_USERS_SELFCARE_WO_SASL_JAAS_CONFIG} -kafka-manager.datalake-contracts-topic = ${KAFKA_CONTRACTS_TOPIC} -kafka-manager.sc-users-topic= ${KAFKA_USER_TOPIC} -kafka-manager.sasl-mechanism = ${KAFKA_SASL_MECHANISM:PLAIN} -kafka-manager.security-protocol = ${KAFKA_SECURITY_PROTOCOL:SASL_SSL} -kafka-manager.bootstrap-servers = ${KAFKA_BROKER} diff --git a/app/src/main/resources/swagger/api-docs.json b/app/src/main/resources/swagger/api-docs.json index d584a9dcf..0879ebed6 100644 --- a/app/src/main/resources/swagger/api-docs.json +++ b/app/src/main/resources/swagger/api-docs.json @@ -21,9 +21,6 @@ "tags" : [ { "name" : "Delegation", "description" : "Delegation Controller" - }, { - "name" : "Event", - "description" : "Queue Notification Controller" }, { "name" : "External", "description" : "External Controller" @@ -2328,71 +2325,6 @@ "bearerAuth" : [ "global" ] } ] } - }, - "/notification-event/contracts" : { - "put" : { - "tags" : [ "Event" ], - "summary" : "resendContractsByInstitutionIdAndTokenId", - "description" : "Function to send a specific onboarding using institutionId and tokenId ", - "operationId" : "resendContractsByInstitutionIdAndTokenIdUsingPUT", - "parameters" : [ { - "name" : "tokenId", - "in" : "query", - "description" : "tokenId", - "required" : true, - "style" : "form", - "schema" : { - "type" : "string" - } - }, { - "name" : "institutionId", - "in" : "query", - "description" : "institutionId", - "required" : true, - "style" : "form", - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "200" : { - "description" : "OK" - }, - "400" : { - "description" : "Bad Request", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "403" : { - "description" : "Forbidden", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - }, - "404" : { - "description" : "Not Found", - "content" : { - "application/problem+json" : { - "schema" : { - "$ref" : "#/components/schemas/Problem" - } - } - } - } - }, - "security" : [ { - "bearerAuth" : [ "global" ] - } ] - } } }, "components" : { @@ -3020,12 +2952,6 @@ }, "tokenId" : { "type" : "string" - }, - "users" : { - "type" : "array", - "items" : { - "$ref" : "#/components/schemas/Person" - } } } }, @@ -3723,41 +3649,6 @@ } } }, - "Person" : { - "title" : "Person", - "type" : "object", - "properties" : { - "email" : { - "type" : "string" - }, - "env" : { - "type" : "string", - "enum" : [ "COLL", "DEV", "PROD", "ROOT" ] - }, - "id" : { - "type" : "string" - }, - "name" : { - "type" : "string" - }, - "productRole" : { - "type" : "string" - }, - "role" : { - "type" : "string", - "enum" : [ "DELEGATE", "MANAGER", "OPERATOR", "SUB_DELEGATE" ] - }, - "roleLabel" : { - "type" : "string" - }, - "surname" : { - "type" : "string" - }, - "taxCode" : { - "type" : "string" - } - } - }, "Problem" : { "title" : "Problem", "type" : "object", diff --git a/app/src/test/java/it/pagopa/selfcare/mscore/web/config/SwaggerConfigTest.java b/app/src/test/java/it/pagopa/selfcare/mscore/web/config/SwaggerConfigTest.java index e0dd11aba..572f386f5 100644 --- a/app/src/test/java/it/pagopa/selfcare/mscore/web/config/SwaggerConfigTest.java +++ b/app/src/test/java/it/pagopa/selfcare/mscore/web/config/SwaggerConfigTest.java @@ -47,18 +47,12 @@ class SwaggerConfigTest { @MockBean OnboardingService onboardingService; - @MockBean - QueueNotificationService queueNotificationService; - @Autowired WebApplicationContext context; @MockBean DelegationService delegationService; - @MockBean - private UserEventService userEventService; - @Autowired private ObjectMapper objectMapper; @@ -66,7 +60,7 @@ class SwaggerConfigTest { void swaggerSpringPlugin() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); mockMvc.perform(MockMvcRequestBuilders.get("/v3/api-docs").accept(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andDo((result) -> { + .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()).andDo(result -> { assertNotNull(result); assertNotNull(result.getResponse()); final String content = result.getResponse().getContentAsString(); diff --git a/connector-api/pom.xml b/connector-api/pom.xml index 7ac6b0f6e..05da1aeb5 100644 --- a/connector-api/pom.xml +++ b/connector-api/pom.xml @@ -25,11 +25,6 @@ org.springframework.data spring-data-commons - - org.springframework.kafka - spring-kafka - 2.7.3 - it.pagopa.selfcare selc-commons-base @@ -38,7 +33,7 @@ it.pagopa.selfcare onboarding-sdk-product - 0.1.10 + 0.1.8 diff --git a/connector-api/src/main/java/it/pagopa/selfcare/mscore/api/ConfigConnector.java b/connector-api/src/main/java/it/pagopa/selfcare/mscore/api/ConfigConnector.java deleted file mode 100644 index 7b827eaa7..000000000 --- a/connector-api/src/main/java/it/pagopa/selfcare/mscore/api/ConfigConnector.java +++ /dev/null @@ -1,9 +0,0 @@ -package it.pagopa.selfcare.mscore.api; - -import it.pagopa.selfcare.mscore.model.Config; - -public interface ConfigConnector { - - Config findAndUpdate(String id); - -} diff --git a/connector-api/src/main/java/it/pagopa/selfcare/mscore/model/Config.java b/connector-api/src/main/java/it/pagopa/selfcare/mscore/model/Config.java deleted file mode 100644 index e3efd942a..000000000 --- a/connector-api/src/main/java/it/pagopa/selfcare/mscore/model/Config.java +++ /dev/null @@ -1,22 +0,0 @@ -package it.pagopa.selfcare.mscore.model; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class Config { - - private String id; - - private String productFilter; - - private int firstPage; - - private int lastPage; - - private boolean enableKafkaScheduler; - -} diff --git a/connector-api/src/main/java/it/pagopa/selfcare/mscore/model/NotificationToSend.java b/connector-api/src/main/java/it/pagopa/selfcare/mscore/model/NotificationToSend.java deleted file mode 100644 index 6e3fb0b2e..000000000 --- a/connector-api/src/main/java/it/pagopa/selfcare/mscore/model/NotificationToSend.java +++ /dev/null @@ -1,30 +0,0 @@ -package it.pagopa.selfcare.mscore.model; - -import com.fasterxml.jackson.annotation.JsonInclude; -import it.pagopa.selfcare.mscore.model.institution.Billing; -import lombok.Data; - -import java.time.OffsetDateTime; -import java.util.List; - -@Data -@JsonInclude(JsonInclude.Include.NON_NULL) -public class NotificationToSend { - - private String id; - private String internalIstitutionID; - private String product; - private String state; - private String filePath; - private String fileName; - private String contentType; - private String onboardingTokenId; - private String pricingPlan; - private InstitutionToNotify institution; - private Billing billing; - private OffsetDateTime createdAt; - private OffsetDateTime closedAt; - private OffsetDateTime updatedAt; - private QueueEvent notificationType; - -} diff --git a/connector-api/src/main/java/it/pagopa/selfcare/mscore/model/UserNotificationToSend.java b/connector-api/src/main/java/it/pagopa/selfcare/mscore/model/UserNotificationToSend.java deleted file mode 100644 index 9c0d8ae3b..000000000 --- a/connector-api/src/main/java/it/pagopa/selfcare/mscore/model/UserNotificationToSend.java +++ /dev/null @@ -1,19 +0,0 @@ -package it.pagopa.selfcare.mscore.model; - -import lombok.Data; - -import java.time.OffsetDateTime; - -@Data -public class UserNotificationToSend { - - private String id; - private String institutionId; - private String productId; - private String onboardingTokenId; - private OffsetDateTime createdAt; - private OffsetDateTime updatedAt; - private QueueEvent eventType; - private UserToNotify user; - -} diff --git a/connector-api/src/main/java/it/pagopa/selfcare/mscore/model/onboarding/PaginatedToken.java b/connector-api/src/main/java/it/pagopa/selfcare/mscore/model/onboarding/PaginatedToken.java deleted file mode 100644 index a7ac8c602..000000000 --- a/connector-api/src/main/java/it/pagopa/selfcare/mscore/model/onboarding/PaginatedToken.java +++ /dev/null @@ -1,15 +0,0 @@ -package it.pagopa.selfcare.mscore.model.onboarding; - -import it.pagopa.selfcare.mscore.model.NotificationToSend; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class PaginatedToken { - private List items; -} diff --git a/connector-api/src/main/java/it/pagopa/selfcare/mscore/utils/MockUtils.java b/connector-api/src/main/java/it/pagopa/selfcare/mscore/utils/MockUtils.java deleted file mode 100644 index ae94b09fb..000000000 --- a/connector-api/src/main/java/it/pagopa/selfcare/mscore/utils/MockUtils.java +++ /dev/null @@ -1,134 +0,0 @@ -package it.pagopa.selfcare.mscore.utils; - -import it.pagopa.selfcare.commons.base.security.PartyRole; -import it.pagopa.selfcare.commons.base.utils.InstitutionType; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.constant.TokenType; -import it.pagopa.selfcare.mscore.model.Config; -import it.pagopa.selfcare.mscore.model.institution.*; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import it.pagopa.selfcare.mscore.model.onboarding.TokenUser; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; - -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.List; - -@NoArgsConstructor(access = AccessLevel.NONE) -public class MockUtils { - - public static Config createConfigMock(boolean enabled, String productFilter) { - Config configMock = new Config(); - configMock.setId("KafkaScheduler"); - configMock.setEnableKafkaScheduler(enabled); - configMock.setProductFilter(productFilter); - configMock.setFirstPage(0); - configMock.setLastPage(10); - return configMock; - } - - public static Token createTokenMock(Integer bias, RelationshipState status, InstitutionType institutionType) { - Token tokenMock = new Token(); - tokenMock.setId("TokenId" + (bias == null ? "" : bias)); - tokenMock.setType(TokenType.INSTITUTION); - tokenMock.setStatus(status); - tokenMock.setInstitutionId("InstitutionId" + (bias == null ? "" : bias)); - tokenMock.setProductId("ProductId" + (bias == null ? "" : bias)); - tokenMock.setExpiringDate(OffsetDateTime.now().plusDays(60)); - tokenMock.setChecksum("Checksum"); - tokenMock.setContractVersion("ContractVersion"); - tokenMock.setContractTemplate("ContractTemplate"); - tokenMock.setContractSigned("ContractPath/" + tokenMock.getId() + "/FileName"); - tokenMock.setContentType("application/pdf"); - tokenMock.setUsers(List.of(createTokenUserMock(1, PartyRole.MANAGER), createTokenUserMock(2, PartyRole.DELEGATE))); - tokenMock.setInstitutionUpdate(createInstitutionUpdateMock(bias, institutionType)); - tokenMock.setCreatedAt(OffsetDateTime.now().minusDays(2)); - tokenMock.setUpdatedAt(OffsetDateTime.now().minusDays(1)); - tokenMock.setDeletedAt((status.equals(RelationshipState.DELETED) ? OffsetDateTime.now() : null)); - return tokenMock; - } - - public static List createTokenListMock(Integer numberOfTokens, Integer startingBias, RelationshipState status, InstitutionType institutionType) { - List tokensMock = new ArrayList<>(); - - numberOfTokens += startingBias; - for (int i = startingBias; i < numberOfTokens; i++) { - tokensMock.add(createTokenMock(i, status, institutionType)); - } - - return tokensMock; - } - - public static TokenUser createTokenUserMock(Integer bias, PartyRole partyRole) { - return new TokenUser("TokenUserId" + (bias == null ? "" : bias), partyRole); - } - - public static InstitutionUpdate createInstitutionUpdateMock(Integer bias, InstitutionType institutionType) { - InstitutionUpdate institutionUpdateMock = new InstitutionUpdate(); - institutionUpdateMock.setInstitutionType(institutionType); - institutionUpdateMock.setDescription("Description" + (bias == null ? "" : bias)); - institutionUpdateMock.setDigitalAddress("DigitalAddress" + (bias == null ? "" : bias)); - institutionUpdateMock.setAddress("Address" + (bias == null ? "" : bias)); - institutionUpdateMock.setTaxCode("TaxCode" + (bias == null ? "" : bias)); - institutionUpdateMock.setZipCode("ZipCode" + (bias == null ? "" : bias)); - institutionUpdateMock.setGeographicTaxonomies(List.of(createInstitutionGeographicTaxonomiesMock(1))); - institutionUpdateMock.setSupportEmail("SupportEmail" + (bias == null ? "" : bias)); - institutionUpdateMock.setImported(false); - return institutionUpdateMock; - } - - public static InstitutionGeographicTaxonomies createInstitutionGeographicTaxonomiesMock(Integer bias) { - return new InstitutionGeographicTaxonomies("InstitutionGeographicTaxonomiesCode" + (bias == null ? "" : bias), "InstitutionGeographicTaxonomiesDesc" + (bias == null ? "" : bias)); - } - - public static Institution createInstitutionMock(Integer bias, RelationshipState status, InstitutionType institutionType) { - Institution institutionMock = new Institution(); - institutionMock.setId("InstitutionId" + (bias == null ? "" : bias)); - institutionMock.setExternalId("InstitutionExternalId" + (bias == null ? "" : bias)); - institutionMock.setOrigin("Origin"); - institutionMock.setOriginId("OriginId"); - institutionMock.setDescription("Description" + (bias == null ? "" : bias)); - institutionMock.setInstitutionType(institutionType); - institutionMock.setDigitalAddress("DigitalAddress" + (bias == null ? "" : bias)); - institutionMock.setAddress("Address" + (bias == null ? "" : bias)); - institutionMock.setTaxCode("TaxCode" + (bias == null ? "" : bias)); - institutionMock.setZipCode("ZipCode" + (bias == null ? "" : bias)); - institutionMock.setBilling(createBilling(bias)); - institutionMock.setOnboarding(List.of(createOnboarding(bias, status))); - institutionMock.setGeographicTaxonomies(List.of(createInstitutionGeographicTaxonomiesMock(null), createInstitutionGeographicTaxonomiesMock(1))); - institutionMock.setSupportEmail("SupportEmail" + (bias == null ? "" : bias)); - institutionMock.setCreatedAt(OffsetDateTime.now().minusDays(2)); - institutionMock.setUpdatedAt(OffsetDateTime.now().minusDays(1)); - return institutionMock; - } - - public static List createInstitutionListMock(Integer numberOfInstitutions, Integer startingBias, RelationshipState status, InstitutionType institutionType) { - List institutionListMock = new ArrayList<>(); - - numberOfInstitutions += startingBias; - for (int i = startingBias; i < numberOfInstitutions; i++) { - institutionListMock.add(createInstitutionMock(i, status, institutionType)); - } - - return institutionListMock; - } - - public static Billing createBilling(Integer bias) { - Billing billingMock = new Billing(); - billingMock.setVatNumber("VatNumber" + (bias == null ? "" : bias)); - billingMock.setRecipientCode("RecipientCode" + (bias == null ? "" : bias)); - billingMock.setPublicServices(false); - return billingMock; - } - - public static Onboarding createOnboarding(Integer bias, RelationshipState status) { - Onboarding onboardingMock = new Onboarding(); - onboardingMock.setTokenId("TokenId" + (bias == null ? "" : bias)); - onboardingMock.setStatus(status); - onboardingMock.setContract("Contract"); - onboardingMock.setPricingPlan("PricingPlan"); - return onboardingMock; - } - -} diff --git a/connector-api/src/test/java/it/pagopa/selfcare/mscore/utils/MockUtilsTest.java b/connector-api/src/test/java/it/pagopa/selfcare/mscore/utils/MockUtilsTest.java deleted file mode 100644 index 1a52bedb2..000000000 --- a/connector-api/src/test/java/it/pagopa/selfcare/mscore/utils/MockUtilsTest.java +++ /dev/null @@ -1,161 +0,0 @@ -package it.pagopa.selfcare.mscore.utils; - -import it.pagopa.selfcare.commons.base.security.PartyRole; -import it.pagopa.selfcare.commons.base.utils.InstitutionType; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.model.Config; -import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.institution.InstitutionGeographicTaxonomies; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import it.pagopa.selfcare.mscore.model.onboarding.TokenUser; -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -class MockUtilsTest { - - @Test - void createConfigMock() { - // Given - boolean enabledMock = true; - String productFilterMock = "productFilterMock"; - // When - Config result = MockUtils.createConfigMock(enabledMock, productFilterMock); - // Then - assertNotNull(result); - assertEquals("KafkaScheduler", result.getId()); - assertEquals(enabledMock, result.isEnableKafkaScheduler()); - assertEquals(productFilterMock, result.getProductFilter()); - } - - @Test - void createTokenMock() { - // Given - Integer biasMock = 1; - RelationshipState statusMock = RelationshipState.ACTIVE; - InstitutionType institutionTypeMock = InstitutionType.PA; - // When - Token result = MockUtils.createTokenMock(biasMock, statusMock, institutionTypeMock); - // Then - assertNotNull(result); - assertEquals("TokenId" + biasMock, result.getId()); - assertEquals("InstitutionId" + biasMock, result.getInstitutionId()); - assertEquals("ProductId" + biasMock, result.getProductId()); - assertEquals(statusMock, result.getStatus()); - assertEquals(institutionTypeMock, result.getInstitutionUpdate().getInstitutionType()); - } - - @Test - void createTokenMock_nullBias() { - // Given - RelationshipState statusMock = RelationshipState.ACTIVE; - InstitutionType institutionTypeMock = InstitutionType.PA; - // When - Token result = MockUtils.createTokenMock(null, statusMock, institutionTypeMock); - // Then - assertNotNull(result); - assertEquals("TokenId", result.getId()); - assertEquals("InstitutionId", result.getInstitutionId()); - assertEquals("ProductId", result.getProductId()); - assertEquals(statusMock, result.getStatus()); - assertEquals(institutionTypeMock, result.getInstitutionUpdate().getInstitutionType()); - } - - @Test - void createTokenListMock() { - // Given - Integer numberOfTokensMock = 30; - // When - List result = MockUtils.createTokenListMock(numberOfTokensMock, 0, RelationshipState.PENDING, InstitutionType.PSP); - // Then - assertNotNull(result); - assertEquals(numberOfTokensMock, result.size()); - } - - @Test - void createTokenUserMock() { - // Given - Integer biasMock = 1; - PartyRole partyRoleMock = PartyRole.MANAGER; - // When - TokenUser result = MockUtils.createTokenUserMock(biasMock, partyRoleMock); - // Then - assertNotNull(result); - assertEquals("TokenUserId" + biasMock, result.getUserId()); - assertEquals(partyRoleMock, result.getRole()); - } - - @Test - void createTokenUserMock_nullBias() { - // Given - PartyRole partyRoleMock = PartyRole.DELEGATE; - // When - TokenUser result = MockUtils.createTokenUserMock(null, partyRoleMock); - // Then - assertNotNull(result); - assertEquals("TokenUserId", result.getUserId()); - assertEquals(partyRoleMock, result.getRole()); - } - - @Test - void createInstitutionGeographicTaxonomiesMock_nullBias() { - // When - InstitutionGeographicTaxonomies result = MockUtils.createInstitutionGeographicTaxonomiesMock(null); - // Then - assertNotNull(result); - assertEquals("InstitutionGeographicTaxonomiesCode", result.getCode()); - assertEquals("InstitutionGeographicTaxonomiesDesc", result.getDesc()); - } - - @Test - void createInstitutionMock() { - // Given - Integer biasMock = 1; - RelationshipState statusMock = RelationshipState.SUSPENDED; - InstitutionType institutionTypeMock = InstitutionType.GSP; - // When - Institution result = MockUtils.createInstitutionMock(biasMock, statusMock, institutionTypeMock); - // Then - assertNotNull(result); - assertEquals("InstitutionId" + biasMock, result.getId()); - assertEquals("InstitutionExternalId" + biasMock, result.getExternalId()); - assertEquals("Description" + biasMock, result.getDescription()); - assertEquals("DigitalAddress" + biasMock, result.getDigitalAddress()); - assertEquals("SupportEmail" + biasMock, result.getSupportEmail()); - assertEquals(statusMock, result.getOnboarding().get(0).getStatus()); - assertEquals(institutionTypeMock, result.getInstitutionType()); - } - - @Test - void createInstitutionMock_nullBias() { - // Given - RelationshipState statusMock = RelationshipState.SUSPENDED; - InstitutionType institutionTypeMock = InstitutionType.GSP; - // When - Institution result = MockUtils.createInstitutionMock(null, statusMock, institutionTypeMock); - // Then - assertNotNull(result); - assertEquals("InstitutionId", result.getId()); - assertEquals("InstitutionExternalId", result.getExternalId()); - assertEquals("Description", result.getDescription()); - assertEquals("DigitalAddress", result.getDigitalAddress()); - assertEquals("SupportEmail", result.getSupportEmail()); - assertEquals(statusMock, result.getOnboarding().get(0).getStatus()); - assertEquals(institutionTypeMock, result.getInstitutionType()); - } - - @Test - void createInsituttionMock_nullBias() { - // Given - Integer numberOfInstitutionsMock = 30; - // When - List result = MockUtils.createInstitutionListMock(numberOfInstitutionsMock, 0, RelationshipState.PENDING, InstitutionType.PSP); - // Then - assertNotNull(result); - assertEquals(numberOfInstitutionsMock, result.size()); - } - -} diff --git a/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/ConfigConnectorImpl.java b/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/ConfigConnectorImpl.java deleted file mode 100644 index a7537a0c9..000000000 --- a/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/ConfigConnectorImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -package it.pagopa.selfcare.mscore.connector.dao; - -import it.pagopa.selfcare.mscore.api.ConfigConnector; -import it.pagopa.selfcare.mscore.connector.dao.model.ConfigEntity; -import it.pagopa.selfcare.mscore.connector.dao.model.mapper.ConfigMapper; -import it.pagopa.selfcare.mscore.model.Config; -import lombok.extern.slf4j.Slf4j; -import org.springframework.data.mongodb.core.FindAndModifyOptions; -import org.springframework.data.mongodb.core.query.Criteria; -import org.springframework.data.mongodb.core.query.Query; -import org.springframework.data.mongodb.core.query.Update; -import org.springframework.stereotype.Component; - -import java.time.OffsetDateTime; - -@Slf4j -@Component -public class ConfigConnectorImpl implements ConfigConnector { - - private final ConfigRepository repository; - - public ConfigConnectorImpl(ConfigRepository repository) { - this.repository = repository; - } - - @Override - public Config findAndUpdate(String id) { - Query query = Query.query(Criteria.where(ConfigEntity.Fields.id.name()).is(id) - .and(ConfigEntity.Fields.enableKafkaScheduler.name()).is(true)); - - Update update = new Update() - .set(ConfigEntity.Fields.enableKafkaScheduler.name(), false) - .set(ConfigEntity.Fields.productFilter.name(), "") - .set(ConfigEntity.Fields.lastRequestDate.name(), OffsetDateTime.now()); - - FindAndModifyOptions findAndModifyOptions = FindAndModifyOptions.options().upsert(false).returnNew(false); - ConfigEntity result = repository.findAndModify(query, update, findAndModifyOptions, ConfigEntity.class); - return ConfigMapper.convertToConfig(result); - } - -} diff --git a/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/ConfigRepository.java b/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/ConfigRepository.java deleted file mode 100644 index ec3a98889..000000000 --- a/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/ConfigRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package it.pagopa.selfcare.mscore.connector.dao; - -import it.pagopa.selfcare.mscore.connector.dao.model.ConfigEntity; -import org.springframework.data.mongodb.repository.MongoRepository; - -public interface ConfigRepository extends MongoRepository, MongoCustomConnector { -} diff --git a/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/model/ConfigEntity.java b/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/model/ConfigEntity.java deleted file mode 100644 index 6afb790ca..000000000 --- a/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/model/ConfigEntity.java +++ /dev/null @@ -1,28 +0,0 @@ -package it.pagopa.selfcare.mscore.connector.dao.model; - -import lombok.Data; -import lombok.experimental.FieldNameConstants; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; - -import java.time.OffsetDateTime; - -@Data -@Document("Config") -@FieldNameConstants(asEnum = true) -public class ConfigEntity { - - @Id - private String id; - - private String productFilter; - - private int firstPage; - - private int lastPage; - - private boolean enableKafkaScheduler; - - private OffsetDateTime lastRequestDate; - -} diff --git a/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/model/mapper/ConfigMapper.java b/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/model/mapper/ConfigMapper.java deleted file mode 100644 index a3b0e7b29..000000000 --- a/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/model/mapper/ConfigMapper.java +++ /dev/null @@ -1,24 +0,0 @@ -package it.pagopa.selfcare.mscore.connector.dao.model.mapper; - -import it.pagopa.selfcare.mscore.connector.dao.model.ConfigEntity; -import it.pagopa.selfcare.mscore.model.Config; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; - -@NoArgsConstructor(access = AccessLevel.NONE) -public class ConfigMapper { - - public static Config convertToConfig(ConfigEntity entity) { - Config config = null; - if (entity != null) { - config = new Config(); - config.setId(entity.getId()); - config.setProductFilter(entity.getProductFilter()); - config.setEnableKafkaScheduler(entity.isEnableKafkaScheduler()); - config.setFirstPage(entity.getFirstPage()); - config.setLastPage(entity.getLastPage()); - } - return config; - } - -} diff --git a/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/utils/DaoMockUtils.java b/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/utils/DaoMockUtils.java deleted file mode 100644 index 56d77ae67..000000000 --- a/connector/dao/src/main/java/it/pagopa/selfcare/mscore/connector/dao/utils/DaoMockUtils.java +++ /dev/null @@ -1,40 +0,0 @@ -package it.pagopa.selfcare.mscore.connector.dao.utils; - -import it.pagopa.selfcare.mscore.connector.dao.model.ConfigEntity; -import it.pagopa.selfcare.mscore.connector.dao.model.TokenEntity; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.constant.TokenType; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; - -import java.time.OffsetDateTime; - -@NoArgsConstructor(access = AccessLevel.NONE) -public class DaoMockUtils { - - public static ConfigEntity createConfigEntityMock() { - ConfigEntity configEntityMock = new ConfigEntity(); - configEntityMock.setId("KafkaScheduler"); - configEntityMock.setProductFilter(""); - configEntityMock.setEnableKafkaScheduler(true); - return configEntityMock; - } - - public static TokenEntity createTokenEntityMock(Integer bias, RelationshipState status) { - TokenEntity tokenEntityMock = new TokenEntity(); - tokenEntityMock.setId("TokenId" + (bias == null ? "" : bias)); - tokenEntityMock.setType(TokenType.INSTITUTION); - tokenEntityMock.setStatus(status); - tokenEntityMock.setInstitutionId("InstitutionId" + (bias == null ? "" : bias)); - tokenEntityMock.setProductId("ProductId" + (bias == null ? "" : bias)); - tokenEntityMock.setExpiringDate(OffsetDateTime.now().plusDays(60)); - tokenEntityMock.setChecksum("Checksum"); - tokenEntityMock.setContractVersion("ContractVersion"); - tokenEntityMock.setContractTemplate("ContractTemplate"); - tokenEntityMock.setContractSigned("ContractPath/" + tokenEntityMock.getId() + "/FileName"); - tokenEntityMock.setCreatedAt(OffsetDateTime.now().minusDays(2)); - tokenEntityMock.setUpdatedAt(OffsetDateTime.now().minusDays(1)); - tokenEntityMock.setDeletedAt((status.equals(RelationshipState.DELETED) ? OffsetDateTime.now() : null)); - return tokenEntityMock; - } -} diff --git a/connector/dao/src/test/java/it/pagopa/selfcare/mscore/connector/dao/ConfigConnectorImplTest.java b/connector/dao/src/test/java/it/pagopa/selfcare/mscore/connector/dao/ConfigConnectorImplTest.java deleted file mode 100644 index 53fcf9272..000000000 --- a/connector/dao/src/test/java/it/pagopa/selfcare/mscore/connector/dao/ConfigConnectorImplTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package it.pagopa.selfcare.mscore.connector.dao; - -import it.pagopa.selfcare.mscore.connector.dao.model.ConfigEntity; -import it.pagopa.selfcare.mscore.connector.dao.utils.DaoMockUtils; -import it.pagopa.selfcare.mscore.model.Config; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.*; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.data.mongodb.core.FindAndModifyOptions; -import org.springframework.data.mongodb.core.query.Query; -import org.springframework.data.mongodb.core.query.Update; -import org.springframework.test.context.ContextConfiguration; - -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - -@ContextConfiguration(classes = {ConfigConnectorImpl.class}) -@ExtendWith(MockitoExtension.class) -class ConfigConnectorImplTest { - - @InjectMocks - ConfigConnectorImpl configConnector; - @Mock - ConfigRepository configRepository; - - @Captor - ArgumentCaptor queryArgumentCaptor; - - @Captor - ArgumentCaptor updateArgumentCaptor; - - @Captor - ArgumentCaptor findAndModifyOptionsArgumentCaptor; - - @Test - void findAndUpdate() { - // Given - String configId = "KafkaScheduler"; - ConfigEntity configEntityMock = DaoMockUtils.createConfigEntityMock(); - - when(configRepository.findAndModify(any(), any(), any(), any())) - .thenReturn(configEntityMock); - // When - Config result = configConnector.findAndUpdate(configId); - // Then - assertNotNull(result); - verify(configRepository, times(1)) - .findAndModify(queryArgumentCaptor.capture(), updateArgumentCaptor.capture(), findAndModifyOptionsArgumentCaptor.capture(), Mockito.eq(ConfigEntity.class)); - List capturedQuery = queryArgumentCaptor.getAllValues(); - assertEquals(1, capturedQuery.size()); - assertEquals(configId, capturedQuery.get(0).getQueryObject().get(ConfigEntity.Fields.id.name())); - assertEquals(true, capturedQuery.get(0).getQueryObject().get(ConfigEntity.Fields.enableKafkaScheduler.name())); - assertEquals(1, updateArgumentCaptor.getAllValues().size()); - Update update = updateArgumentCaptor.getAllValues().get(0); - assertTrue(update.getUpdateObject().get("$set").toString().contains(ConfigEntity.Fields.productFilter.name()) && - update.getUpdateObject().get("$set").toString().contains(ConfigEntity.Fields.enableKafkaScheduler.name())); - verifyNoMoreInteractions(configRepository); - } - -} diff --git a/connector/dao/src/test/java/it/pagopa/selfcare/mscore/connector/dao/model/mapper/ConfigMapperTest.java b/connector/dao/src/test/java/it/pagopa/selfcare/mscore/connector/dao/model/mapper/ConfigMapperTest.java deleted file mode 100644 index 566d6a4c4..000000000 --- a/connector/dao/src/test/java/it/pagopa/selfcare/mscore/connector/dao/model/mapper/ConfigMapperTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package it.pagopa.selfcare.mscore.connector.dao.model.mapper; - -import it.pagopa.selfcare.mscore.connector.dao.model.ConfigEntity; -import it.pagopa.selfcare.mscore.connector.dao.utils.DaoMockUtils; -import it.pagopa.selfcare.mscore.model.Config; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.*; - -class ConfigMapperTest { - - @Test - void convertToConfig() { - // Given - ConfigEntity entity = DaoMockUtils.createConfigEntityMock(); - // When - Config result = ConfigMapper.convertToConfig(entity); - // Then - assertNotNull(result); - assertEquals(entity.getId(), result.getId()); - assertEquals(entity.getProductFilter(), result.getProductFilter()); - assertEquals(entity.isEnableKafkaScheduler(), result.isEnableKafkaScheduler()); - } - - @Test - void convertToConfig_nullEntity() { - // Given - // When - Config result = ConfigMapper.convertToConfig(null); - // Then - assertNull(result); - } - -} diff --git a/connector/dao/src/test/java/it/pagopa/selfcare/mscore/connector/dao/utils/DaoMockUtilsTest.java b/connector/dao/src/test/java/it/pagopa/selfcare/mscore/connector/dao/utils/DaoMockUtilsTest.java deleted file mode 100644 index fab021dad..000000000 --- a/connector/dao/src/test/java/it/pagopa/selfcare/mscore/connector/dao/utils/DaoMockUtilsTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package it.pagopa.selfcare.mscore.connector.dao.utils; - -import it.pagopa.selfcare.mscore.connector.dao.model.ConfigEntity; -import it.pagopa.selfcare.mscore.connector.dao.model.TokenEntity; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -class DaoMockUtilsTest { - - @Test - void createConfigEntityMock() { - // When - ConfigEntity result = DaoMockUtils.createConfigEntityMock(); - // Then - assertNotNull(result); - } - - @Test - void createTokeEntitynMock() { - // Given - Integer biasMock = 1; - RelationshipState statusMock = RelationshipState.ACTIVE; - // When - TokenEntity result = DaoMockUtils.createTokenEntityMock(biasMock, statusMock); - // Then - assertNotNull(result); - assertEquals("TokenId" + biasMock, result.getId()); - assertEquals("InstitutionId" + biasMock, result.getInstitutionId()); - assertEquals("ProductId" + biasMock, result.getProductId()); - assertEquals(statusMock, result.getStatus()); - } - - @Test - void createTokenEntityMock_nullBias() { - // Given - RelationshipState statusMock = RelationshipState.ACTIVE; - // When - TokenEntity result = DaoMockUtils.createTokenEntityMock(null, statusMock); - // Then - assertNotNull(result); - assertEquals("TokenId", result.getId()); - assertEquals("InstitutionId", result.getInstitutionId()); - assertEquals("ProductId", result.getProductId()); - assertEquals(statusMock, result.getStatus()); - } -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/ContractEventNotificationService.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/ContractEventNotificationService.java deleted file mode 100644 index bda69cc74..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/ContractEventNotificationService.java +++ /dev/null @@ -1,14 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import it.pagopa.selfcare.mscore.model.NotificationToSend; -import it.pagopa.selfcare.mscore.model.QueueEvent; -import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.onboarding.Token; - -public interface ContractEventNotificationService { - void sendDataLakeNotification(Institution institution, Token token, QueueEvent queueEvent); - - NotificationToSend toNotificationToSend(Institution institution, Token token, QueueEvent queueEvent); - - NotificationToSend toNotificationToSend(NotificationToSend notification, Institution institution, Token token); -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/ContractEventNotificationServiceIgnore.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/ContractEventNotificationServiceIgnore.java deleted file mode 100644 index 024fec740..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/ContractEventNotificationServiceIgnore.java +++ /dev/null @@ -1,32 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import it.pagopa.selfcare.mscore.model.NotificationToSend; -import it.pagopa.selfcare.mscore.model.QueueEvent; -import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import lombok.extern.slf4j.Slf4j; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Service; - -@Slf4j -@Service -@ConditionalOnProperty( - value="core.contract-event-service.type", - havingValue = "ignore", - matchIfMissing = true) -public class ContractEventNotificationServiceIgnore implements ContractEventNotificationService { - @Override - public void sendDataLakeNotification(Institution institution, Token token, QueueEvent queueEvent) { - - } - - @Override - public NotificationToSend toNotificationToSend(Institution institution, Token token, QueueEvent queueEvent) { - return null; - } - - @Override - public NotificationToSend toNotificationToSend(NotificationToSend notification, Institution institution, Token token) { - return null; - } -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/ContractEventNotificationServiceImpl.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/ContractEventNotificationServiceImpl.java deleted file mode 100644 index be5c27360..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/ContractEventNotificationServiceImpl.java +++ /dev/null @@ -1,227 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.module.SimpleModule; -import it.pagopa.selfcare.commons.base.logging.LogUtils; -import it.pagopa.selfcare.mscore.api.InstitutionConnector; -import it.pagopa.selfcare.mscore.api.PartyRegistryProxyConnector; -import it.pagopa.selfcare.mscore.config.CoreConfig; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.core.config.KafkaPropertiesConfig; -import it.pagopa.selfcare.mscore.core.util.InstitutionPaSubunitType; -import it.pagopa.selfcare.mscore.exception.InvalidRequestException; -import it.pagopa.selfcare.mscore.exception.MsCoreException; -import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; -import it.pagopa.selfcare.mscore.model.InstitutionToNotify; -import it.pagopa.selfcare.mscore.model.NotificationToSend; -import it.pagopa.selfcare.mscore.model.QueueEvent; -import it.pagopa.selfcare.mscore.model.RootParent; -import it.pagopa.selfcare.mscore.model.institution.GeographicTaxonomies; -import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.institution.InstitutionProxyInfo; -import it.pagopa.selfcare.mscore.model.institution.Onboarding; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import lombok.extern.slf4j.Slf4j; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.kafka.core.KafkaTemplate; -import org.springframework.kafka.support.SendResult; -import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; -import org.springframework.util.concurrent.ListenableFuture; -import org.springframework.util.concurrent.ListenableFutureCallback; - -import java.io.IOException; -import java.nio.file.Paths; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; - -@Slf4j -@Service -@ConditionalOnProperty( - value="core.contract-event-service.type", - havingValue = "send") -public class ContractEventNotificationServiceImpl implements ContractEventNotificationService { - - - static final String DESCRIPTION_TO_REPLACE_REGEX = " - COMUNE"; - - private final KafkaTemplate kafkaTemplate; - private final KafkaPropertiesConfig kafkaPropertiesConfig; - private final ObjectMapper mapper; - private final PartyRegistryProxyConnector partyRegistryProxyConnector; - private final InstitutionConnector institutionConnector; - private final CoreConfig coreConfig; - - public ContractEventNotificationServiceImpl(KafkaTemplate kafkaTemplate, KafkaPropertiesConfig kafkaPropertiesConfig, PartyRegistryProxyConnector partyRegistryProxyConnector, InstitutionConnector institutionConnector, CoreConfig coreConfig) { - this.kafkaTemplate = kafkaTemplate; - this.kafkaPropertiesConfig = kafkaPropertiesConfig; - this.partyRegistryProxyConnector = partyRegistryProxyConnector; - this.institutionConnector = institutionConnector; - this.coreConfig = coreConfig; - - - this.mapper = new ObjectMapper(); - SimpleModule simpleModule = new SimpleModule(); - simpleModule.addSerializer(OffsetDateTime.class, new JsonSerializer<>() { - @Override - public void serialize(OffsetDateTime offsetDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { - jsonGenerator.writeString(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(offsetDateTime)); - } - }); - mapper.registerModule(simpleModule); - } - - @Override - public void sendDataLakeNotification(Institution institution, Token token, QueueEvent queueEvent) { - log.debug(LogUtils.CONFIDENTIAL_MARKER, "sendDataLakeNotification institution = {}, token = {}, queueEvent = {}", institution, token, queueEvent); - if (institution != null) { - NotificationToSend notification = toNotificationToSend(institution, token, queueEvent); - log.debug(LogUtils.CONFIDENTIAL_MARKER, "Notification to send to the data lake, notification: {}", notification); - try { - String msg = mapper.writeValueAsString(notification); - sendNotification(msg, token.getId()); - } catch (JsonProcessingException e) { - log.warn("error during send dataLake notification for token {}", notification.getId()); - } - } - } - - - @Override - public NotificationToSend toNotificationToSend(Institution institution, Token token, QueueEvent queueEvent) { - NotificationToSend notification = new NotificationToSend(); - if (queueEvent.equals(QueueEvent.ADD)) { - // When Onboarding.complete event id is the onboarding id - notification.setId(token.getId()); - notification.setState(RelationshipState.ACTIVE.toString()); - // when onboarding complete last update is activated date - notification.setUpdatedAt(Optional.ofNullable(token.getActivatedAt()).orElse(token.getCreatedAt())); - } else { - // New id - notification.setId(UUID.randomUUID().toString()); - notification.setState(token.getStatus() == RelationshipState.DELETED ? "CLOSED" : token.getStatus().toString()); - // when update last update is updated date - notification.setUpdatedAt(Optional.ofNullable(token.getUpdatedAt()).orElse(token.getCreatedAt())); - if (token.getStatus().equals(RelationshipState.DELETED)) { - // Queue.ClosedAt: if token.deleted show closedAt - notification.setClosedAt(Optional.ofNullable(token.getDeletedAt()).orElse(token.getUpdatedAt())); - notification.setUpdatedAt(Optional.ofNullable(token.getDeletedAt()).orElse(token.getUpdatedAt())); - } else { - // when update last update is updated date - notification.setUpdatedAt(Optional.ofNullable(token.getUpdatedAt()).orElse(token.getCreatedAt())); - } - } - // ADD or UPDATE msg event - notification.setNotificationType(queueEvent); - return toNotificationToSend(notification, institution, token); - } - - @Override - public NotificationToSend toNotificationToSend(NotificationToSend notification, Institution institution, Token token) { - notification.setInternalIstitutionID(institution.getId()); - notification.setProduct(token.getProductId()); - notification.setFilePath(token.getContractSigned()); - notification.setOnboardingTokenId(token.getId()); - // Queue.CreatedAt: onboarding complete date - notification.setCreatedAt(Optional.ofNullable(token.getActivatedAt()).orElse(token.getCreatedAt())); - - // ADD or UPDATE msg event - notification.setFileName(token.getContractSigned() == null ? "" : Paths.get(token.getContractSigned()).getFileName().toString()); - notification.setContentType(token.getContentType() == null ? "" : token.getContentType()); - - if (token.getProductId() != null && institution.getOnboarding() != null) { - Onboarding onboarding = institution.getOnboarding().stream() - .filter(o -> token.getProductId().equalsIgnoreCase(o.getProductId())) - .findFirst().orElseThrow(() -> new InvalidRequestException(String.format("Product %s not found", token.getProductId()), "0000")); - notification.setPricingPlan(onboarding.getPricingPlan()); - notification.setBilling(onboarding.getBilling() != null ? onboarding.getBilling() : institution.getBilling()); - notification.setInstitution(toInstitutionToNotify(institution)); - } - - return notification; - } - - private void sendNotification(String message, String tokenId) { - ListenableFuture> future = - kafkaTemplate.send(kafkaPropertiesConfig.getDatalakeContractsTopic(), message); - - future.addCallback(new ListenableFutureCallback<>() { - - @Override - public void onSuccess(SendResult result) { - log.info("sent dataLake notification for token : {}", tokenId); - } - - @Override - public void onFailure(Throwable ex) { - log.warn("error during send dataLake notification for token {}: {} ", tokenId, ex.getMessage(), ex); - } - }); - - } - - - - private InstitutionToNotify toInstitutionToNotify(Institution institution) { - InstitutionToNotify toNotify = new InstitutionToNotify(); - toNotify.setInstitutionType(institution.getInstitutionType()); - toNotify.setDescription(institution.getDescription()); - toNotify.setDigitalAddress(institution.getDigitalAddress() == null? coreConfig.getInstitutionAlternativeEmail(): institution.getDigitalAddress()); - toNotify.setAddress(institution.getAddress()); - toNotify.setTaxCode(institution.getTaxCode()); - toNotify.setOrigin(institution.getOrigin()); - toNotify.setOriginId(institution.getOriginId()); - toNotify.setZipCode(institution.getZipCode()); - toNotify.setPaymentServiceProvider(institution.getPaymentServiceProvider()); - if (institution.getSubunitType() != null && !"EC".equals(institution.getSubunitType())) { - InstitutionPaSubunitType.valueOf(institution.getSubunitType()); - toNotify.setSubUnitType(institution.getSubunitType()); - toNotify.setSubUnitCode(institution.getSubunitCode()); - } - RootParent rootParent = new RootParent(); - rootParent.setDescription(institution.getParentDescription()); - if (StringUtils.hasText(institution.getRootParentId())) { - rootParent.setId(institution.getRootParentId()); - Institution rootParentInstitution = institutionConnector.findById(institution.getRootParentId()); - rootParent.setOriginId(Objects.nonNull(rootParentInstitution) ? rootParentInstitution.getOriginId() : null); - toNotify.setRootParent(rootParent); - } - - if (institution.getAttributes() != null && !institution.getAttributes().isEmpty()) { - toNotify.setCategory(institution.getAttributes().get(0).getCode()); - } - if (institution.getCity() == null) { - setInstitutionLocation(toNotify, institution); - } else { - toNotify.setCounty(institution.getCounty()); - toNotify.setCountry(institution.getCountry()); - toNotify.setIstatCode(institution.getIstatCode()); - toNotify.setCity(institution.getCity().replace(DESCRIPTION_TO_REPLACE_REGEX, "")); - } - return toNotify; - } - - - - private void setInstitutionLocation(InstitutionToNotify toNotify, Institution institution) { - try { - InstitutionProxyInfo institutionProxyInfo = partyRegistryProxyConnector.getInstitutionById(institution.getExternalId()); - toNotify.setIstatCode(institutionProxyInfo.getIstatCode()); - toNotify.setCategory(institutionProxyInfo.getCategory()); - GeographicTaxonomies geographicTaxonomies = partyRegistryProxyConnector.getExtByCode(toNotify.getIstatCode()); - toNotify.setCounty(geographicTaxonomies.getProvinceAbbreviation()); - toNotify.setCountry(geographicTaxonomies.getCountryAbbreviation()); - toNotify.setCity(geographicTaxonomies.getDescription().replace(DESCRIPTION_TO_REPLACE_REGEX, "")); - } catch (MsCoreException | ResourceNotFoundException e) { - log.warn("Error while searching institution {} on IPA, {} ", institution.getExternalId(), e.getMessage()); - toNotify.setIstatCode(null); - } - } -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImpl.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImpl.java index 6a9b03b9a..bb24f192b 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImpl.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImpl.java @@ -9,7 +9,6 @@ import it.pagopa.selfcare.mscore.config.CoreConfig; import it.pagopa.selfcare.mscore.constant.*; import it.pagopa.selfcare.mscore.core.mapper.InstitutionMapper; -import it.pagopa.selfcare.mscore.core.mapper.TokenMapper; import it.pagopa.selfcare.mscore.core.strategy.CreateInstitutionStrategy; import it.pagopa.selfcare.mscore.core.strategy.factory.CreateInstitutionStrategyFactory; import it.pagopa.selfcare.mscore.core.strategy.input.CreateInstitutionStrategyInput; @@ -18,9 +17,7 @@ import it.pagopa.selfcare.mscore.exception.MsCoreException; import it.pagopa.selfcare.mscore.exception.ResourceConflictException; import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; -import it.pagopa.selfcare.mscore.model.QueueEvent; import it.pagopa.selfcare.mscore.model.institution.*; -import it.pagopa.selfcare.mscore.model.onboarding.Token; import lombok.extern.slf4j.Slf4j; import org.owasp.encoder.Encode; import org.springframework.stereotype.Service; @@ -41,28 +38,22 @@ public class InstitutionServiceImpl implements InstitutionService { private final DelegationConnector delegationConnector; private final PartyRegistryProxyConnector partyRegistryProxyConnector; private final CoreConfig coreConfig; - private final ContractEventNotificationService contractService; private final InstitutionMapper institutionMapper; private final CreateInstitutionStrategyFactory createInstitutionStrategyFactory; - private final TokenMapper tokenMapper; public InstitutionServiceImpl(PartyRegistryProxyConnector partyRegistryProxyConnector, InstitutionConnector institutionConnector, UserApiConnector userApiConnector, DelegationConnector delegationConnector, CoreConfig coreConfig, - ContractEventNotificationService contractService, InstitutionMapper institutionMapper, - CreateInstitutionStrategyFactory createInstitutionStrategyFactory, - TokenMapper tokenMapper) { + CreateInstitutionStrategyFactory createInstitutionStrategyFactory) { this.partyRegistryProxyConnector = partyRegistryProxyConnector; this.institutionConnector = institutionConnector; this.userApiConnector = userApiConnector; this.delegationConnector = delegationConnector; this.coreConfig = coreConfig; - this.contractService = contractService; this.institutionMapper = institutionMapper; this.createInstitutionStrategyFactory = createInstitutionStrategyFactory; - this.tokenMapper = tokenMapper; } @Override @@ -393,14 +384,7 @@ public void updateCreatedAt(String institutionId, String productId, OffsetDateTi Assert.hasText(productId, "A product ID is required."); Assert.notNull(createdAt, "A createdAt date is required."); - Institution updatedInstitution = institutionConnector.updateOnboardedProductCreatedAt(institutionId, productId, createdAt); - Onboarding onboarding = updatedInstitution.getOnboarding().stream() - .filter(onboarding1 -> onboarding1.getProductId().equals(productId) && onboarding1.getStatus() == RelationshipState.ACTIVE) - .findFirst() - .orElseThrow(() -> new ResourceNotFoundException(String.format(CustomError.CONTRACT_NOT_FOUND.getMessage(), institutionId, productId), CustomError.CONTRACT_NOT_FOUND.getCode())); - Token updatedToken = tokenMapper.toToken(onboarding, institutionId, productId); - - contractService.sendDataLakeNotification(updatedInstitution, updatedToken, QueueEvent.UPDATE); + institutionConnector.updateOnboardedProductCreatedAt(institutionId, productId, createdAt); log.trace("updateCreatedAt end"); } diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingDao.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingDao.java index da9177a59..21b17059f 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingDao.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingDao.java @@ -20,7 +20,7 @@ public OnboardingDao(InstitutionConnector institutionConnector) { - public void rollbackPersistOnboarding(String institutionId, Onboarding onboarding, List users) { + public void rollbackPersistOnboarding(String institutionId, Onboarding onboarding) { institutionConnector.findAndRemoveOnboarding(institutionId, onboarding); log.debug("rollback persistOnboarding"); } diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingService.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingService.java index 71efe1f3c..9aa2c15ad 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingService.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingService.java @@ -3,9 +3,6 @@ import it.pagopa.selfcare.mscore.model.institution.Institution; import it.pagopa.selfcare.mscore.model.institution.Onboarding; import it.pagopa.selfcare.mscore.model.onboarding.VerifyOnboardingFilters; -import it.pagopa.selfcare.mscore.model.user.UserToOnboard; - -import java.util.List; public interface OnboardingService { @@ -15,6 +12,6 @@ public interface OnboardingService { void verifyOnboardingInfoByFilters(VerifyOnboardingFilters filters); - Institution persistOnboarding(String institutionId, String productId, List users, Onboarding onboarding); + Institution persistOnboarding(String institutionId, String productId, Onboarding onboarding); } diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImpl.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImpl.java index fadc21f36..a23cc5c46 100644 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImpl.java +++ b/core/src/main/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImpl.java @@ -3,17 +3,12 @@ import it.pagopa.selfcare.mscore.api.InstitutionConnector; import it.pagopa.selfcare.mscore.constant.CustomError; import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.core.mapper.TokenMapper; import it.pagopa.selfcare.mscore.core.util.UtilEnumList; import it.pagopa.selfcare.mscore.exception.InvalidRequestException; import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; -import it.pagopa.selfcare.mscore.model.QueueEvent; import it.pagopa.selfcare.mscore.model.institution.Institution; import it.pagopa.selfcare.mscore.model.institution.Onboarding; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import it.pagopa.selfcare.mscore.model.onboarding.TokenUser; import it.pagopa.selfcare.mscore.model.onboarding.VerifyOnboardingFilters; -import it.pagopa.selfcare.mscore.model.user.UserToOnboard; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -29,20 +24,14 @@ public class OnboardingServiceImpl implements OnboardingService { private final OnboardingDao onboardingDao; private final InstitutionService institutionService; - private final ContractEventNotificationService contractEventNotification; private final InstitutionConnector institutionConnector; - private final TokenMapper tokenMapper; public OnboardingServiceImpl(OnboardingDao onboardingDao, InstitutionService institutionService, - ContractEventNotificationService contractEventNotification, - InstitutionConnector institutionConnector, - TokenMapper tokenMapper) { + InstitutionConnector institutionConnector) { this.onboardingDao = onboardingDao; this.institutionService = institutionService; - this.contractEventNotification = contractEventNotification; this.institutionConnector = institutionConnector; - this.tokenMapper = tokenMapper; } @Override @@ -73,10 +62,10 @@ public void verifyOnboardingInfoByFilters(VerifyOnboardingFilters filters) { @Override public Institution persistOnboarding(String institutionId, String - productId, List users, Onboarding onboarding) { + productId, Onboarding onboarding) { log.trace("persistForUpdate start"); - log.debug("persistForUpdate institutionId = {}, productId = {}, users = {}", institutionId, productId, users); + log.debug("persistForUpdate institutionId = {}, productId = {}", institutionId, productId); onboarding.setStatus(RelationshipState.ACTIVE); onboarding.setProductId(productId); @@ -100,28 +89,13 @@ public Institution persistOnboarding(String institutionId, String log.trace("persistForUpdate end"); - //Prepare data for sending to queue ScContract and ScUsers using method exists - //using Token pojo as temporary solution, these methods will be refactored or moved as CDC of institution - //https://pagopa.atlassian.net/browse/SELC-3571 - Token token = tokenMapper.toToken(onboarding, institutionId, productId); - token.setUsers(users.stream().map(this::toTokenUser).toList()); - institution.setOnboarding(List.of(onboarding)); - contractEventNotification.sendDataLakeNotification(institution, token, QueueEvent.ADD); - return institutionUpdated; } catch (Exception e) { - onboardingDao.rollbackPersistOnboarding(institutionId, onboarding, users); + onboardingDao.rollbackPersistOnboarding(institutionId, onboarding); log.info("rollbackPersistOnboarding completed for institution {} and product {}", institutionId, productId); throw new InvalidRequestException(ONBOARDING_OPERATION_ERROR.getMessage() + " " + e.getMessage(), ONBOARDING_OPERATION_ERROR.getCode()); } } - private TokenUser toTokenUser(UserToOnboard user) { - TokenUser tokenUser = new TokenUser(); - tokenUser.setUserId(user.getId()); - tokenUser.setRole(user.getRole()); - return tokenUser; - } - } diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/QueueNotificationService.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/QueueNotificationService.java deleted file mode 100644 index 52acfb0df..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/QueueNotificationService.java +++ /dev/null @@ -1,10 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import org.springframework.scheduling.annotation.Async; - -public interface QueueNotificationService { - - @Async - void sendContractsNotificationsByInstitutionIdAndTokenId(String tokenId, String institutionId); - -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/QueueNotificationServiceImpl.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/QueueNotificationServiceImpl.java deleted file mode 100644 index 5f5ee599d..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/QueueNotificationServiceImpl.java +++ /dev/null @@ -1,70 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import it.pagopa.selfcare.mscore.api.InstitutionConnector; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.core.mapper.TokenMapper; -import it.pagopa.selfcare.mscore.model.QueueEvent; -import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.institution.Onboarding; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import lombok.extern.slf4j.Slf4j; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -@Service -@Slf4j -public class QueueNotificationServiceImpl implements QueueNotificationService { - - public static final int TOKEN_PAGE_SIZE = 100; - public static final int USER_PAGE_SIZE = 100; - private final ContractEventNotificationService contractService; - private Optional page_size_api = Optional.empty(); - private Optional page = Optional.empty(); - private final InstitutionConnector institutionConnector; - private Optional> productsFilter = Optional.empty(); - private final TokenMapper tokenMapper; - private final List statesToSend = List.of(RelationshipState.ACTIVE, RelationshipState.DELETED); - - - public QueueNotificationServiceImpl(ContractEventNotificationService contractService, - InstitutionConnector institutionConnector, TokenMapper tokenMapper) { - this.tokenMapper = tokenMapper; - log.info("Initializing {}...", QueueNotificationServiceImpl.class.getSimpleName()); - this.contractService = contractService; - this.institutionConnector = institutionConnector; - } - - @Override - @Async - public void sendContractsNotificationsByInstitutionIdAndTokenId(String tokenId, String institutionId) { - log.trace("regenerateQueueNotifications start"); - log.debug("Regenerating notifications on queue with institutionId {} and tokenId {}", institutionId, tokenId); - - Institution institution = institutionConnector.findById(institutionId); - - List onboardings = institution.getOnboarding().stream() - .filter(item -> Objects.nonNull(item.getStatus()) && statesToSend.contains(item.getStatus())) - .filter(item -> tokenId.equals(item.getTokenId())) - .toList(); - - if(onboardings.isEmpty()) { - log.trace("Onboarding not found with institutionId {} and tokenId {}", institutionId, tokenId); - return; - } - - for(Onboarding onboarding : onboardings) { - - Token token = tokenMapper.toToken(onboarding, institutionId, onboarding.getProductId()); - //token.setUsers(users.stream().map(this::toTokenUser).toList()); - institution.setOnboarding(List.of(onboarding)); - contractService.sendDataLakeNotification(institution, token, QueueEvent.UPDATE); - } - - log.trace("regenerateQueueNotifications end"); - } - -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventService.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventService.java deleted file mode 100644 index 9afd3dc1b..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventService.java +++ /dev/null @@ -1,9 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; - -public interface UserEventService { - - void sendOnboardedUserNotification(OnboardedUser onboardedUser, String productId); - -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventServiceIgnore.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventServiceIgnore.java deleted file mode 100644 index c93b29f66..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventServiceIgnore.java +++ /dev/null @@ -1,20 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import lombok.extern.slf4j.Slf4j; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.stereotype.Service; - -@Slf4j -@Service -@ConditionalOnProperty( - value="core.user-event-service.type", - havingValue = "ignore", - matchIfMissing = true) -public class UserEventServiceIgnore implements UserEventService{ - - @Override - public void sendOnboardedUserNotification(OnboardedUser onboardedUser, String productId) { - - } -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventServiceImpl.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventServiceImpl.java deleted file mode 100644 index 59b2042fb..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/UserEventServiceImpl.java +++ /dev/null @@ -1,131 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.module.SimpleModule; -import it.pagopa.selfcare.mscore.api.UserRegistryConnector; -import it.pagopa.selfcare.mscore.config.CoreConfig; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.core.config.KafkaPropertiesConfig; -import it.pagopa.selfcare.mscore.core.util.NotificationMapper; -import it.pagopa.selfcare.mscore.core.util.UserNotificationMapper; -import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; -import it.pagopa.selfcare.mscore.model.QueueEvent; -import it.pagopa.selfcare.mscore.model.UserNotificationToSend; -import it.pagopa.selfcare.mscore.model.UserToNotify; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.user.User; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import lombok.extern.slf4j.Slf4j; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.kafka.core.KafkaTemplate; -import org.springframework.kafka.support.SendResult; -import org.springframework.stereotype.Service; -import org.springframework.util.concurrent.ListenableFuture; -import org.springframework.util.concurrent.ListenableFutureCallback; - -import java.io.IOException; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.EnumSet; - -@Slf4j -@Service -@ConditionalOnProperty( - value = "core.user-event-service.type", - havingValue = "send") -public class UserEventServiceImpl implements UserEventService { - public static final String ERROR_DURING_SEND_DATA_LAKE_NOTIFICATION_FOR_USER = "error during send dataLake notification for user {}"; - public static final String DONE_SEND_DATA_LAKE_NOTIFICATION_FOR_USER = "done send dataLake notification for user {}"; - private final CoreConfig coreConfig; - private final KafkaTemplate kafkaTemplateUsers; - private final EnumSet ALLOWED_RELATIONSHIP_STATUSES = EnumSet.of(RelationshipState.ACTIVE, RelationshipState.SUSPENDED, RelationshipState.DELETED); - private final KafkaPropertiesConfig kafkaPropertiesConfig; - private final ObjectMapper mapper; - private final UserRegistryConnector userRegistryConnector; - - private final NotificationMapper notificationMapper; - - private final UserNotificationMapper userNotificationMapper; - - public UserEventServiceImpl(CoreConfig coreConfig, - KafkaTemplate kafkaTemplateUsers, - KafkaPropertiesConfig kafkaPropertiesConfig, - ObjectMapper mapper, - UserRegistryConnector userRegistryConnector, - NotificationMapper notificationMapper, - UserNotificationMapper userNotificationMapper) { - this.coreConfig = coreConfig; - this.kafkaTemplateUsers = kafkaTemplateUsers; - this.kafkaPropertiesConfig = kafkaPropertiesConfig; - this.mapper = mapper; - this.userRegistryConnector = userRegistryConnector; - this.notificationMapper = notificationMapper; - this.userNotificationMapper = userNotificationMapper; - - SimpleModule simpleModule = new SimpleModule(); - simpleModule.addSerializer(OffsetDateTime.class, new JsonSerializer<>() { - @Override - public void serialize(OffsetDateTime offsetDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { - jsonGenerator.writeString(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(offsetDateTime)); - } - }); - mapper.registerModule(simpleModule); - } - - @Override - public void sendOnboardedUserNotification(OnboardedUser onboardedUser, String productId) { - try { - onboardedUser.getBindings().forEach(userBinding -> { - for (OnboardedProduct onboardedProduct : userBinding.getProducts()) { - if (productId.equals(onboardedProduct.getProductId()) && ALLOWED_RELATIONSHIP_STATUSES.contains(onboardedProduct.getStatus())) { - sendUserNotificationFromBindings(onboardedUser.getId(), QueueEvent.ADD, userBinding, onboardedProduct); - } - } - }); - }catch (ResourceNotFoundException e){ - log.error("Error while operating on user: {}", onboardedUser.getId()); - } - - } - - private void sendUserNotificationFromBindings(String userId, QueueEvent eventType, UserBinding userBinding, OnboardedProduct onboardedProduct) { - User user = userRegistryConnector.getUserByInternalId(userId); - UserToNotify userToNotify = userNotificationMapper.toUserNotify(user, onboardedProduct, userBinding.getInstitutionId()); - UserNotificationToSend userNotification = notificationMapper.setNotificationDetailsFromOnboardedProduct(userToNotify, onboardedProduct, userBinding.getInstitutionId()); - userNotification.setId(idBuilder(userId, userBinding.getInstitutionId(), onboardedProduct.getProductId(), onboardedProduct.getProductRole())); - userNotification.setEventType(eventType); - try { - String msg = mapper.writeValueAsString(userNotification); - sendUserNotification(msg, userId); - log.info(DONE_SEND_DATA_LAKE_NOTIFICATION_FOR_USER, userId); - } catch (JsonProcessingException e) { - log.warn(ERROR_DURING_SEND_DATA_LAKE_NOTIFICATION_FOR_USER, userId); - } - } - - private String idBuilder(String userId, String institutionId, String productId, String productRole){ - return String.format("%s_%s_%s_%s", userId, institutionId, productId, productRole); - } - private void sendUserNotification(String message, String userId) { - ListenableFuture> future = - kafkaTemplateUsers.send(kafkaPropertiesConfig.getScUsersTopic(), message); - - future.addCallback(new ListenableFutureCallback<>() { - - @Override - public void onSuccess(SendResult result) { - log.info("sent dataLake notification for user : {}", userId); - } - - @Override - public void onFailure(Throwable ex) { - log.warn("error during send dataLake notification for user {}: {} ", userId, ex.getMessage(), ex); - } - }); - } -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/config/KafkaProducerConfig.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/config/KafkaProducerConfig.java deleted file mode 100644 index 7caaafb68..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/config/KafkaProducerConfig.java +++ /dev/null @@ -1,81 +0,0 @@ -package it.pagopa.selfcare.mscore.core.config; - -import org.apache.kafka.clients.admin.AdminClientConfig; -import org.apache.kafka.clients.producer.ProducerConfig; -import org.apache.kafka.common.config.SaslConfigs; -import org.apache.kafka.common.serialization.StringSerializer; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.kafka.core.DefaultKafkaProducerFactory; -import org.springframework.kafka.core.KafkaTemplate; -import org.springframework.kafka.core.ProducerFactory; - -import java.util.HashMap; -import java.util.Map; - -@Configuration -public class KafkaProducerConfig { - - @Autowired - private final KafkaPropertiesConfig kafkaPropertiesConfig; - - public KafkaProducerConfig(KafkaPropertiesConfig kafkaPropertiesConfig) { - this.kafkaPropertiesConfig = kafkaPropertiesConfig; - } - - @Bean - public ProducerFactory producerFactory() { - Map configProps = new HashMap<>(); - configProps.put( - ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, - kafkaPropertiesConfig.getBootstrapServers()); - configProps.put( - AdminClientConfig.SECURITY_PROTOCOL_CONFIG, - kafkaPropertiesConfig.getSecurityProtocol()); - configProps.put( - SaslConfigs.SASL_MECHANISM, - kafkaPropertiesConfig.getSaslMechanism()); - configProps.put( - SaslConfigs.SASL_JAAS_CONFIG, - kafkaPropertiesConfig.getDatalakeContractsSaslJaasConfig()); - configProps.put( - ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, - StringSerializer.class); - configProps.put( - ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, - StringSerializer.class); - return new DefaultKafkaProducerFactory<>(configProps); - } - @Bean - ProducerFactory producerFactoryUser(){ - Map configProps = new HashMap<>(); - configProps.put( - ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, - kafkaPropertiesConfig.getBootstrapServers()); - configProps.put( - AdminClientConfig.SECURITY_PROTOCOL_CONFIG, - kafkaPropertiesConfig.getSecurityProtocol()); - configProps.put( - SaslConfigs.SASL_MECHANISM, - kafkaPropertiesConfig.getSaslMechanism()); - configProps.put( - SaslConfigs.SASL_JAAS_CONFIG, - kafkaPropertiesConfig.getUsersSaslJaasConfig()); - configProps.put( - ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, - StringSerializer.class); - configProps.put( - ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, - StringSerializer.class); - return new DefaultKafkaProducerFactory<>(configProps); - } - - @Bean - public KafkaTemplate kafkaTemplate() { - return new KafkaTemplate<>(producerFactory()); - } - - @Bean - public KafkaTemplate kafkaTemplateUsers(){return new KafkaTemplate<>(producerFactoryUser());} -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/config/KafkaPropertiesConfig.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/config/KafkaPropertiesConfig.java deleted file mode 100644 index bc711f0ff..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/config/KafkaPropertiesConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package it.pagopa.selfcare.mscore.core.config; - -import lombok.Data; -import lombok.ToString; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; - -@Configuration -@PropertySource("classpath:config/kafka.properties") -@ConfigurationProperties(prefix = "kafka-manager") -@Data -@ToString -public class KafkaPropertiesConfig { - private String datalakeContractsSaslJaasConfig; - private String usersSaslJaasConfig; - private String datalakeContractsTopic ; - private String scUsersTopic; - private String saslMechanism; - private String securityProtocol; - private String bootstrapServers; -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/util/NotificationMapper.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/util/NotificationMapper.java deleted file mode 100644 index 75cb92628..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/util/NotificationMapper.java +++ /dev/null @@ -1,36 +0,0 @@ -package it.pagopa.selfcare.mscore.core.util; - -import it.pagopa.selfcare.mscore.model.QueueEvent; -import it.pagopa.selfcare.mscore.model.UserNotificationToSend; -import it.pagopa.selfcare.mscore.model.UserToNotify; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import it.pagopa.selfcare.mscore.model.user.RelationshipInfo; -import org.mapstruct.Mapper; -import org.mapstruct.Mapping; -import java.util.UUID; - -@Mapper(componentModel = "spring", imports = UUID.class) -public interface NotificationMapper { - - @Mapping(source = "relationshipInfo.institution.id", target = "institutionId") - @Mapping(source = "relationshipInfo.onboardedProduct.productId", target = "productId") - @Mapping(source = "relationshipInfo.onboardedProduct.createdAt", target = "createdAt") - @Mapping(target = "updatedAt", expression = "java((null == relationshipInfo.getOnboardedProduct().getUpdatedAt()) ? relationshipInfo.getOnboardedProduct().getCreatedAt() : relationshipInfo.getOnboardedProduct().getUpdatedAt())") - UserNotificationToSend setNotificationDetailsFromRelationship(RelationshipInfo relationshipInfo, UserToNotify user, QueueEvent eventType); - - @Mapping(source = "token.institutionId", target = "institutionId") - @Mapping(source = "token.productId", target = "productId") - @Mapping(source = "token.id", target = "onboardingTokenId") - @Mapping(source = "token.createdAt", target = "createdAt") - @Mapping(source = "token.updatedAt", target = "updatedAt") - UserNotificationToSend setNotificationDetailsFromToken(Token token, UserToNotify user, QueueEvent eventType); - - @Mapping(source = "onboardedProduct.createdAt", target = "createdAt") - @Mapping(target = "updatedAt", expression = "java((null == onboardedProduct.getUpdatedAt()) ? onboardedProduct.getCreatedAt() : onboardedProduct.getUpdatedAt())") - @Mapping(source = "onboardedProduct.tokenId", target = "onboardingTokenId") - @Mapping(source = "onboardedProduct.productId", target = "productId") - UserNotificationToSend setNotificationDetailsFromOnboardedProduct(UserToNotify user, OnboardedProduct onboardedProduct, String institutionId); - - UserNotificationToSend setUpdateUserNotification(String institutionId, UserToNotify user); -} diff --git a/core/src/main/java/it/pagopa/selfcare/mscore/core/util/UserNotificationMapper.java b/core/src/main/java/it/pagopa/selfcare/mscore/core/util/UserNotificationMapper.java deleted file mode 100644 index 65c53b5e8..000000000 --- a/core/src/main/java/it/pagopa/selfcare/mscore/core/util/UserNotificationMapper.java +++ /dev/null @@ -1,21 +0,0 @@ -package it.pagopa.selfcare.mscore.core.util; - -import it.pagopa.selfcare.mscore.model.UserToNotify; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.user.User; -import org.mapstruct.Mapper; -import org.mapstruct.Mapping; - -import java.util.UUID; - -@Mapper(componentModel = "spring", imports = UUID.class) -public interface UserNotificationMapper { - - @Mapping(source = "onboardedProduct.role", target = "role") - @Mapping(source = "onboardedProduct.status", target = "relationshipStatus") - @Mapping(source = "onboardedProduct.productRole", target = "productRole") - @Mapping(source = "user.id", target = "userId") - @Mapping(target = "email", expression = "java(null == user.getWorkContacts() ? \"\" : user.getWorkContacts().containsKey(institutionId) ? user.getWorkContacts().get(institutionId).getEmail() : \"\")") - UserToNotify toUserNotify(User user, OnboardedProduct onboardedProduct, String institutionId); - -} diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/ContractEventNotificationServiceImplTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/ContractEventNotificationServiceImplTest.java deleted file mode 100644 index 6648a3270..000000000 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/ContractEventNotificationServiceImplTest.java +++ /dev/null @@ -1,597 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import it.pagopa.selfcare.commons.base.security.PartyRole; -import it.pagopa.selfcare.mscore.api.InstitutionConnector; -import it.pagopa.selfcare.mscore.api.PartyRegistryProxyConnector; -import it.pagopa.selfcare.mscore.api.UserRegistryConnector; -import it.pagopa.selfcare.mscore.config.CoreConfig; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.core.config.KafkaPropertiesConfig; -import it.pagopa.selfcare.mscore.core.util.InstitutionPaSubunitType; -import it.pagopa.selfcare.mscore.exception.MsCoreException; -import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; -import it.pagopa.selfcare.mscore.model.Certification; -import it.pagopa.selfcare.mscore.model.CertifiedField; -import it.pagopa.selfcare.mscore.model.NotificationToSend; -import it.pagopa.selfcare.mscore.model.QueueEvent; -import it.pagopa.selfcare.mscore.model.institution.*; -import it.pagopa.selfcare.mscore.model.onboarding.Token; -import it.pagopa.selfcare.mscore.model.onboarding.TokenUser; -import it.pagopa.selfcare.mscore.model.user.User; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.http.MediaType; -import org.springframework.kafka.core.KafkaTemplate; -import org.springframework.kafka.core.ProducerFactory; - -import java.time.OffsetDateTime; -import java.util.*; - -import static it.pagopa.selfcare.commons.utils.TestUtils.checkNotNullFields; -import static it.pagopa.selfcare.commons.utils.TestUtils.mockInstance; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - -@ExtendWith(MockitoExtension.class) -class ContractEventNotificationServiceImplTest { - - - - @InjectMocks - private ContractEventNotificationServiceImpl contractService; - @Mock - private KafkaTemplate kafkaTemplate; - - @Mock - private PartyRegistryProxyConnector partyRegistryProxyConnectorMock; - - @Mock - private KafkaPropertiesConfig kafkaPropertiesConfig; - - @Mock - private InstitutionConnector institutionConnector; - - /** - * Method under test: {@link ContractEventNotificationServiceImpl#sendDataLakeNotification(Institution, Token, QueueEvent)} - */ - @Test - void testSendDataLakeNotification2() { - ProducerFactory producerFactory = (ProducerFactory) mock(ProducerFactory.class); - when(producerFactory.transactionCapable()).thenReturn(true); - KafkaTemplate kafkaTemplate = new KafkaTemplate<>(producerFactory); - - CoreConfig coreConfig = new CoreConfig(); - - UserRegistryConnector userRegistryConnector = mock(UserRegistryConnector.class); - PartyRegistryProxyConnector partyRegistryProxyConnector = mock(PartyRegistryProxyConnector.class); - InstitutionConnector institutionConnector = mock(InstitutionConnector.class); - ContractEventNotificationService contractService = new ContractEventNotificationServiceImpl(kafkaTemplate, new KafkaPropertiesConfig(), - partyRegistryProxyConnector, institutionConnector, coreConfig); - Onboarding onboarding = mockInstance(new Onboarding()); - onboarding.setProductId("prod"); - - Institution institution = mockInstance(new Institution(), "setCity", "setCounty", "setCountry", "setSubunitType"); - institution.setOrigin("IPA"); - institution.setOnboarding(List.of(onboarding)); - - InstitutionUpdate institutionUpdate = mockInstance(new InstitutionUpdate()); - - TokenUser tokenUser1 = new TokenUser("tokenUserId1", PartyRole.MANAGER); - TokenUser tokenUser2 = new TokenUser("tokenUserId2", PartyRole.DELEGATE); - - Token token = mockInstance(new Token()); - token.setId(UUID.randomUUID().toString()); - token.setProductId("prod"); - token.setStatus(RelationshipState.ACTIVE); - token.setInstitutionUpdate(institutionUpdate); - token.setDeletedAt(null); - token.setUsers(List.of(tokenUser1, tokenUser2)); - token.setContractSigned("docs/parties".concat("/").concat(token.getId()).concat("/").concat("fileName.pdf")); - token.setContentType(MediaType.APPLICATION_JSON_VALUE); - - User user1 = new User(); - user1.setId(tokenUser1.getUserId()); - user1.setName(createCertifiedField_certified("User1Name")); - user1.setFamilyName(createCertifiedField_certified("User1FamilyName")); - user1.setFiscalCode("FiscalCode1"); - Map workContacts1 = new HashMap<>(); - workContacts1.put("NotFoundInstitutionId", createWorkContact("user1workemailNotFound@examepl.com")); - workContacts1.put(institution.getId(), createWorkContact("user1workEmail@example.com")); - user1.setWorkContacts(workContacts1); - - User user2 = new User(); - user2.setId(tokenUser1.getUserId()); - user2.setName(createCertifiedField_uncertified("User2Name")); - user2.setFamilyName(createCertifiedField_certified("User2FamilyName")); - user2.setFiscalCode("FiscalCode2"); - Map workContacts2 = new HashMap<>(); - workContacts2.put(institution.getId(), createWorkContact("user2workEmail@example.com")); - workContacts2.put("NotFoundInstitutionId", createWorkContact("user2workemailNotFound@examepl.com")); - workContacts2.put("NotFoundInstitutionId2", createWorkContact("user2workemailNotFound2@examepl.com")); - user2.setWorkContacts(workContacts2); - - InstitutionProxyInfo institutionProxyInfoMock = mockInstance(new InstitutionProxyInfo()); - institutionProxyInfoMock.setTaxCode(institution.getExternalId()); - - GeographicTaxonomies geographicTaxonomiesMock = mockInstance(new GeographicTaxonomies()); - geographicTaxonomiesMock.setIstatCode(institutionProxyInfoMock.getIstatCode()); - when(partyRegistryProxyConnector.getInstitutionById(any())) - .thenReturn(institutionProxyInfoMock); - when(partyRegistryProxyConnector.getExtByCode(any())).thenReturn(geographicTaxonomiesMock); - - assertThrows(IllegalArgumentException.class, () -> contractService.sendDataLakeNotification(institution, token, QueueEvent.ADD), - "Topic cannot be null"); - - verify(partyRegistryProxyConnector, times(1)) - .getInstitutionById(institution.getExternalId()); - verifyNoMoreInteractions(userRegistryConnector, partyRegistryProxyConnector); - } - - @Test - void testSendDataLakeNotification3() { - ProducerFactory producerFactory = (ProducerFactory) mock(ProducerFactory.class); - when(producerFactory.transactionCapable()).thenReturn(true); - KafkaTemplate kafkaTemplate = new KafkaTemplate<>(producerFactory); - CoreConfig coreConfig = new CoreConfig(); - - UserRegistryConnector userRegistryConnector = mock(UserRegistryConnector.class); - PartyRegistryProxyConnector partyRegistryProxyConnector = mock(PartyRegistryProxyConnector.class); - InstitutionConnector institutionConnector = mock(InstitutionConnector.class); - ContractEventNotificationService contractService = new ContractEventNotificationServiceImpl(kafkaTemplate, new KafkaPropertiesConfig(), - partyRegistryProxyConnector, institutionConnector, coreConfig); - - Onboarding onboarding = mockInstance(new Onboarding()); - onboarding.setProductId("prod"); - - Institution institution = mockInstance(new Institution(), "setSubunitType"); - institution.setOrigin("IPA"); - institution.setOnboarding(List.of(onboarding)); - - InstitutionUpdate institutionUpdate = mockInstance(new InstitutionUpdate()); - - TokenUser tokenUser1 = new TokenUser("tokenUserId1", PartyRole.MANAGER); - TokenUser tokenUser2 = new TokenUser("tokenUserId2", PartyRole.DELEGATE); - - Token token = mockInstance(new Token()); - token.setId(UUID.randomUUID().toString()); - token.setProductId("prod"); - token.setStatus(RelationshipState.ACTIVE); - token.setInstitutionUpdate(institutionUpdate); - token.setDeletedAt(null); - token.setUsers(List.of(tokenUser1, tokenUser2)); - token.setContractSigned("docs/parties".concat("/").concat(token.getId()).concat("/").concat("fileName.pdf")); - token.setContentType(MediaType.APPLICATION_JSON_VALUE); - assertThrows(IllegalArgumentException.class, () -> contractService.sendDataLakeNotification(institution, token, QueueEvent.ADD), - "Topic cannot be null"); - - verifyNoMoreInteractions(userRegistryConnector, partyRegistryProxyConnector); - } - - /** - * Method under test: {@link ContractEventNotificationServiceImpl#sendDataLakeNotification(Institution, Token, QueueEvent)} - */ - @ParameterizedTest - @ValueSource(classes = { - MsCoreException.class, - ResourceNotFoundException.class - }) - void testSendDataLakeNotification_notOnIpa(Class clazz) { - ProducerFactory producerFactory = (ProducerFactory) mock(ProducerFactory.class); - when(producerFactory.transactionCapable()).thenReturn(true); - KafkaTemplate kafkaTemplate = new KafkaTemplate<>(producerFactory); - CoreConfig coreConfig = new CoreConfig(); - - UserRegistryConnector userRegistryConnector = mock(UserRegistryConnector.class); - PartyRegistryProxyConnector partyRegistryProxyConnector = mock(PartyRegistryProxyConnector.class); - InstitutionConnector institutionConnector = mock(InstitutionConnector.class); - - ContractEventNotificationService contractService = new ContractEventNotificationServiceImpl(kafkaTemplate, new KafkaPropertiesConfig(), - partyRegistryProxyConnector, institutionConnector, coreConfig); - - Onboarding onboarding = mockInstance(new Onboarding()); - onboarding.setProductId("prod"); - - Institution institution = mockInstance(new Institution(), "setCity", "setSubunitType"); - institution.setOrigin("IPA"); - institution.setOnboarding(List.of(onboarding)); - - InstitutionUpdate institutionUpdate = mockInstance(new InstitutionUpdate()); - - TokenUser tokenUser1 = new TokenUser("tokenUserId1", PartyRole.MANAGER); - TokenUser tokenUser2 = new TokenUser("tokenUserId2", PartyRole.DELEGATE); - - Token token = mockInstance(new Token()); - token.setProductId("prod"); - token.setStatus(RelationshipState.ACTIVE); - token.setInstitutionUpdate(institutionUpdate); - token.setDeletedAt(null); - token.setUsers(List.of(tokenUser1, tokenUser2)); - token.setContractSigned(null); - - User user1 = new User(); - user1.setId(tokenUser1.getUserId()); - user1.setName(createCertifiedField_certified("User1Name")); - user1.setFamilyName(createCertifiedField_certified("User1FamilyName")); - user1.setFiscalCode("FiscalCode1"); - Map workContacts1 = new HashMap<>(); - workContacts1.put("NotFoundInstitutionId", createWorkContact("user1workemailNotFound@examepl.com")); - workContacts1.put(institution.getId(), createWorkContact("user1workEmail@example.com")); - user1.setWorkContacts(workContacts1); - - User user2 = new User(); - user2.setId(tokenUser1.getUserId()); - user2.setName(createCertifiedField_uncertified("User2Name")); - user2.setFamilyName(createCertifiedField_certified("User2FamilyName")); - user2.setFiscalCode("FiscalCode2"); - Map workContacts2 = new HashMap<>(); - workContacts2.put(institution.getId(), createWorkContact("user2workEmail@example.com")); - workContacts2.put("NotFoundInstitutionId", createWorkContact("user2workemailNotFound@examepl.com")); - workContacts2.put("NotFoundInstitutionId2", createWorkContact("user2workemailNotFound2@examepl.com")); - user2.setWorkContacts(workContacts2); - - Exception exceptionMock = (Exception) Mockito.mock(clazz); - - when(partyRegistryProxyConnector.getInstitutionById(any())) - .thenThrow(exceptionMock); - - assertThrows(IllegalArgumentException.class, () -> contractService.sendDataLakeNotification(institution, token, QueueEvent.ADD), - "Topic cannot be null"); - - verifyNoMoreInteractions(userRegistryConnector, partyRegistryProxyConnector); - } - - @Test - void testSendDataLakeNotification_updateQueueEvent() { - ProducerFactory producerFactory = (ProducerFactory) mock(ProducerFactory.class); - when(producerFactory.transactionCapable()).thenReturn(true); - KafkaTemplate kafkaTemplate = new KafkaTemplate<>(producerFactory); - - CoreConfig coreConfig = new CoreConfig(); - PartyRegistryProxyConnector partyRegistryProxyConnector = mock(PartyRegistryProxyConnector.class); - InstitutionConnector institutionConnector = mock(InstitutionConnector.class); - - ContractEventNotificationService contractService = new ContractEventNotificationServiceImpl(kafkaTemplate, new KafkaPropertiesConfig(), - partyRegistryProxyConnector, institutionConnector, coreConfig); - - Onboarding onboarding = mockInstance(new Onboarding()); - onboarding.setProductId("prod"); - - Institution institution = mockInstance(new Institution(), "setCity", "setCounty", "setCountry", "setSubunitType"); - institution.setOrigin("IPA"); - institution.setOnboarding(List.of(onboarding)); - - InstitutionUpdate institutionUpdate = mockInstance(new InstitutionUpdate()); - - TokenUser tokenUser1 = new TokenUser("tokenUserId1", PartyRole.MANAGER); - TokenUser tokenUser2 = new TokenUser("tokenUserId2", PartyRole.DELEGATE); - - Token token = mockInstance(new Token()); - token.setProductId("prod"); - token.setStatus(RelationshipState.DELETED); - token.setInstitutionUpdate(institutionUpdate); - token.setDeletedAt(null); - token.setUsers(List.of(tokenUser1, tokenUser2)); - token.setContractSigned(null); - token.setContentType(null); - - User user1 = new User(); - user1.setId(tokenUser1.getUserId()); - user1.setName(createCertifiedField_certified("User1Name")); - user1.setFamilyName(createCertifiedField_certified("User1FamilyName")); - user1.setFiscalCode("FiscalCode1"); - Map workContacts1 = new HashMap<>(); - workContacts1.put("NotFoundInstitutionId", createWorkContact("user1workemailNotFound@examepl.com")); - workContacts1.put(institution.getId(), createWorkContact("user1workEmail@example.com")); - user1.setWorkContacts(workContacts1); - - User user2 = new User(); - user2.setId(tokenUser1.getUserId()); - user2.setName(createCertifiedField_uncertified("User2Name")); - user2.setFamilyName(createCertifiedField_certified("User2FamilyName")); - user2.setFiscalCode("FiscalCode2"); - Map workContacts2 = new HashMap<>(); - workContacts2.put(institution.getId(), createWorkContact("user2workEmail@example.com")); - workContacts2.put("NotFoundInstitutionId", createWorkContact("user2workemailNotFound@examepl.com")); - workContacts2.put("NotFoundInstitutionId2", createWorkContact("user2workemailNotFound2@examepl.com")); - user2.setWorkContacts(workContacts2); - - InstitutionProxyInfo institutionProxyInfoMock = mockInstance(new InstitutionProxyInfo()); - institutionProxyInfoMock.setTaxCode(institution.getExternalId()); - - GeographicTaxonomies geographicTaxonomiesMock = mockInstance(new GeographicTaxonomies()); - geographicTaxonomiesMock.setIstatCode(institutionProxyInfoMock.getIstatCode()); - when(partyRegistryProxyConnector.getInstitutionById(any())) - .thenReturn(institutionProxyInfoMock); - when(partyRegistryProxyConnector.getExtByCode(any())).thenReturn(geographicTaxonomiesMock); - - assertThrows(IllegalArgumentException.class, () -> contractService.sendDataLakeNotification(institution, token, QueueEvent.UPDATE), - "Topic cannot be null"); - - verify(partyRegistryProxyConnector, times(1)) - .getInstitutionById(institution.getExternalId()); - } - - - - /** - * Method under test: {@link ContractEventNotificationServiceImpl#toNotificationToSend(Institution, Token, QueueEvent)} - */ - @Test - void testGenerateMessageActiveWithActivatedAt() { - - String institutionId = "i1"; - String tokenId = "t1"; - - Onboarding onboarding = createOnboarding(tokenId, "prod"); - Institution institution = createInstitutionWithoutLocation(institutionId, onboarding); - InstitutionUpdate institutionUpdate = mockInstance(new InstitutionUpdate()); - Token token = createToken(institutionId, tokenId, institutionUpdate, - RelationshipState.ACTIVE, - OffsetDateTime.parse("2020-11-01T10:00:00Z"), // createdAt - OffsetDateTime.parse("2020-11-02T10:00:00Z"), // activatedAt - OffsetDateTime.parse("2020-11-02T10:00:00Z"), // updatedAt - null); // deletedAt - - mockPartyRegistryProxy(partyRegistryProxyConnectorMock, institution); - - NotificationToSend notification = contractService.toNotificationToSend(institution, token, QueueEvent.ADD); - - assertNotNull(notification); - assertNull(notification.getClosedAt()); - assertEquals(RelationshipState.ACTIVE.toString(), notification.getState()); - assertEquals(token.getActivatedAt(), notification.getCreatedAt()); - assertEquals(token.getUpdatedAt(), notification.getCreatedAt()); - assertEquals(QueueEvent.ADD, notification.getNotificationType()); - } - - /** - * Method under test: {@link ContractEventNotificationServiceImpl#toNotificationToSend(Institution, Token, QueueEvent)} - */ - @Test - void testGenerateMessageActiveWithoutActivatedAt() { - - String institutionId = "i1"; - String tokenId = "t1"; - - Onboarding onboarding = createOnboarding(tokenId, "prod"); - Institution institution = createInstitutionWithoutLocation(institutionId, onboarding); - InstitutionUpdate institutionUpdate = mockInstance(new InstitutionUpdate()); - Token token = createToken(institutionId, tokenId, institutionUpdate, - RelationshipState.ACTIVE, - OffsetDateTime.parse("2020-11-01T10:00:00Z"), // createdAt - null, // activatedAt - OffsetDateTime.parse("2020-11-02T10:00:00Z"), // updatedAt - null); // deletedAt - - mockPartyRegistryProxy(partyRegistryProxyConnectorMock, institution); - - NotificationToSend notification = contractService.toNotificationToSend(institution, token, QueueEvent.ADD); - - assertNotNull(notification); - assertNull(notification.getClosedAt()); - assertEquals(RelationshipState.ACTIVE.toString(), notification.getState()); - assertEquals(token.getCreatedAt(), notification.getCreatedAt()); - assertEquals(token.getCreatedAt(), notification.getUpdatedAt()); - assertEquals(QueueEvent.ADD, notification.getNotificationType()); - } - - /** - * Method under test: {@link ContractEventNotificationServiceImpl#toNotificationToSend(Institution, Token, QueueEvent)} - */ - @Test - void testGenerateMessageClosedWithoutActivatedAt() { - - String institutionId = "i1"; - String tokenId = "t1"; - - Onboarding onboarding = createOnboarding(tokenId, "prod"); - Institution institution = createInstitutionWithoutLocation(institutionId, onboarding); - InstitutionUpdate institutionUpdate = mockInstance(new InstitutionUpdate()); - Token token = createToken(institutionId, tokenId, institutionUpdate, - RelationshipState.DELETED, - OffsetDateTime.parse("2020-11-01T10:00:00Z"), // createdAt - null, // activatedAt - OffsetDateTime.parse("2020-11-02T10:00:00Z"), // updatedAt - null); // deletedAt - - mockPartyRegistryProxy(partyRegistryProxyConnectorMock, institution); - when(institutionConnector.findById(any())).thenReturn(null); - - NotificationToSend notification = contractService.toNotificationToSend(institution, token, QueueEvent.UPDATE); - - assertNotNull(notification); - assertNotNull(notification.getClosedAt()); - assertEquals("CLOSED", notification.getState()); - assertEquals(token.getCreatedAt(), notification.getCreatedAt()); - assertEquals(token.getUpdatedAt(), notification.getUpdatedAt()); - assertEquals(QueueEvent.UPDATE, notification.getNotificationType()); - } - - @Test - void toNotificationToSend_attributesNull() { - //given - final String institutionId = UUID.randomUUID().toString(); - final String tokenId = UUID.randomUUID().toString(); - Institution institutionMock = createInstitution(institutionId, createOnboarding(tokenId, "product")); - institutionMock.setAttributes(null); - institutionMock.setOrigin("SELC"); - institutionMock.setRootParentId(null); - InstitutionProxyInfo institutionProxyInfoMock = mockInstance(new InstitutionProxyInfo()); - institutionProxyInfoMock.setTaxCode(institutionMock.getTaxCode()); - Token tokenMock = createToken(institutionId, tokenId, null, - RelationshipState.ACTIVE, - OffsetDateTime.parse("2020-11-01T10:00:00Z"), // createdAt - null, // activatedAt - OffsetDateTime.parse("2020-11-02T10:00:00Z"), // updatedAt - null); // deletedAt - tokenMock.setProductId("product"); - //when - NotificationToSend notificationToSend = contractService.toNotificationToSend(institutionMock, tokenMock, QueueEvent.ADD); - //then - checkNotNullFields(notificationToSend, "closedAt"); - } - - @Test - void toNotificationToSend_emptyAttributes() { - //given - final String institutionId = UUID.randomUUID().toString(); - final String tokenId = UUID.randomUUID().toString(); - Institution institutionMock = createInstitutionWithoutLocation(institutionId, createOnboarding(tokenId, "product")); - institutionMock.setAttributes(new ArrayList<>()); - institutionMock.setOrigin("IPA"); - institutionMock.setRootParentId(null); - Token tokenMock = createToken(institutionId, tokenId, null, - RelationshipState.ACTIVE, - OffsetDateTime.parse("2020-11-01T10:00:00Z"), // createdAt - null, // activatedAt - OffsetDateTime.parse("2020-11-02T10:00:00Z"), // updatedAt - null); // deletedAt - tokenMock.setProductId("product"); - mockPartyRegistryProxy(partyRegistryProxyConnectorMock, institutionMock); - //when - NotificationToSend notificationToSend = contractService.toNotificationToSend(institutionMock, tokenMock, QueueEvent.ADD); - //then - checkNotNullFields(notificationToSend, "closedAt"); - } - - @Test - void toNotificationToSend_nullLocation() { - //given - final String institutionId = UUID.randomUUID().toString(); - final String tokenId = UUID.randomUUID().toString(); - Onboarding onboarding = createOnboarding(tokenId, "prod"); - Institution institutionMock = createInstitutionWithoutLocation(institutionId, onboarding); - institutionMock.setRootParentId(null); - institutionMock.setSubunitType(InstitutionPaSubunitType.UO.name()); - - Token tokenMock = createToken(institutionId, tokenId, null, - RelationshipState.DELETED, - OffsetDateTime.parse("2020-11-01T10:00:00Z"), // createdAt - null, // activatedAt - OffsetDateTime.parse("2020-11-02T10:00:00Z"), // updatedAt - null); // deletedAt - tokenMock.setProductId("prod"); - mockPartyRegistryProxy(partyRegistryProxyConnectorMock, institutionMock); - //when - NotificationToSend notification = contractService.toNotificationToSend(institutionMock, tokenMock, QueueEvent.UPDATE); - //then - assertNotNull(notification.getInstitution().getCategory()); - assertNotNull(notification.getInstitution().getCity()); - assertNotNull(notification.getBilling()); - assertEquals(onboarding.getBilling(), notification.getBilling()); - verify(partyRegistryProxyConnectorMock, times(1)).getInstitutionById(institutionMock.getExternalId()); - verify(partyRegistryProxyConnectorMock, times(1)).getExtByCode(any()); - } - - @Test - void toNotificationAttributesNotNull() { - //given - final String institutionId = UUID.randomUUID().toString(); - final String tokenId = UUID.randomUUID().toString(); - Institution institutionMock = createInstitution(institutionId, createOnboarding(tokenId, "product")); - Attributes attribute = new Attributes(); - attribute.setCode("code"); - institutionMock.setAttributes(List.of(attribute)); - institutionMock.setCity(null); - institutionMock.setRootParentId(null); - Token tokenMock = createToken(institutionId, tokenId, null, - RelationshipState.ACTIVE, - OffsetDateTime.parse("2020-11-01T10:00:00Z"), // createdAt - null, // activatedAt - OffsetDateTime.parse("2020-11-02T10:00:00Z"), // updatedAt - null); // deletedAt - tokenMock.setProductId("product"); - mockPartyRegistryProxy(partyRegistryProxyConnectorMock, institutionMock); - //when - NotificationToSend notificationToSend = contractService.toNotificationToSend(institutionMock, tokenMock, QueueEvent.ADD); - //then - checkNotNullFields(notificationToSend, "closedAt"); - - } - - private static Institution createInstitution(String institutionId, Onboarding onboarding) { - Institution institution = mockInstance(new Institution(), "setSubunitType"); - institution.setId(institutionId); - institution.setOrigin("IPA"); - institution.setOnboarding(List.of(onboarding)); - return institution; - } - - private static Institution createInstitutionWithoutLocation(String institutionId, Onboarding onboarding) { - Institution institution = mockInstance(new Institution(), "setCity", "setCounty", "setCountry", "setSubunitType"); - institution.setId(institutionId); - institution.setOrigin("IPA"); - institution.setOnboarding(List.of(onboarding)); - return institution; - } - - - private static Onboarding createOnboarding(String tokenId, String productId) { - Onboarding onboarding = mockInstance(new Onboarding()); - onboarding.setProductId(productId); - onboarding.setTokenId(tokenId); - return onboarding; - } - - private static Token createToken(String institutionId, String tokenId, InstitutionUpdate institutionUpdate, - RelationshipState status, - OffsetDateTime createdAt, OffsetDateTime activatedAt, - OffsetDateTime updatedAt, OffsetDateTime deletedAt) { - TokenUser tokenUser1 = new TokenUser("tokenUserId1", PartyRole.MANAGER); - TokenUser tokenUser2 = new TokenUser("tokenUserId2", PartyRole.DELEGATE); - - Token token = mockInstance(new Token()); - token.setId(tokenId); - token.setInstitutionId(institutionId); - token.setProductId("prod"); - token.setStatus(status); - token.setInstitutionUpdate(institutionUpdate); - token.setCreatedAt(createdAt); - token.setActivatedAt(activatedAt); - token.setUpdatedAt(updatedAt); - token.setDeletedAt(deletedAt); - token.setUsers(List.of(tokenUser1, tokenUser2)); - token.setContractSigned("ContractPath".concat("/").concat(token.getId()).concat("/").concat("fileName.pdf")); - token.setContentType(MediaType.APPLICATION_JSON_VALUE); - return token; - } - - private static void mockPartyRegistryProxy(PartyRegistryProxyConnector partyRegistryProxyConnector, Institution institution) { - InstitutionProxyInfo institutionProxyInfoMock = mockInstance(new InstitutionProxyInfo(), "setCity", "setCounty", "setCountry"); - institutionProxyInfoMock.setTaxCode(institution.getExternalId()); - - GeographicTaxonomies geographicTaxonomiesMock = mockInstance(new GeographicTaxonomies()); - geographicTaxonomiesMock.setIstatCode(institutionProxyInfoMock.getIstatCode()); - - when(partyRegistryProxyConnector.getInstitutionById(any())) - .thenReturn(institutionProxyInfoMock); - when(partyRegistryProxyConnector.getExtByCode(any())).thenReturn(geographicTaxonomiesMock); - } - - private WorkContact createWorkContact(String workContactEmail) { - WorkContact workContact = new WorkContact(); - workContact.setEmail(createCertifiedField_certified(workContactEmail)); - return workContact; - } - - private CertifiedField createCertifiedField_certified(String fieldValue) { - CertifiedField certifiedField = new CertifiedField<>(); - certifiedField.setCertification(Certification.SPID); - certifiedField.setValue(fieldValue); - return certifiedField; - } - - private CertifiedField createCertifiedField_uncertified(String fieldValue) { - CertifiedField certifiedField = new CertifiedField<>(); - certifiedField.setCertification(Certification.NONE); - certifiedField.setValue(fieldValue); - return certifiedField; - } -} diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImplTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImplTest.java index ecf19a0c1..0fc09af26 100644 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImplTest.java +++ b/core/src/test/java/it/pagopa/selfcare/mscore/core/InstitutionServiceImplTest.java @@ -21,9 +21,7 @@ import it.pagopa.selfcare.mscore.exception.MsCoreException; import it.pagopa.selfcare.mscore.exception.ResourceConflictException; import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; -import it.pagopa.selfcare.mscore.model.QueueEvent; import it.pagopa.selfcare.mscore.model.institution.*; -import it.pagopa.selfcare.mscore.model.onboarding.Token; import it.pagopa.selfcare.mscore.model.onboarding.TokenUser; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -65,9 +63,6 @@ class InstitutionServiceImplTest { @Mock private CoreConfig coreConfig; - @Mock - private ContractEventNotificationService contractService; - @Mock private CreateInstitutionStrategyFactory createInstitutionStrategyFactory; @@ -998,8 +993,6 @@ void updateCreatedAt() { tokenUserMock2.setUserId("321e9876-e89b-12d3-a456-426614174000"); tokenUserMock2.setRole(PartyRole.DELEGATE); - Token updatedTokenMock = tokenMapper.toToken(onboardingMock2, institutionIdMock, productIdMock); - when(institutionConnector.updateOnboardedProductCreatedAt(institutionIdMock, productIdMock, createdAtMock)) .thenReturn(updatedInstitutionMock); @@ -1008,9 +1001,7 @@ void updateCreatedAt() { // Then verify(institutionConnector, times(1)) .updateOnboardedProductCreatedAt(institutionIdMock, productIdMock, createdAtMock); - verify(contractService, times(1)) - .sendDataLakeNotification(updatedInstitutionMock, updatedTokenMock, QueueEvent.UPDATE); - verifyNoMoreInteractions(institutionConnector, contractService); + verifyNoMoreInteractions(institutionConnector); } @Test @@ -1064,7 +1055,7 @@ void updateCreatedAt_onboardingNotFound() { Institution institutionMock = mockInstance(new Institution()); institutionMock.setOnboarding(Collections.emptyList()); when(institutionConnector.updateOnboardedProductCreatedAt(institutionIdMock, productIdMock, createdAtMock)) - .thenReturn(institutionMock); + .thenThrow(ResourceNotFoundException.class); // When Executable executable = () -> institutionServiceImpl.updateCreatedAt(institutionIdMock, productIdMock, createdAtMock, activatedAtMock); // Then diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingDaoTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingDaoTest.java index b067836b4..b6283d2af 100644 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingDaoTest.java +++ b/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingDaoTest.java @@ -2,16 +2,12 @@ import it.pagopa.selfcare.mscore.api.InstitutionConnector; import it.pagopa.selfcare.mscore.model.institution.Onboarding; -import it.pagopa.selfcare.mscore.model.user.UserToOnboard; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.ArrayList; -import java.util.List; - import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -24,11 +20,6 @@ class OnboardingDaoTest { @InjectMocks private OnboardingDao onboardingDao; - UserToOnboard dummyUserToOnboard() { - UserToOnboard user = new UserToOnboard(); - user.setId("id"); - return user; - } @Test void rollbackPersistOnboarding() { @@ -36,11 +27,8 @@ void rollbackPersistOnboarding() { final String institutionId = "institutionId"; final Onboarding onboarding = new Onboarding(); onboarding.setProductId("productId"); - final List users = new ArrayList<>(); - UserToOnboard user = dummyUserToOnboard(); - users.add(user); - onboardingDao.rollbackPersistOnboarding(institutionId, onboarding, users); + onboardingDao.rollbackPersistOnboarding(institutionId, onboarding); verify(institutionConnector, times(1)) .findAndRemoveOnboarding(institutionId, onboarding); diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImplTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImplTest.java index 3264e69ca..22e2a3c1b 100644 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImplTest.java +++ b/core/src/test/java/it/pagopa/selfcare/mscore/core/OnboardingServiceImplTest.java @@ -1,25 +1,16 @@ package it.pagopa.selfcare.mscore.core; -import it.pagopa.selfcare.commons.base.security.PartyRole; import it.pagopa.selfcare.mscore.api.InstitutionConnector; import it.pagopa.selfcare.mscore.api.ProductConnector; -import it.pagopa.selfcare.mscore.constant.Env; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.constant.TokenType; import it.pagopa.selfcare.mscore.core.mapper.TokenMapper; import it.pagopa.selfcare.mscore.core.mapper.TokenMapperImpl; import it.pagopa.selfcare.mscore.core.util.UtilEnumList; import it.pagopa.selfcare.mscore.exception.InvalidRequestException; import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; -import it.pagopa.selfcare.mscore.model.Certification; -import it.pagopa.selfcare.mscore.model.CertifiedField; import it.pagopa.selfcare.mscore.model.institution.Billing; import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.institution.InstitutionUpdate; import it.pagopa.selfcare.mscore.model.institution.Onboarding; import it.pagopa.selfcare.mscore.model.onboarding.*; -import it.pagopa.selfcare.mscore.model.user.User; -import it.pagopa.selfcare.mscore.model.user.UserToOnboard; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -28,8 +19,6 @@ import org.springframework.test.context.ContextConfiguration; import java.time.LocalDate; -import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -40,9 +29,6 @@ @ExtendWith(MockitoExtension.class) class OnboardingServiceImplTest { - @Mock - private ContractEventNotificationService contractEventNotificationService; - @Mock private OnboardingDao onboardingDao; @@ -52,9 +38,6 @@ class OnboardingServiceImplTest { @Mock private InstitutionService institutionService; - @Mock - private UserEventService userEventService; - @Mock private InstitutionConnector institutionConnector; @@ -124,18 +107,6 @@ void testVerifyOnboardingInfoByFilterNotFound() { verify(institutionConnector).existsOnboardingByFilters(Mockito.any()); } - /** - * Method under test: {@link OnboardingServiceImpl#verifyOnboardingInfo(String, String)} - */ - @Test - void testVerifyOnboardingInfo4() { - doNothing().when(institutionService) - .retrieveInstitutionsWithFilter(any(), any(), any()); - onboardingServiceImpl.verifyOnboardingInfo("42", "42"); - verify(institutionService).retrieveInstitutionsWithFilter(any(), any(), - any()); - } - /** * Method under test: {@link OnboardingServiceImpl#verifyOnboardingInfo(String, String)} */ @@ -148,55 +119,6 @@ void testVerifyOnboardingInfo5() { any()); } - /** - * Method under test: {@link OnboardingServiceImpl#verifyOnboardingInfo(String, String)} - */ - @Test - void testVerifyOnboardingInfo6() { - doNothing().when(institutionService) - .retrieveInstitutionsWithFilter(any(), any(), any()); - onboardingServiceImpl.verifyOnboardingInfo("42", "42"); - verify(institutionService).retrieveInstitutionsWithFilter(any(), any(), - any()); - } - - /** - * Method under test: {@link OnboardingServiceImpl#verifyOnboardingInfo(String, String)} - */ - @Test - void testVerifyOnboardingInfo7() { - doThrow(new InvalidRequestException("An error occurred", "Code")).when(institutionService) - .retrieveInstitutionsWithFilter(any(), any(), any()); - assertThrows(InvalidRequestException.class, () -> onboardingServiceImpl.verifyOnboardingInfo("42", "42")); - verify(institutionService).retrieveInstitutionsWithFilter(any(), any(), - any()); - } - - private Institution dummyInstitution() { - Institution institution = new Institution(); - institution.setId("42"); - - Onboarding onboarding = new Onboarding(); - onboarding.setStatus(RelationshipState.ACTIVE); - onboarding.setProductId("42"); - institution.setOnboarding(List.of(onboarding)); - return institution; - } - - private UserToOnboard createSimpleUserToOnboard() { - UserToOnboard userToOnboard = new UserToOnboard(); - userToOnboard.setEmail("jane.doe@example.org"); - userToOnboard.setEnv(Env.ROOT); - userToOnboard.setId("42"); - userToOnboard.setName("Name"); - userToOnboard.setProductRole(""); - userToOnboard.setRole(PartyRole.MANAGER); - userToOnboard.setSurname("Doe"); - userToOnboard.setTaxCode("Tax Code"); - return userToOnboard; - } - - @Test void persistOnboarding_shouldThrowIfOnboardingExists() { @@ -208,14 +130,19 @@ void persistOnboarding_shouldThrowIfOnboardingExists() { institution.setOnboarding(List.of(onboarding, dummyOnboarding())); when(institutionConnector.findById(institution.getId())).thenReturn(institution); - assertThrows(InvalidRequestException.class, () -> onboardingServiceImpl.persistOnboarding(institution.getId(), - onboarding.getProductId(), List.of(), new Onboarding())); + String institutionId = institution.getId(); + + String productId = onboarding.getProductId(); + Onboarding onb = new Onboarding(); + + assertThrows(InvalidRequestException.class, () -> onboardingServiceImpl.persistOnboarding(institutionId, + productId, onb)); } /** - * Method under test: {@link OnboardingServiceImpl#persistOnboarding(String, String, List, Onboarding)} + * Method under test: {@link OnboardingServiceImpl#persistOnboarding(String, String, Onboarding)} */ @Test void persistOnboarding_shouldRollback() { @@ -234,24 +161,19 @@ void persistOnboarding_shouldRollback() { institution.setId("institutionId"); institution.setOnboarding(List.of(onboarding)); - UserToOnboard userToOnboard = createSimpleUserToOnboard(); - User user = new User(); - user.setFiscalCode("fiscalCode"); - user.setId("42"); - final List userToOnboards = List.of(userToOnboard); - when(institutionConnector.findById(institution.getId())).thenReturn(institution); when(institutionConnector.findAndUpdate(any(), any(), any(), any())).thenThrow(new RuntimeException()); + String institutionId = institution.getId(); - Assertions.assertThrows(InvalidRequestException.class, () -> onboardingServiceImpl.persistOnboarding(institution.getId(), productId, userToOnboards, onboardingToPersist)); + Assertions.assertThrows(InvalidRequestException.class, () -> onboardingServiceImpl.persistOnboarding(institutionId, productId, onboardingToPersist)); verify(onboardingDao, times(1)) - .rollbackPersistOnboarding(any(), any(), any()); + .rollbackPersistOnboarding(any(), any()); } /** - * Method under test: {@link OnboardingServiceImpl#persistOnboarding(String, String, List, Onboarding)} + * Method under test: {@link OnboardingServiceImpl#persistOnboarding(String, String, Onboarding)} */ @Test void persistOnboarding_whenUserNotExistsOnRegistry() { @@ -276,12 +198,6 @@ void persistOnboarding_whenUserNotExistsOnRegistry() { institution.setId("institutionId"); institution.setOnboarding(List.of(onboarding)); - UserToOnboard userToOnboard = createSimpleUserToOnboard(); - User user = new User(); - user.setFiscalCode("fiscalCode"); - user.setId("42"); - final List userToOnboards = List.of(userToOnboard); - Token token = new Token(); token.setId(onboarding.getTokenId()); @@ -295,7 +211,7 @@ void persistOnboarding_whenUserNotExistsOnRegistry() { when(institutionConnector.findById(institution.getId())).thenReturn(institution); when(institutionConnector.findAndUpdate(any(), any(), any(), any())).thenReturn(institution); - onboardingServiceImpl.persistOnboarding(institution.getId(), productId, userToOnboards, onboardingToPersist); + onboardingServiceImpl.persistOnboarding(institution.getId(), productId, onboardingToPersist); ArgumentCaptor captor = ArgumentCaptor.forClass(Onboarding.class); @@ -306,76 +222,6 @@ void persistOnboarding_whenUserNotExistsOnRegistry() { assertEquals(actual.getCreatedAt().getDayOfYear(), LocalDate.now().getDayOfYear()); } - private OnboardedProduct getOnboardedProduct() { - OnboardedProduct onboardedProduct = new OnboardedProduct(); - onboardedProduct.setContract("START - getUser with id: {}"); - onboardedProduct.setCreatedAt(null); - onboardedProduct.setEnv(Env.ROOT); - onboardedProduct.setProductId("42"); - onboardedProduct.setProductRole(""); - onboardedProduct.setRole(PartyRole.MANAGER); - onboardedProduct.setStatus(RelationshipState.PENDING); - onboardedProduct.setUpdatedAt(null); - return onboardedProduct; - } - - private OnboardingRequest getOnboardingRequest() { - Contract contract = new Contract(); - contract.setPath("Contract Template"); - OnboardingRequest expectedRequest = new OnboardingRequest(); - expectedRequest.setProductId("42"); - expectedRequest.setContract(contract); - expectedRequest.setPricingPlan("C3"); - expectedRequest.setProductName("42"); - expectedRequest.setInstitutionUpdate(new InstitutionUpdate()); - expectedRequest.setBillingRequest(new Billing()); - expectedRequest.setSignContract(true); - return expectedRequest; - } - - private Token getToken(InstitutionUpdate institutionUpdate) { - Token token = new Token(); - token.setChecksum("Checksum"); - token.setDeletedAt(null); - token.setContractSigned("Contract Signed"); - token.setContractTemplate("Contract Template"); - token.setCreatedAt(null); - token.setExpiringDate(null); - token.setId("42"); - token.setInstitutionId("42"); - token.setInstitutionUpdate(institutionUpdate); - token.setProductId("42"); - token.setStatus(RelationshipState.PENDING); - token.setType(TokenType.INSTITUTION); - token.setUpdatedAt(null); - token.setUsers(new ArrayList<>()); - return token; - } - - - private User dummyUser() { - CertifiedField certifiedField = new CertifiedField<>(); - certifiedField.setCertification(Certification.NONE); - certifiedField.setValue("42"); - - CertifiedField certifiedField1 = new CertifiedField<>(); - certifiedField1.setCertification(Certification.NONE); - certifiedField1.setValue("42"); - - CertifiedField certifiedField2 = new CertifiedField<>(); - certifiedField2.setCertification(Certification.NONE); - certifiedField2.setValue("42"); - - User user = new User(); - user.setEmail(certifiedField); - user.setFamilyName(certifiedField1); - user.setFiscalCode("Fiscal Code"); - user.setId("42"); - user.setName(certifiedField2); - user.setWorkContacts(new HashMap<>()); - return user; - } - private Onboarding dummyOnboarding() { Onboarding onboarding = new Onboarding(); onboarding.setBilling(new Billing()); diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/QueueNotificationServiceTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/QueueNotificationServiceTest.java deleted file mode 100644 index 0de605a67..000000000 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/QueueNotificationServiceTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import it.pagopa.selfcare.mscore.api.InstitutionConnector; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.core.mapper.TokenMapper; -import it.pagopa.selfcare.mscore.core.mapper.TokenMapperImpl; -import it.pagopa.selfcare.mscore.model.institution.Institution; -import it.pagopa.selfcare.mscore.model.institution.Onboarding; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.api.function.Executable; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.jupiter.MockitoExtension; - -import java.util.List; - -import static it.pagopa.selfcare.commons.utils.TestUtils.mockInstance; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - - -@ExtendWith(MockitoExtension.class) -class QueueNotificationServiceTest { - @InjectMocks - private QueueNotificationServiceImpl schedulerService; - @Mock - private ContractEventNotificationService contractService; - @Mock - private InstitutionConnector institutionConnector; - @Spy - private TokenMapper tokenMapper = new TokenMapperImpl(); - - - @Test - void sendContractsNotificationsByInstitutionIdAndTokenId() { - //given - String institutionId = "institutionId"; - String tokenId = "tokenId"; - final Institution institution = mockInstance(new Institution()); - Onboarding onboardingActive = new Onboarding(); - onboardingActive.setTokenId(tokenId); - onboardingActive.setStatus(RelationshipState.ACTIVE); - Onboarding onboarding = new Onboarding(); - onboarding.setTokenId(tokenId); - onboarding.setStatus(RelationshipState.PENDING); - Onboarding onboardingDeleted = new Onboarding(); - onboardingDeleted.setTokenId(tokenId); - onboardingDeleted.setStatus(RelationshipState.DELETED); - institution.setOnboarding(List.of(onboardingActive, onboardingDeleted, onboarding)); - - schedulerService = new QueueNotificationServiceImpl(contractService, institutionConnector, tokenMapper); - - when(institutionConnector.findById(institutionId)).thenReturn(institution); - //when - Executable executable = () -> schedulerService.sendContractsNotificationsByInstitutionIdAndTokenId(tokenId, institutionId); - //then - assertDoesNotThrow(executable); - verify(institutionConnector, times(1)).findById(institutionId); - verify(contractService, times(2)).sendDataLakeNotification(any(), any(), any()); - verifyNoMoreInteractions(contractService); - } - - -} diff --git a/core/src/test/java/it/pagopa/selfcare/mscore/core/UserEventServiceTest.java b/core/src/test/java/it/pagopa/selfcare/mscore/core/UserEventServiceTest.java deleted file mode 100644 index 2db960a5e..000000000 --- a/core/src/test/java/it/pagopa/selfcare/mscore/core/UserEventServiceTest.java +++ /dev/null @@ -1,170 +0,0 @@ -package it.pagopa.selfcare.mscore.core; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import it.pagopa.selfcare.mscore.api.UserRegistryConnector; -import it.pagopa.selfcare.mscore.config.CoreConfig; -import it.pagopa.selfcare.mscore.constant.RelationshipState; -import it.pagopa.selfcare.mscore.core.config.KafkaPropertiesConfig; -import it.pagopa.selfcare.mscore.core.util.NotificationMapper; -import it.pagopa.selfcare.mscore.core.util.NotificationMapperImpl; -import it.pagopa.selfcare.mscore.core.util.UserNotificationMapper; -import it.pagopa.selfcare.mscore.core.util.UserNotificationMapperImpl; -import it.pagopa.selfcare.mscore.core.util.model.DummyUser; -import it.pagopa.selfcare.mscore.exception.ResourceNotFoundException; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedProduct; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.user.User; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.api.function.Executable; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.kafka.core.KafkaTemplate; -import org.springframework.kafka.support.SendResult; -import org.springframework.util.concurrent.ListenableFuture; -import org.springframework.util.concurrent.ListenableFutureCallback; - -import java.util.List; -import java.util.UUID; - -import static it.pagopa.selfcare.commons.utils.TestUtils.mockInstance; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - -@ExtendWith(MockitoExtension.class) -class UserEventServiceTest { - @Mock - private KafkaTemplate kafkaTemplateUsers; - @InjectMocks - private UserEventServiceImpl userEventService; - @Mock - private KafkaPropertiesConfig kafkaPropertiesConfig; - @Spy - private ObjectMapper mapper; - @Mock - private UserRegistryConnector userRegistryConnector; - @Mock - private CoreConfig coreConfig; - @Mock - private SendResult mockSendResult; - @Mock - private ListenableFuture> mockFuture; - - @Spy - private NotificationMapper notificationMapper = new NotificationMapperImpl(); - @Spy - UserNotificationMapper userNotificationMapper = new UserNotificationMapperImpl(); - - - @ParameterizedTest - @EnumSource(value = RelationshipState.class, names = {"ACTIVE", "DELETED", "SUSPENDED"}) - void sendOnboardedUserNotification(RelationshipState state){ - //given - final String userId = UUID.randomUUID().toString(); - final String institutionId = UUID.randomUUID().toString(); - final String productId = "product-test"; - when(kafkaTemplateUsers.send(any(), any())) - .thenReturn(mockFuture); - doAnswer(invocationOnMock -> { - ListenableFutureCallback callback = invocationOnMock.getArgument(0); - callback.onSuccess(mockSendResult); - return null; - }).when(mockFuture).addCallback(any(ListenableFutureCallback.class)); - final OnboardedUser onboardedUser = mockInstance(new OnboardedUser()); - onboardedUser.setId(userId); - final OnboardedProduct onboardedProduct = mockInstance(new OnboardedProduct()); - onboardedProduct.setProductId(productId); - onboardedProduct.setStatus(state); - final UserBinding userBinding = mockInstance(new UserBinding()); - final User user = new DummyUser(institutionId); - user.setId(userId); - userBinding.setInstitutionId(institutionId); - userBinding.setProducts(List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - when(userRegistryConnector.getUserByInternalId(any())).thenReturn(user); - //when - Executable executable = () ->userEventService.sendOnboardedUserNotification(onboardedUser, productId); - //then - assertDoesNotThrow(executable); - verify(userRegistryConnector, times(1)).getUserByInternalId(userId); - } - - @Test - void sendOnboardedUserNotification1() throws JsonProcessingException { - //given - final String userId = UUID.randomUUID().toString(); - final String institutionId = UUID.randomUUID().toString(); - final String productId = "product-test"; - final OnboardedUser onboardedUser = mockInstance(new OnboardedUser()); - onboardedUser.setId(userId); - final OnboardedProduct onboardedProduct = mockInstance(new OnboardedProduct()); - onboardedProduct.setProductId(productId); - onboardedProduct.setStatus(RelationshipState.PENDING); - final UserBinding userBinding = mockInstance(new UserBinding()); - final User user = new DummyUser(institutionId); - user.setId(userId); - userBinding.setInstitutionId(institutionId); - userBinding.setProducts(List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - //when - Executable executable = () ->userEventService.sendOnboardedUserNotification(onboardedUser, productId); - //then - assertDoesNotThrow(executable); - verifyNoInteractions(kafkaTemplateUsers); - } - @Test - void sendOnboardedUserNotification2(){ - //given - final String userId = UUID.randomUUID().toString(); - final String institutionId = UUID.randomUUID().toString(); - final String productId = "product-test"; - final OnboardedUser onboardedUser = mockInstance(new OnboardedUser()); - onboardedUser.setId(userId); - final OnboardedProduct onboardedProduct = mockInstance(new OnboardedProduct()); - onboardedProduct.setProductId("product"); - onboardedProduct.setStatus(RelationshipState.ACTIVE); - final UserBinding userBinding = mockInstance(new UserBinding()); - final User user = new DummyUser(institutionId); - user.setId(userId); - userBinding.setInstitutionId(institutionId); - userBinding.setProducts(List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - //when - Executable executable = () ->userEventService.sendOnboardedUserNotification(onboardedUser, productId); - //then - assertDoesNotThrow(executable); - verifyNoInteractions(kafkaTemplateUsers); - } - - @Test - void sendOnboardedUserNotifications_userNotFound(){ - //given - final String userId = UUID.randomUUID().toString(); - final String institutionId = UUID.randomUUID().toString(); - final String productId = "product-test"; - final OnboardedUser onboardedUser = mockInstance(new OnboardedUser()); - onboardedUser.setId(userId); - final OnboardedProduct onboardedProduct = mockInstance(new OnboardedProduct()); - onboardedProduct.setProductId(productId); - final UserBinding userBinding = mockInstance(new UserBinding()); - final User user = new DummyUser(institutionId); - user.setId(userId); - userBinding.setInstitutionId(institutionId); - userBinding.setProducts(List.of(onboardedProduct)); - onboardedUser.setBindings(List.of(userBinding)); - when(userRegistryConnector.getUserByInternalId(any())).thenThrow(ResourceNotFoundException.class); - //when - Executable executable = () ->userEventService.sendOnboardedUserNotification(onboardedUser, productId); - //then - assertDoesNotThrow(executable); - verify(userRegistryConnector, times(1)).getUserByInternalId(userId); - } - -} \ No newline at end of file diff --git a/infra/container_apps/env/dev-pnpg/terraform.tfvars b/infra/container_apps/env/dev-pnpg/terraform.tfvars index e720fe364..d7857b7f7 100644 --- a/infra/container_apps/env/dev-pnpg/terraform.tfvars +++ b/infra/container_apps/env/dev-pnpg/terraform.tfvars @@ -70,18 +70,6 @@ app_settings = [ name = "STORAGE_TEMPLATE_URL" value = "https://selcdweupnpgcheckoutsa.z6.web.core.windows.net" }, - { - name = "KAFKA_BROKER" - value = "selc-d-eventhub-ns.servicebus.windows.net:9093" - }, - { - name = "KAFKA_CONTRACTS_TOPIC" - value = "SC-Contracts" - }, - { - name = "KAFKA_USER_TOPIC" - value = "SC-Users" - }, { name = "APPLICATIONINSIGHTS_ROLE_NAME" value = "ms-core" diff --git a/infra/container_apps/env/dev/terraform.tfvars b/infra/container_apps/env/dev/terraform.tfvars index 277be4870..a4471baf2 100644 --- a/infra/container_apps/env/dev/terraform.tfvars +++ b/infra/container_apps/env/dev/terraform.tfvars @@ -74,18 +74,6 @@ app_settings = [ name = "STORAGE_TEMPLATE_URL" value = "https://selcdcheckoutsa.z6.web.core.windows.net" }, - { - name = "KAFKA_BROKER" - value = "selc-d-eventhub-ns.servicebus.windows.net:9093" - }, - { - name = "KAFKA_CONTRACTS_TOPIC" - value = "SC-Contracts" - }, - { - name = "KAFKA_USER_TOPIC" - value = "SC-Users" - }, { name = "APPLICATIONINSIGHTS_ROLE_NAME" value = "ms-core" @@ -103,16 +91,6 @@ app_settings = [ value = "DEBUG" # // prod è “INFO" }, - { - name = "CORE_USER_EVENT_SERVICE_TYPE" - value = "ignore" - # //solo selfcare - }, - { - name = "CORE_CONTRACT_EVENT_SERVICE_TYPE" - value = "ignore" - # //solo selfcare - }, { name = "SMTP_HOST" value = "smtps.pec.aruba.it" @@ -154,13 +132,11 @@ secrets_names = { "MONGODB_CONNECTION_URI" = "mongodb-connection-string" "BLOB_STORAGE_CONN_STRING" = "blob-storage-contract-connection-string" "STORAGE_CREDENTIAL_SECRET" = "contracts-storage-access-key" - "KAFKA_CONTRACTS_SELFCARE_WO_SASL_JAAS_CONFIG" = "eventhub-sc-contracts-selfcare-wo-connection-string-lc" "SMTP_USR" = "smtp-usr" "SMTP_PSW" = "smtp-psw" "ONBOARDING_INSTITUTION_ALTERNATIVE_EMAIL" = "party-test-institution-email" "USER_REGISTRY_API_KEY" = "user-registry-api-key" "JWT_TOKEN_PUBLIC_KEY" = "jwt-public-key" - "KAFKA_USERS_SELFCARE_WO_SASL_JAAS_CONFIG" = "eventhub-sc-users-selfcare-wo-connection-string-lc" "BLOB_STORAGE_PRODUCT_CONNECTION_STRING" = "blob-storage-product-connection-string" "AWS_SES_ACCESS_KEY_ID" = "aws-ses-access-key-id" "AWS_SES_SECRET_ACCESS_KEY" = "aws-ses-secret-access-key" diff --git a/infra/container_apps/env/prod-pnpg/terraform.tfvars b/infra/container_apps/env/prod-pnpg/terraform.tfvars index 590e400ab..b88bfa3ff 100644 --- a/infra/container_apps/env/prod-pnpg/terraform.tfvars +++ b/infra/container_apps/env/prod-pnpg/terraform.tfvars @@ -65,18 +65,6 @@ app_settings = [ name = "STORAGE_TEMPLATE_URL" value = "https://selcpweupnpgcheckoutsa.z6.web.core.windows.net" }, - { - name = "KAFKA_BROKER" - value = "selc-p-pnpg-eventhub-ns.servicebus.windows.net:9093" - }, - { - name = "KAFKA_CONTRACTS_TOPIC" - value = "SC-Contracts" - }, - { - name = "KAFKA_USER_TOPIC" - value = "SC-Users" - }, { name = "APPLICATIONINSIGHTS_ROLE_NAME" value = "ms-core" diff --git a/infra/container_apps/env/prod/terraform.tfvars b/infra/container_apps/env/prod/terraform.tfvars index fb04e9a03..96bb2c8f9 100644 --- a/infra/container_apps/env/prod/terraform.tfvars +++ b/infra/container_apps/env/prod/terraform.tfvars @@ -69,18 +69,6 @@ app_settings = [ name = "STORAGE_TEMPLATE_URL" value = "https://selcpcheckoutsa.z6.web.core.windows.net" }, - { - name = "KAFKA_BROKER" - value = "selc-p-eventhub-ns.servicebus.windows.net:9093" - }, - { - name = "KAFKA_CONTRACTS_TOPIC" - value = "SC-Contracts" - }, - { - name = "KAFKA_USER_TOPIC" - value = "SC-Users" - }, { name = "APPLICATIONINSIGHTS_ROLE_NAME" value = "ms-core" @@ -96,15 +84,7 @@ app_settings = [ { name = "EXTERNAL_API_LOG_LEVEL" value = "“INFO" - }, - { - name = "CORE_USER_EVENT_SERVICE_TYPE" - value = "ignore" - }, - { - name = "CORE_CONTRACT_EVENT_SERVICE_TYPE" - value = "ignore" - }, + } { name = "SMTP_HOST" value = "smtps.pec.aruba.it" @@ -150,13 +130,11 @@ secrets_names = { "MONGODB_CONNECTION_URI" = "mongodb-connection-string" "BLOB_STORAGE_CONN_STRING" = "blob-storage-contract-connection-string" "STORAGE_CREDENTIAL_SECRET" = "contracts-storage-access-key" - "KAFKA_CONTRACTS_SELFCARE_WO_SASL_JAAS_CONFIG" = "eventhub-sc-contracts-selfcare-wo-connection-string-lc" "SMTP_USR" = "smtp-usr" "SMTP_PSW" = "smtp-psw" "ONBOARDING_INSTITUTION_ALTERNATIVE_EMAIL" = "party-test-institution-email" "USER_REGISTRY_API_KEY" = "user-registry-api-key" "JWT_TOKEN_PUBLIC_KEY" = "jwt-public-key" - "KAFKA_USERS_SELFCARE_WO_SASL_JAAS_CONFIG" = "eventhub-sc-users-selfcare-wo-connection-string-lc" "BLOB_STORAGE_PRODUCT_CONNECTION_STRING" = "blob-storage-product-connection-string" "AWS_SES_ACCESS_KEY_ID" = "aws-ses-access-key-id" "AWS_SES_SECRET_ACCESS_KEY" = "aws-ses-secret-access-key" diff --git a/infra/container_apps/env/uat-pnpg/terraform.tfvars b/infra/container_apps/env/uat-pnpg/terraform.tfvars index 6e69a51fc..2426434ea 100644 --- a/infra/container_apps/env/uat-pnpg/terraform.tfvars +++ b/infra/container_apps/env/uat-pnpg/terraform.tfvars @@ -58,18 +58,6 @@ app_settings = [ name = "STORAGE_TEMPLATE_URL" value = "https://selcuweupnpgcheckoutsa.z6.web.core.windows.net" }, - { - name = "KAFKA_BROKER" - value = "selc-u-pnpg-eventhub-ns.servicebus.windows.net:9093" - }, - { - name = "KAFKA_CONTRACTS_TOPIC" - value = "SC-Contracts" - }, - { - name = "KAFKA_USER_TOPIC" - value = "SC-Users" - }, { name = "APPLICATIONINSIGHTS_ROLE_NAME" value = "ms-core" diff --git a/infra/container_apps/env/uat/terraform.tfvars b/infra/container_apps/env/uat/terraform.tfvars index 87890e38f..64f9ff605 100644 --- a/infra/container_apps/env/uat/terraform.tfvars +++ b/infra/container_apps/env/uat/terraform.tfvars @@ -59,18 +59,6 @@ app_settings = [ name = "STORAGE_TEMPLATE_URL" value = "https://selcucheckoutsa.z6.web.core.windows.net" }, - { - name = "KAFKA_BROKER" - value = "selc-u-eventhub-ns.servicebus.windows.net:9093" - }, - { - name = "KAFKA_CONTRACTS_TOPIC" - value = "SC-Contracts" - }, - { - name = "KAFKA_USER_TOPIC" - value = "SC-Users" - }, { name = "APPLICATIONINSIGHTS_ROLE_NAME" value = "ms-core" @@ -88,14 +76,6 @@ app_settings = [ value = "DEBUG" # // prod è “INFO" }, - { - name = "CORE_USER_EVENT_SERVICE_TYPE" - value = "ignore" - }, - { - name = "CORE_CONTRACT_EVENT_SERVICE_TYPE" - value = "ignore" - }, { name = "SMTP_HOST" value = "smtps.pec.aruba.it" @@ -141,13 +121,11 @@ secrets_names = { "MONGODB_CONNECTION_URI" = "mongodb-connection-string" "BLOB_STORAGE_CONN_STRING" = "blob-storage-contract-connection-string" "STORAGE_CREDENTIAL_SECRET" = "contracts-storage-access-key" - "KAFKA_CONTRACTS_SELFCARE_WO_SASL_JAAS_CONFIG" = "eventhub-sc-contracts-selfcare-wo-connection-string-lc" "SMTP_USR" = "smtp-usr" "SMTP_PSW" = "smtp-psw" "ONBOARDING_INSTITUTION_ALTERNATIVE_EMAIL" = "party-test-institution-email" "USER_REGISTRY_API_KEY" = "user-registry-api-key" "JWT_TOKEN_PUBLIC_KEY" = "jwt-public-key" - "KAFKA_USERS_SELFCARE_WO_SASL_JAAS_CONFIG" = "eventhub-sc-users-selfcare-wo-connection-string-lc" "BLOB_STORAGE_PRODUCT_CONNECTION_STRING" = "blob-storage-product-connection-string" "AWS_SES_ACCESS_KEY_ID" = "aws-ses-access-key-id" "AWS_SES_SECRET_ACCESS_KEY" = "aws-ses-secret-access-key" diff --git a/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/InstitutionController.java b/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/InstitutionController.java index 83bd169fe..8565933e1 100644 --- a/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/InstitutionController.java +++ b/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/InstitutionController.java @@ -12,7 +12,6 @@ import it.pagopa.selfcare.mscore.core.InstitutionService; import it.pagopa.selfcare.mscore.core.OnboardingService; import it.pagopa.selfcare.mscore.model.institution.*; -import it.pagopa.selfcare.mscore.model.user.UserToOnboard; import it.pagopa.selfcare.mscore.web.model.institution.*; import it.pagopa.selfcare.mscore.web.model.mapper.*; import it.pagopa.selfcare.mscore.web.model.onboarding.OnboardedProducts; @@ -44,18 +43,15 @@ public class InstitutionController { private final OnboardingResourceMapper onboardingResourceMapper; private final InstitutionResourceMapper institutionResourceMapper; private final BrokerMapper brokerMapper; - private final UserMapper userMapper; public InstitutionController(InstitutionService institutionService, OnboardingService onboardingService, OnboardingResourceMapper onboardingResourceMapper, InstitutionResourceMapper institutionResourceMapper, - BrokerMapper brokerMapper, - UserMapper userMapper) { + BrokerMapper brokerMapper) { this.institutionService = institutionService; this.onboardingService = onboardingService; this.onboardingResourceMapper = onboardingResourceMapper; this.institutionResourceMapper = institutionResourceMapper; - this.userMapper = userMapper; this.brokerMapper = brokerMapper; } @@ -354,10 +350,7 @@ public ResponseEntity updateInstitution(@ApiParam("${swagge public ResponseEntity onboardingInstitution(@RequestBody @Valid InstitutionOnboardingRequest request, @PathVariable("id") String id) { CustomExceptionMessage.setCustomMessage(GenericError.ONBOARDING_OPERATION_ERROR); - List usersToOnboard = Optional.ofNullable(request.getUsers()) - .map(users -> users.stream().map(userMapper::toUserToOnboard).toList()) - .orElse(List.of()); - Institution institution = onboardingService.persistOnboarding(id, request.getProductId(), usersToOnboard, onboardingResourceMapper.toOnboarding(request)); + Institution institution = onboardingService.persistOnboarding(id, request.getProductId(), onboardingResourceMapper.toOnboarding(request)); return ResponseEntity .status(HttpStatus.CREATED) .body(institutionResourceMapper.toInstitutionResponse(institution)); diff --git a/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/QueueNotificationController.java b/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/QueueNotificationController.java deleted file mode 100644 index 1d0e74415..000000000 --- a/web/src/main/java/it/pagopa/selfcare/mscore/web/controller/QueueNotificationController.java +++ /dev/null @@ -1,31 +0,0 @@ -package it.pagopa.selfcare.mscore.web.controller; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import it.pagopa.selfcare.mscore.core.QueueNotificationService; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.*; - -@RestController -@Slf4j -@RequestMapping("/notification-event") -@Api(tags = "Event") -public class QueueNotificationController { - - private final QueueNotificationService queueNotificationService; - - public QueueNotificationController(QueueNotificationService queueNotificationService) { - this.queueNotificationService = queueNotificationService; - } - @ApiOperation(value = "", notes = "Function to send a specific onboarding using institutionId and tokenId ") - @PutMapping(value = "/contracts") - @ResponseStatus(HttpStatus.OK) - public void resendContractsByInstitutionIdAndTokenId(@RequestParam(name = "tokenId") String tokenId, - @RequestParam(name = "institutionId") String institutionId){ - - log.trace("Resend contracts byInstitutionIdAndTokenId events started"); - queueNotificationService.sendContractsNotificationsByInstitutionIdAndTokenId(tokenId, institutionId); - } - -} \ No newline at end of file diff --git a/web/src/main/java/it/pagopa/selfcare/mscore/web/model/institution/InstitutionOnboardingRequest.java b/web/src/main/java/it/pagopa/selfcare/mscore/web/model/institution/InstitutionOnboardingRequest.java index fb7662e30..61d5ae5e8 100644 --- a/web/src/main/java/it/pagopa/selfcare/mscore/web/model/institution/InstitutionOnboardingRequest.java +++ b/web/src/main/java/it/pagopa/selfcare/mscore/web/model/institution/InstitutionOnboardingRequest.java @@ -1,11 +1,9 @@ package it.pagopa.selfcare.mscore.web.model.institution; -import it.pagopa.selfcare.mscore.web.model.user.Person; import lombok.Data; import javax.validation.constraints.NotEmpty; import java.time.LocalDateTime; -import java.util.List; @Data public class InstitutionOnboardingRequest { @@ -13,9 +11,6 @@ public class InstitutionOnboardingRequest { @NotEmpty(message = "productId is required") private String productId; - @NotEmpty(message = "at least one user is required") - private List users; - private String tokenId; private String contractPath; private String pricingPlan; diff --git a/web/src/main/java/it/pagopa/selfcare/mscore/web/model/mapper/UserMapper.java b/web/src/main/java/it/pagopa/selfcare/mscore/web/model/mapper/UserMapper.java index 74c259b89..d5eddec8d 100644 --- a/web/src/main/java/it/pagopa/selfcare/mscore/web/model/mapper/UserMapper.java +++ b/web/src/main/java/it/pagopa/selfcare/mscore/web/model/mapper/UserMapper.java @@ -1,57 +1,12 @@ package it.pagopa.selfcare.mscore.web.model.mapper; -import it.pagopa.selfcare.mscore.model.UserNotificationToSend; -import it.pagopa.selfcare.mscore.model.aggregation.QueryCount; -import it.pagopa.selfcare.mscore.model.institution.InstitutionUpdate; -import it.pagopa.selfcare.mscore.model.institution.WorkContact; -import it.pagopa.selfcare.mscore.model.onboarding.OnboardedUser; -import it.pagopa.selfcare.mscore.model.user.User; -import it.pagopa.selfcare.mscore.model.user.UserBinding; -import it.pagopa.selfcare.mscore.model.user.UserInfo; import it.pagopa.selfcare.mscore.model.user.UserToOnboard; -import it.pagopa.selfcare.mscore.web.model.institution.InstitutionUpdateRequest; -import it.pagopa.selfcare.mscore.web.model.institution.UserInfoResponse; -import it.pagopa.selfcare.mscore.web.model.user.*; +import it.pagopa.selfcare.mscore.web.model.user.Person; import org.mapstruct.Mapper; -import org.mapstruct.Mapping; -import org.mapstruct.Named; - -import java.util.List; -import java.util.Map; @Mapper(componentModel = "spring") public interface UserMapper { - @Mapping(source = "user.fiscalCode", target = "taxCode") - @Mapping(source = "user.familyName", target = "surname") - @Mapping(target = "email", expression = "java(retrieveMailFromWorkContacts(user.getWorkContacts(), institutionId))") - UserResponse toUserResponse(User user, String institutionId); - UserToOnboard toUserToOnboard(Person p); - - UserProductsResponse toEntity(OnboardedUser model); - - @Mapping(source = "userInfo.user.fiscalCode", target = "taxCode") - @Mapping(source = "userInfo.user.familyName", target = "surname") - @Mapping(source = "userInfo.user.name", target = "name") - @Mapping(target = "email", expression = "java(retrieveMailFromWorkContacts(userInfo.getUser().getWorkContacts(), institutionId))") - UserInfoResponse toUserInfoResponse(UserInfo userInfo, String institutionId); - - InstitutionProducts toInstitutionProducts(UserBinding model); - - InstitutionUpdate toInstitutionUpdate(InstitutionUpdateRequest request); - - UserNotificationResponse toUserNotification(UserNotificationToSend user); - UserProductsResponse toOnboardedUserResponse(OnboardedUser onboardedUser); - @Mapping(source = "_id", target = "productId") - ProductCount toProductCount(QueryCount queryCount); - - @Named("retrieveMailFromWorkContacts") - default String retrieveMailFromWorkContacts(Map map, String institutionId){ - if(map!=null && !map.isEmpty() && map.containsKey(institutionId)){ - return map.get(institutionId).getEmail(); - } - return null; - } } diff --git a/web/src/main/java/it/pagopa/selfcare/mscore/web/model/user/UserNotificationBindingsResponse.java b/web/src/main/java/it/pagopa/selfcare/mscore/web/model/user/UserNotificationBindingsResponse.java deleted file mode 100644 index bc6b113a4..000000000 --- a/web/src/main/java/it/pagopa/selfcare/mscore/web/model/user/UserNotificationBindingsResponse.java +++ /dev/null @@ -1,17 +0,0 @@ -package it.pagopa.selfcare.mscore.web.model.user; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Data -@NoArgsConstructor -public class UserNotificationBindingsResponse { - private List bindings; - - public UserNotificationBindingsResponse(List bindings) { - this.bindings = bindings; - } -} diff --git a/web/src/main/java/it/pagopa/selfcare/mscore/web/model/user/UserNotificationResponse.java b/web/src/main/java/it/pagopa/selfcare/mscore/web/model/user/UserNotificationResponse.java deleted file mode 100644 index e35f550ec..000000000 --- a/web/src/main/java/it/pagopa/selfcare/mscore/web/model/user/UserNotificationResponse.java +++ /dev/null @@ -1,24 +0,0 @@ -package it.pagopa.selfcare.mscore.web.model.user; - -import it.pagopa.selfcare.mscore.model.QueueEvent; -import it.pagopa.selfcare.mscore.model.UserToNotify; -import lombok.Data; - -import java.time.OffsetDateTime; - -/** - * This objects wrap user's info sent on topic sc-users - */ -@Data -public class UserNotificationResponse { - - private String id; - private String institutionId; - private String productId; - private String onboardingTokenId; - private OffsetDateTime createdAt; - private OffsetDateTime updatedAt; - private QueueEvent eventType; - private UserToNotify user; - -} diff --git a/web/src/main/java/it/pagopa/selfcare/mscore/web/model/user/UsersNotificationResponse.java b/web/src/main/java/it/pagopa/selfcare/mscore/web/model/user/UsersNotificationResponse.java deleted file mode 100644 index 651aa7148..000000000 --- a/web/src/main/java/it/pagopa/selfcare/mscore/web/model/user/UsersNotificationResponse.java +++ /dev/null @@ -1,15 +0,0 @@ -package it.pagopa.selfcare.mscore.web.model.user; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Data -@NoArgsConstructor -@AllArgsConstructor -public class UsersNotificationResponse { - - private List users; -} diff --git a/web/src/main/resources/swagger/swagger_en.properties b/web/src/main/resources/swagger/swagger_en.properties index e9a9343c2..323dfa9d4 100644 --- a/web/src/main/resources/swagger/swagger_en.properties +++ b/web/src/main/resources/swagger/swagger_en.properties @@ -7,9 +7,6 @@ swagger.mscore.external.institution.products=retrieves the products related to I swagger.mscore.external.geotaxonomies=retrieves the geographic taxonomies related to Institution. swagger.mscore.external.institution.relationships=returns the relationships related to the institution swagger.mscore.institutions=Gets institutions filtering by taxCode and/or subunitCode -swagger.ms-core.notification-event.api.start=Service to resend contract notifications on SC-Contracts topic -swagger.ms-core.notification-event.api.start.users=Service to resend old user onboardings to the SCUsers kafka queue, it can send the onboardings of a single user or also retrieve all the users for a given set of products in a paged manner by passing page and size -swagger.ms-core.notification-event.api.start.users.count=Users' Count for single product swagger.mscore.institution.create.from-ipa=create an institution from ipa registry swagger.mscore.institution.create.from-ivass=create an institution from ivass CSV swagger.mscore.institution.create.from-infocamere=create an institution from infocamere registry diff --git a/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/InstitutionControllerTest.java b/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/InstitutionControllerTest.java index 4ece7fd7b..4363b21c5 100644 --- a/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/InstitutionControllerTest.java +++ b/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/InstitutionControllerTest.java @@ -13,7 +13,6 @@ import it.pagopa.selfcare.mscore.web.TestUtils; import it.pagopa.selfcare.mscore.web.model.institution.*; import it.pagopa.selfcare.mscore.web.model.mapper.*; -import it.pagopa.selfcare.mscore.web.model.user.Person; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -80,20 +79,20 @@ class InstitutionControllerTest { private final static Onboarding onboarding; - private final static Billing billing; + private final static Billing staticBilling; - private final static Institution institution; + private final static Institution staticInstitution; static { - billing = new Billing(); - billing.setVatNumber("example"); - billing.setRecipientCode("example"); - billing.setTaxCodeInvoicing("example"); + staticBilling = new Billing(); + staticBilling.setVatNumber("example"); + staticBilling.setRecipientCode("example"); + staticBilling.setTaxCodeInvoicing("example"); onboarding = new Onboarding(); onboarding.setProductId("example"); onboarding.setStatus(RelationshipState.ACTIVE); - onboarding.setBilling(billing); + onboarding.setBilling(staticBilling); onboarding.setContract("contract"); onboarding.setTokenId("tokenId"); onboarding.setPricingPlan("setPricingPlan"); @@ -103,13 +102,13 @@ class InstitutionControllerTest { attribute.setCode("code"); attribute.setDescription("description"); - institution = new Institution(); - institution.setId("42"); - institution.setInstitutionType(InstitutionType.PG); - institution.setDescription("description"); - institution.setOnboarding(List.of(onboarding)); - institution.setAttributes(List.of(attribute)); - institution.setIstatCode("istatCode"); + staticInstitution = new Institution(); + staticInstitution.setId("42"); + staticInstitution.setInstitutionType(InstitutionType.PG); + staticInstitution.setDescription("description"); + staticInstitution.setOnboarding(List.of(onboarding)); + staticInstitution.setAttributes(List.of(attribute)); + staticInstitution.setIstatCode("istatCode"); } @@ -265,8 +264,8 @@ void shouldGetOnboardingsInstitutionByProductId() throws Exception { void retrieveInstitutionById() throws Exception { SecurityContext securityContext = Mockito.mock(SecurityContext.class); SecurityContextHolder.setContext(securityContext); - when(institutionService.retrieveInstitutionById("42")).thenReturn(institution); - institution.setId("id"); + when(institutionService.retrieveInstitutionById("42")).thenReturn(staticInstitution); + staticInstitution.setId("id"); MockHttpServletRequestBuilder requestBuilder = get("/institutions/{id}", "42"); ResultActions actualPerformResult = MockMvcBuilders.standaloneSetup(institutionController) .build() @@ -280,7 +279,7 @@ void retrieveInstitutionById() throws Exception { */ @Test void testRetrieveInstitutionById() throws Exception { - when(institutionService.retrieveInstitutionById(any())).thenReturn(institution); + when(institutionService.retrieveInstitutionById(any())).thenReturn(staticInstitution); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/institutions/{id}", "42"); MockMvcBuilders.standaloneSetup(institutionController) .build() @@ -1238,7 +1237,7 @@ void findFromProduct() throws Exception { Integer sizeMock = 2; // When - when(institutionService.getInstitutionsByProductId(any(), any(), any())).thenReturn(List.of(institution)); + when(institutionService.getInstitutionsByProductId(any(), any(), any())).thenReturn(List.of(staticInstitution)); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(BASE_URL + "/products/{productId}", productIdMock) .param("page", pageMock.toString()) .param("size", sizeMock.toString()); @@ -1352,10 +1351,9 @@ void institutionOnboarding() throws Exception { final String institutionId = "institutionId"; InstitutionOnboardingRequest request = new InstitutionOnboardingRequest(); request.setProductId("id"); - request.setUsers(List.of(new Person())); request.setIsAggregator(true); - when(onboardingService.persistOnboarding(any(), any(), any(), any())) + when(onboardingService.persistOnboarding(any(), any(), any())) .thenReturn(new Institution()); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders diff --git a/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/QueueNotificationControllerTest.java b/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/QueueNotificationControllerTest.java deleted file mode 100644 index a6b4b416a..000000000 --- a/web/src/test/java/it/pagopa/selfcare/mscore/web/controller/QueueNotificationControllerTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package it.pagopa.selfcare.mscore.web.controller; - -import com.fasterxml.jackson.databind.ObjectMapper; -import it.pagopa.selfcare.mscore.core.QueueNotificationService; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; - -import java.util.List; -import java.util.Optional; - -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@WebMvcTest(value = {QueueNotificationController.class}, excludeAutoConfiguration = SecurityAutoConfiguration.class) -@ContextConfiguration(classes = {QueueNotificationController.class}) -class QueueNotificationControllerTest { - private static final String BASE_URL = "/notification-event"; - @Autowired - protected MockMvc mvc; - - @MockBean - private QueueNotificationService queueNotificationService; - - @Autowired - private ObjectMapper objectMapper; - - @Test - void sendContractsByInstitutionIdAndTokenId() throws Exception { - - String institutionId = "institutionId"; - String tokenId = "tokenId"; - mvc.perform(MockMvcRequestBuilders - .put(BASE_URL + "/contracts") - .param("tokenId", tokenId) - .param("institutionId", institutionId)) - .andExpect(status().isOk()); - - Mockito.verify(queueNotificationService, Mockito.times(1)).sendContractsNotificationsByInstitutionIdAndTokenId(tokenId, institutionId); - } - -} \ No newline at end of file