diff --git a/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/openapi/LearnerEventsApi.kt b/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/openapi/LearnerEventsApi.kt index 3a5a1f5..e0a4e15 100644 --- a/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/openapi/LearnerEventsApi.kt +++ b/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/openapi/LearnerEventsApi.kt @@ -9,7 +9,6 @@ import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.parameters.RequestBody import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.security.SecurityRequirement -import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.Roles.ROLE_LEARNERS_RO import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.Roles.ROLE_LEARNERS_UI import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.LearnerEventsResponse import uk.gov.justice.hmpps.kotlin.common.ErrorResponse @@ -219,167 +218,3 @@ import uk.gov.justice.hmpps.kotlin.common.ErrorResponse ], ) annotation class LearnerEventsApi - -@Target(AnnotationTarget.FUNCTION) -@Retention(AnnotationRetention.RUNTIME) -@Operation( - summary = "Get learning events by Nomis ID", - description = "Get personal learning records and events by Nomis ID", - parameters = [Parameter(name = "X-Username", `in` = ParameterIn.HEADER, required = true)], - requestBody = RequestBody( - description = "Nomis ID of the learner", - required = true, - content = [ - Content( - mediaType = "application/json", - examples = [ - ExampleObject( - value = """ - { - "nomisId": "123456" - } - """, - ), - ], - ), - ], - ), - security = [SecurityRequirement(name = ROLE_LEARNERS_RO)], - responses = [ - ApiResponse( - responseCode = "200", - description = "The request was successful and a response was returned.", - content = [ - Content( - mediaType = "application/json", - schema = Schema(implementation = LearnerEventsResponse::class), - examples = [ - ExampleObject( - name = "Exact Match Response", - value = """ - { - "searchParameters": { - "givenName": "Sean", - "familyName": "Findlay", - "uln": "1174112637", - "dateOfBirth": "1980-11-01", - "gender": "MALE" - }, - "responseType": "Exact Match", - "foundUln": "1174112637", - "incomingUln": "1174112637", - "learnerRecord": [ - { - "id": "2931", - "achievementProviderUkprn": "10030488", - "achievementProviderName": "LUTON PENTECOSTAL CHURCH", - "awardingOrganisationName": "UNKNOWN", - "qualificationType": "GCSE", - "subjectCode": "50079116", - "achievementAwardDate": "2011-10-24", - "credits": "0", - "source": "ILR", - "dateLoaded": "2012-05-31 16:47:04", - "underDataChallenge": "N", - "level": "", - "status": "F", - "subject": "GCSE in English Literature", - "grade": "9999999999", - "awardingOrganisationUkprn": "UNKNWN", - "collectionType": "W", - "returnNumber": "02", - "participationStartDate": "2011-10-02", - "participationEndDate": "2011-10-24" - } - ] - } - """, - ), - ExampleObject( - name = "Linked Learner Match Response", - value = """ - { - "searchParameters": { - "givenName": "Connor", - "familyName": "Carroll", - "uln": "4444599390" - }, - "responseType": "Linked Learner Match", - "foundUln": "6936002314", - "incomingUln": "4444599390", - "learnerRecord": [ - { - "id": "4284", - "achievementProviderUkprn": "10032743", - "achievementProviderName": "PRIORSLEE PRIMARY SCHOOL ACADEMY TRUST", - "awardingOrganisationName": "UNKNOWN", - "qualificationType": "NVQ/GNVQ Key Skills Unit", - "subjectCode": "1000323X", - "achievementAwardDate": "2010-09-26", - "credits": "0", - "source": "ILR", - "dateLoaded": "2012-05-31 16:47:04", - "underDataChallenge": "N", - "level": "", - "status": "F", - "subject": "Key Skills in Application of Number - level 1", - "grade": "9999999999", - "awardingOrganisationUkprn": "UNKNWN", - "collectionType": "W", - "returnNumber": "02", - "participationStartDate": "2010-09-01", - "participationEndDate": "2010-09-26" - } - ] - } - """, - ), - ExampleObject( - name = "Learner opted to not share data Response", - value = """ - { - "searchParameters": { - "givenName": "John", - "familyName": "Smith", - "uln": "1026922983" - }, - "responseType": "Learner opted to not share data", - "foundUln": "1026922983", - "incomingUln": "1026922983", - "learnerRecord": [] - } - """, - ), - ExampleObject( - name = "Learner could not be verified Response", - value = """ - { - "searchParameters": { - "givenName": "John", - "familyName": "Smith", - "uln": "1174112637" - }, - "responseType": "Learner could not be verified", - "foundUln": "", - "incomingUln": "1174112637", - "learnerRecord": [] - } - """, - ), - ], - ), - ], - ), - ApiResponse( - responseCode = "401", - description = "Unauthorized to access this endpoint", - content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], - ), - ApiResponse( - responseCode = "403", - description = "Forbidden to access this endpoint", - content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], - ), - ], -) -annotation class LearnerEventsByNomisIdApi diff --git a/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/openapi/MatchConfirmApi.kt b/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/openapi/MatchConfirmApi.kt index 0a65455..a487b33 100644 --- a/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/openapi/MatchConfirmApi.kt +++ b/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/openapi/MatchConfirmApi.kt @@ -11,6 +11,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.security.SecurityRequirement import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.Roles.ROLE_LEARNERS_UI import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.request.ConfirmMatchRequest +import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.LearnerEventsResponse import uk.gov.justice.hmpps.kotlin.common.ErrorResponse @Target(AnnotationTarget.FUNCTION) @@ -61,3 +62,150 @@ import uk.gov.justice.hmpps.kotlin.common.ErrorResponse ], ) annotation class MatchConfirmApi + +@Target(AnnotationTarget.FUNCTION) +@Retention(AnnotationRetention.RUNTIME) +@Operation( + summary = "Get learning events by Nomis ID", + description = "Get personal learning records and events by Nomis ID", + parameters = [ + Parameter(name = "X-Username", `in` = ParameterIn.HEADER, required = true), + Parameter(name = "nomisId", `in` = ParameterIn.PATH, required = true), + ], + security = [SecurityRequirement(name = "learner-records-search-read-only-role")], + responses = [ + ApiResponse( + responseCode = "200", + description = "The request was successful and a response was returned.", + content = [ + Content( + mediaType = "application/json", + schema = Schema(implementation = LearnerEventsResponse::class), + examples = [ + ExampleObject( + name = "Exact Match Response", + value = """ + { + "searchParameters": { + "givenName": "Sean", + "familyName": "Findlay", + "uln": "1174112637" + }, + "responseType": "Exact Match", + "foundUln": "1174112637", + "incomingUln": "1174112637", + "learnerRecord": [ + { + "id": "2931", + "achievementProviderUkprn": "10030488", + "achievementProviderName": "LUTON PENTECOSTAL CHURCH", + "awardingOrganisationName": "UNKNOWN", + "qualificationType": "GCSE", + "subjectCode": "50079116", + "achievementAwardDate": "2011-10-24", + "credits": "0", + "source": "ILR", + "dateLoaded": "2012-05-31 16:47:04", + "underDataChallenge": "N", + "level": "", + "status": "F", + "subject": "GCSE in English Literature", + "grade": "9999999999", + "awardingOrganisationUkprn": "UNKNWN", + "collectionType": "W", + "returnNumber": "02", + "participationStartDate": "2011-10-02", + "participationEndDate": "2011-10-24" + } + ] + } + """, + ), + ExampleObject( + name = "Linked Learner Match Response", + value = """ + { + "searchParameters": { + "givenName": "Connor", + "familyName": "Carroll", + "uln": "4444599390" + }, + "responseType": "Linked Learner Match", + "foundUln": "6936002314", + "incomingUln": "4444599390", + "learnerRecord": [ + { + "id": "4284", + "achievementProviderUkprn": "10032743", + "achievementProviderName": "PRIORSLEE PRIMARY SCHOOL ACADEMY TRUST", + "awardingOrganisationName": "UNKNOWN", + "qualificationType": "NVQ/GNVQ Key Skills Unit", + "subjectCode": "1000323X", + "achievementAwardDate": "2010-09-26", + "credits": "0", + "source": "ILR", + "dateLoaded": "2012-05-31 16:47:04", + "underDataChallenge": "N", + "level": "", + "status": "F", + "subject": "Key Skills in Application of Number - level 1", + "grade": "9999999999", + "awardingOrganisationUkprn": "UNKNWN", + "collectionType": "W", + "returnNumber": "02", + "participationStartDate": "2010-09-01", + "participationEndDate": "2010-09-26" + } + ] + } + """, + ), + ExampleObject( + name = "Learner opted to not share data Response", + value = """ + { + "searchParameters": { + "givenName": "John", + "familyName": "Smith", + "uln": "1026922983" + }, + "responseType": "Learner opted to not share data", + "foundUln": "1026922983", + "incomingUln": "1026922983", + "learnerRecord": [] + } + """, + ), + ExampleObject( + name = "Learner could not be verified Response", + value = """ + { + "searchParameters": { + "givenName": "John", + "familyName": "Smith", + "uln": "1174112637" + }, + "responseType": "Learner could not be verified", + "foundUln": "", + "incomingUln": "1174112637", + "learnerRecord": [] + } + """, + ), + ], + ), + ], + ), + ApiResponse( + responseCode = "401", + description = "Unauthorized to access this endpoint", + content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], + ), + ApiResponse( + responseCode = "403", + description = "Forbidden to access this endpoint", + content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], + ), + ], +) +annotation class LearnerEventsByNomisIdApi diff --git a/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/LearnerEventsResource.kt b/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/LearnerEventsResource.kt index cffd81d..bd3415e 100644 --- a/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/LearnerEventsResource.kt +++ b/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/LearnerEventsResource.kt @@ -2,7 +2,6 @@ package uk.gov.justice.digital.hmpps.learnerrecordsapi.resource import io.swagger.v3.oas.annotations.tags.Tag import jakarta.validation.Valid -import net.minidev.json.JSONObject import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.security.access.prepost.PreAuthorize @@ -10,31 +9,22 @@ import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestHeader import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController -import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.AuditEvent.createAuditEvent -import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.Roles.ROLE_LEARNERS_RO import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.Roles.ROLE_LEARNERS_UI import uk.gov.justice.digital.hmpps.learnerrecordsapi.logging.LoggerUtil import uk.gov.justice.digital.hmpps.learnerrecordsapi.logging.LoggerUtil.log -import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.lrsapi.response.exceptions.MatchNotFoundException import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.request.LearnerEventsRequest -import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.CheckMatchResponse import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.LearnerEventsResponse import uk.gov.justice.digital.hmpps.learnerrecordsapi.openapi.LearnerEventsApi -import uk.gov.justice.digital.hmpps.learnerrecordsapi.openapi.LearnerEventsByNomisIdApi import uk.gov.justice.digital.hmpps.learnerrecordsapi.service.LearnerEventsService -import uk.gov.justice.hmpps.sqs.audit.HmppsAuditService @RestController +@PreAuthorize("hasRole('$ROLE_LEARNERS_UI')") class LearnerEventsResource( private val learnerEventsService: LearnerEventsService, - private val auditService: HmppsAuditService, ) { val logger = LoggerUtil.getLogger() - val searchLearnerEventsByULN = "SEARCH_LEARNER_EVENTS_BY_ULN" - val searchLearnerEventsByNomisId = "SEARCH_LEARNER_EVENTS_BY_NOMISID" - @PreAuthorize("hasRole('$ROLE_LEARNERS_UI')") @RequestMapping(value = ["/learner-events"], produces = ["application/json"]) @Tag(name = "Learning Events") @LearnerEventsApi @@ -42,30 +32,8 @@ class LearnerEventsResource( @RequestBody @Valid learnerEventsRequest: LearnerEventsRequest, @RequestHeader("X-Username", required = true) userName: String, ): ResponseEntity { - auditService.publishEvent(createAuditEvent(searchLearnerEventsByULN, userName, learnerEventsRequest.toString())) logger.log("Received a post request to learner events endpoint", learnerEventsRequest) val learnerEventsResponse = learnerEventsService.getLearningEvents(learnerEventsRequest, userName) return ResponseEntity.status(HttpStatus.OK).body(learnerEventsResponse) } - - @PreAuthorize("hasRole('$ROLE_LEARNERS_RO')") - @RequestMapping(value = ["/learner-events/nomisId"], produces = ["application/json"]) - @Tag(name = "Learning Events By Nomis ID") - @LearnerEventsByNomisIdApi - suspend fun findLearnerEventsByNomisId( - @RequestBody nomisId: JSONObject, - @RequestHeader("X-Username", required = true) userName: String, - ): ResponseEntity { - val nomisId = nomisId.getAsString("nomisId") - auditService.publishEvent(createAuditEvent(searchLearnerEventsByNomisId, userName, nomisId)) - logger.log("Received a post request to learner events by Nomis ID endpoint", nomisId) - val checkMatchResponse: CheckMatchResponse? = learnerEventsService.getMatchEntityForNomisId(nomisId) - if (checkMatchResponse == null) { - throw MatchNotFoundException(nomisId) - } else { - val learnerEventsRequest = learnerEventsService.formLearningEventRequestFromMatchEntity(checkMatchResponse) - val learnerEventsResponse = learnerEventsService.getLearningEvents(learnerEventsRequest, userName) - return ResponseEntity.status(HttpStatus.OK).body(learnerEventsResponse) - } - } } diff --git a/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/LearnersResource.kt b/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/LearnersResource.kt index 434730c..4a6bae3 100644 --- a/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/LearnersResource.kt +++ b/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/LearnersResource.kt @@ -10,7 +10,6 @@ import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestHeader import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController -import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.AuditEvent.createAuditEvent import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.Roles.ROLE_LEARNERS_UI import uk.gov.justice.digital.hmpps.learnerrecordsapi.logging.LoggerUtil import uk.gov.justice.digital.hmpps.learnerrecordsapi.logging.LoggerUtil.log @@ -18,18 +17,15 @@ import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.request.LearnersReq import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.LearnersResponse import uk.gov.justice.digital.hmpps.learnerrecordsapi.openapi.FindByDemographicApi import uk.gov.justice.digital.hmpps.learnerrecordsapi.service.LearnersService -import uk.gov.justice.hmpps.sqs.audit.HmppsAuditService @RestController @PreAuthorize("hasRole('$ROLE_LEARNERS_UI')") @RequestMapping(value = ["/learners"], produces = ["application/json"]) class LearnersResource( private val learnersService: LearnersService, - private val auditService: HmppsAuditService, ) { val logger = LoggerUtil.getLogger() - val searchLearnersByDemographics = "SEARCH_LEARNER_BY_DEMOGRAPHICS" @PostMapping @Tag(name = "Learners") @@ -39,13 +35,6 @@ class LearnersResource( @RequestHeader("X-Username", required = true) userName: String, ): ResponseEntity { logger.log("Received a post request to learners endpoint", findLearnerByDemographicsRequest) - auditService.publishEvent( - createAuditEvent( - searchLearnersByDemographics, - userName, - findLearnerByDemographicsRequest.toString(), - ), - ) val learnersResponse = learnersService.getLearners(findLearnerByDemographicsRequest, userName) return ResponseEntity.status(HttpStatus.OK).body(learnersResponse) } diff --git a/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/MatchResource.kt b/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/MatchResource.kt index 9cbd75f..7afa94a 100644 --- a/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/MatchResource.kt +++ b/src/main/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/MatchResource.kt @@ -12,25 +12,34 @@ import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestHeader import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController +import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.AuditEvent.createAuditEvent import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.Roles.ROLE_LEARNERS_RO import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.Roles.ROLE_LEARNERS_UI import uk.gov.justice.digital.hmpps.learnerrecordsapi.logging.LoggerUtil import uk.gov.justice.digital.hmpps.learnerrecordsapi.logging.LoggerUtil.log +import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.lrsapi.response.exceptions.MatchNotFoundException import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.request.ConfirmMatchRequest import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.CheckMatchResponse import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.CheckMatchStatus +import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.LearnerEventsResponse +import uk.gov.justice.digital.hmpps.learnerrecordsapi.openapi.LearnerEventsByNomisIdApi import uk.gov.justice.digital.hmpps.learnerrecordsapi.openapi.MatchCheckApi import uk.gov.justice.digital.hmpps.learnerrecordsapi.openapi.MatchConfirmApi +import uk.gov.justice.digital.hmpps.learnerrecordsapi.service.LearnerEventsService import uk.gov.justice.digital.hmpps.learnerrecordsapi.service.MatchService +import uk.gov.justice.hmpps.sqs.audit.HmppsAuditService import java.net.URI @RestController @RequestMapping(value = ["/match"], produces = ["application/json"]) class MatchResource( private val matchService: MatchService, + private val learnerEventsService: LearnerEventsService, + private val auditService: HmppsAuditService, ) { val logger = LoggerUtil.getLogger() + val searchLearnerEventsByNomisId = "SEARCH_LEARNER_EVENTS_BY_NOMISID" @PreAuthorize("hasAnyRole('$ROLE_LEARNERS_UI', '$ROLE_LEARNERS_RO')") @GetMapping("/{nomisId}") @@ -65,4 +74,24 @@ class MatchResource( matchService.saveMatch(nomisId, confirmMatchRequest) return ResponseEntity.created(URI.create("/match/$nomisId")).build() } + + @PreAuthorize("hasRole('$ROLE_LEARNERS_RO')") + @GetMapping(value = ["/{nomisId}/learner-events"], produces = ["application/json"]) + @Tag(name = "Learning Events By Nomis ID") + @LearnerEventsByNomisIdApi + suspend fun findLearnerEventsByNomisId( + @PathVariable(name = "nomisId", required = true) nomisId: String, + @RequestHeader("X-Username", required = true) userName: String, + ): ResponseEntity { + auditService.publishEvent(createAuditEvent(searchLearnerEventsByNomisId, userName, nomisId)) + logger.log("Received a post request to learner events by Nomis ID endpoint", nomisId) + val checkMatchResponse: CheckMatchResponse? = learnerEventsService.getMatchEntityForNomisId(nomisId) + if (checkMatchResponse == null) { + throw MatchNotFoundException(nomisId) + } else { + val learnerEventsRequest = learnerEventsService.formLearningEventRequestFromMatchEntity(checkMatchResponse) + val learnerEventsResponse = learnerEventsService.getLearningEvents(learnerEventsRequest, userName) + return ResponseEntity.status(HttpStatus.OK).body(learnerEventsResponse) + } + } } diff --git a/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/integration/LearnerEventsResourceIntTest.kt b/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/integration/LearnerEventsResourceIntTest.kt index 88d68f1..4995bd6 100644 --- a/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/integration/LearnerEventsResourceIntTest.kt +++ b/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/integration/LearnerEventsResourceIntTest.kt @@ -1,21 +1,15 @@ package uk.gov.justice.digital.hmpps.learnerrecordsapi.integration import com.fasterxml.jackson.databind.ObjectMapper -import net.minidev.json.JSONObject import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired -import org.springframework.http.HttpStatus import org.springframework.http.MediaType -import software.amazon.awssdk.services.sqs.model.PurgeQueueRequest -import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.HmppsBoldLrsExceptionHandler -import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.Roles.ROLE_LEARNERS_RO import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.Roles.ROLE_LEARNERS_UI import uk.gov.justice.digital.hmpps.learnerrecordsapi.integration.wiremock.LRSApiExtension.Companion.lrsApiMock -import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.db.MatchEntity import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.lrsapi.response.LearningEvent import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.request.Gender import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.request.LearnerEventsRequest @@ -24,8 +18,6 @@ import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.LearnerEve import uk.gov.justice.digital.hmpps.learnerrecordsapi.repository.MatchRepository import uk.gov.justice.hmpps.sqs.HmppsQueueService import uk.gov.justice.hmpps.sqs.MissingQueueException -import uk.gov.justice.hmpps.sqs.audit.HmppsAuditEvent -import java.time.Instant class LearnerEventsResourceIntTest : IntegrationTestBase() { @@ -297,136 +289,4 @@ class LearnerEventsResourceIntTest : IntegrationTestBase() { null, Gender.MALE, ) - - @Test - fun `should emit an event that request is received for findByUln `() { - lrsApiMock.stubLearningEventsExactMatchFull() - - auditSqsClient.purgeQueue( - PurgeQueueRequest.builder() - .queueUrl(auditQueueUrl) - .build(), - ) - - webTestClient.post() - .uri("/learner-events") - .headers(setAuthorisation(roles = listOf(ROLE_LEARNERS_UI))) - .header("X-Username", "TestUser") - .bodyValue(getLearningEventsRequest) - .accept(MediaType.parseMediaType("application/json")) - .exchange() - .expectStatus() - .isOk - .expectBody() - .returnResult() - .responseBody - - val receivedEvent = objectMapper.readValue( - auditSqsClient.receiveMessage( - ReceiveMessageRequest.builder().queueUrl(auditQueueUrl).build(), - ).get().messages()[0].body(), - HmppsAuditEvent::class.java, - ) - - assertThat(receivedEvent.what).isEqualTo("SEARCH_LEARNER_EVENTS_BY_ULN") - assertThat(receivedEvent.who).isEqualTo("TestUser") - assertThat(receivedEvent.service).isEqualTo("hmpps-learner-records-api") - assertThat(receivedEvent.`when`).isBeforeOrEqualTo(Instant.now()) - } - - @Test - fun `should return Found if the Given Nomis ID does match or exists and return Learning Events`() { - lrsApiMock.stubLearningEventsExactMatchFull() - - val requestJson = JSONObject() - requestJson.put("nomisId", "123456") - - matchRepository.save( - MatchEntity( - null, - "123456", - "1234567890", - getLearningEventsRequest.givenName, - getLearningEventsRequest.familyName, - getLearningEventsRequest.dateOfBirth, - getLearningEventsRequest.gender.toString(), - ), - ) - - val expectedResponse = LearnerEventsResponse( - getLearningEventsRequest, - LRSResponseType.EXACT_MATCH, - "1234567890", - "1234567890", - listOf( - LearningEvent( - id = "28538264", - achievementProviderUkprn = "90000051", - achievementProviderName = "TEST90000051", - awardingOrganisationName = "Pearson Education Ltd", - qualificationType = "", - subjectCode = "K/501/5773", - achievementAwardDate = "2010-01-01", - credits = "2", - source = "QCFU", - dateLoaded = "2014-05-21 14:49:01", - underDataChallenge = "N", - level = "Entry Level", - status = "F", - subject = "Introduction to Construction Work: Entry 3", - grade = "Pass", - awardingOrganisationUkprn = "90000051", - ), - ), - ) - - val actualResponse = objectMapper.readValue( - webTestClient.post() - .uri("/learner-events/nomisId") - .headers(setAuthorisation(roles = listOf(ROLE_LEARNERS_RO))) - .header("X-Username", "TestUser") - .bodyValue(requestJson) - .accept(MediaType.parseMediaType("application/json")) - .exchange() - .expectStatus() - .isOk - .expectBody() - .returnResult() - .responseBody, - LearnerEventsResponse::class.java, - ) - - assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse) - } - - @Test - fun `should return Not Found if the Given Nomis ID does not match or exists`() { - val requestJson = JSONObject() - requestJson.put("nomisId", "123456") - - val expectedResponse = HmppsBoldLrsExceptionHandler.ErrorResponse( - status = HttpStatus.NOT_FOUND, - errorCode = "Match not found", - userMessage = "No Match found for given NomisId 123456", - developerMessage = "Individual with this NomisId has not been matched to a ULN yet", - moreInfo = "Individual with this NomisId has not been matched to a ULN yet", - ) - - val actualResponse = objectMapper.readValue( - webTestClient.post() - .uri("/learner-events/nomisId") - .headers(setAuthorisation(roles = listOf(ROLE_LEARNERS_RO))) - .header("X-Username", "TestUser") - .bodyValue(requestJson) - .accept(MediaType.parseMediaType("application/json")) - .exchange() - .expectStatus() - .isNotFound - .expectBody() - .returnResult() - .responseBody, - HmppsBoldLrsExceptionHandler.ErrorResponse::class.java, - ) - assertThat(actualResponse).isEqualTo(expectedResponse) - } } diff --git a/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/integration/LearnersResourceIntTest.kt b/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/integration/LearnersResourceIntTest.kt index c2c7e7e..cb18ca0 100644 --- a/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/integration/LearnersResourceIntTest.kt +++ b/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/integration/LearnersResourceIntTest.kt @@ -1,47 +1,26 @@ package uk.gov.justice.digital.hmpps.learnerrecordsapi.integration import com.fasterxml.jackson.databind.ObjectMapper -import net.minidev.json.JSONObject import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.MediaType -import software.amazon.awssdk.services.sqs.model.PurgeQueueRequest -import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.HmppsBoldLrsExceptionHandler -import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.Roles.ROLE_LEARNERS_RO import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.Roles.ROLE_LEARNERS_UI import uk.gov.justice.digital.hmpps.learnerrecordsapi.integration.wiremock.LRSApiExtension.Companion.lrsApiMock -import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.db.MatchEntity import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.lrsapi.response.Learner import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.request.Gender import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.request.LearnersRequest import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.LRSResponseType import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.LearnersResponse -import uk.gov.justice.digital.hmpps.learnerrecordsapi.repository.MatchRepository -import uk.gov.justice.hmpps.sqs.HmppsQueueService -import uk.gov.justice.hmpps.sqs.MissingQueueException -import uk.gov.justice.hmpps.sqs.audit.HmppsAuditEvent -import java.time.Instant class LearnersResourceIntTest : IntegrationTestBase() { - @Autowired - protected lateinit var hmppsQueueService: HmppsQueueService @Autowired protected lateinit var objectMapper: ObjectMapper - @Autowired - lateinit var matchRepository: MatchRepository - - private val auditQueue by lazy { - hmppsQueueService.findByQueueId("audit") ?: throw MissingQueueException("HmppsQueue audit not found") - } - protected val auditSqsClient by lazy { auditQueue.sqsClient } - protected val auditQueueUrl by lazy { auditQueue.queueUrl } - @Nested @DisplayName("POST /learners") inner class LearnersEndpoint { @@ -349,92 +328,5 @@ class LearnersResourceIntTest : IntegrationTestBase() { val actualResponseString = executedRequest?.toString(Charsets.UTF_8) assertThat(actualResponseString).contains("Unrecognized field \\\"unknownValue\\\"") } - - @Test - fun `should emit an event that request is received for findByDemographics `() { - lrsApiMock.stubLearnerByDemographicsExactMatch() - - auditSqsClient.purgeQueue( - PurgeQueueRequest.builder() - .queueUrl(auditQueueUrl) - .build(), - ) - - webTestClient.post() - .uri("/learners") - .headers(setAuthorisation(roles = listOf(ROLE_LEARNERS_UI))) - .header("X-Username", "TestUser") - .bodyValue(findLearnerByDemographicsRequest) - .accept(MediaType.parseMediaType("application/json")) - .exchange() - .expectStatus() - .is2xxSuccessful - .expectBody() - .returnResult() - .responseBody - - val receivedEvent = objectMapper.readValue( - auditSqsClient.receiveMessage( - ReceiveMessageRequest.builder().queueUrl(auditQueueUrl).build(), - ).get().messages()[0].body(), - HmppsAuditEvent::class.java, - ) - - assertThat(receivedEvent.what).isEqualTo("SEARCH_LEARNER_BY_DEMOGRAPHICS") - assertThat(receivedEvent.who).isEqualTo("TestUser") - assertThat(receivedEvent.service).isEqualTo("hmpps-learner-records-api") - assertThat(receivedEvent.`when`).isBeforeOrEqualTo(Instant.now()) - } - - @Test - fun `should emit an event that request is received for find Learning Events by Nomis ID `() { - lrsApiMock.stubLearningEventsLinkedMatchFull() - - auditSqsClient.purgeQueue( - PurgeQueueRequest.builder() - .queueUrl(auditQueueUrl) - .build(), - ) - - val requestJson = JSONObject() - requestJson.put("nomisId", "123456") - - matchRepository.save( - MatchEntity( - null, - "123456", - "1234567890", - "Some Given Name", - "Some Family Name", - null, - Gender.MALE.toString(), - ), - ) - - webTestClient.post() - .uri("/learner-events/nomisId") - .headers(setAuthorisation(roles = listOf(ROLE_LEARNERS_RO))) - .header("X-Username", "TestUser") - .bodyValue(requestJson) - .accept(MediaType.parseMediaType("application/json")) - .exchange() - .expectStatus() - .is2xxSuccessful - .expectBody() - .returnResult() - .responseBody - - val receivedEvent = objectMapper.readValue( - auditSqsClient.receiveMessage( - ReceiveMessageRequest.builder().queueUrl(auditQueueUrl).build(), - ).get().messages()[0].body(), - HmppsAuditEvent::class.java, - ) - - assertThat(receivedEvent.what).isEqualTo("SEARCH_LEARNER_EVENTS_BY_NOMISID") - assertThat(receivedEvent.who).isEqualTo("TestUser") - assertThat(receivedEvent.service).isEqualTo("hmpps-learner-records-api") - assertThat(receivedEvent.`when`).isBeforeOrEqualTo(Instant.now()) - } } } diff --git a/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/integration/MatchResourceIntTest.kt b/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/integration/MatchResourceIntTest.kt index 7787b58..b2840c8 100644 --- a/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/integration/MatchResourceIntTest.kt +++ b/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/integration/MatchResourceIntTest.kt @@ -18,15 +18,27 @@ import org.springframework.context.annotation.Import import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.test.web.reactive.server.WebTestClient +import software.amazon.awssdk.services.sqs.model.PurgeQueueRequest +import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.HmppsBoldLrsExceptionHandler import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.Roles.ROLE_LEARNERS_RO import uk.gov.justice.digital.hmpps.learnerrecordsapi.config.Roles.ROLE_LEARNERS_UI +import uk.gov.justice.digital.hmpps.learnerrecordsapi.integration.wiremock.LRSApiExtension.Companion.lrsApiMock import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.db.MatchEntity +import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.lrsapi.response.LearningEvent import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.request.ConfirmMatchRequest +import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.request.Gender +import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.request.LearnerEventsRequest import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.CheckMatchResponse import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.CheckMatchStatus +import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.LRSResponseType +import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.LearnerEventsResponse import uk.gov.justice.digital.hmpps.learnerrecordsapi.repository.MatchRepository import uk.gov.justice.digital.hmpps.learnerrecordsapi.service.MatchService +import uk.gov.justice.hmpps.sqs.HmppsQueueService +import uk.gov.justice.hmpps.sqs.MissingQueueException +import uk.gov.justice.hmpps.sqs.audit.HmppsAuditEvent +import java.time.Instant @TestConfiguration class MockitoSpyConfig { @@ -49,6 +61,15 @@ class MatchResourceIntTest : IntegrationTestBase() { @Autowired protected lateinit var matchService: MatchService + @Autowired + protected lateinit var hmppsQueueService: HmppsQueueService + + private val auditQueue by lazy { + hmppsQueueService.findByQueueId("audit") ?: throw MissingQueueException("HmppsQueue audit not found") + } + protected val auditSqsClient by lazy { auditQueue.sqsClient } + protected val auditQueueUrl by lazy { auditQueue.queueUrl } + val nomisId = "A1234BC" val matchedUln = "A" val givenName = "John" @@ -203,4 +224,146 @@ class MatchResourceIntTest : IntegrationTestBase() { verify(matchService, times(1)).saveMatch(any(), any()) assertThat(actualResponse).isEqualTo(expectedError) } + + @Test + fun `should emit an event that request is received for find Learning Events by Nomis ID `() { + lrsApiMock.stubLearningEventsLinkedMatchFull() + + auditSqsClient.purgeQueue( + PurgeQueueRequest.builder() + .queueUrl(auditQueueUrl) + .build(), + ) + + matchRepository.save( + MatchEntity( + null, + "123456", + "1234567890", + "Some Given Name", + "Some Family Name", + null, + Gender.MALE.toString(), + ), + ) + + webTestClient.get() + .uri("/match/{nomisId}/learner-events", "123456") + .headers(setAuthorisation(roles = listOf(ROLE_LEARNERS_RO))) + .header("X-Username", "TestUser") + .accept(MediaType.parseMediaType("application/json")) + .exchange() + .expectStatus() + .is2xxSuccessful + .expectBody() + .returnResult() + .responseBody + + val receivedEvent = objectMapper.readValue( + auditSqsClient.receiveMessage( + ReceiveMessageRequest.builder().queueUrl(auditQueueUrl).build(), + ).get().messages()[0].body(), + HmppsAuditEvent::class.java, + ) + + assertThat(receivedEvent.what).isEqualTo("SEARCH_LEARNER_EVENTS_BY_NOMISID") + assertThat(receivedEvent.who).isEqualTo("TestUser") + assertThat(receivedEvent.service).isEqualTo("hmpps-learner-records-api") + assertThat(receivedEvent.`when`).isBeforeOrEqualTo(Instant.now()) + } + + @Test + fun `should return Found if the Given Nomis ID does match or exists and return Learning Events`() { + lrsApiMock.stubLearningEventsExactMatchFull() + + matchRepository.save( + MatchEntity( + null, + "123456", + "1234567890", + "Some Given Name", + "Some Family Name", + null, + Gender.MALE.toString(), + ), + ) + + val learningEventRequest = LearnerEventsRequest( + "Some Given Name", + "Some Family Name", + "1234567890", + null, + Gender.MALE, + ) + + val expectedResponse = LearnerEventsResponse( + learningEventRequest, + LRSResponseType.EXACT_MATCH, + "1234567890", + "1234567890", + listOf( + LearningEvent( + id = "28538264", + achievementProviderUkprn = "90000051", + achievementProviderName = "TEST90000051", + awardingOrganisationName = "Pearson Education Ltd", + qualificationType = "", + subjectCode = "K/501/5773", + achievementAwardDate = "2010-01-01", + credits = "2", + source = "QCFU", + dateLoaded = "2014-05-21 14:49:01", + underDataChallenge = "N", + level = "Entry Level", + status = "F", + subject = "Introduction to Construction Work: Entry 3", + grade = "Pass", + awardingOrganisationUkprn = "90000051", + ), + ), + ) + + val actualResponse = objectMapper.readValue( + webTestClient.get() + .uri("/match/{nomisId}/learner-events", "123456") + .headers(setAuthorisation(roles = listOf(ROLE_LEARNERS_RO))) + .header("X-Username", "TestUser") + .exchange() + .expectStatus() + .isOk + .expectBody() + .returnResult() + .responseBody, + LearnerEventsResponse::class.java, + ) + + assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse) + } + + @Test + fun `should return Not Found if the Given Nomis ID does not match or exists`() { + val expectedResponse = HmppsBoldLrsExceptionHandler.ErrorResponse( + status = HttpStatus.NOT_FOUND, + errorCode = "Match not found", + userMessage = "No Match found for given NomisId 123456", + developerMessage = "Individual with this NomisId has not been matched to a ULN yet", + moreInfo = "Individual with this NomisId has not been matched to a ULN yet", + ) + + val actualResponse = objectMapper.readValue( + webTestClient.get() + .uri("/match/{nomisId}/learner-events", "123456") + .headers(setAuthorisation(roles = listOf(ROLE_LEARNERS_RO))) + .header("X-Username", "TestUser") + .accept(MediaType.parseMediaType("application/json")) + .exchange() + .expectStatus() + .isNotFound + .expectBody() + .returnResult() + .responseBody, + HmppsBoldLrsExceptionHandler.ErrorResponse::class.java, + ) + assertThat(actualResponse).isEqualTo(expectedResponse) + } } diff --git a/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/LearnerEventsResourceTest.kt b/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/LearnerEventsResourceTest.kt deleted file mode 100644 index 458e13e..0000000 --- a/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/LearnerEventsResourceTest.kt +++ /dev/null @@ -1,73 +0,0 @@ -package uk.gov.justice.digital.hmpps.learnerrecordsapi.resource - -import kotlinx.coroutines.test.runTest -import net.minidev.json.JSONObject -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.assertThrows -import org.junit.jupiter.api.extension.ExtendWith -import org.mockito.Mockito.mock -import org.mockito.Mockito.`when` -import org.mockito.junit.jupiter.MockitoExtension -import org.mockito.kotlin.any -import org.springframework.http.HttpStatus -import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.lrsapi.response.exceptions.MatchNotFoundException -import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.CheckMatchResponse -import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.CheckMatchStatus -import uk.gov.justice.digital.hmpps.learnerrecordsapi.service.LearnerEventsService -import uk.gov.justice.digital.hmpps.learnerrecordsapi.service.MatchService -import uk.gov.justice.hmpps.sqs.audit.HmppsAuditService -import java.time.LocalDate - -@ExtendWith(MockitoExtension::class) -class LearnerEventsResourceTest { - private val nomisId = "A1234BC" - private val matchedUln = "q1234" - private val familyName = "Smith" - private val dateOfBirth = LocalDate.of(1980, 1, 1).toString() - private val gender = "Male" - private val givenName = "John Smith" - - private lateinit var mockMatchService: MatchService - private lateinit var mockLearnerEventsService: LearnerEventsService - private lateinit var mockAuditService: HmppsAuditService - private lateinit var learnerEventsResource: LearnerEventsResource - - @BeforeEach - fun setup() { - mockMatchService = mock(MatchService::class.java) - mockLearnerEventsService = mock(LearnerEventsService::class.java) - mockAuditService = mock(HmppsAuditService::class.java) - learnerEventsResource = LearnerEventsResource(mockLearnerEventsService, mockAuditService) - } - - @Test - fun `should throw MatchNotFound Exception if no match found`(): Unit = runTest { - `when`(mockLearnerEventsService.getMatchEntityForNomisId(any())).thenReturn(null) - val requestJson = JSONObject() - requestJson.put("nomisId", nomisId) - val exception = assertThrows { - learnerEventsResource.findLearnerEventsByNomisId(requestJson, "") - } - assertThat(exception.message).isEqualTo(nomisId) - } - - @Test - fun `should return entity if record found`(): Unit = runTest { - `when`(mockLearnerEventsService.getMatchEntityForNomisId(any())).thenReturn( - CheckMatchResponse( - matchedUln = matchedUln, - familyName = familyName, - givenName = givenName, - dateOfBirth = dateOfBirth, - gender = gender, - status = CheckMatchStatus.Found, - ), - ) - val requestJson = JSONObject() - requestJson.put("nomisId", nomisId) - val actual = learnerEventsResource.findLearnerEventsByNomisId(requestJson, "") - assertThat(actual.statusCode).isEqualTo(HttpStatus.OK) - } -} diff --git a/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/MatchResourceTest.kt b/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/MatchResourceTest.kt index 8662276..622c76c 100644 --- a/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/MatchResourceTest.kt +++ b/src/test/kotlin/uk/gov/justice/digital/hmpps/learnerrecordsapi/resource/MatchResourceTest.kt @@ -1,30 +1,46 @@ package uk.gov.justice.digital.hmpps.learnerrecordsapi.resource +import kotlinx.coroutines.test.runTest import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.extension.ExtendWith import org.mockito.Mockito.mock import org.mockito.Mockito.`when` import org.mockito.junit.jupiter.MockitoExtension import org.mockito.kotlin.any import org.springframework.http.HttpStatus +import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.lrsapi.response.exceptions.MatchNotFoundException import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.CheckMatchResponse import uk.gov.justice.digital.hmpps.learnerrecordsapi.models.response.CheckMatchStatus +import uk.gov.justice.digital.hmpps.learnerrecordsapi.service.LearnerEventsService import uk.gov.justice.digital.hmpps.learnerrecordsapi.service.MatchService +import uk.gov.justice.hmpps.sqs.audit.HmppsAuditService +import java.time.LocalDate @ExtendWith(MockitoExtension::class) class MatchResourceTest { private val nomisId = "A1234BC" private val matchedUln = "q1234" + private val familyName = "Smith" + private val dateOfBirth = LocalDate.of(1980, 1, 1).toString() + private val gender = "Male" + private val givenName = "John Smith" private lateinit var mockMatchService: MatchService private lateinit var matchResource: MatchResource + private lateinit var learnerEventsResource: LearnerEventsResource + private lateinit var mockAuditService: HmppsAuditService + private lateinit var mockLearnerEventsService: LearnerEventsService @BeforeEach fun setup() { mockMatchService = mock(MatchService::class.java) - matchResource = MatchResource(mockMatchService) + mockLearnerEventsService = mock(LearnerEventsService::class.java) + mockAuditService = mock(HmppsAuditService::class.java) + matchResource = MatchResource(mockMatchService, mockLearnerEventsService, mockAuditService) + learnerEventsResource = LearnerEventsResource(mockLearnerEventsService) } @Test @@ -62,4 +78,29 @@ class MatchResourceTest { assertThat(actual.statusCode).isEqualTo(HttpStatus.OK) assertThat(actual.body?.status ?: "").isEqualTo(CheckMatchStatus.NoMatch) } + + @Test + fun `should throw MatchNotFound Exception if no match found`(): Unit = runTest { + `when`(mockLearnerEventsService.getMatchEntityForNomisId(any())).thenReturn(null) + val exception = assertThrows { + matchResource.findLearnerEventsByNomisId(nomisId, "") + } + assertThat(exception.message).isEqualTo(nomisId) + } + + @Test + fun `should return Match entity if record found`(): Unit = runTest { + `when`(mockLearnerEventsService.getMatchEntityForNomisId(any())).thenReturn( + CheckMatchResponse( + matchedUln = matchedUln, + familyName = familyName, + givenName = givenName, + dateOfBirth = dateOfBirth, + gender = gender, + status = CheckMatchStatus.Found, + ), + ) + val actual = matchResource.findLearnerEventsByNomisId(nomisId, "") + assertThat(actual.statusCode).isEqualTo(HttpStatus.OK) + } }