diff --git a/build.gradle b/build.gradle index f5f327a81..b95193338 100644 --- a/build.gradle +++ b/build.gradle @@ -17,11 +17,11 @@ buildscript { plugins { id 'org.springframework.boot' version "${springBootVersion}" id "org.flywaydb.flyway" version "${flywayVersion}" - id 'org.owasp.dependencycheck' version '9.2.0' + id 'org.owasp.dependencycheck' version '10.0.3' id 'checkstyle' id 'pmd' id 'com.github.ben-manes.versions' version '0.51.0' - id 'org.sonarqube' version '5.0.0.4638' + id 'org.sonarqube' version '5.1.0.4882' } apply plugin: 'java' apply plugin: 'eclipse' @@ -137,14 +137,14 @@ dependencies { testImplementation 'org.apache.httpcomponents.client5:httpclient5:5.3.1' //testImplementation 'org.apache.httpcomponents:httpclient:4.5.13' - testImplementation 'net.javacrumbs.json-unit:json-unit-fluent:3.3.0' - testImplementation('org.assertj:assertj-core:3.26.0') + testImplementation 'net.javacrumbs.json-unit:json-unit-fluent:3.4.1' + testImplementation('org.assertj:assertj-core:3.26.3') testImplementation 'org.mockito:mockito-core:5.12.0' testImplementation('org.projectlombok:lombok') testAnnotationProcessor('org.projectlombok:lombok') - testImplementation('net.bytebuddy:byte-buddy:1.14.17') + testImplementation('net.bytebuddy:byte-buddy:1.14.19') testImplementation('junit:junit:4.13.2') testImplementation "org.testcontainers:testcontainers:1.19.8" testImplementation "org.testcontainers:junit-jupiter:1.19.8" @@ -239,7 +239,7 @@ processResources.finalizedBy(copyDocs) wrapper { - gradleVersion = '8.8' + gradleVersion = '8.10' } sourceSets { @@ -287,7 +287,7 @@ pmdTest { maxFailures = 294 } pmdMain { - maxFailures = 780 + maxFailures = 776 } pmd { maxFailures = 0 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e6441136f..a4b76b953 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 6f7a6eb33..66cd5a0e4 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-all.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew index b740cf133..f5feea6d6 100755 --- a/gradlew +++ b/gradlew @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -84,7 +86,8 @@ done # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum diff --git a/gradlew.bat b/gradlew.bat index 7101f8e46..9b42019c7 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,6 +13,8 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## diff --git a/infrastructure/.terraform-version b/infrastructure/.terraform-version index f8e233b27..d615fd0c0 100644 --- a/infrastructure/.terraform-version +++ b/infrastructure/.terraform-version @@ -1 +1 @@ -1.9.0 +1.9.4 diff --git a/infrastructure/state.tf b/infrastructure/state.tf index 6d6e20f8f..ccbf18b7a 100644 --- a/infrastructure/state.tf +++ b/infrastructure/state.tf @@ -4,7 +4,7 @@ terraform { required_providers { azurerm = { source = "hashicorp/azurerm" - version = "3.110" + version = "3.116" } } } diff --git a/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/BureauEndpointControllerTest.java b/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/BureauEndpointControllerTest.java index 5af1c4483..de3d8a4ca 100644 --- a/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/BureauEndpointControllerTest.java +++ b/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/BureauEndpointControllerTest.java @@ -172,11 +172,7 @@ public void updateResponseStatus_happy_closed() throws Exception { final URI uri = URI.create("/api/v1/bureau/status/644892530"); - final String bureauJwt = mintBureauJwt(BureauJwtPayload.builder() - .userLevel("99") - .login("testlogin") - .owner(JurorDigitalApplication.JUROR_OWNER) - .build()); + final String bureauJwt = createJwtBureau("testlogin"); // assert db state before merge. assertThat(jdbcTemplate.queryForObject("SELECT count(*) FROM juror_mod.juror", Integer.class)).isEqualTo(1); @@ -256,11 +252,7 @@ public void updateResponseStatus_unhappy_optimisticLockingMismatch() throws Exce final URI uri = URI.create("/api/v1/bureau/status/644892530"); - final String bureauJwt = mintBureauJwt(BureauJwtPayload.builder() - .userLevel("99") - .login("testlogin") - .owner(JurorDigitalApplication.JUROR_OWNER) - .build()); + final String bureauJwt = createJwtBureau("testlogin"); // assert db state before merge. assertThat(jdbcTemplate.queryForObject("SELECT count(*) FROM juror_mod.juror", Integer.class)).isEqualTo(1); diff --git a/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/CourtCatchmentControllerTest.java b/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/CourtCatchmentControllerTest.java index 12f793ab7..8d9f5f522 100644 --- a/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/CourtCatchmentControllerTest.java +++ b/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/CourtCatchmentControllerTest.java @@ -20,7 +20,6 @@ import uk.gov.hmcts.juror.api.AbstractIntegrationTest; import uk.gov.hmcts.juror.api.SpringBootErrorResponse; import uk.gov.hmcts.juror.api.bureau.controller.response.CourtCatchmentStatusDto; -import uk.gov.hmcts.juror.api.config.bureau.BureauJwtPayload; import java.net.URI; import java.util.Collections; @@ -55,11 +54,7 @@ void setUp() throws Exception { @Sql("/db/standing_data.sql") @Sql("/db/BureauResponseCourtCatchmentController.sql") void courtCatchmentChanged() throws Exception { - final String bureauJwt = mintBureauJwt(BureauJwtPayload.builder() - .userLevel("99") - .login("ncrawford") - .owner("400") - .build()); + final String bureauJwt = createJwtBureau("ncrawford"); httpHeaders.set(HttpHeaders.AUTHORIZATION, bureauJwt); @@ -93,11 +88,7 @@ void courtCatchmentChanged() throws Exception { @Sql("/db/standing_data.sql") @Sql("/db/BureauResponseCourtCatchmentController.sql") void courtCatchmentUnchanged() throws Exception { - final String bureauJwt = mintBureauJwt(BureauJwtPayload.builder() - .userLevel("99") - .login("ncrawford") - .owner("400") - .build()); + final String bureauJwt = createJwtBureau("ncrawford"); httpHeaders.set(HttpHeaders.AUTHORIZATION, bureauJwt); @@ -130,11 +121,7 @@ void courtCatchmentUnchanged() throws Exception { @Sql("/db/standing_data.sql") @Sql("/db/BureauResponseCourtCatchmentController_Unhappy.sql") void courtCatchmentLocCodeNotFoundUnhappy() throws Exception { - final String bureauJwt = mintBureauJwt(BureauJwtPayload.builder() - .userLevel("99") - .login("ncrawford") - .owner("400") - .build()); + final String bureauJwt = createJwtBureau("ncrawford"); httpHeaders.set(HttpHeaders.AUTHORIZATION, bureauJwt); diff --git a/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/ResponseDisqualifyControllerTest.java b/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/ResponseDisqualifyControllerTest.java index 8a2f61a40..15c21b8c4 100644 --- a/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/ResponseDisqualifyControllerTest.java +++ b/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/ResponseDisqualifyControllerTest.java @@ -22,7 +22,6 @@ import uk.gov.hmcts.juror.api.bureau.controller.ResponseDisqualifyController.DisqualifyReasonsDto; import uk.gov.hmcts.juror.api.bureau.domain.DisCode; import uk.gov.hmcts.juror.api.bureau.domain.IPoolStatus; -import uk.gov.hmcts.juror.api.config.bureau.BureauJwtPayload; import uk.gov.hmcts.juror.api.moj.domain.DisqualifiedCode; import java.net.URI; @@ -57,12 +56,7 @@ public void setUp() throws Exception { @SuppressWarnings("PMD.JUnitAssertionsShouldIncludeMessage")//False positive public void testGDisqualifyReasons_happy() { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); ResponseEntity responseEntity = template.exchange(new RequestEntity(httpHeaders, HttpMethod.GET, URI.create("/api/v1/bureau/juror/disqualify")), DisqualifyReasonsDto.class); @@ -90,12 +84,7 @@ public void testGDisqualifyReasons_happy() { }) public void disqualifyJuror_happy() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); DisqualifiedCode disqualifyCodeEntity = new DisqualifiedCode("B", "On Bail", true); DisqualifyCodeDto disqualifyDto = @@ -213,12 +202,7 @@ public void disqualifyJuror_happy() throws Exception { }) public void disqualifyJuror_happy_ageDisqualification() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); DisqualifiedCode disqualifyCodeEntity = new DisqualifiedCode("A", "Less Than Eighteen Years of Age or" + " Over 70", true); @@ -305,12 +289,7 @@ public void disqualifyJuror_happy_ageDisqualification() throws Exception { }) public void disqualifyJuror_unhappy_invalidDisqualifyCode() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); DisqualifiedCode disqualifyCodeEntity = new DisqualifiedCode("Z", "Zinvalid code", true); DisqualifyCodeDto disqualifyDto = new DisqualifyCodeDto(disqualifyCodeEntity); @@ -391,12 +370,7 @@ public void disqualifyJuror_unhappy_invalidDisqualifyCode() throws Exception { }) public void disqualifyJuror_unhappy_jurorNotFound() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); DisqualifiedCode disqualifyCodeEntity = new DisqualifiedCode("B", "On Bail", true); DisqualifyCodeDto disqualifyDto = new DisqualifyCodeDto(disqualifyCodeEntity); @@ -471,12 +445,7 @@ public void disqualifyJuror_unhappy_jurorNotFound() throws Exception { }) public void disqualifyJuror_unhappy_incorrectVersion() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION,createJwtBureau(loginName)); DisqualifiedCode disqualifyCodeEntity = new DisqualifiedCode("B", "On Bail", true); DisqualifyCodeDto disqualifyDto = new DisqualifyCodeDto(disqualifyCodeEntity); @@ -551,12 +520,7 @@ public void disqualifyJuror_unhappy_incorrectVersion() throws Exception { }) public void disqualifyJuror_unhappy_nullVersion() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); DisqualifiedCode disqualifyCodeEntity = new DisqualifiedCode("B", "On Bail", true); DisqualifyCodeDto disqualifyDto = new DisqualifyCodeDto(disqualifyCodeEntity); diff --git a/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/ResponseExcusalControllerTest.java b/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/ResponseExcusalControllerTest.java index b778dc9a7..ebcb3f71e 100644 --- a/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/ResponseExcusalControllerTest.java +++ b/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/ResponseExcusalControllerTest.java @@ -21,7 +21,6 @@ import uk.gov.hmcts.juror.api.bureau.controller.ResponseExcusalController.ExcusalCodeDto; import uk.gov.hmcts.juror.api.bureau.controller.ResponseExcusalController.ExcusalReasonsDto; import uk.gov.hmcts.juror.api.bureau.domain.IPoolStatus; -import uk.gov.hmcts.juror.api.config.bureau.BureauJwtPayload; import uk.gov.hmcts.juror.api.moj.enumeration.ExcusalCodeEnum; import java.net.URI; @@ -57,12 +56,7 @@ public void setUp() throws Exception { @Sql("/db/standing_data.sql") public void testGExcusalReasons_happy() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); ResponseEntity responseEntity = template.exchange(new RequestEntity(httpHeaders, HttpMethod.GET, URI.create("/api/v1/bureau/juror/excuse")), ExcusalReasonsDto.class); @@ -88,12 +82,7 @@ public void testGExcusalReasons_happy() throws Exception { }) public void excuseJuror_happy() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); ExcusalCodeDto excusalDto = new ExcusalCodeDto(ExcusalCodeEnum.B); excusalDto.setVersion(555); @@ -215,12 +204,7 @@ public void excuseJuror_happy() throws Exception { }) public void excuseJuror_happy_deceasedExcusal() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); ExcusalCodeDto excusalDto = new ExcusalCodeDto(ExcusalCodeEnum.D); excusalDto.setVersion(555); @@ -335,12 +319,7 @@ public void excuseJuror_happy_deceasedExcusal() throws Exception { }) public void excuseJuror_unhappy_invalidExcusalCode() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); ExcusalCodeDto excusalDto = new ExcusalCodeDto(555, "ZINVALID", "Invalid Excusal"); @@ -426,12 +405,7 @@ public void excuseJuror_unhappy_invalidExcusalCode() throws Exception { }) public void excuseJuror_unhappy_JurorNotFound() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); ExcusalCodeDto excusalDto = new ExcusalCodeDto(ExcusalCodeEnum.B); excusalDto.setVersion(555); @@ -482,12 +456,7 @@ public void excuseJuror_unhappy_JurorNotFound() throws Exception { }) public void excuseJuror_unhappy_incorrectVersion() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); ExcusalCodeDto excusalDto = new ExcusalCodeDto(ExcusalCodeEnum.B); excusalDto.setVersion(554); @@ -566,12 +535,7 @@ public void excuseJuror_unhappy_incorrectVersion() throws Exception { }) public void excuseJuror_unhappy_nullVersion() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); ExcusalCodeDto excusalDto = new ExcusalCodeDto(ExcusalCodeEnum.B); excusalDto.setVersion(null); @@ -650,12 +614,7 @@ public void excuseJuror_unhappy_nullVersion() throws Exception { }) public void rejectExcusalRequest_happy() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); ExcusalCodeDto excusalDto = new ExcusalCodeDto(ExcusalCodeEnum.B); excusalDto.setVersion(555); @@ -786,12 +745,7 @@ public void rejectExcusalRequest_happy() throws Exception { }) public void rejectExcusalRequest_unhappy_invalidExcusalCode() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); ExcusalCodeDto excusalDto = new ExcusalCodeDto(ExcusalCodeEnum.B); @@ -856,12 +810,7 @@ public void rejectExcusalRequest_unhappy_invalidExcusalCode() throws Exception { }) public void rejectExcusalRequest_unhappy_JurorNotFound() throws Exception { final String loginName = "testlogin"; - httpHeaders.set(HttpHeaders.AUTHORIZATION, mintBureauJwt(BureauJwtPayload.builder() - .userLevel("1") - .login(loginName) - .owner("400") - .build()) - ); + httpHeaders.set(HttpHeaders.AUTHORIZATION, createJwtBureau(loginName)); ExcusalCodeDto excusalDto = new ExcusalCodeDto(ExcusalCodeEnum.B); excusalDto.setVersion(555); diff --git a/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/ResponseUpdateControllerTest.java b/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/ResponseUpdateControllerTest.java index ed7d11298..3066c2795 100644 --- a/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/ResponseUpdateControllerTest.java +++ b/src/integration-test/java/uk/gov/hmcts/juror/api/bureau/controller/ResponseUpdateControllerTest.java @@ -28,6 +28,7 @@ import uk.gov.hmcts.juror.api.bureau.service.ResponseUpdateServiceImpl.CjsEmployment; import uk.gov.hmcts.juror.api.config.bureau.BureauJwtPayload; import uk.gov.hmcts.juror.api.juror.domain.ProcessingStatus; +import uk.gov.hmcts.juror.api.moj.exception.MojException; import java.net.URI; import java.time.LocalDate; @@ -94,7 +95,7 @@ public void jurorNoteByJurorNumber_unhappyNonExistentJuror() throws Exception { assertThat(responseEntity.getStatusCodeValue()).isEqualTo(HttpStatus.NOT_FOUND.value()); assertThat(responseEntity.getBody()).isNotNull(); assertThat(responseEntity.getBody().getException()).as("Error is correct") - .isEqualTo(ResponseNotesService.NoteNotFoundException.class.getTypeName()); + .isEqualTo(MojException.NotFound.class.getTypeName()); } @Test @@ -103,10 +104,7 @@ public void jurorNoteByJurorNumber_unhappyNonExistentJuror() throws Exception { public void updateNoteByJurorNumber_happy() throws Exception { final String loginName = "testlogin"; - final String bureauJwt = mintBureauJwt( - BureauJwtPayload.builder().userLevel("5").login(loginName) - .owner("400").staff(BureauJwtPayload.Staff.builder().active(1).rank(1).name(loginName) - .courts(Collections.singletonList("123")).build()).build()); + final String bureauJwt = createJwtBureau(loginName); // assert db state before merge. assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM juror_mod.juror", Integer.class)) @@ -157,11 +155,7 @@ public void updateNoteByJurorNumber_happy() throws Exception { public void updateNoteByJurorNumber_unhappyNonExistentJuror() throws Exception { final String loginName = "testlogin"; - final String bureauJwt = mintBureauJwt( - BureauJwtPayload.builder().userLevel("5").login(loginName) - .owner("400").staff( - BureauJwtPayload.Staff.builder().active(1).rank(1).name(loginName + " Mc" + loginName) - .courts(Collections.singletonList("123")).build()).build()); + final String bureauJwt = createJwtBureau(loginName); // assert db state before merge. assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM juror_mod.juror", Integer.class)).isEqualTo(2); @@ -183,7 +177,7 @@ public void updateNoteByJurorNumber_unhappyNonExistentJuror() throws Exception { assertThat(exchange.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); assertThat(exchange.getBody().getException()).as("Error is correct") - .isEqualTo(ResponseNotesService.NoteNotFoundException.class.getTypeName()); + .isEqualTo(MojException.NotFound.class.getTypeName()); // assert the DB change was NOT applied assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM juror_mod.juror", Integer.class)) @@ -203,11 +197,7 @@ public void updateNoteByJurorNumber_unhappyNonExistentJuror() throws Exception { public void updateNoteByJurorNumber_unhappy_hashMismatch() throws Exception { final String loginName = "testlogin"; - final String bureauJwt = mintBureauJwt( - BureauJwtPayload.builder().userLevel("5").login(loginName) - .owner("400").staff( - BureauJwtPayload.Staff.builder().active(1).rank(1).name(loginName + " Mc" + loginName) - .courts(Collections.singletonList("123")).build()).build()); + final String bureauJwt = createJwtBureau(loginName); // assert db state before merge. assertThat(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM juror_mod.juror", Integer.class)).isEqualTo(2); @@ -2085,9 +2075,7 @@ public void updateResponseStatus_legacy_status_2_changed() throws Exception { final URI uri = URI.create("/api/v1/bureau/juror/644892530/response/status"); - final String bureauJwt = mintBureauJwt( - BureauJwtPayload.builder().userLevel("99").login("testlogin") - .owner(JurorDigitalApplication.JUROR_OWNER).build()); + final String bureauJwt = createJwtBureau("testlogin"); // assert db state before merge. assertThat(jdbcTemplate.queryForObject("SELECT count(*) FROM juror_mod.juror", Integer.class)).isEqualTo(2); @@ -2147,9 +2135,7 @@ public void updateResponseStatus_legacy_status_11_changed() throws Exception { final URI uri = URI.create("/api/v1/bureau/juror/644892530/response/status"); - final String bureauJwt = mintBureauJwt( - BureauJwtPayload.builder().userLevel("99").login("testlogin") - .owner(JurorDigitalApplication.JUROR_OWNER).build()); + final String bureauJwt = createJwtBureau("testlogin"); // assert db state before merge. assertThat(jdbcTemplate.queryForObject("SELECT count(*) FROM juror_mod.juror", Integer.class)).isEqualTo(2); diff --git a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/AuditControllerITest.java b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/AuditControllerITest.java index 21110739d..e1fadbcd3 100644 --- a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/AuditControllerITest.java +++ b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/AuditControllerITest.java @@ -97,7 +97,6 @@ void negativeInvalidDateFormat() { testBuilder() .url(toUrl("INVALID")) .triggerInvalid() - .printResponse() .assertInvalidPathParam("INVALID is the incorrect data type or is not in the expected format (date)"); } } diff --git a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/JurorRecordControllerITest.java b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/JurorRecordControllerITest.java index e7bf5d555..c0b09b444 100644 --- a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/JurorRecordControllerITest.java +++ b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/JurorRecordControllerITest.java @@ -863,7 +863,6 @@ void testGJurorDetailsBureauUser() { assertThat(response.getStatusCode()) .as("Expect the HTTP GET request to be successful") .isEqualTo(HttpStatus.OK); - JurorDetailsResponseDto jurorDetails = response.getBody(); assertThat(jurorDetails).isNotNull(); diff --git a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/JurorResponseControllerITest.java b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/JurorResponseControllerITest.java index 501cec65b..1b29915d7 100644 --- a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/JurorResponseControllerITest.java +++ b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/JurorResponseControllerITest.java @@ -52,7 +52,6 @@ import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseCjsEmploymentRepositoryMod; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseCommonRepositoryMod; import uk.gov.hmcts.juror.api.moj.utils.DataUtils; -import uk.gov.hmcts.juror.api.moj.utils.JurorPoolUtils; import java.net.URI; import java.time.LocalDate; @@ -1013,7 +1012,8 @@ private void validateUpdatedDigitalResponsePersonalDetails(String jurorNumber, private void validateAgeDisqualificationMergedJurorRecord(String jurorNumber, ReplyMethod replyMethod, int statusCode) { AbstractJurorResponse jurorResponse = createGenericJurorResponse(replyMethod, jurorNumber); - JurorPool jurorPool = JurorPoolUtils.getLatestActiveJurorPoolRecord(jurorPoolRepository, jurorNumber); + JurorPool jurorPool = + jurorPoolRepository.findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(jurorNumber, true).get(0); Juror juror = jurorPool.getJuror(); assertThat(juror.getPendingTitle()).isEqualToIgnoringCase(jurorResponse.getTitle()); @@ -1046,7 +1046,8 @@ private AbstractJurorResponse createGenericJurorResponse(ReplyMethod replyMethod } private void verifyAgeDisqualification(String jurorNumber) { - JurorPool jurorPool = JurorPoolUtils.getLatestActiveJurorPoolRecord(jurorPoolRepository, jurorNumber); + JurorPool jurorPool = + jurorPoolRepository.findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(jurorNumber, true).get(0); Juror juror = jurorPool.getJuror(); assertThat(juror.isResponded()).as("Juror record should be updated and marked as responded").isTrue(); @@ -1078,7 +1079,8 @@ private void verifyAgeDisqualification(String jurorNumber) { private void verifyStraightThroughAgeDisqualificationNotProcessed(String jurorNumber, ReplyMethod replyMethod, int statusCode) { AbstractJurorResponse jurorResponse = createGenericJurorResponse(replyMethod, jurorNumber); - JurorPool jurorPool = JurorPoolUtils.getLatestActiveJurorPoolRecord(jurorPoolRepository, jurorNumber); + JurorPool jurorPool = + jurorPoolRepository.findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(jurorNumber, true).get(0); final Juror juror = jurorPool.getJuror(); assertThat(jurorResponse.getProcessingComplete()) diff --git a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/MessagingControllerITest.java b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/MessagingControllerITest.java index e50aaa97b..3bed24456 100644 --- a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/MessagingControllerITest.java +++ b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/MessagingControllerITest.java @@ -706,7 +706,7 @@ protected Positive() { addTest(MessageType.REMIND_TO_ATTEND, "Reminder: Please attend for your Jury Service at Court on at " + ". If you have any questions, please contact the jury office on .", - "Nodyn Atgoffa: Cofiwch fynychu eich Gwasanaeth Rheithgor yn Llys ar " + "Nodyn Atgoffa: Cofiwch fynychu eich Gwasanaeth Rheithgor yn Llys ar " + " am . Os oes gennych unrhyw gwestiynau, cysylltwch â'r swyddfa " + "rheithgor drwy ffonio .", List.of( @@ -728,7 +728,7 @@ protected Positive() { addTest(MessageType.FAILED_TO_ATTEND_COURT, "You failed to attend for Jury Service at Court on . Please contact the" + " jury office on .", - "Bu ichi fethu â mynychu eich Gwasanaeth Rheithgor yn Llys ar . " + "Bu ichi fethu â mynychu eich Gwasanaeth Rheithgor yn Llys ar . " + "Cysylltwch â'r Swyddfa Rheithgor drwy ffonio .", List.of( TestData.Placeholder.ENGLISH_COURT_NAME.toPlaceholder(), @@ -748,7 +748,7 @@ protected Positive() { + "service and will not be added on at the end. If you have any questions, please contact the" + " jury office on .", "Mae dyddiad mynychu eich Gwasanaeth Rheithgor wedi newid i am yn " - + "Llys. Mae'r dyddiau pan na fydd eich angen yn y llys dal yn ffurfio rhan " + + "Llys . Mae'r dyddiau pan na fydd eich angen yn y llys dal yn ffurfio rhan " + "o'ch gwasanaeth rheithgor ac ni fyddant yn cael eu hychwanegu ar y diwedd. Os oes gennych " + "unrhyw gwestiynau, cysylltwch â'r swyddfa rheithgor drwy ffonio .", List.of( @@ -814,7 +814,7 @@ protected Positive() { + " Court. If you have any questions, please contact the jury office on " + ".", "Mae angen i chi fynychu'r llys eto ar gyfer eich Gwasanaeth Rheithgor ar am " - + " yn Llys. Os oes gennych unrhyw gwestiynau, cysylltwch â'r " + + " yn Llys . Os oes gennych unrhyw gwestiynau, cysylltwch â'r " + "swyddfa rheithgor drwy ffonio .", List.of( TestData.Placeholder.ATTEND_DATE.toPlaceholder(), @@ -850,7 +850,7 @@ protected Positive() { addTest(MessageType.PLEASE_CONTACT_COURT, "Please contact Jury Office on with regard to your jury service.", - "Cysylltwch â Swyddfa Rheithgor drwy ffonio ynghylch eich " + "Cysylltwch â Swyddfa Rheithgor drwy ffonio ynghylch eich " + "gwasanaeth rheithgor.", List.of( TestData.Placeholder.ENGLISH_COURT_NAME.toPlaceholder(), @@ -887,7 +887,7 @@ protected Positive() { + " Court on at . If you have any questions, please " + "contact the jury office on .", "Rydych wedi cael eich dewis i fod yn rhan o banel a bydd Rheithgor yn cael ei ddewis o blith y " - + "panel hwnnw. Ewch i Lys ar am . Os oes gennych" + + "panel hwnnw. Ewch i Lys ar am . Os oes gennych" + " unrhyw gwestiynau, cysylltwch â'r swyddfa rheithgor drwy ffonio .", List.of( TestData.Placeholder.ENGLISH_COURT_NAME.toPlaceholder(), @@ -1834,7 +1834,7 @@ protected Positive() { + "05:00. If you have any questions, please contact the jury office on 01244 356726.", "Reminder: Please attend for your Jury Service at CARMARTHEN Court on 01/01/2023 at " + "05:00. If you have any questions, please contact the jury office on 01792 637000.", - "Nodyn Atgoffa: Cofiwch fynychu eich Gwasanaeth Rheithgor yn LlysCAERFYRDDIN ar 01/01/2023" + "Nodyn Atgoffa: Cofiwch fynychu eich Gwasanaeth Rheithgor yn Llys CAERFYRDDIN ar 01/01/2023" + " am 05:00. Os oes gennych unrhyw gwestiynau, cysylltwch â'r swyddfa rheithgor drwy" + " ffonio 01792 637000.", Map.of( @@ -1852,7 +1852,7 @@ protected Positive() { + "the jury office on 01244 356726.", "You failed to attend for Jury Service at CARMARTHEN Court on 01/01/2023. Please contact " + "the jury office on 01792 637000.", - "Bu ichi fethu â mynychu eich Gwasanaeth Rheithgor yn LlysCAERFYRDDIN ar 01/01/2023. " + "Bu ichi fethu â mynychu eich Gwasanaeth Rheithgor yn Llys CAERFYRDDIN ar 01/01/2023. " + "Cysylltwch â'r Swyddfa Rheithgor drwy ffonio 01792 637000.", Map.of( "", "2023-01-01" @@ -1873,7 +1873,7 @@ protected Positive() { + "service and will not be added on at the end. If you have any questions, please contact the" + " jury office on 01792 637000.", "Mae dyddiad mynychu eich Gwasanaeth Rheithgor wedi newid i 01/01/2023 am 05:00 yn " - + "LlysCAERFYRDDIN. Mae'r dyddiau pan na fydd eich angen yn y llys dal yn ffurfio rhan o'ch " + + "Llys CAERFYRDDIN. Mae'r dyddiau pan na fydd eich angen yn y llys dal yn ffurfio rhan o'ch " + "gwasanaeth rheithgor ac ni fyddant yn cael eu hychwanegu ar y diwedd. Os oes gennych unrhyw " + "gwestiynau, cysylltwch â'r swyddfa rheithgor drwy ffonio 01792 637000.", Map.of( @@ -1940,7 +1940,7 @@ protected Positive() { "You are next required to attend for Jury Service on 03/01/2023 at 08:00 at CARMARTHEN " + "Court. If you have any questions, please contact the jury office on 01792 637000.", "Mae angen i chi fynychu'r llys eto ar gyfer eich Gwasanaeth Rheithgor ar 03/01/2023 " - + "am 08:00 yn LlysCAERFYRDDIN. Os oes gennych unrhyw gwestiynau, cysylltwch â'r swyddfa " + + "am 08:00 yn Llys CAERFYRDDIN. Os oes gennych unrhyw gwestiynau, cysylltwch â'r swyddfa " + "rheithgor drwy ffonio 01792 637000.", Map.of( "", "2023-01-03", @@ -1975,7 +1975,7 @@ protected Positive() { MessageType.PLEASE_CONTACT_COURT, "Please contact WARRINGTON Jury Office on 01244 356726 with regard to your jury service.", "Please contact CARMARTHEN Jury Office on 01792 637000 with regard to your jury service.", - "Cysylltwch â Swyddfa RheithgorCAERFYRDDIN drwy ffonio 01792 637000 ynghylch eich gwasanaeth " + "Cysylltwch â Swyddfa Rheithgor CAERFYRDDIN drwy ffonio 01792 637000 ynghylch eich gwasanaeth " + "rheithgor.", Map.of(), "Please contact", @@ -2015,7 +2015,7 @@ protected Positive() { + "CARMARTHEN Court on 02/01/2023 at 15:30. If you have any questions, please " + "contact the jury office on 01792 637000.", "Rydych wedi cael eich dewis i fod yn rhan o banel a bydd Rheithgor yn cael ei ddewis o blith y " - + "panel hwnnw. Ewch i LysCAERFYRDDIN ar 02/01/2023 am 15:30. Os oes gennych unrhyw " + + "panel hwnnw. Ewch i Lys CAERFYRDDIN ar 02/01/2023 am 15:30. Os oes gennych unrhyw " + "gwestiynau, cysylltwch â'r swyddfa rheithgor drwy ffonio 01792 637000.", Map.of( "", "2023-01-02", @@ -2995,7 +2995,7 @@ protected Positive() { + "05:00. If you have any questions, please contact the jury office on 01244 356726.", "Reminder: Please attend for your Jury Service at CARMARTHEN Court on 01/01/2023 at " + "05:00. If you have any questions, please contact the jury office on 01792 637000.", - "Nodyn Atgoffa: Cofiwch fynychu eich Gwasanaeth Rheithgor yn LlysCAERFYRDDIN ar 01/01/2023" + "Nodyn Atgoffa: Cofiwch fynychu eich Gwasanaeth Rheithgor yn Llys CAERFYRDDIN ar 01/01/2023" + " am 05:00. Os oes gennych unrhyw gwestiynau, cysylltwch â'r swyddfa rheithgor drwy" + " ffonio 01792 637000.", Map.of( @@ -3010,7 +3010,7 @@ protected Positive() { + "the jury office on 01244 356726.", "You failed to attend for Jury Service at CARMARTHEN Court on 01/01/2023. Please contact " + "the jury office on 01792 637000.", - "Bu ichi fethu â mynychu eich Gwasanaeth Rheithgor yn LlysCAERFYRDDIN ar 01/01/2023. " + "Bu ichi fethu â mynychu eich Gwasanaeth Rheithgor yn Llys CAERFYRDDIN ar 01/01/2023. " + "Cysylltwch â'r Swyddfa Rheithgor drwy ffonio 01792 637000.", Map.of( "", "2023-01-01" @@ -3028,7 +3028,7 @@ protected Positive() { + "service and will not be added on at the end. If you have any questions, please contact the" + " jury office on 01792 637000.", "Mae dyddiad mynychu eich Gwasanaeth Rheithgor wedi newid i 01/01/2023 am 05:00 yn " - + "LlysCAERFYRDDIN. Mae'r dyddiau pan na fydd eich angen yn y llys dal yn ffurfio rhan o'ch " + + "Llys CAERFYRDDIN. Mae'r dyddiau pan na fydd eich angen yn y llys dal yn ffurfio rhan o'ch " + "gwasanaeth rheithgor ac ni fyddant yn cael eu hychwanegu ar y diwedd. Os oes gennych unrhyw " + "gwestiynau, cysylltwch â'r swyddfa rheithgor drwy ffonio 01792 637000.", Map.of( @@ -3082,7 +3082,7 @@ protected Positive() { "You are next required to attend for Jury Service on 03/01/2023 at 08:00 at CARMARTHEN " + "Court. If you have any questions, please contact the jury office on 01792 637000.", "Mae angen i chi fynychu'r llys eto ar gyfer eich Gwasanaeth Rheithgor ar 03/01/2023 " - + "am 08:00 yn LlysCAERFYRDDIN. Os oes gennych unrhyw gwestiynau, cysylltwch â'r swyddfa " + + "am 08:00 yn Llys CAERFYRDDIN. Os oes gennych unrhyw gwestiynau, cysylltwch â'r swyddfa " + "rheithgor drwy ffonio 01792 637000.", Map.of( "", "2023-01-03", @@ -3111,7 +3111,7 @@ protected Positive() { MessageType.PLEASE_CONTACT_COURT, "Please contact WARRINGTON Jury Office on 01244 356726 with regard to your jury service.", "Please contact CARMARTHEN Jury Office on 01792 637000 with regard to your jury service.", - "Cysylltwch â Swyddfa RheithgorCAERFYRDDIN drwy ffonio 01792 637000 ynghylch eich gwasanaeth " + "Cysylltwch â Swyddfa Rheithgor CAERFYRDDIN drwy ffonio 01792 637000 ynghylch eich gwasanaeth " + "rheithgor.", Map.of(), MessageType.SendType.EMAIL_AND_SMS @@ -3145,7 +3145,7 @@ protected Positive() { + "CARMARTHEN Court on 02/01/2023 at 15:30. If you have any questions, please " + "contact the jury office on 01792 637000.", "Rydych wedi cael eich dewis i fod yn rhan o banel a bydd Rheithgor yn cael ei ddewis o blith y " - + "panel hwnnw. Ewch i LysCAERFYRDDIN ar 02/01/2023 am 15:30. Os oes gennych unrhyw " + + "panel hwnnw. Ewch i Lys CAERFYRDDIN ar 02/01/2023 am 15:30. Os oes gennych unrhyw " + "gwestiynau, cysylltwch â'r swyddfa rheithgor drwy ffonio 01792 637000.", Map.of( "", "2023-01-02", diff --git a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/UserControllerITest.java b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/UserControllerITest.java index 83038a427..fb9f59201 100644 --- a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/UserControllerITest.java +++ b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/controller/UserControllerITest.java @@ -963,7 +963,7 @@ void courtManager() { .isActive(true) .lastSignIn(null) .userType(UserType.COURT) - .approvalLimit(new BigDecimal("0.00")) + .approvalLimit(null) .roles(Set.of()) .courts(List.of(UserCourtDto.builder() .primaryCourt(CourtDto.builder() @@ -1171,8 +1171,7 @@ void assertUserUpdated( assertThat(user.getEmail()).isEqualTo(oldUser.getEmail()); assertThat(user.getName()).isEqualTo(oldUser.getName()); assertThat(user.isActive()).isEqualTo(oldUser.isActive()); - assertThat(user.getApprovalLimit()).isEqualTo( - isCourtManager ? userDto.getApprovalLimit() : oldUser.getApprovalLimit()); + assertThat(user.getApprovalLimit()).isEqualTo(oldUser.getApprovalLimit()); } assertThat(user.getRoles()).isEqualTo(Optional.ofNullable(userDto.getRoles()).orElse(Set.of())); assertThat(user.getUpdatedBy()).isEqualTo(updatedBy); diff --git a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/report/grouped/CompletionOfServiceReportITest.java b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/report/grouped/CompletionOfServiceReportITest.java index e106cb9b1..845f79b25 100644 --- a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/report/grouped/CompletionOfServiceReportITest.java +++ b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/report/grouped/CompletionOfServiceReportITest.java @@ -66,7 +66,7 @@ void positiveTypicalCourt() { testBuilder() .triggerValid() .responseConsumer(this::verifyAndRemoveReportCreated) - .assertEquals(createResponse("CHESTER (415)", 7, + .assertEquals(createResponse("CHESTER (415)", 8, true)); } @@ -184,6 +184,11 @@ private GroupedTableData createMockTableData(boolean populate) { .add(LAST_NAME_KEY, "LASTNAMEFIVE") .add(COMPLETION_DATE_KEY, "2023-01-30"))) .add("416220902,CROWN COURT", List.of( + new ReportLinkedMap<>() + .add(JUROR_NUMBER_KEY, "415000004") + .add(FIRST_NAME_KEY, "FIRSTNAMEFOUR") + .add(LAST_NAME_KEY, "LASTNAMEFOUR") + .add(COMPLETION_DATE_KEY, "2023-01-30"), new ReportLinkedMap() .add(JUROR_NUMBER_KEY, "415000006") .add(FIRST_NAME_KEY, "FIRSTNAMESIX") diff --git a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/report/grouped/ExcusedAndDisqualifiedListReportITest.java b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/report/grouped/ExcusedAndDisqualifiedListReportITest.java index 209798082..7c1b857d6 100644 --- a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/report/grouped/ExcusedAndDisqualifiedListReportITest.java +++ b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/report/grouped/ExcusedAndDisqualifiedListReportITest.java @@ -123,7 +123,6 @@ void invalidUnauthorized() { testBuilder() .jwt(getCourtJwt("414")) .triggerInvalid() - .printResponse() .assertMojForbiddenResponse("User not allowed to access this pool"); } diff --git a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/report/standard/PoolAttendanceAuditReportITest.java b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/report/standard/PoolAttendanceAuditReportITest.java index 3366f1e15..d8655da3d 100644 --- a/src/integration-test/java/uk/gov/hmcts/juror/api/moj/report/standard/PoolAttendanceAuditReportITest.java +++ b/src/integration-test/java/uk/gov/hmcts/juror/api/moj/report/standard/PoolAttendanceAuditReportITest.java @@ -43,7 +43,6 @@ protected StandardReportRequest getValidPayload() { @Test void positiveTypical() { - testBuilder().triggerInvalid().printResponse(); testBuilder() .triggerValid() .responseConsumer(this::verifyAndRemoveReportCreated) diff --git a/src/integration-test/resources/db/JurorRecordController_jurorDetailThirdPartyRequestBureau.sql b/src/integration-test/resources/db/JurorRecordController_jurorDetailThirdPartyRequestBureau.sql index 234206840..41a126d27 100644 --- a/src/integration-test/resources/db/JurorRecordController_jurorDetailThirdPartyRequestBureau.sql +++ b/src/integration-test/resources/db/JurorRecordController_jurorDetailThirdPartyRequestBureau.sql @@ -25,9 +25,7 @@ VALUES NULL, 'Y', NULL, 'N', NULL, 'N', NULL, 'N', NULL, 'C', '7/6/2023, 3/7/2023, 9/8/2023', NULL, NULL, 'N', 0, 'TPFIRSTNAME', 'TPLASTNAME', 'Son of the juror', '012033223', '07878787323', 'new_email@address.com', 'Unable to read english or welsh', 'OTHER_REASON', - false, - false, - NULL, - NULL, - 'N', - NULL, 'N', 'Digital'); + false,false,NULL,NULL,'N', NULL,'N','Digital'); + +INSERT INTO juror_mod.juror_third_party (juror_number, first_name, last_name, relationship, main_phone, other_phone, email_address, reason, other_reason, contact_juror_by_phone, contact_juror_by_email) +VALUES('641600096', 'TPFIRSTNAME', 'TPLASTNAME', 'Son of the juror', '012033223', '07878787323', NULL, 'Unable to read english or welsh', NULL, false, false); diff --git a/src/integration-test/resources/db/JurorRecordController_processNameChangeApproval.sql b/src/integration-test/resources/db/JurorRecordController_processNameChangeApproval.sql index 59ee280cc..df6fe9333 100644 --- a/src/integration-test/resources/db/JurorRecordController_processNameChangeApproval.sql +++ b/src/integration-test/resources/db/JurorRecordController_processNameChangeApproval.sql @@ -21,10 +21,10 @@ VALUES ('415', '111111111', '415230701', true, 2); INSERT INTO juror_mod.rev_info (revision_number, revision_timestamp) -VALUES(0, EXTRACT (EPOCH FROM current_date)); +VALUES(1, EXTRACT (EPOCH FROM current_date)); INSERT INTO juror_mod.juror_audit (revision, juror_number, rev_type, title, first_name, last_name, dob, address_line_1, address_line_4, postcode, pending_title, pending_first_name, pending_last_name) -VALUES(0, '111111111', 1, NULL, 'FNAMEONE', 'LNAMEONE', '1989-03-31', '543 STREET NAME', 'ANYTOWN', 'CH1 2AN', 'Mr', +VALUES(1, '111111111', 1, NULL, 'FNAMEONE', 'LNAMEONE', '1989-03-31', '543 STREET NAME', 'ANYTOWN', 'CH1 2AN', 'Mr', 'Test' ,'Person'); diff --git a/src/integration-test/resources/db/mod/reports/CompletionOfServiceReportITest_typical.sql b/src/integration-test/resources/db/mod/reports/CompletionOfServiceReportITest_typical.sql index 28b6a11d7..60e6a2fa8 100644 --- a/src/integration-test/resources/db/mod/reports/CompletionOfServiceReportITest_typical.sql +++ b/src/integration-test/resources/db/mod/reports/CompletionOfServiceReportITest_typical.sql @@ -33,4 +33,6 @@ INSERT INTO juror_mod.juror_pool ("owner",juror_number,pool_number,status,is_act ('415','415000006','416220902',1,'Y','01','N'), ('415','415000007','416220902',10,'Y','01','N'), ('416','415000008','416220903',2,'Y','01','N'), - ('416','415000009','416220903',2,'Y','01','N'); \ No newline at end of file + ('416','415000009','416220903',2,'Y','01','N'), + ('415','415000004','416220902',1,'Y','01',true), + ('415','415000005','416220902',1,'N','01',false); diff --git a/src/integration-test/resources/db/notify-scenarios.sql b/src/integration-test/resources/db/notify-scenarios.sql index 8779946d1..08f11bfd4 100644 --- a/src/integration-test/resources/db/notify-scenarios.sql +++ b/src/integration-test/resources/db/notify-scenarios.sql @@ -424,45 +424,45 @@ VALUES ('641500930', 'H', 'H'), ('641500109', 'R', 'R'); -INSERT INTO juror_mod.juror_pool(juror_number, pool_number, owner, next_date) -VALUES ('641500092', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500093', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500094', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500095', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500096', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500101', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500102', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500108', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500109', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500119', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500120', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500127', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500128', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500130', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500131', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500192', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500496', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500497', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500518', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500519', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500521', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500522', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500529', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500530', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500531', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500532', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500534', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500535', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500537', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500538', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500540', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500541', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500542', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500543', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500684', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500807', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500811', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500902', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500905', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500919', '415170402', '400',to_date('02-APR-18','DD-MON-YY')), - ('641500930', '415170402', '400',to_date('02-APR-18','DD-MON-YY')); \ No newline at end of file +INSERT INTO juror_mod.juror_pool(juror_number, pool_number, owner, next_date,is_active) +VALUES ('641500092', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500093', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500094', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500095', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500096', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500101', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500102', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500108', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500109', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500119', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500120', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500127', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500128', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500130', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500131', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500192', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500496', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500497', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500518', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500519', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500521', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500522', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500529', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500530', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500531', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500532', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500534', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500535', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500537', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500538', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500540', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500541', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500542', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500543', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500684', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500807', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500811', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500902', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500905', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500919', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true), + ('641500930', '415170402', '400',to_date('02-APR-18','DD-MON-YY'), true); \ No newline at end of file diff --git a/src/main/java/uk/gov/hmcts/juror/api/bureau/service/JurorDashboardSmartSurveyImportImpl.java b/src/main/java/uk/gov/hmcts/juror/api/bureau/service/JurorDashboardSmartSurveyImportImpl.java index 3c5932ab9..2362eef5f 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/bureau/service/JurorDashboardSmartSurveyImportImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/bureau/service/JurorDashboardSmartSurveyImportImpl.java @@ -1,6 +1,6 @@ package uk.gov.hmcts.juror.api.bureau.service; -import io.jsonwebtoken.lang.Assert; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.json.JSONArray; import org.json.JSONObject; @@ -24,7 +24,6 @@ import java.net.InetSocketAddress; import java.net.Proxy; -import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.ZoneId; @@ -34,48 +33,25 @@ import java.util.Date; import java.util.HashMap; import java.util.List; -import java.util.Locale; import java.util.Map; @Configuration @Slf4j @Component +@RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class JurorDashboardSmartSurveyImportImpl implements BureauProcessService { private final AppSettingService appSetting; - //private final NotifyConfigurationProperties notifyConfigurationProperties; private final SmartSurveyConfigurationProperties smartSurveyConfigurationProperties; private final SurveyResponseRepository surveyResponseRepository; - private Proxy proxy; - private String proxyHost; - private String proxyPort; - private Proxy.Type proxyType; private Boolean proxyEnabled = false; - @Autowired - public JurorDashboardSmartSurveyImportImpl( - final AppSettingService appSetting, - //final NotifyConfigurationProperties notifyConfigurationProperties, - final SmartSurveyConfigurationProperties smartSurveyConfigurationProperties, - final SurveyResponseRepository surveyResponseRepository) { - Assert.notNull(appSetting, "appSetting cannot be null."); - //Assert.notNull(notifyConfigurationProperties, "notifyConfigurationProperties cannot be null"); - Assert.notNull(smartSurveyConfigurationProperties, "smartSurveyConfigurationProperties cannot be null"); - Assert.notNull(surveyResponseRepository, "SurveyResponseRepository cannot be null."); - - this.appSetting = appSetting; - //this.notifyConfigurationProperties = notifyConfigurationProperties; - this.smartSurveyConfigurationProperties = smartSurveyConfigurationProperties; - this.surveyResponseRepository = surveyResponseRepository; - } - /** * Implements a specific job execution. * Process retrieval of satisfaction survey responses via the smart survey rest api. */ - @Override @Transactional public SchedulerServiceClient.Result process() { @@ -95,14 +71,12 @@ public SchedulerServiceClient.Result process() { String smartSurveyToken = smartSurveyConfigurationProperties.getToken(); String smartSurveyCredentials = "?api_token={apiToken}&api_token_secret={apiTokenSecret}"; - String exportId = null; - String exportUrl = null; + String exportUrl; - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); LocalDate currentDate = LocalDate.now(); LocalDate startDate = currentDate.minusDays(surveyDays); - List surveyResponseList = new ArrayList(); + List surveyResponseList; int dbInsertCount = 0; int dbSkipCount = 0; @@ -129,6 +103,9 @@ public SchedulerServiceClient.Result process() { proxyEnabled = proxyProperties.getEnabled(); log.info("Smart Survey proxy enabled: {}", proxyEnabled); + String proxyHost; + Proxy.Type proxyType; + String proxyPort; if (proxyEnabled) { proxyHost = proxyProperties.getHost(); proxyPort = proxyProperties.getPort(); diff --git a/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseDisqualifyServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseDisqualifyServiceImpl.java index af765bae3..facfdb3af 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseDisqualifyServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseDisqualifyServiceImpl.java @@ -23,6 +23,7 @@ import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorDigitalResponseRepositoryMod; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseAuditRepositoryMod; import uk.gov.hmcts.juror.api.moj.service.JurorHistoryService; +import uk.gov.hmcts.juror.api.moj.service.JurorPoolService; import uk.gov.hmcts.juror.api.moj.service.PrintDataService; import uk.gov.hmcts.juror.api.moj.utils.RepositoryUtils; @@ -38,6 +39,7 @@ public class ResponseDisqualifyServiceImpl implements ResponseDisqualifyService private final JurorDigitalResponseRepositoryMod responseRepository; private final JurorResponseAuditRepositoryMod jurorResponseAuditRepository; private final JurorPoolRepository detailsRepository; + private final JurorPoolService jurorPoolService; private final JurorStatusRepository jurorStatusRepository; private final DisqualifiedCodeRepository disqualifyCodeRepository; private final ResponseMergeService mergeService; @@ -112,7 +114,7 @@ public boolean disqualifyJuror(String jurorId, DisqualifyCodeDto disqualifyCodeD } // update juror pool entry - JurorPool jurorDetails = detailsRepository.findByJurorJurorNumber(savedResponse.getJurorNumber()); + JurorPool jurorDetails = jurorPoolService.getJurorPoolFromUser(savedResponse.getJurorNumber()); jurorDetails.getJuror().setResponded(true); jurorDetails.getJuror().setDisqualifyDate(LocalDate.now()); jurorDetails.getJuror().setDisqualifyCode(disqualifyCodeDto.getDisqualifyCode()); diff --git a/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseExcusalServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseExcusalServiceImpl.java index 47a06ae24..265a2f8f0 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseExcusalServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseExcusalServiceImpl.java @@ -25,6 +25,7 @@ import uk.gov.hmcts.juror.api.moj.repository.JurorStatusRepository; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorDigitalResponseRepositoryMod; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseAuditRepositoryMod; +import uk.gov.hmcts.juror.api.moj.service.JurorPoolService; import uk.gov.hmcts.juror.api.moj.service.PrintDataService; import uk.gov.hmcts.juror.api.moj.utils.RepositoryUtils; @@ -49,6 +50,7 @@ public class ResponseExcusalServiceImpl implements ResponseExcusalService { private final EntityManager entityManager; private final AssignOnUpdateService assignOnUpdateService; private final PrintDataService printDataService; + private final JurorPoolService jurorPoolService; @Override @@ -119,7 +121,7 @@ public boolean excuseJuror(String jurorId, ExcusalCodeDto excusalCodeDto, String } // update juror pool entry - JurorPool poolDetails = detailsRepository.findByJurorJurorNumber(savedResponse.getJurorNumber()); + JurorPool poolDetails = jurorPoolService.getJurorPoolFromUser(savedResponse.getJurorNumber()); poolDetails.getJuror().setResponded(true); poolDetails.getJuror().setExcusalDate(LocalDate.now()); poolDetails.getJuror().setExcusalCode(excusalCodeDto.getExcusalCode()); @@ -211,7 +213,7 @@ public boolean rejectExcusalRequest(String jurorId, ExcusalCodeDto excusalCodeDt } // update juror pool entry - JurorPool poolDetails = detailsRepository.findByJurorJurorNumber(savedResponse.getJurorNumber()); + JurorPool poolDetails = jurorPoolService.getJurorPoolFromUser(savedResponse.getJurorNumber()); poolDetails.getJuror().setResponded(true); poolDetails.getJuror().setExcusalDate(LocalDate.now()); poolDetails.getJuror().setExcusalCode(excusalCodeDto.getExcusalCode()); diff --git a/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseNotesService.java b/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseNotesService.java index 1cea73671..f5ed3619a 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseNotesService.java +++ b/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseNotesService.java @@ -22,13 +22,6 @@ public interface ResponseNotesService { */ void updateNote(ResponseUpdateController.JurorNoteDto noteDto, String jurorId, String auditUser); - @ResponseStatus(HttpStatus.NOT_FOUND) - class NoteNotFoundException extends RuntimeException { - public NoteNotFoundException(String message) { - super(message); - } - } - @ResponseStatus(HttpStatus.CONFLICT) class NoteComparisonFailureException extends RuntimeException { public NoteComparisonFailureException() { diff --git a/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdateServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdateServiceImpl.java index fc88c8ff6..53404f833 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdateServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdateServiceImpl.java @@ -27,9 +27,9 @@ import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorDigitalResponseRepositoryMod; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorReasonableAdjustmentRepository; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseAuditRepositoryMod; -import uk.gov.hmcts.juror.api.moj.utils.DataUtils; +import uk.gov.hmcts.juror.api.moj.service.JurorPoolService; +import uk.gov.hmcts.juror.api.moj.service.JurorThirdPartyService; import uk.gov.hmcts.juror.api.moj.utils.RepositoryUtils; -import uk.gov.hmcts.juror.api.validation.ValidationConstants; import java.time.LocalDate; import java.time.LocalDateTime; @@ -45,7 +45,6 @@ @RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class ResponseStatusUpdateServiceImpl implements ResponseStatusUpdateService, ResponseMergeService { private final JurorDigitalResponseRepositoryMod jurorResponseRepository; - private final JurorResponseAuditRepositoryMod auditRepository; private final JurorPoolRepository jurorDetailsRepository; private final JurorStatusRepository jurorStatusRepository; private final JurorHistoryRepository partHistRepository; @@ -56,6 +55,8 @@ public class ResponseStatusUpdateServiceImpl implements ResponseStatusUpdateServ private final JurorReasonableAdjustmentRepository specialNeedsRepository; private final WelshCourtLocationRepository welshCourtLocationRepository; private final JurorResponseAuditRepositoryMod jurorResponseAuditRepositoryMod; + private final JurorPoolService jurorPoolService; + private final JurorThirdPartyService jurorThirdPartyService; /** @@ -106,7 +107,7 @@ public void updateJurorResponseStatus(final String jurorNumber, final Processing mergeResponse(jurorResponse, auditorUsername); // JDB-2487 AC16.6: Changing to a CLOSED processingStatus, so set required "Positive Response" values - JurorPool jurorDetails = jurorPoolRepository.findByJurorJurorNumber(jurorNumber); + JurorPool jurorDetails = jurorPoolService.getJurorPoolFromUser(jurorNumber); jurorDetails.getJuror().setResponded(true); jurorDetails.setUserEdtq(auditorUsername); jurorDetails.setStatus(RepositoryUtils.retrieveFromDatabase(IJurorStatus.RESPONDED, @@ -146,7 +147,7 @@ public void mergeResponse(final DigitalResponse originalDetails, final String au log.trace("Merging response {}", originalDetails); } - final JurorPool jurorDetails = jurorDetailsRepository.findByJurorJurorNumber(originalDetails.getJurorNumber()); + final JurorPool jurorDetails = jurorPoolService.getJurorPoolFromUser(originalDetails.getJurorNumber()); if (jurorDetails == null) { log.error("No pool entry found for Juror {}", originalDetails.getJurorNumber()); throw new JurorPoolEntryNotFoundException("No pool entry found"); @@ -166,38 +167,30 @@ public void mergeResponse(final DigitalResponse originalDetails, final String au specialNeedsByJurorNumber.size() ); - if (specialNeedsByJurorNumber != null) { - //if multiple set need to M - if (specialNeedsByJurorNumber.size() > 1) { - jurorDetails.getJuror().setReasonableAdjustmentCode("M"); - jurorDetails.getJuror() - .setReasonableAdjustmentMessage( - DataUtils.trimToLength( - specialNeedsByJurorNumber - .stream() - .reduce( - "", - (acc, item) -> acc + item.getReasonableAdjustmentDetail() + ", ", - String::concat - ).trim(), - ValidationConstants.REASONABLE_ADJUSTMENT_MESSAGE_LENGTH_MAX)); - } else if (specialNeedsByJurorNumber.size() == 1 - && specialNeedsByJurorNumber.get(0) != null) { - jurorDetails.getJuror() - .setReasonableAdjustmentCode(specialNeedsByJurorNumber.get(0).getReasonableAdjustment().getCode()); - jurorDetails.getJuror() - .setReasonableAdjustmentMessage(specialNeedsByJurorNumber.get(0).getReasonableAdjustmentDetail()); - } - - log.debug("Merging special need information for juror {}, Special need {}", jurorDetails.getJurorNumber(), - // poolDetails.getSpecialNeed() - jurorDetails.getJuror().getReasonableAdjustmentMessage() - ); - jurorDetailsRepository.save(jurorDetails);// save the updated pool table data + if (updatedDetails.getThirdPartyFName() != null) { + jurorThirdPartyService.createOrUpdateThirdParty(jurorDetails.getJuror(), updatedDetails); + } - log.debug("Merged special need information for juror {}", jurorDetails.getJurorNumber()); + //if multiple set need to M + if (specialNeedsByJurorNumber.size() > 1) { + jurorDetails.getJuror().setReasonableAdjustmentCode("M"); + } else if (specialNeedsByJurorNumber.size() == 1 + && specialNeedsByJurorNumber.get(0) != null) { + jurorDetails.getJuror() + .setReasonableAdjustmentCode(specialNeedsByJurorNumber.get(0).getReasonableAdjustment().getCode()); } + jurorDetails.getJuror() + .setReasonableAdjustmentMessage(updatedDetails.getReasonableAdjustmentsArrangements()); + + log.debug("Merging special need information for juror {}, Special need {}", jurorDetails.getJurorNumber(), + // poolDetails.getSpecialNeed() + jurorDetails.getJuror().getReasonableAdjustmentMessage() + ); + + jurorDetailsRepository.save(jurorDetails);// save the updated pool table data + + log.debug("Merged special need information for juror {}", jurorDetails.getJurorNumber()); if ("deceased".equalsIgnoreCase(originalDetails.getThirdPartyReason())) { log.info("Third party deceased flow."); @@ -217,7 +210,7 @@ public void mergeResponse(final DigitalResponse originalDetails, final String au // perform merge or changes // check for changes in original values - boolean titleChanged = false; + boolean titleChanged; if (updatedDetails.getTitle() != null) { if (jurorDetails.getJuror().getTitle() != null) { titleChanged = updatedDetails.getTitle().compareTo(jurorDetails.getJuror().getTitle()) != 0; diff --git a/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseUpdateServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseUpdateServiceImpl.java index e87757598..cd3db103a 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseUpdateServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/bureau/service/ResponseUpdateServiceImpl.java @@ -18,14 +18,16 @@ import uk.gov.hmcts.juror.api.moj.domain.ContactLog; import uk.gov.hmcts.juror.api.moj.domain.IContactCode; import uk.gov.hmcts.juror.api.moj.domain.IJurorStatus; +import uk.gov.hmcts.juror.api.moj.domain.Juror; import uk.gov.hmcts.juror.api.moj.domain.JurorPool; import uk.gov.hmcts.juror.api.moj.domain.User; import uk.gov.hmcts.juror.api.moj.domain.jurorresponse.DigitalResponse; import uk.gov.hmcts.juror.api.moj.domain.jurorresponse.JurorReasonableAdjustment; import uk.gov.hmcts.juror.api.moj.domain.jurorresponse.JurorResponseCjsEmployment; +import uk.gov.hmcts.juror.api.moj.exception.MojException; import uk.gov.hmcts.juror.api.moj.repository.ContactCodeRepository; import uk.gov.hmcts.juror.api.moj.repository.ContactLogRepository; -import uk.gov.hmcts.juror.api.moj.repository.JurorPoolRepository; +import uk.gov.hmcts.juror.api.moj.repository.JurorRepository; import uk.gov.hmcts.juror.api.moj.repository.UserRepository; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorDigitalResponseRepositoryMod; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorReasonableAdjustmentRepository; @@ -33,6 +35,7 @@ import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseCjsEmploymentRepositoryMod; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.ReasonableAdjustmentsRepository; import uk.gov.hmcts.juror.api.moj.service.JurorHistoryService; +import uk.gov.hmcts.juror.api.moj.service.JurorPoolService; import uk.gov.hmcts.juror.api.moj.utils.RepositoryUtils; import java.lang.reflect.Field; @@ -89,9 +92,9 @@ public class ResponseUpdateServiceImpl implements ResponseUpdateService { private final ContactCodeRepository contactCodeRepository; static final String HASH_SALT = "445NlwAglWA78Vh9DKbVwN5vPHsvy2kA"; - private static final String MESSAGE = "User {} applied {} total changes to response {}"; private static final String OTHER_1 = "Other"; - private final JurorPoolRepository jurorRepository; + private final JurorRepository jurorRepository; + private final JurorPoolService jurorPoolService; private final ContactLogRepository phoneLogRepository; private final JurorDigitalResponseRepositoryMod responseRepository; private final UserRepository userRepository; @@ -106,14 +109,14 @@ public class ResponseUpdateServiceImpl implements ResponseUpdateService { @Override @Transactional(readOnly = true) public JurorNoteDto notesByJurorNumber(final String jurorId) { - final JurorPool juror = jurorRepository.findByJurorJurorNumber(jurorId); + final Juror juror = jurorRepository.findByJurorNumber(jurorId); if (juror != null) { - final String notes = juror.getJuror().getNotes(); + final String notes = juror.getNotes(); return new JurorNoteDto(notes, comparisonHash(notes)); } else { - log.error("No POOL entry found for PART_NO={}", jurorId); - throw new NoteNotFoundException("POOL entry not found"); + log.error("Juror entry not found for juror number = {}", jurorId); + throw new MojException.NotFound("Juror entry not found",null); } } @@ -122,42 +125,37 @@ public JurorNoteDto notesByJurorNumber(final String jurorId) { public void updateNote(final JurorNoteDto noteDto, final String jurorId, final String auditUser) { - final JurorPool juror = jurorRepository.findByJurorJurorNumber(jurorId); + final JurorPool juror = jurorPoolService.getJurorPoolFromUser(jurorId); - if (juror != null) { - if (comparisonHash(juror.getJuror().getNotes()).compareTo(noteDto.getVersion()) == 0) { - // hashcode matches, save changes to notes - juror.getJuror().setNotes(noteDto.getNotes()); - final JurorPool updatedPool = jurorRepository.save(juror); - - // JDB-2685: if no staff assigned, assign current login - DigitalResponse jurorResponse = responseRepository.findByJurorNumber(jurorId); - if (null == jurorResponse.getStaff()) { - assignOnUpdateService.assignToCurrentLogin(jurorResponse, auditUser); - } + if (comparisonHash(juror.getJuror().getNotes()).compareTo(noteDto.getVersion()) == 0) { + // hashcode matches, save changes to notes + juror.getJuror().setNotes(noteDto.getNotes()); + final JurorPool updatedPool = jurorPoolService.save(juror); - // 2. persist response - if (log.isTraceEnabled()) { - log.trace("Persisting staff assignment update for response: {}", jurorResponse); - } - responseRepository.save(jurorResponse); + // JDB-2685: if no staff assigned, assign current login + DigitalResponse jurorResponse = responseRepository.findByJurorNumber(jurorId); + if (null == jurorResponse.getStaff()) { + assignOnUpdateService.assignToCurrentLogin(jurorResponse, auditUser); + } - if (log.isDebugEnabled()) { - log.debug("Updated note for juror {}: {}", jurorId, updatedPool.getJuror().getNotes()); - } + // 2. persist response + if (log.isTraceEnabled()) { + log.trace("Persisting staff assignment update for response: {}", jurorResponse); + } + responseRepository.save(jurorResponse); - // audit the change to the notes column - jurorHistoryService.createPoolEditHistory(updatedPool); - } else { - log.debug("Note failed hash comparison."); - if (log.isTraceEnabled()) { - log.trace("UI={} DB={}", noteDto.getVersion(), comparisonHash(juror.getJuror().getNotes())); - } - throw new NoteComparisonFailureException(); + if (log.isDebugEnabled()) { + log.debug("Updated note for juror {}: {}", jurorId, updatedPool.getJuror().getNotes()); } + + // audit the change to the notes column + jurorHistoryService.createPoolEditHistory(updatedPool); } else { - log.warn("No Juror entry found for PART_NO={}", jurorId); - throw new NoteNotFoundException("Juror entry not found"); + log.debug("Note failed hash comparison."); + if (log.isTraceEnabled()) { + log.trace("UI={} DB={}", noteDto.getVersion(), comparisonHash(juror.getJuror().getNotes())); + } + throw new NoteComparisonFailureException(); } } @@ -421,7 +419,7 @@ public void updateResponseStatus(String jurorId, ProcessingStatus status, Intege log.debug("Start - update response status, when legacy status changed for juror {}", jurorId); final DigitalResponse domain = responseRepository.findByJurorNumber(jurorId); - final JurorPool juror = jurorRepository.findByJurorJurorNumber(jurorId); + final JurorPool juror = jurorPoolService.getJurorPoolFromUser(jurorId); applyOptimisticLocking(domain, version); if (juror != null) { @@ -761,7 +759,7 @@ private void applyOptimisticLocking(final DigitalResponse domain, final Integer /** * Save changelog and juror response to the database catching and wrapping a optimistic locking exception. * - * @param domain Updated DETATCHED juror response entity + * @param domain Updated DETATCHED juror response entity */ private void saveUpdatesOptimistically(final DigitalResponse domain) throws BureauOptimisticLockingException { diff --git a/src/main/java/uk/gov/hmcts/juror/api/juror/controller/response/JurorHolidaysResponseDto.java b/src/main/java/uk/gov/hmcts/juror/api/juror/controller/response/JurorHolidaysResponseDto.java index 2ff0f8621..e495c9a5f 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/juror/controller/response/JurorHolidaysResponseDto.java +++ b/src/main/java/uk/gov/hmcts/juror/api/juror/controller/response/JurorHolidaysResponseDto.java @@ -62,11 +62,17 @@ public static class Holidays implements Serializable { public static List from(List publicHolidaysDates) { return publicHolidaysDates.stream() - .map(holiday -> Holidays.builder() - .date(holiday.getHoliday()) - .publicHoliday(holiday.getPublicHoliday()) - .locCode(holiday.getCourtLocation().getLocCode()) - .build()) + .map(holiday -> { + String locCode = null; + if (holiday.getCourtLocation() != null) { + locCode = holiday.getCourtLocation().getLocCode(); + } + return Holidays.builder() + .date(holiday.getHoliday()) + .publicHoliday(holiday.getPublicHoliday()) + .locCode(locCode) + .build(); + }) .toList(); } } diff --git a/src/main/java/uk/gov/hmcts/juror/api/juror/service/JurorPersistenceServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/juror/service/JurorPersistenceServiceImpl.java index 237a9bba8..c1c3db4f1 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/juror/service/JurorPersistenceServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/juror/service/JurorPersistenceServiceImpl.java @@ -47,8 +47,8 @@ public Boolean persistJurorResponse(final JurorResponseDto responseDto) { sendNotificationResponse(savedResponse, NotifyTemplateType.STRAIGHT_THROUGH); return Boolean.TRUE;// prevent further processing of straight through due to success. } catch (StraightThroughProcessingServiceException stpse) { - log.info("Failed to process Juror {} Response as a straight through acceptance: {}", - savedResponse.getJurorNumber(), stpse + log.info("Failed to process Juror {} Response as a straight through acceptance: {} - {}", + savedResponse.getJurorNumber(), stpse.getClass().getSimpleName(), stpse.getMessage() ); } } @@ -64,8 +64,8 @@ public Boolean persistJurorResponse(final JurorResponseDto responseDto) { sendNotificationResponse(savedResponse, NotifyTemplateType.EXCUSAL_DECEASED); return Boolean.TRUE;// prevent further processing of straight through due to success. } catch (StraightThroughProcessingServiceException stpse) { - log.info("Failed to process Juror {} Response as a straight-through deceased-excusal: {}", - savedResponse.getJurorNumber(), stpse + log.info("Failed to process Juror {} Response as a straight-through deceased-excusal: {} - {}", + savedResponse.getJurorNumber(), stpse.getClass().getSimpleName(), stpse.getMessage() ); } } @@ -81,8 +81,8 @@ public Boolean persistJurorResponse(final JurorResponseDto responseDto) { sendNotificationResponse(savedResponse, NotifyTemplateType.DISQUALIFICATION_AGE); return Boolean.TRUE;// prevent further processing of straight through due to success. } catch (StraightThroughProcessingServiceException stpse) { - log.info("Failed to process Juror {} Response as a straight-through age-excusal: {}", - savedResponse.getJurorNumber(), stpse + log.info("Failed to process Juror {} Response as a straight-through age-excusal: {} - {}", + savedResponse.getJurorNumber(), stpse.getClass().getSimpleName(), stpse.getMessage() ); } } @@ -105,7 +105,7 @@ private void sendNotificationResponse(final DigitalResponse savedResponse, try { jurorNotificationService.sendResponseReceipt(savedResponse, notifyTemplateType); } catch (Exception e) { - log.warn("Could not send receipt for juror {} response! {}", savedResponse.getJurorNumber(), e); + log.warn("Could not send receipt for juror {} response!", savedResponse.getJurorNumber(), e); } } @@ -133,7 +133,7 @@ private boolean allowStraightThroughProcessingType(StraightThroughType straightT return true; } } catch (Exception e) { - log.warn("Failed to query application setting for Straight Through {} Processing: {}", + log.warn("Failed to query application setting for Straight Through {} Processing:", straightThroughType.getReadableName(), e ); return false; diff --git a/src/main/java/uk/gov/hmcts/juror/api/juror/service/StraightThroughProcessorImpl.java b/src/main/java/uk/gov/hmcts/juror/api/juror/service/StraightThroughProcessorImpl.java index 07bfb5caa..fed7bcf07 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/juror/service/StraightThroughProcessorImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/juror/service/StraightThroughProcessorImpl.java @@ -25,6 +25,7 @@ import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorDigitalResponseRepositoryMod; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseAuditRepositoryMod; import uk.gov.hmcts.juror.api.moj.service.JurorHistoryService; +import uk.gov.hmcts.juror.api.moj.service.JurorPoolService; import uk.gov.hmcts.juror.api.moj.service.PrintDataService; import uk.gov.hmcts.juror.api.moj.utils.JurorPoolUtils; import uk.gov.hmcts.juror.api.moj.utils.RepositoryUtils; @@ -56,6 +57,7 @@ public class StraightThroughProcessorImpl implements StraightThroughProcessor { private final JurorStatusRepository jurorStatusRepository; private final JurorHistoryService jurorHistoryService; private final PrintDataService printDataService; + private final JurorPoolService jurorPoolService; private static final String THIRD_PARTY_REASON_DECEASED = "deceased"; private static final String MESSAGE = "Urgent response does not qualify for straight-through"; @@ -87,7 +89,7 @@ public void processAcceptance( final DigitalResponse savedDigitalResponse = jurorDigitalResponseRepository.findByJurorNumber(digitalResponse.getJurorNumber()); final JurorPool jurorDetails = - jurorRepository.findByJurorJurorNumber(savedDigitalResponse.getJurorNumber()); + jurorPoolService.getJurorPoolFromUser(savedDigitalResponse.getJurorNumber()); // check the response for answers making it ineligible for straight through processing. // JDB-126 a. the title, first name and last name must be the same in the Juror response as they are on @@ -275,9 +277,8 @@ public void processAcceptance( mergeService.mergeResponse(savedDigitalResponse, AUTO_USER); // update juror entry - // final Pool updatedDetails = detailsRepository.findByJurorNumber(savedDigitalResponse.getJurorNumber()); final JurorPool updatedJurorDetails = - jurorRepository.findByJurorJurorNumber(savedDigitalResponse.getJurorNumber()); + jurorPoolService.getJurorPoolFromUser(savedDigitalResponse.getJurorNumber()); updatedJurorDetails.getJuror().setResponded(true); updatedJurorDetails.setUserEdtq(AUTO_USER); updatedJurorDetails.setStatus(RepositoryUtils.retrieveFromDatabase(IJurorStatus.RESPONDED, @@ -327,8 +328,7 @@ public void processDeceasedExcusal( try { final DigitalResponse savedDigitalResponse = jurorDigitalResponseRepository.findByJurorNumber(digitalResponse.getJurorNumber()); - final JurorPool jurorDetails = - jurorRepository.findByJurorJurorNumber(savedDigitalResponse.getJurorNumber()); + final JurorPool jurorDetails = jurorPoolService.getJurorPoolFromUser(savedDigitalResponse.getJurorNumber()); // check the response for answers making it ineligible for straight through processing. //JDB-73 a. the response must have been submitted by a third party diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/controller/request/EditJurorRecordRequestDto.java b/src/main/java/uk/gov/hmcts/juror/api/moj/controller/request/EditJurorRecordRequestDto.java index d25bf5e43..4a3da287d 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/controller/request/EditJurorRecordRequestDto.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/controller/request/EditJurorRecordRequestDto.java @@ -152,4 +152,7 @@ public class EditJurorRecordRequestDto { @Schema(description = "Determines if Juror requires Welsh language") private Boolean welshLanguageRequired; + @JsonProperty("third_party") + private JurorThirdPartyDto thirdParty; + } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/controller/request/JurorThirdPartyDto.java b/src/main/java/uk/gov/hmcts/juror/api/moj/controller/request/JurorThirdPartyDto.java new file mode 100644 index 000000000..2576c2c07 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/controller/request/JurorThirdPartyDto.java @@ -0,0 +1,116 @@ +package uk.gov.hmcts.juror.api.moj.controller.request; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.Pattern; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.hibernate.validator.constraints.Length; +import uk.gov.hmcts.juror.api.moj.service.JurorThirdPartyService; + +import static uk.gov.hmcts.juror.api.validation.ValidationConstants.EMAIL_ADDRESS_REGEX; +import static uk.gov.hmcts.juror.api.validation.ValidationConstants.NO_PIPES_REGEX; +import static uk.gov.hmcts.juror.api.validation.ValidationConstants.PHONE_NO_REGEX; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class JurorThirdPartyDto implements JurorThirdPartyService.ThirdPartyUpdateDto { + + @JsonProperty("first_name") + @Length(max = 50) + @Pattern(regexp = NO_PIPES_REGEX) + @Schema(description = "Third party first name") + private String firstName; + + @JsonProperty("last_name") + @Length(max = 50) + @Pattern(regexp = NO_PIPES_REGEX) + @Schema(description = "Third party last name") + private String lastName; + + @JsonProperty("relationship") + @Length(max = 50) + @Pattern(regexp = NO_PIPES_REGEX) + @Schema(description = "Relationship to juror") + private String relationship; + + @JsonProperty("main_phone") + @Length(max = 50) + @Pattern(regexp = PHONE_NO_REGEX) + @Schema(description = "Main phone number") + private String mainPhone; + + @JsonProperty("other_phone") + @Length(max = 50) + @Pattern(regexp = PHONE_NO_REGEX) + @Schema(description = "Other phone number") + private String otherPhone; + + @JsonProperty("email_address") + @Length(max = 254) + @Pattern(regexp = EMAIL_ADDRESS_REGEX) + @Schema(description = "Email address") + private String emailAddress; + + @JsonProperty("reason") + @Length(max = 1250) + @Pattern(regexp = NO_PIPES_REGEX) + @Schema(description = "Reason for third party") + private String reason; + + @JsonProperty("other_reason") + @Length(max = 1250) + @Pattern(regexp = NO_PIPES_REGEX) + @Schema(description = "Other reason for third party") + private String otherReason; + + @JsonProperty("contact_juror_by_phone") + private boolean contactJurorByPhone; + + @JsonProperty("contact_juror_by_email") + private boolean contactJurorByEmail; + + @Override + public String getThirdPartyOtherReason() { + return this.getOtherReason(); + } + + @Override + public String getThirdPartyReason() { + return this.getReason(); + } + + @Override + public String getThirdPartyEmailAddress() { + return this.getEmailAddress(); + } + + @Override + public String getThirdPartyOtherPhone() { + return this.getOtherPhone(); + } + + @Override + public String getThirdPartyMainPhone() { + return this.getMainPhone(); + } + + @Override + public String getThirdPartyRelationship() { + return this.getRelationship(); + } + + @Override + public String getThirdPartyLastName() { + return this.getLastName(); + } + + @Override + public String getThirdPartyFirstName() { + return this.getFirstName(); + } +} \ No newline at end of file diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/controller/response/JurorDetailsResponseDto.java b/src/main/java/uk/gov/hmcts/juror/api/moj/controller/response/JurorDetailsResponseDto.java index 5e1b5ac11..c01fc2fa4 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/controller/response/JurorDetailsResponseDto.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/controller/response/JurorDetailsResponseDto.java @@ -12,6 +12,7 @@ import uk.gov.hmcts.juror.api.juror.domain.WelshCourtLocationRepository; import uk.gov.hmcts.juror.api.moj.domain.Juror; import uk.gov.hmcts.juror.api.moj.domain.JurorPool; +import uk.gov.hmcts.juror.api.moj.domain.JurorThirdParty; import uk.gov.hmcts.juror.api.moj.domain.PoliceCheck; import uk.gov.hmcts.juror.api.moj.enumeration.jurorresponse.ReasonableAdjustmentsEnum; import uk.gov.hmcts.juror.api.moj.repository.JurorStatusRepository; @@ -114,7 +115,6 @@ public class JurorDetailsResponseDto { @Schema(name = "Optic Reference", description = "Eight digit Optic Reference Number for Juror") private String opticReference; - /** * Initialise an instance of this DTO class using a JurorPool object to populate its properties. * @@ -155,6 +155,25 @@ public JurorDetailsResponseDto(JurorPool jurorPool, } this.specialNeedMessage = juror.getReasonableAdjustmentMessage(); this.opticReference = juror.getOpticRef(); + setJurorThirdParty(juror.getThirdParty()); + } + + private void setJurorThirdParty(JurorThirdParty jurorThirdParty) { + if (jurorThirdParty == null) { + this.thirdParty = null; + return; + } + this.thirdParty = new JurorResponseDto.ThirdParty(); + this.thirdParty.setThirdPartyFName(jurorThirdParty.getFirstName()); + this.thirdParty.setThirdPartyLName(jurorThirdParty.getLastName()); + this.thirdParty.setThirdPartyReason(jurorThirdParty.getReason()); + this.thirdParty.setThirdPartyOtherReason(jurorThirdParty.getOtherReason()); + this.thirdParty.setRelationship(jurorThirdParty.getRelationship()); + this.thirdParty.setMainPhone(jurorThirdParty.getMainPhone()); + this.thirdParty.setOtherPhone(jurorThirdParty.getOtherPhone()); + this.thirdParty.setEmailAddress(jurorThirdParty.getEmailAddress()); + this.thirdParty.setUseJurorEmailDetails(jurorThirdParty.isContactJurorByEmail()); + this.thirdParty.setUseJurorPhoneDetails(jurorThirdParty.isContactJurorByPhone()); } /** diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/controller/response/JurorOverviewResponseDto.java b/src/main/java/uk/gov/hmcts/juror/api/moj/controller/response/JurorOverviewResponseDto.java index 4bb820a74..7fdad8616 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/controller/response/JurorOverviewResponseDto.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/controller/response/JurorOverviewResponseDto.java @@ -15,6 +15,7 @@ import uk.gov.hmcts.juror.api.moj.domain.Juror; import uk.gov.hmcts.juror.api.moj.domain.JurorPool; import uk.gov.hmcts.juror.api.moj.domain.trial.Courtroom; +import uk.gov.hmcts.juror.api.moj.domain.trial.Panel; import uk.gov.hmcts.juror.api.moj.enumeration.AppearanceStage; import uk.gov.hmcts.juror.api.moj.enumeration.AttendanceType; import uk.gov.hmcts.juror.api.moj.enumeration.IdCheckCodeEnum; @@ -121,9 +122,15 @@ public JurorOverviewResponseDto(JurorPool jurorPool, if (todayAppearance.isPresent() && todayAppearance.get().getTimeIn() != null) { this.checkedInTodayTime = todayAppearance.get().getTimeIn(); - this.location = getLocation(todayAppearance.get(), panelRepository, jurorPool); } + if (todayAppearance.isPresent() && todayAppearance.get().getTimeOut() != null) { + this.location = null; + } else { + this.location = getLocationFromPanel(panelRepository, jurorPool); + } + + this.attendances = appearanceList.stream() .filter(appearance -> !AttendanceType.ABSENT.equals(appearance.getAttendanceType())) .filter(appearance -> !AttendanceType.NON_ATTENDANCE.equals(appearance.getAttendanceType())) @@ -151,19 +158,17 @@ public JurorOverviewResponseDto(JurorPool jurorPool, } @JsonIgnore - private String getLocation(Appearance appearance, PanelRepository panelRepository, JurorPool jurorPool) { - if (appearance.getTimeOut() != null) { - return null; - } - return Optional.ofNullable(appearance.getTrialNumber()) - .flatMap(trialNumber -> Optional.ofNullable(panelRepository - .findByTrialTrialNumberAndTrialCourtLocationLocCodeAndJurorJurorNumber( - trialNumber, - jurorPool.getCourt().getLocCode(), - jurorPool.getJurorNumber())) - .map(panel -> panel.getTrial().getCourtroom().getDescription())) + private String getLocationFromPanel(PanelRepository panelRepository, JurorPool jurorPool) { + return getActivePanel(panelRepository, jurorPool) + .map(panel -> panel.getTrial().getCourtroom().getDescription()) .orElse(Optional.ofNullable(jurorPool.getCourt().getAssemblyRoom()) - .map(Courtroom::getDescription) - .orElse(null)); + .map(Courtroom::getDescription) + .orElse(null)); + } + + private Optional getActivePanel(PanelRepository panelRepository, JurorPool jurorPool) { + return Optional.ofNullable(panelRepository.findActivePanelByCourtGroup( + SecurityUtil.getCourts(), + jurorPool.getJurorNumber())); } } \ No newline at end of file diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/controller/response/PoolSummaryResponseDto.java b/src/main/java/uk/gov/hmcts/juror/api/moj/controller/response/PoolSummaryResponseDto.java index c99d1dd92..213538124 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/controller/response/PoolSummaryResponseDto.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/controller/response/PoolSummaryResponseDto.java @@ -137,6 +137,9 @@ public static class AdditionalStatistics { @Schema(name = "Court Supply", description = "The number of Pool Members owned by the court (e.g. court " + "deferrals) with a status of 'Responded'") private int courtSupply; + + @JsonProperty("totalJurorsInPool") + private long totalJurorsInPool; } } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/domain/Juror.java b/src/main/java/uk/gov/hmcts/juror/api/moj/domain/Juror.java index 8abf9e956..964db6860 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/domain/Juror.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/domain/Juror.java @@ -211,7 +211,6 @@ public class Juror extends Address implements Serializable { private String summonsFile; - @Length(max = 254) @Column(name = "h_email") private String email; @@ -305,6 +304,10 @@ public class Juror extends Address implements Serializable { @Generated private String phoneNumberCombined; + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "juror_number") + @NotAudited + private JurorThirdParty thirdParty; @PrePersist @SuppressWarnings("PMD.UnusedPrivateMethod") diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/domain/JurorThirdParty.java b/src/main/java/uk/gov/hmcts/juror/api/moj/domain/JurorThirdParty.java new file mode 100644 index 000000000..497f7f7f6 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/domain/JurorThirdParty.java @@ -0,0 +1,78 @@ +package uk.gov.hmcts.juror.api.moj.domain; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import org.hibernate.envers.Audited; +import org.hibernate.validator.constraints.Length; + +import static uk.gov.hmcts.juror.api.validation.ValidationConstants.NO_PIPES_REGEX; + +@Entity +@Table(name = "juror_third_party", schema = "juror_mod") +@Getter +@Setter +@Audited +@AllArgsConstructor +@NoArgsConstructor +@ToString +public class JurorThirdParty { + + @Id + @NotNull + @Column(name = "juror_number") + private String jurorNumber; + + @Column(name = "first_name") + @Length(max = 50) + private String firstName; + + @Column(name = "last_name") + @Length(max = 50) + private String lastName; + + @Column(name = "relationship") + @Length(max = 50) + @Pattern(regexp = NO_PIPES_REGEX) + private String relationship; + + @Column(name = "main_phone") + @Length(max = 50) + private String mainPhone; + + @Column(name = "other_phone") + @Length(max = 50) + private String otherPhone; + + @Column(name = "email_address") + @Length(max = 254) + private String emailAddress; + + @Column(name = "reason") + @Pattern(regexp = NO_PIPES_REGEX) + @Length(max = 1250) + private String reason; + + @Column(name = "other_reason") + @Pattern(regexp = NO_PIPES_REGEX) + @Length(max = 1250) + private String otherReason; + + @Column(name = "contact_juror_by_phone") + private boolean contactJurorByPhone; + + @Column(name = "contact_juror_by_email") + private boolean contactJurorByEmail; + + public JurorThirdParty(String jurorNumber) { + this.jurorNumber = jurorNumber; + } +} diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/domain/jurorresponse/DigitalResponse.java b/src/main/java/uk/gov/hmcts/juror/api/moj/domain/jurorresponse/DigitalResponse.java index f22a64134..05bea8e4f 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/domain/jurorresponse/DigitalResponse.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/domain/jurorresponse/DigitalResponse.java @@ -13,6 +13,7 @@ import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder; +import uk.gov.hmcts.juror.api.moj.service.JurorThirdPartyService; import uk.gov.hmcts.juror.api.moj.validation.DigitalThirdPartyOtherReason; import static uk.gov.hmcts.juror.api.validation.ValidationConstants.NO_PIPES_REGEX; @@ -27,7 +28,8 @@ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) @SuppressWarnings("PMD.TooManyFields") -public class DigitalResponse extends AbstractJurorResponse { +public class DigitalResponse extends AbstractJurorResponse + implements JurorThirdPartyService.ThirdPartyUpdateDto { @Column(name = "residency") @NotNull @@ -107,4 +109,45 @@ public DigitalResponse() { super(); super.setReplyType(new ReplyType("Digital", "Online response")); } + + + @Override + public String getThirdPartyEmailAddress() { + return this.getEmailAddress(); + } + + @Override + public String getThirdPartyOtherPhone() { + return this.getOtherPhone(); + } + + @Override + public String getThirdPartyMainPhone() { + return this.getMainPhone(); + } + + @Override + public String getThirdPartyRelationship() { + return this.getRelationship(); + } + + @Override + public String getThirdPartyLastName() { + return this.getThirdPartyLName(); + } + + @Override + public String getThirdPartyFirstName() { + return this.getThirdPartyFName(); + } + + @Override + public boolean isContactJurorByEmail() { + return this.getJurorEmailDetails() != null && this.getJurorEmailDetails(); + } + + @Override + public boolean isContactJurorByPhone() { + return this.getJurorPhoneDetails() != null && this.getJurorPhoneDetails(); + } } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/report/grouped/CompletionOfServiceReport.java b/src/main/java/uk/gov/hmcts/juror/api/moj/report/grouped/CompletionOfServiceReport.java index 0cf58a8da..030db64b9 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/report/grouped/CompletionOfServiceReport.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/report/grouped/CompletionOfServiceReport.java @@ -55,6 +55,7 @@ public Class getRequestValidatorC public void preProcessQuery(JPAQuery query, StandardReportRequest request) { query.where(QJuror.juror.completionDate.between(request.getFromDate(), request.getToDate())); query.where(QJurorPool.jurorPool.pool.courtLocation.locCode.eq(SecurityUtil.getLocCode())); + query.where(QJurorPool.jurorPool.isActive.isTrue()); query.orderBy(QJuror.juror.jurorNumber.asc()); } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/IAppearanceRepositoryImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/IAppearanceRepositoryImpl.java index 9f2912cc3..050160502 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/IAppearanceRepositoryImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/IAppearanceRepositoryImpl.java @@ -62,7 +62,9 @@ public List getAppearanc String locCode, LocalDate date, String jurorNumber, JurorStatusGroup group) { List jurorStatuses = group.getStatusList(); - JPAQuery query = sqlFetchAppearanceRecords(locCode, date, jurorStatuses); + JPAQuery query = sqlFetchAppearanceRecords(locCode, date, jurorStatuses, + group == JurorStatusGroup.IN_WAITING); + // check if we need to just return one juror's record if (jurorNumber != null) { @@ -83,7 +85,7 @@ public List retrieveAttendanceDetails(RetrieveAttendanceDetailsDto reques // start building the query JPAQuery query = sqlFetchAppearanceRecords(commonData.getLocationCode(), commonData.getAttendanceDate(), - jurorStatuses); + jurorStatuses, request.isJurorInWaiting()); if (commonData.getTag().equals(RetrieveAttendanceDetailsTag.JUROR_NUMBER)) { query = query.where(APPEARANCE.jurorNumber.in(request.getJuror())); @@ -139,10 +141,11 @@ private List sqlFilterQueryJurorStatus(@NotNull RetrieveAttendanceDetai } } - private JPAQuery sqlFetchAppearanceRecords(String locCode, LocalDate date, List jurorStatuses) { + private JPAQuery sqlFetchAppearanceRecords(String locCode, LocalDate date, List jurorStatuses, + boolean excludeJuryAttendances) { JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager); - return queryFactory.select( + JPAQuery query = queryFactory.select( JUROR.jurorNumber.as("juror_number"), JUROR.firstName.as("first_name"), JUROR.lastName.as("last_name"), @@ -164,6 +167,11 @@ private JPAQuery sqlFetchAppearanceRecords(String locCode, LocalDate date .where(APPEARANCE.attendanceDate.eq(date)) .where(JUROR_POOL.status.status.in(jurorStatuses)) .where(JUROR_POOL.isActive.isTrue()); + if (excludeJuryAttendances) { + query.where(APPEARANCE.attendanceAuditNumber.isNull() + .or(APPEARANCE.attendanceAuditNumber.startsWith("J").not())); + } + return query; } private List sqlOrderQueryResults(JPAQuery query) { @@ -313,7 +321,7 @@ public List getTrialsWithAttendanceCount(String locationCode, LocalDate a .where(APPEARANCE.appearanceStage.in(AppearanceStage.EXPENSE_ENTERED, AppearanceStage.EXPENSE_AUTHORISED, AppearanceStage.EXPENSE_EDITED)) .where(APPEARANCE.courtLocation.locCode.eq(locationCode)) - .where(PANEL.result.eq(PanelResult.JUROR)) + .where(APPEARANCE.attendanceAuditNumber.startsWith("J")) .groupBy(PANEL.trial.trialNumber, APPEARANCE.attendanceAuditNumber) .fetch(); diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/JurorPoolRepository.java b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/JurorPoolRepository.java index 9811bc5d9..d4c6f21ea 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/JurorPoolRepository.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/JurorPoolRepository.java @@ -48,11 +48,11 @@ Optional findByJurorJurorNumberAndStatusStatusAndIsActive(String juro JurorPool findByJurorJurorNumberAndPoolPoolNumberAndStatus(String jurorNumber, String poolNumber, JurorStatus status); - List findByJurorJurorNumberOrderByDateCreatedDesc(String jurorNumber); JurorPool findByOwnerAndJurorJurorNumberAndPoolPoolNumberAndIsActive(String owner, String jurorNumber, String poolNumber, boolean isActive); + @Deprecated JurorPool findByJurorJurorNumber(String jurorNumber); JurorPool findByJurorJurorNumberAndIsActiveAndOwner(String jurorNumber, boolean isActive, String owner); diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/JurorRepository.java b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/JurorRepository.java index 14b166968..7453ab28c 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/JurorRepository.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/JurorRepository.java @@ -35,5 +35,7 @@ List callDailyUtilStats(@Param("LocCode") String locCode, List callDailyUtilJurorsStats(@Param("LocCode") String locCode, @Param("reportDate") LocalDate reportDate) throws SQLException; - -} + @Query(value = "SELECT MAX(j.revision) FROM juror_mod.juror_audit j WHERE j.juror_number = ?1", + nativeQuery = true) + Long getLatestRevision(String jurorNumber); +} \ No newline at end of file diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/JurorRepositoryImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/JurorRepositoryImpl.java index 3dac70479..6ca6f5f72 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/JurorRepositoryImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/JurorRepositoryImpl.java @@ -84,19 +84,19 @@ public JPAQuery fetchFilteredJurorRecords(JurorRecordFilterRequestQuery q if (null != query.getJurorName()) { - final String jurorName = query.getJurorName().toLowerCase().trim(); + final String jurorName = query.getJurorName().trim(); String[] names = jurorName.split(" "); if (names.length == 2) { - partialQuery.where((JUROR.firstName.toLowerCase().contains(names[0])) - .and(JUROR.lastName.toLowerCase().contains(names[1])) - .or(JUROR.firstName.concat(" ").concat(JUROR.lastName).contains(jurorName))); + partialQuery.where((JUROR.firstName.containsIgnoreCase(names[0])) + .and(JUROR.lastName.containsIgnoreCase(names[1])) + .or(JUROR.firstName.concat(" ").concat(JUROR.lastName).containsIgnoreCase(jurorName))); } else if (names.length > 2) { // assume first name is first word and last name is the rest - partialQuery.where((JUROR.firstName.toLowerCase().contains(names[0]) - .and(JUROR.lastName.toLowerCase().contains(jurorName.substring(names[0].length() + 1)))) - .or(JUROR.firstName.concat(" ").concat(JUROR.lastName).contains(jurorName))); + partialQuery.where((JUROR.firstName.containsIgnoreCase(names[0]) + .and(JUROR.lastName.containsIgnoreCase(jurorName.substring(names[0].length() + 1)))) + .or(JUROR.firstName.concat(" ").concat(JUROR.lastName).containsIgnoreCase(jurorName))); } else { partialQuery.where(JUROR.firstName.concat(" ").concat(JUROR.lastName).containsIgnoreCase(jurorName)); } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/juror/JurorThirdPartyRepository.java b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/juror/JurorThirdPartyRepository.java new file mode 100644 index 000000000..fd719d233 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/juror/JurorThirdPartyRepository.java @@ -0,0 +1,9 @@ +package uk.gov.hmcts.juror.api.moj.repository.juror; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import uk.gov.hmcts.juror.api.moj.domain.JurorThirdParty; + +@Repository +public interface JurorThirdPartyRepository extends JpaRepository { +} diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/jurorresponse/JurorResponseCommonRepositoryModImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/jurorresponse/JurorResponseCommonRepositoryModImpl.java index 04d63077a..85b16c0ef 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/jurorresponse/JurorResponseCommonRepositoryModImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/jurorresponse/JurorResponseCommonRepositoryModImpl.java @@ -8,6 +8,7 @@ import jakarta.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import uk.gov.hmcts.juror.api.moj.controller.request.summonsmanagement.JurorResponseRetrieveRequestDto; +import uk.gov.hmcts.juror.api.moj.domain.QJuror; import uk.gov.hmcts.juror.api.moj.domain.QJurorPool; import uk.gov.hmcts.juror.api.moj.domain.jurorresponse.AbstractJurorResponse; import uk.gov.hmcts.juror.api.moj.domain.jurorresponse.JurorResponseCommon; @@ -23,7 +24,7 @@ /** * Custom Repository implementation for juror responses (paper or digital). - * */ + */ @Repository public class JurorResponseCommonRepositoryModImpl implements JurorResponseCommonRepositoryMod { @@ -32,6 +33,7 @@ public class JurorResponseCommonRepositoryModImpl implements JurorResponseCommon private static final QDigitalResponse DIGITAL_RESPONSE = QDigitalResponse.digitalResponse; private static final QPaperResponse PAPER_RESPONSE = QPaperResponse.paperResponse; private static final QJurorPool JUROR_POOL = QJurorPool.jurorPool; + private static final QJuror JUROR = QJuror.juror; @PersistenceContext @@ -96,7 +98,10 @@ private JPAQuery sqlRetrieveJurorResponseDetails(JurorResponseRetrieveReq .join(JUROR_POOL) .on(JUROR_RESPONSE_COMMON.jurorNumber .eq(JUROR_POOL.juror.jurorNumber) - .and(JUROR_POOL.isActive.eq(true))); + .and(JUROR_POOL.isActive.eq(true))) + .join(JUROR) + .on(JUROR_RESPONSE_COMMON.jurorNumber.eq(JUROR.jurorNumber)) + .where(JUROR.bureauTransferDate.isNull()); // add filters to query addCommonFilters(request, query); @@ -132,7 +137,7 @@ private void addTeamLeaderFilters(JurorResponseRetrieveRequestDto request, JPAQu } if (request.getOfficerAssigned() != null && !request.getOfficerAssigned().isBlank()) { - query.where(JUROR_RESPONSE_COMMON.staff.username.equalsIgnoreCase(request.getOfficerAssigned())); + query.where(JUROR_RESPONSE_COMMON.staff.username.eq(request.getOfficerAssigned())); } if (isNotEmptyOrNull(request.getProcessingStatus())) { diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/letter/CourtPrintLetterRepositoryImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/letter/CourtPrintLetterRepositoryImpl.java index b413ac7e4..05d98d043 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/letter/CourtPrintLetterRepositoryImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/letter/CourtPrintLetterRepositoryImpl.java @@ -248,6 +248,7 @@ private List> fetchCommonPrintData(boolean welsh) { expressions.add(COURT_LOCATION.signatory); expressions.add(COURT_LOCATION.locCode); expressions.add(COURT_LOCATION.postcode); + expressions.add(COURT_LOCATION.courtAttendTime); // Juror information expressions.add(JUROR_POOL.juror.firstName); diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/trial/ITrialRepositoryImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/trial/ITrialRepositoryImpl.java index 23b64c2f8..a3a47328a 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/trial/ITrialRepositoryImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/trial/ITrialRepositoryImpl.java @@ -8,6 +8,7 @@ import jakarta.persistence.PersistenceContext; import uk.gov.hmcts.juror.api.moj.controller.request.trial.TrialSearch; import uk.gov.hmcts.juror.api.moj.domain.PaginatedList; +import uk.gov.hmcts.juror.api.moj.domain.QAppearance; import uk.gov.hmcts.juror.api.moj.domain.SortMethod; import uk.gov.hmcts.juror.api.moj.domain.trial.QPanel; import uk.gov.hmcts.juror.api.moj.domain.trial.QTrial; @@ -28,6 +29,7 @@ public class ITrialRepositoryImpl implements ITrialRepository { private static final QTrial TRIAL = QTrial.trial; private static final QPanel PANEL = QPanel.panel; + private static final QAppearance APPEARANCE = QAppearance.appearance; @Override public PaginatedList getListOfTrials(TrialSearch trialSearch, @@ -61,17 +63,27 @@ public List getActiveTrialsWithJurorCount(String locationCode, LocalDate return queryFactory.select(TRIAL.trialNumber, TRIAL.description, - TRIAL.trialType.stringValue(), + TRIAL.trialType, TRIAL.courtroom.description, TRIAL.judge.name, - PANEL.juror.count()) + PANEL.count()) .from(TRIAL) .join(PANEL) .on(TRIAL.eq(PANEL.trial)) - .where(TRIAL.trialEndDate.isNull().and(TRIAL.courtLocation.locCode.eq(locationCode))) + .leftJoin(APPEARANCE).on( + APPEARANCE.jurorNumber.eq(PANEL.juror.jurorNumber) + .and(APPEARANCE.locCode.eq(locationCode)) + .and(APPEARANCE.attendanceDate.eq(attendanceDate)) + .and(APPEARANCE.attendanceAuditNumber.startsWith("J")) + .and(APPEARANCE.trialNumber.eq(TRIAL.trialNumber)) + ) + .where(TRIAL.courtLocation.locCode.eq(locationCode)) .where(TRIAL.trialStartDate.loe(attendanceDate)) - .where(PANEL.result.eq(PanelResult.JUROR)) - .groupBy(TRIAL.trialNumber, TRIAL.description, TRIAL.trialType.stringValue(), TRIAL.courtroom.description, + .where(TRIAL.trialEndDate.isNull().or(TRIAL.trialEndDate.goe(attendanceDate))) + //If they are a JUROR or have an appearance with a jury confirmation audit number + .where(PANEL.result.eq(PanelResult.JUROR) + .or(APPEARANCE.isNotNull())) + .groupBy(TRIAL.trialNumber, TRIAL.description, TRIAL.trialType, TRIAL.courtroom.description, TRIAL.judge.name) .fetch(); } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/trial/PanelRepository.java b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/trial/PanelRepository.java index f6109e7fa..2dc9f5ad6 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/repository/trial/PanelRepository.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/repository/trial/PanelRepository.java @@ -33,5 +33,12 @@ boolean existsByTrialTrialNumberAndTrialCourtLocationLocCodeAndJurorJurorNumber( ) Panel findActivePanel(String locCode, String jurorNumber); + @Query( + value = "SELECT * FROM juror_mod.juror_trial " + + "WHERE loc_code in ?1 AND juror_number = ?2 AND (result IS NULL OR result = 'J')", + nativeQuery = true + ) + Panel findActivePanelByCourtGroup(List locCode, String jurorNumber); + long countByJurorJurorNumberAndTrialCourtLocationLocCode(String jurorNumber, String locCode); } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/DeferralResponseServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/DeferralResponseServiceImpl.java index eb7a801e5..5df31ac68 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/DeferralResponseServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/DeferralResponseServiceImpl.java @@ -64,8 +64,7 @@ public void respondToDeferralRequest(BureauJwtPayload payload, DeferralRequestDt final String jurorNumber = deferralRequestDto.getJurorNumber(); final String owner = payload.getOwner(); - JurorPool jurorPool = JurorPoolUtils.getActiveJurorPoolRecord( - jurorPoolRepository, jurorPoolService, jurorNumber); + JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(jurorNumber); JurorPoolUtils.checkOwnershipForCurrentUser(jurorPool, owner); checkExcusalCodeIsValid(deferralRequestDto.getDeferralReason()); diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/ExcusalResponseServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/ExcusalResponseServiceImpl.java index 8d4cd9403..aa8a46a8a 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/ExcusalResponseServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/ExcusalResponseServiceImpl.java @@ -60,8 +60,7 @@ public void respondToExcusalRequest(BureauJwtPayload payload, ExcusalDecisionDto checkExcusalCodeIsValid(excusalDecisionDto.getExcusalReasonCode()); - JurorPool jurorPool = JurorPoolUtils.getActiveJurorPoolRecord( - jurorPoolRepository, jurorPoolService, jurorNumber); + JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(jurorNumber); JurorPoolUtils.checkOwnershipForCurrentUser(jurorPool, owner); diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/FinancialAuditServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/FinancialAuditServiceImpl.java index 972d6c844..2f6a52ed1 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/FinancialAuditServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/FinancialAuditServiceImpl.java @@ -3,12 +3,10 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.history.Revision; import org.springframework.stereotype.Service; import uk.gov.hmcts.juror.api.moj.domain.Appearance; import uk.gov.hmcts.juror.api.moj.domain.FinancialAuditDetails; import uk.gov.hmcts.juror.api.moj.domain.FinancialAuditDetailsAppearances; -import uk.gov.hmcts.juror.api.moj.domain.Juror; import uk.gov.hmcts.juror.api.moj.domain.SortMethod; import uk.gov.hmcts.juror.api.moj.exception.MojException; import uk.gov.hmcts.juror.api.moj.repository.AppearanceRepository; @@ -40,16 +38,13 @@ public FinancialAuditDetails createFinancialAuditDetail(String jurorNumber, String courtLocationCode, FinancialAuditDetails.Type type, List appearances) { - Revision jurorRevision = revisionService.getLatestJurorRevision(jurorNumber); - - // create a single financial audit details object with a new audit number generated for this batch of expenses FinancialAuditDetails auditDetails = FinancialAuditDetails.builder() .createdBy(userRepository.findByUsername(SecurityUtil.getActiveLogin())) .createdOn(LocalDateTime.now(clock)) .type(type) .jurorNumber(jurorNumber) - .jurorRevision(jurorRevision.getRequiredRevisionNumber()) + .jurorRevision(revisionService.getLatestJurorRevisionNumber(jurorNumber)) .locCode(courtLocationCode) .courtLocationRevision(revisionService.getLatestCourtRevisionNumber(courtLocationCode)) .build(); diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorPaperResponseServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorPaperResponseServiceImpl.java index 2777fd249..5574de93a 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorPaperResponseServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorPaperResponseServiceImpl.java @@ -520,6 +520,7 @@ private void setUpReasonableAdjustments(PaperResponse jurorPaperResponse, Juror juror = jurorRepository.findByJurorNumber(jurorNumber); juror.setReasonableAdjustmentCode(type); juror.setReasonableAdjustmentMessage(message); + jurorPaperResponse.setReasonableAdjustmentsArrangements(message); }); diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorPoolService.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorPoolService.java index de40002ee..99c0f9cb1 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorPoolService.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorPoolService.java @@ -18,4 +18,6 @@ public interface JurorPoolService { JurorPool getJurorPoolFromUser(String jurorNumber); JurorPool getLastJurorPoolForJuror(String locCode, String jurorNumber); + + JurorPool save(JurorPool jurorPool); } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorPoolServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorPoolServiceImpl.java index 5532df7b5..60793a6e3 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorPoolServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorPoolServiceImpl.java @@ -66,6 +66,9 @@ public PaginatedList search(JurorPoolSearch search) { @Override public JurorPool getJurorPoolFromUser(String jurorNumber) { + if (!SecurityUtil.hasBureauJwtPayload() || SecurityUtil.isBureau() || SecurityUtil.isSystem()) { + return getLastActiveJurorPool(jurorNumber); + } return Optional.ofNullable(jurorPoolRepository.findByJurorJurorNumberAndIsActiveAndOwner( jurorNumber, true, SecurityUtil.getActiveOwner())) .orElseThrow(() -> new MojException.NotFound("Juror not found: " + jurorNumber, null)); @@ -87,7 +90,21 @@ public JurorPool getLastJurorPoolForJuror(String locCode, String jurorNumber) { throw new MojException.NotFound("Juror not found: " + jurorNumber, null); } + @Override + public JurorPool save(JurorPool jurorPool) { + return jurorPoolRepository.save(jurorPool); + } + private List getJurorPools(String locCode, String jurorNumber) { return jurorPoolRepository.findByPoolCourtLocationLocCodeAndJurorJurorNumber(locCode, jurorNumber); } + + private JurorPool getLastActiveJurorPool(String jurorNumber) { + List jurorPools = + jurorPoolRepository.findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(jurorNumber, true); + if (!jurorPools.isEmpty()) { + return jurorPools.get(0); + } + throw new MojException.NotFound("Juror not found: " + jurorNumber, null); + } } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorRecordServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorRecordServiceImpl.java index 65c425840..4e583f28f 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorRecordServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorRecordServiceImpl.java @@ -18,7 +18,6 @@ import uk.gov.hmcts.juror.api.bureau.service.BureauService; import uk.gov.hmcts.juror.api.config.bureau.BureauJwtPayload; import uk.gov.hmcts.juror.api.config.security.IsCourtUser; -import uk.gov.hmcts.juror.api.juror.controller.request.JurorResponseDto; import uk.gov.hmcts.juror.api.juror.domain.CourtLocation; import uk.gov.hmcts.juror.api.juror.domain.ProcessingStatus; import uk.gov.hmcts.juror.api.juror.domain.WelshCourtLocationRepository; @@ -190,6 +189,7 @@ public class JurorRecordServiceImpl implements JurorRecordService { private final WelshCourtLocationRepository welshCourtLocationRepository; private final JurorResponseAuditRepositoryMod jurorResponseAuditRepository; private final JurorPoolService jurorPoolService; + private final JurorThirdPartyService jurorThirdPartyService; @Override @Transactional @@ -225,6 +225,11 @@ public void editJurorDetails(BureauJwtPayload payload, EditJurorRecordRequestDto juror.setReasonableAdjustmentCode(null); juror.setReasonableAdjustmentMessage(null); } + if (requestDto.getThirdParty() == null) { + jurorThirdPartyService.deleteThirdParty(juror); + } else { + jurorThirdPartyService.createOrUpdateThirdParty(juror, requestDto.getThirdParty()); + } juror.setPendingTitle(requestDto.getPendingTitle()); juror.setPendingFirstName(requestDto.getPendingFirstName()); @@ -326,10 +331,6 @@ public JurorDetailsResponseDto getJurorDetails(BureauJwtPayload payload, String if (jurorResponse != null) { jurorDetailsResponseDto.setReplyMethod(REPLY_METHOD_ONLINE); jurorDetailsResponseDto.setReplyProcessingStatus(jurorResponse.getProcessingStatus().getDescription()); - // Todo keep this in for now but will need to revisit post UAT - if (jurorResponse.getThirdPartyFName() != null) { - jurorDetailsResponseDto.setThirdParty(getThirdPartyDetails(jurorResponse)); - } return jurorDetailsResponseDto; } @@ -338,7 +339,6 @@ public JurorDetailsResponseDto getJurorDetails(BureauJwtPayload payload, String jurorDetailsResponseDto.setReplyMethod(REPLY_METHOD_PAPER); jurorDetailsResponseDto.setReplyProcessingStatus(response.getProcessingStatus().getDescription()); } - return jurorDetailsResponseDto; } @@ -580,8 +580,7 @@ public void processPendingJuror(ProcessPendingJurorRequestDto processPendingJuro public void updateAttendance(UpdateAttendanceRequestDto dto) { log.info("Placing juror on call for juror {} ", dto.getJurorNumber()); - JurorPool jurorPool = JurorPoolUtils.getSingleActiveJurorPool(jurorPoolRepository, dto.getJurorNumber()); - + JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(dto.getJurorNumber()); validateUpdateAttendance(dto); if (dto.isOnCall()) { @@ -856,8 +855,7 @@ public String getJurorOpticReference(String jurorNumber, String poolNumber, Bure final String owner = payload.getOwner(); - JurorPool jurorPool = JurorPoolUtils.getActiveJurorPoolRecord( - jurorPoolRepository, jurorPoolService, jurorNumber); + JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(jurorNumber); // Bureau should always be able to read record JurorPoolUtils.checkReadAccessForCurrentUser(jurorPool, owner); @@ -1037,8 +1035,7 @@ public void processPendingNameChange(BureauJwtPayload payload, String jurorNumbe final String contactLogNotes = WordUtils.capitalize(requestDto.getDecision().getDescription()) + " the juror's name change. " + requestDto.getNotes(); - JurorPool jurorPool = JurorPoolUtils.getActiveJurorPoolRecord( - jurorPoolRepository, jurorPoolService, jurorNumber); + JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(jurorNumber); Juror juror = jurorPool.getJuror(); JurorUtils.checkOwnershipForCurrentUser(juror, payload.getOwner()); @@ -1085,30 +1082,11 @@ private void updateJurorNameDetails(String auditorUsername, JurorPool jurorPool, log.trace("Exit updateJurorNameDetails"); } - private JurorResponseDto.ThirdParty getThirdPartyDetails(DigitalResponse jurorResponse) { - - JurorResponseDto.ThirdParty thirdParty = new JurorResponseDto.ThirdParty(); - - thirdParty.setThirdPartyFName(jurorResponse.getThirdPartyFName()); - thirdParty.setThirdPartyLName(jurorResponse.getThirdPartyLName()); - thirdParty.setThirdPartyReason(jurorResponse.getThirdPartyReason()); - thirdParty.setThirdPartyOtherReason(jurorResponse.getThirdPartyOtherReason()); - thirdParty.setRelationship(jurorResponse.getRelationship()); - thirdParty.setMainPhone(jurorResponse.getMainPhone()); - thirdParty.setOtherPhone(jurorResponse.getOtherPhone()); - thirdParty.setEmailAddress(jurorResponse.getEmailAddress()); - thirdParty.setUseJurorEmailDetails(jurorResponse.getJurorEmailDetails()); - thirdParty.setUseJurorPhoneDetails(jurorResponse.getJurorPhoneDetails()); - - return thirdParty; - } - @Override @Transactional public PoliceCheckStatusDto updatePncStatus(final String jurorNumber, final PoliceCheck policeCheck) { log.info("Attempting to update PNC check status for juror {} to be {}", jurorNumber, policeCheck); - final JurorPool jurorPool = JurorPoolUtils.getActiveJurorPoolRecord( - jurorPoolRepository, jurorPoolService, jurorNumber); + final JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(jurorNumber); final Juror juror = jurorPool.getJuror(); final PoliceCheck oldPoliceCheckValue = juror.getPoliceCheck(); diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorThirdPartyService.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorThirdPartyService.java new file mode 100644 index 000000000..5e2d60df1 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorThirdPartyService.java @@ -0,0 +1,33 @@ +package uk.gov.hmcts.juror.api.moj.service; + +import uk.gov.hmcts.juror.api.moj.domain.Juror; + +public interface JurorThirdPartyService { + void deleteThirdParty(Juror juror); + + void createOrUpdateThirdParty(Juror juror, ThirdPartyUpdateDto thirdPartyUpdate); + + + interface ThirdPartyUpdateDto { + + String getThirdPartyOtherReason(); + + String getThirdPartyReason(); + + String getThirdPartyEmailAddress(); + + String getThirdPartyOtherPhone(); + + String getThirdPartyMainPhone(); + + String getThirdPartyRelationship(); + + String getThirdPartyLastName(); + + String getThirdPartyFirstName(); + + boolean isContactJurorByEmail(); + + boolean isContactJurorByPhone(); + } +} diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorThirdPartyServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorThirdPartyServiceImpl.java new file mode 100644 index 000000000..eef78d458 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/JurorThirdPartyServiceImpl.java @@ -0,0 +1,46 @@ +package uk.gov.hmcts.juror.api.moj.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import uk.gov.hmcts.juror.api.moj.domain.Juror; +import uk.gov.hmcts.juror.api.moj.domain.JurorThirdParty; +import uk.gov.hmcts.juror.api.moj.repository.juror.JurorThirdPartyRepository; +import uk.gov.hmcts.juror.api.moj.utils.DataUtils; + +@Service +@RequiredArgsConstructor(onConstructor = @__(@Autowired)) +public class JurorThirdPartyServiceImpl implements JurorThirdPartyService { + private final JurorThirdPartyRepository jurorThirdPartyRepository; + + @Override + @Transactional + public void deleteThirdParty(Juror juror) { + jurorThirdPartyRepository.deleteById(juror.getJurorNumber()); + juror.setThirdParty(null); + } + + @Override + @Transactional + public void createOrUpdateThirdParty(Juror juror, ThirdPartyUpdateDto thirdPartyUpdate) { + JurorThirdParty jurorThirdParty = getOrCreateJurorThirdParty(juror.getJurorNumber()); + jurorThirdParty.setFirstName(DataUtils.nullIfBlank(thirdPartyUpdate.getThirdPartyFirstName())); + jurorThirdParty.setLastName(DataUtils.nullIfBlank(thirdPartyUpdate.getThirdPartyLastName())); + jurorThirdParty.setRelationship(DataUtils.nullIfBlank(thirdPartyUpdate.getThirdPartyRelationship())); + jurorThirdParty.setMainPhone(DataUtils.nullIfBlank(thirdPartyUpdate.getThirdPartyMainPhone())); + jurorThirdParty.setOtherPhone(DataUtils.nullIfBlank(thirdPartyUpdate.getThirdPartyOtherPhone())); + jurorThirdParty.setEmailAddress(DataUtils.nullIfBlank(thirdPartyUpdate.getThirdPartyEmailAddress())); + jurorThirdParty.setReason(DataUtils.nullIfBlank(thirdPartyUpdate.getThirdPartyReason())); + jurorThirdParty.setOtherReason(DataUtils.nullIfBlank(thirdPartyUpdate.getThirdPartyOtherReason())); + jurorThirdParty.setContactJurorByEmail(thirdPartyUpdate.isContactJurorByEmail()); + jurorThirdParty.setContactJurorByPhone(thirdPartyUpdate.isContactJurorByPhone()); + + jurorThirdPartyRepository.save(jurorThirdParty); + } + + private JurorThirdParty getOrCreateJurorThirdParty(String jurorNumber) { + return jurorThirdPartyRepository.findById(jurorNumber) + .orElseGet(() -> new JurorThirdParty(jurorNumber)); + } +} diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/PoolStatisticsServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/PoolStatisticsServiceImpl.java index 489691c8a..84771d192 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/PoolStatisticsServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/PoolStatisticsServiceImpl.java @@ -42,7 +42,7 @@ public PoolSummaryResponseDto calculatePoolStatistics(String poolNumber) { populatePoolDetailsData(poolSummaryResponse, poolRequest); populateBureauSummoningData(poolSummaryResponse, poolStatistics, poolRequest.getNumberRequested()); populatePoolSummaryData(poolSummaryResponse, poolStatistics, poolRequest.getTotalNoRequired()); - populateAdditionalStatsData(poolSummaryResponse, poolStatistics); + populateAdditionalStatsData(poolSummaryResponse, poolStatistics, poolRequest); poolSummaryResponse.getPoolDetails().setCurrentOwner(poolRequest.getOwner()); @@ -113,10 +113,12 @@ private void populatePoolSummaryData(PoolSummaryResponseDto poolSummaryResponse, } private void populateAdditionalStatsData(PoolSummaryResponseDto poolSummaryResponse, - PoolStatistics poolStatistics) { + PoolStatistics poolStatistics, + PoolRequest poolRequest) { PoolSummaryResponseDto.AdditionalStatistics additionalStatistics = poolSummaryResponse.getAdditionalStatistics(); additionalStatistics.setCourtSupply(poolStatistics.getCourtSupply()); + additionalStatistics.setTotalJurorsInPool(poolRequest.getJurorPools().size()); } } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/ReissueLetterServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/ReissueLetterServiceImpl.java index 821eccd4e..f3e27b9b5 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/ReissueLetterServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/ReissueLetterServiceImpl.java @@ -125,8 +125,7 @@ private void printLetterFromFormCode(ReissueLetterRequestDto.@NotNull ReissueLet log.debug("Printing letter for juror number {} with form code {}", letter.getJurorNumber(), letter.getFormCode()); - JurorPool jurorPool = JurorPoolUtils.getActiveJurorPoolRecord( - jurorPoolRepository, jurorPoolService, letter.getJurorNumber()); + JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(letter.getJurorNumber()); BiConsumer letterPrinter = formCode.getLetterPrinter(); if (letterPrinter == null) { @@ -144,8 +143,7 @@ private void validateReissueRequest(ReissueLetterRequestDto request, ReissueLett request.getLetters().forEach(letter -> { FormCode formCode = FormCode.getFormCode(letter.getFormCode()); - JurorPool jurorPool = JurorPoolUtils.getActiveJurorPoolRecord( - jurorPoolRepository, jurorPoolService, letter.getJurorNumber()); + JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(letter.getJurorNumber()); JurorStatus jurorStatus = RepositoryUtils.retrieveFromDatabase( formCode.getJurorStatus(), jurorStatusRepository); @@ -301,8 +299,7 @@ private void createLetterHistory(ReissueLetterRequestDto.ReissueLetterRequestDat if (FormCode.ENG_SUMMONS_REMINDER.getCode().equals(letter.getFormCode()) || FormCode.BI_SUMMONS_REMINDER.getCode().equals(letter.getFormCode())) { - JurorPool jurorPool = JurorPoolUtils.getActiveJurorPoolRecord( - jurorPoolRepository, jurorPoolService, letter.getJurorNumber()); + JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(letter.getJurorNumber()); jurorPool.setReminderSent(true); if (Set.of("5228", "5228C").contains(letter.getFormCode())) { diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/RevisionService.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/RevisionService.java index 363f52399..b2e6d98de 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/RevisionService.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/RevisionService.java @@ -1,19 +1,8 @@ package uk.gov.hmcts.juror.api.moj.service; -import org.springframework.data.history.Revision; -import uk.gov.hmcts.juror.api.juror.domain.CourtLocation; -import uk.gov.hmcts.juror.api.moj.domain.Appearance; -import uk.gov.hmcts.juror.api.moj.domain.AppearanceId; -import uk.gov.hmcts.juror.api.moj.domain.Juror; - public interface RevisionService { - - Revision getLatestCourtRevision(String locCode); - Long getLatestCourtRevisionNumber(String locCode); - Revision getLatestJurorRevision(String jurorNumber); - - Revision getLatestAppearanceRevision(AppearanceId appearanceId); + Long getLatestJurorRevisionNumber(String jurorNumber); } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/RevisionServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/RevisionServiceImpl.java index 574ce3c83..c21865825 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/RevisionServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/RevisionServiceImpl.java @@ -3,14 +3,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.history.Revision; import org.springframework.stereotype.Service; -import uk.gov.hmcts.juror.api.juror.domain.CourtLocation; -import uk.gov.hmcts.juror.api.moj.domain.Appearance; -import uk.gov.hmcts.juror.api.moj.domain.AppearanceId; -import uk.gov.hmcts.juror.api.moj.domain.Juror; -import uk.gov.hmcts.juror.api.moj.exception.MojException; -import uk.gov.hmcts.juror.api.moj.repository.AppearanceRepository; import uk.gov.hmcts.juror.api.moj.repository.CourtLocationRepository; import uk.gov.hmcts.juror.api.moj.repository.JurorRepository; @@ -21,13 +14,6 @@ public class RevisionServiceImpl implements RevisionService { private final CourtLocationRepository courtLocationRepository; private final JurorRepository jurorRepository; - private final AppearanceRepository appearanceRepository; - - @Override - public Revision getLatestCourtRevision(String locCode) { - return courtLocationRepository.findLastChangeRevision(locCode) - .orElseThrow(() -> new MojException.NotFound("Court revision: " + locCode + " not found", null)); - } @Override public Long getLatestCourtRevisionNumber(String locCode) { @@ -35,14 +21,7 @@ public Long getLatestCourtRevisionNumber(String locCode) { } @Override - public Revision getLatestJurorRevision(String jurorNumber) { - return jurorRepository.findLastChangeRevision(jurorNumber) - .orElseThrow(() -> new MojException.NotFound("Juror revision: " + jurorNumber + " not found", null)); - } - - @Override - public Revision getLatestAppearanceRevision(AppearanceId appearanceId) { - return appearanceRepository.findLastChangeRevision(appearanceId) - .orElseThrow(() -> new MojException.NotFound("Appearance revision not found", null)); + public Long getLatestJurorRevisionNumber(String jurorNumber) { + return jurorRepository.getLatestRevision(jurorNumber); } } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/SummonsReplyStatusUpdateServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/SummonsReplyStatusUpdateServiceImpl.java index 9f907adf7..d2971434c 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/SummonsReplyStatusUpdateServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/SummonsReplyStatusUpdateServiceImpl.java @@ -1,12 +1,12 @@ package uk.gov.hmcts.juror.api.moj.service; import jakarta.persistence.EntityManager; -import jakarta.validation.constraints.NotNull; -import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -35,10 +35,10 @@ import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorReasonableAdjustmentRepository; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseAuditRepositoryMod; import uk.gov.hmcts.juror.api.moj.service.jurormanagement.JurorAuditChangeService; +import uk.gov.hmcts.juror.api.moj.service.summonsmanagement.JurorResponseService; import uk.gov.hmcts.juror.api.moj.utils.DataUtils; import uk.gov.hmcts.juror.api.moj.utils.JurorPoolUtils; import uk.gov.hmcts.juror.api.moj.utils.RepositoryUtils; -import uk.gov.hmcts.juror.api.validation.ValidationConstants; import java.time.LocalDateTime; import java.util.List; @@ -52,35 +52,19 @@ @RequiredArgsConstructor(onConstructor_ = {@Autowired}) @SuppressWarnings("PMD.CyclomaticComplexity") public class SummonsReplyStatusUpdateServiceImpl implements SummonsReplyStatusUpdateService, SummonsReplyMergeService { - public static final String COPY_RESPONSE_TO_GENERIC_JUROR_RESPONSE_POJO = "Juror: {}. Copying properties from {} " - + "to a generic juror response pojo"; - - @NonNull private final JurorPaperResponseRepositoryMod jurorPaperResponseRepository; - @NotNull private final JurorDigitalResponseRepositoryMod jurorDigitalResponseRepository; - @NonNull - private final JurorResponseAuditRepositoryMod auditRepository; - @NonNull private final AssignOnUpdateServiceMod assignOnUpdateService; - @NotNull private final EntityManager entityManager; - @NonNull private final JurorRepository jurorRepository; - @NonNull private final JurorPoolRepository jurorPoolRepository; - @NonNull private final JurorStatusRepository jurorStatusRepository; - @NonNull private final JurorHistoryRepository jurorHistoryRepository; - @NonNull private final JurorReasonableAdjustmentRepository jurorReasonableAdjustmentsRepository; - @NonNull private final WelshCourtLocationRepository welshCourtLocationRepository; - @NonNull private final JurorRecordService jurorRecordService; - @NonNull private final JurorAuditChangeService jurorAuditChangeService; + private final JurorThirdPartyService jurorThirdPartyService; private static final String TITLE = "title"; private static final String FIRST_NAME = "firstName"; @@ -88,11 +72,10 @@ public class SummonsReplyStatusUpdateServiceImpl implements SummonsReplyStatusUp private static final String PHONE_NO = "phoneNumber"; private static final String ALT_PHONE_NO = "altPhoneNumber"; private static final String EMAIL = "email"; - - private static final String ADDRESS = "address"; - - private static final String POSTCODE = "postcode"; private final JurorResponseAuditRepositoryMod jurorResponseAuditRepositoryMod; + @Autowired + @Lazy + JurorResponseService jurorResponseService; /** * Update the processing status of a Juror response within Juror Digital. @@ -283,6 +266,7 @@ private void mergeJurorResponseImplementation(AbstractJurorResponse jurorRespons // TODO - Processing a paper summons reply for a deceased juror is currently awaiting design/sign off Juror juror = jurorPool.getJuror(); + mergeThirdPartyDetails(jurorResponse, juror); // Check for changes between the new/updated values and the juror record values Map changedPropertiesMap = @@ -418,6 +402,69 @@ private void recordJurorPoolRespondedHistory(String jurorNumber, String auditorU log.trace("Exit recordJurorPoolResponseHistory"); } + private void mergeThirdPartyDetails(AbstractJurorResponse abstractJurorResponse, Juror juror) { + if (StringUtils.isNotBlank(abstractJurorResponse.getThirdPartyReason()) + || StringUtils.isNotBlank(abstractJurorResponse.getRelationship())) { + if (abstractJurorResponse instanceof DigitalResponse digitalResponse) { + jurorThirdPartyService.createOrUpdateThirdParty(juror, digitalResponse); + } else { + jurorThirdPartyService.createOrUpdateThirdParty(juror, + new JurorThirdPartyService.ThirdPartyUpdateDto() { + + @Override + public String getThirdPartyOtherReason() { + return null; + } + + @Override + public String getThirdPartyReason() { + return abstractJurorResponse.getThirdPartyReason(); + } + + @Override + public String getThirdPartyEmailAddress() { + return null; + } + + @Override + public String getThirdPartyOtherPhone() { + return null; + } + + @Override + public String getThirdPartyMainPhone() { + return null; + } + + @Override + public String getThirdPartyRelationship() { + return abstractJurorResponse.getRelationship(); + } + + @Override + public String getThirdPartyLastName() { + return null; + } + + @Override + public String getThirdPartyFirstName() { + return null; + } + + @Override + public boolean isContactJurorByEmail() { + return true; + } + + @Override + public boolean isContactJurorByPhone() { + return true; + } + }); + } + } + } + private void mergeReasonableAdjustments(JurorPool jurorPool) { final String multipleAdjustmentsCode = "M"; final String jurorNumber = jurorPool.getJurorNumber(); @@ -431,21 +478,12 @@ private void mergeReasonableAdjustments(JurorPool jurorPool) { Juror juror = jurorPool.getJuror(); if (reasonableAdjustments.size() > 1) { juror.setReasonableAdjustmentCode(multipleAdjustmentsCode); - juror.setReasonableAdjustmentMessage( - DataUtils.trimToLength( - reasonableAdjustments - .stream() - .reduce( - "", - (acc, item) -> acc + item.getReasonableAdjustmentDetail() + ", ", - String::concat - ).trim(), - ValidationConstants.REASONABLE_ADJUSTMENT_MESSAGE_LENGTH_MAX)); } else if (reasonableAdjustments.size() == 1 && reasonableAdjustments.get(0) != null) { juror.setReasonableAdjustmentCode(reasonableAdjustments.get(0).getReasonableAdjustment().getCode()); - juror.setReasonableAdjustmentMessage(reasonableAdjustments.get(0).getReasonableAdjustmentDetail()); } - + jurorResponseService.getCommonJurorResponseOptional(jurorNumber) + .ifPresent(abstractResponse -> + juror.setReasonableAdjustmentMessage(abstractResponse.getReasonableAdjustmentsArrangements())); jurorPoolRepository.save(jurorPool); log.trace("Juror: {}. Exit mergeReasonableAdjustments", jurorNumber); } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/deferralmaintenance/ManageDeferralsServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/deferralmaintenance/ManageDeferralsServiceImpl.java index ea6cda043..8a004b8b0 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/deferralmaintenance/ManageDeferralsServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/deferralmaintenance/ManageDeferralsServiceImpl.java @@ -174,8 +174,7 @@ public int useCourtDeferrals(PoolRequest newPool, int deferralsRequested, String public void processJurorDeferral(BureauJwtPayload payload, String jurorNumber, DeferralReasonRequestDto deferralReasonDto) { String auditorUsername = payload.getLogin(); - JurorPool jurorPool = JurorPoolUtils.getActiveJurorPoolRecord( - jurorPoolRepository, jurorPoolService, jurorNumber); + JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(jurorNumber); JurorPoolUtils.checkOwnershipForCurrentUser(jurorPool, payload.getOwner()); // if not empty then we need to move the juror to the active pool @@ -224,8 +223,7 @@ public void processJurorDeferral(BureauJwtPayload payload, String jurorNumber, public void changeJurorDeferralDate(BureauJwtPayload payload, String jurorNumber, DeferralReasonRequestDto deferralReasonDto) { String auditorUsername = payload.getLogin(); - JurorPool jurorPool = JurorPoolUtils.getActiveJurorPoolRecord( - jurorPoolRepository, jurorPoolService, jurorNumber); + JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(jurorNumber); JurorPoolUtils.checkOwnershipForCurrentUser(jurorPool, payload.getOwner()); // if not empty then we need to move the juror to the active pool @@ -293,8 +291,7 @@ public void allocateJurorsToActivePool(BureauJwtPayload payload, DeferralAllocat // Add deferred member to active pool log.trace("Juror {} - adding pool member to requested active pool", jurorNumber); - JurorPool jurorPool = JurorPoolUtils.getActiveJurorPoolRecord( - jurorPoolRepository, jurorPoolService, jurorNumber); + JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(jurorNumber); JurorPoolUtils.checkOwnershipForCurrentUser(jurorPool, payload.getOwner()); JurorPool newJurorPool = addMemberToNewPool(poolRequest, jurorPool, payload.getLogin(), @@ -319,8 +316,7 @@ public DeferralResponseDto processJurorPostponement(BureauJwtPayload payload, int countJurorsPostponed = 0; for (String jurorNumber : request.jurorNumbers) { // validation - JurorPool jurorPool = JurorPoolUtils.getActiveJurorPoolRecord( - jurorPoolRepository, jurorPoolService, jurorNumber); + JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(jurorNumber); JurorPoolUtils.checkOwnershipForCurrentUser(jurorPool, payload.getOwner()); if (jurorPool.getPoolNumber().equalsIgnoreCase(request.getPoolNumber())) { @@ -441,8 +437,7 @@ public DeferralOptionsDto findActivePoolsForDates(DeferralDatesRequestDto deferr log.trace("Juror {}: Enter findActivePoolsForDates", jurorNumber); String owner = payload.getOwner(); - JurorPool jurorPool = JurorPoolUtils.getActiveJurorPoolRecord( - jurorPoolRepository, jurorPoolService, jurorNumber); + JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(jurorNumber); JurorPoolUtils.checkOwnershipForCurrentUser(jurorPool, payload.getOwner()); String currentCourtLocation = jurorPool.getCourt().getLocCode(); @@ -555,8 +550,7 @@ public void deleteDeferral(BureauJwtPayload payload, String jurorNumber) { String customErrorMessage = String.format("Cannot find deferred record for juror number %s - ", jurorNumber); - JurorPool jurorPool = JurorPoolUtils.getActiveJurorPoolRecord( - jurorPoolRepository, jurorPoolService, jurorNumber); + JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(jurorNumber); JurorPoolUtils.checkOwnershipForCurrentUser(jurorPool, payload.getOwner()); Optional currentlyDeferred = currentlyDeferredRepository.findById(jurorNumber); diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/jurormanagement/JurorAppearanceServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/jurormanagement/JurorAppearanceServiceImpl.java index 3045ae3ac..1472e4a99 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/jurormanagement/JurorAppearanceServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/jurormanagement/JurorAppearanceServiceImpl.java @@ -26,13 +26,15 @@ import uk.gov.hmcts.juror.api.moj.domain.IJurorStatus; import uk.gov.hmcts.juror.api.moj.domain.Juror; import uk.gov.hmcts.juror.api.moj.domain.JurorPool; +import uk.gov.hmcts.juror.api.moj.domain.QAppearance; import uk.gov.hmcts.juror.api.moj.domain.trial.Panel; +import uk.gov.hmcts.juror.api.moj.domain.trial.QPanel; +import uk.gov.hmcts.juror.api.moj.domain.trial.QTrial; import uk.gov.hmcts.juror.api.moj.enumeration.AppearanceStage; import uk.gov.hmcts.juror.api.moj.enumeration.AttendanceType; import uk.gov.hmcts.juror.api.moj.enumeration.jurormanagement.JurorStatusGroup; import uk.gov.hmcts.juror.api.moj.enumeration.jurormanagement.RetrieveAttendanceDetailsTag; import uk.gov.hmcts.juror.api.moj.enumeration.jurormanagement.UpdateAttendanceStatus; -import uk.gov.hmcts.juror.api.moj.enumeration.trial.TrialType; import uk.gov.hmcts.juror.api.moj.exception.MojException; import uk.gov.hmcts.juror.api.moj.repository.AppearanceRepository; import uk.gov.hmcts.juror.api.moj.repository.CourtLocationRepository; @@ -544,12 +546,12 @@ public JurorsOnTrialResponseDto retrieveJurorsOnTrials(String locationCode, Loca for (Tuple tuple : jurorsOnTrialsTuples) { JurorsOnTrialResponseDto.JurorsOnTrialResponseData jurorsOnTrialData = JurorsOnTrialResponseDto.JurorsOnTrialResponseData.builder() - .trialNumber(tuple.get(0, String.class)) - .parties(tuple.get(1, String.class)) - .trialType(TrialType.valueOf(tuple.get(2, String.class)).getDescription()) - .courtroom(tuple.get(3, String.class)) - .judge(tuple.get(4, String.class)) - .totalJurors(tuple.get(5, Long.class)) + .trialNumber(tuple.get(QTrial.trial.trialNumber)) + .parties(tuple.get(QTrial.trial.description)) + .trialType(tuple.get(QTrial.trial.trialType).getDescription()) + .courtroom(tuple.get(QTrial.trial.courtroom.description)) + .judge(tuple.get(QTrial.trial.judge.name)) + .totalJurors(tuple.get(QPanel.panel.count())) .build(); jurorsOnTrialResponseDto.getTrialsList().add(jurorsOnTrialData); @@ -562,9 +564,9 @@ public JurorsOnTrialResponseDto retrieveJurorsOnTrials(String locationCode, Loca // update the response with the number of jurors attended jurorsOnTrialResponseDto.getTrialsList().forEach(jurorsOnTrialData -> { jurorsAttendanceCounts.forEach(tuple -> { - if (jurorsOnTrialData.getTrialNumber().equals(tuple.get(0, String.class))) { - jurorsOnTrialData.setNumberAttended(tuple.get(1, Long.class)); - jurorsOnTrialData.setAttendanceAudit(tuple.get(2, String.class)); + if (jurorsOnTrialData.getTrialNumber().equals(tuple.get(QPanel.panel.trial.trialNumber))) { + jurorsOnTrialData.setNumberAttended(tuple.get(QAppearance.appearance.jurorNumber.count())); + jurorsOnTrialData.setAttendanceAudit(tuple.get(QAppearance.appearance.attendanceAuditNumber)); } }); }); diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/letter/court/CourtLetterPrintServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/letter/court/CourtLetterPrintServiceImpl.java index 995d89667..262934d00 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/letter/court/CourtLetterPrintServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/letter/court/CourtLetterPrintServiceImpl.java @@ -279,7 +279,7 @@ private PrintLetterDataResponseDto createPrintLetterDataResponseDto(Tuple data, LocalDateTime attendanceTime = data.get(POOL_REQUEST.attendTime); builder.attendTime(attendanceTime != null ? attendanceTime.toLocalTime() - : null); + : data.get(COURT_LOCATION.courtAttendTime)); builder.date(formatDate(LocalDate.now(), welsh)); switch (dto.getLetterType()) { diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/service/trial/TrialServiceImpl.java b/src/main/java/uk/gov/hmcts/juror/api/moj/service/trial/TrialServiceImpl.java index 4c96911de..33924da89 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/service/trial/TrialServiceImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/service/trial/TrialServiceImpl.java @@ -206,8 +206,7 @@ public void returnPanel(BureauJwtPayload payload, String trialNo, String locCode // grabs the panel members from the DB and checks to make sure they match the requested members to be returned List panelList = panelRepository.findByTrialTrialNumberAndTrialCourtLocationLocCode(trialNo, locCode); - List panelMembersToReturn = getPanelMembersToReturn(null, IJurorStatus.PANEL, jurorDetailRequestDto, - panelList); + List panelMembersToReturn = getPanelMembersToReturn(jurorDetailRequestDto, panelList); log.debug(String.format("found %d panel members to be returned", panelMembersToReturn.size())); @@ -219,8 +218,10 @@ public void returnPanel(BureauJwtPayload payload, String trialNo, String locCode panelRepository.saveAndFlush(panel); JurorPool jurorPool = PanelUtils.getAssociatedJurorPool(jurorPoolRepository, panel); - jurorPool.setStatus(jurorStatus); - jurorPoolRepository.saveAndFlush(jurorPool); + if (jurorPool.getStatus().getStatus() == IJurorStatus.PANEL) { + jurorPool.setStatus(jurorStatus); + jurorPoolRepository.saveAndFlush(jurorPool); + } log.debug(String.format("updated juror trial record for juror %s", panel.getJurorNumber())); jurorHistoryService.createReturnFromPanelHistory(jurorPool, panel); @@ -236,8 +237,7 @@ public void returnJury(BureauJwtPayload payload, String trialNumber, String loca List panelList = panelRepository.findByTrialTrialNumberAndTrialCourtLocationLocCode(trialNumber, locationCode); - List juryMembersToBeReturned = getPanelMembersToReturn(PanelResult.JUROR, IJurorStatus.JUROR, - returnJuryDto.getJurors(), panelList); + List juryMembersToBeReturned = getPanelMembersToReturn(returnJuryDto.getJurors(), panelList); log.info(String.format("found %d jury members to be returned", juryMembersToBeReturned.size())); @@ -250,7 +250,8 @@ public void returnJury(BureauJwtPayload payload, String trialNumber, String loca final String jurorNumber = panel.getJurorNumber(); JurorPool jurorPool = PanelUtils.getAssociatedJurorPool(jurorPoolRepository, panel); - if (StringUtils.isNotEmpty(returnJuryDto.getCheckIn())) { + if (jurorPool.getStatus().getStatus() == IJurorStatus.JUROR + && StringUtils.isNotEmpty(returnJuryDto.getCheckIn())) { Appearance appearance = getJurorAppearanceForDate(jurorPool, returnJuryDto.getAttendanceDate(), locationCode); @@ -279,9 +280,12 @@ public void returnJury(BureauJwtPayload payload, String trialNumber, String loca panel.setReturnDate(LocalDate.now()); panelRepository.saveAndFlush(panel); - JurorStatus jurorStatus = new JurorStatus(); - jurorStatus.setStatus(IJurorStatus.RESPONDED); - jurorPool.setStatus(jurorStatus); + if (jurorPool.getStatus().getStatus() == IJurorStatus.JUROR + || jurorPool.getStatus().getStatus() == IJurorStatus.PANEL) { + JurorStatus jurorStatus = new JurorStatus(); + jurorStatus.setStatus(IJurorStatus.RESPONDED); + jurorPool.setStatus(jurorStatus); + } log.debug(String.format("updated juror trial record for juror %s", jurorNumber)); jurorHistoryService.createReturnFromPanelHistory(jurorPool, panel); @@ -316,15 +320,11 @@ public void endTrial(EndTrialDto dto) { trialRepository.save(trial); } - private List getPanelMembersToReturn(PanelResult panelResult, int jurorStatus, - List jurorList, List panelList) { + private List getPanelMembersToReturn(List jurorList, List panelList) { List panelMembersToReturn = new ArrayList<>(); for (Panel panel : panelList) { for (JurorDetailRequestDto dto : jurorList) { - if (dto.getJurorNumber().equals(panel.getJurorNumber()) - && panel.getResult() == panelResult - && PanelUtils.getAssociatedJurorPool(jurorPoolRepository, - panel).getStatus().getStatus() == jurorStatus) { + if (dto.getJurorNumber().equals(panel.getJurorNumber())) { panelMembersToReturn.add(panel); break; } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/utils/DataUtils.java b/src/main/java/uk/gov/hmcts/juror/api/moj/utils/DataUtils.java index 6f5752f04..9a63c4467 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/utils/DataUtils.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/utils/DataUtils.java @@ -143,4 +143,11 @@ public static String trim(String value) { } return value.trim(); } + + public static String nullIfBlank(String value) { + if (value == null || value.trim().isBlank()) { + return null; + } + return value.trim(); + } } diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/utils/JurorPoolUtils.java b/src/main/java/uk/gov/hmcts/juror/api/moj/utils/JurorPoolUtils.java index 167aee226..1b2acc77a 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/utils/JurorPoolUtils.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/utils/JurorPoolUtils.java @@ -9,7 +9,6 @@ import uk.gov.hmcts.juror.api.moj.exception.JurorRecordException; import uk.gov.hmcts.juror.api.moj.exception.MojException; import uk.gov.hmcts.juror.api.moj.repository.JurorPoolRepository; -import uk.gov.hmcts.juror.api.moj.service.JurorPoolService; import java.util.ArrayList; import java.util.List; @@ -137,7 +136,7 @@ public static List getActiveJurorPoolRecords(JurorPoolRepository juro * String jurorNumber) */ @Deprecated(forRemoval = true) - public static JurorPool getLatestActiveJurorPoolRecord(JurorPoolRepository jurorPoolRepository, + private static JurorPool getLatestActiveJurorPoolRecord(JurorPoolRepository jurorPoolRepository, String jurorNumber) { log.debug("Retrieving active juror records for juror number {}", jurorNumber); List jurorPools = @@ -152,15 +151,6 @@ public static JurorPool getLatestActiveJurorPoolRecord(JurorPoolRepository juror return jurorPools.get(0); } - public static JurorPool getActiveJurorPoolRecord(JurorPoolRepository jurorPoolRepository, - JurorPoolService jurorPoolService, - String jurorNumber) { - if (!SecurityUtil.hasBureauJwtPayload() || SecurityUtil.isBureau() || SecurityUtil.isSystem()) { - return getLatestActiveJurorPoolRecord(jurorPoolRepository, jurorNumber); - } - return jurorPoolService.getJurorPoolFromUser(jurorNumber); - } - /** * Reusable utility function to query the database and return the active juror pool association for a * given juror number and location. diff --git a/src/main/java/uk/gov/hmcts/juror/api/moj/utils/SecurityUtil.java b/src/main/java/uk/gov/hmcts/juror/api/moj/utils/SecurityUtil.java index 56fc7585d..ea237bd78 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/moj/utils/SecurityUtil.java +++ b/src/main/java/uk/gov/hmcts/juror/api/moj/utils/SecurityUtil.java @@ -172,7 +172,7 @@ public static boolean hasRole(Role role) { } public static boolean canEditApprovalLimit() { - return isAdministration() || isManager() && isCourt(); + return isAdministration(); } public static boolean isSystem() { diff --git a/src/main/java/uk/gov/hmcts/juror/api/validation/ResponseInspectorImpl.java b/src/main/java/uk/gov/hmcts/juror/api/validation/ResponseInspectorImpl.java index e0020a19b..4c17db043 100644 --- a/src/main/java/uk/gov/hmcts/juror/api/validation/ResponseInspectorImpl.java +++ b/src/main/java/uk/gov/hmcts/juror/api/validation/ResponseInspectorImpl.java @@ -2,20 +2,21 @@ import com.google.common.base.Strings; import lombok.NonNull; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.BooleanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.Assert; import uk.gov.hmcts.juror.api.bureau.domain.SystemParameter; import uk.gov.hmcts.juror.api.bureau.domain.SystemParameterRepository; import uk.gov.hmcts.juror.api.juror.domain.WelshCourtLocationRepository; import uk.gov.hmcts.juror.api.juror.notify.NotifyTemplateType; import uk.gov.hmcts.juror.api.moj.domain.JurorPool; import uk.gov.hmcts.juror.api.moj.domain.jurorresponse.DigitalResponse; -import uk.gov.hmcts.juror.api.moj.repository.JurorPoolRepository; +import uk.gov.hmcts.juror.api.moj.repository.JurorRepository; import uk.gov.hmcts.juror.api.moj.service.AppSettingService; +import uk.gov.hmcts.juror.api.moj.service.JurorPoolService; import java.time.LocalDate; import java.time.Period; @@ -23,6 +24,7 @@ @Component @Slf4j +@RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class ResponseInspectorImpl implements ResponseInspector { static final int AGE_LOWER_SP_ID = 101; static final int AGE_UPPER_SP_ID = 100; @@ -33,26 +35,11 @@ public class ResponseInspectorImpl implements ResponseInspector { public static final String DECEASED = "deceased"; private final SystemParameterRepository systemParameterRepository; - private final JurorPoolRepository jurorRepository; + private final JurorRepository jurorRepository; private final WelshCourtLocationRepository welshCourtLocRepository; private final AppSettingService appSettingService; - - @Autowired - public ResponseInspectorImpl(final SystemParameterRepository systemParameterRepository, - - final JurorPoolRepository jurorRepository, - final AppSettingService appSettingService, - final WelshCourtLocationRepository welshCourtLocRepository) { - Assert.notNull(systemParameterRepository, "SystemParameterRepository cannot be null."); - Assert.notNull(jurorRepository, "JurorRepository cannot be null."); - Assert.notNull(appSettingService, "AppSettingService cannot be null."); - Assert.notNull(welshCourtLocRepository, "WelshCourtLocationRepository cannot be null."); - this.systemParameterRepository = systemParameterRepository; - this.jurorRepository = jurorRepository; - this.appSettingService = appSettingService; - this.welshCourtLocRepository = welshCourtLocRepository; - } + private final JurorPoolService jurorPoolService; @Override public boolean isThirdPartyResponse(@NonNull final DigitalResponse response) { @@ -129,7 +116,7 @@ public NotifyTemplateType responseType(@NonNull final DigitalResponse response) @Override public boolean isJurorAgeDisqualified(final DigitalResponse response) { try { - final JurorPool jurorPool = jurorRepository.findByJurorJurorNumber(response.getJurorNumber()); + final JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(response.getJurorNumber()); int age = getJurorAgeAtHearingDate(response.getDateOfBirth(), jurorPool.getNextDate()); if (log.isTraceEnabled()) { log.trace( @@ -264,9 +251,7 @@ public int getTooOldJurorAge() { @Override public int getPoolNotification(final DigitalResponse response) { try { - // final Pool p = poolRepository.findByJurorNumber(response.getJurorNumber()); - final JurorPool jurorPool = jurorRepository.findByJurorJurorNumber(response.getJurorNumber()); - return jurorPool.getJuror().getNotifications(); + return jurorRepository.findByJurorNumber(response.getJurorNumber()).getNotifications(); } catch (Exception exception) { log.error("Failed to retrieve the pool.notification value for this juror response.", exception); return -1; @@ -277,7 +262,7 @@ public int getPoolNotification(final DigitalResponse response) { public boolean isWelshCourt(final DigitalResponse response) { boolean courtIsWelsh = false; try { - final JurorPool jurorPool = jurorRepository.findByJurorJurorNumber(response.getJurorNumber()); + final JurorPool jurorPool = jurorPoolService.getJurorPoolFromUser(response.getJurorNumber()); if (isWelshLanguage(response) && welshCourtLocRepository.findByLocCode(jurorPool.getCourt().getLocCode()) != null) { log.debug("Court (locCode) {} is Welsh.", jurorPool.getCourt().getLocCode()); diff --git a/src/main/resources/db/migrationv2/V2_23__message_template.sql b/src/main/resources/db/migrationv2/V2_23__message_template.sql new file mode 100644 index 000000000..f1eb90245 --- /dev/null +++ b/src/main/resources/db/migrationv2/V2_23__message_template.sql @@ -0,0 +1,23 @@ +update juror_mod.t_message_template +set text = 'Cysylltwch â Swyddfa Rheithgor drwy ffonio ynghylch eich gwasanaeth rheithgor.' +where id = 26; + +update juror_mod.t_message_template +set text = 'Nodyn Atgoffa: Cofiwch fynychu eich Gwasanaeth Rheithgor yn Llys ar am . Os oes gennych unrhyw gwestiynau, cysylltwch â''r swyddfa rheithgor drwy ffonio .' +where id = 18; + +update juror_mod.t_message_template +set text = 'Bu ichi fethu â mynychu eich Gwasanaeth Rheithgor yn Llys ar . Cysylltwch â''r Swyddfa Rheithgor drwy ffonio .' +where id = 19; + +update juror_mod.t_message_template +set text = 'Mae dyddiad mynychu eich Gwasanaeth Rheithgor wedi newid i am yn Llys . Mae''r dyddiau pan na fydd eich angen yn y llys dal yn ffurfio rhan o''ch gwasanaeth rheithgor ac ni fyddant yn cael eu hychwanegu ar y diwedd. Os oes gennych unrhyw gwestiynau, cysylltwch â''r swyddfa rheithgor drwy ffonio .' +where id = 20; + +update juror_mod.t_message_template +set text = 'Mae angen i chi fynychu''r llys eto ar gyfer eich Gwasanaeth Rheithgor ar am yn Llys . Os oes gennych unrhyw gwestiynau, cysylltwch â''r swyddfa rheithgor drwy ffonio .' +where id = 24; + +update juror_mod.t_message_template +set text = 'Rydych wedi cael eich dewis i fod yn rhan o banel a bydd Rheithgor yn cael ei ddewis o blith y panel hwnnw. Ewch i Lys ar am . Os oes gennych unrhyw gwestiynau, cysylltwch â''r swyddfa rheithgor drwy ffonio .' +where id = 28; \ No newline at end of file diff --git a/src/main/resources/db/migrationv2/V2_24__juror_third_party_details.sql b/src/main/resources/db/migrationv2/V2_24__juror_third_party_details.sql new file mode 100644 index 000000000..97a09a2cb --- /dev/null +++ b/src/main/resources/db/migrationv2/V2_24__juror_third_party_details.sql @@ -0,0 +1,32 @@ +CREATE TABLE juror_mod.juror_third_party ( + juror_number varchar(9) NOT NULL, + first_name varchar(50) NULL, + last_name varchar(50) NULL, + relationship varchar(50) NULL, + main_phone varchar(50) NULL, + other_phone varchar(50) NULL, + email_address varchar(254) NULL, + reason varchar(1250) NULL, + other_reason varchar(1250) NULL, + contact_juror_by_phone bool not NULL, + contact_juror_by_email bool not null, + CONSTRAINT juror_third_party_pk PRIMARY KEY (juror_number) +); + +CREATE TABLE juror_mod.juror_third_party_audit ( + revision int8 NOT NULL, + rev_type int4 NULL, + juror_number varchar(9) NOT NULL, + first_name varchar(50) NULL, + last_name varchar(50) NULL, + relationship varchar(50) NULL, + main_phone varchar(50) NULL, + other_phone varchar(50) NULL, + email_address varchar(254) NULL, + reason varchar(1250) NULL, + other_reason varchar(1250) NULL, + contact_juror_by_phone bool NULL, + contact_juror_by_email bool null, + CONSTRAINT juror_third_party_audit_pkey PRIMARY KEY (revision, juror_number), + CONSTRAINT juror_third_party_fk_revision_number FOREIGN KEY (revision) REFERENCES juror_mod.rev_info(revision_number) +); \ No newline at end of file diff --git a/src/main/resources/db/migrationv2/V2_25__require_pnc_batch_strip_double_space.sql b/src/main/resources/db/migrationv2/V2_25__require_pnc_batch_strip_double_space.sql new file mode 100644 index 000000000..14206ec8e --- /dev/null +++ b/src/main/resources/db/migrationv2/V2_25__require_pnc_batch_strip_double_space.sql @@ -0,0 +1,13 @@ +CREATE OR REPLACE VIEW juror_mod.require_pnc_check_view +AS SELECT j.police_check, + j.juror_number, + regexp_replace(j.first_name::text, '\s.*'::text, ''::text) AS first_name, + NULLIF(regexp_replace(j.first_name::text, '.*?\s'::text, ''::text), j.first_name::text) AS middle_name, + j.last_name, + j.dob AS date_of_birth, + upper(regexp_replace(j.postcode::text, '\s+'::text, ''::text)) AS post_code + FROM juror_mod.juror j + JOIN juror_mod.juror_pool jp ON jp.juror_number::text = j.juror_number::text + WHERE jp.status = 2 AND (j.police_check IS NULL OR (j.police_check::text <> ALL (ARRAY['UNCHECKED_MAX_RETRIES_EXCEEDED'::character varying::text, 'ELIGIBLE'::character varying::text, 'INELIGIBLE'::character varying::text]))) AND jp.owner::text = '400'::text AND jp.is_active = true + and upper(regexp_replace(j.postcode::text, '\s+'::text, ''::text)) ~ '^[A-Z0-9]{5,8}$' +; \ No newline at end of file diff --git a/src/main/resources/db/migrationv2/V2_26__bulk_print_data_notify_comms_blank_email_exclusion.sql b/src/main/resources/db/migrationv2/V2_26__bulk_print_data_notify_comms_blank_email_exclusion.sql new file mode 100644 index 000000000..0ad71ab26 --- /dev/null +++ b/src/main/resources/db/migrationv2/V2_26__bulk_print_data_notify_comms_blank_email_exclusion.sql @@ -0,0 +1,31 @@ +-- Create a View of the mod.bulk_print_data tables +DROP VIEW juror_mod.bulk_print_data_notify_comms; +create or replace view juror_mod.bulk_print_data_notify_comms ("id", "creation_date","form_type","detail_rec", "extracted_flag","juror_no","digital_comms", "template_id", "template_name", "notify_name", "h_email" ) AS +select + b.id, + b.creation_date, + b.form_type, + b.detail_rec, + b.extracted_flag, + b.juror_no, + b.digital_comms, + n.template_id, + n.template_name, + n.notify_name, + j.h_email +FROM + juror_mod.bulk_print_data b, + "juror_mod"."notify_template_mapping" n, + "juror_mod"."juror" j, + "juror_mod"."juror_pool" jp +WHERE + b.form_type = n.form_type + and b.juror_no = j.juror_number + and jp.juror_number = j.juror_number + and b.creation_date > (current_date - 3) + and b.digital_comms = false + and n.notification_type = 1 + and jp.owner = '400' + and jp.is_active = true + and j.h_email is not null + and length(trim(j.h_email)) > 0; \ No newline at end of file diff --git a/src/main/resources/db/migrationv2/V2_27__juror_audit_index.sql b/src/main/resources/db/migrationv2/V2_27__juror_audit_index.sql new file mode 100644 index 000000000..d70b1d190 --- /dev/null +++ b/src/main/resources/db/migrationv2/V2_27__juror_audit_index.sql @@ -0,0 +1 @@ +CREATE INDEX juror_audit_juror_number_idx ON juror_mod.juror_audit (juror_number); \ No newline at end of file diff --git a/src/test/java/uk/gov/hmcts/juror/api/TestUtils.java b/src/test/java/uk/gov/hmcts/juror/api/TestUtils.java index ff9df9f0d..8b8f91ded 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/TestUtils.java +++ b/src/test/java/uk/gov/hmcts/juror/api/TestUtils.java @@ -186,6 +186,9 @@ public static BureauJwtPayload mockBureauUser() { .roles(Set.of()) .userType(UserType.BUREAU) .activeUserType(UserType.BUREAU) + .staff(BureauJwtPayload.Staff.builder() + .courts(List.of("400")) + .build()) .build()); } diff --git a/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseDisqualifyServiceImplTest.java b/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseDisqualifyServiceImplTest.java index dd2c3e662..30da1bdc3 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseDisqualifyServiceImplTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseDisqualifyServiceImplTest.java @@ -23,6 +23,7 @@ import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorDigitalResponseRepositoryMod; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseAuditRepositoryMod; import uk.gov.hmcts.juror.api.moj.service.JurorHistoryService; +import uk.gov.hmcts.juror.api.moj.service.JurorPoolService; import uk.gov.hmcts.juror.api.moj.service.PrintDataService; import java.time.LocalDate; @@ -45,35 +46,28 @@ public class ResponseDisqualifyServiceImplTest { @Mock private JurorDigitalResponseRepositoryMod jurorResponseRepository; - @Mock private JurorResponseAuditRepositoryMod jurorResponseAuditRepository; - @Mock private JurorStatusRepository jurorStatusRepository; @Mock private JurorPoolRepository poolRepository; - @Mock private JurorHistoryService jurorHistoryService; - @Mock private DisqualifiedCodeRepository disqualifyCodeRepository; - @Mock private ResponseMergeService mergeService; - @Mock private EntityManager entityManager; - @Mock private UserRepository userRepository; - @Mock private AssignOnUpdateService assignOnUpdateService; - @Mock private PrintDataService printDataService; + @Mock + private JurorPoolService jurorPoolService; @InjectMocks private ResponseDisqualifyServiceImpl responseDisqualifyService; @@ -112,7 +106,7 @@ public void disqualifyJuror_happy() throws Exception { JurorPool poolDetails = mock(JurorPool.class); Juror juror = mock(Juror.class); when(poolDetails.getJuror()).thenReturn(juror); - given(poolRepository.findByJurorJurorNumber(any(String.class))).willReturn(poolDetails); + given(jurorPoolService.getJurorPoolFromUser(any(String.class))).willReturn(poolDetails); List disqualifyCodeEntityList = new ArrayList<>(); String disqualifyCode = "B"; diff --git a/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseExcusalServiceImplTest.java b/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseExcusalServiceImplTest.java index da5a6f3ca..a424a9f2e 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseExcusalServiceImplTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseExcusalServiceImplTest.java @@ -24,6 +24,7 @@ import uk.gov.hmcts.juror.api.moj.repository.UserRepository; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorDigitalResponseRepositoryMod; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseAuditRepositoryMod; +import uk.gov.hmcts.juror.api.moj.service.JurorPoolService; import uk.gov.hmcts.juror.api.moj.service.PrintDataService; import java.time.LocalDate; @@ -46,31 +47,26 @@ public class ResponseExcusalServiceImplTest { @Mock private JurorDigitalResponseRepositoryMod jurorResponseRepository; - @Mock private JurorResponseAuditRepositoryMod jurorResponseAuditRepository; - @Mock private JurorPoolRepository poolRepository; @Mock private JurorStatusRepository jurorStatusRepository; @Mock private JurorHistoryRepository partHistRepository; - @Mock private ExcusalCodeRepository excusalCodeRepository; - @Mock private ResponseMergeService mergeService; - @Mock private UserRepository userRepository; - @Mock private AssignOnUpdateService assignOnUpdateService; - @Mock private EntityManager entityManager; + @Mock + private JurorPoolService jurorPoolService; @InjectMocks private ResponseExcusalServiceImpl responseExcusalService; @@ -109,7 +105,7 @@ public void excuseJuror_happy() throws Exception { JurorPool poolDetails = mock(JurorPool.class); Juror juror = mock(Juror.class); when(poolDetails.getJuror()).thenReturn(juror); - given(poolRepository.findByJurorJurorNumber(any(String.class))).willReturn(poolDetails); + given(jurorPoolService.getJurorPoolFromUser(any(String.class))).willReturn(poolDetails); String excusalCode = "B"; List excusalCodeEntityList = new ArrayList<>(); @@ -241,7 +237,7 @@ public void rejectExcusalRequest_happy() throws Exception { JurorPool poolDetails = mock(JurorPool.class); Juror juror = mock(Juror.class); when(poolDetails.getJuror()).thenReturn(juror); - given(poolRepository.findByJurorJurorNumber(any(String.class))).willReturn(poolDetails); + given(jurorPoolService.getJurorPoolFromUser(any(String.class))).willReturn(poolDetails); String excusalCode = "B"; List excusalCodeEntityList = new ArrayList<>(); diff --git a/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdatePhoneNumberRulesTest.java b/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdatePhoneNumberRulesTest.java index 2c3f0eb65..1d2f750ef 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdatePhoneNumberRulesTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdatePhoneNumberRulesTest.java @@ -20,6 +20,7 @@ import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorDigitalResponseRepositoryMod; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorReasonableAdjustmentRepository; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseAuditRepositoryMod; +import uk.gov.hmcts.juror.api.moj.service.JurorPoolService; import java.util.ArrayList; import java.util.List; @@ -52,12 +53,12 @@ public class ResponseStatusUpdatePhoneNumberRulesTest { private EntityManager entityManager; @Mock private AssignOnUpdateService assignOnUpdateService; - @Mock private JurorReasonableAdjustmentRepository specialNeedsRepository; - @Mock private WelshCourtLocationRepository welshCourtLocationRepository; + @Mock + private JurorPoolService jurorPoolService; @InjectMocks private ResponseStatusUpdateServiceImpl statusUpdateService; @@ -78,7 +79,7 @@ public void setup() { PoolRequest poolRequest = new PoolRequest(); poolRequest.setPoolNumber(TestConstants.VALID_POOL_NUMBER); poolDetails.setPool(poolRequest); - doReturn(poolDetails).when(poolDetailsRepository).findByJurorJurorNumber(JUROR_NUMBER); + doReturn(poolDetails).when(jurorPoolService).getJurorPoolFromUser(JUROR_NUMBER); } diff --git a/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdateServiceImplTest.java b/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdateServiceImplTest.java index 5b2bf9d95..841096371 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdateServiceImplTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdateServiceImplTest.java @@ -22,6 +22,7 @@ import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorDigitalResponseRepositoryMod; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorReasonableAdjustmentRepository; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseAuditRepositoryMod; +import uk.gov.hmcts.juror.api.moj.service.JurorPoolService; import java.util.Optional; @@ -40,32 +41,26 @@ public class ResponseStatusUpdateServiceImplTest { @Mock JurorDigitalResponseRepositoryMod jurorResponseRepository; - @Mock JurorStatusRepository jurorStatusRepository; @Mock JurorResponseAuditRepositoryMod auditRepository; - @Mock JurorPoolRepository poolDetailsRepository; - @Mock JurorHistoryRepository partHistRepository; - @Mock EntityManager entityManager; - @Mock private UserRepository userRepository; - @Mock private AssignOnUpdateService assignOnUpdateService; - @Mock private JurorReasonableAdjustmentRepository specialNeedsRepository; - @Mock private WelshCourtLocationRepository welshCourtLocationRepository; + @Mock + private JurorPoolService jurorPoolService; @InjectMocks private ResponseStatusUpdateServiceImpl responseStatusUpdateService; @@ -209,7 +204,7 @@ public void updateResponse_closed_happy() throws Exception { given(jurorResponseRepository.findByJurorNumber(any(String.class))).willReturn(mockJurorResponse); given(mockJurorResponse.getJurorNumber()).willReturn(jurorNumber); given(mockJurorResponse.getProcessingStatus()).willReturn(currentProcessingStatus); - given(poolDetailsRepository.findByJurorJurorNumber(jurorNumber)).willReturn(mockPool); + given(jurorPoolService.getJurorPoolFromUser(jurorNumber)).willReturn(mockPool); User mockStaff = mock(User.class); given(mockJurorResponse.getStaff()).willReturn(mockStaff); @@ -228,7 +223,7 @@ public void updateResponse_closed_happy() throws Exception { // as we're setting the status to CLOSED, we should be merging data to Juror // and also setting RESPONDED to Y, so double the Pool interactions - verify(poolDetailsRepository, times(2)).findByJurorJurorNumber(jurorNumber); + verify(jurorPoolService, times(2)).getJurorPoolFromUser(jurorNumber); verify(poolDetailsRepository, times(3)).save(any(JurorPool.class)); verify(partHistRepository, times(2)).save(any(JurorHistory.class)); } diff --git a/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdateThirdPartyRulesTest.java b/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdateThirdPartyRulesTest.java index 98f5add8f..ebf5b3fb2 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdateThirdPartyRulesTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/bureau/service/ResponseStatusUpdateThirdPartyRulesTest.java @@ -17,6 +17,7 @@ import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorDigitalResponseRepositoryMod; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorReasonableAdjustmentRepository; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseAuditRepositoryMod; +import uk.gov.hmcts.juror.api.moj.service.JurorPoolService; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; @@ -58,6 +59,8 @@ public class ResponseStatusUpdateThirdPartyRulesTest { private JurorReasonableAdjustmentRepository specialNeedsRepository; @Mock private WelshCourtLocationRepository welshCourtLocationRepository; + @Mock + private JurorPoolService jurorPoolService; @InjectMocks private ResponseStatusUpdateServiceImpl statusUpdateService; @@ -92,7 +95,7 @@ public void setUp() { poolRequest = new PoolRequest(); poolDetails.setPool(poolRequest); poolDetails.getJuror().setJurorNumber(JUROR_NUMBER); - doReturn(poolDetails).when(poolDetailsRepository).findByJurorJurorNumber(JUROR_NUMBER); + doReturn(poolDetails).when(jurorPoolService).getJurorPoolFromUser(JUROR_NUMBER); } @Test diff --git a/src/test/java/uk/gov/hmcts/juror/api/juror/service/StraightThroughProcessorImplTest.java b/src/test/java/uk/gov/hmcts/juror/api/juror/service/StraightThroughProcessorImplTest.java index 7e3be3000..75b830e4a 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/juror/service/StraightThroughProcessorImplTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/juror/service/StraightThroughProcessorImplTest.java @@ -25,6 +25,7 @@ import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorDigitalResponseRepositoryMod; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseAuditRepositoryMod; import uk.gov.hmcts.juror.api.moj.service.JurorHistoryService; +import uk.gov.hmcts.juror.api.moj.service.JurorPoolService; import uk.gov.hmcts.juror.api.moj.service.PrintDataService; import uk.gov.hmcts.juror.api.moj.utils.JurorPoolUtils; import uk.gov.hmcts.juror.api.validation.ResponseInspectorImpl; @@ -46,35 +47,30 @@ /** * Unit test of {@link StraightThroughProcessorImpl}. */ -@SuppressWarnings({"Duplicates", "PMD.TooManyMethods"}) +@SuppressWarnings({"Duplicates", "PMD.TooManyMethods", "PMD.ExcessiveImports"}) @RunWith(MockitoJUnitRunner.class) public class StraightThroughProcessorImplTest { @Mock private JurorDigitalResponseRepositoryMod jurorResponseRepository; - @Mock private JurorResponseAuditRepositoryMod jurorResponseAuditRepository; - @Mock private JurorPoolRepository poolRepository; @Mock private JurorStatusRepository jurorStatusRepository; - @Mock private ResponseMergeService mergeService; - @Mock private JurorHistoryRepository partHistRepository; - @Mock private UserRepository userRepository; - @Mock private ResponseInspectorImpl responseInspector; - @Mock private JurorHistoryService jurorHistoryService; + @Mock + private JurorPoolService jurorPoolService; @InjectMocks private StraightThroughProcessorImpl straightThroughProcessor; @@ -107,7 +103,7 @@ public void setup() { jurorPool = mock(JurorPool.class); juror = mock(Juror.class); given(jurorPool.getJuror()).willReturn(juror); - given(poolRepository.findByJurorJurorNumber(TEST_JUROR_NUMBER)).willReturn(jurorPool); + given(jurorPoolService.getJurorPoolFromUser(TEST_JUROR_NUMBER)).willReturn(jurorPool); given(responseInspector.getYoungestJurorAgeAllowed()).willReturn(18); given(responseInspector.getTooOldJurorAge()).willReturn(76); diff --git a/src/test/java/uk/gov/hmcts/juror/api/moj/report/grouped/CompletionOfServiceReportTest.java b/src/test/java/uk/gov/hmcts/juror/api/moj/report/grouped/CompletionOfServiceReportTest.java index 8715c39fa..11417e897 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/moj/report/grouped/CompletionOfServiceReportTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/moj/report/grouped/CompletionOfServiceReportTest.java @@ -95,6 +95,7 @@ public void positivePreProcessQueryTypical(JPAQuery query, StandardReport verify(query).where(QJuror.juror.completionDate.between(DATE_FROM_TEST_VALUE, DATE_TO_TEST_VALUE)); verify(query).where(QJurorPool.jurorPool.pool.courtLocation.locCode.eq(VALID_COURT_LOCATION)); + verify(query).where(QJurorPool.jurorPool.isActive.isTrue()); verify(query).orderBy(QJuror.juror.jurorNumber.asc()); } diff --git a/src/test/java/uk/gov/hmcts/juror/api/moj/service/DeferralResponseServiceImplTest.java b/src/test/java/uk/gov/hmcts/juror/api/moj/service/DeferralResponseServiceImplTest.java index 6f84084c0..5ec940a91 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/moj/service/DeferralResponseServiceImplTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/moj/service/DeferralResponseServiceImplTest.java @@ -33,8 +33,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.any; -import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -145,8 +145,8 @@ public void test_denyDeferralRequest_happyPath_bureauUser_bureauOwner() { deferralResponseService.respondToDeferralRequest(payload, deferralRequestDto); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), anyBoolean()); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(any()); verify(jurorPoolRepository, times(1)).save(any()); verify(jurorHistoryRepository, times(2)).save(any()); @@ -167,8 +167,8 @@ public void test_denyDeferralRequest_bureauUser_courtOwner() { deferralResponseService.respondToDeferralRequest(payload, deferralRequestDto); }); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), anyBoolean()); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(any()); verify(jurorPoolRepository, never()).save(any()); verify(jurorHistoryRepository, never()).save(any()); @@ -205,11 +205,13 @@ public void test_denyDeferralRequest_noJurorRecord() { DeferralRequestDto deferralRequestDto = createTestDeferralRequestDto(jurorNumber); + doThrow(MojException.NotFound.class).when(jurorPoolService).getJurorPoolFromUser(jurorNumber); + Assertions.assertThatExceptionOfType(MojException.NotFound.class) .isThrownBy(() -> deferralResponseService.respondToDeferralRequest(payload, deferralRequestDto)); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), anyBoolean()); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(any()); verify(jurorPoolRepository, never()).save(any()); diff --git a/src/test/java/uk/gov/hmcts/juror/api/moj/service/ExcusalResponseServiceImplTest.java b/src/test/java/uk/gov/hmcts/juror/api/moj/service/ExcusalResponseServiceImplTest.java index 15b5e74fe..f389e8686 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/moj/service/ExcusalResponseServiceImplTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/moj/service/ExcusalResponseServiceImplTest.java @@ -38,6 +38,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -82,15 +83,9 @@ void setUpMocks() { JurorPool jurorPool400 = createTestJurorPool("400", "123456789"); Mockito.doReturn(jurorPool400) .when(jurorPoolService).getJurorPoolFromUser("123456789"); - Mockito.doReturn(Collections.singletonList(jurorPool400)) - .when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc("123456789", true); JurorPool jurorPool415 = createTestJurorPool("415", "987654321"); Mockito.doReturn(jurorPool415) .when(jurorPoolService).getJurorPoolFromUser("987654321"); - Mockito.doReturn(Collections.singletonList(jurorPool415)) - .when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc("987654321", true); Mockito.doReturn(Optional.of(createJurorStatus(1))).when(jurorStatusRepository).findById(1); Mockito.doReturn(Optional.of(createJurorStatus(2))).when(jurorStatusRepository).findById(2); @@ -116,8 +111,7 @@ void testRefuseExcusalRequestHappyPathPaperResponseBureauUserBureauOwner() { excusalResponseService.respondToExcusalRequest(payload, excusalDecisionDto, jurorNumber); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), Mockito.anyBoolean()); + verify(jurorPoolService, times(1)).getJurorPoolFromUser(any()); verify(jurorResponseService, times(1)).setResponseProcessingStatusToClosed(jurorNumber); verifyHappyRefuseJurorPoolPath(2, true); @@ -159,15 +153,14 @@ void testGrantExcusalRequestHappyPathPaperResponseBureauUserBureauOwner() { poolRequest.setPoolNumber("987654321"); jurorPool.setPool(new PoolRequest()); - Mockito.doReturn(List.of(jurorPool)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_NUMBER, true); + Mockito.doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(JUROR_NUMBER); TestUtils.mockBureauUser(); final BureauJwtPayload payload = TestUtils.createJwt("400", "SOME_USER"); excusalResponseService.respondToExcusalRequest(payload, excusalDecisionDto, JUROR_NUMBER); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), Mockito.anyBoolean()); + verify(jurorPoolService, times(1)).getJurorPoolFromUser(any()); verify(jurorResponseService, times(1)).setResponseProcessingStatusToClosed(JUROR_NUMBER); verifyHappyGrantJurorPoolPath(); @@ -201,8 +194,7 @@ void testRefuseExcusalRequestHappyPathDigitalResponseBureauUserBureauOwner() { excusalResponseService.respondToExcusalRequest(payload, excusalDecisionDto, JUROR_NUMBER); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), Mockito.anyBoolean()); + verify(jurorPoolService, times(1)).getJurorPoolFromUser(any()); verify(jurorResponseService, times(1)).setResponseProcessingStatusToClosed(JUROR_NUMBER); verifyHappyRefuseJurorPoolPath(2, true); @@ -246,13 +238,12 @@ void testGrantExcusalRequestHappyPathDigitalResponseBureauUserBureauOwner() { poolRequest.setPoolNumber("987654321"); jurorPool.setPool(new PoolRequest()); - Mockito.doReturn(List.of(jurorPool)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_NUMBER, true); + Mockito.doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(JUROR_NUMBER); excusalResponseService.respondToExcusalRequest(payload, excusalDecisionDto, JUROR_NUMBER); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), Mockito.anyBoolean()); + verify(jurorPoolService, times(1)).getJurorPoolFromUser(any()); verify(jurorResponseService, times(1)).setResponseProcessingStatusToClosed(JUROR_NUMBER); verifyHappyGrantJurorPoolPath(); @@ -295,13 +286,12 @@ void testGrantExcusalRequestHappyPathExcusalCodeDeceased() { poolRequest.setPoolNumber("987654321"); jurorPool.setPool(new PoolRequest()); - Mockito.doReturn(List.of(jurorPool)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_NUMBER, true); + Mockito.doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(JUROR_NUMBER); excusalResponseService.respondToExcusalRequest(payload, excusalDecisionDto, JUROR_NUMBER); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), Mockito.anyBoolean()); + verify(jurorPoolService, times(1)).getJurorPoolFromUser(any()); verifyHappyGrantJurorPoolPathNoLetter(); // deceased jurors don't get letters verifyHappyExcusalLetter(jurorPool, excusalDecisionDto); } @@ -317,8 +307,7 @@ void testExcusalRequestPaperResponseBureauUserCourtOwner() { .isThrownBy(() -> excusalResponseService.respondToExcusalRequest(payload, excusalDecisionDto, JUROR_NUMBER2)); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), Mockito.anyBoolean()); + verify(jurorPoolService, times(1)).getJurorPoolFromUser(any()); verifyFailedInitialChecksPath(); } @@ -355,15 +344,14 @@ void testExcusalRequestPaperResponseAlreadyClosed() { poolRequest.setPoolNumber("987654321"); jurorPool.setPool(new PoolRequest()); - Mockito.doReturn(List.of(jurorPool)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_NUMBER, true); + Mockito.doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(JUROR_NUMBER); TestUtils.mockBureauUser(); BureauJwtPayload payload = TestUtils.createJwt("400", "SOME_USER"); excusalResponseService.respondToExcusalRequest(payload, excusalDecisionDto, JUROR_NUMBER); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), Mockito.anyBoolean()); + verify(jurorPoolService, times(1)).getJurorPoolFromUser(any()); verifyHappyExcusalLetter(jurorPool, excusalDecisionDto); } @@ -386,13 +374,12 @@ void testExcusalRequestDigitalResponseAlreadyClosed() { poolRequest.setPoolNumber("987654321"); jurorPool.setPool(new PoolRequest()); - Mockito.doReturn(List.of(jurorPool)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_NUMBER, true); + Mockito.doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(JUROR_NUMBER); excusalResponseService.respondToExcusalRequest(payload, excusalDecisionDto, JUROR_NUMBER); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), Mockito.anyBoolean()); + verify(jurorPoolService, times(1)).getJurorPoolFromUser(any()); verifyHappyExcusalLetter(jurorPool, excusalDecisionDto); } @@ -439,12 +426,13 @@ void testExcusalRequestNoJurorRecord() { BureauJwtPayload payload = TestUtils.createJwt("400", "SOME_USER"); ExcusalDecisionDto excusalDecisionDto = createTestExcusalDecisionRequest(); + doThrow(MojException.NotFound.class).when(jurorPoolService) + .getJurorPoolFromUser(jurorNumber); Assertions.assertThatExceptionOfType(MojException.NotFound.class) .isThrownBy(() -> excusalResponseService.respondToExcusalRequest(payload, excusalDecisionDto, jurorNumber)); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), Mockito.anyBoolean()); + verify(jurorPoolService, times(1)).getJurorPoolFromUser(any()); verifyFailedInitialChecksPath(); } @@ -459,8 +447,7 @@ void testExcusalRequestPaperResponseDoesNotExist() { excusalResponseService.respondToExcusalRequest(payload, excusalDecisionDto, JUROR_NUMBER); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), Mockito.anyBoolean()); + verify(jurorPoolService, times(1)).getJurorPoolFromUser(any()); verify(jurorResponseService, times(1)).setResponseProcessingStatusToClosed(JUROR_NUMBER); } @@ -481,13 +468,12 @@ void testExcusalRequestWithoutResponseGrantBureauUserBureauOwner() { poolRequest.setPoolNumber("987654321"); jurorPool.setPool(new PoolRequest()); - Mockito.doReturn(List.of(jurorPool)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_NUMBER, true); + Mockito.doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(JUROR_NUMBER); excusalResponseService.respondToExcusalRequest(payload, excusalDecisionDto, JUROR_NUMBER); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), Mockito.anyBoolean()); + verify(jurorPoolService, times(1)).getJurorPoolFromUser(any()); verifyHappyGrantJurorPoolPath(); verifyHappyExcusalLetter(jurorPool, excusalDecisionDto); @@ -503,8 +489,7 @@ void testExcusalRequestWithoutResponseRefuseBureauUserBureauOwner() { excusalResponseService.respondToExcusalRequest(payload, excusalDecisionDto, JUROR_NUMBER); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), Mockito.anyBoolean()); + verify(jurorPoolService, times(1)).getJurorPoolFromUser(any()); verifyHappyRefuseJurorPoolPath(2, true); verifyHappyExcusalDeniedLetter(); @@ -566,8 +551,7 @@ void testExcusalRequestWithoutResponseGrantBureauUserCourtOwner() { excusalResponseService.respondToExcusalRequest(payload, excusalDecisionDto, JUROR_NUMBER2); }); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), Mockito.anyBoolean()); + verify(jurorPoolService, times(1)).getJurorPoolFromUser(any()); verifyFailedInitialChecksPath(); } diff --git a/src/test/java/uk/gov/hmcts/juror/api/moj/service/FinancialAuditServiceImplTest.java b/src/test/java/uk/gov/hmcts/juror/api/moj/service/FinancialAuditServiceImplTest.java index 8d741fa44..cbbebae44 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/moj/service/FinancialAuditServiceImplTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/moj/service/FinancialAuditServiceImplTest.java @@ -6,13 +6,11 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; -import org.springframework.data.history.Revision; import uk.gov.hmcts.juror.api.TestConstants; import uk.gov.hmcts.juror.api.juror.domain.CourtLocation; import uk.gov.hmcts.juror.api.moj.domain.Appearance; import uk.gov.hmcts.juror.api.moj.domain.FinancialAuditDetails; import uk.gov.hmcts.juror.api.moj.domain.FinancialAuditDetailsAppearances; -import uk.gov.hmcts.juror.api.moj.domain.Juror; import uk.gov.hmcts.juror.api.moj.domain.User; import uk.gov.hmcts.juror.api.moj.repository.AppearanceRepository; import uk.gov.hmcts.juror.api.moj.repository.FinancialAuditDetailsAppearancesRepository; @@ -89,10 +87,8 @@ void afterEach() { @Test void positiveTypical() { FinancialAuditDetails.Type type = FinancialAuditDetails.Type.APPROVED_CASH; - Revision jurorRevision = mock(Revision.class); - doReturn(jurorRevision).when(revisionService) - .getLatestJurorRevision(TestConstants.VALID_JUROR_NUMBER); - doReturn(1L).when(jurorRevision).getRequiredRevisionNumber(); + doReturn(1L).when(revisionService) + .getLatestJurorRevisionNumber(TestConstants.VALID_JUROR_NUMBER); doReturn(12L).when(revisionService) .getLatestCourtRevisionNumber(TestConstants.VALID_COURT_LOCATION); @@ -181,10 +177,8 @@ void positiveTypical() { @Test void positiveTypicalReApproval() { FinancialAuditDetails.Type type = FinancialAuditDetails.Type.REAPPROVED_BACS; - Revision jurorRevision = mock(Revision.class); - doReturn(jurorRevision).when(revisionService) - .getLatestJurorRevision(TestConstants.VALID_JUROR_NUMBER); - doReturn(1L).when(jurorRevision).getRequiredRevisionNumber(); + doReturn(1L).when(revisionService) + .getLatestJurorRevisionNumber(TestConstants.VALID_JUROR_NUMBER); doReturn(12L).when(revisionService) .getLatestCourtRevisionNumber(TestConstants.VALID_COURT_LOCATION); diff --git a/src/test/java/uk/gov/hmcts/juror/api/moj/service/JurorRecordServiceTest.java b/src/test/java/uk/gov/hmcts/juror/api/moj/service/JurorRecordServiceTest.java index 3ab70dd45..e94b0e5dd 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/moj/service/JurorRecordServiceTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/moj/service/JurorRecordServiceTest.java @@ -222,6 +222,8 @@ class JurorRecordServiceTest { private JurorPaymentsSummaryRepository jurorPaymentsSummaryRepository; @Mock private JurorPoolService jurorPoolService; + @Mock + private JurorThirdPartyService jurorThirdPartyService; @Mock private Clock clock; @@ -1578,11 +1580,7 @@ void testBureauGetJurorOverviewPoliceCheckStatusInProgress(PoliceCheck policeChe } private void setupBureauUser() { - TestUtils.mockSecurityUtil( - BureauJwtPayload.builder() - .locCode("400") - .build() - ); + TestUtils.mockBureauUser(); } @Test @@ -2195,18 +2193,15 @@ void testProcessPendingNameChangeRejected() { @Test void testProcessPendingNameChangeInvalidPermission() { - String courtOwner = "415"; String username = "COURT_USER"; String jurorNumber = "111111111"; TestUtils.mockBureauUser(); BureauJwtPayload payload = TestUtils.createJwt("416", username); - - JurorPool jurorPool = createValidJurorPool(jurorNumber, courtOwner); String notes = "Their name has not been legally changed"; ProcessNameChangeRequestDto dto = new ProcessNameChangeRequestDto(ApprovalDecision.REJECT, notes); - doReturn(jurorPool).when(jurorPoolService) + doThrow(MojException.NotFound.class).when(jurorPoolService) .getJurorPoolFromUser(jurorNumber); assertThatExceptionOfType(MojException.NotFound.class).isThrownBy(() -> @@ -2276,8 +2271,8 @@ void updateAttendanceHappyPathOnCall() { jurorPool.setOnCall(false); jurorPool.setNextDate(LocalDate.now().plusWeeks(1)); - doReturn(Collections.singletonList(jurorPool)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActive(jurorNumber, true); + doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(jurorNumber); jurorRecordService.updateAttendance(dto); @@ -2302,8 +2297,8 @@ void updateAttendanceHappyPathChangeNextDate() { jurorPool.setOnCall(false); jurorPool.setNextDate(LocalDate.now().plusWeeks(1)); - doReturn(Collections.singletonList(jurorPool)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActive(jurorNumber, true); + doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(jurorNumber); jurorRecordService.updateAttendance(dto); @@ -2350,8 +2345,8 @@ void updateAttendanceNoJurorPoolFound() { JurorPool jurorPool = createValidJurorPool(jurorNumber, courtOwner); jurorPool.setOnCall(false); - doReturn(Collections.singletonList(jurorPool)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActive(jurorNumber, true); + doThrow(MojException.NotFound.class).when(jurorPoolService) + .getJurorPoolFromUser(jurorNumberNotExist); assertThatExceptionOfType(MojException.NotFound.class).isThrownBy(() -> jurorRecordService.updateAttendance(dto)); @@ -2372,8 +2367,8 @@ void updateAttendanceJurorAlreadyOnCall() { JurorPool jurorPool = createValidJurorPool(jurorNumber, courtOwner); jurorPool.setOnCall(true); - doReturn(Collections.singletonList(jurorPool)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActive(jurorNumber, true); + doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(jurorNumber); assertThatExceptionOfType(MojException.BadRequest.class).isThrownBy(() -> jurorRecordService.updateAttendance(dto)); @@ -2438,8 +2433,8 @@ void beforeEach() { private JurorPool setupJurorPool(PoliceCheck policeCheck) { JurorPool jurorPool = createValidJurorPool(TestConstants.VALID_JUROR_NUMBER, "400"); jurorPool.getJuror().setPoliceCheck(policeCheck); - doReturn(List.of(jurorPool)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(TestConstants.VALID_JUROR_NUMBER, true); + doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(TestConstants.VALID_JUROR_NUMBER); return jurorPool; } @@ -2457,8 +2452,8 @@ void positiveStraightForwardUpdateOnly(PoliceCheck policeCheck) { jurorHistoryService, printDataService ); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(TestConstants.VALID_JUROR_NUMBER, true); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(TestConstants.VALID_JUROR_NUMBER); verify(jurorPoolRepository, times(1)).save(jurorPool); verify(jurorRepository, times(1)).save(jurorPool.getJuror()); verifyNoMoreInteractions(jurorPoolRepository, jurorRepository, jurorHistoryService, printDataService); @@ -2477,8 +2472,8 @@ void positiveNonMaxRetiesExceeded(PoliceCheck policeCheck) { verify(jurorHistoryService, times(1)) .createPoliceCheckQualifyHistory(jurorPool, false); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(TestConstants.VALID_JUROR_NUMBER, true); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(TestConstants.VALID_JUROR_NUMBER); verify(jurorPoolRepository, times(1)).save(jurorPool); verify(jurorRepository, times(1)).save(jurorPool.getJuror()); verify(printDataService, times(1)).printConfirmationLetter(jurorPool); @@ -2497,8 +2492,8 @@ void positiveEligible() { verify(jurorHistoryService, times(1)) .createPoliceCheckQualifyHistory(jurorPool, true); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(TestConstants.VALID_JUROR_NUMBER, true); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(TestConstants.VALID_JUROR_NUMBER); verify(jurorPoolRepository, times(1)).save(jurorPool); verify(jurorRepository, times(1)).save(jurorPool.getJuror()); verify(printDataService, times(1)).printConfirmationLetter(jurorPool); @@ -2518,8 +2513,8 @@ void positiveEligibleCourt() { verify(jurorHistoryService, times(1)) .createPoliceCheckQualifyHistory(jurorPool, true); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(TestConstants.VALID_JUROR_NUMBER, true); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(TestConstants.VALID_JUROR_NUMBER); verify(jurorPoolRepository, times(1)).save(jurorPool); verify(jurorRepository, times(1)).save(jurorPool.getJuror()); verifyNoMoreInteractions(jurorPoolRepository, jurorRepository, jurorHistoryService, printDataService); @@ -2549,8 +2544,8 @@ void positiveInEligible() { verify(jurorHistoryService, times(1)) .createWithdrawHistory(jurorPool, "Withdrawal Letter Auto", "E"); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(TestConstants.VALID_JUROR_NUMBER, true); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(TestConstants.VALID_JUROR_NUMBER); verify(jurorPoolRepository, times(1)).save(jurorPool); verify(jurorRepository, times(1)).save(jurorPool.getJuror()); verifyNoMoreInteractions(jurorPoolRepository, jurorRepository, jurorHistoryService, printDataService); @@ -2580,8 +2575,8 @@ void positiveInEligibleCourt() { .createPoliceCheckDisqualifyHistory(jurorPool); verifyNoMoreInteractions(printDataService); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(TestConstants.VALID_JUROR_NUMBER, true); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(TestConstants.VALID_JUROR_NUMBER); verify(jurorPoolRepository, times(1)).save(jurorPool); verify(jurorRepository, times(1)).save(jurorPool.getJuror()); verifyNoMoreInteractions(jurorPoolRepository, jurorRepository, jurorHistoryService, printDataService); @@ -2597,8 +2592,8 @@ void negativeNoUpdateOldAndSameMatch() { verifyNoInteractions(jurorHistoryService); verifyNoInteractions(printDataService); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(TestConstants.VALID_JUROR_NUMBER, true); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(TestConstants.VALID_JUROR_NUMBER); verifyNoMoreInteractions(jurorPoolRepository, jurorRepository, jurorHistoryService, printDataService); verifyNoInteractions(jurorRepository); } @@ -2617,8 +2612,8 @@ void positivePoliceCheckUpdateInProgress() { verify(jurorHistoryService, times(1)) .createPoliceCheckInProgressHistory(jurorPool); verifyNoMoreInteractions(jurorHistoryService); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(TestConstants.VALID_JUROR_NUMBER, true); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(TestConstants.VALID_JUROR_NUMBER); verify(jurorPoolRepository, times(1)).save(jurorPool); verify(jurorRepository, times(1)).save(jurorPool.getJuror()); verifyNoMoreInteractions(jurorPoolRepository, jurorRepository, jurorHistoryService, printDataService); @@ -2638,8 +2633,8 @@ void positivePoliceCheckUpdateInsufficientInformation() { verify(jurorHistoryService, times(1)) .createPoliceCheckInsufficientInformationHistory(jurorPool); verifyNoMoreInteractions(jurorHistoryService); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(TestConstants.VALID_JUROR_NUMBER, true); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(TestConstants.VALID_JUROR_NUMBER); verify(jurorPoolRepository, times(1)).save(jurorPool); verify(jurorRepository, times(1)).save(jurorPool.getJuror()); verifyNoMoreInteractions(jurorPoolRepository, jurorRepository, jurorHistoryService, printDataService); @@ -3691,8 +3686,6 @@ class GetJurorBankDetails { @Test void positiveTypical() { String courtOwner = "415"; - String username = "JURY_USER"; - TestUtils.mockCourtUser(courtOwner); Juror juror = new Juror(); diff --git a/src/test/java/uk/gov/hmcts/juror/api/moj/service/PoolRequestServiceTest.java b/src/test/java/uk/gov/hmcts/juror/api/moj/service/PoolRequestServiceTest.java index 59f1a54d7..fa7d7cb00 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/moj/service/PoolRequestServiceTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/moj/service/PoolRequestServiceTest.java @@ -379,7 +379,7 @@ public void test_savePoolRequest_newCourtOnlyPool_validCourt() { PoolRequestDto poolRequestDto = createValidPoolRequestDto(); poolRequestDto.setCourtOnly(true); - poolRequestDto.setAttendanceTime(null); + poolRequestDto.setAttendanceTime(LocalTime.of(10,11)); poolRequestDto.setNumberRequested(0); CourtLocation courtLocation = new CourtLocation(); @@ -418,8 +418,8 @@ public void test_savePoolRequest_newCourtOnlyPool_validCourt() { .as("Expect service start date to be mapped from request dto") .isEqualTo(poolRequestDto.getAttendanceDate()); assertThat(poolRequest.getAttendTime()) - .as("Expect attendance time not to be set") - .isNull(); + .as("Expect attendance time to be set") + .isEqualTo(LocalDateTime.of(poolRequestDto.getAttendanceDate(), poolRequestDto.getAttendanceTime())); assertThat(poolRequest.getNewRequest()) .as("Expect new request flag to be set to 'N' - pool request goes straight to created") .isEqualTo('N'); diff --git a/src/test/java/uk/gov/hmcts/juror/api/moj/service/PoolStatisticsServiceTest.java b/src/test/java/uk/gov/hmcts/juror/api/moj/service/PoolStatisticsServiceTest.java index 00e49101f..222723042 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/moj/service/PoolStatisticsServiceTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/moj/service/PoolStatisticsServiceTest.java @@ -17,6 +17,7 @@ import java.time.LocalDate; import java.time.format.DateTimeFormatter; +import java.util.ArrayList; import java.util.Optional; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; @@ -51,6 +52,7 @@ private PoolRequest initPoolRequest(String poolNumber, int numberRequested, int poolRequest.setCourtLocation(courtLocation); poolRequest.setNilPool(isNilPool); poolRequest.setPoolType(new PoolType("CIV", "Civil Court")); + poolRequest.setJurorPools(new ArrayList<>()); return poolRequest; } diff --git a/src/test/java/uk/gov/hmcts/juror/api/moj/service/RevisionServiceImplTest.java b/src/test/java/uk/gov/hmcts/juror/api/moj/service/RevisionServiceImplTest.java index fd1a4ee8c..5adf0e73c 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/moj/service/RevisionServiceImplTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/moj/service/RevisionServiceImplTest.java @@ -2,20 +2,11 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.data.history.Revision; import uk.gov.hmcts.juror.api.TestConstants; -import uk.gov.hmcts.juror.api.juror.domain.CourtLocation; -import uk.gov.hmcts.juror.api.moj.domain.AppearanceId; -import uk.gov.hmcts.juror.api.moj.domain.Juror; -import uk.gov.hmcts.juror.api.moj.exception.MojException; -import uk.gov.hmcts.juror.api.moj.repository.AppearanceRepository; import uk.gov.hmcts.juror.api.moj.repository.CourtLocationRepository; import uk.gov.hmcts.juror.api.moj.repository.JurorRepository; -import java.util.Optional; - import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -27,108 +18,46 @@ class RevisionServiceImplTest { private CourtLocationRepository courtLocationRepository; private JurorRepository jurorRepository; - private AppearanceRepository appearanceRepository; private RevisionServiceImpl revisionService; @BeforeEach void beforeEach() { this.courtLocationRepository = mock(CourtLocationRepository.class); this.jurorRepository = mock(JurorRepository.class); - this.appearanceRepository = mock(AppearanceRepository.class); this.revisionService = new RevisionServiceImpl( this.courtLocationRepository, - this.jurorRepository, - this.appearanceRepository + this.jurorRepository ); } @Test void positiveGetLatestCourtRevision() { - Revision revision = mock(Revision.class); - doReturn(Optional.of(revision)).when(courtLocationRepository) - .findLastChangeRevision(TestConstants.VALID_COURT_LOCATION); + long revision = 123L; + doReturn(revision).when(courtLocationRepository) + .getLatestRevision(TestConstants.VALID_COURT_LOCATION); assertThat( - revisionService.getLatestCourtRevision(TestConstants.VALID_COURT_LOCATION) + revisionService.getLatestCourtRevisionNumber(TestConstants.VALID_COURT_LOCATION) ).isEqualTo(revision); verify(courtLocationRepository, times(1)) - .findLastChangeRevision(TestConstants.VALID_COURT_LOCATION); + .getLatestRevision(TestConstants.VALID_COURT_LOCATION); verifyNoMoreInteractions(courtLocationRepository); } - @Test - void negativeGetLatestCourtRevisionNotFound() { - doReturn(Optional.empty()).when(courtLocationRepository) - .findLastChangeRevision(TestConstants.VALID_COURT_LOCATION); - - MojException.NotFound exception = assertThrows(MojException.NotFound.class, - () -> revisionService.getLatestCourtRevision(TestConstants.VALID_COURT_LOCATION), - "Expected exception to be thrown when court revision is not found"); - - assertThat(exception.getMessage()) - .isEqualTo("Court revision: " + TestConstants.VALID_COURT_LOCATION + " not found"); - assertThat(exception.getCause()).isNull(); - } @Test void positiveGetLatestJurorRevision() { - Revision revision = mock(Revision.class); - doReturn(Optional.of(revision)).when(jurorRepository) - .findLastChangeRevision(TestConstants.VALID_JUROR_NUMBER); + long revision = 123L; + doReturn(revision).when(jurorRepository) + .getLatestRevision(TestConstants.VALID_JUROR_NUMBER); assertThat( - revisionService.getLatestJurorRevision(TestConstants.VALID_JUROR_NUMBER) + revisionService.getLatestJurorRevisionNumber(TestConstants.VALID_JUROR_NUMBER) ).isEqualTo(revision); verify(jurorRepository, times(1)) - .findLastChangeRevision(TestConstants.VALID_JUROR_NUMBER); + .getLatestRevision(TestConstants.VALID_JUROR_NUMBER); verifyNoMoreInteractions(jurorRepository); } - - @Test - void negativeGetLatestJurorRevisionNotFound() { - doReturn(Optional.empty()).when(jurorRepository) - .findLastChangeRevision(TestConstants.VALID_JUROR_NUMBER); - - MojException.NotFound exception = assertThrows(MojException.NotFound.class, - () -> revisionService.getLatestJurorRevision(TestConstants.VALID_JUROR_NUMBER), - "Expected exception to be thrown when juror revision is not found"); - - assertThat(exception.getMessage()) - .isEqualTo("Juror revision: " + TestConstants.VALID_JUROR_NUMBER + " not found"); - assertThat(exception.getCause()).isNull(); - } - - - @Test - void positiveGetLatestAppearanceRevision() { - AppearanceId appearanceId = mock(AppearanceId.class); - Revision revision = mock(Revision.class); - doReturn(Optional.of(revision)).when(appearanceRepository) - .findLastChangeRevision(appearanceId); - - assertThat( - revisionService.getLatestAppearanceRevision(appearanceId) - ).isEqualTo(revision); - - verify(appearanceRepository, times(1)) - .findLastChangeRevision(appearanceId); - verifyNoMoreInteractions(appearanceRepository); - } - - @Test - void negativeGetLatestAppearanceRevisionNotFound() { - AppearanceId appearanceId = mock(AppearanceId.class); - doReturn(Optional.empty()).when(appearanceRepository) - .findLastChangeRevision(appearanceId); - - MojException.NotFound exception = assertThrows(MojException.NotFound.class, - () -> revisionService.getLatestAppearanceRevision(appearanceId), - "Expected exception to be thrown when appearance revision is not found"); - - assertThat(exception.getMessage()) - .isEqualTo("Appearance revision not found"); - assertThat(exception.getCause()).isNull(); - } } diff --git a/src/test/java/uk/gov/hmcts/juror/api/moj/service/SummonsReplyStatusUpdateServiceImplTest.java b/src/test/java/uk/gov/hmcts/juror/api/moj/service/SummonsReplyStatusUpdateServiceImplTest.java index c05f462e0..bf81282fb 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/moj/service/SummonsReplyStatusUpdateServiceImplTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/moj/service/SummonsReplyStatusUpdateServiceImplTest.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.juror.api.moj.service; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; @@ -34,6 +35,7 @@ import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorReasonableAdjustmentRepository; import uk.gov.hmcts.juror.api.moj.repository.jurorresponse.JurorResponseAuditRepositoryMod; import uk.gov.hmcts.juror.api.moj.service.jurormanagement.JurorAuditChangeService; +import uk.gov.hmcts.juror.api.moj.service.summonsmanagement.JurorResponseService; import java.text.ParseException; import java.time.LocalDate; @@ -54,6 +56,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; @RunWith(SpringRunner.class) @SuppressWarnings({"PMD.ExcessiveImports", "PMD.CouplingBetweenObjects"}) @@ -84,10 +87,21 @@ public class SummonsReplyStatusUpdateServiceImplTest { private JurorRecordService jurorRecordService; @Mock private JurorAuditChangeService jurorAuditChangeService; + @Mock + private JurorThirdPartyService jurorThirdPartyService; + @Mock + private JurorResponseService jurorResponseService; @InjectMocks private SummonsReplyStatusUpdateServiceImpl summonsReplyStatusUpdateService; + @Before + public void setUp() { + when(jurorResponseService.getCommonJurorResponseOptional(anyString())) + .thenReturn(Optional.empty()); + summonsReplyStatusUpdateService.jurorResponseService = jurorResponseService; + } + //Interface method: updateJurorResponseStatus @Test public void test_updateJurorResponseStatus_noResponseFound() { diff --git a/src/test/java/uk/gov/hmcts/juror/api/moj/service/deferralmaintenance/ManageDeferralsServiceTest.java b/src/test/java/uk/gov/hmcts/juror/api/moj/service/deferralmaintenance/ManageDeferralsServiceTest.java index 3c82ac238..7bc028d32 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/moj/service/deferralmaintenance/ManageDeferralsServiceTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/moj/service/deferralmaintenance/ManageDeferralsServiceTest.java @@ -81,6 +81,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -189,9 +190,9 @@ void processJurorPostponementHappyPathMoveToActivePoolPoliceChecked() { JurorStatus jurorStatus = new JurorStatus(); jurorStatus.setStatus(IJurorStatus.RESPONDED); - List jurorPools = createJurorPoolMember(JUROR_123456789); - doReturn(jurorPools).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_123456789, true); + JurorPool jurorPool = createJurorPool(JUROR_123456789); + doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(JUROR_123456789); doReturn(Optional.of(oldPoolRequest)).when(poolRequestRepository).findByPoolNumber(POOL_111111111); doReturn(Optional.of(jurorStatus)).when(jurorStatusRepository).findById(anyInt()); @@ -205,12 +206,12 @@ void processJurorPostponementHappyPathMoveToActivePoolPoliceChecked() { assertThat(response.getCountJurorsPostponed()).isEqualTo(1); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_123456789, true); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(JUROR_123456789); verify(jurorPoolRepository, times(2)).saveAndFlush(any()); verify(jurorPoolRepository, times(2)).save(any()); verify(jurorHistoryRepository, times(2)).save(any()); - verify(jurorHistoryService).createPostponementLetterHistory(jurorPools.get(0), ""); + verify(jurorHistoryService).createPostponementLetterHistory(jurorPool, ""); verify(poolRequestRepository, times(1)).findByPoolNumber(POOL_111111111); verify(poolRequestRepository, times(1)).findByPoolNumber(POOL_111111112); verify(poolMemberSequenceService, times(1)) @@ -242,11 +243,11 @@ void processJurorPostponementHappyPathMoveToActivePoolNotPoliceChecked() { JurorStatus jurorStatus = new JurorStatus(); jurorStatus.setStatus(IJurorStatus.RESPONDED); - List jurorPool = createJurorPoolMember(JUROR_123456789); - jurorPool.get(0).getJuror().setPoliceCheck(PoliceCheck.NOT_CHECKED); + JurorPool jurorPool = createJurorPool(JUROR_123456789); + jurorPool.getJuror().setPoliceCheck(PoliceCheck.NOT_CHECKED); - doReturn(jurorPool).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_123456789, true); + doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(JUROR_123456789); doReturn(Optional.of(oldPoolRequest)).when(poolRequestRepository).findByPoolNumber(POOL_111111111); doReturn(Optional.of(jurorStatus)).when(jurorStatusRepository).findById(anyInt()); @@ -258,12 +259,12 @@ void processJurorPostponementHappyPathMoveToActivePoolNotPoliceChecked() { assertThat(response.getCountJurorsPostponed()).isEqualTo(1); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_123456789, true); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(JUROR_123456789); verify(jurorPoolRepository, times(2)).saveAndFlush(any()); verify(jurorPoolRepository, times(2)).save(any()); verify(jurorHistoryRepository, times(2)).save(any()); - verify(jurorHistoryService).createPostponementLetterHistory(jurorPool.get(0), ""); + verify(jurorHistoryService).createPostponementLetterHistory(jurorPool, ""); verify(poolRequestRepository, times(1)).findByPoolNumber(POOL_111111111); verify(poolRequestRepository, times(1)).findByPoolNumber(POOL_111111112); verify(poolMemberSequenceService, times(1)) @@ -295,14 +296,13 @@ void processJurorPostponementHappyPathMoveToActivePoolMultipleJurors() { JurorStatus jurorStatus = new JurorStatus(); jurorStatus.setStatus(IJurorStatus.RESPONDED); - List jurorPools1 = createJurorPoolMember(JUROR_123456789); - doReturn(jurorPools1).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_123456789, true); + JurorPool jurorPool1 = createJurorPool(JUROR_123456789); + doReturn(jurorPool1).when(jurorPoolService) + .getJurorPoolFromUser(JUROR_123456789); - - List jurorPools2 = createJurorPoolMember(JUROR_111111111); - doReturn(jurorPools2).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_111111111, true); + JurorPool jurorPool2 = createJurorPool(JUROR_111111111); + doReturn(jurorPool2).when(jurorPoolService) + .getJurorPoolFromUser(JUROR_111111111); doReturn(Optional.of(oldPoolRequest)).when(poolRequestRepository).findByPoolNumber(POOL_111111111); doReturn(Optional.of(jurorStatus)).when(jurorStatusRepository).findById(anyInt()); @@ -320,13 +320,13 @@ void processJurorPostponementHappyPathMoveToActivePoolMultipleJurors() { assertThat(response.getCountJurorsPostponed()).isEqualTo(2); - verify(jurorPoolRepository, times(2)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), anyBoolean()); + verify(jurorPoolService, times(2)) + .getJurorPoolFromUser(any()); verify(jurorPoolRepository, times(4)).saveAndFlush(any()); verify(jurorPoolRepository, times(4)).save(any()); verify(jurorHistoryRepository, times(4)).save(any()); - verify(jurorHistoryService).createPostponementLetterHistory(jurorPools1.get(0), ""); - verify(jurorHistoryService).createPostponementLetterHistory(jurorPools2.get(0), ""); + verify(jurorHistoryService).createPostponementLetterHistory(jurorPool1, ""); + verify(jurorHistoryService).createPostponementLetterHistory(jurorPool2, ""); verify(poolRequestRepository, times(4)).findByPoolNumber(anyString()); verify(poolMemberSequenceService, times(2)) .getPoolMemberSequenceNumber(any(String.class)); @@ -343,8 +343,8 @@ void processJurorPostponementUnhappyPathInvalidReasonCode() { TestUtils.mockBureauUser(); final BureauJwtPayload bureauPayload = TestUtils.createJwt(BUREAU_OWNER, BUREAU_USER); - doReturn(createJurorPoolMember(JUROR_123456789)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_123456789, true); + doReturn(createJurorPool(JUROR_123456789)).when(jurorPoolService) + .getJurorPoolFromUser(JUROR_123456789); ProcessJurorPostponementRequestDto request = createProcessJurorRequestDto(); request.setExcusalReasonCode("C"); // setting an invalid reason code, should be "P" @@ -352,8 +352,8 @@ void processJurorPostponementUnhappyPathInvalidReasonCode() { assertThatExceptionOfType(MojException.BadRequest.class).isThrownBy(() -> manageDeferralsService.processJurorPostponement(bureauPayload, request)); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), anyBoolean()); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(any()); // make sure no letters are sent or deferral records created verify(printDataService, never()).printConfirmationLetter(any()); @@ -369,16 +369,15 @@ void processJurorPostponementUnhappyPathJurorNumberNotFound() { dto.setPoolNumber(POOL_111111111); dto.setExcusalReasonCode("P"); - List poolMembers = new ArrayList<>(); - doReturn(poolMembers).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_123456789, true); + doThrow(MojException.NotFound.class) + .when(jurorPoolService).getJurorPoolFromUser(JUROR_123456789); assertThatExceptionOfType(MojException.NotFound.class).isThrownBy(() -> manageDeferralsService.processJurorPostponement(bureauPayload, createProcessJurorRequestDto())); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), anyBoolean()); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(any()); // make sure no letters are sent or deferral records created verify(printDataService, never()).printConfirmationLetter(any()); @@ -391,15 +390,15 @@ void processJurorPostponementUnhappyPathPoolNumberNotFound() { TestUtils.mockBureauUser(); final BureauJwtPayload bureauPayload = TestUtils.createJwt(BUREAU_OWNER, BUREAU_USER); - doReturn(createJurorPoolMember(JUROR_123456789)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_123456789, true); + doReturn(createJurorPool(JUROR_123456789)).when(jurorPoolService) + .getJurorPoolFromUser(JUROR_123456789); doReturn(Optional.empty()).when(poolRequestRepository).findByPoolNumber(POOL_111111112); assertThatExceptionOfType(MojException.NotFound.class).isThrownBy(() -> manageDeferralsService.processJurorPostponement(bureauPayload, createProcessJurorRequestDto())); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), anyBoolean()); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(any()); verify(poolRequestRepository, times(1)).findByPoolNumber(anyString()); @@ -415,9 +414,9 @@ void processJurorPostponementHappyPathMoveToCurrentlyDeferred() { final BureauJwtPayload bureauPayload = TestUtils.createJwt(BUREAU_OWNER, BUREAU_USER, UserType.BUREAU, Collections.singletonList(Role.MANAGER)); - List jurorPools = createJurorPoolMember(JUROR_123456789); - doReturn(jurorPools).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_123456789, true); + JurorPool jurorPool = createJurorPool(JUROR_123456789); + doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(JUROR_123456789); DeferralResponseDto response = manageDeferralsService.processJurorPostponement(bureauPayload, createProcessJurorRequestDtoToCurrentlyDeferred()); @@ -427,7 +426,7 @@ void processJurorPostponementHappyPathMoveToCurrentlyDeferred() { verify(jurorPoolRepository, times(0)).saveAndFlush(any()); verify(jurorPoolRepository, times(2)).save(any()); verify(jurorHistoryRepository, times(1)).save(any()); - verify(jurorHistoryService).createPostponementLetterHistory(jurorPools.get(0), ""); + verify(jurorHistoryService).createPostponementLetterHistory(jurorPool, ""); verify(poolRequestRepository, times(0)).findByPoolNumber(anyString()); verify(poolMemberSequenceService, times(0)) .getPoolMemberSequenceNumber(any(String.class)); @@ -449,8 +448,8 @@ void processJurorPostponementUnhappyPathPostponeToExistingPoolNumber() { request.setExcusalReasonCode("P"); request.setPoolNumber(POOL_111111111); - doReturn(createJurorPoolMember(JUROR_123456789)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(JUROR_123456789, true); + doReturn(createJurorPool(JUROR_123456789)).when(jurorPoolService) + .getJurorPoolFromUser(JUROR_123456789); doReturn(Optional.empty()).when(poolRequestRepository).findByPoolNumber(POOL_111111111); MojException.BadRequest exception = @@ -460,8 +459,8 @@ void processJurorPostponementUnhappyPathPostponeToExistingPoolNumber() { assertEquals("Cannot postpone to the same pool", exception.getMessage(), "Message should match"); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), anyBoolean()); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(any()); // make sure no letters are sent or deferral records created verify(printDataService, never()).printConfirmationLetter(any()); @@ -469,14 +468,6 @@ void processJurorPostponementUnhappyPathPostponeToExistingPoolNumber() { verify(currentlyDeferredRepository, times(0)).save(any()); } - private List createJurorPoolMember(String jurorNumber) { - List poolMembers = new ArrayList<>(); - JurorPool member1 = createJurorPool(jurorNumber); - poolMembers.add(member1); - - return poolMembers; - } - private ProcessJurorPostponementRequestDto createProcessJurorRequestDto() { ProcessJurorPostponementRequestDto request = new ProcessJurorPostponementRequestDto(); request.setJurorNumbers(Collections.singletonList(JUROR_123456789)); @@ -526,10 +517,7 @@ void deleteDeferralHappyPathBureauUser() { String poolNumber = "987654321"; CurrentlyDeferred deferredRecord = createDeferredRecord("400", jurorNumber); - when(jurorPoolRepository.findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - any(), - anyBoolean() - )) + when(jurorPoolService.getJurorPoolFromUser(any())) .thenReturn(createDeferredJurorPools("400")); PoolRequest poolRequest = createPoolRequest(poolNumber, "415", LocalDate.now()); @@ -543,8 +531,8 @@ void deleteDeferralHappyPathBureauUser() { manageDeferralsService.deleteDeferral(bureauPayload, jurorNumber); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), anyBoolean()); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(any()); verify(currentlyDeferredRepository, times(1)).findById(any()); verify(jurorPoolRepository, times(1)).save(jurorPoolArgumentCaptor.capture()); @@ -568,7 +556,7 @@ void deleteDeferralDeferralNotFound() { String jurorNumber = "123456789"; String poolNumber = "987654321"; - when(jurorPoolRepository.findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(jurorNumber, true)) + when(jurorPoolService.getJurorPoolFromUser(jurorNumber)) .thenReturn(createDeferredJurorPools("400")); PoolRequest poolRequest = createPoolRequest(poolNumber, "415", LocalDate.now()); @@ -582,8 +570,8 @@ void deleteDeferralDeferralNotFound() { manageDeferralsService.deleteDeferral(bureauPayload, jurorNumber); }); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(any(), anyBoolean()); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(any()); verify(currentlyDeferredRepository, times(1)).findById(any()); verify(jurorPoolRepository, never()).save(any()); verify(currentlyDeferredRepository, never()).delete(any()); @@ -1323,8 +1311,8 @@ void test_findActivePoolsForDates_happyPath() { LocalDate.of(2023, 7, 3) )); - doReturn(Collections.singletonList(jurorPool)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(jurorNumber, true); + doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(jurorNumber); DeferralOptionsDto deferralOptionsDto = manageDeferralsService.findActivePoolsForDates(deferralDatesRequestDto, jurorNumber, payload); @@ -1442,9 +1430,8 @@ void test_findActivePoolsForDates_invalidAccess() { LocalDate.of(2023, 6, 16), LocalDate.of(2023, 7, 3))); - doReturn(Collections.singletonList(jurorPool)) - .when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(jurorNumber, true); + doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(jurorNumber); assertThatExceptionOfType(MojException.Forbidden.class).isThrownBy(() -> manageDeferralsService.findActivePoolsForDates( @@ -1509,9 +1496,8 @@ void test_findActivePoolsForDates_noDates() { DeferralDatesRequestDto deferralDatesRequestDto = new DeferralDatesRequestDto(); - doReturn(Collections.singletonList(jurorPool)) - .when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(jurorNumber, true); + doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(jurorNumber); DeferralOptionsDto deferralOptionsDto = manageDeferralsService.findActivePoolsForDates(deferralDatesRequestDto, jurorNumber, payload); @@ -1575,8 +1561,8 @@ void testFindActivePoolsForDatesAndLocationCodeHappyPath() { jurorPool.setJuror(juror); jurorPool.setPool(poolRequest); - doReturn(Collections.singletonList(jurorPool)).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(jurorNumber, true); + doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(jurorNumber); Tuple deferralOption = mock(Tuple.class); setUpMockQueryResult(deferralOption, @@ -1917,9 +1903,8 @@ void test_getPreferredDeferralDates_noDigitalResponse() { jurorPool.setOwner("400"); jurorPool.setJuror(juror); - doReturn(Collections.singletonList(jurorPool)) - .when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(jurorNumber, true); + doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(jurorNumber); doReturn(Optional.empty()).when(digitalResponseRepository).findById(jurorNumber); assertThatExceptionOfType(MojException.NotFound.class).isThrownBy(() -> @@ -1957,9 +1942,8 @@ void test_moveJurorsToActivePool_singleJuror() { int index = 0; for (String juror : jurorNumbers) { - doReturn(Collections.singletonList(poolMembers.get(index))) - .when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(eq(juror), eq(true)); + doReturn(poolMembers.get(index)).when(jurorPoolService) + .getJurorPoolFromUser(eq(juror)); doReturn(Optional.of(deferrals.get(index))) .when(currentlyDeferredRepository) .findById(juror); @@ -2020,9 +2004,8 @@ void test_moveJurorsToActivePool_multipleJuror() { int index = 0; for (String juror : jurorNumbers) { - doReturn(Collections.singletonList(poolMembers.get(index))) - .when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(eq(juror), eq(true)); + doReturn(poolMembers.get(index)).when(jurorPoolService) + .getJurorPoolFromUser(eq(juror)); doReturn(Optional.of(deferrals.get(index))) .when(currentlyDeferredRepository) .findById(juror); @@ -2063,9 +2046,8 @@ void test_moveJurorsToActivePool_poolRequestNotFound() { int index = 0; for (String juror : jurorNumbers) { - doReturn(Collections.singletonList(poolMembers.get(index))) - .when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(eq(juror), eq(true)); + doReturn(poolMembers.get(index)).when(jurorPoolService) + .getJurorPoolFromUser(eq(juror)); doReturn(Optional.of(deferrals.get(index))) .when(currentlyDeferredRepository) .findById(juror); @@ -2104,9 +2086,8 @@ void test_getDeferralsByCourtLocationCode() { int index = 0; for (String juror : courtJurors) { - doReturn(Collections.singletonList(poolMembers.get(index))) - .when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(eq(juror), eq(true)); + doReturn(poolMembers.get(index)).when(jurorPoolService) + .getJurorPoolFromUser(eq(juror)); doReturn(Optional.of(deferrals.get(index))) .when(currentlyDeferredRepository) .findById(juror); @@ -2588,9 +2569,7 @@ private List createDeferrals(String owner, String locCode, Li } - private List createDeferredJurorPools(String owner) { - final List jurorPools = new ArrayList<>(); - + private JurorPool createDeferredJurorPools(String owner) { PoolRequest poolRequest = new PoolRequest(); poolRequest.setPoolNumber("987654321"); @@ -2616,10 +2595,7 @@ private List createDeferredJurorPools(String owner) { jurorPool.setPool(poolRequest); juror.setAssociatedPools(Set.of(jurorPool)); - - jurorPools.add(jurorPool); - - return jurorPools; + return jurorPool; } private JurorPool createDeferredJuror(String owner) { diff --git a/src/test/java/uk/gov/hmcts/juror/api/moj/service/jurormanagement/JurorAppearanceServiceTest.java b/src/test/java/uk/gov/hmcts/juror/api/moj/service/jurormanagement/JurorAppearanceServiceTest.java index 49e346b65..33902e9f4 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/moj/service/jurormanagement/JurorAppearanceServiceTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/moj/service/jurormanagement/JurorAppearanceServiceTest.java @@ -36,6 +36,9 @@ import uk.gov.hmcts.juror.api.moj.domain.JurorStatus; import uk.gov.hmcts.juror.api.moj.domain.PoolRequest; import uk.gov.hmcts.juror.api.moj.domain.trial.Panel; +import uk.gov.hmcts.juror.api.moj.domain.trial.QCourtroom; +import uk.gov.hmcts.juror.api.moj.domain.trial.QPanel; +import uk.gov.hmcts.juror.api.moj.domain.trial.QTrial; import uk.gov.hmcts.juror.api.moj.domain.trial.Trial; import uk.gov.hmcts.juror.api.moj.enumeration.AppearanceStage; import uk.gov.hmcts.juror.api.moj.enumeration.AttendanceType; @@ -43,6 +46,7 @@ import uk.gov.hmcts.juror.api.moj.enumeration.jurormanagement.JurorStatusGroup; import uk.gov.hmcts.juror.api.moj.enumeration.jurormanagement.RetrieveAttendanceDetailsTag; import uk.gov.hmcts.juror.api.moj.enumeration.jurormanagement.UpdateAttendanceStatus; +import uk.gov.hmcts.juror.api.moj.enumeration.trial.TrialType; import uk.gov.hmcts.juror.api.moj.exception.MojException; import uk.gov.hmcts.juror.api.moj.repository.AppearanceRepository; import uk.gov.hmcts.juror.api.moj.repository.CourtLocationRepository; @@ -2870,12 +2874,12 @@ void jurorsOnTrialHappy() { doReturn(Optional.of(courtLocation)).when(courtLocationRepository).findById(locationCode); Tuple t1 = mock(Tuple.class); - doReturn("T10000000").when(t1).get(0, String.class); - doReturn("test defendants").when(t1).get(1, String.class); - doReturn("CIV").when(t1).get(2, String.class); - doReturn("Big Court Room").when(t1).get(3, String.class); - doReturn("Big Judge").when(t1).get(4, String.class); - doReturn(8L).when(t1).get(5, Long.class); + doReturn("T10000000").when(t1).get(QTrial.trial.trialNumber); + doReturn("test defendants").when(t1).get(QTrial.trial.description); + doReturn(TrialType.CIV).when(t1).get(QTrial.trial.trialType); + doReturn("Big Court Room").when(t1).get(QCourtroom.courtroom.description); + doReturn("Big Judge").when(t1).get(QTrial.trial.judge.name); + doReturn(8L).when(t1).get(QPanel.panel.count()); List jurorsOnTrialTuples = new ArrayList<>(); jurorsOnTrialTuples.add(t1); @@ -2884,8 +2888,8 @@ void jurorsOnTrialHappy() { .thenReturn(jurorsOnTrialTuples); Tuple t2 = mock(Tuple.class); - doReturn("T10000000").when(t2).get(0, String.class); - doReturn(6L).when(t2).get(1, Long.class); + doReturn("T10000000").when(t2).get(QTrial.trial.trialNumber); + doReturn("Trial Desc").when(t2).get(QTrial.trial.description); List jurorsOnTrialsAttended = new ArrayList<>(); jurorsOnTrialsAttended.add(t2); diff --git a/src/test/java/uk/gov/hmcts/juror/api/moj/service/letter/ReissueLetterServiceTest.java b/src/test/java/uk/gov/hmcts/juror/api/moj/service/letter/ReissueLetterServiceTest.java index 5c475d7ac..c53574000 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/moj/service/letter/ReissueLetterServiceTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/moj/service/letter/ReissueLetterServiceTest.java @@ -42,9 +42,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -458,9 +458,9 @@ void reissueDeferralLetterHappyPath(String formCode) { when(jurorStatusRepository.findById(IJurorStatus.DEFERRED)) .thenReturn(Optional.of(deferredStatus)); - List jurorPools = getJurorPools(deferredStatus); - when(jurorPoolRepository.findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(), true)).thenReturn(jurorPools); + JurorPool jurorPool = getJurorPool(deferredStatus); + when(jurorPoolService.getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber())) + .thenReturn(jurorPool); reissueLetterService.reissueLetter(reissueLetterRequestDto); @@ -473,9 +473,8 @@ void reissueDeferralLetterHappyPath(String formCode) { reissueLetterRequestData.getFormCode()); verify(jurorStatusRepository, times(1)).findById(IJurorStatus.DEFERRED); - verify(jurorPoolRepository, times(2)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(), true); + verify(jurorPoolService, times(2)) + .getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber()); } @ParameterizedTest @@ -506,13 +505,9 @@ void reissueWithdrawalLetterHappyPath(String formCode) { when(jurorStatusRepository.findById(IJurorStatus.DISQUALIFIED)) .thenReturn(Optional.of(withdrawalStatus)); - List jurorPools = getJurorPools(withdrawalStatus); - when(jurorPoolRepository.findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(),true)).thenReturn(jurorPools); - - doReturn(jurorPools).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(),true); + JurorPool jurorPool = getJurorPool(withdrawalStatus); + when(jurorPoolService.getJurorPoolFromUser( + reissueLetterRequestData.getJurorNumber())).thenReturn(jurorPool); reissueLetterService.reissueLetter(reissueLetterRequestDto); @@ -525,9 +520,8 @@ void reissueWithdrawalLetterHappyPath(String formCode) { reissueLetterRequestData.getFormCode()); verify(jurorStatusRepository, times(1)).findById(IJurorStatus.DISQUALIFIED); - verify(jurorPoolRepository, times(2)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(),true); + verify(jurorPoolService, times(2)) + .getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber()); } @ParameterizedTest @@ -551,9 +545,9 @@ void reissueLetterUnhappyAlreadyPending(String formCode) { when(jurorStatusRepository.findById(IJurorStatus.DEFERRED)) .thenReturn(Optional.of(deferredStatus)); - List jurorPools = getJurorPools(deferredStatus); - when(jurorPoolRepository.findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(),true)).thenReturn(jurorPools); + JurorPool jurorPool = getJurorPool(deferredStatus); + when(jurorPoolService.getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber())) + .thenReturn(jurorPool); doReturn(Optional.ofNullable(bulkPrintData)).when(bulkPrintDataRepository) .findByJurorNumberFormCodeDatePrinted(reissueLetterRequestData.getJurorNumber(), @@ -573,8 +567,8 @@ void reissueLetterUnhappyAlreadyPending(String formCode) { .findByJurorNumberFormCodeAndPending(reissueLetterRequestData.getJurorNumber(), reissueLetterRequestData.getFormCode()); verify(jurorStatusRepository, times(1)).findById(Mockito.anyInt()); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(Mockito.anyString(), anyBoolean()); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(Mockito.anyString()); } @@ -610,9 +604,9 @@ void reissueLetterUnhappyStatusChanged(String formCode) { .thenReturn(Optional.of(deferredStatus)); // Mock the status change from deferred to disqualified - List jurorPools = getJurorPools(disqualifiedStatus); - when(jurorPoolRepository.findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(),true)).thenReturn(jurorPools); + JurorPool jurorPool = getJurorPool(disqualifiedStatus); + when(jurorPoolService.getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber())) + .thenReturn(jurorPool); ReissueLetterReponseDto responseDto = reissueLetterService.reissueLetter(reissueLetterRequestDto); @@ -630,8 +624,8 @@ void reissueLetterUnhappyStatusChanged(String formCode) { .findByJurorNumberFormCodeAndPending(reissueLetterRequestData.getJurorNumber(), reissueLetterRequestData.getFormCode()); verify(jurorStatusRepository, times(1)).findById(Mockito.anyInt()); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(Mockito.anyString(),anyBoolean()); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(Mockito.anyString()); } @ParameterizedTest @@ -651,7 +645,8 @@ void reissueLetterUnhappyNotFound(String formCode) { doReturn(Optional.empty()).when(bulkPrintDataRepository) .findByJurorNumberFormCodeDatePrinted(reissueLetterRequestData.getJurorNumber(), reissueLetterRequestData.getFormCode(), reissueLetterRequestData.getDatePrinted()); - + doThrow(MojException.NotFound.class).when(jurorPoolService) + .getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber()); assertThatExceptionOfType(MojException.NotFound.class).isThrownBy(() -> reissueLetterService.reissueLetter(reissueLetterRequestDto)); @@ -662,8 +657,8 @@ void reissueLetterUnhappyNotFound(String formCode) { .findByJurorNumberFormCodeAndPending(reissueLetterRequestData.getJurorNumber(), reissueLetterRequestData.getFormCode()); verify(jurorStatusRepository, times(0)).findById(Mockito.anyInt()); - verify(jurorPoolRepository, times(1)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc(Mockito.anyString(), anyBoolean()); + verify(jurorPoolService, times(1)) + .getJurorPoolFromUser(Mockito.anyString()); } @ParameterizedTest @@ -698,8 +693,8 @@ void reissuePostponeLetterHappyPath(String formCode) { jurorPool.setStatus(postponedStatus); - when(jurorPoolRepository.findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(), true)).thenReturn(List.of(jurorPool)); + when(jurorPoolService.getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber())) + .thenReturn(jurorPool); reissueLetterService.reissueLetter(reissueLetterRequestDto); @@ -712,9 +707,8 @@ void reissuePostponeLetterHappyPath(String formCode) { reissueLetterRequestData.getFormCode()); verify(jurorStatusRepository, times(1)).findById(IJurorStatus.DEFERRED); - verify(jurorPoolRepository, times(2)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(), true); + verify(jurorPoolService, times(2)) + .getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber()); } @ParameterizedTest @@ -743,11 +737,11 @@ void reissueInitialSummonsLetterHappyPath(String formCode) { JurorStatus summoned = new JurorStatus(); summoned.setStatus(IJurorStatus.SUMMONED); when(jurorStatusRepository.findById(IJurorStatus.SUMMONED)) - .thenReturn(Optional.ofNullable(summoned)); + .thenReturn(Optional.of(summoned)); - List jurorPools = getJurorPools(summoned); - when(jurorPoolRepository.findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(), true)).thenReturn(jurorPools); + JurorPool jurorPool = getJurorPool(summoned); + when(jurorPoolService.getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber())) + .thenReturn(jurorPool); reissueLetterService.reissueLetter(reissueLetterRequestDto); @@ -760,9 +754,8 @@ void reissueInitialSummonsLetterHappyPath(String formCode) { reissueLetterRequestData.getFormCode()); verify(jurorStatusRepository, times(1)).findById(IJurorStatus.SUMMONED); - verify(jurorPoolRepository, times(2)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(), true); + verify(jurorPoolService, times(2)) + .getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber()); } @ParameterizedTest @@ -786,12 +779,11 @@ void reissueInitialSummonsReminderLetterHistory(String formCode) { when(jurorStatusRepository.findById(IJurorStatus.SUMMONED)) .thenReturn(Optional.of(summoned)); - List jurorPools = getJurorPools(summoned); + JurorPool jurorPool = getJurorPool(summoned); - doReturn(jurorPools).when(jurorPoolRepository).findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - "555555561", true); + doReturn(jurorPool).when(jurorPoolService).getJurorPoolFromUser("555555561"); - doNothing().when(jurorHistoryService).createSummonsReminderLetterHistory(jurorPools.get(0)); + doNothing().when(jurorHistoryService).createSummonsReminderLetterHistory(jurorPool); reissueLetterService.reissueLetter(reissueLetterRequestDto); @@ -804,11 +796,10 @@ void reissueInitialSummonsReminderLetterHistory(String formCode) { reissueLetterRequestData.getFormCode()); verify(jurorStatusRepository, times(1)).findById(IJurorStatus.SUMMONED); - verify(jurorPoolRepository, times(3)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(),true); + verify(jurorPoolService, times(3)) + .getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber()); verify(jurorHistoryService, times(1)) - .createSummonsReminderLetterHistory(jurorPools.get(0)); + .createSummonsReminderLetterHistory(jurorPool); } @@ -846,8 +837,8 @@ void reissueInformationLetterHappyPath(String formCode) { List jurorPools = new ArrayList<>(); jurorPools.add(jurorPool); - when(jurorPoolRepository.findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(),true)).thenReturn(jurorPools); + when(jurorPoolService.getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber())) + .thenReturn(jurorPool); reissueLetterService.reissueLetter(reissueLetterRequestDto); @@ -860,13 +851,12 @@ void reissueInformationLetterHappyPath(String formCode) { reissueLetterRequestData.getFormCode()); verify(jurorStatusRepository, times(1)).findById(IJurorStatus.SUMMONED); - verify(jurorPoolRepository, times(2)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(),true); + verify(jurorPoolService, times(2)) + .getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber()); } - private static List getJurorPools(JurorStatus status) { + private static JurorPool getJurorPool(JurorStatus status) { Juror juror = new Juror(); juror.setJurorNumber("555555561"); juror.setFirstName("John"); @@ -875,10 +865,7 @@ private static List getJurorPools(JurorStatus status) { JurorPool jurorPool = new JurorPool(); jurorPool.setJuror(juror); jurorPool.setStatus(status); - - List jurorPools = new ArrayList<>(); - jurorPools.add(jurorPool); - return jurorPools; + return jurorPool; } private static BulkPrintData getBulkPrintData( @@ -925,15 +912,14 @@ void reissueInitialSummonsReminderLetterHistoryNotImplementedForFormCode() { when(jurorStatusRepository.findById(IJurorStatus.SUMMONED)) .thenReturn(Optional.ofNullable(summoned)); - List jurorPools = getJurorPools(summoned); - when(jurorPoolRepository.findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc("555555561", true)) - .thenReturn(jurorPools); + JurorPool jurorPool = getJurorPool(summoned); + when(jurorPoolService.getJurorPoolFromUser("555555561")) + .thenReturn(jurorPool); - doReturn(jurorPools).when(jurorPoolRepository) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(),true); + doReturn(jurorPool).when(jurorPoolService) + .getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber()); - doNothing().when(jurorHistoryService).createSummonsReminderLetterHistory(jurorPools.get(0)); + doNothing().when(jurorHistoryService).createSummonsReminderLetterHistory(jurorPool); reissueLetterService.reissueLetter(reissueLetterRequestDto); @@ -946,9 +932,8 @@ void reissueInitialSummonsReminderLetterHistoryNotImplementedForFormCode() { reissueLetterRequestData.getFormCode()); verify(jurorStatusRepository, times(1)).findById(IJurorStatus.SUMMONED); - verify(jurorPoolRepository, times(2)) - .findByJurorJurorNumberAndIsActiveOrderByPoolReturnDateDesc( - reissueLetterRequestData.getJurorNumber(), true); + verify(jurorPoolService, times(2)) + .getJurorPoolFromUser(reissueLetterRequestData.getJurorNumber()); verifyNoMoreInteractions(jurorHistoryService); } } diff --git a/src/test/java/uk/gov/hmcts/juror/api/validation/ResponseInspectorImplTest.java b/src/test/java/uk/gov/hmcts/juror/api/validation/ResponseInspectorImplTest.java index ef3123025..c9e47f79f 100644 --- a/src/test/java/uk/gov/hmcts/juror/api/validation/ResponseInspectorImplTest.java +++ b/src/test/java/uk/gov/hmcts/juror/api/validation/ResponseInspectorImplTest.java @@ -18,6 +18,7 @@ import uk.gov.hmcts.juror.api.moj.domain.jurorresponse.DigitalResponse; import uk.gov.hmcts.juror.api.moj.repository.JurorPoolRepository; import uk.gov.hmcts.juror.api.moj.service.AppSettingService; +import uk.gov.hmcts.juror.api.moj.service.JurorPoolService; import java.time.LocalDate; import java.util.Optional; @@ -42,15 +43,14 @@ public class ResponseInspectorImplTest { @Mock private SystemParameterRepository mockSystemParameterRepository; - @Mock private JurorPoolRepository mockPoolRepository; - @Mock private AppSettingService mockAppSettingService; - @Mock private WelshCourtLocationRepository welshCourtLocationRepository; + @Mock + private JurorPoolService jurorPoolService; @InjectMocks private ResponseInspectorImpl inspector; @@ -193,7 +193,7 @@ public void isJurorAgeDisqualified_1day_too_young() { final DigitalResponse tooYoungJuror = new DigitalResponse(); tooYoungJuror.setJurorNumber(youngJurorNumber); tooYoungJuror.setDateOfBirth(hearingDate.minusYears(18).plusDays(1)); - given(mockPoolRepository.findByJurorJurorNumber(anyString())) + given(jurorPoolService.getJurorPoolFromUser(anyString())) .willReturn(JurorPool.builder() .juror(Juror.builder() .jurorNumber(TestConstants.VALID_JUROR_NUMBER) @@ -217,7 +217,7 @@ public void isJurorAgeDisqualified_18_exactly() { tooYoungJuror.setJurorNumber(youngJurorNumber); tooYoungJuror.setDateOfBirth(hearingDate.minusYears(18)); - when(mockPoolRepository.findByJurorJurorNumber(anyString())) + when(jurorPoolService.getJurorPoolFromUser(anyString())) .thenReturn(JurorPool.builder() .nextDate(hearingDate) .build()); @@ -236,7 +236,7 @@ public void isJurorAgeDisqualified_50_years_old() { final DigitalResponse tooYoungJuror = new DigitalResponse(); tooYoungJuror.setJurorNumber(youngJurorNumber); tooYoungJuror.setDateOfBirth(hearingDate.minusYears(50)); - given(mockPoolRepository.findByJurorJurorNumber(anyString())) + given(jurorPoolService.getJurorPoolFromUser(anyString())) .willReturn(JurorPool.builder() .nextDate(hearingDate) .build()); @@ -255,7 +255,7 @@ public void isJurorAgeDisqualified_too_old_exactly_76() { final DigitalResponse tooYoungJuror = new DigitalResponse(); tooYoungJuror.setJurorNumber(youngJurorNumber); tooYoungJuror.setDateOfBirth(hearingDate.minusYears(76)); - given(mockPoolRepository.findByJurorJurorNumber(anyString())) + given(jurorPoolService.getJurorPoolFromUser(anyString())) .willReturn(JurorPool.builder() .juror(Juror.builder().jurorNumber(TestConstants.VALID_JUROR_NUMBER).build()) .nextDate(hearingDate) @@ -278,7 +278,7 @@ public void isJurorAgeDisqualified_1_day_before_76th_birthday() { tooYoungJuror.setDateOfBirth(hearingDate.minusYears(76).plusDays(1) .plusDays(1)); - given(mockPoolRepository.findByJurorJurorNumber(anyString())) + given(jurorPoolService.getJurorPoolFromUser(anyString())) .willReturn(JurorPool.builder() .juror(Juror.builder().jurorNumber(TestConstants.VALID_JUROR_NUMBER).build()) .nextDate(hearingDate) @@ -519,7 +519,7 @@ public void isWelshCourtTrue() { jurorResponseEnglishLanguageDefault.setJurorNumber(jurorNumber); jurorResponseEnglishLanguageDefault.setWelsh(true); - given(mockPoolRepository.findByJurorJurorNumber(anyString())).willReturn(pool); + given(jurorPoolService.getJurorPoolFromUser(anyString())).willReturn(pool); given(welshCourtLocationRepository.findByLocCode(anyString())).willReturn(welshCourt); @@ -559,7 +559,7 @@ public void isWelshCourtFalse() { jurorResponseEnglishLanguageDefault.setWelsh(true); - given(mockPoolRepository.findByJurorJurorNumber(anyString())).willReturn(pool); + given(jurorPoolService.getJurorPoolFromUser(anyString())).willReturn(pool); given(welshCourtLocationRepository.findByLocCode(anyString())).willReturn(null);