diff --git a/src/main/java/org/folio/client/feign/ConsortiaConfigurationClient.java b/src/main/java/org/folio/client/feign/ConsortiaConfigurationClient.java new file mode 100644 index 00000000..d9602ae5 --- /dev/null +++ b/src/main/java/org/folio/client/feign/ConsortiaConfigurationClient.java @@ -0,0 +1,13 @@ +package org.folio.client.feign; + +import org.folio.domain.dto.ConsortiaConfiguration; +import org.folio.spring.config.FeignClientConfiguration; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; + +@FeignClient(name = "consortia-configuration", url = "consortia-configuration", configuration = FeignClientConfiguration.class) +public interface ConsortiaConfigurationClient { + + @GetMapping + ConsortiaConfiguration getConfiguration(); +} diff --git a/src/main/java/org/folio/domain/Constants.java b/src/main/java/org/folio/domain/Constants.java deleted file mode 100644 index 35a1ad8e..00000000 --- a/src/main/java/org/folio/domain/Constants.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.folio.domain; - -import static org.folio.domain.dto.Request.RequestTypeEnum.HOLD; - -import org.folio.domain.dto.Request; - -import lombok.experimental.UtilityClass; - -@UtilityClass -public class Constants { - public static final String CENTRAL_TENANT_ID = "consortium"; - public static final Request.RequestTypeEnum PRIMARY_REQUEST_TYPE = HOLD; -} diff --git a/src/main/java/org/folio/listener/kafka/KafkaEventListener.java b/src/main/java/org/folio/listener/kafka/KafkaEventListener.java index 64d393fb..bc87dfed 100644 --- a/src/main/java/org/folio/listener/kafka/KafkaEventListener.java +++ b/src/main/java/org/folio/listener/kafka/KafkaEventListener.java @@ -1,8 +1,7 @@ package org.folio.listener.kafka; -import static org.folio.domain.Constants.CENTRAL_TENANT_ID; - import java.nio.charset.StandardCharsets; +import java.util.Map; import java.util.Optional; import org.folio.domain.dto.Loan; @@ -11,28 +10,34 @@ import org.folio.domain.dto.User; import org.folio.domain.dto.UserGroup; import org.folio.exception.KafkaEventDeserializationException; +import org.folio.service.ConsortiaService; import org.folio.service.KafkaEventHandler; import org.folio.service.impl.LoanEventHandler; import org.folio.service.impl.RequestBatchUpdateEventHandler; import org.folio.service.impl.RequestEventHandler; import org.folio.service.impl.UserEventHandler; import org.folio.service.impl.UserGroupEventHandler; +import org.folio.spring.DefaultFolioExecutionContext; +import org.folio.spring.FolioExecutionContext; +import org.folio.spring.FolioModuleMetadata; import org.folio.spring.integration.XOkapiHeaders; +import org.folio.spring.scope.FolioExecutionContextSetter; import org.folio.spring.service.SystemUserScopedExecutionService; import org.folio.support.KafkaEvent; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.annotation.KafkaListener; -import org.springframework.messaging.MessageHeaders; +import org.springframework.messaging.handler.annotation.Headers; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j2; @Component @Log4j2 +@RequiredArgsConstructor public class KafkaEventListener { private static final ObjectMapper objectMapper = new ObjectMapper(); private final RequestEventHandler requestEventHandler; @@ -41,26 +46,14 @@ public class KafkaEventListener { private final UserEventHandler userEventHandler; private final SystemUserScopedExecutionService systemUserScopedExecutionService; private final RequestBatchUpdateEventHandler requestBatchEventHandler; - - @Autowired - public KafkaEventListener(RequestEventHandler requestEventHandler, - LoanEventHandler loanEventHandler, RequestBatchUpdateEventHandler requestBatchEventHandler, - SystemUserScopedExecutionService systemUserScopedExecutionService, - UserGroupEventHandler userGroupEventHandler, UserEventHandler userEventHandler) { - - this.requestEventHandler = requestEventHandler; - this.loanEventHandler = loanEventHandler; - this.systemUserScopedExecutionService = systemUserScopedExecutionService; - this.userGroupEventHandler = userGroupEventHandler; - this.requestBatchEventHandler = requestBatchEventHandler; - this.userEventHandler = userEventHandler; - } + private final ConsortiaService consortiaService; + private final FolioModuleMetadata folioModuleMetadata; @KafkaListener( topicPattern = "${folio.environment}\\.\\w+\\.circulation\\.request", groupId = "${spring.kafka.consumer.group-id}" ) - public void handleRequestEvent(String eventString, MessageHeaders messageHeaders) { + public void handleRequestEvent(String eventString, @Headers Map messageHeaders) { handleEvent(eventString, requestEventHandler, messageHeaders, Request.class); } @@ -68,7 +61,7 @@ public void handleRequestEvent(String eventString, MessageHeaders messageHeaders topicPattern = "${folio.environment}\\.\\w+\\.circulation\\.loan", groupId = "${spring.kafka.consumer.group-id}" ) - public void handleLoanEvent(String eventString, MessageHeaders messageHeaders) { + public void handleLoanEvent(String eventString, @Headers Map messageHeaders) { handleEvent(eventString, loanEventHandler, messageHeaders, Loan.class); } @@ -76,7 +69,7 @@ public void handleLoanEvent(String eventString, MessageHeaders messageHeaders) { topicPattern = "${folio.environment}\\.\\w+\\.circulation\\.request-queue-reordering", groupId = "${spring.kafka.consumer.group-id}" ) - public void handleRequestBatchUpdateEvent(String eventString, MessageHeaders messageHeaders) { + public void handleRequestBatchUpdateEvent(String eventString, @Headers Map messageHeaders) { handleEvent(eventString, requestBatchEventHandler, messageHeaders, RequestsBatchUpdate.class); } @@ -84,7 +77,7 @@ public void handleRequestBatchUpdateEvent(String eventString, MessageHeaders mes topicPattern = "${folio.environment}\\.\\w+\\.users\\.userGroup", groupId = "${spring.kafka.consumer.group-id}" ) - public void handleUserGroupEvent(String eventString, MessageHeaders messageHeaders) { + public void handleUserGroupEvent(String eventString, @Headers Map messageHeaders) { handleEvent(eventString, userGroupEventHandler, messageHeaders, UserGroup.class); } @@ -92,18 +85,23 @@ public void handleUserGroupEvent(String eventString, MessageHeaders messageHeade topicPattern = "${folio.environment}\\.\\w+\\.users\\.users", groupId = "${spring.kafka.consumer.group-id}" ) - public void handleUserEvent(String eventString, MessageHeaders messageHeaders) { + public void handleUserEvent(String eventString, @Headers Map messageHeaders) { handleEvent(eventString, userEventHandler, messageHeaders, User.class); } private void handleEvent(String eventString, KafkaEventHandler handler, - MessageHeaders messageHeaders, Class payloadType) { + Map messageHeaders, Class payloadType) { log.debug("handleEvent:: event: {}", () -> eventString); KafkaEvent event = deserialize(eventString, messageHeaders, payloadType); log.info("handleEvent:: event received: {}", event::getId); - try { - systemUserScopedExecutionService.executeAsyncSystemUserScoped(CENTRAL_TENANT_ID, + + FolioExecutionContext context = DefaultFolioExecutionContext.fromMessageHeaders( + folioModuleMetadata, messageHeaders); + + try (FolioExecutionContextSetter contextSetter = new FolioExecutionContextSetter(context)) { + String centralTenantId = consortiaService.getCentralTenantId(); + systemUserScopedExecutionService.executeAsyncSystemUserScoped(centralTenantId, () -> handler.handle(event)); } catch (Exception e) { log.error("handleEvent:: failed to handle event {}", event.getId(), e); @@ -111,7 +109,7 @@ private void handleEvent(String eventString, KafkaEventHandler handler, log.info("handleEvent:: event consumed: {}", event::getId); } - private static KafkaEvent deserialize(String eventString, MessageHeaders messageHeaders, + private static KafkaEvent deserialize(String eventString, Map messageHeaders, Class dataType) { try { @@ -128,7 +126,7 @@ private static KafkaEvent deserialize(String eventString, MessageHeaders } } - private static String getHeaderValue(MessageHeaders headers, String headerName) { + private static String getHeaderValue(Map headers, String headerName) { log.debug("getHeaderValue:: headers: {}, headerName: {}", () -> headers, () -> headerName); var headerValue = headers.get(headerName); var value = headerValue == null diff --git a/src/main/java/org/folio/repository/EcsTlrRepository.java b/src/main/java/org/folio/repository/EcsTlrRepository.java index c80cce38..4c45fde6 100644 --- a/src/main/java/org/folio/repository/EcsTlrRepository.java +++ b/src/main/java/org/folio/repository/EcsTlrRepository.java @@ -14,5 +14,5 @@ public interface EcsTlrRepository extends JpaRepository { Optional findByPrimaryRequestId(UUID primaryRequestId); Optional findByInstanceId(UUID instanceId); List findByPrimaryRequestIdIn(List primaryRequestIds); - List findByItemIdAndRequesterId(UUID itemId, UUID requesterId); + List findByItemId(UUID itemId); } diff --git a/src/main/java/org/folio/service/ConsortiaService.java b/src/main/java/org/folio/service/ConsortiaService.java index 562d9749..f676f228 100644 --- a/src/main/java/org/folio/service/ConsortiaService.java +++ b/src/main/java/org/folio/service/ConsortiaService.java @@ -8,4 +8,5 @@ public interface ConsortiaService { TenantCollection getAllConsortiumTenants(String consortiumId); Collection getAllConsortiumTenants(); + String getCentralTenantId(); } diff --git a/src/main/java/org/folio/service/impl/ConsortiaServiceImpl.java b/src/main/java/org/folio/service/impl/ConsortiaServiceImpl.java index e328de0b..cbc145ef 100644 --- a/src/main/java/org/folio/service/impl/ConsortiaServiceImpl.java +++ b/src/main/java/org/folio/service/impl/ConsortiaServiceImpl.java @@ -6,6 +6,8 @@ import java.util.Optional; import org.folio.client.feign.ConsortiaClient; +import org.folio.client.feign.ConsortiaConfigurationClient; +import org.folio.domain.dto.ConsortiaConfiguration; import org.folio.domain.dto.Tenant; import org.folio.domain.dto.TenantCollection; import org.folio.domain.dto.UserTenant; @@ -21,6 +23,7 @@ @RequiredArgsConstructor public class ConsortiaServiceImpl implements ConsortiaService { private final ConsortiaClient consortiaClient; + private final ConsortiaConfigurationClient consortiaConfigurationClient; private final UserTenantsService userTenantsService; @Override @@ -40,4 +43,14 @@ public Collection getAllConsortiumTenants() { log.info("getAllConsortiumTenants:: found {} consortium tenants", tenants::size); return tenants; } + + @Override + public String getCentralTenantId() { + log.info("getCentralTenantId:: resolving central tenant ID"); + String centralTenantId = Optional.ofNullable(consortiaConfigurationClient.getConfiguration()) + .map(ConsortiaConfiguration::getCentralTenantId) + .orElseThrow(); + log.info("getCentralTenantId:: central tenant ID: {}", centralTenantId); + return centralTenantId; + } } diff --git a/src/main/java/org/folio/service/impl/LoanEventHandler.java b/src/main/java/org/folio/service/impl/LoanEventHandler.java index 1e21c8ef..2f996126 100644 --- a/src/main/java/org/folio/service/impl/LoanEventHandler.java +++ b/src/main/java/org/folio/service/impl/LoanEventHandler.java @@ -10,6 +10,7 @@ import java.util.Collection; import java.util.EnumSet; +import java.util.List; import java.util.UUID; import org.folio.domain.dto.Loan; @@ -129,15 +130,17 @@ else if (eventTenantIdIsSecondaryTenantId && secondaryTransactionRole == LENDER dcbService.updateTransactionStatuses(StatusEnum.CLOSED, ecsTlr); return; } - log.info("updateEcsTlr:: ECS TLR {} was not updated", ecsTlr::getId); + log.info("updateEcsTlr:: ECS TLR {} does not match loan update event, skipping", ecsTlr::getId); } log.info("updateEcsTlr:: suitable ECS TLR for loan {} in tenant {} was not found", loan.getId(), tenantId); } private Collection findEcsTlrs(Loan loan) { - log.info("findEcsTlr:: searching ECS TLRs for loan {}", loan::getId); - return ecsTlrRepository.findByItemIdAndRequesterId(UUID.fromString(loan.getItemId()), - UUID.fromString(loan.getUserId())); + log.info("findEcsTlrs:: searching ECS TLRs for item {}", loan::getItemId); + List ecsTlrs = ecsTlrRepository.findByItemId(UUID.fromString(loan.getItemId())); + log.info("findEcsTlrs:: found {} ECS TLRs", ecsTlrs::size); + + return ecsTlrs; } } diff --git a/src/main/java/org/folio/service/impl/RequestServiceImpl.java b/src/main/java/org/folio/service/impl/RequestServiceImpl.java index 313d4b8e..242c7c61 100644 --- a/src/main/java/org/folio/service/impl/RequestServiceImpl.java +++ b/src/main/java/org/folio/service/impl/RequestServiceImpl.java @@ -234,7 +234,7 @@ public CirculationItem createCirculationItem(Request request, String inventoryTe .effectiveLocationId(item.getEffectiveLocationId()) .lendingLibraryCode("TEST_CODE"); - log.info("createCirculationItem:: creating circulation item {}", circulationItem.toString()); + log.info("createCirculationItem:: creating circulation item {}", itemId); return circulationItemClient.createCirculationItem(itemId, circulationItem); } diff --git a/src/main/resources/swagger.api/ecs-tlr.yaml b/src/main/resources/swagger.api/ecs-tlr.yaml index b1d4460c..52bc6adb 100644 --- a/src/main/resources/swagger.api/ecs-tlr.yaml +++ b/src/main/resources/swagger.api/ecs-tlr.yaml @@ -90,9 +90,11 @@ components: transactionStatusResponse: $ref: 'schemas/transactionStatusResponse.yaml#/TransactionStatusResponse' tenant: - $ref: 'schemas/tenant.yaml#/Tenant' + $ref: 'schemas/consortia/tenant.yaml#/Tenant' tenants: - $ref: 'schemas/tenant.yaml#/TenantCollection' + $ref: 'schemas/consortia/tenant.yaml#/TenantCollection' + consortiaConfiguration: + $ref: 'schemas/consortia/consortiaConfiguration.yaml#/ConsortiaConfiguration' publicationRequest: $ref: 'schemas/publication.yaml#/PublicationRequest' publicationResponse: diff --git a/src/main/resources/swagger.api/schemas/consortia/consortiaConfiguration.yaml b/src/main/resources/swagger.api/schemas/consortia/consortiaConfiguration.yaml new file mode 100644 index 00000000..10b01b6d --- /dev/null +++ b/src/main/resources/swagger.api/schemas/consortia/consortiaConfiguration.yaml @@ -0,0 +1,9 @@ +ConsortiaConfiguration: + type: "object" + description: "Consortia Configuration" + properties: + id: + type: "string" + format: "uuid" + centralTenantId: + type: "string" \ No newline at end of file diff --git a/src/main/resources/swagger.api/schemas/tenant.yaml b/src/main/resources/swagger.api/schemas/consortia/tenant.yaml similarity index 100% rename from src/main/resources/swagger.api/schemas/tenant.yaml rename to src/main/resources/swagger.api/schemas/consortia/tenant.yaml diff --git a/src/test/java/org/folio/api/BaseIT.java b/src/test/java/org/folio/api/BaseIT.java index 4e905b89..f836fe5d 100644 --- a/src/test/java/org/folio/api/BaseIT.java +++ b/src/test/java/org/folio/api/BaseIT.java @@ -1,5 +1,6 @@ package org.folio.api; +import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -16,6 +17,8 @@ import org.apache.kafka.clients.admin.KafkaAdminClient; import org.apache.kafka.clients.admin.NewTopic; import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.header.Header; +import org.apache.kafka.common.header.internals.RecordHeader; import org.folio.spring.FolioExecutionContext; import org.folio.spring.FolioModuleMetadata; import org.folio.spring.integration.XOkapiHeaders; @@ -35,7 +38,6 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.kafka.core.KafkaTemplate; -import org.springframework.messaging.MessageHeaders; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.DynamicPropertyRegistry; @@ -74,6 +76,7 @@ public class BaseIT { private static final String FOLIO_ENVIRONMENT = "folio"; protected static final String HEADER_TENANT = "x-okapi-tenant"; + protected static final String USED_ID = "08d51c7a-0f36-4f3d-9e35-d285612a23df"; protected static final String TOKEN = "test_token"; protected static final String TENANT_ID_CONSORTIUM = "consortium"; // central tenant protected static final String TENANT_ID_UNIVERSITY = "university"; @@ -156,22 +159,48 @@ public static String getOkapiUrl() { protected static void setUpTenant(MockMvc mockMvc) { mockMvc.perform(MockMvcRequestBuilders.post("/_/tenant") .content(asJsonString(new TenantAttributes().moduleTo("mod-tlr"))) - .headers(defaultHeaders()) + .headers(defaultHeadersForRequest()) .contentType(APPLICATION_JSON)).andExpect(status().isNoContent()); } - public static HttpHeaders defaultHeaders() { + public static HttpHeaders defaultHeadersForRequest() { final HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.setContentType(APPLICATION_JSON); - httpHeaders.add(XOkapiHeaders.TENANT, TENANT_ID_CONSORTIUM); - httpHeaders.add(XOkapiHeaders.URL, wireMockServer.baseUrl()); - httpHeaders.add(XOkapiHeaders.TOKEN, TOKEN); - httpHeaders.add(XOkapiHeaders.USER_ID, "08d51c7a-0f36-4f3d-9e35-d285612a23df"); - + buildHeaders().forEach(httpHeaders::add); return httpHeaders; } + protected static Collection
buildHeadersForKafkaProducer(String tenant) { + return buildKafkaHeaders(tenant) + .entrySet() + .stream() + .map(entry -> new RecordHeader(entry.getKey(), (byte[]) entry.getValue())) + .collect(toList()); + } + + protected static Map buildKafkaHeaders(String tenantId) { + Map headers = buildHeaders(tenantId); + headers.put("folio.tenantId", tenantId); + + return headers.entrySet() + .stream() + .collect(toMap(Map.Entry::getKey, entry -> entry.getValue().getBytes())); + } + + protected static Map buildHeaders() { + return buildHeaders(TENANT_ID_CONSORTIUM); + } + + protected static Map buildHeaders(String tenantId) { + Map headers = new HashMap<>(); + headers.put(XOkapiHeaders.TENANT, tenantId); + headers.put(XOkapiHeaders.URL, wireMockServer.baseUrl()); + headers.put(XOkapiHeaders.TOKEN, TOKEN); + headers.put(XOkapiHeaders.USER_ID, USED_ID); + headers.put(XOkapiHeaders.REQUEST_ID, randomId()); + return headers; + } + @SneakyThrows public static String asJsonString(Object value) { return OBJECT_MAPPER.writeValueAsString(value); @@ -228,7 +257,7 @@ protected static String randomId() { } private static Map> buildDefaultHeaders() { - return new HashMap<>(defaultHeaders().entrySet() + return new HashMap<>(defaultHeadersForRequest().entrySet() .stream() .collect(toMap(Map.Entry::getKey, Map.Entry::getValue))); } @@ -260,11 +289,4 @@ private static String buildTopicName(String env, String tenant, String module, S return String.format("%s.%s.%s.%s", env, tenant, module, objectType); } - protected MessageHeaders getMessageHeaders(String tenantName, String tenantId) { - Map header = new HashMap<>(); - header.put(XOkapiHeaders.TENANT, tenantName.getBytes()); - header.put("folio.tenantId", tenantId); - - return new MessageHeaders(header); - } } diff --git a/src/test/java/org/folio/controller/KafkaEventListenerTest.java b/src/test/java/org/folio/controller/KafkaEventListenerTest.java index 8e896c79..3462e274 100644 --- a/src/test/java/org/folio/controller/KafkaEventListenerTest.java +++ b/src/test/java/org/folio/controller/KafkaEventListenerTest.java @@ -27,8 +27,8 @@ import static org.junit.jupiter.api.Assertions.assertNull; import java.time.ZonedDateTime; +import java.util.Collection; import java.util.Date; -import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -37,7 +37,7 @@ import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.TopicPartition; -import org.apache.kafka.common.header.internals.RecordHeader; +import org.apache.kafka.common.header.Header; import org.awaitility.Awaitility; import org.folio.api.BaseIT; import org.folio.domain.dto.DcbItem; @@ -622,11 +622,8 @@ private void publishEvent(String tenant, String topic, KafkaEvent event) @SneakyThrows private void publishEvent(String tenant, String topic, String payload) { - kafkaTemplate.send(new ProducerRecord<>(topic, 0, randomId(), payload, - List.of( - new RecordHeader(XOkapiHeaders.TENANT, tenant.getBytes()), - new RecordHeader("folio.tenantId", randomId().getBytes()) - ))) + Collection
headers = buildHeadersForKafkaProducer(tenant); + kafkaTemplate.send(new ProducerRecord<>(topic, 0, randomId(), payload, headers)) .get(10, SECONDS); } diff --git a/src/test/java/org/folio/listener/KafkaEventListenerTest.java b/src/test/java/org/folio/listener/KafkaEventListenerTest.java index fe5f8f5d..f1e698e5 100644 --- a/src/test/java/org/folio/listener/KafkaEventListenerTest.java +++ b/src/test/java/org/folio/listener/KafkaEventListenerTest.java @@ -8,6 +8,7 @@ import java.util.Map; import org.folio.listener.kafka.KafkaEventListener; +import org.folio.service.ConsortiaService; import org.folio.service.impl.LoanEventHandler; import org.folio.service.impl.RequestBatchUpdateEventHandler; import org.folio.service.impl.RequestEventHandler; @@ -16,6 +17,7 @@ import org.folio.spring.service.SystemUserScopedExecutionService; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.messaging.MessageHeaders; @@ -34,14 +36,15 @@ class KafkaEventListenerTest { UserGroupEventHandler userGroupEventHandler; @Mock UserEventHandler userEventHandler; + @Mock + ConsortiaService consortiaService; + @InjectMocks + KafkaEventListener kafkaEventListener; @Test void shouldHandleExceptionInEventHandler() { doThrow(new NullPointerException("NPE")).when(systemUserScopedExecutionService) .executeAsyncSystemUserScoped(any(), any()); - KafkaEventListener kafkaEventListener = new KafkaEventListener(requestEventHandler, - loanEventHandler, requestBatchEventHandler, systemUserScopedExecutionService, - userGroupEventHandler, userEventHandler); kafkaEventListener.handleRequestEvent("{}", new MessageHeaders(Map.of(TENANT, "default".getBytes()))); diff --git a/src/test/java/org/folio/service/LoanEventHandlerTest.java b/src/test/java/org/folio/service/LoanEventHandlerTest.java index a9afe582..294e4adc 100644 --- a/src/test/java/org/folio/service/LoanEventHandlerTest.java +++ b/src/test/java/org/folio/service/LoanEventHandlerTest.java @@ -69,14 +69,14 @@ void checkInEventIsIgnoredWhenEcsTlrForUpdatedLoanIsNotFound() { .itemId(itemId.toString()) .userId(userId.toString()); - when(ecsTlrRepository.findByItemIdAndRequesterId(itemId, userId)) + when(ecsTlrRepository.findByItemId(itemId)) .thenReturn(emptyList()); KafkaEvent event = new KafkaEvent<>(randomUUID().toString(), "test_tenant", UPDATED, 0L, new KafkaEvent.EventData<>(loan, loan), "test_tenant"); loanEventHandler.handle(event); - verify(ecsTlrRepository).findByItemIdAndRequesterId(itemId, userId); + verify(ecsTlrRepository).findByItemId(itemId); verifyNoInteractions(dcbService); } @@ -90,14 +90,14 @@ void checkInEventIsIgnoredWhenEcsTlrDoesNotContainsNoTransactionIds() { .itemId(itemId.toString()) .userId(userId.toString()); - when(ecsTlrRepository.findByItemIdAndRequesterId(itemId, userId)) + when(ecsTlrRepository.findByItemId(itemId)) .thenReturn(List.of(new EcsTlrEntity())); KafkaEvent event = new KafkaEvent<>(randomUUID().toString(), "test_tenant", UPDATED, 0L, new KafkaEvent.EventData<>(loan, loan), "test_tenant"); loanEventHandler.handle(event); - verify(ecsTlrRepository).findByItemIdAndRequesterId(itemId, userId); + verify(ecsTlrRepository).findByItemId(itemId); verifyNoInteractions(dcbService); } @@ -117,14 +117,14 @@ void checkInEventIsIgnoredWhenEventTenantDoesNotMatchEcsRequestTransactionTenant ecsTlr.setPrimaryRequestDcbTransactionId(randomUUID()); ecsTlr.setSecondaryRequestDcbTransactionId(randomUUID()); - when(ecsTlrRepository.findByItemIdAndRequesterId(itemId, userId)) + when(ecsTlrRepository.findByItemId(itemId)) .thenReturn(List.of(ecsTlr)); KafkaEvent event = new KafkaEvent<>(randomUUID().toString(), "test_tenant", UPDATED, 0L, new KafkaEvent.EventData<>(loan, loan), "test_tenant"); loanEventHandler.handle(event); - verify(ecsTlrRepository).findByItemIdAndRequesterId(itemId, userId); + verify(ecsTlrRepository).findByItemId(itemId); verifyNoInteractions(dcbService); } @@ -162,7 +162,7 @@ void checkInEventIsHandled(String primaryTransactionRole, String primaryTransact mockEcsTlr.setPrimaryRequestDcbTransactionId(primaryTransactionId); mockEcsTlr.setSecondaryRequestDcbTransactionId(secondaryTransactionId); - when(ecsTlrRepository.findByItemIdAndRequesterId(itemId, userId)) + when(ecsTlrRepository.findByItemId(itemId)) .thenReturn(List.of(mockEcsTlr)); TransactionStatusResponse mockPrimaryTransactionResponse = buildTransactionStatusResponse( @@ -185,7 +185,7 @@ void checkInEventIsHandled(String primaryTransactionRole, String primaryTransact loanEventHandler.handle(event); - verify(ecsTlrRepository).findByItemIdAndRequesterId(itemId, userId); + verify(ecsTlrRepository).findByItemId(itemId); verify(dcbService).getTransactionStatus(primaryTransactionId, primaryRequestTenant); verify(dcbService).getTransactionStatus(secondaryTransactionId, secondaryRequestTenant); verify(dcbService).updateTransactionStatuses(expectedNewStatus, mockEcsTlr); diff --git a/src/test/java/org/folio/service/RequestBatchUpdateEventHandlerTest.java b/src/test/java/org/folio/service/RequestBatchUpdateEventHandlerTest.java index 8425f55c..2de1dcd0 100644 --- a/src/test/java/org/folio/service/RequestBatchUpdateEventHandlerTest.java +++ b/src/test/java/org/folio/service/RequestBatchUpdateEventHandlerTest.java @@ -116,7 +116,7 @@ void shouldReorderTwoSecondaryRequestsWhenPrimaryRequestsReordered() { null, new RequestsBatchUpdate() .instanceId(instanceId) .requestLevel(RequestsBatchUpdate.RequestLevelEnum.TITLE))), - getMessageHeaders(CENTRAL_TENANT_ID, CENTRAL_TENANT_ID)); + buildKafkaHeaders(CENTRAL_TENANT_ID)); verify(requestService, times(1)).reorderRequestsQueueForInstance( instanceId, firstTenant, reorderQueue); @@ -193,7 +193,7 @@ void shouldReorderThreeSecondaryRequestsWhenPrimaryRequestsReordered() { null, new RequestsBatchUpdate() .instanceId(instanceId) .requestLevel(RequestsBatchUpdate.RequestLevelEnum.TITLE))), - getMessageHeaders(CENTRAL_TENANT_ID, CENTRAL_TENANT_ID)); + buildKafkaHeaders(CENTRAL_TENANT_ID)); verify(requestService, times(1)).reorderRequestsQueueForInstance( instanceId, firstTenant, reorderQueue); @@ -250,7 +250,7 @@ void shouldNotReorderSecondaryRequestsWhenPrimaryRequestsOrderIsUnchanged() { null, new RequestsBatchUpdate() .instanceId(instanceId) .requestLevel(RequestsBatchUpdate.RequestLevelEnum.TITLE))), - getMessageHeaders(CENTRAL_TENANT_ID, CENTRAL_TENANT_ID)); + buildKafkaHeaders(CENTRAL_TENANT_ID)); verify(requestService, times(0)).reorderRequestsQueueForInstance( eq(instanceId), eq(firstTenant), any()); @@ -308,7 +308,7 @@ void shouldNotReorderSecondaryRequestsWhenPrimaryRequestsAreNullOrEmtpy( null, new RequestsBatchUpdate() .instanceId(instanceId) .requestLevel(RequestsBatchUpdate.RequestLevelEnum.TITLE))), - getMessageHeaders(CENTRAL_TENANT_ID, CENTRAL_TENANT_ID)); + buildKafkaHeaders(CENTRAL_TENANT_ID)); verify(requestService, times(0)).reorderRequestsQueueForInstance( eq(instanceId), eq(firstTenant), any()); @@ -377,7 +377,7 @@ null, new RequestsBatchUpdate() .instanceId(instanceId) .itemId(itemId) .requestLevel(RequestsBatchUpdate.RequestLevelEnum.ITEM))), - getMessageHeaders(CENTRAL_TENANT_ID, CENTRAL_TENANT_ID)); + buildKafkaHeaders(CENTRAL_TENANT_ID)); verify(requestService, times(1)).reorderRequestsQueueForItem( itemId, firstTenant, reorderQueue); diff --git a/src/test/java/org/folio/service/RequestEventHandlerTest.java b/src/test/java/org/folio/service/RequestEventHandlerTest.java index 70c2615b..a1172aee 100644 --- a/src/test/java/org/folio/service/RequestEventHandlerTest.java +++ b/src/test/java/org/folio/service/RequestEventHandlerTest.java @@ -8,7 +8,6 @@ import static org.mockito.Mockito.when; import java.util.Optional; -import java.util.UUID; import org.folio.api.BaseIT; import org.folio.listener.kafka.KafkaEventListener; @@ -35,8 +34,7 @@ class RequestEventHandlerTest extends BaseIT { void handleRequestUpdateTest() { when(ecsTlrRepository.findBySecondaryRequestId(any())).thenReturn(Optional.of(getEcsTlrEntity())); doNothing().when(dcbService).createLendingTransaction(any()); - eventListener.handleRequestEvent(REQUEST_UPDATE_EVENT_SAMPLE, getMessageHeaders( - TENANT_ID_CONSORTIUM, UUID.randomUUID().toString())); + eventListener.handleRequestEvent(REQUEST_UPDATE_EVENT_SAMPLE, buildKafkaHeaders(TENANT_ID_CONSORTIUM)); verify(ecsTlrRepository).findBySecondaryRequestId(any()); } } diff --git a/src/test/java/org/folio/service/UserEventHandlerTest.java b/src/test/java/org/folio/service/UserEventHandlerTest.java index 94569125..7e7f4035 100644 --- a/src/test/java/org/folio/service/UserEventHandlerTest.java +++ b/src/test/java/org/folio/service/UserEventHandlerTest.java @@ -23,6 +23,7 @@ void handleUserUpdatingEventShouldUpdateUserForAllDataTenants() { when(userTenantsService.findFirstUserTenant()).thenReturn(mockUserTenant()); when(consortiaService.getAllConsortiumTenants(anyString())).thenReturn(mockTenantCollection()); when(userService.update(any(User.class))).thenReturn(new User()); + when(consortiaService.getCentralTenantId()).thenReturn(CENTRAL_TENANT_ID); doAnswer(invocation -> { ((Runnable) invocation.getArguments()[1]).run(); @@ -30,8 +31,7 @@ void handleUserUpdatingEventShouldUpdateUserForAllDataTenants() { }).when(systemUserScopedExecutionService).executeAsyncSystemUserScoped(anyString(), any(Runnable.class)); - eventListener.handleUserEvent(USER_UPDATING_EVENT_SAMPLE, - getMessageHeaders(TENANT, TENANT_ID)); + eventListener.handleUserEvent(USER_UPDATING_EVENT_SAMPLE, buildKafkaHeaders(CENTRAL_TENANT_ID)); verify(systemUserScopedExecutionService, times(3)) .executeAsyncSystemUserScoped(anyString(), any(Runnable.class)); diff --git a/src/test/java/org/folio/service/UserGroupEventHandlerTest.java b/src/test/java/org/folio/service/UserGroupEventHandlerTest.java index 6b92c7f5..5b6c227f 100644 --- a/src/test/java/org/folio/service/UserGroupEventHandlerTest.java +++ b/src/test/java/org/folio/service/UserGroupEventHandlerTest.java @@ -30,6 +30,7 @@ void handleUserGroupCreatingEventShouldCreateUserGroupForAllDataTenants() { when(userTenantsService.findFirstUserTenant()).thenReturn(mockUserTenant()); when(consortiaService.getAllConsortiumTenants(anyString())).thenReturn(mockTenantCollection()); when(userGroupService.create(any(UserGroup.class))).thenReturn(new UserGroup()); + when(consortiaService.getCentralTenantId()).thenReturn(CENTRAL_TENANT_ID); doAnswer(invocation -> { ((Runnable) invocation.getArguments()[1]).run(); @@ -38,7 +39,7 @@ void handleUserGroupCreatingEventShouldCreateUserGroupForAllDataTenants() { any(Runnable.class)); eventListener.handleUserGroupEvent(USER_GROUP_CREATING_EVENT_SAMPLE, - getMessageHeaders(TENANT, TENANT_ID)); + buildKafkaHeaders(CENTRAL_TENANT_ID)); verify(systemUserScopedExecutionService, times(3)).executeAsyncSystemUserScoped(anyString(), any(Runnable.class)); @@ -50,6 +51,7 @@ void handleUserGroupUpdatingEventShouldUpdateUserGroupForAllDataTenants() { when(userTenantsService.findFirstUserTenant()).thenReturn(mockUserTenant()); when(consortiaService.getAllConsortiumTenants(anyString())).thenReturn(mockTenantCollection()); when(userGroupService.update(any(UserGroup.class))).thenReturn(new UserGroup()); + when(consortiaService.getCentralTenantId()).thenReturn(CENTRAL_TENANT_ID); doAnswer(invocation -> { ((Runnable) invocation.getArguments()[1]).run(); @@ -58,7 +60,7 @@ void handleUserGroupUpdatingEventShouldUpdateUserGroupForAllDataTenants() { any(Runnable.class)); eventListener.handleUserGroupEvent(USER_GROUP_UPDATING_EVENT_SAMPLE, - getMessageHeaders(TENANT, TENANT_ID)); + buildKafkaHeaders(CENTRAL_TENANT_ID)); verify(systemUserScopedExecutionService, times(3)) .executeAsyncSystemUserScoped(anyString(), any(Runnable.class)); diff --git a/src/test/resources/mappings/consortiaConfiguration.json b/src/test/resources/mappings/consortiaConfiguration.json new file mode 100644 index 00000000..b978e6df --- /dev/null +++ b/src/test/resources/mappings/consortiaConfiguration.json @@ -0,0 +1,20 @@ +{ + "mappings": [ + { + "request": { + "method": "GET", + "url": "/consortia-configuration" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "jsonBody": { + "id": "0bc8835b-1233-48ba-bc75-979cb04dc06e", + "centralTenantId": "consortium" + } + } + } + ] +}