diff --git a/pom.xml b/pom.xml index e803793be7..e26a315384 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ uk.gov.moj.cpp.common service-parent-pom - 17.103.5 + 17.103.11 uk.gov.moj.cpp.sjp @@ -46,14 +46,14 @@ 17.0.38 17.0.11 0.1.49 - 17.104.46 - 17.0.246 + 17.104.48 + 17.0.262 17.0.66 4.1.4-ATCM true file://${project.build.directory}/site 2.3.0 - 17.103.12 + 17.103.13 ${coredomain.version} 3.0.0 2.10 @@ -66,7 +66,7 @@ -Djava.locale.providers=CLDR 6.13 7.16.2 - 17.103.76 + 17.104.81 17.0.26 1.5.0 4.13.1 diff --git a/runIntegrationTests.sh b/runIntegrationTests.sh index 37cbb95417..c9fad01e39 100755 --- a/runIntegrationTests.sh +++ b/runIntegrationTests.sh @@ -12,7 +12,7 @@ DOCKER_CONTAINER_REGISTRY_HOST_NAME=crmdvrepo01 LIQUIBASE_COMMAND=update #LIQUIBASE_COMMAND=dropAll - +# #fail script on error set -e diff --git a/sjp-command/sjp-command-controller/src/main/java/uk/gov/moj/cpp/sjp/command/controller/ApplicationDecisionController.java b/sjp-command/sjp-command-controller/src/main/java/uk/gov/moj/cpp/sjp/command/controller/ApplicationDecisionController.java index 09bbe05430..f0a43ae9b2 100644 --- a/sjp-command/sjp-command-controller/src/main/java/uk/gov/moj/cpp/sjp/command/controller/ApplicationDecisionController.java +++ b/sjp-command/sjp-command-controller/src/main/java/uk/gov/moj/cpp/sjp/command/controller/ApplicationDecisionController.java @@ -1,6 +1,5 @@ package uk.gov.moj.cpp.sjp.command.controller; -import static javax.json.Json.createObjectBuilder; import static uk.gov.justice.services.core.annotation.Component.COMMAND_CONTROLLER; import static uk.gov.justice.services.messaging.JsonEnvelope.envelopeFrom; import static uk.gov.justice.services.messaging.JsonEnvelope.metadataFrom; diff --git a/sjp-command/sjp-command-controller/src/main/java/uk/gov/moj/cpp/sjp/command/controller/DecisionController.java b/sjp-command/sjp-command-controller/src/main/java/uk/gov/moj/cpp/sjp/command/controller/DecisionController.java index 02d2d46fb4..7dad081c04 100644 --- a/sjp-command/sjp-command-controller/src/main/java/uk/gov/moj/cpp/sjp/command/controller/DecisionController.java +++ b/sjp-command/sjp-command-controller/src/main/java/uk/gov/moj/cpp/sjp/command/controller/DecisionController.java @@ -5,7 +5,6 @@ import static java.util.Optional.ofNullable; import static java.util.UUID.randomUUID; import static javax.json.Json.createArrayBuilder; -import static javax.json.Json.createObjectBuilder; import static uk.gov.justice.services.core.annotation.Component.COMMAND_CONTROLLER; import static uk.gov.justice.services.core.enveloper.Enveloper.envelop; import static uk.gov.justice.services.messaging.JsonObjects.createObjectBuilder; diff --git a/sjp-command/sjp-command-handler/src/main/java/uk/gov/moj/cpp/sjp/command/handler/AcknowledgeDefendantDetailsUpdatesHandler.java b/sjp-command/sjp-command-handler/src/main/java/uk/gov/moj/cpp/sjp/command/handler/AcknowledgeDefendantDetailsUpdatesHandler.java index 3b35fb90ae..92f07b5096 100644 --- a/sjp-command/sjp-command-handler/src/main/java/uk/gov/moj/cpp/sjp/command/handler/AcknowledgeDefendantDetailsUpdatesHandler.java +++ b/sjp-command/sjp-command-handler/src/main/java/uk/gov/moj/cpp/sjp/command/handler/AcknowledgeDefendantDetailsUpdatesHandler.java @@ -53,7 +53,8 @@ public void acknowledgeDefendantDetailsUpdates( final ProsecutingAuthorityAccess currentUsersProsecutingAuthorityAccess = prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(command); final Stream events = caseAggregate - .acknowledgeDefendantDetailsUpdates(defendantId, clock.now(), currentUsersProsecutingAuthorityAccess.getProsecutingAuthority()); + .acknowledgeDefendantDetailsUpdates(defendantId, clock.now(), currentUsersProsecutingAuthorityAccess.getProsecutingAuthority(), + currentUsersProsecutingAuthorityAccess.getAgentProsecutorAuthorityAccess()); eventStream.append(events.map(enveloper.withMetadataFrom(command))); } diff --git a/sjp-command/sjp-command-handler/src/main/java/uk/gov/moj/cpp/sjp/command/handler/AddDatesToAvoidHandler.java b/sjp-command/sjp-command-handler/src/main/java/uk/gov/moj/cpp/sjp/command/handler/AddDatesToAvoidHandler.java index b79beb15be..a5be230319 100644 --- a/sjp-command/sjp-command-handler/src/main/java/uk/gov/moj/cpp/sjp/command/handler/AddDatesToAvoidHandler.java +++ b/sjp-command/sjp-command-handler/src/main/java/uk/gov/moj/cpp/sjp/command/handler/AddDatesToAvoidHandler.java @@ -23,7 +23,8 @@ public void addDatesToAvoid(final JsonEnvelope command) throws EventStreamExcept final JsonObject payload = command.payloadAsJsonObject(); final String datesToAvoid = payload.getString("datesToAvoid"); final ProsecutingAuthorityAccess prosecutingAuthorityAccess = prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(command); - applyToCaseAggregate(command, aggregate -> aggregate.addDatesToAvoid(datesToAvoid, prosecutingAuthorityAccess.getProsecutingAuthority())); + applyToCaseAggregate(command, aggregate -> aggregate.addDatesToAvoid(datesToAvoid, prosecutingAuthorityAccess.getProsecutingAuthority(), + prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess())); } @Handles("sjp.command.expire-dates-to-avoid-timer") diff --git a/sjp-command/sjp-command-handler/src/main/java/uk/gov/moj/cpp/sjp/command/handler/OffenceWithdrawalRequestHandler.java b/sjp-command/sjp-command-handler/src/main/java/uk/gov/moj/cpp/sjp/command/handler/OffenceWithdrawalRequestHandler.java index d76214b6e5..0874e4d250 100644 --- a/sjp-command/sjp-command-handler/src/main/java/uk/gov/moj/cpp/sjp/command/handler/OffenceWithdrawalRequestHandler.java +++ b/sjp-command/sjp-command-handler/src/main/java/uk/gov/moj/cpp/sjp/command/handler/OffenceWithdrawalRequestHandler.java @@ -53,7 +53,8 @@ public void setOffencesWithdrawalRequestsStatus(final Envelope agentProsecutorAuthorityAccess = List.of("TFL", "TVL"); final SetOffencesWithdrawalRequestsStatus requestsStatus = new SetOffencesWithdrawalRequestsStatus(caseId, requestPayload(offenceId_1, offenceId_2)); final UUID userId = randomUUID(); @@ -125,6 +126,7 @@ public void shouldHandleOffenceWithdrawalRequestCorrectly() throws EventStreamEx when(aggregateService.get(eventStream, CaseAggregate.class)).thenReturn(caseAggregate); when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(any())).thenReturn(prosecutingAuthorityAccess); when(prosecutingAuthorityAccess.getProsecutingAuthority()).thenReturn(prosecutionAuthority); + when(prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess()).thenReturn(agentProsecutorAuthorityAccess); final List offenceWithdrawalRequestsStatus = requestsStatus.getWithdrawalRequestsStatus().stream() @@ -134,7 +136,7 @@ public void shouldHandleOffenceWithdrawalRequestCorrectly() throws EventStreamEx ) .collect(Collectors.toList()); - when(caseAggregate.requestForOffenceWithdrawal(eq(requestsStatus.getCaseId()), eq(userId), eq(setAt), eq(offenceWithdrawalRequestsStatus), eq(prosecutionAuthority))) + when(caseAggregate.requestForOffenceWithdrawal(eq(requestsStatus.getCaseId()), eq(userId), eq(setAt), eq(offenceWithdrawalRequestsStatus), eq(prosecutionAuthority), eq(agentProsecutorAuthorityAccess))) .thenReturn(Stream.of(new OffencesWithdrawalRequestsStatusSet(caseId, setAt, userId, requestPayload(offenceId_1, offenceId_2)), new OffenceWithdrawalRequested(caseId, offenceId_1, withdrawalRequestReasonId, userId, setAt), new OffenceWithdrawalRequested(caseId, offenceId_2, withdrawalRequestReasonId, userId, setAt))); diff --git a/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/CaseAggregate.java b/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/CaseAggregate.java index 356fcee897..e598c73fba 100644 --- a/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/CaseAggregate.java +++ b/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/CaseAggregate.java @@ -223,8 +223,8 @@ public Stream updateHearingRequirements(final UUID userId, return apply(CaseLanguageHandler.INSTANCE.updateHearingRequirements(userId, defendantId, interpreterLanguage, speakWelsh, state, pleaMethod, createdOn)); } - public Stream addDatesToAvoid(final String datesToAvoid, final String userProsecutingAuthority) { - return applyAndResolveCaseReadiness(() -> CaseCoreHandler.INSTANCE.addDatesToAvoid(datesToAvoid, state, userProsecutingAuthority)); + public Stream addDatesToAvoid(final String datesToAvoid, final String userProsecutingAuthority, final List agentProsecutorAuthorityAccess) { + return applyAndResolveCaseReadiness(() -> CaseCoreHandler.INSTANCE.addDatesToAvoid(datesToAvoid, state, userProsecutingAuthority, agentProsecutorAuthorityAccess)); } public Stream expireDefendantResponseTimer() { @@ -258,9 +258,10 @@ public Stream markAsLegalSocChecked(final UUID caseId, final UUID checke public Stream acknowledgeDefendantDetailsUpdates( final UUID defendantId, final ZonedDateTime acknowledgedAt, - final String userProsecutingAuthority) { + final String userProsecutingAuthority, + final List agentProsecutorAuthorityAccess) { - return apply(CaseDefendantHandler.INSTANCE.acknowledgeDefendantDetailsUpdates(defendantId, acknowledgedAt, state, userProsecutingAuthority)); + return apply(CaseDefendantHandler.INSTANCE.acknowledgeDefendantDetailsUpdates(defendantId, acknowledgedAt, state, userProsecutingAuthority, agentProsecutorAuthorityAccess)); } public Stream updateDefendantDetails(final UUID userId, @@ -368,8 +369,10 @@ public Stream addCaseNote(final UUID caseId, final Note note, final User state)); } - public Stream requestForOffenceWithdrawal(final UUID caseId, final UUID setBy, final ZonedDateTime setAt, final List withdrawalRequestsStatus, final String prosecutionAuthority) { - return applyAndResolveCaseReadiness(() -> OffenceWithdrawalHandler.INSTANCE.requestOffenceWithdrawal(caseId, setBy, setAt, withdrawalRequestsStatus, state, prosecutionAuthority)); + public Stream requestForOffenceWithdrawal(final UUID caseId, final UUID setBy, final ZonedDateTime setAt, final List withdrawalRequestsStatus, + final String prosecutionAuthority, final List agentProsecutorAuthorityAccess) { + return applyAndResolveCaseReadiness(() -> OffenceWithdrawalHandler.INSTANCE.requestOffenceWithdrawal(caseId, setBy, setAt, withdrawalRequestsStatus, state, + prosecutionAuthority, agentProsecutorAuthorityAccess)); } public Stream setPleas(final UUID caseId, final SetPleas pleas, final UUID userId, final ZonedDateTime pleadAt) { diff --git a/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/CaseCoreHandler.java b/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/CaseCoreHandler.java index be3d27c7bb..a932cc56d9 100644 --- a/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/CaseCoreHandler.java +++ b/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/CaseCoreHandler.java @@ -135,14 +135,16 @@ public Stream updateCaseListedInCcForReferToCourt(final List addDatesToAvoid(final String datesToAvoid, - final CaseAggregateState state, final String userProsecutingAuthority) { + final CaseAggregateState state, final String userProsecutingAuthority, + final List agentProsecutorAuthorityAccess) { return createRejectionEvents( null, "Add dates to avoid", null, state, - userProsecutingAuthority + userProsecutingAuthority, + agentProsecutorAuthorityAccess ).orElse(Stream.of(state.getDatesToAvoid() == null ? new DatesToAvoidAdded(state.getCaseId(), datesToAvoid) : new DatesToAvoidUpdated(state.getCaseId(), datesToAvoid))); diff --git a/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/CaseDefendantHandler.java b/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/CaseDefendantHandler.java index 2da5b3abff..4111b32da0 100644 --- a/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/CaseDefendantHandler.java +++ b/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/CaseDefendantHandler.java @@ -31,6 +31,7 @@ import java.time.LocalDate; import java.time.ZonedDateTime; +import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; @@ -66,7 +67,8 @@ public Stream acknowledgeDefendantDetailsUpdates( final UUID defendantId, final ZonedDateTime acknowledgedAt, final CaseAggregateState state, - final String userProsecutingAuthority) { + final String userProsecutingAuthority, + final List agentProsecutorAuthorityAccess) { Object event; if (state.getCaseId() == null) { @@ -75,8 +77,19 @@ public Stream acknowledgeDefendantDetailsUpdates( } else if (defendantId != null && !state.hasDefendant(defendantId)) { LOGGER.warn("Defendant not found: {}", defendantId); event = new DefendantNotFound(defendantId, "Acknowledge defendant details updates"); - } else if (!(state.getProsecutingAuthority().toUpperCase().startsWith(userProsecutingAuthority) || "ALL".equalsIgnoreCase(userProsecutingAuthority))) { - event = new ProsecutionAuthorityAccessDenied(userProsecutingAuthority, state.getProsecutingAuthority()); + } else if (!(state.getProsecutingAuthority().toUpperCase().startsWith(userProsecutingAuthority) || + "ALL".equalsIgnoreCase(userProsecutingAuthority) || + (agentProsecutorAuthorityAccess != null && agentProsecutorAuthorityAccess.stream().anyMatch(s-> s.equalsIgnoreCase(state.getProsecutingAuthority()))))) { + + final List prosecutorAuthorityAccess = new ArrayList<>(); + + if(agentProsecutorAuthorityAccess != null && agentProsecutorAuthorityAccess.size() > 1) { + prosecutorAuthorityAccess.addAll(agentProsecutorAuthorityAccess); + } else { + prosecutorAuthorityAccess.add(userProsecutingAuthority); + } + + event = new ProsecutionAuthorityAccessDenied(state.getProsecutingAuthority(), prosecutorAuthorityAccess); } else { event = new DefendantDetailsUpdatesAcknowledged(state.getCaseId(), defendantId, acknowledgedAt); } diff --git a/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/HandlerUtils.java b/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/HandlerUtils.java index 5d21542f27..1af2d33d96 100644 --- a/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/HandlerUtils.java +++ b/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/HandlerUtils.java @@ -12,6 +12,7 @@ import uk.gov.moj.cpp.sjp.event.DefendantNotFound; import uk.gov.moj.cpp.sjp.event.OffenceNotFound; +import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; @@ -35,7 +36,8 @@ public static Optional> createRejectionEvents(final UUID userId, final String action, final UUID defendantId, final CaseAggregateState state, - final String userProsecutingAuthority) { + final String userProsecutingAuthority, // initial + final List agentProsecutorAuthorityAccess) { // new Object event = null; if (isNull(state.getCaseId())) { LOGGER.warn("Case not found: {}", action); @@ -52,8 +54,19 @@ public static Optional> createRejectionEvents(final UUID userId, } else if (state.isCaseReferredForCourtHearing()) { LOGGER.warn("Update rejected because case is referred to court for hearing: {}", action); event = new CaseUpdateRejected(state.getCaseId(), CaseUpdateRejected.RejectReason.CASE_REFERRED_FOR_COURT_HEARING); - } else if (!(state.getProsecutingAuthority().toUpperCase().startsWith(userProsecutingAuthority) || "ALL".equalsIgnoreCase(userProsecutingAuthority))) { - event = new ProsecutionAuthorityAccessDenied(userProsecutingAuthority, state.getProsecutingAuthority()); + } else if (!(state.getProsecutingAuthority().toUpperCase().startsWith(userProsecutingAuthority) || + "ALL".equalsIgnoreCase(userProsecutingAuthority) || + (agentProsecutorAuthorityAccess != null && agentProsecutorAuthorityAccess.stream().anyMatch(s-> s.equalsIgnoreCase(state.getProsecutingAuthority()))))) { + + final List prosecutorAuthorityAccess = new ArrayList<>(); + + if(agentProsecutorAuthorityAccess != null && agentProsecutorAuthorityAccess.size() > 1) { + prosecutorAuthorityAccess.addAll(agentProsecutorAuthorityAccess); + } else { + prosecutorAuthorityAccess.add(userProsecutingAuthority); + } + + event = new ProsecutionAuthorityAccessDenied(state.getProsecutingAuthority(), prosecutorAuthorityAccess); } return Optional.ofNullable(event).map(Stream::of); diff --git a/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/OffenceWithdrawalHandler.java b/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/OffenceWithdrawalHandler.java index 54880515b5..6b39cd0ec8 100644 --- a/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/OffenceWithdrawalHandler.java +++ b/sjp-domain/sjp-domain-aggregate/src/main/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/OffenceWithdrawalHandler.java @@ -24,10 +24,11 @@ public class OffenceWithdrawalHandler { private OffenceWithdrawalHandler() { } - public Stream requestOffenceWithdrawal(final UUID caseId, final UUID setBy, final ZonedDateTime setAt, final List withdrawalRequestsStatus, final CaseAggregateState state, final String prosecutionAuthority) { + public Stream requestOffenceWithdrawal(final UUID caseId, final UUID setBy, final ZonedDateTime setAt, final List withdrawalRequestsStatus, + final CaseAggregateState state, final String prosecutionAuthority, final List agentProsecutorAuthorityAccess) { return HandlerUtils. - createRejectionEvents(null, "Request Offence Withdrawal", null, state, prosecutionAuthority). + createRejectionEvents(null, "Request Offence Withdrawal", null, state, prosecutionAuthority, agentProsecutorAuthorityAccess). orElse(createWithdrawalEvents(caseId, setBy, setAt, withdrawalRequestsStatus, state)); } diff --git a/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/AddDatesToAvoidTest.java b/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/AddDatesToAvoidTest.java index 646326a0f5..c66cb101fc 100644 --- a/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/AddDatesToAvoidTest.java +++ b/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/AddDatesToAvoidTest.java @@ -15,7 +15,9 @@ import uk.gov.moj.cpp.sjp.event.CaseUpdateRejected; import uk.gov.moj.cpp.sjp.event.DatesToAvoidAdded; import uk.gov.moj.cpp.sjp.event.DatesToAvoidUpdated; +import uk.gov.moj.cpp.sjp.event.ProsecutionAuthorityAccessDenied; +import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; @@ -32,7 +34,7 @@ public class AddDatesToAvoidTest extends CaseAggregateBaseTest { @Test public void datesToAvoidAddedEvent() { //when - final List events = caseAggregate.addDatesToAvoid(DATES_TO_AVOID, ALL).collect(toList()); + final List events = caseAggregate.addDatesToAvoid(DATES_TO_AVOID, ALL, null).collect(toList()); final DatesToAvoidAdded datesToAvoidAdded = (DatesToAvoidAdded) events.get(0); //then @@ -45,7 +47,7 @@ public void raiseDatesToAvoidUpdatedEvent() { datesToAvoidAddedEvent(DATES_TO_AVOID); //when - final List datesToAvoidUpdatedEvents = caseAggregate.addDatesToAvoid(DATES_TO_AVOID_UPDATED, ALL).collect(toList()); + final List datesToAvoidUpdatedEvents = caseAggregate.addDatesToAvoid(DATES_TO_AVOID_UPDATED, ALL, null).collect(toList()); final DatesToAvoidUpdated datesToAvoidUpdated = (DatesToAvoidUpdated) datesToAvoidUpdatedEvents.get(0); //then @@ -65,7 +67,7 @@ private void assertThatDatesToAvoidUpdatedEventWasRaised(List datesToAvo } private DatesToAvoidAdded datesToAvoidAddedEvent(final String datesToAvoid) { - final List datesToAvoidAddedEvents = caseAggregate.addDatesToAvoid(datesToAvoid, ALL).collect(toList()); + final List datesToAvoidAddedEvents = caseAggregate.addDatesToAvoid(datesToAvoid, ALL, null).collect(toList()); return (DatesToAvoidAdded) datesToAvoidAddedEvents.get(0); } @@ -76,7 +78,7 @@ public void caseCompletedDoesNotAcceptDatesToAvoid() { AggregateHelper.saveDecision(caseAggregate, aCase, session, VerdictType.FOUND_NOT_GUILTY); //when - final List events = caseAggregate.addDatesToAvoid(DATES_TO_AVOID, ALL).collect(toList()); + final List events = caseAggregate.addDatesToAvoid(DATES_TO_AVOID, ALL, null).collect(toList()); //then assertThat(events, hasSize(1)); @@ -91,7 +93,7 @@ public void caseAssignedDoesNotAcceptDatesToAvoid() { caseAggregate.assignCase(randomUUID(), clock.now(), CaseAssignmentType.DELEGATED_POWERS_DECISION); //when - final List events = caseAggregate.addDatesToAvoid(DATES_TO_AVOID, ALL).collect(toList()); + final List events = caseAggregate.addDatesToAvoid(DATES_TO_AVOID, ALL, null).collect(toList()); //then assertThat(events, hasSize(1)); @@ -103,7 +105,7 @@ public void caseAssignedDoesNotAcceptDatesToAvoid() { @Test public void caseNotFound() { //when - final List events = new CaseAggregate().addDatesToAvoid(DATES_TO_AVOID, ALL).collect(toList()); + final List events = new CaseAggregate().addDatesToAvoid(DATES_TO_AVOID, ALL, null).collect(toList()); //then assertThat(events, hasSize(1)); @@ -112,4 +114,38 @@ public void caseNotFound() { assertThat(datesToAvoidReceived.getDescription(), equalTo("Add dates to avoid")); } + @Test + public void prosecutionAuthorityAccessAllowedForAgent() { + //given an assigned case + caseAggregate.assignCase(randomUUID(), clock.now(), CaseAssignmentType.DELEGATED_POWERS_DECISION); + caseAggregate.getState().setAssigneeId(null); + + //when + final List events = caseAggregate.addDatesToAvoid(DATES_TO_AVOID, "TVL", Arrays.asList("TFL")).collect(toList()); + + //then + assertThat(events, hasSize(1)); + final DatesToAvoidAdded datesToAvoidAdded = (DatesToAvoidAdded) events.get(0); + assertThat(datesToAvoidAdded.getCaseId(), equalTo(caseId)); + assertThat(datesToAvoidAdded.getDatesToAvoid(), equalTo(DATES_TO_AVOID)); + } + + @Test + public void prosecutionAuthorityAccessDenied() { + //given an assigned case + caseAggregate.assignCase(randomUUID(), clock.now(), CaseAssignmentType.DELEGATED_POWERS_DECISION); + caseAggregate.getState().setAssigneeId(null); + + //when + final List events = caseAggregate.addDatesToAvoid(DATES_TO_AVOID, "TVL", Arrays.asList("XYZ", "TVL")).collect(toList()); + + //then + assertThat(events, hasSize(1)); + final ProsecutionAuthorityAccessDenied prosecutionAuthorityAccessDenied = (ProsecutionAuthorityAccessDenied) events.get(0); + + assertThat(prosecutionAuthorityAccessDenied.getCaseAuthority(), equalTo("TFL")); + assertThat(prosecutionAuthorityAccessDenied.getProsecutorAuthorityAccess().size(), equalTo(2)); + assertThat(prosecutionAuthorityAccessDenied.getProsecutorAuthorityAccess().get(0), equalTo("XYZ")); + assertThat(prosecutionAuthorityAccessDenied.getProsecutorAuthorityAccess().get(1), equalTo("TVL")); + } } diff --git a/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/CaseAcknowledgeDefendantDetailsUpdatesTest.java b/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/CaseAcknowledgeDefendantDetailsUpdatesTest.java index 8fd0326c1e..4a226db439 100644 --- a/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/CaseAcknowledgeDefendantDetailsUpdatesTest.java +++ b/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/CaseAcknowledgeDefendantDetailsUpdatesTest.java @@ -20,14 +20,14 @@ public class CaseAcknowledgeDefendantDetailsUpdatesTest extends CaseAggregateBas @Test public void shouldAcknowledgeDefendantDetailsUpdates() { - when(caseAggregate.acknowledgeDefendantDetailsUpdates(defendantId, clock.now(), ALL)) + when(caseAggregate.acknowledgeDefendantDetailsUpdates(defendantId, clock.now(), ALL, null)) .thenExpect(new DefendantDetailsUpdatesAcknowledged(caseId, defendantId, clock.now())); } @Test public void shouldNotAcknowledgeDefendantDetailsUpdatesWhenDefendantNotFound() { final UUID anotherDefendantId = randomUUID(); - when(caseAggregate.acknowledgeDefendantDetailsUpdates(anotherDefendantId, clock.now(), ALL)) + when(caseAggregate.acknowledgeDefendantDetailsUpdates(anotherDefendantId, clock.now(), ALL, null)) .thenExpect(new DefendantNotFound(anotherDefendantId, "Acknowledge defendant details updates")); } @@ -37,7 +37,7 @@ public void shouldNotAcknowledgeDefendantDetailsUpdateWhenNoCaseReceived() { defendantId = randomUUID(); - when(caseAggregate.acknowledgeDefendantDetailsUpdates(defendantId, clock.now(), ALL)) + when(caseAggregate.acknowledgeDefendantDetailsUpdates(defendantId, clock.now(), ALL, null)) .thenExpect(new CaseNotFound(caseId, "Acknowledge defendant details updates")); } diff --git a/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/CaseReadinessTest.java b/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/CaseReadinessTest.java index 8af0936b1e..13ec0aa7a8 100644 --- a/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/CaseReadinessTest.java +++ b/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/CaseReadinessTest.java @@ -50,7 +50,7 @@ public void shouldChangeStatusAfterPleadingGuiltyOnNotGuiltyOffences() { aCase.receiveCase(caseBuilder.build(), ZonedDateTime.now()); aCase.setPleas(CASE_ID, prepareSetPleas(offences, PleaType.GUILTY), randomUUID(), ZonedDateTime.now()); aCase.setPleas(CASE_ID, prepareSetPleas(offences, PleaType.NOT_GUILTY), randomUUID(), ZonedDateTime.now()); - aCase.addDatesToAvoid("not today", "ALL"); + aCase.addDatesToAvoid("not today", "ALL", null); final Stream eventsAfterGuiltYPlea = aCase.setPleas(CASE_ID, prepareSetPleas(offences, PleaType.GUILTY), randomUUID(), ZonedDateTime.now()); final List listOfEventsAfterGuiltyPlea = eventsAfterGuiltYPlea diff --git a/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/PleadOnlineTest.java b/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/PleadOnlineTest.java index 09e1f8ba9e..c974a52df9 100644 --- a/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/PleadOnlineTest.java +++ b/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/PleadOnlineTest.java @@ -348,7 +348,7 @@ public void shouldStoreOnlinePleaWhenWithdrawalOffencesRequested() { final UUID userId = randomUUID(); final UUID withdrawalRequestReasonId = randomUUID(); caseAggregate.requestForOffenceWithdrawal(caseId, userId, ZonedDateTime.now(), - singletonList(new WithdrawalRequestsStatus(offenceId, withdrawalRequestReasonId)), "ALL"); + singletonList(new WithdrawalRequestsStatus(offenceId, withdrawalRequestReasonId)), "ALL", null); //when final PleadOnline pleadOnline = StoreOnlinePleaBuilder.defaultStoreOnlinePleaWithGuiltyPlea(offenceId, defendantId, null, null); @@ -375,9 +375,9 @@ public void shouldStoreOnlinePleaWhenWithdrawalOffencesRequestCancelled() { final UUID userId = randomUUID(); final UUID withdrawalRandomId = randomUUID(); caseAggregate.requestForOffenceWithdrawal(caseId, userId, ZonedDateTime.now(), - singletonList(new WithdrawalRequestsStatus(offenceId, withdrawalRandomId)), "ALL"); + singletonList(new WithdrawalRequestsStatus(offenceId, withdrawalRandomId)), "ALL", null); //cancel withdrawal request - caseAggregate.requestForOffenceWithdrawal(caseId, userId, ZonedDateTime.now(), emptyList(), "ALL"); + caseAggregate.requestForOffenceWithdrawal(caseId, userId, ZonedDateTime.now(), emptyList(), "ALL", null); //when final PleadOnline pleadOnline = StoreOnlinePleaBuilder.defaultStoreOnlinePleaWithGuiltyPlea(offenceId, defendantId, null, null); diff --git a/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/CaseDefendantHandlerComprehensiveTest.java b/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/CaseDefendantHandlerComprehensiveTest.java index c3af3ebd43..91af0d65ac 100644 --- a/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/CaseDefendantHandlerComprehensiveTest.java +++ b/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/CaseDefendantHandlerComprehensiveTest.java @@ -131,7 +131,7 @@ void shouldAcknowledgeDefendantDetailsUpdatesSuccessfully() { // when final Stream eventStream = caseDefendantHandler.acknowledgeDefendantDetailsUpdates( - defendantId, acknowledgedAt, state, userProsecutingAuthority); + defendantId, acknowledgedAt, state, userProsecutingAuthority, null); // then final List eventList = eventStream.toList(); @@ -153,7 +153,7 @@ void shouldReturnCaseNotFoundWhenAcknowledgingDefendantDetailsUpdatesCaseNotFoun // when final Stream eventStream = caseDefendantHandler.acknowledgeDefendantDetailsUpdates( - defendantId, acknowledgedAt, state, userProsecutingAuthority); + defendantId, acknowledgedAt, state, userProsecutingAuthority, null); // then final List eventList = eventStream.toList(); @@ -173,7 +173,7 @@ void shouldReturnDefendantNotFoundWhenAcknowledgingDefendantDetailsUpdatesDefend // when final Stream eventStream = caseDefendantHandler.acknowledgeDefendantDetailsUpdates( - defendantId, acknowledgedAt, state, userProsecutingAuthority); + defendantId, acknowledgedAt, state, userProsecutingAuthority, null); // then final List eventList = eventStream.toList(); @@ -194,7 +194,49 @@ void shouldReturnProsecutionAuthorityAccessDeniedWhenAcknowledgingWithWrongAutho // when final Stream eventStream = caseDefendantHandler.acknowledgeDefendantDetailsUpdates( - defendantId, acknowledgedAt, state, userProsecutingAuthority); + defendantId, acknowledgedAt, state, userProsecutingAuthority, null); + + // then + final List eventList = eventStream.toList(); + assertThat(eventList.size(), is(1)); + assertThat(eventList.get(0), instanceOf(ProsecutionAuthorityAccessDenied.class)); + } + + @Test + void shouldReturnProsecutionAuthorityAccessDeniedWhenAgentWithMultipleProsecutorsIsAcknowledgingWithWrongAuthority() { + // given + final UUID defendantId = UUID.randomUUID(); + final UUID caseId = UUID.randomUUID(); + final ZonedDateTime acknowledgedAt = ZonedDateTime.now(); + final String userProsecutingAuthority = "TFL"; + when(state.getCaseId()).thenReturn(caseId); + when(state.hasDefendant(defendantId)).thenReturn(true); + when(state.getProsecutingAuthority()).thenReturn("POLICE"); + + // when + final Stream eventStream = caseDefendantHandler.acknowledgeDefendantDetailsUpdates( + defendantId, acknowledgedAt, state, userProsecutingAuthority, List.of("TFL", "XYZ")); + + // then + final List eventList = eventStream.toList(); + assertThat(eventList.size(), is(1)); + assertThat(eventList.get(0), instanceOf(ProsecutionAuthorityAccessDenied.class)); + } + + @Test + void shouldReturnProsecutionAuthorityAccessDeniedWhenAgentIsAcknowledgingWithWrongAuthority() { + // given + final UUID defendantId = UUID.randomUUID(); + final UUID caseId = UUID.randomUUID(); + final ZonedDateTime acknowledgedAt = ZonedDateTime.now(); + final String userProsecutingAuthority = "TFL"; + when(state.getCaseId()).thenReturn(caseId); + when(state.hasDefendant(defendantId)).thenReturn(true); + when(state.getProsecutingAuthority()).thenReturn("POLICE"); + + // when + final Stream eventStream = caseDefendantHandler.acknowledgeDefendantDetailsUpdates( + defendantId, acknowledgedAt, state, userProsecutingAuthority, List.of("TFL")); // then final List eventList = eventStream.toList(); @@ -215,7 +257,7 @@ void shouldAcknowledgeDefendantDetailsUpdatesWithAllAuthority() { // when final Stream eventStream = caseDefendantHandler.acknowledgeDefendantDetailsUpdates( - defendantId, acknowledgedAt, state, userProsecutingAuthority); + defendantId, acknowledgedAt, state, userProsecutingAuthority, null); // then final List eventList = eventStream.toList(); @@ -234,7 +276,7 @@ void shouldAcknowledgeDefendantDetailsUpdatesWithNullDefendantId() { // when final Stream eventStream = caseDefendantHandler.acknowledgeDefendantDetailsUpdates( - null, acknowledgedAt, state, userProsecutingAuthority); + null, acknowledgedAt, state, userProsecutingAuthority, null); // then final List eventList = eventStream.toList(); diff --git a/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/HandlerUtilsTest.java b/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/HandlerUtilsTest.java index 7efdee8233..9557add4eb 100644 --- a/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/HandlerUtilsTest.java +++ b/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/HandlerUtilsTest.java @@ -20,6 +20,7 @@ import uk.gov.moj.cpp.sjp.domain.verdict.VerdictType; import uk.gov.moj.cpp.sjp.event.CaseUpdateRejected; import uk.gov.moj.cpp.sjp.event.CaseUpdateRejected.RejectReason; +import uk.gov.moj.cpp.sjp.event.ProsecutionAuthorityAccessDenied; import java.time.LocalDate; import java.time.ZonedDateTime; @@ -67,6 +68,49 @@ public void updateShouldBeRejectedWhenPleaIsForPostConvictionAdjournment() { assertEquals(expected, results); } + @Test + void updateShouldBeRejectedWhenTheAgenWithMultipleProsecutorsIsNotAuthorised() { + + final List offenceDecisions = Arrays.asList( + adjournOffenceDecision(OFFENCE_ID_1, PROVED_SJP), + withdrawOffenceDecision(OFFENCE_ID_2), + withdrawOffenceDecision(OFFENCE_ID_3) + ); + final List pleas = singletonList(new Plea(DEFENDANT_ID, OFFENCE_ID_1, PleaType.GUILTY)); + caseAggregateState.setPleas(pleas); + caseAggregateState.updateOffenceDecisions(offenceDecisions, randomUUID()); + caseAggregateState.updateOffenceConvictionDetails(ZonedDateTime.now().plusDays(7), offenceDecisions, null); + caseAggregateState.setProsecutingAuthority("XYZ"); + + final List results = HandlerUtils.createRejectionEvents(USER_ID, "action", DEFENDANT_ID, caseAggregateState, "TFL", List.of("TFL", "TVL")).get().toList(); + + final ProsecutionAuthorityAccessDenied prosecutionAuthorityAccessDenied = (ProsecutionAuthorityAccessDenied) results.get(0); + assertEquals("XYZ", prosecutionAuthorityAccessDenied.getCaseAuthority()); + assertEquals("TFL", prosecutionAuthorityAccessDenied.getProsecutorAuthorityAccess().get(0)); + assertEquals("TVL", prosecutionAuthorityAccessDenied.getProsecutorAuthorityAccess().get(1)); + } + + @Test + void updateShouldBeRejectedWhenTheAgentIsNotAuthorised() { + + final List offenceDecisions = Arrays.asList( + adjournOffenceDecision(OFFENCE_ID_1, PROVED_SJP), + withdrawOffenceDecision(OFFENCE_ID_2), + withdrawOffenceDecision(OFFENCE_ID_3) + ); + final List pleas = singletonList(new Plea(DEFENDANT_ID, OFFENCE_ID_1, PleaType.GUILTY)); + caseAggregateState.setPleas(pleas); + caseAggregateState.updateOffenceDecisions(offenceDecisions, randomUUID()); + caseAggregateState.updateOffenceConvictionDetails(ZonedDateTime.now().plusDays(7), offenceDecisions, null); + caseAggregateState.setProsecutingAuthority("XYZ"); + + final List results = HandlerUtils.createRejectionEvents(USER_ID, "action", DEFENDANT_ID, caseAggregateState, "TFL", List.of("TFL")).get().toList(); + + final ProsecutionAuthorityAccessDenied prosecutionAuthorityAccessDenied = (ProsecutionAuthorityAccessDenied) results.get(0); + assertEquals("XYZ", prosecutionAuthorityAccessDenied.getCaseAuthority()); + assertEquals("TFL", prosecutionAuthorityAccessDenied.getProsecutorAuthorityAccess().get(0)); + } + @Test public void updateShouldBeAllowedWhenPleaIsForPreConvictionAdjournment() { diff --git a/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/OffenceWithdrawalHandlerTest.java b/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/OffenceWithdrawalHandlerTest.java index 0830370abe..f23497cda4 100644 --- a/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/OffenceWithdrawalHandlerTest.java +++ b/sjp-domain/sjp-domain-aggregate/src/test/java/uk/gov/moj/cpp/sjp/domain/aggregate/handler/OffenceWithdrawalHandlerTest.java @@ -49,7 +49,8 @@ public void requestForOffenceWithdrawal() { final UUID offenceId = randomUUID(); offenceWithdrawalDetails.add(new WithdrawalRequestsStatus(offenceId, withdrawalRequestReasonId)); final ZonedDateTime now = ZonedDateTime.now(); - final List eventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), now, offenceWithdrawalDetails, caseAggregateState, "ALL").collect(toList()); + final List eventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), now, offenceWithdrawalDetails, caseAggregateState, + "ALL", new ArrayList<>()).collect(toList()); final List offenceWithdrawalList = convertWtihdrawalRequestsStatus(offenceWithdrawalDetails); assertThat(eventList, containsInAnyOrder(new OffencesWithdrawalRequestsStatusSet(caseID, now, user.getUserId(), offenceWithdrawalList), new OffenceWithdrawalRequested(caseID, offenceId, withdrawalRequestReasonId, user.getUserId(), now))); @@ -61,7 +62,8 @@ public void requestForOffenceWithdrawalOnACompletedCaseShouldBeRejected(){ final UUID offenceId = randomUUID(); final List offenceWithdrawalDetails = newArrayList(new WithdrawalRequestsStatus(offenceId, withdrawalRequestReasonId)); final ZonedDateTime now = ZonedDateTime.now(); - final List eventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), now, offenceWithdrawalDetails, caseAggregateState, "ALL").collect(toList()); + final List eventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), now, offenceWithdrawalDetails, caseAggregateState, + "ALL", new ArrayList<>()).collect(toList()); assertThat(eventList, containsInAnyOrder( new CaseUpdateRejected(caseID, CaseUpdateRejected.RejectReason.CASE_COMPLETED) )); @@ -73,7 +75,8 @@ public void requestForOffenceWithdrawalOnAnAssignedCaseShouldBeRejected(){ final UUID offenceId = randomUUID(); final List offenceWithdrawalDetails = newArrayList(new WithdrawalRequestsStatus(offenceId, withdrawalRequestReasonId)); final ZonedDateTime now = ZonedDateTime.now(); - final List eventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), now, offenceWithdrawalDetails, caseAggregateState, "ALL").collect(toList()); + final List eventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), now, offenceWithdrawalDetails, caseAggregateState, + "ALL", new ArrayList<>()).collect(toList()); assertThat(eventList, containsInAnyOrder( new CaseUpdateRejected(caseID, CaseUpdateRejected.RejectReason.CASE_ASSIGNED) )); @@ -89,7 +92,8 @@ public void requestForMultipleOffenceWithdrawal() { final UUID offenceId_2 = randomUUID(); offenceWithdrawalDetails.add(new WithdrawalRequestsStatus(offenceId_2, withdrawalRequestReasonId)); final ZonedDateTime now = ZonedDateTime.now(); - final List eventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), now, offenceWithdrawalDetails, caseAggregateState, "ALL").collect(toList()); + final List eventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), now, offenceWithdrawalDetails, caseAggregateState, + "ALL", new ArrayList<>()).collect(toList()); final List offenceWithdrawalList = convertWtihdrawalRequestsStatus(offenceWithdrawalDetails); assertThat(eventList, containsInAnyOrder(new OffencesWithdrawalRequestsStatusSet(caseID, now, user.getUserId(), offenceWithdrawalList), @@ -105,7 +109,8 @@ public void cancelOffenceWithdrawalRequest() { final List offenceWithdrawalDetails = new ArrayList<>(); final ZonedDateTime after2Days = ZonedDateTime.now().plusDays(2); - final List cancelEventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), after2Days, offenceWithdrawalDetails, caseAggregateState, "ALL").collect(toList()); + final List cancelEventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), after2Days, offenceWithdrawalDetails, caseAggregateState, + "ALL", new ArrayList<>()).collect(toList()); final List offenceWithdrawalList = convertWtihdrawalRequestsStatus(offenceWithdrawalDetails); @@ -128,7 +133,8 @@ public void cancelMultipleOffenceWithdrawalRequests() { offenceWithdrawalDetails.add(new WithdrawalRequestsStatus(offenceId, withdrawalRequestReasonId)); offenceWithdrawalDetails.add(new WithdrawalRequestsStatus(offenceId_1, withdrawalRequestReasonId)); final ZonedDateTime after2Days = ZonedDateTime.now().plusDays(2); - final List cancelEventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), after2Days, offenceWithdrawalDetails, caseAggregateState, "ALL").collect(toList()); + final List cancelEventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), after2Days, offenceWithdrawalDetails, caseAggregateState, + "ALL", new ArrayList<>()).collect(toList()); final List offenceWithdrawalList = convertWtihdrawalRequestsStatus(offenceWithdrawalDetails); assertThat(cancelEventList, containsInAnyOrder(new OffencesWithdrawalRequestsStatusSet(caseID, after2Days, user.getUserId(), offenceWithdrawalList), @@ -145,7 +151,8 @@ public void requestForOffenceWithdrawalWithDifferentReason() { final List offenceWithdrawalDetails = new ArrayList<>(); offenceWithdrawalDetails.add(new WithdrawalRequestsStatus(offenceId, offenceNewWithdrawalRequestReasonId)); final ZonedDateTime after2Days = ZonedDateTime.now().plusDays(2); - final List reasonChangedEventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), after2Days, offenceWithdrawalDetails, caseAggregateState, "ALL").collect(toList()); + final List reasonChangedEventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), after2Days, offenceWithdrawalDetails, caseAggregateState, + "ALL", new ArrayList<>()).collect(toList()); final List offenceWithdrawalList = convertWtihdrawalRequestsStatus(offenceWithdrawalDetails); assertThat(reasonChangedEventList, containsInAnyOrder(new OffencesWithdrawalRequestsStatusSet(caseID, after2Days, user.getUserId(), offenceWithdrawalList), @@ -164,7 +171,8 @@ public void requestForMultipleOffenceWithdrawalWithDifferentReason() { offenceWithdrawalDetails.add(new WithdrawalRequestsStatus(offenceId, offenceNewWithdrawalRequestReasonId)); offenceWithdrawalDetails.add(new WithdrawalRequestsStatus(offenceId_1, offenceNewWithdrawalRequestReasonId)); final ZonedDateTime after2Days = ZonedDateTime.now().plusDays(2); - final List reasonChangedEventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), after2Days, offenceWithdrawalDetails, caseAggregateState, "ALL").collect(toList()); + final List reasonChangedEventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), after2Days, offenceWithdrawalDetails, caseAggregateState, + "ALL", new ArrayList<>()).collect(toList()); final List offenceWithdrawalList = convertWtihdrawalRequestsStatus(offenceWithdrawalDetails); assertThat(reasonChangedEventList, containsInAnyOrder(new OffencesWithdrawalRequestsStatusSet(caseID, after2Days, user.getUserId(), offenceWithdrawalList), @@ -189,7 +197,8 @@ public void requestCancelAndReasonChangedForMultipleOffences() { offenceWithdrawalDetails.add(new WithdrawalRequestsStatus(offenceId_1, offenceNewWithdrawalRequestReasonId)); final ZonedDateTime after2Days = ZonedDateTime.now().plusDays(2); - final List eventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), after2Days, offenceWithdrawalDetails, caseAggregateState, "ALL").collect(toList()); + final List eventList = offenceWithdrawalHandler.requestOffenceWithdrawal(caseID, user.getUserId(), after2Days, offenceWithdrawalDetails, caseAggregateState, + "ALL", new ArrayList<>()).collect(toList()); final List offenceWithdrawalList = convertWtihdrawalRequestsStatus(offenceWithdrawalDetails); assertThat(eventList, containsInAnyOrder(new OffencesWithdrawalRequestsStatusSet(caseID, after2Days, user.getUserId(), offenceWithdrawalList), diff --git a/sjp-domain/sjp-domain-event/src/main/java/uk/gov/moj/cpp/sjp/event/ProsecutionAuthorityAccessDenied.java b/sjp-domain/sjp-domain-event/src/main/java/uk/gov/moj/cpp/sjp/event/ProsecutionAuthorityAccessDenied.java index 2ef6b8b741..1556bd1722 100644 --- a/sjp-domain/sjp-domain-event/src/main/java/uk/gov/moj/cpp/sjp/event/ProsecutionAuthorityAccessDenied.java +++ b/sjp-domain/sjp-domain-event/src/main/java/uk/gov/moj/cpp/sjp/event/ProsecutionAuthorityAccessDenied.java @@ -2,25 +2,30 @@ import uk.gov.justice.domain.annotation.Event; +import java.io.Serializable; +import java.util.List; + @Event(ProsecutionAuthorityAccessDenied.EVENT_NAME) -public class ProsecutionAuthorityAccessDenied { +public class ProsecutionAuthorityAccessDenied implements Serializable { + private static final long serialVersionUID = 1L; - private final String userAuthority; private final String caseAuthority; + private final List prosecutorAuthorityAccess; public static final String EVENT_NAME = "sjp.events.prosecution-authority-access-denied"; - public ProsecutionAuthorityAccessDenied(final String userAuthority, final String caseAuthority) { - this.userAuthority = userAuthority; + public ProsecutionAuthorityAccessDenied(final String caseAuthority, + final List prosecutorAuthorityAccess) { this.caseAuthority = caseAuthority; - } - - public String getUserAuthority() { - return userAuthority; + this.prosecutorAuthorityAccess = prosecutorAuthorityAccess; } public String getCaseAuthority() { return caseAuthority; } + + public List getProsecutorAuthorityAccess() { + return prosecutorAuthorityAccess; + } } diff --git a/sjp-event/sjp-event-processor/src/test/java/uk/gov/moj/cpp/sjp/event/processor/HearingResultedProcessorTest.java b/sjp-event/sjp-event-processor/src/test/java/uk/gov/moj/cpp/sjp/event/processor/HearingResultedProcessorTest.java index 344c6f4f68..f5e695a150 100644 --- a/sjp-event/sjp-event-processor/src/test/java/uk/gov/moj/cpp/sjp/event/processor/HearingResultedProcessorTest.java +++ b/sjp-event/sjp-event-processor/src/test/java/uk/gov/moj/cpp/sjp/event/processor/HearingResultedProcessorTest.java @@ -1,14 +1,18 @@ package uk.gov.moj.cpp.sjp.event.processor; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; +import static java.util.Collections.singletonList; +import static java.util.UUID.randomUUID; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static uk.gov.justice.core.courts.CourtApplication.courtApplication; +import static uk.gov.justice.core.courts.Hearing.hearing; +import static uk.gov.justice.json.schemas.domains.sjp.results.PublicHearingResulted.publicHearingResulted; +import static uk.gov.justice.services.messaging.JsonEnvelope.envelopeFrom; +import static uk.gov.justice.services.test.utils.core.messaging.MetadataBuilderFactory.metadataWithRandomUUID; +import static uk.gov.justice.services.test.utils.core.reflection.ReflectionUtil.setField; +import static uk.gov.moj.cpp.sjp.event.processor.utils.ApplicationResult.G; +import static uk.gov.moj.cpp.sjp.event.processor.utils.SjpApplicationTypes.APPEARANCE_TO_MAKE_STATUTORY_DECLARATION_SJP; + import uk.gov.justice.core.courts.CourtApplication; import uk.gov.justice.core.courts.CourtApplicationType; import uk.gov.justice.core.courts.Hearing; @@ -24,23 +28,19 @@ import uk.gov.justice.services.messaging.Envelope; import uk.gov.justice.services.messaging.JsonEnvelope; -import javax.json.JsonValue; -import java.util.Arrays; import java.util.UUID; -import static java.util.Collections.singletonList; -import static java.util.UUID.randomUUID; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static uk.gov.justice.core.courts.CourtApplication.courtApplication; -import static uk.gov.justice.core.courts.Hearing.hearing; -import static uk.gov.justice.json.schemas.domains.sjp.results.PublicHearingResulted.publicHearingResulted; -import static uk.gov.justice.services.messaging.JsonEnvelope.envelopeFrom; -import static uk.gov.justice.services.test.utils.core.messaging.MetadataBuilderFactory.metadataWithRandomUUID; -import static uk.gov.justice.services.test.utils.core.reflection.ReflectionUtil.setField; -import static uk.gov.moj.cpp.sjp.event.processor.utils.ApplicationResult.G; -import static uk.gov.moj.cpp.sjp.event.processor.utils.SjpApplicationTypes.APPEARANCE_TO_MAKE_STATUTORY_DECLARATION_SJP; +import javax.json.JsonValue; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) @@ -61,7 +61,11 @@ public class HearingResultedProcessorTest { private final ProsecutionCase prosecutionCase = ProsecutionCase.prosecutionCase(). - withMigrationSourceSystem(new MigrationSourceSystem("1234","Exhibit")) + withMigrationSourceSystem(MigrationSourceSystem + .migrationSourceSystem() + .withMigrationSourceSystemCaseIdentifier("1234") + .withMigrationSourceSystemName("Exhibit") + .build()) .build(); final UUID caseId = randomUUID(); diff --git a/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/pollingquery/PendingDatesToAvoidPoller.java b/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/pollingquery/PendingDatesToAvoidPoller.java index e4066ec148..f462c53286 100644 --- a/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/pollingquery/PendingDatesToAvoidPoller.java +++ b/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/pollingquery/PendingDatesToAvoidPoller.java @@ -16,14 +16,18 @@ public class PendingDatesToAvoidPoller { - private static RequestParamsBuilder getDatesToAvoid(final String userId) { + private static RequestParamsBuilder getDatesToAvoid(final String userId, final String prosecutingAuthority) { + final String url = prosecutingAuthority != null ? "/cases/pending-dates-to-avoid?prosecutingAuthority=" + + prosecutingAuthority : "/cases/pending-dates-to-avoid"; + final String contentType = "application/vnd.sjp.query.pending-dates-to-avoid+json"; - return requestParams(getReadUrl("/cases/pending-dates-to-avoid"), contentType) + return requestParams(getReadUrl(url), contentType) .withHeader(HeaderConstants.USER_ID, userId); } - public static JsonPath pollUntilPendingDatesToAvoidIsOk(final String userId, final Matcher jsonPayloadMatcher) { - return new JsonPath(pollWithDefaults(getDatesToAvoid(userId)) + public static JsonPath pollUntilPendingDatesToAvoidIsOk(final String userId, final Matcher jsonPayloadMatcher, + final String prosecutingAuthority) { + return new JsonPath(pollWithDefaults(getDatesToAvoid(userId, prosecutingAuthority)) .until( status().is(OK), payload().isJson(jsonPayloadMatcher) diff --git a/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/DatesToAvoidIT.java b/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/DatesToAvoidIT.java index e241e1a23f..4921b5fb72 100644 --- a/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/DatesToAvoidIT.java +++ b/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/DatesToAvoidIT.java @@ -122,7 +122,7 @@ public void setUp() throws Exception { @Test public void shouldCaseBePendingDatesToAvoidForPleaChangeScenariosAndBeResultedAfterDatesToAvoid() { setupIdMapperStub(); - shouldCaseBePendingDatesToAvoidForPleaChangeScenarios(); + shouldCaseBePendingDatesToAvoidForPleaChangeScenarios(null); addDatesToAvoid(tflCaseBuilder.getId(), DATE_TO_AVOID); assertThatNumberOfCasesPendingDatesToAvoidIsAccurate(tflUserId, tflInitialPendingDatesToAvoidCount); @@ -134,7 +134,7 @@ public void shouldCaseBePendingDatesToAvoidForPleaChangeScenariosAndBeResultedAf @Test public void shouldCaseBePendingDatesToAvoidForPleaChangeScenariosAndBeReadyAfterDatesToAvoidExpiry() { - shouldCaseBePendingDatesToAvoidForPleaChangeScenarios(); + shouldCaseBePendingDatesToAvoidForPleaChangeScenarios("TFL"); pollUntilCaseHasStatus(tflCaseBuilder.getId(), PLEA_RECEIVED_NOT_READY_FOR_DECISION); makeDatesToAvoidExpired(eventListener, tflCaseBuilder.getId()); verifyDatesToAvoidExpiredEventEmitted(eventListener, tflCaseBuilder.getId()); @@ -198,7 +198,7 @@ private void shouldCaseBePendingDatesToAvoidForResultedCaseScenario(UUID userId, updatePleaToNotGuiltyAndConfirm(tvlCaseBuilder.getId(), tvlCaseBuilder.getOffenceId(), tvlCaseBuilder.getDefendantBuilder().getId()); //checks that correct dates-to-avoid record is retrieved (i.e. the one related to the case passed in) - assertThatDatesToAvoidIsPendingSubmissionForCase(userId, createCasePayloadBuilder); + assertThatDatesToAvoidIsPendingSubmissionForCase(userId, createCasePayloadBuilder, null); requestWithdrawalOfOffences(createCasePayloadBuilder.getId(), userId, asList(withdrawalRequestsStatus() .withOffenceId(createCasePayloadBuilder.getOffenceId()) @@ -210,11 +210,11 @@ private void shouldCaseBePendingDatesToAvoidForResultedCaseScenario(UUID userId, assertThatNumberOfCasesPendingDatesToAvoidIsAccurate(userId, expectedPendingDatesToAvoidCount); } - private void shouldCaseBePendingDatesToAvoidForPleaChangeScenarios() { + private void shouldCaseBePendingDatesToAvoidForPleaChangeScenarios(final String prosecutingAuthority) { //checks that dates-to-avoid is pending submission when NOT_GUILTY plea submitted updatePleaToNotGuiltyAndConfirm(tflCaseBuilder.getId(), tflCaseBuilder.getOffenceId(), tflCaseBuilder.getDefendantBuilder().getId()); // verifyDatesToAvoidRequiredEvent(tflCaseBuilder.getId()); - assertThatDatesToAvoidIsPendingSubmissionForCase(tflUserId, tflCaseBuilder); + assertThatDatesToAvoidIsPendingSubmissionForCase(tflUserId, tflCaseBuilder, prosecutingAuthority); //checks that dates-to-avoid NOT pending submission when plea is cancelled cancelPlea(tflCaseBuilder.getId(), tflCaseBuilder.getOffenceId(), tflCaseBuilder.getDefendantBuilder().getId()); @@ -223,7 +223,7 @@ private void shouldCaseBePendingDatesToAvoidForPleaChangeScenarios() { //checks that dates-to-avoid is pending submission again when plea updated to NOT_GUILTY updatePleaToNotGuiltyAndConfirm(tflCaseBuilder.getId(), tflCaseBuilder.getOffenceId(), tflCaseBuilder.getDefendantBuilder().getId()); - assertThatDatesToAvoidIsPendingSubmissionForCase(tflUserId, tflCaseBuilder); + assertThatDatesToAvoidIsPendingSubmissionForCase(tflUserId, tflCaseBuilder, prosecutingAuthority); } private void completeCase(CreateCase.CreateCasePayloadBuilder createCasePayloadBuilder) { @@ -242,11 +242,12 @@ private void cancelPlea(final UUID caseId, final UUID offenceId, final UUID defe false, null, singletonList(Triple.of(offenceId, defendantId, null))); } - private void assertThatDatesToAvoidIsPendingSubmissionForCase(final UUID userId, final CreateCase.CreateCasePayloadBuilder aCase) { + private void assertThatDatesToAvoidIsPendingSubmissionForCase(final UUID userId, final CreateCase.CreateCasePayloadBuilder aCase, + final String prosecutingAuthority) { final Matcher pendingDatesToAvoidMatcher = withJsonPath("$.cases[-1].caseId", equalTo(aCase.getId().toString())); - final JsonPath path = pollUntilPendingDatesToAvoidIsOk(userId.toString(), pendingDatesToAvoidMatcher); + final JsonPath path = pollUntilPendingDatesToAvoidIsOk(userId.toString(), pendingDatesToAvoidMatcher, prosecutingAuthority); final List pendingDatesToAvoid = path.getList("cases"); final Integer datesToAvoidCount = path.get("count"); final Map map = pendingDatesToAvoid.get(pendingDatesToAvoid.size() - 1); @@ -267,12 +268,12 @@ private void assertThatDatesToAvoidIsPendingSubmissionForCase(final UUID userId, } private int pollForCountOfCasesPendingDatesToAvoid(final UUID userId) { - return pollUntilPendingDatesToAvoidIsOk(userId.toString(), withJsonPath("$.count")) + return pollUntilPendingDatesToAvoidIsOk(userId.toString(), withJsonPath("$.count"), null) .get("count"); } private void assertThatNumberOfCasesPendingDatesToAvoidIsAccurate(final UUID userId, final int pendingDatesToAvoidCount) { - pollUntilPendingDatesToAvoidIsOk(userId.toString(), withJsonPath("$.count", equalTo(pendingDatesToAvoidCount))); + pollUntilPendingDatesToAvoidIsOk(userId.toString(), withJsonPath("$.count", equalTo(pendingDatesToAvoidCount)), null); } private void assertWithinSeconds(final long value, final long tolerance) { diff --git a/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/DefendantDetailsIT.java b/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/DefendantDetailsIT.java index b96e6c442e..8c508398fd 100644 --- a/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/DefendantDetailsIT.java +++ b/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/DefendantDetailsIT.java @@ -245,7 +245,7 @@ public void shouldObeyLimit() { @Test public void shouldReturnUpdatedDetailsBasedOnUserProsecutingAuthority() { - final JsonObject existingUpdatedDefendantDetails = getUpdatedDefendantDetails(tvlUserUid); + final JsonObject existingUpdatedDefendantDetails = getUpdatedDefendantDetails(tvlUserUid, "TVL"); updateDefendantDetailsForCaseAndPayload( caseIdOne, @@ -278,6 +278,16 @@ private JsonObject getUpdatedDefendantDetails(UUID userUid) { return Json.createReader(new StringReader(response.readEntity(String.class))).readObject(); } + private JsonObject getUpdatedDefendantDetails(UUID userUid, String prosecutingAuhority) { + final Response response = makeGetCall( + "/defendant-details-updates?limit=" + Integer.MAX_VALUE + "&prosecutingAuthority="+ prosecutingAuhority, + DEFENDANT_DETAIL_UPDATES_CONTENT_TYPE, + userUid); + assertThat(response.getStatus(), equalTo(Response.Status.OK.getStatusCode())); + + return Json.createReader(new StringReader(response.readEntity(String.class))).readObject(); + } + private JsonObject responseToJsonObject(String response) { return Json.createReader(new StringReader(response)).readObject(); } diff --git a/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/DefendantPotentialCaseIT.java b/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/DefendantPotentialCaseIT.java index ee1003169e..243954fea3 100644 --- a/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/DefendantPotentialCaseIT.java +++ b/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/DefendantPotentialCaseIT.java @@ -9,6 +9,7 @@ import static uk.gov.moj.sjp.it.command.CreateCase.createCaseForPayloadBuilder; import static uk.gov.moj.sjp.it.model.ProsecutingAuthority.TFL; import static uk.gov.moj.sjp.it.pollingquery.CasePoller.pollForCase; +import static uk.gov.moj.sjp.it.pollingquery.CasePoller.pollUntilCaseByIdIsOk; import static uk.gov.moj.sjp.it.pollingquery.CasePoller.pollUntilPotentialCasesByDefendantIdIsOk; import static uk.gov.moj.sjp.it.stub.ReferenceDataServiceStub.stubProsecutorQuery; import static uk.gov.moj.sjp.it.stub.UnifiedSearchStub.stubUnifiedSearchQueryForCases; @@ -64,7 +65,7 @@ public void shouldReturnFalseForPotentialCases() { } @Test - public void shouldFindPotentialCases() { + public void shouldFindPotentialCases(){ UUID caseId = randomCaseId; UUID defendantId = randomUUID(); @@ -81,6 +82,8 @@ public void shouldFindPotentialCases() { .popEvent(CaseReceived.EVENT_NAME); assertTrue(caseReceivedEvent.isPresent()); + pollUntilCaseByIdIsOk(caseId); + final String potentialCasesResponsePayload = pollUntilPotentialCasesByDefendantIdIsOk(defendantId); final JsonObject potentialCases = responseToJsonObject(potentialCasesResponsePayload); final JsonArray sjpOpenCases = potentialCases.getJsonArray("sjpOpenCases"); diff --git a/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/MultipleOffencesWithdrawalRequestedIT.java b/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/MultipleOffencesWithdrawalRequestedIT.java index 1c105dacdd..392985c24c 100644 --- a/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/MultipleOffencesWithdrawalRequestedIT.java +++ b/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/MultipleOffencesWithdrawalRequestedIT.java @@ -35,6 +35,7 @@ import static uk.gov.moj.sjp.it.model.ProsecutingAuthority.DVLA; import static uk.gov.moj.sjp.it.model.ProsecutingAuthority.TFL; import static uk.gov.moj.sjp.it.model.ProsecutingAuthority.TVL; +import static uk.gov.moj.sjp.it.stub.IdMapperStub.stubForIdMapperSuccess; import static uk.gov.moj.sjp.it.stub.ReferenceDataServiceStub.stubDefaultCourtByCourtHouseOUCodeQuery; import static uk.gov.moj.sjp.it.stub.ReferenceDataServiceStub.stubEnforcementAreaByPostcode; import static uk.gov.moj.sjp.it.stub.ReferenceDataServiceStub.stubProsecutorQuery; @@ -74,6 +75,8 @@ import java.util.UUID; import java.util.stream.Collectors; +import javax.ws.rs.core.Response; + import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import org.hamcrest.Matcher; @@ -185,8 +188,7 @@ public void offenceWithdrawalForSomeOffencesOnAPartiallyDecidedCaseMakesCaseRead stubDefaultCourtByCourtHouseOUCodeQuery(); stubForUserDetails(user, "ALL"); stubEnforcementAreaByPostcode(aCase.getDefendantBuilder().getAddressBuilder().getPostcode(), "1080", "Bedfordshire Magistrates' Court"); - - + stubForIdMapperSuccess(Response.Status.OK); final UUID sessionId = randomUUID(); diff --git a/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/UpdateDefendantDetailsFromCCIT.java b/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/UpdateDefendantDetailsFromCCIT.java index 514f547f57..265c358677 100644 --- a/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/UpdateDefendantDetailsFromCCIT.java +++ b/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/test/UpdateDefendantDetailsFromCCIT.java @@ -365,4 +365,90 @@ public void shouldUpdateLegalEntityDefendantDetailsFromCCWhenEventReceived() { assertThat(payload.containsKey("lastName") ? payload.isNull("lastName") : true, is(true)); assertThat(payload.containsKey("title") ? payload.isNull("title") : true, is(true)); } + + @Test + public void shouldUpdateLegalEntityDefendantDetailsWithoutContactFromCCWhenEventReceived() { + // given - create a case with legal entity defendant + final UUID legalEntityCaseId = randomUUID(); + final CreateCase.CreateCasePayloadBuilder legalEntityCaseBuilder = withDefaults() + .withId(legalEntityCaseId) + .withDefendantBuilder(defaultLegalEntityDefendant()); + + stubEnforcementAreaByPostcode(legalEntityCaseBuilder.getDefendantBuilder().getAddressBuilder().getPostcode(), + "1080", "Bedfordshire Magistrates' Court"); + stubRegionByPostcode("1080", "TestRegion"); + stubProsecutorQuery(legalEntityCaseBuilder.getProsecutingAuthority().name(), + legalEntityCaseBuilder.getProsecutingAuthority().getFullName(), randomUUID()); + + createCaseForPayloadBuilder(legalEntityCaseBuilder); + + UUID defendantId = UUID.fromString(pollUntilCaseByIdIsOk(legalEntityCaseId).getString("defendant.id")); + + // Prepare legal entity defendant update with new name and address + // Using Organisation structure as per LegalEntityDefendant class + final JsonObject updatedAddress = createObjectBuilder() + .add("address1", "789 Corporate Avenue") + .add("address2", "Business District") + .add("address3", "London") + .add("address4", "Greater London") + .add("address5", "UK") + .add("postcode", "EC1A 1BB") + .build(); + + final JsonObject organisation = createObjectBuilder() + .add("name", "Acme Corporation Ltd") + .add("address", updatedAddress) + .add("incorporationNumber", "INC123456") + .build(); + + final JsonObject legalEntityDefendant = createObjectBuilder() + .add("organisation", organisation) + .build(); + + final JsonObject defendant = createObjectBuilder() + .add("id", defendantId.toString()) + .add("prosecutionCaseId", legalEntityCaseId.toString()) + .add("legalEntityDefendant", legalEntityDefendant) + .build(); + + final JsonObject eventPayload = createObjectBuilder() + .add("defendant", defendant) + .build(); + + // when + final EventListener defendantDetailsUpdatedListener = new EventListener() + .subscribe(DEFENDANT_DETAILS_UPDATED_PUBLIC_EVENT) + .run(() -> { + final JmsMessageProducerClient publicJmsMessageProducerClient = newPublicJmsMessageProducerClientProvider() + .getMessageProducerClient(); + publicJmsMessageProducerClient.sendMessage("public.progression.case-defendant-changed", eventPayload); + }); + + // then + final Optional defendantDetailsUpdatedEvent = defendantDetailsUpdatedListener.popEvent(DEFENDANT_DETAILS_UPDATED_PUBLIC_EVENT); + + assertThat(defendantDetailsUpdatedEvent.isPresent(), is(true)); + final JsonObject payload = defendantDetailsUpdatedEvent.get().payloadAsJsonObject(); + + // Verify basic identifiers + assertThat(payload.getString("caseId"), is(legalEntityCaseId.toString())); + assertThat(payload.getString("defendantId"), is(defendantId.toString())); + + // Verify legal entity name from LegalEntityDefendant + assertThat(payload.getString("legalEntityName"), is("Acme Corporation Ltd")); + + // Verify address from LegalEntityDefendant + final JsonObject updatedEventAddress = payload.getJsonObject("address"); + assertThat(updatedEventAddress, is(notNullValue())); + assertThat(updatedEventAddress.getString("address1"), is("789 Corporate Avenue")); + assertThat(updatedEventAddress.getString("address2"), is("Business District")); + assertThat(updatedEventAddress.getString("postcode"), is("EC1A 1BB")); + + + assertThat(payload.containsKey("contactNumber"), is(false)); + // For legal entity defendants, person-specific fields should be null/absent + assertThat(payload.containsKey("firstName") ? payload.isNull("firstName") : true, is(true)); + assertThat(payload.containsKey("lastName") ? payload.isNull("lastName") : true, is(true)); + assertThat(payload.containsKey("title") ? payload.isNull("title") : true, is(true)); + } } diff --git a/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/util/HttpClientUtil.java b/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/util/HttpClientUtil.java index 64dff23352..72463dfbd6 100644 --- a/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/util/HttpClientUtil.java +++ b/sjp-integration-test/src/test/java/uk/gov/moj/sjp/it/util/HttpClientUtil.java @@ -57,7 +57,13 @@ public static UUID makePostCall(final UUID userId, final String url, final Strin final String writeUrl = getWriteUrl(url); try (Response response = restClient.postCommand(writeUrl, mediaType, payload, map)) { - assertThat(format("Post returned not expected status code with body: %s", response.readEntity(String.class)), + String responseBody = ""; + try { + responseBody = response.readEntity(String.class); + } catch (IllegalStateException e) { + //no-op in case of no response + } + assertThat(format("Post returned not expected status code with body: %s", responseBody), response.getStatus(), is(expectedStatus.getStatusCode())); } @@ -70,11 +76,15 @@ public static String getPostCallResponse(final String url, final String mediaTyp map.add(HeaderConstants.CLIENT_CORRELATION_ID, randomUUID()); final String writeUrl = getWriteUrl(url); - final String responseBody; + String responseBody = ""; try (Response response = restClient.postCommand(writeUrl, mediaType, payload, map)) { LOGGER.info("Post call made: \n\tURL = {} \n\tMedia type = {} \n\tUser = {}\n", writeUrl, mediaType, USER_ID); - responseBody = response.readEntity(String.class); + try { + responseBody = response.readEntity(String.class); + } catch (IllegalStateException e) { + //no-op in case of no response + } assertThat(format("Post returned not expected status code with body: %s", responseBody), response.getStatus(), is(expectedStatus.getStatusCode())); } diff --git a/sjp-query/sjp-query-api/src/raml/sjp-query-api.raml b/sjp-query/sjp-query-api/src/raml/sjp-query-api.raml index cbf58e9ec9..71280a8234 100644 --- a/sjp-query/sjp-query-api/src/raml/sjp-query-api.raml +++ b/sjp-query/sjp-query-api/src/raml/sjp-query-api.raml @@ -134,6 +134,10 @@ baseUri: http://localhost:8080/sjp-query-api/query/api/rest/sjp description: The defendant's region. type: string required: false + prosecutingAuthority: + description: The prosecuting authority + type: string + required: false responses: 200: @@ -378,6 +382,10 @@ baseUri: http://localhost:8080/sjp-query-api/query/api/rest/sjp description: The defendant's region id. type: string required: false + prosecutingAuthority: + description: The prosecuting authority + type: string + required: false responses: 200: description: OK diff --git a/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/response/DefendantDetailsUpdatesView.java b/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/response/DefendantDetailsUpdatesView.java index 3bff8fbb11..146fd85a93 100644 --- a/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/response/DefendantDetailsUpdatesView.java +++ b/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/response/DefendantDetailsUpdatesView.java @@ -116,6 +116,8 @@ public static class DefendantDetailsUpdate { */ private String legalEntityName; + private String prosecutingAuthority; + @SuppressWarnings("squid:S00107") public DefendantDetailsUpdate( final String firstName, @@ -129,7 +131,8 @@ public DefendantDetailsUpdate( final boolean addressUpdated, final String updatedOn, final String region, - final String legalEntityName) { + final String legalEntityName, + final String prosecutingAuthority) { this.firstName = firstName; this.lastName = lastName; @@ -143,6 +146,7 @@ public DefendantDetailsUpdate( this.updatedOn = updatedOn; this.region = region; this.legalEntityName = legalEntityName; + this.prosecutingAuthority = prosecutingAuthority; } public String getLastName() { @@ -197,6 +201,10 @@ public void setLegalEntityName(final String legalEntityName) { this.legalEntityName = legalEntityName; } + public String getProsecutingAuthority() { + return prosecutingAuthority; + } + public static DefendantDetailsUpdate of(UpdatedDefendantDetails defendantDetail) { return new DefendantDetailsUpdate( defendantDetail.getFirstName(), @@ -214,7 +222,8 @@ public static DefendantDetailsUpdate of(UpdatedDefendantDetails defendantDetail) .map(DateTimeFormatter.ISO_LOCAL_DATE::format) .orElse(DateTimeFormatter.ISO_LOCAL_DATE.format(ZonedDateTime.now())), defendantDetail.getRegion(), - defendantDetail.getLegalEntityName()); + defendantDetail.getLegalEntityName(), + defendantDetail.getProsecutingAuthority()); } @Override diff --git a/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/CaseService.java b/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/CaseService.java index d9d17ef608..42bfd2aff3 100644 --- a/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/CaseService.java +++ b/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/CaseService.java @@ -17,6 +17,7 @@ import uk.gov.justice.services.common.converter.ListToJsonArrayConverter; import uk.gov.justice.services.messaging.JsonEnvelope; +import uk.gov.moj.cpp.accesscontrol.sjp.providers.ProsecutingAuthorityAccess; import uk.gov.moj.cpp.accesscontrol.sjp.providers.ProsecutingAuthorityProvider; import uk.gov.moj.cpp.sjp.domain.common.CaseManagementStatus; import uk.gov.moj.cpp.sjp.persistence.entity.CaseDetail; @@ -52,6 +53,7 @@ import java.time.LocalDate; import java.time.ZoneOffset; import java.time.ZonedDateTime; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -177,19 +179,29 @@ public CasesMissingSjpnView findCasesMissingSjpn(final JsonEnvelope envelope, final Optional postedBefore) { final List casesDetails; - + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = prosecutingAuthorityProvider + .getCurrentUsersProsecutingAuthorityAccess(envelope); final String prosecutingAuthorityFilterValue = prosecutingAuthorityAccessFilterConverter - .convertToProsecutingAuthorityAccessFilter(prosecutingAuthorityProvider - .getCurrentUsersProsecutingAuthorityAccess(envelope)); + .convertToProsecutingAuthorityAccessFilter(prosecutingAuthorityAccess); + + final List agentProsecutorAuthorityAccessFilterValue; + if (prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess() == null || prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess().isEmpty()){ + agentProsecutorAuthorityAccessFilterValue = Arrays.asList("DUMMY_VALUE"); + } else { + agentProsecutorAuthorityAccessFilterValue = prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess(); + } if (limit.isPresent() && limit.get() < 1) { casesDetails = Collections.emptyList(); } else { QueryResult caseDetailsResult; + if (postedBefore.isPresent()) { - caseDetailsResult = caseRepository.findCasesMissingSjpn(prosecutingAuthorityFilterValue, postedBefore.get()); + caseDetailsResult = caseRepository.findCasesMissingSjpn(prosecutingAuthorityFilterValue, postedBefore.get(), + agentProsecutorAuthorityAccessFilterValue); } else { - caseDetailsResult = caseRepository.findCasesMissingSjpn(prosecutingAuthorityFilterValue); + caseDetailsResult = caseRepository.findCasesMissingSjpn(prosecutingAuthorityFilterValue, + agentProsecutorAuthorityAccessFilterValue); } if (limit.isPresent()) { @@ -206,8 +218,8 @@ public CasesMissingSjpnView findCasesMissingSjpn(final JsonEnvelope envelope, .map(CaseSummaryView::new).collect(toList()); final int casesCount = postedBefore - .map(localDate -> caseRepository.countCasesMissingSjpn(prosecutingAuthorityFilterValue, localDate)) - .orElseGet(() -> caseRepository.countCasesMissingSjpn(prosecutingAuthorityFilterValue)); + .map(localDate -> caseRepository.countCasesMissingSjpn(prosecutingAuthorityFilterValue, localDate, agentProsecutorAuthorityAccessFilterValue)) + .orElseGet(() -> caseRepository.countCasesMissingSjpn(prosecutingAuthorityFilterValue, agentProsecutorAuthorityAccessFilterValue)); return new CasesMissingSjpnView(casesIds, cases, casesCount); } @@ -333,14 +345,22 @@ private Optional getProsecutorDetails(final String prosecutingAuthor public CaseSearchResultsView searchCases(final JsonEnvelope envelope, final String query) { - final String prosecutingAuthorityFilterValue = prosecutingAuthorityAccessFilterConverter.convertToProsecutingAuthorityAccessFilter(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)); + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope); + final String prosecutingAuthorityFilterValue = prosecutingAuthorityAccessFilterConverter.convertToProsecutingAuthorityAccessFilter(prosecutingAuthorityAccess); + + final List agentProsecutorAuthorityAccessFilterValue; + if (prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess() == null || prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess().isEmpty()){ + agentProsecutorAuthorityAccessFilterValue = Arrays.asList("DUMMY_VALUE"); + } else { + agentProsecutorAuthorityAccessFilterValue = prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess(); + } - List searchResults = caseSearchResultRepository.findByUrn(prosecutingAuthorityFilterValue, query); + List searchResults = caseSearchResultRepository.findByUrn(prosecutingAuthorityFilterValue, query, agentProsecutorAuthorityAccessFilterValue); if (searchResults.isEmpty()) { - searchResults = caseSearchResultRepository.findByLastName(prosecutingAuthorityFilterValue, query); + searchResults = caseSearchResultRepository.findByLastName(prosecutingAuthorityFilterValue, query, agentProsecutorAuthorityAccessFilterValue); } if (searchResults.isEmpty()) { - searchResults = caseSearchResultRepository.findByLegalEntityName(prosecutingAuthorityFilterValue, query); + searchResults = caseSearchResultRepository.findByLegalEntityName(prosecutingAuthorityFilterValue, query, agentProsecutorAuthorityAccessFilterValue); } return new CaseSearchResultsView(searchResults); diff --git a/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/DatesToAvoidService.java b/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/DatesToAvoidService.java index 40d707fdec..5d01d518c7 100644 --- a/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/DatesToAvoidService.java +++ b/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/DatesToAvoidService.java @@ -11,6 +11,7 @@ import uk.gov.moj.cpp.sjp.query.view.converter.ProsecutingAuthorityAccessFilterConverter; import uk.gov.moj.cpp.sjp.query.view.response.CasesPendingDatesToAvoidView; +import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @@ -38,8 +39,17 @@ public class DatesToAvoidService { public CasesPendingDatesToAvoidView findCasesPendingDatesToAvoid(final JsonEnvelope envelope) { final ProsecutingAuthorityAccess prosecutingAuthorityAccess = prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope); final String prosecutingAuthorityFilterValue = prosecutingAuthorityAccessFilterConverter.convertToProsecutingAuthorityAccessFilter(prosecutingAuthorityAccess); + final List agentProsecutorAuthorityAccess; + + if (prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess() == null || prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess().isEmpty()) { + agentProsecutorAuthorityAccess = Arrays.asList("DUMMY_VALUE"); + } else { + agentProsecutorAuthorityAccess = prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess(); + } + + List pendingCases = pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid(prosecutingAuthorityFilterValue, + agentProsecutorAuthorityAccess); - List pendingCases = pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid(prosecutingAuthorityFilterValue); final int total = pendingCases.size(); final String regionFilter = getRegionFilterCriteria(envelope); @@ -51,6 +61,12 @@ public CasesPendingDatesToAvoidView findCasesPendingDatesToAvoid(final JsonEnvel pendingCases = filterByRegionId(envelope, pendingCases, regionFilter); } + final String prosecutingAuthorityFilter = getProsecutingAuthorityFilterCriteria(envelope); + + if (isFilterByProsecutingAuthority(prosecutingAuthorityFilter)) { + pendingCases = filterByProsecutingAuthority(pendingCases, prosecutingAuthorityFilter); + } + return new CasesPendingDatesToAvoidView(pendingCases, total); } @@ -58,6 +74,10 @@ private String getRegionFilterCriteria(final JsonEnvelope envelope) { return envelope.payloadAsJsonObject().getString("regionId", null); } + private String getProsecutingAuthorityFilterCriteria(final JsonEnvelope envelope) { + return envelope.payloadAsJsonObject().getString("prosecutingAuthority", null); + } + private boolean isFilterByUnknownRegion(final String regionFilter) { return nonNull(regionFilter) && isBlankRegion(regionFilter); } @@ -70,6 +90,10 @@ private boolean isFilterByRegionId(final String regionFilter) { return nonNull(regionFilter) && !isBlankRegion(regionFilter); } + private boolean isFilterByProsecutingAuthority(final String prosecutingAuthority) { + return nonNull(prosecutingAuthority); + } + private List filterByRegionId(final JsonEnvelope envelope, final List pendingCases, final String regionFilter) { final List regions = referenceDataService.getRegionalOrganisations(envelope); final String regionName = getRegionNameById(regionFilter, regions); @@ -87,6 +111,13 @@ private List filterByUnknownRegion(final List filterByProsecutingAuthority(final List pendingCases, final String prosecutingAuthorityFilter) { + return pendingCases + .stream() + .filter(pendingCase -> prosecutingAuthorityFilter.equalsIgnoreCase(pendingCase.getCaseDetail().getProsecutingAuthority())) + .collect(Collectors.toList()); + } + private String getRegionNameById(String regionId, List regions) { return regions.stream() .filter(region -> regionId.equalsIgnoreCase(region.getId().toString())) diff --git a/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/DefendantService.java b/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/DefendantService.java index 009bc73c76..939e48b35a 100644 --- a/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/DefendantService.java +++ b/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/DefendantService.java @@ -6,10 +6,12 @@ import static org.apache.commons.lang3.StringUtils.isBlank; import uk.gov.justice.services.messaging.JsonEnvelope; +import uk.gov.moj.cpp.accesscontrol.sjp.providers.ProsecutingAuthorityAccess; import uk.gov.moj.cpp.accesscontrol.sjp.providers.ProsecutingAuthorityProvider; import uk.gov.moj.cpp.sjp.domain.DefendantOutstandingFineRequest; import uk.gov.moj.cpp.sjp.domain.DefendantOutstandingFineRequestsQueryResult; import uk.gov.moj.cpp.sjp.persistence.entity.DefendantDetail; +import uk.gov.moj.cpp.sjp.persistence.entity.PendingDatesToAvoid; import uk.gov.moj.cpp.sjp.persistence.entity.view.UpdatedDefendantDetails; import uk.gov.moj.cpp.sjp.persistence.repository.DefendantRepository; import uk.gov.moj.cpp.sjp.query.view.converter.ProsecutingAuthorityAccessFilterConverter; @@ -41,14 +43,17 @@ public class DefendantService { private ReferenceDataService referenceDataService; public DefendantDetailsUpdatesView findDefendantDetailUpdates(final JsonEnvelope envelope) { + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = prosecutingAuthorityProvider + .getCurrentUsersProsecutingAuthorityAccess(envelope); final String prosecutingAuthorityFilterValue = prosecutingAuthorityAccessFilterConverter - .convertToProsecutingAuthorityAccessFilter(prosecutingAuthorityProvider - .getCurrentUsersProsecutingAuthorityAccess(envelope)); + .convertToProsecutingAuthorityAccessFilter(prosecutingAuthorityAccess); + final List agentProsecutorAuthorityAccessFilterValue = prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess(); final List updatedDefendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority( prosecutingAuthorityFilterValue, ZonedDateTime.now().minusDays(UPDATES_DAYS_HISTORY), - ZonedDateTime.now()); + ZonedDateTime.now(), + agentProsecutorAuthorityAccessFilterValue); List results = updatedDefendantDetails; @@ -62,6 +67,12 @@ public DefendantDetailsUpdatesView findDefendantDetailUpdates(final JsonEnvelope results = filterByRegionId(envelope, updatedDefendantDetails, filterCriteria); } + final String prosecutingAuthorityFilter = getProsecutingAuthorityFilterCriteria(envelope); + + if (isFilterByProsecutingAuthority(prosecutingAuthorityFilter)) { + results = filterByProsecutingAuthority(results, prosecutingAuthorityFilter); + } + return DefendantDetailsUpdatesView.of(updatedDefendantDetails.size(), sortByMostRecentUpdated(envelope, results)); } @@ -77,10 +88,21 @@ private List filterByRegionId(final JsonEnvelope envelo return sortedDefendantDetailsResult; } + private List filterByProsecutingAuthority(final List updatedDefendantDetails, final String prosecutingAuthorityFilter) { + return updatedDefendantDetails + .stream() + .filter(updatedDefendantDetail -> prosecutingAuthorityFilter.equalsIgnoreCase(updatedDefendantDetail.getProsecutingAuthority())) + .collect(Collectors.toList()); + } + private boolean isFilterByRegionId(final String filterCriteria) { return !isBlankRegion(filterCriteria) && nonNull(filterCriteria); } + private boolean isFilterByProsecutingAuthority(final String prosecutingAuthority) { + return nonNull(prosecutingAuthority); + } + private List filterByUnknownRegion(final List updatedDefendantDetails) { return updatedDefendantDetails .stream() @@ -96,6 +118,10 @@ private String getRegionFilterCriteria(final JsonEnvelope envelope) { return envelope.payloadAsJsonObject().getString("regionId", null); } + private String getProsecutingAuthorityFilterCriteria(final JsonEnvelope envelope) { + return envelope.payloadAsJsonObject().getString("prosecutingAuthority", null); + } + private List sortByMostRecentUpdated(final JsonEnvelope envelope, final List updatedDefendantDetails) { return updatedDefendantDetails.stream() .sorted(comparing(defendantDetails -> defendantDetails.getMostRecentUpdateDate().get())) diff --git a/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/ProgressionService.java b/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/ProgressionService.java index 9422df415c..5857d231a7 100644 --- a/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/ProgressionService.java +++ b/sjp-query/sjp-query-view/src/main/java/uk/gov/moj/cpp/sjp/query/view/service/ProgressionService.java @@ -60,7 +60,11 @@ public Optional findCaseById(UUID caseId) { withName(PROGRESSION_CASE_QUERY), requestPayload); final JsonEnvelope jsonResultEnvelope = requester.requestAsAdmin(requestEnvelope); - return ofNullable(jsonResultEnvelope.payloadAsJsonObject()); + if (!jsonResultEnvelope.payloadIsNull()){ + return ofNullable(jsonResultEnvelope.payloadAsJsonObject()); + } else { + return Optional.empty(); + } } public List findDefendantOffences(UUID caseId, DefendantDetail defendant) { diff --git a/sjp-query/sjp-query-view/src/raml/sjp-query-view.raml b/sjp-query/sjp-query-view/src/raml/sjp-query-view.raml index 1a824582e2..11a7a9e5bc 100644 --- a/sjp-query/sjp-query-view/src/raml/sjp-query-view.raml +++ b/sjp-query/sjp-query-view/src/raml/sjp-query-view.raml @@ -163,6 +163,10 @@ baseUri: http://localhost:8080/sjp-query-view/query/view/rest/sjp description: The defendant's region. type: string required: false + prosecutingAuthority: + description: The prosecuting authority + type: string + required: false responses: 200: @@ -459,6 +463,10 @@ baseUri: http://localhost:8080/sjp-query-view/query/view/rest/sjp description: The defendant's region id. type: string required: false + prosecutingAuthority: + description: The prosecuting authority + type: string + required: false responses: 200: description: OK diff --git a/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/SjpQueryViewTest.java b/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/SjpQueryViewTest.java index cb0471c05b..3998a7d55e 100644 --- a/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/SjpQueryViewTest.java +++ b/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/SjpQueryViewTest.java @@ -887,7 +887,9 @@ public void shouldFindDetailDetailUpdates() { true, updatedOn, REGION, - null); + null, + null + ); DefendantDetailsUpdatesView.DefendantDetailsUpdate defendantDetailsUpdateCompany = new DefendantDetailsUpdatesView.DefendantDetailsUpdate( null, @@ -901,7 +903,8 @@ public void shouldFindDetailDetailUpdates() { true, updatedOn, REGION, - LEGAL_ENTITY_NAME); + LEGAL_ENTITY_NAME, + null); when(defendantService.findDefendantDetailUpdates(queryEnvelope)).thenReturn(new DefendantDetailsUpdatesView( diff --git a/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/converter/ProsecutingAuthorityAccessFilterConverterTest.java b/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/converter/ProsecutingAuthorityAccessFilterConverterTest.java index e88b4a44aa..31b357d14a 100644 --- a/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/converter/ProsecutingAuthorityAccessFilterConverterTest.java +++ b/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/converter/ProsecutingAuthorityAccessFilterConverterTest.java @@ -3,6 +3,7 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; +import java.util.ArrayList; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -21,7 +22,7 @@ public class ProsecutingAuthorityAccessFilterConverterTest { static Stream data() { return Stream.of( Arguments.of(ProsecutingAuthorityAccess.NONE, null), - Arguments.of(ProsecutingAuthorityAccess.of(PROSECUTING_AUTHORITY), PROSECUTING_AUTHORITY), + Arguments.of(ProsecutingAuthorityAccess.of(PROSECUTING_AUTHORITY, new ArrayList<>()), PROSECUTING_AUTHORITY), Arguments.of(ProsecutingAuthorityAccess.ALL, "%") ); } diff --git a/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/CaseServiceFindCasesMissingSjpnTest.java b/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/CaseServiceFindCasesMissingSjpnTest.java index 892031ecbd..b5e7bb95b7 100644 --- a/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/CaseServiceFindCasesMissingSjpnTest.java +++ b/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/CaseServiceFindCasesMissingSjpnTest.java @@ -9,6 +9,8 @@ import static org.hamcrest.Matchers.hasSize; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -22,6 +24,7 @@ import uk.gov.moj.cpp.sjp.query.view.response.CasesMissingSjpnView; import java.time.LocalDate; +import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -39,6 +42,8 @@ public class CaseServiceFindCasesMissingSjpnTest { private static final LocalDate NOW = LocalDate.now(); private static final int COUNT = 10; private static final String TVL_FILTER_VALUE = "TVL"; + + private static final List AGENT_FILTER_VALUE = Arrays.asList("TFL", "XYZ"); private List caseDetails; @Mock private QueryResult queryResult; @@ -66,8 +71,10 @@ public void init() { public void shouldFindAllCasesMissingSjpn() { when(queryResult.getResultList()).thenReturn(caseDetails); - when(caseRepository.findCasesMissingSjpn(TVL_FILTER_VALUE)).thenReturn(queryResult); - when(caseRepository.countCasesMissingSjpn(TVL_FILTER_VALUE)).thenReturn(COUNT); + when(caseRepository.findCasesMissingSjpn(eq(TVL_FILTER_VALUE), anyList())) + .thenReturn(queryResult); + when(caseRepository.countCasesMissingSjpn(eq(TVL_FILTER_VALUE), anyList())) + .thenReturn(COUNT); final CasesMissingSjpnView casesMissingSjpnView = service.findCasesMissingSjpn(envelope, empty(), empty()); @@ -81,8 +88,8 @@ public void shouldFindAllCasesMissingSjpn() { public void shouldFindCasesMissingSjpnLimitedByPostingDate() { when(queryResult.getResultList()).thenReturn(caseDetails); - when(caseRepository.findCasesMissingSjpn(TVL_FILTER_VALUE, NOW)).thenReturn(queryResult); - when(caseRepository.countCasesMissingSjpn(TVL_FILTER_VALUE, NOW)).thenReturn(COUNT); + when(caseRepository.findCasesMissingSjpn(TVL_FILTER_VALUE, NOW, AGENT_FILTER_VALUE)).thenReturn(queryResult); + when(caseRepository.countCasesMissingSjpn(TVL_FILTER_VALUE, NOW, AGENT_FILTER_VALUE)).thenReturn(COUNT); final CasesMissingSjpnView casesMissingSjpnView = service.findCasesMissingSjpn(envelope, empty(), Optional.of(NOW)); @@ -96,12 +103,12 @@ public void shouldFindCasesMissingSjpnLimitedByPostingDate() { public void shouldReturnEmptyListWhenLimitIsZero() { final int limit = 0; - when(caseRepository.countCasesMissingSjpn(TVL_FILTER_VALUE)).thenReturn(COUNT); + when(caseRepository.countCasesMissingSjpn(TVL_FILTER_VALUE, AGENT_FILTER_VALUE)).thenReturn(COUNT); final CasesMissingSjpnView casesMissingSjpnView = service.findCasesMissingSjpn(envelope, Optional.of(limit), empty()); - verify(caseRepository, never()).findCasesMissingSjpn(any(String.class)); - verify(caseRepository, never()).findCasesMissingSjpn(any(String.class), any(LocalDate.class)); + verify(caseRepository, never()).findCasesMissingSjpn(any(String.class), any(List.class)); + verify(caseRepository, never()).findCasesMissingSjpn(any(String.class), any(LocalDate.class), any(List.class)); verify(queryResult, never()).maxResults(anyInt()); assertThat(casesMissingSjpnView.ids, hasSize(0)); @@ -114,12 +121,12 @@ public void shouldFindCasesMissingSjpnWhenLimitIsPositive() { when(queryResult.getResultList()).thenReturn(caseDetails); when(queryResult.maxResults(anyInt())).thenReturn(queryResult); - when(caseRepository.findCasesMissingSjpn(TVL_FILTER_VALUE)).thenReturn(queryResult); - when(caseRepository.countCasesMissingSjpn(TVL_FILTER_VALUE)).thenReturn(COUNT); + when(caseRepository.findCasesMissingSjpn(eq(TVL_FILTER_VALUE), anyList())).thenReturn(queryResult); + when(caseRepository.countCasesMissingSjpn(eq(TVL_FILTER_VALUE), anyList())).thenReturn(COUNT); final CasesMissingSjpnView casesMissingSjpnView = service.findCasesMissingSjpn(envelope, Optional.of(limit), empty()); - verify(caseRepository).findCasesMissingSjpn(TVL_FILTER_VALUE); + verify(caseRepository).findCasesMissingSjpn(TVL_FILTER_VALUE, AGENT_FILTER_VALUE); verify(queryResult).maxResults(limit); assertThat(casesMissingSjpnView.ids, equalTo(extractCaseIds(caseDetails))); @@ -132,12 +139,12 @@ public void shouldFindCasesMissingSjpnWithCountAndPostingDateLimits() { when(queryResult.getResultList()).thenReturn(caseDetails); when(queryResult.maxResults(anyInt())).thenReturn(queryResult); - when(caseRepository.findCasesMissingSjpn(TVL_FILTER_VALUE, NOW)).thenReturn(queryResult); - when(caseRepository.countCasesMissingSjpn(TVL_FILTER_VALUE, NOW)).thenReturn(COUNT); + when(caseRepository.findCasesMissingSjpn(TVL_FILTER_VALUE, NOW, AGENT_FILTER_VALUE)).thenReturn(queryResult); + when(caseRepository.countCasesMissingSjpn(TVL_FILTER_VALUE, NOW, AGENT_FILTER_VALUE)).thenReturn(COUNT); final CasesMissingSjpnView casesMissingSjpnView = service.findCasesMissingSjpn(envelope, Optional.of(limit), Optional.of(NOW)); - verify(caseRepository).findCasesMissingSjpn(TVL_FILTER_VALUE, NOW); + verify(caseRepository).findCasesMissingSjpn(TVL_FILTER_VALUE, NOW, AGENT_FILTER_VALUE); verify(queryResult).maxResults(limit); assertThat(casesMissingSjpnView.ids, equalTo(extractCaseIds(caseDetails))); @@ -145,11 +152,11 @@ public void shouldFindCasesMissingSjpnWithCountAndPostingDateLimits() { } private void mockProsecutingAuthorityAccess() { - when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)) .thenReturn(prosecutingAuthorityAccess); when(prosecutingAuthorityAccessFilterConverter.convertToProsecutingAuthorityAccessFilter(prosecutingAuthorityAccess)) .thenReturn(TVL_FILTER_VALUE); + when(prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess()).thenReturn(AGENT_FILTER_VALUE); } private CaseDetail createCaseDetails() { diff --git a/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/CaseServiceTest.java b/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/CaseServiceTest.java index dd7c913d5c..b017d976d7 100644 --- a/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/CaseServiceTest.java +++ b/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/CaseServiceTest.java @@ -18,6 +18,7 @@ import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.BDDMockito.given; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -720,12 +721,15 @@ public void shouldSearchCasesByUrn() { final String query = URN; final ProsecutingAuthorityAccess prosecutingAuthorityAccess = mock(ProsecutingAuthorityAccess.class); final String prosecutingAuthorityAccessFilterValue = "SOME_FILTER"; + final List agents = Arrays.asList("AGENT"); + when(prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess()) + .thenReturn(agents); when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)) .thenReturn(prosecutingAuthorityAccess); when(prosecutingAuthorityAccessFilterConverter.convertToProsecutingAuthorityAccessFilter(prosecutingAuthorityAccess)) .thenReturn(prosecutingAuthorityAccessFilterValue); - when(caseSearchResultRepository.findByUrn(prosecutingAuthorityAccessFilterValue, query)) + when(caseSearchResultRepository.findByUrn(prosecutingAuthorityAccessFilterValue, query, agents)) .thenReturn(singletonList(createCaseSearchResult())); final CaseSearchResultsView cases = service.searchCases(envelope, query); @@ -740,15 +744,55 @@ public void shouldSearchCasesByLastName() { final String query = LAST_NAME; final ProsecutingAuthorityAccess prosecutingAuthorityAccess = mock(ProsecutingAuthorityAccess.class); final String prosecutingAuthorityAccessFilterValue = "SOME_FILTER"; + final List agents = Arrays.asList("AGENT"); + when(prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess()) + .thenReturn(agents); when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)) .thenReturn(prosecutingAuthorityAccess); when(prosecutingAuthorityAccessFilterConverter.convertToProsecutingAuthorityAccessFilter(prosecutingAuthorityAccess)) .thenReturn(prosecutingAuthorityAccessFilterValue); - when(caseSearchResultRepository.findByUrn(prosecutingAuthorityAccessFilterValue, query)) + when(caseSearchResultRepository.findByUrn(prosecutingAuthorityAccessFilterValue, query, agents)) .thenReturn(emptyList()); - when(caseSearchResultRepository.findByLastName(prosecutingAuthorityAccessFilterValue, query)) + when(caseSearchResultRepository.findByLastName(prosecutingAuthorityAccessFilterValue, query, agents)) + .thenReturn(singletonList(createCaseSearchResult())); + + final CaseSearchResultsView cases = service.searchCases(envelope, query); + + verify(prosecutingAuthorityProvider).getCurrentUsersProsecutingAuthorityAccess(envelope); + + final CaseSearchResultsView.CaseSearchResultView result = cases.getResults().get(0); + assertThat(result.getCaseId(), equalTo(CASE_ID)); + assertThat(result.getUrn(), equalTo(URN)); + assertThat(result.getEnterpriseId(), equalTo(ENTERPRISE_ID)); + assertThat(result.getProsecutingAuthority(), equalTo(PROSECUTING_AUTHORITY)); + assertThat(result.getPostingDate(), equalTo(POSTING_DATE)); + assertThat(result.getStatus(), equalTo(CASE_STATUS_REFERRED_FOR_COURT_HEARING)); + assertThat(result.getDefendant().getFirstName(), equalTo(FIRST_NAME)); + assertThat(result.getDefendant().getLastName(), equalTo(LAST_NAME)); + assertThat(result.getDefendant().getDateOfBirth(), equalTo(DATE_OF_BIRTH)); + } + + @Test + public void shouldSearchCasesByLegalEntityName() { + final String query = LAST_NAME; + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = mock(ProsecutingAuthorityAccess.class); + final String prosecutingAuthorityAccessFilterValue = "SOME_FILTER"; + final List agents = new ArrayList<>(); + + when(prosecutingAuthorityAccess.getAgentProsecutorAuthorityAccess()) + .thenReturn(agents); + when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)) + .thenReturn(prosecutingAuthorityAccess); + when(prosecutingAuthorityAccessFilterConverter.convertToProsecutingAuthorityAccessFilter(prosecutingAuthorityAccess)) + .thenReturn(prosecutingAuthorityAccessFilterValue); + + when(caseSearchResultRepository.findByUrn(anyString(), anyString(), anyList())) + .thenReturn(emptyList()); + when(caseSearchResultRepository.findByLastName(anyString(), anyString(), anyList())) + .thenReturn(emptyList()); + when(caseSearchResultRepository.findByLegalEntityName(anyString(), anyString(), anyList())) .thenReturn(singletonList(createCaseSearchResult())); final CaseSearchResultsView cases = service.searchCases(envelope, query); diff --git a/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/DatesToAvoidServiceTest.java b/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/DatesToAvoidServiceTest.java index b59961cb6b..6e71a676cc 100644 --- a/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/DatesToAvoidServiceTest.java +++ b/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/DatesToAvoidServiceTest.java @@ -31,7 +31,9 @@ import uk.gov.moj.cpp.sjp.query.view.response.CasesPendingDatesToAvoidView; import java.time.LocalDate; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.UUID; @@ -48,6 +50,7 @@ public class DatesToAvoidServiceTest { private static final UUID OXFORD_REGION_ID = UUID.randomUUID(); private static final UUID LEICESTER_REGION_ID = UUID.randomUUID(); private static final String TITLE = "title"; + private static final String REGION = "region"; private static final String FIRST_NAME = "firstname"; private static final String LAST_NAME = "lastname"; private static final LocalDate DATE_OF_BIRTH = now().minusYears(50); @@ -80,7 +83,7 @@ public void setUpForLegalEntityDetails() { new PendingDatesToAvoid(createCaseDetailsWithRegionAndLegalEntityDetails(" ")), new PendingDatesToAvoid(createCaseDetailsWithRegionAndLegalEntityDetails(null)) ); - when(pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid(any())).thenReturn(pendingCases); + when(pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid(any(), any())).thenReturn(pendingCases); when(referenceDataService.getRegionalOrganisations(any())).thenReturn(REGIONS); } @Test @@ -93,17 +96,17 @@ public void shouldReturnFinancialMeansIfExists() { new PendingDatesToAvoid(createCaseDetailsWithRegionAndPersonalDetails(" ")), new PendingDatesToAvoid(createCaseDetailsWithRegionAndPersonalDetails(null)) ); - when(pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid(any())).thenReturn(pendingCases); final JsonEnvelope envelope = createEnvelope(); - final ProsecutingAuthorityAccess prosecutingAuthorityAccess = ProsecutingAuthorityAccess.of("TFL"); + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = ProsecutingAuthorityAccess.of("TFL", new ArrayList<>()); final String prosecutingAuthorityFilterValue = "TFL"; final CaseDetail caseDetail = new CaseDetail(UUID.randomUUID()); caseDetail.getDefendant().setAddress(new Address()); final List pendingDatesToAvoidList = Arrays.asList(new PendingDatesToAvoid(caseDetail)); + final List agentProsecutorAuthorityAccess = Arrays.asList("DUMMY_VALUE"); when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)).thenReturn(prosecutingAuthorityAccess); when(prosecutingAuthorityAccessFilterConverter.convertToProsecutingAuthorityAccessFilter(prosecutingAuthorityAccess)).thenReturn(prosecutingAuthorityFilterValue); - when(pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid(prosecutingAuthorityFilterValue)).thenReturn(pendingDatesToAvoidList); + when(pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid(prosecutingAuthorityFilterValue, agentProsecutorAuthorityAccess)).thenReturn(pendingDatesToAvoidList); final CasesPendingDatesToAvoidView datesToAvoidsView = datesToAvoidService.findCasesPendingDatesToAvoid(envelope); @@ -122,10 +125,13 @@ public void shouldFilterPendingCasesByRegionId() { new PendingDatesToAvoid(createCaseDetailsWithRegionAndPersonalDetails(" ")), new PendingDatesToAvoid(createCaseDetailsWithRegionAndPersonalDetails(null)) ); - when(pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid(any())).thenReturn(pendingCases); + when(pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid(any(), any())).thenReturn(pendingCases); when(referenceDataService.getRegionalOrganisations(any())).thenReturn(REGIONS); final JsonEnvelope envelope = createEnvelope(LONDON_REGION_ID); + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = ProsecutingAuthorityAccess.of("TFL", new ArrayList<>()); + when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)).thenReturn(prosecutingAuthorityAccess); + final CasesPendingDatesToAvoidView datesToAvoidsView = datesToAvoidService.findCasesPendingDatesToAvoid(envelope); assertThat(datesToAvoidsView.getCases(), hasSize(1)); @@ -136,10 +142,39 @@ public void shouldFilterPendingCasesByRegionId() { assertThat(datesToAvoidsView.getCount(), is(pendingCases.size())); } + @Test + public void shouldFilterPendingCasesByProsecutingAuthority() { + pendingCases = Arrays.asList( + new PendingDatesToAvoid(createCaseDetailsWithProsecutingAuthority("TFL")), + new PendingDatesToAvoid(createCaseDetailsWithProsecutingAuthority("TVL")), + new PendingDatesToAvoid(createCaseDetailsWithProsecutingAuthority("TFL")), + new PendingDatesToAvoid(createCaseDetailsWithProsecutingAuthority("TVL")), + new PendingDatesToAvoid(createCaseDetailsWithProsecutingAuthority("TFL")), + new PendingDatesToAvoid(createCaseDetailsWithProsecutingAuthority("TVL")) + ); + when(pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid(any(), any())).thenReturn(pendingCases); + final JsonEnvelope envelope = createEnvelopeWithProsecutingAuthority("TFL"); + + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = ProsecutingAuthorityAccess.of("TFL", new ArrayList<>()); + when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)).thenReturn(prosecutingAuthorityAccess); + + final CasesPendingDatesToAvoidView datesToAvoidsView = datesToAvoidService.findCasesPendingDatesToAvoid(envelope); + + assertThat(datesToAvoidsView.getCases(), hasSize(3)); + assertThat(datesToAvoidsView.getCases(), hasItem(hasProperty("region", equalTo("region")))); + assertEquals(FIRST_NAME, datesToAvoidsView.getCases().get(0).getFirstName()); + assertEquals(LAST_NAME, datesToAvoidsView.getCases().get(0).getLastName()); + assertEquals(DATE_OF_BIRTH, datesToAvoidsView.getCases().get(0).getDateOfBirth()); + assertThat(datesToAvoidsView.getCount(), is(pendingCases.size())); + } + @Test public void shouldFilterPendingCasesByRegionIdWithLegalEntityDetails() { setUpForLegalEntityDetails(); final JsonEnvelope envelope = createEnvelope(LONDON_REGION_ID); + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = ProsecutingAuthorityAccess.of("TFL", new ArrayList<>()); + + when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)).thenReturn(prosecutingAuthorityAccess); final CasesPendingDatesToAvoidView datesToAvoidsView = datesToAvoidService.findCasesPendingDatesToAvoid(envelope); @@ -160,9 +195,12 @@ public void shouldReturnAllPendingCasesWhenFilterCriteriaIsNotProvided() { new PendingDatesToAvoid(createCaseDetailsWithRegionAndPersonalDetails(" ")), new PendingDatesToAvoid(createCaseDetailsWithRegionAndPersonalDetails(null)) ); - when(pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid(any())).thenReturn(pendingCases); + when(pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid(any(), any())).thenReturn(pendingCases); final JsonEnvelope envelope = createEnvelope(); + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = ProsecutingAuthorityAccess.of("TFL", new ArrayList<>()); + when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)).thenReturn(prosecutingAuthorityAccess); + final CasesPendingDatesToAvoidView datesToAvoidsView = datesToAvoidService.findCasesPendingDatesToAvoid(envelope); assertThat(datesToAvoidsView.getCases(), containsInAnyOrder( @@ -186,9 +224,12 @@ public void shouldReturnPendingCasesWithEmptyRegionWhenFilterCriteriaIsUnknown() new PendingDatesToAvoid(createCaseDetailsWithRegionAndPersonalDetails(" ")), new PendingDatesToAvoid(createCaseDetailsWithRegionAndPersonalDetails(null)) ); - when(pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid(any())).thenReturn(pendingCases); + when(pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid(any(), any())).thenReturn(pendingCases); final JsonEnvelope envelope = createEnvelope("UNKNOWN"); + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = ProsecutingAuthorityAccess.of("TFL", new ArrayList<>()); + when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)).thenReturn(prosecutingAuthorityAccess); + final CasesPendingDatesToAvoidView datesToAvoidsView = datesToAvoidService.findCasesPendingDatesToAvoid(envelope); assertThat(datesToAvoidsView.getCases(), containsInAnyOrder( @@ -211,6 +252,13 @@ private JsonEnvelope createEnvelope(final String regionId) { .build(); } + private JsonEnvelope createEnvelopeWithProsecutingAuthority(final String prosecutingAuthority) { + return envelope() + .with(metadataWithRandomUUID("sjp.pending-dates-to-avoid")) + .withPayloadOf(prosecutingAuthority, "prosecutingAuthority") + .build(); + } + private JsonEnvelope createEnvelope() { return envelope() .with(metadataWithRandomUUID("sjp.pending-dates-to-avoid")) @@ -227,7 +275,23 @@ private CaseDetail createCaseDetailsWithRegionAndPersonalDetails(final String re .withLastName(LAST_NAME) .withDateOfBirth(DATE_OF_BIRTH) .build()) - .build()).build(); + .build()) + .build(); + } + + private CaseDetail createCaseDetailsWithProsecutingAuthority(final String prosecutingAuthority) { + return CaseDetailBuilder.aCase().withDefendantDetail( + DefendantDetailBuilder.aDefendantDetail() + .withRegion(REGION) + .withPersonalDetails(buildPersonalDetails() + .withTitle(TITLE) + .withFirstName(FIRST_NAME) + .withLastName(LAST_NAME) + .withDateOfBirth(DATE_OF_BIRTH) + .build()) + .build()) + .withProsecutingAuthority(prosecutingAuthority) + .build(); } private CaseDetail createCaseDetailsWithRegionAndLegalEntityDetails(final String region) { diff --git a/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/DefendantServiceTest.java b/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/DefendantServiceTest.java index 3e1a4b3702..a07d946474 100644 --- a/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/DefendantServiceTest.java +++ b/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/DefendantServiceTest.java @@ -21,9 +21,9 @@ import static uk.gov.moj.cpp.sjp.persistence.builder.UpdatedDefendantDetailsBuilder.anUpdatedDefendantDetails; import static uk.gov.moj.cpp.sjp.query.view.response.DefendantDetailsUpdatesView.DefendantDetailsUpdate; -import org.mockito.ArgumentMatchers; import uk.gov.justice.json.schemas.domains.sjp.Gender; import uk.gov.justice.services.messaging.JsonEnvelope; +import uk.gov.moj.cpp.accesscontrol.sjp.providers.ProsecutingAuthorityAccess; import uk.gov.moj.cpp.accesscontrol.sjp.providers.ProsecutingAuthorityProvider; import uk.gov.moj.cpp.sjp.domain.DefendantOutstandingFineRequestsQueryResult; import uk.gov.moj.cpp.sjp.persistence.builder.CaseDetailBuilder; @@ -37,6 +37,7 @@ import uk.gov.moj.cpp.sjp.query.view.response.DefendantDetailsUpdatesView; import java.time.ZonedDateTime; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; @@ -79,11 +80,11 @@ public class DefendantServiceTest { @BeforeEach public void setup() { - updatedDefendantDetails1 = createUpdatedDefendantDetailsWithRegion("London"); - updatedDefendantDetails2 = createUpdatedDefendantDetailsWithRegion("Oxford"); - updatedDefendantDetails3 = createUpdatedDefendantDetailsWithRegion(" "); - updatedDefendantDetails4 = createUpdatedDefendantDetailsWithRegion(""); - updatedDefendantDetails5 = createUpdatedDefendantDetailsWithRegion(null); + updatedDefendantDetails1 = createUpdatedDefendantDetailsWithRegionAndProsecutingAuthority("London", null); + updatedDefendantDetails2 = createUpdatedDefendantDetailsWithRegionAndProsecutingAuthority("Oxford", "TVL"); + updatedDefendantDetails3 = createUpdatedDefendantDetailsWithRegionAndProsecutingAuthority(" ", null); + updatedDefendantDetails4 = createUpdatedDefendantDetailsWithRegionAndProsecutingAuthority("", "TFL"); + updatedDefendantDetails5 = createUpdatedDefendantDetailsWithRegionAndProsecutingAuthority(null, "TFL"); updatedDefendantDetails = newArrayList( updatedDefendantDetails1, @@ -106,11 +107,15 @@ public void shouldFindDefendantUpdates() { updatedDefendantDetails3, updatedDefendantDetails2); when(defendantRepository.findUpdatedByCaseProsecutingAuthority( + any(), any(), any(), any())) .thenReturn(updatedDefendantDetails); + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = ProsecutingAuthorityAccess.of("TFL", new ArrayList<>()); + when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)).thenReturn(prosecutingAuthorityAccess); + final DefendantDetailsUpdatesView defendantDetailUpdates = defendantService.findDefendantDetailUpdates(envelope); assertThat(defendantDetailUpdates.getTotal(), is(3)); @@ -131,11 +136,15 @@ public void shouldObeyLimitProvided() { .mapToObj(i -> createUpdatedDefendantDetails(ZonedDateTime.now())) .collect(toList()); when(defendantRepository.findUpdatedByCaseProsecutingAuthority( + any(), any(), any(), any())) .thenReturn(updatedDefendantDetails); + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = ProsecutingAuthorityAccess.of("TFL", new ArrayList<>()); + when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)).thenReturn(prosecutingAuthorityAccess); + final DefendantDetailsUpdatesView defendantDetailUpdates = defendantService.findDefendantDetailUpdates(envelope); assertThat(defendantDetailUpdates.getTotal(), is(3)); @@ -170,11 +179,15 @@ public void shouldFindDefendantListByReadyCases() { public void shouldReturnDefendantDetailUpdatesUnfilteredWhenNoFilterCriteriaIsProvided() { final JsonEnvelope envelope = envelope(); when(defendantRepository.findUpdatedByCaseProsecutingAuthority( + any(), any(), any(), any())) .thenReturn(updatedDefendantDetails); + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = ProsecutingAuthorityAccess.of("TFL", new ArrayList<>()); + when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)).thenReturn(prosecutingAuthorityAccess); + final DefendantDetailsUpdatesView defendantDetailUpdates = defendantService.findDefendantDetailUpdates(envelope); assertThat(defendantDetailUpdates.getDefendantDetailsUpdates(), containsInAnyOrder( @@ -192,11 +205,15 @@ public void shouldReturnDefendantUpdatesFilteredByRegionId() { final JsonEnvelope envelope = envelope(LONDON_REGION_ID.toString()); when(referenceDataService.getRegionalOrganisations(any())).thenReturn(REGIONS); when(defendantRepository.findUpdatedByCaseProsecutingAuthority( + any(), any(), any(), any())) .thenReturn(updatedDefendantDetails); + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = ProsecutingAuthorityAccess.of("TFL", new ArrayList<>()); + when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)).thenReturn(prosecutingAuthorityAccess); + final DefendantDetailsUpdatesView defendantDetailUpdates = defendantService.findDefendantDetailUpdates(envelope); assertThat(defendantDetailUpdates.getDefendantDetailsUpdates(), containsInAnyOrder( @@ -204,15 +221,43 @@ public void shouldReturnDefendantUpdatesFilteredByRegionId() { assertThat(defendantDetailUpdates.getTotal(), is(updatedDefendantDetails.size())); } + @Test + public void shouldReturnDefendantUpdatesFilteredByProsecutingAuthority() { + final JsonEnvelope envelope = envelopeWithProsecutingAuthority("TFL"); + when(defendantRepository.findUpdatedByCaseProsecutingAuthority( + any(), + any(), + any(), + any())) + .thenReturn(updatedDefendantDetails); + + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = ProsecutingAuthorityAccess.of("TFL", new ArrayList<>()); + when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)).thenReturn(prosecutingAuthorityAccess); + + final DefendantDetailsUpdatesView defendantDetailUpdates = defendantService.findDefendantDetailUpdates(envelope); + + assertThat(defendantDetailUpdates.getDefendantDetailsUpdates().size(), is(2)); + assertThat(defendantDetailUpdates.getDefendantDetailsUpdates(), + containsInAnyOrder( + DefendantDetailsUpdate.of(updatedDefendantDetails4), + DefendantDetailsUpdate.of(updatedDefendantDetails5) + )); + assertThat(defendantDetailUpdates.getTotal(), is(updatedDefendantDetails.size())); + } + @Test public void shouldFindDefendantUpdatesFilteredEmptyList() { final JsonEnvelope envelope = envelope("UNKNOWN"); when(defendantRepository.findUpdatedByCaseProsecutingAuthority( + any(), any(), any(), any())) .thenReturn(updatedDefendantDetails); + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = ProsecutingAuthorityAccess.of("TFL", new ArrayList<>()); + when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)).thenReturn(prosecutingAuthorityAccess); + final DefendantDetailsUpdatesView defendantDetailUpdates = defendantService.findDefendantDetailUpdates(envelope); assertThat(defendantDetailUpdates.getDefendantDetailsUpdates(), containsInAnyOrder( @@ -231,10 +276,14 @@ public void shouldApplyLimitAfterFilteredByRegionAndOrderByLastUpdated() { final UpdatedDefendantDetails update2 = anUpdatedDefendantDetails().withUpdateTime(ZonedDateTime.now().minusDays(1)).withRegion("").build(); final UpdatedDefendantDetails update3 = anUpdatedDefendantDetails().withUpdateTime(ZonedDateTime.now().minusDays(2)).withRegion("").build(); when(defendantRepository.findUpdatedByCaseProsecutingAuthority(any(), + any(), any(), any())) .thenReturn(asList(update3, update2, update1)); + final ProsecutingAuthorityAccess prosecutingAuthorityAccess = ProsecutingAuthorityAccess.of("TFL", new ArrayList<>()); + when(prosecutingAuthorityProvider.getCurrentUsersProsecutingAuthorityAccess(envelope)).thenReturn(prosecutingAuthorityAccess); + final DefendantDetailsUpdatesView defendantDetailUpdates = defendantService.findDefendantDetailUpdates(envelope); assertThat(defendantDetailUpdates.getDefendantDetailsUpdates(), hasSize(2)); @@ -267,9 +316,12 @@ public void shouldFindDefendantListByReadyCasesWithOnlyRequiredFields() { } - private UpdatedDefendantDetails createUpdatedDefendantDetailsWithRegion(final String region) { + private UpdatedDefendantDetails createUpdatedDefendantDetailsWithRegionAndProsecutingAuthority(final String region, + final String prosecutingAuthority) { return anUpdatedDefendantDetails() .withRegion(region) + .withProsecutingAuthority(prosecutingAuthority) + .withUpdateTime(ZonedDateTime.now()) .build(); } @@ -288,6 +340,15 @@ private JsonEnvelope envelope(final String regionFilterCriteria) { ); } + private JsonEnvelope envelopeWithProsecutingAuthority(final String prosecutingAuthority) { + return envelopeFrom( + metadataWithRandomUUIDAndName(), + createObjectBuilder() + .add("prosecutingAuthority", prosecutingAuthority) + .add("limit", 5) + ); + } + private JsonEnvelope envelope(final String regionFilterCriteria, final int limit) { return envelopeFrom( metadataWithRandomUUIDAndName(), diff --git a/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/ProgressionServiceTest.java b/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/ProgressionServiceTest.java index 9cb07c0e8a..be2a84085d 100644 --- a/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/ProgressionServiceTest.java +++ b/sjp-query/sjp-query-view/src/test/java/uk/gov/moj/cpp/sjp/query/view/service/ProgressionServiceTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; import uk.gov.justice.services.core.requester.Requester; @@ -28,7 +29,7 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -@ExtendWith(MockitoExtension.class) +@ExtendWith({MockitoExtension.class}) public class ProgressionServiceTest { @Mock @@ -45,8 +46,9 @@ public class ProgressionServiceTest { @BeforeEach public void setup() { defaultDefendant = createDefaultDefendantDetail(); - when(envelope.payloadAsJsonObject()).thenReturn(createProsecutionCase(defaultDefendant.getPersonalDetails())); + lenient().when(envelope.payloadAsJsonObject()).thenReturn(createProsecutionCase(defaultDefendant.getPersonalDetails())); when(requester.requestAsAdmin(any())).thenReturn(envelope); + when(envelope.payloadIsNull()).thenReturn(false); } @Test @@ -60,6 +62,15 @@ public void shouldFindMatchingDefendantOffencesFromProsecutionCase() { assertEquals(expectedOffences, defendantOffences); } + @Test + void shouldNotFindMatchingDefendantOffencesFromEmptyProsecutionCase() { + when(envelope.payloadIsNull()).thenReturn(true); + final DefendantDetail defendantDetail = createDefaultDefendantDetail(); + final List defendantOffences = + progressionService.findDefendantOffences(UUID.randomUUID(), defendantDetail); + assertEquals(0, defendantOffences.size()); + } + @Test public void shouldFindNoMatchingDefendantOffencesFromProsecutionCase() { final DefendantDetail defendantDetail = createDefaultDefendantDetail(); diff --git a/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/entity/view/UpdatedDefendantDetails.java b/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/entity/view/UpdatedDefendantDetails.java index 921f43eb94..cbe0d71e0b 100644 --- a/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/entity/view/UpdatedDefendantDetails.java +++ b/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/entity/view/UpdatedDefendantDetails.java @@ -22,6 +22,7 @@ public class UpdatedDefendantDetails { private final UUID caseId; private final String region; private final String legalEntityName; + private final String prosecutingAuthority; @SuppressWarnings("squid:S00107") public UpdatedDefendantDetails( @@ -35,7 +36,8 @@ public UpdatedDefendantDetails( final String caseUrn, final UUID caseId, final String region, - final String legalEntityName) { + final String legalEntityName, + final String prosecutingAuthority) { this.firstName = firstName; this.lastName = lastName; @@ -48,6 +50,7 @@ public UpdatedDefendantDetails( this.caseId = caseId; this.region = region; this.legalEntityName = legalEntityName; + this.prosecutingAuthority = prosecutingAuthority; } /** @@ -115,6 +118,10 @@ public String getLegalEntityName() { return legalEntityName; } + public String getProsecutingAuthority() { + return prosecutingAuthority; + } + @SuppressWarnings("squid:S1067") @Override public boolean equals(final Object o) { @@ -136,7 +143,8 @@ public boolean equals(final Object o) { Objects.equal(caseUrn, that.caseUrn) && Objects.equal(caseId, that.caseId) && Objects.equal(region, that.region)&& - Objects.equal(legalEntityName, that.legalEntityName); + Objects.equal(legalEntityName, that.legalEntityName) && + Objects.equal(prosecutingAuthority, that.prosecutingAuthority); } @Override @@ -152,6 +160,7 @@ public int hashCode() { caseUrn, caseId, region, - legalEntityName); + legalEntityName, + prosecutingAuthority); } } diff --git a/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseRepository.java b/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseRepository.java index f1cebff613..c422dcbf23 100644 --- a/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseRepository.java +++ b/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseRepository.java @@ -101,20 +101,25 @@ public abstract CaseDetail findByUrnPostcode(@QueryParam("urn") String urn, public abstract List findByDefendantId(@QueryParam("defendantId") final UUID defendantId); @Query(value = "SELECT cd FROM CaseDetail cd LEFT OUTER JOIN cd.caseDocuments cdocs ON cdocs.documentType = 'SJPN' " + - "WHERE cdocs IS NULL AND cd.completed IS NOT true AND cd.prosecutingAuthority LIKE :prosecutingAuthorityFilter") - public abstract QueryResult findCasesMissingSjpn(@QueryParam("prosecutingAuthorityFilter") String prosecutingAuthorityFilter); + "WHERE cdocs IS NULL AND cd.completed IS NOT true AND ( cd.prosecutingAuthority LIKE :prosecutingAuthorityFilter OR cd.prosecutingAuthority IN (:agentProsecutorAuthorityAccess))") + public abstract QueryResult findCasesMissingSjpn(@QueryParam("prosecutingAuthorityFilter") String prosecutingAuthorityFilter, + @QueryParam("agentProsecutorAuthorityAccess") List agentProsecutorAuthorityAccess); @Query(value = "SELECT cd FROM CaseDetail cd LEFT OUTER JOIN cd.caseDocuments cdocs ON cdocs.documentType = 'SJPN' " + - "WHERE cdocs IS NULL AND cd.postingDate < :postedBefore AND cd.completed IS NOT true AND cd.prosecutingAuthority LIKE :prosecutingAuthorityFilter") - public abstract QueryResult findCasesMissingSjpn(@QueryParam("prosecutingAuthorityFilter") String prosecutingAuthorityFilter, @QueryParam("postedBefore") final LocalDate postedBefore); + "WHERE cdocs IS NULL AND cd.postingDate < :postedBefore AND cd.completed IS NOT true AND ( cd.prosecutingAuthority LIKE :prosecutingAuthorityFilter " + + "OR cd.prosecutingAuthority IN (:agentProsecutorAuthorityAccess))") + public abstract QueryResult findCasesMissingSjpn(@QueryParam("prosecutingAuthorityFilter") String prosecutingAuthorityFilter, @QueryParam("postedBefore") final LocalDate postedBefore, + @QueryParam("agentProsecutorAuthorityAccess") List agentProsecutorAuthorityAccess); @Query(value = "SELECT COUNT(cd) FROM CaseDetail cd LEFT OUTER JOIN cd.caseDocuments cdocs ON cdocs.documentType = 'SJPN' " + - "WHERE cdocs IS NULL AND cd.completed IS NOT true AND cd.prosecutingAuthority LIKE :prosecutingAuthorityFilter") - public abstract int countCasesMissingSjpn(@QueryParam("prosecutingAuthorityFilter") String prosecutingAuthorityFilter); + "WHERE cdocs IS NULL AND cd.completed IS NOT true AND ( cd.prosecutingAuthority LIKE :prosecutingAuthorityFilter OR cd.prosecutingAuthority IN (:agentProsecutorAuthorityAccess) )") + public abstract int countCasesMissingSjpn(@QueryParam("prosecutingAuthorityFilter") String prosecutingAuthorityFilter, + @QueryParam("agentProsecutorAuthorityAccess") List agentProsecutorAuthorityAccess); @Query(value = "SELECT COUNT(cd) FROM CaseDetail cd LEFT OUTER JOIN cd.caseDocuments cdocs ON cdocs.documentType = 'SJPN' " + - "WHERE cdocs IS NULL AND cd.postingDate < :postedBefore AND cd.completed IS NOT true AND cd.prosecutingAuthority LIKE :prosecutingAuthorityFilter") - public abstract int countCasesMissingSjpn(@QueryParam("prosecutingAuthorityFilter") String prosecutingAuthorityFilter, @QueryParam("postedBefore") final LocalDate postedBefore); + "WHERE cdocs IS NULL AND cd.postingDate < :postedBefore AND cd.completed IS NOT true AND ( cd.prosecutingAuthority LIKE :prosecutingAuthorityFilter OR cd.prosecutingAuthority IN (:agentProsecutorAuthorityAccess))") + public abstract int countCasesMissingSjpn(@QueryParam("prosecutingAuthorityFilter") String prosecutingAuthorityFilter, @QueryParam("postedBefore") final LocalDate postedBefore, + @QueryParam("agentProsecutorAuthorityAccess") List agentProsecutorAuthorityAccess); @Query(value = "SELECT cd.caseDocuments FROM CaseDetail cd where cd.id = :caseId") public abstract List findCaseDocuments(@QueryParam("caseId") final UUID caseId); diff --git a/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseSearchResultRepository.java b/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseSearchResultRepository.java index fb6fdd3be1..6041f65f37 100644 --- a/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseSearchResultRepository.java +++ b/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseSearchResultRepository.java @@ -15,21 +15,24 @@ public interface CaseSearchResultRepository extends EntityRepository findByLastName(@QueryParam("prosecutingAuthority") String prosecutingAuthority, @QueryParam("lastName") String lastName); + List findByLastName(@QueryParam("prosecutingAuthority") String prosecutingAuthority, @QueryParam("lastName") String lastName, + @QueryParam("agentProsecutorAuthorityAccess") List agentProsecutorAuthorityAccess); @Query("from CaseSearchResult as r inner join fetch r.caseSummary as c where upper(r.caseSummary.urn) = upper(:urn) and r.dateAdded = " + "(select max(z.dateAdded) from CaseSearchResult as z where z.caseId=r.caseId) " + - "and r.caseSummary.prosecutingAuthority like :prosecutingAuthority " + + "and (r.caseSummary.prosecutingAuthority like :prosecutingAuthority OR r.caseSummary.prosecutingAuthority IN (:agentProsecutorAuthorityAccess)) " + "order by r.firstName ASC, c.postingDate DESC") - List findByUrn(@QueryParam("prosecutingAuthority") String prosecutingAuthority, @QueryParam("urn") String urn); + List findByUrn(@QueryParam("prosecutingAuthority") String prosecutingAuthority, @QueryParam("urn") String urn, + @QueryParam("agentProsecutorAuthorityAccess") List agentProsecutorAuthorityAccess); List findByCaseId(UUID caseId); @Query("from CaseSearchResult as r inner join fetch r.caseSummary as c where upper(r.legalEntityName) = upper(:legalEntityName) and r.dateAdded = " + "(select max(z.dateAdded) from CaseSearchResult as z where z.caseId=r.caseId and upper(z.legalEntityName) = upper(:legalEntityName)) " + - "and r.caseSummary.prosecutingAuthority like :prosecutingAuthority " + + "and (r.caseSummary.prosecutingAuthority like :prosecutingAuthority OR r.caseSummary.prosecutingAuthority IN (:agentProsecutorAuthorityAccess)) " + "order by r.legalEntityName ASC, c.postingDate DESC") - List findByLegalEntityName(@QueryParam("prosecutingAuthority") String prosecutingAuthority, @QueryParam("legalEntityName") String legalEntityName); + List findByLegalEntityName(@QueryParam("prosecutingAuthority") String prosecutingAuthority, @QueryParam("legalEntityName") String legalEntityName, + @QueryParam("agentProsecutorAuthorityAccess") List agentProsecutorAuthorityAccess); } diff --git a/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/DefendantRepository.java b/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/DefendantRepository.java index 8842c06873..04dc246a73 100644 --- a/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/DefendantRepository.java +++ b/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/DefendantRepository.java @@ -5,6 +5,7 @@ import uk.gov.moj.cpp.sjp.persistence.entity.view.UpdatedDefendantDetails; import java.time.ZonedDateTime; +import java.util.Collections; import java.util.List; import java.util.UUID; @@ -34,10 +35,11 @@ public abstract class DefendantRepository implements EntityRepository dd.updatesAcknowledgedAt)) " + "OR ((dd.personalDetails.dateOfBirthUpdatedAt BETWEEN :fromDate and :toDate) AND (dd.personalDetails.dateOfBirthUpdatedAt IS NOT NULL AND dd.updatesAcknowledgedAt IS NULL OR dd.personalDetails.dateOfBirthUpdatedAt > dd.updatesAcknowledgedAt)) " + "OR ((dd.nameUpdatedAt BETWEEN :fromDate and :toDate) AND (dd.nameUpdatedAt IS NOT NULL AND dd.updatesAcknowledgedAt IS NULL OR dd.nameUpdatedAt > dd.updatesAcknowledgedAt)))"; @@ -47,11 +49,17 @@ public abstract class DefendantRepository implements EntityRepository findUpdatedByCaseProsecutingAuthority( String prosecutingAuthority, ZonedDateTime fromDate, - ZonedDateTime toDate) { + ZonedDateTime toDate, + List agentProsecutorAuthorityAccess) { + + if (agentProsecutorAuthorityAccess == null || agentProsecutorAuthorityAccess.isEmpty()) { + agentProsecutorAuthorityAccess = Collections.singletonList("DUMMY_VALUE"); + } final javax.persistence.Query query = entityManager.createQuery(UPDATED_DEFENDANT_DETAILS); query.setParameter("prosecutingAuthority", prosecutingAuthority); + query.setParameter("agentProsecutorAuthorityAccess", agentProsecutorAuthorityAccess); query.setParameter("fromDate", fromDate); query.setParameter("toDate", toDate); diff --git a/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/PendingDatesToAvoidRepository.java b/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/PendingDatesToAvoidRepository.java index daec87296e..47e0aa7e07 100644 --- a/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/PendingDatesToAvoidRepository.java +++ b/sjp-viewstore/sjp-viewstore-persistence/src/main/java/uk/gov/moj/cpp/sjp/persistence/repository/PendingDatesToAvoidRepository.java @@ -19,9 +19,10 @@ public abstract class PendingDatesToAvoidRepository implements EntityRepository< @Query(value = "SELECT pda FROM PendingDatesToAvoid as pda INNER JOIN pda.caseDetail as cd " + "WHERE cd.datesToAvoid IS NULL AND cd.assigneeId IS NULL AND cd.completed = false " + - "AND cd.prosecutingAuthority like :prosecutingAuthority " + + "AND (cd.prosecutingAuthority like :prosecutingAuthority OR cd.prosecutingAuthority IN (:agentProsecutorAuthorityAccess) ) " + "ORDER BY pda.pleaDate ASC") - public abstract List findCasesPendingDatesToAvoid(@QueryParam("prosecutingAuthority") String prosecutingAuthority); + public abstract List findCasesPendingDatesToAvoid(@QueryParam("prosecutingAuthority") String prosecutingAuthority, + @QueryParam("agentProsecutorAuthorityAccess") List agentProsecutorAuthorityAccess); public void removeByCaseId(final UUID caseId) { Optional.ofNullable(this.findBy(caseId)).ifPresent(this::remove); diff --git a/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/builder/UpdatedDefendantDetailsBuilder.java b/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/builder/UpdatedDefendantDetailsBuilder.java index ace9bf31b5..4372490042 100644 --- a/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/builder/UpdatedDefendantDetailsBuilder.java +++ b/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/builder/UpdatedDefendantDetailsBuilder.java @@ -11,9 +11,12 @@ public class UpdatedDefendantDetailsBuilder { private ZonedDateTime updateTime; private String region; + private String prosecutingAuthority; + private UpdatedDefendantDetailsBuilder() { this.updateTime = ZonedDateTime.now(); this.region = "region"; + this.prosecutingAuthority = "TFL"; } public static UpdatedDefendantDetailsBuilder anUpdatedDefendantDetails() { @@ -30,6 +33,11 @@ public UpdatedDefendantDetailsBuilder withRegion(final String region) { return this; } + public UpdatedDefendantDetailsBuilder withProsecutingAuthority(final String prosecutingAuthority) { + this.prosecutingAuthority = prosecutingAuthority; + return this; + } + public UpdatedDefendantDetails build() { return new UpdatedDefendantDetails( "firstName", @@ -42,6 +50,7 @@ public UpdatedDefendantDetails build() { "caseUrn", UUID.randomUUID(), region, - null); + null, + prosecutingAuthority); } } diff --git a/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/entity/view/UpdatedDefendantDetailsTest.java b/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/entity/view/UpdatedDefendantDetailsTest.java index bb666c36c0..c0729af9d8 100644 --- a/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/entity/view/UpdatedDefendantDetailsTest.java +++ b/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/entity/view/UpdatedDefendantDetailsTest.java @@ -27,6 +27,7 @@ public void shouldMostRecentUpdateDateForSingleUpdate() { "caseUrn", UUID.randomUUID(), "region", + null, null); final Optional mostRecentUpdateDataOptional = updatedDefendantDetails.getMostRecentUpdateDate(); @@ -52,6 +53,7 @@ public void shouldCorrectlyCompareUpdateDates() { "caseUrn", UUID.randomUUID(), "region", + null, null); final Optional mostRecentUpdateDataOptional = updatedDefendantDetails.getMostRecentUpdateDate(); diff --git a/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseRepositorySjpnTest.java b/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseRepositorySjpnTest.java index 00d0362f1f..f427c6e6d9 100644 --- a/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseRepositorySjpnTest.java +++ b/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseRepositorySjpnTest.java @@ -64,7 +64,7 @@ public void addCasesAndDocuments() { @Test public void findCasesMissingSjpnForTflProsecutors() { - final List actualCases = caseRepository.findCasesMissingSjpn(TFL_PROSECUTOR_FILTER_VALUE).getResultList(); + final List actualCases = caseRepository.findCasesMissingSjpn(TFL_PROSECUTOR_FILTER_VALUE, Collections.emptyList()).getResultList(); final List actualCaseIds = extractCaseIds(actualCases); assertThat(actualCaseIds, equalTo(extractCaseIds(tflCases.uncompletedSjpCasesWithoutSjpn))); @@ -72,7 +72,7 @@ public void findCasesMissingSjpnForTflProsecutors() { @Test public void findCasesMissingSjpnForCourtAdmin() { - final List actualCases = caseRepository.findCasesMissingSjpn(COURT_ADMIN_FILTER_VALUE).getResultList(); + final List actualCases = caseRepository.findCasesMissingSjpn(COURT_ADMIN_FILTER_VALUE, Collections.emptyList()).getResultList(); final List actualCaseIds = extractCaseIds(actualCases); assertThat(actualCaseIds, equalTo(extractCaseIds(allCases.uncompletedSjpCasesWithoutSjpn))); @@ -82,7 +82,7 @@ public void findCasesMissingSjpnForCourtAdmin() { public void findCasesMissingSjpnWithLimitForTflProsecutors() { int limit = 3; - final List actualCases = caseRepository.findCasesMissingSjpn(TFL_PROSECUTOR_FILTER_VALUE).maxResults(limit).getResultList(); + final List actualCases = caseRepository.findCasesMissingSjpn(TFL_PROSECUTOR_FILTER_VALUE, Collections.emptyList()).maxResults(limit).getResultList(); final List actualCaseIds = extractCaseIds(actualCases); assertThat(actualCaseIds, hasSize(limit)); @@ -95,7 +95,7 @@ public void findCasesMissingSjpnWithLimitForTflProsecutors() { public void findCasesMissingSjpnWithLimitForCourtAdmin() { int limit = 3; - final List actualCases = caseRepository.findCasesMissingSjpn(COURT_ADMIN_FILTER_VALUE).maxResults(limit).getResultList(); + final List actualCases = caseRepository.findCasesMissingSjpn(COURT_ADMIN_FILTER_VALUE, Collections.emptyList()).maxResults(limit).getResultList(); final List actualCaseIds = extractCaseIds(actualCases); assertThat(actualCaseIds, hasSize(limit)); @@ -106,14 +106,14 @@ public void findCasesMissingSjpnWithLimitForCourtAdmin() { @Test public void countCasesMissingSjpnForTflProsecutors() { - final int actualCaseCount = caseRepository.countCasesMissingSjpn(TFL_PROSECUTOR_FILTER_VALUE); + final int actualCaseCount = caseRepository.countCasesMissingSjpn(TFL_PROSECUTOR_FILTER_VALUE, Collections.emptyList()); assertThat(actualCaseCount, equalTo(tflCases.uncompletedSjpCasesWithoutSjpn.size())); } @Test public void countCasesMissingSjpnForCourAdmin() { - final int actualCaseCount = caseRepository.countCasesMissingSjpn(COURT_ADMIN_FILTER_VALUE); + final int actualCaseCount = caseRepository.countCasesMissingSjpn(COURT_ADMIN_FILTER_VALUE, Collections.emptyList()); assertThat(actualCaseCount, equalTo(allCases.uncompletedSjpCasesWithoutSjpn.size())); } @@ -123,7 +123,7 @@ public void countCasesMissingSjpnWithPostingDateOlderThanSpecifiedForTflProsecut int sjpCasesMissingSjpnCount = tflCases.uncompletedSjpCasesWithoutSjpn.size(); for (int i = 0; i < sjpCasesMissingSjpnCount; i++) { final LocalDate postingDate = LocalDate.now().minusDays(i); - final int actualCaseCount = caseRepository.countCasesMissingSjpn(TFL_PROSECUTOR_FILTER_VALUE, postingDate); + final int actualCaseCount = caseRepository.countCasesMissingSjpn(TFL_PROSECUTOR_FILTER_VALUE, postingDate, Collections.emptyList()); assertThat(actualCaseCount, equalTo(sjpCasesMissingSjpnCount - i)); } } @@ -133,7 +133,7 @@ public void countCasesMissingSjpnWithPostingDateOlderThanSpecifiedForCourtAdmin( int sjpCasesMissingSjpnCount = allCases.uncompletedSjpCasesWithoutSjpn.size(); for (int i = 0; i < sjpCasesMissingSjpnCount / NUMBER_OF_PROSECUTING_AUTHORITIES; i++) { final LocalDate postingDate = LocalDate.now().minusDays(i); - final int actualCaseCount = caseRepository.countCasesMissingSjpn(COURT_ADMIN_FILTER_VALUE, postingDate); + final int actualCaseCount = caseRepository.countCasesMissingSjpn(COURT_ADMIN_FILTER_VALUE, postingDate, Collections.emptyList()); assertThat(actualCaseCount, equalTo(sjpCasesMissingSjpnCount - (i * NUMBER_OF_PROSECUTING_AUTHORITIES))); } } diff --git a/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseSearchResultRepositoryTest.java b/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseSearchResultRepositoryTest.java index 7c95ba5ed4..32df84d216 100644 --- a/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseSearchResultRepositoryTest.java +++ b/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/CaseSearchResultRepositoryTest.java @@ -16,6 +16,8 @@ import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; @@ -51,7 +53,18 @@ public void shouldFindByLastName() { createCaseSearchResult(false); // check it is case insensitive - final List results = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_WILDCARD, LAST_NAME.toLowerCase()); + final List results = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_WILDCARD, LAST_NAME.toLowerCase(), new ArrayList<>()); + + assertThat(results.get(0).getLastName(), equalTo(LAST_NAME)); + assertThat(results.get(0).getCaseSummary().getUrn(), equalTo(URN)); + } + + @Test + public void shouldFindByLastNameForAgent() { + + createCaseSearchResult(PROSECUTING_AUTHORITY_2); + + final List results = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME.toLowerCase(), Arrays.asList(PROSECUTING_AUTHORITY_2)); assertThat(results.get(0).getLastName(), equalTo(LAST_NAME)); assertThat(results.get(0).getCaseSummary().getUrn(), equalTo(URN)); @@ -62,7 +75,7 @@ public void shouldNotFindByLastNameForOtherProsecutingAuthority() { createCaseSearchResult(PROSECUTING_AUTHORITY_2); - final List results = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME.toLowerCase()); + final List results = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME.toLowerCase(), new ArrayList<>()); assertThat(results.size(), is(0)); } @@ -74,7 +87,7 @@ public void shouldFindByLastNameWithOrdering() { final CaseSearchResult caseSearchResultB = createCaseSearchResultWithFirstname("firstNameB", PROSECUTING_AUTHORITY_1); // check results come back ordered by first name ascending - final List results = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_WILDCARD, LAST_NAME.toLowerCase()); + final List results = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_WILDCARD, LAST_NAME.toLowerCase(), new ArrayList<>()); assertThat(results.get(0).getLastName(), equalTo(LAST_NAME)); assertThat(results.get(0).getFirstName(), equalTo(caseSearchResultA.getFirstName())); @@ -88,7 +101,7 @@ public void shouldFindByLastNameEvenThoughItWasChanged() { // given final CaseSearchResult caseSearchResult = createCaseSearchResult(false); // when - final List results = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME.toLowerCase()); + final List results = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME.toLowerCase(), new ArrayList<>()); // then assertThat(results, hasSize(1)); ensure(results.get(0), LAST_NAME, IS_CURRENT); @@ -97,13 +110,13 @@ public void shouldFindByLastNameEvenThoughItWasChanged() { simulateDefendantLastNameChanged(LAST_NAME_UPDATED, results.get(0).getCaseId()); // when - final List afterUpdateForOldLastName = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME.toLowerCase()); + final List afterUpdateForOldLastName = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME.toLowerCase(), new ArrayList<>()); // then assertThat(afterUpdateForOldLastName, hasSize(1)); ensure(afterUpdateForOldLastName.get(0), LAST_NAME_UPDATED, IS_OLD); // when - final List afterUpdateForNewLastName = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME_UPDATED.toLowerCase()); + final List afterUpdateForNewLastName = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME_UPDATED.toLowerCase(), new ArrayList<>()); // then assertThat(afterUpdateForNewLastName, hasSize(1)); ensure(afterUpdateForNewLastName.get(0), LAST_NAME_UPDATED, IS_CURRENT); @@ -112,13 +125,13 @@ public void shouldFindByLastNameEvenThoughItWasChanged() { simulateDefendantLastNameChanged(LAST_NAME, caseSearchResult.getCaseId()); // when - final List afterUpdateBackForOriginalLastName = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME.toLowerCase()); + final List afterUpdateBackForOriginalLastName = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME.toLowerCase(), new ArrayList<>()); // then assertThat(afterUpdateBackForOriginalLastName, hasSize(1)); ensure(afterUpdateBackForOriginalLastName.get(0), LAST_NAME, IS_CURRENT); // when - final List afterUpdateBackForUpdatedButRevertedLastName = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME_UPDATED.toLowerCase()); + final List afterUpdateBackForUpdatedButRevertedLastName = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME_UPDATED.toLowerCase(), new ArrayList<>()); // then assertThat(afterUpdateBackForUpdatedButRevertedLastName, hasSize(1)); ensure(afterUpdateBackForUpdatedButRevertedLastName.get(0), LAST_NAME, IS_OLD); @@ -128,7 +141,7 @@ public void shouldFindByLastNameEvenThoughItWasChanged() { //simulateDefendantLastNameChanged(LAST_NAME_UPDATED, caseSearchResultRepository.findByUrn(PROSECUTING_AUTHORITY_1, URN)); createCaseSearchResult(false); // when - final List resultsAfterInsert = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME.toLowerCase()); + final List resultsAfterInsert = caseSearchResultRepository.findByLastName(PROSECUTING_AUTHORITY_1, LAST_NAME.toLowerCase(), new ArrayList<>()); // then the results should contain 1 entry with LAST_NAME and 1 entry with LAST_NAME_UPDATED assertThat(resultsAfterInsert, hasSize(2)); ensure(resultsAfterInsert.get(0), LAST_NAME_UPDATED, IS_OLD); @@ -146,19 +159,31 @@ public void shouldFindByUrn() { final CaseSearchResult caseSearchResult = createCaseSearchResult(false); // check it is case insensitive - final List results = caseSearchResultRepository.findByUrn(PROSECUTING_AUTHORITY_WILDCARD, URN.toLowerCase()); + final List results = caseSearchResultRepository.findByUrn(PROSECUTING_AUTHORITY_WILDCARD, URN.toLowerCase(), new ArrayList<>()); assertThat(results.get(0).getLastName(), equalTo(caseSearchResult.getLastName())); assertThat(results.get(0).getCaseSummary().getUrn(), equalTo(caseSearchResult.getCaseSummary().getUrn())); } + @Test + public void shouldFindByUrnForAgent() { + + createCaseSearchResult(PROSECUTING_AUTHORITY_2); + + // check it is case insensitive + final List results = caseSearchResultRepository.findByUrn(PROSECUTING_AUTHORITY_1, URN.toLowerCase(), Arrays.asList(PROSECUTING_AUTHORITY_2)); + + assertThat(results.get(0).getLastName(), equalTo(LAST_NAME)); + assertThat(results.get(0).getCaseSummary().getUrn(), equalTo(URN)); + } + @Test public void shouldNotFindByUrnForOtherProsecutingAuthority() { createCaseSearchResult(PROSECUTING_AUTHORITY_2); // check it is case insensitive - final List results = caseSearchResultRepository.findByUrn(PROSECUTING_AUTHORITY_1, URN.toLowerCase()); + final List results = caseSearchResultRepository.findByUrn(PROSECUTING_AUTHORITY_1, URN.toLowerCase(), new ArrayList<>()); assertThat(results.size(), is(0)); } @@ -171,7 +196,7 @@ public void shouldFindByUrnOnlyLatest() { simulateDefendantLastNameChanged(LAST_NAME, caseSearchResult.getCaseId()); // when - final List resultsByUrn = caseSearchResultRepository.findByUrn(PROSECUTING_AUTHORITY_1, URN); + final List resultsByUrn = caseSearchResultRepository.findByUrn(PROSECUTING_AUTHORITY_1, URN, new ArrayList<>()); final List resultsByCaseId = caseSearchResultRepository.findByCaseId(caseSearchResult.getCaseId()); // then @@ -288,7 +313,17 @@ private CaseSearchResult createCaseSearchResultWithLegalEntity( public void shouldFindByLegalEntityName() { createCaseSearchResult(true); // check it is case insensitive - final List results = caseSearchResultRepository.findByLegalEntityName(PROSECUTING_AUTHORITY_WILDCARD, LEGAL_ENTITY_NAME.toLowerCase()); + final List results = caseSearchResultRepository.findByLegalEntityName(PROSECUTING_AUTHORITY_WILDCARD, LEGAL_ENTITY_NAME.toLowerCase(), new ArrayList<>()); + + assertEquals(LEGAL_ENTITY_NAME, results.get(0).getLegalEntityName()); + assertEquals(URN, results.get(0).getCaseSummary().getUrn()); + } + + @Test + public void shouldFindByLegalEntityNameForAgent() { + createCaseSearchResult(true); + // check it is case insensitive + final List results = caseSearchResultRepository.findByLegalEntityName(PROSECUTING_AUTHORITY_2, LEGAL_ENTITY_NAME.toLowerCase(), Arrays.asList(PROSECUTING_AUTHORITY_1)); assertEquals(LEGAL_ENTITY_NAME, results.get(0).getLegalEntityName()); assertEquals(URN, results.get(0).getCaseSummary().getUrn()); diff --git a/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/DefendantRepositoryTest.java b/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/DefendantRepositoryTest.java index 40389e9c73..3298af8102 100644 --- a/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/DefendantRepositoryTest.java +++ b/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/DefendantRepositoryTest.java @@ -19,6 +19,7 @@ import java.time.LocalDate; import java.time.ZonedDateTime; +import java.util.Collections; import java.util.List; import java.util.UUID; @@ -49,7 +50,7 @@ public void shouldFindDefendantWithDoBUpdatedAndUpdatesNotAcknowledgedYet() { final UpdatedDefendantDetails defendant = createCaseDetail(personalDetails, "TVL", null,null,null); - final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now()); + final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now(), Collections.emptyList()); assertThat(defendantDetails, iterableWithSize(1)); assertThat(defendantDetails, contains(defendant)); @@ -62,7 +63,7 @@ public void shouldFindDefendantWithDoBUpdatedAndUpdatesAcknowledgedBefore() { final UpdatedDefendantDetails defendant = createCaseDetail(personalDetails, "TVL", now().minusDays(2),null,null); - final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now()); + final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now(), Collections.emptyList()); assertThat(defendantDetails, iterableWithSize(1)); assertThat(defendantDetails, contains(defendant)); @@ -75,7 +76,7 @@ public void shouldIgnoreDefendantWithDoBUpdateWhenAcknowledged() { createCaseDetail(personalDetails, "TVL", now(UTC),null,null); - final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now()); + final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now(), Collections.emptyList()); assertThat(defendantDetails, iterableWithSize(0)); } @@ -86,7 +87,7 @@ public void shouldFindDefendantWithAddressUpdatedAndUpdatesNotAcknowledgedYet() final UpdatedDefendantDetails defendant = createCaseDetail(personalDetails, "TVL", null,now(UTC),null); - final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now()); + final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now(), Collections.emptyList()); assertThat(defendantDetails, iterableWithSize(1)); assertThat(defendantDetails.get(0), is(defendant)); @@ -98,7 +99,7 @@ public void shouldIgnoreDefendantWhenUpdateHappenedMoreThan10DaysAgo() { createCaseDetail(personalDetails, "TVL", null, now(UTC).minusDays(15), null); - final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now()); + final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now(), Collections.emptyList()); assertThat(defendantDetails, iterableWithSize(0)); } @@ -109,7 +110,7 @@ public void shouldFindDefendantWithAddressUpdatedAndUpdatesAcknowledgedBefore() final UpdatedDefendantDetails defendant = createCaseDetail(personalDetails, "TVL", now(UTC).minusDays(2), now(UTC), null); - final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now()); + final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now(), Collections.emptyList()); assertThat(defendantDetails, iterableWithSize(1)); assertThat(defendantDetails.get(0), is(defendant)); @@ -121,7 +122,7 @@ public void shouldIgnoreDefendantWithAddressUpdateWhenAcknowledged() { createCaseDetail(personalDetails, "TVL", now(UTC), now(UTC).minusDays(2), null); - final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now()); + final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now(), Collections.emptyList()); assertThat(defendantDetails, iterableWithSize(0)); } @@ -132,7 +133,7 @@ public void shouldFindDefendantWithNameUpdatedAndUpdatesNotAcknowledgedYet() { final UpdatedDefendantDetails defendant = createCaseDetail(personalDetails, "TVL", null, null, now(UTC)); - final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now()); + final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now(), Collections.emptyList()); assertThat(defendantDetails, iterableWithSize(1)); assertThat(defendantDetails.get(0), is(defendant)); @@ -144,7 +145,7 @@ public void shouldFindDefendantWithNameUpdatedAndUpdatesAcknowledgedBefore() { final UpdatedDefendantDetails defendant = createCaseDetail(personalDetails, "TVL", now(UTC).minusDays(2), null, now(UTC)); - final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now()); + final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now(), Collections.emptyList()); assertThat(defendantDetails, iterableWithSize(1)); assertThat(defendantDetails.get(0), is(defendant)); @@ -156,7 +157,7 @@ public void shouldIgnoreDefendantWithNameUpdateWhenAcknowledged() { createCaseDetail(personalDetails, "TVL", now(UTC), null, now(UTC).minusDays(2)); - final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now()); + final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now(), Collections.emptyList()); assertThat(defendantDetails, iterableWithSize(0)); } @@ -165,7 +166,7 @@ public void shouldIgnoreDefendantWithNameUpdateWhenAcknowledged() { public void shouldIgnoreDefendantWithNoDetailChanges() { createCaseDetail(new PersonalDetails(), "TVL", null, null, null); - final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now()); + final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TVL", now().minusDays(10), now(), Collections.emptyList()); assertThat(defendantDetails, iterableWithSize(0)); } @@ -174,7 +175,7 @@ public void shouldIgnoreDefendantWithNoDetailChanges() { public void shouldIgnoreDefendantForOtherAuthorityGroup() { createCaseDetail(null, "TVL", null, null, null); - final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TFL", now().minusDays(10), now()); + final List defendantDetails = defendantRepository.findUpdatedByCaseProsecutingAuthority("TFL", now().minusDays(10), now(), Collections.emptyList()); assertThat(defendantDetails, iterableWithSize(0)); } @@ -239,7 +240,8 @@ private UpdatedDefendantDetails createCaseDetail( defendant.getCaseDetail().getUrn(), defendant.getCaseDetail().getId(), defendant.getRegion(), - null); + null, + "TVL"); } } diff --git a/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/PendingDatesToAvoidRepositoryTest.java b/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/PendingDatesToAvoidRepositoryTest.java index ea51b4ed28..493a3efab3 100644 --- a/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/PendingDatesToAvoidRepositoryTest.java +++ b/sjp-viewstore/sjp-viewstore-persistence/src/test/java/uk/gov/moj/cpp/sjp/persistence/repository/PendingDatesToAvoidRepositoryTest.java @@ -11,6 +11,7 @@ import java.time.ZonedDateTime; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.UUID; @@ -83,7 +84,7 @@ private void setupAndSaveDatesToAvoidData(DatesToAvoidTestData testData) { @Test public void shouldFindCasesPendingDatesToAvoidForTfl() { // WHEN - List results = pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid("TFL"); + List results = pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid("TFL", Collections.emptyList()); // THEN assertThat(results, hasSize(3)); @@ -92,10 +93,25 @@ public void shouldFindCasesPendingDatesToAvoidForTfl() { assertThat(results.get(2).getCaseId(), equalTo(testData.get(0).getCaseId())); } + @Test + public void shouldFindCasesPendingDatesToAvoidForTflAndTvl() { + // WHEN + List results = pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid("TFL", Arrays.asList("TVL", "XYZ")); + + // THEN + assertThat(results, hasSize(6)); + assertThat(results.get(0).getCaseId(), equalTo(testData.get(11).getCaseId())); + assertThat(results.get(1).getCaseId(), equalTo(testData.get(10).getCaseId())); + assertThat(results.get(2).getCaseId(), equalTo(testData.get(4).getCaseId())); + assertThat(results.get(3).getCaseId(), equalTo(testData.get(5).getCaseId())); + assertThat(results.get(4).getCaseId(), equalTo(testData.get(0).getCaseId())); + assertThat(results.get(5).getCaseId(), equalTo(testData.get(6).getCaseId())); + } + @Test public void shouldFindCasesPendingDatesToAvoidForTvl() { // WHEN - List results = pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid("TVL"); + List results = pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid("TVL", Collections.emptyList()); // THEN assertThat(results, hasSize(3)); @@ -106,12 +122,12 @@ public void shouldFindCasesPendingDatesToAvoidForTvl() { @Test public void shouldRemovePendingDatesToAvoid() { - List results = pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid("TFL"); + List results = pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid("TFL", Collections.emptyList()); assertThat(results, hasSize(3)); pendingDatesToAvoidRepository.removeByCaseId(testData.get(0).getCaseId()); - results = pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid("TFL"); + results = pendingDatesToAvoidRepository.findCasesPendingDatesToAvoid("TFL", Collections.emptyList()); assertThat(results, hasSize(2)); assertThat(results.get(0).getCaseId(), equalTo(testData.get(4).getCaseId())); assertThat(results.get(1).getCaseId(), equalTo(testData.get(5).getCaseId()));