Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ESWE-1080] Expression-of-interest API #596

Merged
merged 23 commits into from
Feb 12, 2025
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package uk.gov.justice.digital.hmpps.hmppsintegrationapi.controllers.v1.person

import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.tags.Tag
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps.ExpressionOfInterest
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps.NomisNumber
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps.Response
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps.UpstreamApiError
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.services.GetPersonService
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.services.PutExpressionInterestService

@RestController
@RequestMapping("/v1/persons")
@Tag(name = "persons")
class ExpressionInterestController(
@Autowired val getPersonService: GetPersonService,
@Autowired val putExpressionInterestService: PutExpressionInterestService,
) {
val logger: Logger = LoggerFactory.getLogger(this::class.java)

@PutMapping("{hmppsId}/expression-of-interest/jobs/{jobid}")
@Operation(
summary = "Returns completed response",
responses = [
ApiResponse(responseCode = "200", useReturnTypeSchema = true, description = "Successfully submitted an expression of interest"),
ApiResponse(responseCode = "403", useReturnTypeSchema = true, description = "Access is forbidden"),
ApiResponse(responseCode = "404", useReturnTypeSchema = true, description = "Not found"),
],
)
fun submitExpressionOfInterest(
@Parameter(description = "A URL-encoded HMPPS identifier", example = "2008%2F0545166T") @PathVariable hmppsId: String,
@Parameter(description = "A job identifier") @PathVariable jobid: String,
): ResponseEntity<Void> {
try {
val hmppsIdCheck = getPersonService.getNomisNumber(hmppsId)

if (hmppsIdCheck.hasError(UpstreamApiError.Type.ENTITY_NOT_FOUND)) {
logger.info("Could not find nomis number for hmppsId: $hmppsId")
return ResponseEntity.badRequest().build()
}

if (hmppsIdCheck.hasError(UpstreamApiError.Type.BAD_REQUEST)) {
logger.info("Invalid hmppsId: $hmppsId")
return ResponseEntity.badRequest().build()
}

val verifiedNomisNumber = getVerifiedNomisNumber(hmppsIdCheck) ?: return ResponseEntity.badRequest().build()
putExpressionInterestService.sendExpressionOfInterest(ExpressionOfInterest(jobid, verifiedNomisNumber))

return ResponseEntity.ok().build()
} catch (e: Exception) {
logger.info("ExpressionInterestController: Unable to send message: ${e.message}")
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build<Void>()
}
}

fun getVerifiedNomisNumber(nomisNumberResponse: Response<NomisNumber?>) = nomisNumberResponse.data?.nomisNumber
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package uk.gov.justice.digital.hmpps.hmppsintegrationapi.exception

class MessageFailedException(
msg: String,
) : RuntimeException(msg)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps

data class ExpressionOfInterest(
val jobId: String,
val prisonNumber: String,
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps

data class ExpressionOfInterestMessage(
val messageId: String,
val jobId: String,
val prisonNumber: String,
val eventType: EventType = EventType.EXPRESSION_OF_INTEREST_MESSAGE_CREATED,
) {
enum class EventType {
EXPRESSION_OF_INTEREST_MESSAGE_CREATED,
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package uk.gov.justice.digital.hmpps.hmppsintegrationapi.services

import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.stereotype.Component
import software.amazon.awssdk.services.sqs.model.SendMessageRequest
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.exception.MessageFailedException
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps.ExpressionOfInterest
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps.ExpressionOfInterestMessage
import uk.gov.justice.hmpps.sqs.HmppsQueue
import uk.gov.justice.hmpps.sqs.HmppsQueueService
import java.util.UUID

@Component
class PutExpressionInterestService(
private val hmppsQueueService: HmppsQueueService,
private val objectMapper: ObjectMapper,
) {
private val eoiQueue by lazy { hmppsQueueService.findByQueueId("eoi-queue") as HmppsQueue }
private val eoiQueueSqsClient by lazy { eoiQueue.sqsClient }
private val eoiQueueUrl by lazy { eoiQueue.queueUrl }

fun sendExpressionOfInterest(expressionOfInterest: ExpressionOfInterest) {
try {
val messageBody =
objectMapper.writeValueAsString(
ExpressionOfInterestMessage(
messageId = UUID.randomUUID().toString(),
jobId = expressionOfInterest.jobId,
prisonNumber = expressionOfInterest.prisonNumber,
),
)

eoiQueueSqsClient.sendMessage(
SendMessageRequest
.builder()
.queueUrl(eoiQueueUrl)
.messageBody(messageBody)
.build(),
)
} catch (e: Exception) {
throw MessageFailedException("Failed to send message to SQS")
}
}
}
1 change: 1 addition & 0 deletions src/main/resources/application-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ authorisation:
- "/v1/persons/.*/plp-induction-schedule"
- "/v1/persons/.*/plp-induction-schedule/history"
- "/v1/persons/.*/plp-review-schedule"
- "/v1/persons/[^/]+/expression-of-interest/jobs/[^/]+$"
- "/v1/hmpps/id/by-nomis-number/[^/]*$"
- "/v1/hmpps/id/nomis-number/by-hmpps-id/[^/]*$"
filters:
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/application-integration-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ authorisation:
- "/v1/persons/.*/plp-induction-schedule"
- "/v1/persons/.*/plp-induction-schedule/history"
- "/v1/persons/.*/plp-review-schedule"
- "/v1/persons/.*/expression-of-interest/jobs/[^/]*$"
- "/v1/epf/person-details/.*/[^/]*$"
- "/v1/hmpps/id/nomis-number/[^/]*$"
- "/v1/hmpps/id/by-nomis-number/[^/]*$"
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/application-local-docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ authorisation:
- "/v1/persons/.*/plp-induction-schedule"
- "/v1/persons/.*/plp-induction-schedule/history"
- "/v1/persons/.*/plp-review-schedule"
- "/v1/persons/.*/expression-of-interest/jobs/[^/]*$"
- "/v1/epf/person-details/.*/[^/]*$"
- "/v1/hmpps/id/nomis-number/[^/]*$"
- "/v1/hmpps/id/by-nomis-number/[^/]*$"
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/application-local.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ authorisation:
- "/v1/persons/.*/cell-location"
- "/v1/persons/.*/plp-induction-schedule"
- "/v1/persons/.*/plp-review-schedule"
- "/v1/persons/[^/]+/expression-of-interest/jobs/[^/]+$"
- "/v1/epf/person-details/.*/[^/]*$"
- "/v1/hmpps/id/nomis-number/[^/]*$"
- "/v1/hmpps/id/by-nomis-number/[^/]*$"
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/application-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ authorisation:
- "/v1/persons/.*/plp-induction-schedule"
- "/v1/persons/.*/plp-induction-schedule/history"
- "/v1/persons/.*/plp-review-schedule"
- "/v1/persons/.*/expression-of-interest/jobs/[^/]*$"
- "/v1/hmpps/id/nomis-number/[^/]*$"
- "/v1/hmpps/id/.*/nomis-number"
- "/v1/hmpps/id/by-nomis-number/[^/]*$"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package uk.gov.justice.digital.hmpps.hmppsintegrationapi.controllers.v1.person

import io.kotest.core.spec.style.DescribeSpec
import io.kotest.matchers.shouldBe
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.http.HttpStatus
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.bean.override.mockito.MockitoBean
import org.springframework.test.web.servlet.MockMvc
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.helpers.IntegrationAPIMockMvc
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps.ExpressionOfInterest
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps.NomisNumber
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps.Response
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.services.GetPersonService
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.services.PutExpressionInterestService

@WebMvcTest(controllers = [ExpressionInterestController::class])
@ActiveProfiles("test")
class ExpressionInterestControllerTest(
@Autowired var springMockMvc: MockMvc,
@MockitoBean val getPersonService: GetPersonService,
@MockitoBean val expressionOfInterestService: PutExpressionInterestService,
) : DescribeSpec({
val mockMvc = IntegrationAPIMockMvc(springMockMvc)
val basePath = "/v1/persons"
val validHmppsId = "AABCD1ABC"
val nomisId = "AABCD1ABC"
val invalidHmppsId = "INVALID_ID"
val jobId = "5678"

describe("PUT $basePath/{hmppsId}/expression-of-interest/jobs/{jobId}") {
it("should return 400 Bad Request if ENTITY_NOT_FOUND error occurs") {
val notFoundResponse =
Response<NomisNumber?>(
data = null,
errors = emptyList(),
)
whenever(getPersonService.getNomisNumber(validHmppsId)).thenReturn(notFoundResponse)

val result = mockMvc.performAuthorisedPut("$basePath/$validHmppsId/expression-of-interest/jobs/$jobId")

result.response.status.shouldBe(HttpStatus.BAD_REQUEST.value())
}

it("should return 400 if an invalid hmppsId is provided") {
val result = mockMvc.performAuthorisedPut("$basePath/$invalidHmppsId/expression-of-interest/jobs/$jobId")

result.response.status.shouldBe(HttpStatus.BAD_REQUEST.value())
}

it("should return 200 OK on successful expression of interest submission") {
val validNomisResponse =
Response<NomisNumber?>(
data = NomisNumber(nomisId),
errors = emptyList(),
)
whenever(getPersonService.getNomisNumber(validHmppsId)).thenReturn(validNomisResponse)

val result = mockMvc.performAuthorisedPut("$basePath/$validHmppsId/expression-of-interest/jobs/$jobId")

verify(expressionOfInterestService).sendExpressionOfInterest(ExpressionOfInterest(jobId, nomisId))
result.response.status.shouldBe(HttpStatus.OK.value())
}

it("should return 400 Bad Request if an exception occurs") {
whenever(getPersonService.getNomisNumber(validHmppsId)).thenThrow(RuntimeException("Unexpected error"))

val result = mockMvc.performAuthorisedPut("$basePath/$validHmppsId/expression-of-interest/jobs/$jobId")

result.response.status.shouldBe(HttpStatus.BAD_REQUEST.value())
}
}
})
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ class IntegrationAPIMockMvc(
return mockMvc.perform(MockMvcRequestBuilders.get(path).header("subject-distinguished-name", subjectDistinguishedName)).andReturn()
}

fun performAuthorisedPut(path: String): MvcResult {
val subjectDistinguishedName = "C=GB,ST=London,L=London,O=Home Office,CN=automated-test-client"
return mockMvc.perform(MockMvcRequestBuilders.put(path).header("subject-distinguished-name", subjectDistinguishedName)).andReturn()
}

fun performAuthorisedWithCN(
path: String,
cn: String,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package uk.gov.justice.digital.hmpps.hmppsintegrationapi.services

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.DescribeSpec
import io.kotest.matchers.shouldBe
import org.mockito.kotlin.any
import org.mockito.kotlin.argThat
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.reset
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import software.amazon.awssdk.services.sqs.SqsAsyncClient
import software.amazon.awssdk.services.sqs.model.SendMessageRequest
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.exception.MessageFailedException
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.extensions.MockMvcExtensions.objectMapper
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps.ExpressionOfInterest
import uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps.ExpressionOfInterestMessage
import uk.gov.justice.hmpps.sqs.HmppsQueue
import uk.gov.justice.hmpps.sqs.HmppsQueueService
import kotlin.test.assertEquals

class PutExpressionInterestServiceTest :
DescribeSpec({
val mockQueueService = mock<HmppsQueueService>()
val mockSqsClient = mock<SqsAsyncClient>()
val mockObjectMapper = mock<ObjectMapper>()

val eoiQueue =
mock<HmppsQueue> {
on { sqsClient } doReturn mockSqsClient
on { queueUrl } doReturn "https://test-queue-url"
}

val service = PutExpressionInterestService(mockQueueService, mockObjectMapper)

beforeTest {
reset(mockQueueService, mockSqsClient, mockObjectMapper)
whenever(mockQueueService.findByQueueId("eoi-queue")).thenReturn(eoiQueue)
}

describe("sendExpressionOfInterest") {
it("should send a valid message successfully to SQS") {
val expressionOfInterest = ExpressionOfInterest(jobId = "12345", prisonNumber = "H1234")
val expectedMessage =
ExpressionOfInterestMessage(
messageId = "1",
jobId = "12345",
prisonNumber = "H1234",
)
val messageBody = objectMapper.writeValueAsString(expectedMessage)

whenever(mockObjectMapper.writeValueAsString(any<ExpressionOfInterestMessage>()))
.thenReturn(messageBody)

service.sendExpressionOfInterest(expressionOfInterest)

verify(mockSqsClient).sendMessage(
argThat<SendMessageRequest> { request: SendMessageRequest? ->
(
request?.queueUrl() == "https://test-queue-url" &&
request.messageBody() == messageBody
)
},
)
}

it("should throw MessageFailedException when SQS fails") {
val expressionInterest = ExpressionOfInterest(jobId = "12345", prisonNumber = "H1234")

whenever(mockSqsClient.sendMessage(any<SendMessageRequest>()))
.thenThrow(RuntimeException("Failed to send message to SQS"))

val exception =
shouldThrow<MessageFailedException> {
service.sendExpressionOfInterest(expressionInterest)
}

exception.message shouldBe "Failed to send message to SQS"
}

it("should serialize ExpressionOfInterestMessage with correct keys") {
val expectedMessage =
ExpressionOfInterestMessage(
messageId = "1",
jobId = "12345",
prisonNumber = "H1234",
)

val serializedJson = objectMapper.writeValueAsString(expectedMessage)

val deserializedMap: Map<String, Any?> = objectMapper.readValue(serializedJson)
val eventType = deserializedMap["eventType"]

assert(deserializedMap.containsKey("messageId"))
assert(deserializedMap.containsKey("jobId"))
assert(deserializedMap.containsKey("prisonNumber"))
assert(deserializedMap.containsKey("eventType"))
assertEquals(
expected = ExpressionOfInterestMessage.EventType.EXPRESSION_OF_INTEREST_MESSAGE_CREATED.name,
actual = eventType,
)
}
}
})
Loading