diff --git a/build.gradle b/build.gradle index cf8e7a83075..33539ab08a4 100644 --- a/build.gradle +++ b/build.gradle @@ -597,6 +597,12 @@ def sonarExclusions = [ '**uk/gov/hmcts/reform/prl/mapper/citizen/CitizenPartyDetailsMapper.java', '**uk/gov/hmcts/reform/prl/services/DraftAnOrderService.java', '**uk/gov/hmcts/reform/prl/services/ManageOrderService.java', + '**uk/gov/hmcts/reform/prl/services/localauthority/AbstractSocialWorkerService.java', + '**uk/gov/hmcts/reform/prl/handlers/SocialworkerChangeEventHandler.java', + '**src/main/java/uk/gov/hmcts/reform/prl/clients/ccd/CaseAssignmentService.java', + '**uk/gov/hmcts/reform/prl/controllers/localauthority/SocialWorkerController.java', + '**uk/gov/hmcts/reform/prl/services/localauthority/SocialWorkerAddService.java', + '**uk/gov/hmcts/reform/prl/services/localauthority/SocialWorkerRemoveService.java', '**uk/gov/hmcts/reform/prl/services/ServiceOfApplicationService.java', '**uk/gov/hmcts/reform/prl/controllers/citizen/CaseController.java', '**uk/gov/hmcts/reform/prl/filter/requestbodylogger/*', diff --git a/src/functionalTest/java/uk/gov/hmcts/reform/prl/controllers/ManageOrdersControllerFunctionalTest.java b/src/functionalTest/java/uk/gov/hmcts/reform/prl/controllers/ManageOrdersControllerFunctionalTest.java index 95b41497a28..827d1941cd9 100644 --- a/src/functionalTest/java/uk/gov/hmcts/reform/prl/controllers/ManageOrdersControllerFunctionalTest.java +++ b/src/functionalTest/java/uk/gov/hmcts/reform/prl/controllers/ManageOrdersControllerFunctionalTest.java @@ -515,6 +515,9 @@ public void givenRequestBody_WhenPostRequestTestSendCafcassCymruOrderEmail() thr .body("data.serveOtherPartiesCA", equalTo(null)) .body("data.cafcassCymruServedOptions", equalTo(null)) .body("data.emailInformationCaOnlyC47a", equalTo(null)) + .body("data.localAuthoritySolicitorOrganisationPolicy", equalTo(null)) + .body("data.localAuthority.isLocalAuthorityInvolvedInCase",equalTo("No")) + .body("data.localAuthority.localAuthoritySolicitorOrganisationName", equalTo(null)) .body("data.orderCollection[0].value.serveOrderDetails.cafcassCymruServed", equalTo("Yes")) .body("data.orderCollection[0].value.serveOrderDetails.cafcassCymruEmail", diff --git a/src/functionalTest/resources/requests/cafcass-cymru-send-email-request.json b/src/functionalTest/resources/requests/cafcass-cymru-send-email-request.json index 80ab3f87bc9..d973bd8a2ed 100644 --- a/src/functionalTest/resources/requests/cafcass-cymru-send-email-request.json +++ b/src/functionalTest/resources/requests/cafcass-cymru-send-email-request.json @@ -17,6 +17,18 @@ "performingAction": null, "judgeLaReviewRequired": null, "markedToServeEmailNotification": "No", + "localAuthority": { + "isLocalAuthorityInvolvedInCase": "Yes", + "localAuthoritySolicitorOrganisationName": "Local Authority Private Law AAT Test Organisation" + }, + "localAuthoritySolicitorOrganisationPolicy": { + "Organisation": { + "OrganisationID": "I1SL2TZ", + "OrganisationName": "Local Authority Private Law AAT Test Organisation" + }, + "OrgPolicyReference": null, + "OrgPolicyCaseAssignedRole": "[LASOLICITOR]" + }, "applicants": [ { "id": "97e25c77-f915-4b4e-8436-89a0d1678813", diff --git a/src/main/java/uk/gov/hmcts/reform/prl/constants/ManageDocumentsCategoryConstants.java b/src/main/java/uk/gov/hmcts/reform/prl/constants/ManageDocumentsCategoryConstants.java index 987605e3c6a..2b1d9adb02c 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/constants/ManageDocumentsCategoryConstants.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/constants/ManageDocumentsCategoryConstants.java @@ -47,6 +47,14 @@ public class ManageDocumentsCategoryConstants { public static final String DRUG_AND_ALCOHOL_TEST = "drugAndAlcoholTest(toxicology)"; public static final String POLICE_REPORT = "policeReport"; public static final String SEC37_REPORT = "sec37Report"; + public static final String CHILD_IMPACT_REPORT_1_LA = "childImpactReport1La"; + public static final String CHILD_IMPACT_REPORT_2_LA = "childImpactReport2La"; + public static final String SECTION_7_REPORT_LA = "section7ReportLa"; + public static final String SECTION_7_ADDENDUM_REPORT_LA = "section7AddendumReportLa"; + public static final String LOCAL_AUTHORITY_INVOLVEMENT_LA = "localAuthorityInvolvementLa"; + public static final String SECTION_47_LA = "section47La"; + public static final String CIR_EXTENSION_REQUEST_LA = "cirExtensionRequestLa"; + public static final String CIR_TRANSFER_REQUEST_LA = "cirTransferRequestLa"; public static final String LA_OTHER_DOCS = "localAuthorityOtherDoc"; public static final String ORDERS_SUBMITTED_WITH_APPLICATION = "ordersSubmittedWithApplication"; public static final String APPROVED_ORDERS = "approvedOrders"; diff --git a/src/main/java/uk/gov/hmcts/reform/prl/constants/PrlAppsConstants.java b/src/main/java/uk/gov/hmcts/reform/prl/constants/PrlAppsConstants.java index 8917b0ae63f..5a6641fad47 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/constants/PrlAppsConstants.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/constants/PrlAppsConstants.java @@ -806,6 +806,7 @@ public class PrlAppsConstants { public static final String HMC_STATUS_COMPLETED = "COMPLETED"; public static final String CAFCASS = "Cafcass"; + public static final String LOCAL_AUTHORITY = "LOCAL_AUTHORITY";//TODO review the value later public static final String APPLICANTS = "applicants"; public static final String RESPONDENTS = "respondents"; @@ -1144,6 +1145,9 @@ public class PrlAppsConstants { public static final String IS_INVOKED_FROM_TASK = "isInvokedFromTask"; public static final String ALLOCATED_BARRISTER = "allocatedBarrister"; + public static final String LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY = "localAuthoritySolicitorOrganisationPolicy"; + public static final String LOCAL_AUTHORITY_DATA = "localAuthority"; + public static final String LOCAL_AUTHORITY_SOLICITOR_CASE_ROLE = "[LASOLICITOR]"; public static final String CAFCASS_DATE_TIME = "cafcassDateTime"; public static final String PERMISSION_REQUIRED_DOCUMENT = "uploadOrderDocForPermission"; public static final String MESSAGE_REPLY_DYNAMIC_LIST = "messageReplyDynamicList"; diff --git a/src/main/java/uk/gov/hmcts/reform/prl/controllers/ManageOrdersController.java b/src/main/java/uk/gov/hmcts/reform/prl/controllers/ManageOrdersController.java index 4359c33a50f..841799f792c 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/controllers/ManageOrdersController.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/controllers/ManageOrdersController.java @@ -291,6 +291,9 @@ public AboutToStartOrSubmitCallbackResponse sendEmailNotificationOnClosingOrder( //SNI-4330 fix //update caseSummaryTab with latest state ManageOrderService.cleanUpServeOrderOptions(caseDataUpdated); + + manageOrderService.removeLocalAuthorityFromCase(caseData, caseDataUpdated); + allTabService.submitAllTabsUpdate( startAllTabsUpdateDataContent.authorisation(), String.valueOf(callbackRequest.getCaseDetails().getId()), diff --git a/src/main/java/uk/gov/hmcts/reform/prl/controllers/localauthority/LocalAuthorityController.java b/src/main/java/uk/gov/hmcts/reform/prl/controllers/localauthority/LocalAuthorityController.java new file mode 100644 index 00000000000..33c943a3284 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/prl/controllers/localauthority/LocalAuthorityController.java @@ -0,0 +1,155 @@ +package uk.gov.hmcts.reform.prl.controllers.localauthority; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest; +import uk.gov.hmcts.reform.prl.controllers.AbstractCallbackController; +import uk.gov.hmcts.reform.prl.enums.YesOrNo; +import uk.gov.hmcts.reform.prl.exception.InvalidClientException; +import uk.gov.hmcts.reform.prl.models.caseaccess.OrganisationPolicy; +import uk.gov.hmcts.reform.prl.models.dto.ccd.CaseData; +import uk.gov.hmcts.reform.prl.models.dto.ccd.LocalAuthority; +import uk.gov.hmcts.reform.prl.services.AuthorisationService; +import uk.gov.hmcts.reform.prl.services.EventService; +import uk.gov.hmcts.reform.prl.services.localauthority.RemoveLocalAuthoritySolicitorService; +import uk.gov.hmcts.reform.prl.utils.CaseUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.INVALID_CLIENT; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY_DATA; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY_SOLICITOR_CASE_ROLE; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.SERVICE_AUTHORIZATION_HEADER; + +@Slf4j +@RestController +@SecurityRequirement(name = "Bearer Authentication") +@RequestMapping("/localauthority") +public class LocalAuthorityController extends AbstractCallbackController { + private final AuthorisationService authorisationService; + private final RemoveLocalAuthoritySolicitorService removeLocalAuthoritySolver; + + @Autowired + public LocalAuthorityController(ObjectMapper objectMapper, EventService eventPublisher, + AuthorisationService authorisationService, + RemoveLocalAuthoritySolicitorService removeLocalAuthoritySolver) { + super(objectMapper, eventPublisher); + this.authorisationService = authorisationService; + this.removeLocalAuthoritySolver = removeLocalAuthoritySolver; + } + + @PostMapping(path = "/add/aboutToSubmit", consumes = APPLICATION_JSON, produces = APPLICATION_JSON) + @Operation(description = "Callback to add a Local authority on about to submit") + @SecurityRequirement(name = "Bearer Authentication") + public AboutToStartOrSubmitCallbackResponse handleAddAboutToSubmit( + @RequestHeader(org.springframework.http.HttpHeaders.AUTHORIZATION) @Parameter(hidden = true) String authorisation, + @RequestHeader(SERVICE_AUTHORIZATION_HEADER) String s2sToken, + @RequestBody CallbackRequest callbackRequest) { + + log.info("Inside Local authority/add/submitted for case {}", callbackRequest.getCaseDetails().getId()); + if (authorisationService.isAuthorized(authorisation, s2sToken)) { + Map caseDataUpdated = callbackRequest.getCaseDetails().getData(); + CaseData caseData = objectMapper.convertValue( + callbackRequest.getCaseDetails().getData(), + CaseData.class + ); + + OrganisationPolicy localAuthorityOrganisationPolicy = caseData.getLocalAuthoritySolicitorOrganisationPolicy(); + caseDataUpdated.put( + LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY, + localAuthorityOrganisationPolicy.toBuilder() + .orgPolicyCaseAssignedRole(LOCAL_AUTHORITY_SOLICITOR_CASE_ROLE).build() + ); + + String organisationName = localAuthorityOrganisationPolicy.getOrganisation().getOrganisationName(); + LocalAuthority localAuthority = LocalAuthority.builder().isLocalAuthorityInvolvedInCase(YesOrNo.Yes) + .localAuthoritySolicitorOrganisationName(organisationName) + .build(); + caseDataUpdated.put(LOCAL_AUTHORITY_DATA, localAuthority); + + return AboutToStartOrSubmitCallbackResponse.builder().data(caseDataUpdated).build(); + } else { + throw (new RuntimeException(INVALID_CLIENT)); + } + } + + @PostMapping(path = "/remove/about-to-start", consumes = APPLICATION_JSON, produces = APPLICATION_JSON) + @Operation(description = "Callback to remove a local authority on about-to-start") + @SecurityRequirement(name = "Bearer Authentication") + public AboutToStartOrSubmitCallbackResponse handleRemoveAboutToStart( + @RequestHeader(org.springframework.http.HttpHeaders.AUTHORIZATION) @Parameter(hidden = true) String authorisation, + @RequestHeader(SERVICE_AUTHORIZATION_HEADER) String s2sToken, + @RequestBody CallbackRequest callbackRequest) { + + log.info("Inside localauthority/remove/about-to-start for case {}", callbackRequest.getCaseDetails().getId()); + if (authorisationService.isAuthorized(authorisation, s2sToken)) { + CaseData caseData = CaseUtils.getCaseData(callbackRequest.getCaseDetails(), objectMapper); + List errorList = new ArrayList<>(); + + if (null == caseData.getLocalAuthoritySolicitorOrganisationPolicy() + || null == caseData.getLocalAuthoritySolicitorOrganisationPolicy().getOrganisation()) { + log.info("No Local authority currently assigned to the case."); + errorList.add("No Local authority currently assigned to the case."); + } + + return AboutToStartOrSubmitCallbackResponse.builder() + .data(callbackRequest.getCaseDetails().getData()) + .errors(errorList).build(); + } else { + throw (new InvalidClientException(INVALID_CLIENT)); + } + } + + @PostMapping(path = "/remove/aboutToSubmit", consumes = APPLICATION_JSON, produces = APPLICATION_JSON) + @Operation(description = "Callback to remove a local authority on about to submit") + @SecurityRequirement(name = "Bearer Authentication") + public AboutToStartOrSubmitCallbackResponse handleRemoveAboutToSubmit( + @RequestHeader(org.springframework.http.HttpHeaders.AUTHORIZATION) @Parameter(hidden = true) String authorisation, + @RequestHeader(SERVICE_AUTHORIZATION_HEADER) String s2sToken, + @RequestBody CallbackRequest callbackRequest) { + + log.info("Inside local authority/remove/about to submit for case {}", callbackRequest.getCaseDetails().getId()); + if (authorisationService.isAuthorized(authorisation, s2sToken)) { + + CaseData caseData = objectMapper.convertValue( + callbackRequest.getCaseDetails().getData(), + CaseData.class + ); + List errorList = new ArrayList<>(); + Map caseDataUpdated = callbackRequest.getCaseDetails().getData(); + + if (null != caseData.getLocalAuthoritySolicitorOrganisationPolicy() + && null != caseData.getLocalAuthoritySolicitorOrganisationPolicy().getOrganisation()) { + removeLocalAuthoritySolver.removeLocalAuthoritySolicitor(caseData); + caseDataUpdated.remove(LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY); + + LocalAuthority localAuthority = LocalAuthority.builder().isLocalAuthorityInvolvedInCase(YesOrNo.No) + .localAuthoritySolicitorOrganisationName(null) + .build(); + caseDataUpdated.put(LOCAL_AUTHORITY_DATA, localAuthority); + } else { + errorList.add("No Local authority currently assigned to the case"); + } + + return AboutToStartOrSubmitCallbackResponse.builder().data(caseDataUpdated) + .errors(errorList) + .build(); + } else { + throw (new RuntimeException(INVALID_CLIENT)); + } + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/prl/enums/DocTypeOtherDocumentsEnum.java b/src/main/java/uk/gov/hmcts/reform/prl/enums/DocTypeOtherDocumentsEnum.java index 79ac45ec3f3..f1d4642795e 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/enums/DocTypeOtherDocumentsEnum.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/enums/DocTypeOtherDocumentsEnum.java @@ -86,7 +86,19 @@ public enum DocTypeOtherDocumentsEnum { @JsonProperty("otherDocs") otherDocs("otherDocs", "Cafcass/Cafcass Cymru other documents"), @JsonProperty("sec37Report") - sec37Report("sec37Report","Section 37 report"), + sec37Report("sec37Report","Section 37 (S37) report"), + @JsonProperty("childImpactReport1La") + childImpactReport1La("childImpactReport1La","Child Impact Report 1"), + @JsonProperty("childImpactReport2La") + childImpactReport2La("childImpactReport2La","Child Impact Report 2"), + @JsonProperty("section7ReportLa") + section7ReportLa("section7ReportLa","Section 7 report"), + @JsonProperty("section7AddendumReportLa") + section7AddendumReportLa("section7AddendumReportLa","Section 7 addendum report"), + @JsonProperty("localAuthorityInvolvementLa") + localAuthorityInvolvementLa("localAuthorityInvolvementLa","Local Authority involvement letter"), + @JsonProperty("section47La") + section47La("section47La","Section 47 enquiry"), @JsonProperty("localAuthorityOtherDoc") localAuthorityOtherDoc("localAuthorityOtherDoc","Local Authority other documents"), @JsonProperty("medicalReports") diff --git a/src/main/java/uk/gov/hmcts/reform/prl/enums/Roles.java b/src/main/java/uk/gov/hmcts/reform/prl/enums/Roles.java index 0556d20fe7d..1e24ccc957d 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/enums/Roles.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/enums/Roles.java @@ -10,7 +10,10 @@ public enum Roles { BULK_SCAN("BULK_SCAN","caseworker-privatelaw-bulkscan"), SYSTEM_UPDATE("SYSTEM_UPDATE","caseworker-privatelaw-systemupdate"), COURTNAV("COURTNAV","courtnav"), - ALLOCATED_LEGAL_ADVISER("ALLOCATED_LEGAL_ADVISER","allocated-legal-adviser"); + ALLOCATED_LEGAL_ADVISER("ALLOCATED_LEGAL_ADVISER","allocated-legal-adviser"), + LOCAL_AUTHORITY_STAFF("LASOCIALWORKER", "[LASOCIALWORKER]"), + LOCAL_AUTHORITY_SOLICITOR("LASOLICITOR","[LASOLICITOR]"); + private final String id; private final String value; diff --git a/src/main/java/uk/gov/hmcts/reform/prl/enums/amroles/InternalCaseworkerAmRolesEnum.java b/src/main/java/uk/gov/hmcts/reform/prl/enums/amroles/InternalCaseworkerAmRolesEnum.java index 68df1a8d171..ef29f183471 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/enums/amroles/InternalCaseworkerAmRolesEnum.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/enums/amroles/InternalCaseworkerAmRolesEnum.java @@ -13,7 +13,8 @@ public enum InternalCaseworkerAmRolesEnum { COURT_ADMIN("COURT_ADMIN", List.of("hearing-centre-admin", "ctsc")), COURT_ADMIN_TEAM_LEADER("COURT_ADMIN_TEAM_LEADER", List.of("hearing-centre-admin", "ctsc", "team-leader")), CTSC("CTSC", List.of("ctsc")), - CAFCASS_CYMRU("CAFCASS_CYMRU", List.of("caseworker-privatelaw-externaluser-viewonly")); + CAFCASS_CYMRU("CAFCASS_CYMRU", List.of("caseworker-privatelaw-externaluser-viewonly")), + LOCAL_AUTHORITY("LOCAL_AUTHORITY", List.of("[LASOCIALWORKER]", "[LASOLICITOR]")); private final String user; private final List roles; diff --git a/src/main/java/uk/gov/hmcts/reform/prl/enums/bundle/BundlingDocGroupEnum.java b/src/main/java/uk/gov/hmcts/reform/prl/enums/bundle/BundlingDocGroupEnum.java index 9e73749cab4..b6911a73023 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/enums/bundle/BundlingDocGroupEnum.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/enums/bundle/BundlingDocGroupEnum.java @@ -149,6 +149,30 @@ public enum BundlingDocGroupEnum { @JsonProperty("laSection37Report") laSection37Report("laSection37Report", "laSection37Report"), + @JsonProperty("laSectionChildImpactReport1Report") + laSectionChildImpactReport1Report("laSectionChildImpactReport1Report", "laSectionChildImpactReport1Report"), + + @JsonProperty("laSectionChildImpactReport2Report") + laSectionChildImpactReport2Report("laSectionChildImpactReport2Report", "laSectionChildImpactReport2Report"), + + @JsonProperty("laSectionSection7ReportReport") + laSectionSection7ReportReport("laSectionSection7ReportReport", "laSectionSection7ReportReport"), + + @JsonProperty("laSectionSection7AddendumReportReport") + laSectionSection7AddendumReportReport("laSectionSection7AddendumReportReport", "laSectionSection7AddendumReportReport"), + + @JsonProperty("laSectionLocalAuthorityInvolvementReport") + laSectionLocalAuthorityInvolvementReport("laSectionLocalAuthorityInvolvementReport", "laSectionLocalAuthorityInvolvementReport"), + + @JsonProperty("laSectionSection47EnquiryReport") + laSectionSection47EnquiryReport("laSectionSection47EnquiryReport", "laSectionSection47EnquiryReport"), + + @JsonProperty("laSectionCirExtensionRequestReport") + laSectionCirExtensionRequestReport("laSectionCirExtensionRequestReport", "laSectionCirExtensionRequestReport"), + + @JsonProperty("laSectionCirTransferRequestReport") + laSectionCirTransferRequestReport("laSectionCirTransferRequestReport", "laSectionCirTransferRequestReport"), + @JsonProperty("laOtherDocuments") laOtherDocuments("laOtherDocuments", "laOtherDocuments"), diff --git a/src/main/java/uk/gov/hmcts/reform/prl/mapper/bundle/BundleCreateRequestMapper.java b/src/main/java/uk/gov/hmcts/reform/prl/mapper/bundle/BundleCreateRequestMapper.java index 2460e569c52..f6eea527c5f 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/mapper/bundle/BundleCreateRequestMapper.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/mapper/bundle/BundleCreateRequestMapper.java @@ -47,11 +47,16 @@ import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.CASE_SUMMARY; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.CHILD_IMPACT_REPORT1; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.CHILD_IMPACT_REPORT2; +import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.CHILD_IMPACT_REPORT_1_LA; +import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.CHILD_IMPACT_REPORT_2_LA; +import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.CIR_EXTENSION_REQUEST_LA; +import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.CIR_TRANSFER_REQUEST_LA; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.DNA_REPORTS_EXPERT_REPORT; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.DRUG_AND_ALCOHOL_TEST; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.FM5_STATEMENTS; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.GUARDIAN_REPORT; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.LA_OTHER_DOCS; +import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.LOCAL_AUTHORITY_INVOLVEMENT_LA; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.MAGISTRATES_FACTS_AND_REASONS; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.MEDICAL_REPORTS; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.MIAM_CERTIFICATE; @@ -70,6 +75,9 @@ import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.SEC37_REPORT; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.SECTION7_REPORT; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.SECTION_37_REPORT; +import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.SECTION_47_LA; +import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.SECTION_7_ADDENDUM_REPORT_LA; +import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.SECTION_7_REPORT_LA; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.SIXTEEN_A_RISK_ASSESSMENT; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.SPECIAL_GUARDIANSHIP_REPORT; import static uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants.TRANSCRIPTS_OF_JUDGEMENTS; @@ -413,6 +421,11 @@ private List> mapOtherDocumentsFromCaseData( List> cafcassUploadDocList = caseData.getReviewDocuments().getCafcassUploadDocListDocTab(); allDocuments.addAll(cafcassUploadDocList); } + if (null != caseData.getReviewDocuments().getLocalAuthorityUploadDocListDocTab() + && !caseData.getReviewDocuments().getLocalAuthorityUploadDocListDocTab().isEmpty()) { + List> localAuthorityUploadDocList = caseData.getReviewDocuments().getLocalAuthorityUploadDocListDocTab(); + allDocuments.addAll(localAuthorityUploadDocList); + } if (null != caseData.getReviewDocuments().getLegalProfUploadDocListDocTab() && !caseData.getReviewDocuments().getLegalProfUploadDocListDocTab().isEmpty()) { List> legalProfUploadDocList = caseData.getReviewDocuments().getLegalProfUploadDocListDocTab(); @@ -446,6 +459,7 @@ private BundlingRequestDocument mapBundlingRequestDocumentForOtherDocs(Quarantin mapApplicationsAndOrders(doc, bundleMap); mapWitnessStatements(doc, bundleMap); mapCafcassLaReports(doc, bundleMap); + mapLocalAuthorityDocs(doc, bundleMap); mapOtherDocuments(doc, bundleMap); return bundleMap.get(doc.getCategoryId()); @@ -637,10 +651,50 @@ private static void mapCafcassLaReports(QuarantineLegalDoc doc, HashMap bundleMap) { bundleMap.put(SEC37_REPORT, Objects.nonNull(doc.getSec37ReportDocument()) ? BundlingRequestDocument.builder() .documentLink(doc.getSec37ReportDocument()) .documentFileName(doc.getSec37ReportDocument().getDocumentFileName()) .documentGroup(BundlingDocGroupEnum.laSection37Report).build() : null); + bundleMap.put(CHILD_IMPACT_REPORT_1_LA, Objects.nonNull(doc.getChildImpactReport1LaDocument()) ? BundlingRequestDocument.builder() + .documentLink(doc.getChildImpactReport1LaDocument()) + .documentFileName(doc.getChildImpactReport1LaDocument().getDocumentFileName()) + .documentGroup(BundlingDocGroupEnum.laSectionChildImpactReport1Report).build() : null); + bundleMap.put(CHILD_IMPACT_REPORT_2_LA, Objects.nonNull(doc.getChildImpactReport2LaDocument()) ? BundlingRequestDocument.builder() + .documentLink(doc.getChildImpactReport2LaDocument()) + .documentFileName(doc.getChildImpactReport2LaDocument().getDocumentFileName()) + .documentGroup(BundlingDocGroupEnum.laSectionChildImpactReport2Report).build() : null); + bundleMap.put(SECTION_7_REPORT_LA, Objects.nonNull(doc.getSection7ReportLaDocument()) ? BundlingRequestDocument.builder() + .documentLink(doc.getSection7ReportLaDocument()) + .documentFileName(doc.getSection7ReportLaDocument().getDocumentFileName()) + .documentGroup(BundlingDocGroupEnum.laSectionSection7ReportReport).build() : null); + bundleMap.put(SECTION_7_ADDENDUM_REPORT_LA, Objects.nonNull(doc.getSection7AddendumReportLaDocument()) ? BundlingRequestDocument.builder() + .documentLink(doc.getSection7AddendumReportLaDocument()) + .documentFileName(doc.getSection7AddendumReportLaDocument().getDocumentFileName()) + .documentGroup(BundlingDocGroupEnum.laSectionSection7AddendumReportReport).build() : null); + bundleMap.put(LOCAL_AUTHORITY_INVOLVEMENT_LA, Objects.nonNull(doc.getLocalAuthorityInvolvementLaDocument()) + ? BundlingRequestDocument.builder() + .documentLink(doc.getLocalAuthorityInvolvementLaDocument()) + .documentFileName(doc.getLocalAuthorityInvolvementLaDocument().getDocumentFileName()) + .documentGroup(BundlingDocGroupEnum.laSectionLocalAuthorityInvolvementReport).build() : null); + bundleMap.put(SECTION_47_LA, Objects.nonNull(doc.getSection47LaDocument()) ? BundlingRequestDocument.builder() + .documentLink(doc.getSection47LaDocument()) + .documentFileName(doc.getSection47LaDocument().getDocumentFileName()) + .documentGroup(BundlingDocGroupEnum.laSectionSection47EnquiryReport).build() : null); + bundleMap.put(CIR_EXTENSION_REQUEST_LA, Objects.nonNull(doc.getCirExtensionRequestLaDocument()) ? BundlingRequestDocument.builder() + .documentLink(doc.getCirExtensionRequestLaDocument()) + .documentFileName(doc.getCirExtensionRequestLaDocument().getDocumentFileName()) + .documentGroup(BundlingDocGroupEnum.laSectionCirExtensionRequestReport).build() : null); + + bundleMap.put(CIR_TRANSFER_REQUEST_LA, Objects.nonNull(doc.getCirTransferRequestLaDocument()) ? BundlingRequestDocument.builder() + .documentLink(doc.getCirTransferRequestLaDocument()) + .documentFileName(doc.getCirTransferRequestLaDocument().getDocumentFileName()) + .documentGroup(BundlingDocGroupEnum.laSectionCirTransferRequestReport).build() : null); + + bundleMap.put( LA_OTHER_DOCS, Objects.nonNull(doc.getLocalAuthorityOtherDocDocument()) ? BundlingRequestDocument.builder() diff --git a/src/main/java/uk/gov/hmcts/reform/prl/models/complextypes/QuarantineLegalDoc.java b/src/main/java/uk/gov/hmcts/reform/prl/models/complextypes/QuarantineLegalDoc.java index 5411b1896b0..00bbdee7650 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/models/complextypes/QuarantineLegalDoc.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/models/complextypes/QuarantineLegalDoc.java @@ -68,6 +68,14 @@ public class QuarantineLegalDoc { private final Document drugAndAlcoholTestDocument; // drugAndAlcoholTest(toxicology) private final Document policeReportDocument; private final Document sec37ReportDocument; + private final Document childImpactReport1LaDocument; + private final Document childImpactReport2LaDocument; + private final Document section7ReportLaDocument; + private final Document section7AddendumReportLaDocument; + private final Document localAuthorityInvolvementLaDocument; + private final Document section47LaDocument; + private final Document cirExtensionRequestLaDocument; + private final Document cirTransferRequestLaDocument; private final Document ordersSubmittedWithApplicationDocument; private final Document approvedOrdersDocument; private final Document standardDirectionsOrderDocument; @@ -86,6 +94,7 @@ public class QuarantineLegalDoc { private final Document caseSummaryDocument; private final Document legalProfQuarantineDocument; private final Document cafcassQuarantineDocument; + private final Document localAuthorityQuarantineDocument; private final Document courtStaffQuarantineDocument; private final Document localAuthorityOtherDocDocument; private final Document pathfinderDocument; diff --git a/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/BaseCaseData.java b/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/BaseCaseData.java index 5f1549a4e3e..1e375c75cc3 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/BaseCaseData.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/BaseCaseData.java @@ -16,6 +16,7 @@ import uk.gov.hmcts.reform.prl.enums.YesOrNo; import uk.gov.hmcts.reform.prl.enums.reopenclosedcases.ValidReopenClosedCasesStatusEnum; import uk.gov.hmcts.reform.prl.models.Element; +import uk.gov.hmcts.reform.prl.models.caseaccess.OrganisationPolicy; import uk.gov.hmcts.reform.prl.models.complextypes.RemovableDocument; import uk.gov.hmcts.reform.prl.models.complextypes.refuge.RefugeConfidentialDocuments; import uk.gov.hmcts.reform.prl.models.documents.Document; @@ -164,6 +165,11 @@ public class BaseCaseData { private List> miamDocumentsCopy; + /* Local authority policies */ + @JsonProperty("localAuthoritySolicitorOrganisationPolicy") + private OrganisationPolicy localAuthoritySolicitorOrganisationPolicy; + + private LocalAuthority localAuthority; private YesOrNo orderInPlacePermissionRequired; private String orderDetailsForPermissions; private Document uploadOrderDocForPermission; diff --git a/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/DocumentManagementDetails.java b/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/DocumentManagementDetails.java index e66602d6db1..37f274c50e6 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/DocumentManagementDetails.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/DocumentManagementDetails.java @@ -31,6 +31,8 @@ public class DocumentManagementDetails { private List> courtStaffQuarantineDocsList; @JsonProperty("cafcassQuarantineDocsList") private List> cafcassQuarantineDocsList; + @JsonProperty("localAuthorityQuarantineDocsList") + private List> localAuthorityQuarantineDocsList; @JsonProperty("citizenQuarantineDocsList") private List> citizenQuarantineDocsList; @JsonProperty("tempQuarantineDocumentList") @@ -55,6 +57,7 @@ public List> getRemovableDocuments() { legalProfQuarantineDocsList, courtStaffQuarantineDocsList, cafcassQuarantineDocsList, + localAuthorityQuarantineDocsList, citizenQuarantineDocsList, courtNavQuarantineDocumentList ) diff --git a/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/LocalAuthority.java b/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/LocalAuthority.java new file mode 100644 index 00000000000..be3423987b7 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/LocalAuthority.java @@ -0,0 +1,17 @@ +package uk.gov.hmcts.reform.prl.models.dto.ccd; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Builder; +import lombok.Data; +import uk.gov.hmcts.reform.prl.enums.YesOrNo; + +@Builder +@Data +public class LocalAuthority { + + @JsonProperty("isLocalAuthorityInvolvedInCase") + private YesOrNo isLocalAuthorityInvolvedInCase; + + @JsonProperty("localAuthoritySolicitorOrganisationName") + private String localAuthoritySolicitorOrganisationName; +} diff --git a/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/ReviewDocuments.java b/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/ReviewDocuments.java index fac4e734dad..ce8c569ee54 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/ReviewDocuments.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/models/dto/ccd/ReviewDocuments.java @@ -39,6 +39,7 @@ public class ReviewDocuments { private List> legalProfUploadDocListDocTab; private List> cafcassUploadDocListDocTab; + private List> localAuthorityUploadDocListDocTab; private List> courtStaffUploadDocListDocTab; private List> bulkScannedDocListDocTab; private List> citizenUploadedDocListDocTab; @@ -60,6 +61,7 @@ public List> getRemovableDocuments() { return Stream.of( legalProfUploadDocListDocTab, cafcassUploadDocListDocTab, + localAuthorityUploadDocListDocTab, courtStaffUploadDocListDocTab, bulkScannedDocListDocTab, citizenUploadedDocListDocTab, diff --git a/src/main/java/uk/gov/hmcts/reform/prl/models/dto/citizen/CitizenDocumentsManagement.java b/src/main/java/uk/gov/hmcts/reform/prl/models/dto/citizen/CitizenDocumentsManagement.java index 0f839e27048..05696e345a0 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/models/dto/citizen/CitizenDocumentsManagement.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/models/dto/citizen/CitizenDocumentsManagement.java @@ -45,7 +45,6 @@ public class CitizenDocumentsManagement { Set.of( "section37Report", "16aRiskAssessment", - "sec37Report", "publicFundingCertificates", "noticesOfActingDischarge", "requestForFASFormsToBeChanged", diff --git a/src/main/java/uk/gov/hmcts/reform/prl/models/user/UserRoles.java b/src/main/java/uk/gov/hmcts/reform/prl/models/user/UserRoles.java index 95d7eb354ff..838de5ea175 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/models/user/UserRoles.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/models/user/UserRoles.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.reform.prl.models.user; public enum UserRoles { - SOLICITOR, CASEWORKER, GATEKEEPER, JUDGE, CTSC, COURT_ADMIN, CITIZEN, SYSTEM_UPDATE, LEGAL_ADVISER, BULK_SCAN, CAFCASS, CASEMANAGER; + SOLICITOR, CASEWORKER, GATEKEEPER, JUDGE, CTSC, COURT_ADMIN, CITIZEN, SYSTEM_UPDATE, LEGAL_ADVISER, BULK_SCAN, CAFCASS, + LOCAL_AUTHORITY, CASEMANAGER; } diff --git a/src/main/java/uk/gov/hmcts/reform/prl/services/ManageOrderService.java b/src/main/java/uk/gov/hmcts/reform/prl/services/ManageOrderService.java index c38302c3302..4fc5814f448 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/services/ManageOrderService.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/services/ManageOrderService.java @@ -74,6 +74,7 @@ import uk.gov.hmcts.reform.prl.models.dto.ccd.CaseDetails; import uk.gov.hmcts.reform.prl.models.dto.ccd.HearingData; import uk.gov.hmcts.reform.prl.models.dto.ccd.HearingDataPrePopulatedDynamicLists; +import uk.gov.hmcts.reform.prl.models.dto.ccd.LocalAuthority; import uk.gov.hmcts.reform.prl.models.dto.ccd.ManageOrders; import uk.gov.hmcts.reform.prl.models.dto.ccd.ServeOrderData; import uk.gov.hmcts.reform.prl.models.dto.ccd.StandardDirectionOrder; @@ -89,6 +90,7 @@ import uk.gov.hmcts.reform.prl.models.wa.WaMapper; import uk.gov.hmcts.reform.prl.services.dynamicmultiselectlist.DynamicMultiSelectListService; import uk.gov.hmcts.reform.prl.services.hearings.HearingService; +import uk.gov.hmcts.reform.prl.services.localauthority.RemoveLocalAuthoritySolicitorService; import uk.gov.hmcts.reform.prl.services.time.Time; import uk.gov.hmcts.reform.prl.utils.AutomatedHearingTransactionRequestMapper; import uk.gov.hmcts.reform.prl.utils.CaseUtils; @@ -145,6 +147,8 @@ import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.FL401_CASE_TYPE; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.HEARINGS_TYPE; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.IS_INVOKED_FROM_TASK; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY_DATA; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.NO; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.ORDER_COLLECTION; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.ORDER_HEARING_DETAILS; @@ -200,7 +204,7 @@ @Service @Slf4j @RequiredArgsConstructor(onConstructor = @__(@Autowired)) -@SuppressWarnings({"java:S3776","java:S6204"}) +@SuppressWarnings({"java:S3776", "java:S6204"}) public class ManageOrderService { public static final String IS_THE_ORDER_ABOUT_CHILDREN = "isTheOrderAboutChildren"; @@ -635,6 +639,7 @@ public class ManageOrderService { private final LaunchDarklyClient launchDarklyClient; private final DocumentSealingService documentSealingService; private final FinalisationDetailsService finalisationDetailsService; + private final RemoveLocalAuthoritySolicitorService removeLocalAuthoritySolicitorService; public boolean isSaveAsDraft(CaseData caseData) { return isNotEmpty(caseData.getServeOrderData()) && No.equals( @@ -2108,7 +2113,7 @@ public CaseData populateDirectionOfFactFindingHearingFieldsForDocmosis(CaseData return caseData; } - public CaseData filterEmptyHearingDetails(CaseData caseData) { + public CaseData filterEmptyHearingDetails(CaseData caseData) { List> filteredHearingDataList = caseData.getManageOrders().getOrdersHearingDetails() .stream() .filter(element -> ((element.getValue().getHearingTypes() != null && element.getValue().getHearingTypes().getValue() != null) @@ -3129,7 +3134,7 @@ public String isOrderApproved(CaseData caseData, Map caseDataUpd return isOrderApproved; } - public CaseData updateOrderFieldsForDocmosis(DraftOrder draftOrder,CaseData caseData) { + public CaseData updateOrderFieldsForDocmosis(DraftOrder draftOrder, CaseData caseData) { if (C100_CASE_TYPE.equalsIgnoreCase(CaseUtils.getCaseTypeOfApplication(caseData))) { caseData = caseData.toBuilder() .judgeOrMagistratesLastName(draftOrder.getJudgeOrMagistratesLastName()) @@ -3291,8 +3296,6 @@ public HearingData getHearingData(String authorization, return hearingDataService.generateHearingData(hearingDataPrePopulatedDynamicLists, caseData); } - - private void addC21OrderDetails(CaseData caseData, Map caseDataUpdated) { caseDataUpdated.put("selectedC21Order", (null != caseData.getManageOrders() @@ -3702,4 +3705,31 @@ public boolean isEligibleForAutomatedHearing(List> ordersHe HearingDateConfirmOptionEnum.dateConfirmedByListingTeam.equals(element.getValue().getHearingDateConfirmOptionEnum()) || HearingDateConfirmOptionEnum.dateToBeFixed.equals(element.getValue().getHearingDateConfirmOptionEnum())); } + + public void removeLocalAuthorityFromCase(CaseData caseData, Map caseDataUpdated) { + log.info("inside removeLocalAuthorityFromCase"); + try { + + Optional orderDetails + = caseData.getOrderCollection().stream().map(Element::getValue).findFirst(); + + if (orderDetails.isPresent() && Yes.equals(orderDetails.get().getOrderClosesCase()) + && SelectTypeOfOrderEnum.finl.getDisplayedValue().equals(orderDetails.get().getTypeOfOrder()) + && null != caseData.getLocalAuthoritySolicitorOrganisationPolicy() + && null != caseData.getLocalAuthoritySolicitorOrganisationPolicy().getOrganisation()) { + removeLocalAuthoritySolicitorService.removeLocalAuthoritySolicitor(caseData); + caseDataUpdated.put(LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY, null); + LocalAuthority localAuthority = LocalAuthority.builder().isLocalAuthorityInvolvedInCase(YesOrNo.No) + .localAuthoritySolicitorOrganisationName(null) + .build(); + caseDataUpdated.put(LOCAL_AUTHORITY_DATA, localAuthority); + } + } catch (Exception exp) { + log.info( + "Error occurred while removing LocalAuthority From Case {} exception {}", + caseData.getId(), + exp.getMessage() + ); + } + } } diff --git a/src/main/java/uk/gov/hmcts/reform/prl/services/citizen/CaseService.java b/src/main/java/uk/gov/hmcts/reform/prl/services/citizen/CaseService.java index ec023605f82..d70f4c92cb3 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/services/citizen/CaseService.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/services/citizen/CaseService.java @@ -722,6 +722,8 @@ private List getCitizenDocuments(UserDetails userDetails, citizenDocuments.addAll(addCitizenDocuments(caseData.getReviewDocuments().getLegalProfUploadDocListDocTab())); //add cafacss uploaded docs otherDocuments.addAll(addCitizenDocuments(caseData.getReviewDocuments().getCafcassUploadDocListDocTab())); + //add local authority uploaded docs + otherDocuments.addAll(addCitizenDocuments(caseData.getReviewDocuments().getLocalAuthorityUploadDocListDocTab())); //add court staff uploaded docs citizenDocuments.addAll(addCitizenDocuments(caseData.getReviewDocuments().getCourtStaffUploadDocListDocTab())); //add citizen uploaded docs diff --git a/src/main/java/uk/gov/hmcts/reform/prl/services/closingcase/ClosingCaseService.java b/src/main/java/uk/gov/hmcts/reform/prl/services/closingcase/ClosingCaseService.java index 69b227ffebf..e96d9429810 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/services/closingcase/ClosingCaseService.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/services/closingcase/ClosingCaseService.java @@ -26,6 +26,7 @@ import uk.gov.hmcts.reform.prl.models.complextypes.ChildDetailsRevised; import uk.gov.hmcts.reform.prl.models.complextypes.closingcase.CaseClosingReasonForChildren; import uk.gov.hmcts.reform.prl.models.dto.ccd.CaseData; +import uk.gov.hmcts.reform.prl.models.dto.ccd.LocalAuthority; import uk.gov.hmcts.reform.prl.models.dto.gatekeeping.AllocatedJudge; import uk.gov.hmcts.reform.prl.models.roleassignment.addroleassignment.QueryAttributes; import uk.gov.hmcts.reform.prl.models.roleassignment.addroleassignment.RoleAssignmentQueryRequest; @@ -33,6 +34,7 @@ import uk.gov.hmcts.reform.prl.services.ApplicationsTabService; import uk.gov.hmcts.reform.prl.services.ApplicationsTabServiceHelper; import uk.gov.hmcts.reform.prl.services.SystemUserService; +import uk.gov.hmcts.reform.prl.services.localauthority.RemoveLocalAuthoritySolicitorService; import uk.gov.hmcts.reform.prl.services.tab.summary.CaseSummaryTabService; import uk.gov.hmcts.reform.prl.utils.IncrementalInteger; @@ -56,7 +58,11 @@ import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.EMPTY_STRING; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.FINAL_CASE_CLOSED_DATE; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.FL401_CHILD_DETAILS_TABLE; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY_DATA; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.NEW_CHILDREN; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.TASK_LIST_VERSION_V2; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.TASK_LIST_VERSION_V3; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.YES; import static uk.gov.hmcts.reform.prl.services.reopenclosedcases.ReopenClosedCasesService.REOPEN_STATE_TO; import static uk.gov.hmcts.reform.prl.utils.ElementUtils.element; @@ -82,6 +88,7 @@ public class ClosingCaseService { private final AuthTokenGenerator authTokenGenerator; private final SystemUserService systemUserService; + private final RemoveLocalAuthoritySolicitorService removeLocalAuthoritySolicitorService; public static final String SPECIFIC_ACCESS_GRANT = "SPECIFIC"; @@ -103,8 +110,8 @@ public Map prePopulateChildData(CallbackRequest callbackRequest) private List getChildrenMultiSelectListForFinalDecisions(CaseData caseData) { List listItems = new ArrayList<>(); - if ((PrlAppsConstants.TASK_LIST_VERSION_V2.equals(caseData.getTaskListVersion()) - || PrlAppsConstants.TASK_LIST_VERSION_V3.equals(caseData.getTaskListVersion())) && caseData.getNewChildDetails() != null) { + if ((TASK_LIST_VERSION_V2.equals(caseData.getTaskListVersion()) + || TASK_LIST_VERSION_V3.equals(caseData.getTaskListVersion())) && caseData.getNewChildDetails() != null) { IncrementalInteger i = new IncrementalInteger(1); caseData.getNewChildDetails().forEach(child -> { if (StringUtils.isEmpty(child.getValue().getFinalDecisionResolutionReason())) { @@ -194,6 +201,7 @@ public Map closingCaseForChildren(CallbackRequest callbackReques if (YesOrNo.Yes.equals(caseData.getClosingCaseOptions().getIsTheDecisionAboutAllChildren()) || getChildrenMultiSelectListForFinalDecisions(caseData).isEmpty()) { unAllocateCourtStaffs(caseData, caseDataUpdated); + removeLocalAuthorityFromCase(caseData, caseDataUpdated); markTheCaseAsClosed(caseDataUpdated, finalDecisionResolutionDate, caseData); } updateChildDetailsInTab(caseDataUpdated, caseData); @@ -234,6 +242,7 @@ public void unAllocateCourtStaffs(CaseData caseData, Map caseDat ? caseData.getLegalAdviserList().toBuilder() .value(null) .build() : caseData.getLegalAdviserList()); + } } catch (Exception exp) { log.info( @@ -244,11 +253,34 @@ public void unAllocateCourtStaffs(CaseData caseData, Map caseDat } } + public void removeLocalAuthorityFromCase(CaseData caseData, Map caseDataUpdated) { + log.info("inside removeLocalAuthorityFromCase"); + + try { + if (null != caseData.getLocalAuthoritySolicitorOrganisationPolicy() + && null != caseData.getLocalAuthoritySolicitorOrganisationPolicy().getOrganisation()) { + removeLocalAuthoritySolicitorService.removeLocalAuthoritySolicitor(caseData); + caseDataUpdated.put(LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY, null); + LocalAuthority localAuthority = LocalAuthority.builder().isLocalAuthorityInvolvedInCase(YesOrNo.No) + .localAuthoritySolicitorOrganisationName(null) + .build(); + caseDataUpdated.put(LOCAL_AUTHORITY_DATA, localAuthority); + } + } catch (Exception exp) { + log.info( + "Error occurred while removing LocalAuthority From closed Case {} exception {}", + caseData.getId(), + exp.getMessage() + ); + } + + } + private static void updateChildDetails(Map caseDataUpdated, CaseData caseData, String finalDecisionResolutionDate, Element finalOutcomeForChildrenElement) { if ((PrlAppsConstants.TASK_LIST_VERSION_V2.equals(caseData.getTaskListVersion()) - || PrlAppsConstants.TASK_LIST_VERSION_V3.equals(caseData.getTaskListVersion())) && caseData.getNewChildDetails() != null) { + || TASK_LIST_VERSION_V3.equals(caseData.getTaskListVersion())) && caseData.getNewChildDetails() != null) { List> children = caseData.getNewChildDetails(); caseData.getNewChildDetails().forEach(child -> { if (finalOutcomeForChildrenElement.getId().equals(child.getId())) { @@ -307,7 +339,7 @@ public static void cleanUpClosingCaseChildOptions(Map caseDataUp public void updateChildDetailsInTab(Map caseDataUpdated, CaseData caseData) { if (PrlAppsConstants.C100_CASE_TYPE.equalsIgnoreCase(caseData.getCaseTypeOfApplication())) { if (PrlAppsConstants.TASK_LIST_VERSION_V2.equals(caseData.getTaskListVersion()) - || PrlAppsConstants.TASK_LIST_VERSION_V3.equals(caseData.getTaskListVersion())) { + || TASK_LIST_VERSION_V3.equals(caseData.getTaskListVersion())) { caseDataUpdated.put( CHILD_DETAILS_REVISED_TABLE, applicationsTabServiceHelper.getChildRevisedDetails(caseData) @@ -328,7 +360,7 @@ private void populateFinalOutcomeForChildren(CaseData caseData, List> finalOutcomeForChildren, DynamicMultiselectListElement dynamicMultiselectListElement) { if ((PrlAppsConstants.TASK_LIST_VERSION_V2.equals(caseData.getTaskListVersion()) - || PrlAppsConstants.TASK_LIST_VERSION_V3.equals(caseData.getTaskListVersion())) && caseData.getNewChildDetails() != null) { + || TASK_LIST_VERSION_V3.equals(caseData.getTaskListVersion())) && caseData.getNewChildDetails() != null) { caseData.getNewChildDetails().forEach(child -> getChildList( finalOutcomeForChildren, dynamicMultiselectListElement, diff --git a/src/main/java/uk/gov/hmcts/reform/prl/services/localauthority/RemoveLocalAuthoritySolicitorService.java b/src/main/java/uk/gov/hmcts/reform/prl/services/localauthority/RemoveLocalAuthoritySolicitorService.java new file mode 100644 index 00000000000..5574c8b2b29 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/prl/services/localauthority/RemoveLocalAuthoritySolicitorService.java @@ -0,0 +1,103 @@ +package uk.gov.hmcts.reform.prl.services.localauthority; + +import feign.FeignException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.authorisation.generators.AuthTokenGenerator; +import uk.gov.hmcts.reform.ccd.client.CaseAssignmentApi; +import uk.gov.hmcts.reform.ccd.client.model.CaseAssignmentUserRoleWithOrganisation; +import uk.gov.hmcts.reform.ccd.client.model.CaseAssignmentUserRolesRequest; +import uk.gov.hmcts.reform.prl.exception.GrantCaseAccessException; +import uk.gov.hmcts.reform.prl.models.dto.ccd.CaseData; +import uk.gov.hmcts.reform.prl.models.roleassignment.getroleassignment.RoleAssignmentResponse; +import uk.gov.hmcts.reform.prl.models.roleassignment.getroleassignment.RoleAssignmentServiceResponse; +import uk.gov.hmcts.reform.prl.services.RoleAssignmentService; +import uk.gov.hmcts.reform.prl.services.SystemUserService; + +import java.util.Set; +import java.util.stream.Collectors; + +import static java.util.stream.Collectors.collectingAndThen; +import static java.util.stream.Collectors.toList; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY_SOLICITOR_CASE_ROLE; + +@Slf4j +@Service +@RequiredArgsConstructor +public class RemoveLocalAuthoritySolicitorService { + + private final CaseAssignmentApi caseAssignmentApi; + private final SystemUserService systemUserService; + private final AuthTokenGenerator tokenGenerator; + private final RoleAssignmentService roleAssignmentService; + + public void removeLocalAuthoritySolicitor(CaseData caseData) { + RoleAssignmentServiceResponse roleAssignmentServiceResponse = roleAssignmentService + .getRoleAssignmentForCase(String.valueOf(caseData.getId())); + + Set solicitors = roleAssignmentServiceResponse.getRoleAssignmentResponse().stream() + .filter(roleAssignment -> roleAssignment.getRoleName().equals(LOCAL_AUTHORITY_SOLICITOR_CASE_ROLE)) + .map(RoleAssignmentResponse::getActorId) + .collect(Collectors.toSet()); + + if (!solicitors.isEmpty()) { + log.info("Removing local authority solicitors {} for case id {}", solicitors, caseData.getId()); + removeAmSolicitorCaseRole(caseData, solicitors); + } else { + log.info("No roles to remove for local authority solicitors for case id {}", caseData.getId()); + } + } + + private void removeAmSolicitorCaseRole(CaseData caseData, Set userIds) { + try { + log.info( + "On case id {}, about to start remove case access {} for users {}", + caseData.getId(), + LOCAL_AUTHORITY_SOLICITOR_CASE_ROLE, + userIds + ); + CaseAssignmentUserRolesRequest removeCaseAssignedUserRolesRequest = buildCaseAssignedUserRequest( + caseData.getId(), + caseData.getLocalAuthoritySolicitorOrganisationPolicy().getOrganisation().getOrganisationID(), + userIds + ); + + caseAssignmentApi.removeCaseUserRoles( + systemUserService.getSysUserToken(), + tokenGenerator.generate(), + removeCaseAssignedUserRolesRequest + ); + } catch (FeignException ex) { + String message = String.format( + "Could not remove the user(s) %s role %s from the case %s", + userIds, + LOCAL_AUTHORITY_SOLICITOR_CASE_ROLE, + caseData.getId() + ); + log.error(message, ex); + throw new GrantCaseAccessException(message); + } + } + + + private CaseAssignmentUserRolesRequest buildCaseAssignedUserRequest(Long caseId, + String orgId, + Set users) { + return users.stream() + .map(user -> CaseAssignmentUserRoleWithOrganisation.builder() + .caseDataId(caseId.toString()) + .organisationId(orgId) + .userId(user) + .caseRole(LOCAL_AUTHORITY_SOLICITOR_CASE_ROLE) + .build()) + .collect(collectingAndThen( + toList(), + list -> + CaseAssignmentUserRolesRequest.builder() + .caseAssignmentUserRolesWithOrganisation(list) + .build() + )); + + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/prl/services/managedocuments/ManageDocumentsService.java b/src/main/java/uk/gov/hmcts/reform/prl/services/managedocuments/ManageDocumentsService.java index 308cea1b304..37593458df5 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/services/managedocuments/ManageDocumentsService.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/services/managedocuments/ManageDocumentsService.java @@ -25,6 +25,7 @@ import uk.gov.hmcts.reform.prl.clients.RoleAssignmentApi; import uk.gov.hmcts.reform.prl.clients.ccd.records.StartAllTabsUpdateDataContent; import uk.gov.hmcts.reform.prl.config.launchdarkly.LaunchDarklyClient; +import uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants; import uk.gov.hmcts.reform.prl.constants.PrlAppsConstants; import uk.gov.hmcts.reform.prl.enums.Roles; import uk.gov.hmcts.reform.prl.enums.YesOrNo; @@ -38,8 +39,10 @@ import uk.gov.hmcts.reform.prl.models.documents.Document; import uk.gov.hmcts.reform.prl.models.dto.ccd.CaseData; import uk.gov.hmcts.reform.prl.models.dto.ccd.DocumentManagementDetails; +import uk.gov.hmcts.reform.prl.models.roleassignment.getroleassignment.RoleAssignmentResponse; import uk.gov.hmcts.reform.prl.models.roleassignment.getroleassignment.RoleAssignmentServiceResponse; import uk.gov.hmcts.reform.prl.models.user.UserRoles; +import uk.gov.hmcts.reform.prl.services.RoleAssignmentService; import uk.gov.hmcts.reform.prl.services.SystemUserService; import uk.gov.hmcts.reform.prl.services.UserService; import uk.gov.hmcts.reform.prl.services.notifications.NotificationService; @@ -59,6 +62,7 @@ import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.function.Predicate; import static org.springframework.http.MediaType.APPLICATION_PDF_VALUE; import static org.springframework.util.CollectionUtils.isEmpty; @@ -78,6 +82,7 @@ import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.JURISDICTION; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LEGAL_ADVISER_ROLE; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LEGAL_PROFESSIONAL; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LONDON_TIME_ZONE; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.RESTRICTED_DOCUMENTS; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.SOA_MULTIPART_FILE; @@ -110,18 +115,28 @@ public class ManageDocumentsService { private final LaunchDarklyClient launchDarklyClient; private final RoleAssignmentApi roleAssignmentApi; private final NotificationService notificationService; + private final RoleAssignmentService roleAssignmentService; public static final String CONFIDENTIAL = "Confidential_"; public static final String MANAGE_DOCUMENTS_TRIGGERED_BY = "manageDocumentsTriggeredBy"; + public static final String MANAGE_DOCUMENTS_UPLOADED_CATEGORY = "manageDocUploadedCategory"; public static final String DETAILS_ERROR_MESSAGE = "You must give a reason why the document should be restricted"; public static final String DETAILS_ERROR_MESSAGE_WELSH = "Mae’n rhaid i chi roi rheswm pam na ddylai rhai pobl weld y ddogfen"; public CaseData populateDocumentCategories(String authorization, CaseData caseData) { + UserDetails userDetails = userService.getUserDetails(authorization); + boolean isUserRoleLA = isUserAllocatedRoleForCaseLA(String.valueOf(caseData.getId()), userDetails.getId()); + ManageDocuments manageDocuments = ManageDocuments.builder() - .documentCategories(getCategoriesSubcategories(authorization, String.valueOf(caseData.getId()))) + .documentCategories(getCategoriesSubcategories( + authorization, + String.valueOf(caseData.getId()), + isUserRoleLA + )) + .documentParty(setDefaultDocumentParty(isUserRoleLA)) .build(); return caseData.toBuilder() @@ -132,7 +147,7 @@ public CaseData populateDocumentCategories(String authorization, CaseData caseDa .build(); } - private DynamicList getCategoriesSubcategories(String authorisation, String caseReference) { + private DynamicList getCategoriesSubcategories(String authorisation, String caseReference, boolean isUserRoleLA) { try { CategoriesAndDocuments categoriesAndDocuments = coreCaseDataApi.getCategoriesAndDocuments( authorisation, @@ -142,6 +157,7 @@ private DynamicList getCategoriesSubcategories(String authorisation, String case if (null != categoriesAndDocuments) { List parentCategories = nullSafeCollection(categoriesAndDocuments.getCategories()) .stream() + .filter(category -> isUserRoleLA == category.getCategoryId().equals("localAuthorityDocuments")) .sorted(Comparator.comparing(Category::getCategoryName)) .toList(); @@ -223,7 +239,6 @@ private void transformAndMoveDocument(CaseData caseData, Map cas UserDetails userDetails) { String userRole = CaseUtils.getUserRole(userDetails); - List> manageDocuments = Optional.ofNullable(caseData.getDocumentManagementDetails().getManageDocuments()) .orElse(Collections.emptyList()); @@ -232,14 +247,19 @@ private void transformAndMoveDocument(CaseData caseData, Map cas CaseData updatedCaseData = objectMapper.convertValue(caseDataUpdated, CaseData.class); ManageDocuments manageDocument = element.getValue(); QuarantineLegalDoc quarantineLegalDoc = covertManageDocToQuarantineDoc(manageDocument, userDetails); - - if (!userRole.equals(COURT_ADMIN) - && (DocumentPartyEnum.CAFCASS.equals(manageDocument.getDocumentParty()) - || DocumentPartyEnum.CAFCASS_CYMRU.equals( - manageDocument.getDocumentParty())) && null != quarantineLegalDoc) { - quarantineLegalDoc = updateQuarantineLegalDocForCafcass( - quarantineLegalDoc - ); + if (!userRole.equals(COURT_ADMIN)) { + if ((DocumentPartyEnum.CAFCASS.equals(manageDocument.getDocumentParty()) + || DocumentPartyEnum.CAFCASS_CYMRU.equals( + manageDocument.getDocumentParty())) && null != quarantineLegalDoc) { + quarantineLegalDoc = updateQuarantineLegalDocForCafcass( + quarantineLegalDoc + ); + } else if (isUserAllocatedRoleForCaseLA(String.valueOf(caseData.getId()), userDetails.getId()) + && null != quarantineLegalDoc) { + quarantineLegalDoc = updateQuarantineLegalDocForLocalAuthority( + quarantineLegalDoc + ); + } } if (userRole.equals(COURT_ADMIN) || DocumentPartyEnum.COURT.equals(manageDocument.getDocumentParty()) @@ -270,6 +290,18 @@ private QuarantineLegalDoc updateQuarantineLegalDocForCafcass(QuarantineLegalDoc .build(); } + private QuarantineLegalDoc updateQuarantineLegalDocForLocalAuthority(QuarantineLegalDoc quarantineLegalDoc) { + if (ManageDocumentsCategoryConstants.CIR_EXTENSION_REQUEST_LA.equals(quarantineLegalDoc.getCategoryId()) + || ManageDocumentsCategoryConstants.CIR_TRANSFER_REQUEST_LA.equals(quarantineLegalDoc.getCategoryId())) { + return quarantineLegalDoc.toBuilder() + .isConfidential(YesOrNo.Yes) + .categoryName(quarantineLegalDoc.getCategoryName()) + .categoryId(quarantineLegalDoc.getCategoryId()) + .build(); + } + return quarantineLegalDoc; + } + public void moveDocumentsToRespectiveCategoriesNew(QuarantineLegalDoc quarantineLegalDoc, UserDetails userDetails, CaseData caseData, Map caseDataUpdated, String userRole) { String restrictedKey = getRestrictedOrConfidentialKey(quarantineLegalDoc); @@ -406,19 +438,68 @@ public void setFlagsForWaTask(CaseData caseData, Map caseDataUpd } else { caseDataUpdated.remove(MANAGE_DOCUMENTS_RESTRICTED_FLAG); } + + if (userRole.equals(LOCAL_AUTHORITY)) { + caseDataUpdated.put(MANAGE_DOCUMENTS_UPLOADED_CATEGORY, quarantineLegalDoc.getCategoryId()); + } + if (CollectionUtils.isNotEmpty(caseData.getDocumentManagementDetails().getCourtStaffQuarantineDocsList()) || CollectionUtils.isNotEmpty(caseData.getDocumentManagementDetails().getCafcassQuarantineDocsList()) + || CollectionUtils.isNotEmpty(caseData.getDocumentManagementDetails().getLocalAuthorityQuarantineDocsList()) || CollectionUtils.isNotEmpty(caseData.getDocumentManagementDetails().getLegalProfQuarantineDocsList()) || CollectionUtils.isNotEmpty(caseData.getDocumentManagementDetails().getCitizenQuarantineDocsList()) || CollectionUtils.isNotEmpty(caseData.getDocumentManagementDetails().getCourtNavQuarantineDocumentList()) || (CollectionUtils.isNotEmpty(caseData.getScannedDocuments()) && caseData.getScannedDocuments().size() > 1)) { - caseDataUpdated.remove(MANAGE_DOCUMENTS_TRIGGERED_BY); + if (!userRole.equals(LOCAL_AUTHORITY)) { + caseDataUpdated.remove(MANAGE_DOCUMENTS_TRIGGERED_BY); + } else { + updateTriggeredByForLocalAuthority(caseData, caseDataUpdated, quarantineLegalDoc); + } } else { updateCaseDataUpdatedByRole(caseDataUpdated, userRole); } } + private void updateTriggeredByForLocalAuthority(CaseData caseData, Map caseDataUpdated, QuarantineLegalDoc quarantineLegalDoc) { + boolean newTaskRequired = false; + if (ManageDocumentsCategoryConstants.CIR_EXTENSION_REQUEST_LA.equals(quarantineLegalDoc.getCategoryId())) { + if (isGivenDocumentExists(caseData, getCirExtensionRequestPredicate()).isEmpty()) { + newTaskRequired = true; + } + } else if (ManageDocumentsCategoryConstants.CIR_TRANSFER_REQUEST_LA.equals(quarantineLegalDoc.getCategoryId())) { + if (isGivenDocumentExists(caseData, getCirTransferRequestPredicate()).isEmpty()) { + newTaskRequired = true; + } + } else { + if (isGivenDocumentExists(caseData, getOtherDocumentsPredicate()).isEmpty()) { + newTaskRequired = true; + } + } + if (newTaskRequired) { + caseDataUpdated.put(MANAGE_DOCUMENTS_TRIGGERED_BY, LOCAL_AUTHORITY); + } else { + caseDataUpdated.remove(MANAGE_DOCUMENTS_TRIGGERED_BY); + } + } + + private Optional> isGivenDocumentExists(CaseData caseData, Predicate> predicate) { + return caseData.getDocumentManagementDetails().getLocalAuthorityQuarantineDocsList().stream().filter(predicate).findAny(); + } + + private Predicate> getCirExtensionRequestPredicate() { + return a -> a.getValue().getCategoryId().equals(ManageDocumentsCategoryConstants.CIR_EXTENSION_REQUEST_LA); + } + + private Predicate> getCirTransferRequestPredicate() { + return a -> a.getValue().getCategoryId().equals(ManageDocumentsCategoryConstants.CIR_TRANSFER_REQUEST_LA); + } + + private Predicate> getOtherDocumentsPredicate() { + return a -> !a.getValue().getCategoryId().equals(ManageDocumentsCategoryConstants.CIR_EXTENSION_REQUEST_LA) + && !a.getValue().getCategoryId().equals(ManageDocumentsCategoryConstants.CIR_TRANSFER_REQUEST_LA); + } + public void moveDocumentsToQuarantineTab(QuarantineLegalDoc quarantineLegalDoc, CaseData caseData, Map caseDataUpdated, @@ -570,6 +651,7 @@ public Document getQuarantineDocumentForUploader(String uploadedBy, case CAFCASS -> quarantineLegalDoc.getCafcassQuarantineDocument(); case COURT_STAFF -> quarantineLegalDoc.getCourtStaffQuarantineDocument(); case BULK_SCAN -> quarantineLegalDoc.getUrl(); + case LOCAL_AUTHORITY -> quarantineLegalDoc.getLocalAuthorityQuarantineDocument(); case CITIZEN -> quarantineLegalDoc.getCitizenQuarantineDocument(); case COURTNAV -> quarantineLegalDoc.getCourtNavQuarantineDocument(); default -> null; @@ -584,6 +666,8 @@ private QuarantineLegalDoc setQuarantineDocumentForUploader(ManageDocuments mana quarantineLegalDoc.toBuilder().cafcassQuarantineDocument(manageDocument.getDocument()).build(); case COURT_STAFF -> quarantineLegalDoc.toBuilder().courtStaffQuarantineDocument(manageDocument.getDocument()).build(); + case LOCAL_AUTHORITY -> + quarantineLegalDoc.toBuilder().localAuthorityQuarantineDocument(manageDocument.getDocument()).build(); case BULK_SCAN -> quarantineLegalDoc.toBuilder().url(manageDocument.getDocument()).build(); case CITIZEN -> quarantineLegalDoc.toBuilder().citizenQuarantineDocument(manageDocument.getDocument()).build(); case COURTNAV -> quarantineLegalDoc.toBuilder().courtNavQuarantineDocument(manageDocument.getDocument()).build(); @@ -627,6 +711,8 @@ private void updateCaseDataUpdatedByRole(Map caseDataUpdated, caseDataUpdated.put(MANAGE_DOCUMENTS_TRIGGERED_BY, "CITIZEN"); } else if (COURTNAV.equals(userRole)) { caseDataUpdated.put(MANAGE_DOCUMENTS_TRIGGERED_BY, "COURTNAV"); + } else if (LOCAL_AUTHORITY.equals(userRole)) { + caseDataUpdated.put(MANAGE_DOCUMENTS_TRIGGERED_BY, "LOCAL_AUTHORITY"); } } @@ -660,6 +746,11 @@ private static void updateQuarantineDocsBasedOnRole(Map caseData isDocumentTab ? "courtStaffUploadDocListDocTab" : "courtStaffQuarantineDocsList", quarantineDocs ); + case LOCAL_AUTHORITY -> + caseDataUpdated.put( + isDocumentTab ? "localAuthorityUploadDocListDocTab" : "localAuthorityQuarantineDocsList", + quarantineDocs + ); case COURT_ADMIN -> { if (isDocumentTab) { caseDataUpdated.put("courtStaffUploadDocListDocTab", quarantineDocs); @@ -712,6 +803,11 @@ private List> getQuarantineDocs(CaseData caseData, caseData.getReviewDocuments().getCourtStaffUploadDocListDocTab(), caseData.getReviewDocuments().getCourtStaffUploadDocListConfTab()//not in use ); + case LOCAL_AUTHORITY -> getQuarantineOrUploadDocsBasedOnDocumentTab( + isDocumentTab, + caseData.getReviewDocuments().getLocalAuthorityUploadDocListDocTab(), + caseData.getDocumentManagementDetails().getLocalAuthorityQuarantineDocsList() + ); case BULK_SCAN -> getQuarantineOrUploadDocsBasedOnDocumentTab( isDocumentTab, caseData.getReviewDocuments().getBulkScannedDocListDocTab(), @@ -883,15 +979,22 @@ public List getLoggedInUserType(String authorisation) { null, userDetails.getId() ); - if (roles.contains(Roles.SOLICITOR.getValue())) { + + List amRoles = Optional.ofNullable(roleAssignmentServiceResponse).isPresent() + ? roleAssignmentServiceResponse.getRoleAssignmentResponse() + .stream() + .map(RoleAssignmentResponse::getRoleName).toList() + : List.of(); + + if (roles.contains(Roles.SOLICITOR.getValue()) && !amRoles.isEmpty() + && amRoles.stream().anyMatch(InternalCaseworkerAmRolesEnum.LOCAL_AUTHORITY.getRoles()::contains)) { + loggedInUserType.add(LOCAL_AUTHORITY); + } else if (roles.contains(Roles.SOLICITOR.getValue())) { loggedInUserType.add(LEGAL_PROFESSIONAL); loggedInUserType.add(SOLICITOR_ROLE); } else if (roles.contains(Roles.CITIZEN.getValue())) { loggedInUserType.add(CITIZEN_ROLE); - } else if (roleAssignmentServiceResponse != null) { - List amRoles = roleAssignmentServiceResponse.getRoleAssignmentResponse() - .stream() - .map(role -> role.getRoleName()).toList(); + } else if (!amRoles.isEmpty()) { if (amRoles.stream().anyMatch(InternalCaseworkerAmRolesEnum.JUDGE.getRoles()::contains)) { loggedInUserType.add(COURT_STAFF); loggedInUserType.add(JUDGE_ROLE); @@ -934,4 +1037,13 @@ private static void checkExistingIdamRoleConfig(List roles, List loggedInUserType.add(UserRoles.CAFCASS.name()); } } + + private DocumentPartyEnum setDefaultDocumentParty(boolean isUserRoleLA) { + return isUserRoleLA ? DocumentPartyEnum.LOCAL_AUTHORITY : null; + } + + private boolean isUserAllocatedRoleForCaseLA(String caseId, String idamId) { + return roleAssignmentService.isUserAllocatedRoleForCase(caseId, idamId, Roles.LOCAL_AUTHORITY_STAFF.getValue()) + || roleAssignmentService.isUserAllocatedRoleForCase(caseId, idamId, Roles.LOCAL_AUTHORITY_SOLICITOR.getValue()); + } } diff --git a/src/main/java/uk/gov/hmcts/reform/prl/services/managedocuments/RemoveDocumentsService.java b/src/main/java/uk/gov/hmcts/reform/prl/services/managedocuments/RemoveDocumentsService.java index daffb2a609d..c9a4f3ba6ce 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/services/managedocuments/RemoveDocumentsService.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/services/managedocuments/RemoveDocumentsService.java @@ -127,6 +127,10 @@ public Map removeDocuments(CaseData caseData, List fetchDocumentDynamicListElements(CaseData caseDa .build()) .toList()); } + //Local Authority + if (isNotEmpty(caseData.getDocumentManagementDetails().getLocalAuthorityQuarantineDocsList())) { + dynamicListElements.addAll(caseData.getDocumentManagementDetails().getLocalAuthorityQuarantineDocsList().stream() + .map(element -> DynamicListElement.builder().code(element.getId().toString()) + .label(manageDocumentsService.getQuarantineDocumentForUploader( + element.getValue().getUploaderRole(), + element.getValue() + ).getDocumentFileName() + + HYPHEN_SEPARATOR + formatDateTime( + DATE_TIME_PATTERN, + element.getValue().getDocumentUploadedDate() + )) + .build()) + .toList()); + } //court staff if (isNotEmpty(caseData.getDocumentManagementDetails().getCourtStaffQuarantineDocsList())) { dynamicListElements.addAll(caseData.getDocumentManagementDetails().getCourtStaffQuarantineDocsList().stream() @@ -253,6 +270,9 @@ private List> getTempQuarantineDocumentList(CaseData if (isNotEmpty(caseData.getDocumentManagementDetails().getCafcassQuarantineDocsList())) { tempQuarantineDocumentList.addAll(caseData.getDocumentManagementDetails().getCafcassQuarantineDocsList()); } + if (isNotEmpty(caseData.getDocumentManagementDetails().getLocalAuthorityQuarantineDocsList())) { + tempQuarantineDocumentList.addAll(caseData.getDocumentManagementDetails().getLocalAuthorityQuarantineDocsList()); + } if (isNotEmpty(caseData.getDocumentManagementDetails().getCourtStaffQuarantineDocsList())) { tempQuarantineDocumentList.addAll(caseData.getDocumentManagementDetails().getCourtStaffQuarantineDocsList()); } @@ -334,6 +354,15 @@ public void processReviewDocument(Map caseDataUpdated, CaseData CAFCASS, CAFCASS_QUARANTINE_DOCS_LIST ); + } + //LA uploaded docs + if (!isDocumentFound && null != caseData.getDocumentManagementDetails().getLocalAuthorityQuarantineDocsList()) { + isDocumentFound = processReviewDocument(caseData, caseDataUpdated, + caseData.getDocumentManagementDetails().getLocalAuthorityQuarantineDocsList(), + uuid, UserDetails.builder().roles(List.of(LOCAL_AUTHORITY)).build(), + LOCAL_AUTHORITY, LOCAL_AUTHORITY_QUARANTINE_DOCS_LIST + ); + } //court staff uploaded docs if (!isDocumentFound && null != caseData.getDocumentManagementDetails().getCourtStaffQuarantineDocsList()) { @@ -506,6 +535,7 @@ public ResponseEntity getReviewResult(CaseData caseDa if (CollectionUtils.isEmpty(caseData.getDocumentManagementDetails().getLegalProfQuarantineDocsList()) && (CollectionUtils.isEmpty(caseData.getDocumentManagementDetails().getCourtStaffQuarantineDocsList())) && CollectionUtils.isEmpty(caseData.getDocumentManagementDetails().getCitizenQuarantineDocsList()) + && (CollectionUtils.isEmpty(caseData.getDocumentManagementDetails().getLocalAuthorityQuarantineDocsList())) && CollectionUtils.isEmpty(caseData.getDocumentManagementDetails().getCafcassQuarantineDocsList()) && CollectionUtils.isEmpty(caseData.getDocumentManagementDetails().getCourtNavQuarantineDocumentList()) && CollectionUtils.isEmpty(caseData.getScannedDocuments())) { diff --git a/src/main/java/uk/gov/hmcts/reform/prl/utils/CaseUtils.java b/src/main/java/uk/gov/hmcts/reform/prl/utils/CaseUtils.java index a9662d025da..8a9acc8b339 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/utils/CaseUtils.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/utils/CaseUtils.java @@ -91,6 +91,7 @@ import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.IS_INVOKED_FROM_TASK; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.JUDGE_ROLE; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LEGAL_ADVISER_ROLE; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.SOA_BY_EMAIL; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.SOA_BY_EMAIL_AND_POST; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.SOA_BY_POST; @@ -415,6 +416,8 @@ public static String getUserRole(UserDetails userDetails) { return BULK_SCAN; } else if (roles.contains(CITIZEN_ROLE)) { return CITIZEN; + } else if (roles.contains(LOCAL_AUTHORITY)) { + return LOCAL_AUTHORITY; } return CAFCASS; diff --git a/src/main/java/uk/gov/hmcts/reform/prl/utils/DocumentUtils.java b/src/main/java/uk/gov/hmcts/reform/prl/utils/DocumentUtils.java index 6871826a4e9..bffa04784ec 100644 --- a/src/main/java/uk/gov/hmcts/reform/prl/utils/DocumentUtils.java +++ b/src/main/java/uk/gov/hmcts/reform/prl/utils/DocumentUtils.java @@ -24,6 +24,7 @@ import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.COURTNAV; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.COURT_STAFF; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LEGAL_PROFESSIONAL; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY; @Data @AllArgsConstructor @@ -131,6 +132,8 @@ public static String getLoggedInUserType(UserDetails userDetails) { loggedInUserType = BULK_SCAN; } else if (roles.contains(Roles.COURTNAV.getValue())) { loggedInUserType = COURTNAV; + } else if (roles.contains("LOCAL_AUTHORITY")) { + loggedInUserType = LOCAL_AUTHORITY; } else { loggedInUserType = CAFCASS; } diff --git a/src/test/java/uk/gov/hmcts/reform/prl/controllers/ManageOrdersControllerTest.java b/src/test/java/uk/gov/hmcts/reform/prl/controllers/ManageOrdersControllerTest.java index 28c569aaa2c..87f5f603743 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/controllers/ManageOrdersControllerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/controllers/ManageOrdersControllerTest.java @@ -1093,6 +1093,8 @@ public void testSubmitAmanageorderEmailValidation() throws Exception { ); verify(manageOrderEmailService, times(1)) .sendEmailWhenOrderIsServed(anyString(), any(CaseData.class), anyMap()); + verify(manageOrderService, times(1)) + .removeLocalAuthorityFromCase(any(CaseData.class), anyMap()); } @Test @@ -1649,6 +1651,8 @@ public void testSubmitManageOrderCafacassEmailNotification() throws Exception { ); verify(manageOrderEmailService, times(1)) .sendEmailWhenOrderIsServed("Bearer TestAuthToken", caseData, stringObjectMap); + verify(manageOrderService, times(1)) + .removeLocalAuthorityFromCase(caseData, stringObjectMap); } @Test diff --git a/src/test/java/uk/gov/hmcts/reform/prl/controllers/localauthority/LocalAuthorityControllerTest.java b/src/test/java/uk/gov/hmcts/reform/prl/controllers/localauthority/LocalAuthorityControllerTest.java new file mode 100644 index 00000000000..8a6b5534609 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/prl/controllers/localauthority/LocalAuthorityControllerTest.java @@ -0,0 +1,316 @@ +package uk.gov.hmcts.reform.prl.controllers.localauthority; + +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest; +import uk.gov.hmcts.reform.ccd.client.model.CaseDetails; +import uk.gov.hmcts.reform.prl.enums.YesOrNo; +import uk.gov.hmcts.reform.prl.models.Organisation; +import uk.gov.hmcts.reform.prl.models.caseaccess.OrganisationPolicy; +import uk.gov.hmcts.reform.prl.models.dto.ccd.CaseData; +import uk.gov.hmcts.reform.prl.models.dto.ccd.LocalAuthority; +import uk.gov.hmcts.reform.prl.services.AuthorisationService; +import uk.gov.hmcts.reform.prl.services.EventService; +import uk.gov.hmcts.reform.prl.services.localauthority.RemoveLocalAuthoritySolicitorService; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY_DATA; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY; + +@Slf4j +@ExtendWith(MockitoExtension.class) +class LocalAuthorityControllerTest { + + public static final String authToken = "Bearer TestAuthToken"; + private static final String AUTH = "Bearer testAuth"; + private static final String S2S = "testS2S"; + private static final long CASE_ID = 1234567890123456L; + + @InjectMocks + LocalAuthorityController controller; + + @Mock + private ObjectMapper objectMapper; + + @Mock + private EventService eventPublisher; + + @Mock + private AuthorisationService authorisationService; + + @Mock + private RemoveLocalAuthoritySolicitorService removeLocalAuthoritySolicitorService; + + private CaseData buildCaseDataWithOrgPolicy(String orgId) { + return CaseData.builder() + .id(CASE_ID) + .localAuthoritySolicitorOrganisationPolicy( + OrganisationPolicy.builder().organisation(Organisation.builder().organisationID(orgId) + .organisationName("Some Org").build()).build()) + .build(); + } + + @Test + void handleAddAboutToSubmit_authorised_setsLocalAuthoritySolicitorRoleAndReturnsUpdatedData() { + // Arrange + Map inputData = new HashMap<>(); + CaseDetails caseDetails = CaseDetails.builder().id(CASE_ID).data(inputData).build(); + CallbackRequest callbackRequest = CallbackRequest.builder().caseDetails(caseDetails).build(); + + CaseData caseData = buildCaseDataWithOrgPolicy("ORG-123"); + + when(authorisationService.isAuthorized(AUTH, S2S)).thenReturn(true); + when(objectMapper.convertValue(inputData, CaseData.class)).thenReturn(caseData); + + // Act + AboutToStartOrSubmitCallbackResponse response = + controller.handleAddAboutToSubmit(AUTH, S2S, callbackRequest); + + // Assert + assertNotNull(response, "Response should not be null"); + assertNotNull(response.getData(), "Response data map should not be null"); + + assertTrue( + response.getData().containsKey(LOCAL_AUTHORITY_DATA), + "Expected LOCAL_AUTHORITY_DATA FLAG to be set in response map" + ); + assertEquals(LocalAuthority.builder().isLocalAuthorityInvolvedInCase(YesOrNo.Yes) + .localAuthoritySolicitorOrganisationName("Some Org").build(), + response.getData().get(LOCAL_AUTHORITY_DATA)); + assertTrue( + response.getData().containsKey(LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY), + "Expected policy to be set in response map" + ); + + Object policyObj = response.getData().get(LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY); + assertNotNull(policyObj, "OrganisationPolicy should not be null"); + + assertInstanceOf(OrganisationPolicy.class, policyObj, "Policy object type should be OrganisationPolicy"); + OrganisationPolicy updatedPolicy = (OrganisationPolicy) policyObj; + + assertEquals( + "[LASOLICITOR]", updatedPolicy.getOrgPolicyCaseAssignedRole(), + "Case assigned role must be [LASOLICITOR]" + ); + + // Verify authorisation check and mapping were used + verify(authorisationService, times(1)).isAuthorized(AUTH, S2S); + verify(objectMapper, times(1)).convertValue(inputData, CaseData.class); + verifyNoInteractions(removeLocalAuthoritySolicitorService); + } + + @Test + void handleAddAboutToSubmit_unauthorised_throwsRuntimeException() { + // Arrange + Map inputData = new HashMap<>(); + CaseDetails caseDetails = CaseDetails.builder().id(CASE_ID).data(inputData).build(); + CallbackRequest callbackRequest = CallbackRequest.builder().caseDetails(caseDetails).build(); + + when(authorisationService.isAuthorized(AUTH, S2S)).thenReturn(false); + + // Act + Assert + assertThrows( + RuntimeException.class, + () -> controller.handleAddAboutToSubmit(AUTH, S2S, callbackRequest), + "Expected RuntimeException for unauthorised request" + ); + + verify(authorisationService, times(1)).isAuthorized(AUTH, S2S); + verifyNoInteractions(objectMapper, removeLocalAuthoritySolicitorService); + } + + @Test + void shouldNotHandleRemoveAboutToStartWhenNotAuthorised() { + CallbackRequest callbackRequest = CallbackRequest.builder() + .caseDetails(CaseDetails.builder() + .id(1L) + .build()) + .build(); + + when(authorisationService.isAuthorized(AUTH, S2S)).thenReturn(false); + + Assert.assertThrows( + RuntimeException.class, + () -> controller + .handleRemoveAboutToStart(AUTH, S2S, callbackRequest)); + } + + @Test + public void handleRemoveAboutToStartWhenNoLocalAuthorityOrgPolicy() { + Map caseData = new HashMap<>(); + caseData.put("id", 12345L); + caseData.put("caseTypeOfApplication", "C100"); + + CaseData caseData1 = CaseData.builder() + .id(12345L) + .caseTypeOfApplication("C100") + .build(); + + CallbackRequest callbackRequest = CallbackRequest.builder() + .caseDetails(CaseDetails.builder() + .id(1L) + .data(caseData) + .build()) + .build(); + + when(objectMapper.convertValue(caseData, CaseData.class)).thenReturn(caseData1); + when(authorisationService.isAuthorized(AUTH, S2S)).thenReturn(true); + + AboutToStartOrSubmitCallbackResponse callbackResponse = controller + .handleRemoveAboutToStart(AUTH, S2S, callbackRequest); + + assertEquals("No Local authority currently assigned to the case.", callbackResponse.getErrors().get(0)); + verify(removeLocalAuthoritySolicitorService, never()).removeLocalAuthoritySolicitor(eq(caseData1)); + } + + + @Test + public void handleRemoveAboutToStartWhenNullLocalAuthorityOrgPolicy() { + Map caseData = new HashMap<>(); + caseData.put("id", 12345L); + caseData.put("caseTypeOfApplication", "C100"); + caseData.put("localAuthoritySolicitorOrganisationPolicy", null); + + CaseData caseData1 = CaseData.builder() + .id(12345L) + .caseTypeOfApplication("C100") + .build(); + + CallbackRequest callbackRequest = CallbackRequest.builder() + .caseDetails(CaseDetails.builder() + .id(1L) + .data(caseData) + .build()) + .build(); + + when(objectMapper.convertValue(caseData, CaseData.class)).thenReturn(caseData1); + when(authorisationService.isAuthorized(AUTH, S2S)).thenReturn(true); + + AboutToStartOrSubmitCallbackResponse callbackResponse = controller + .handleRemoveAboutToStart(AUTH, S2S, callbackRequest); + + assertEquals("No Local authority currently assigned to the case.", callbackResponse.getErrors().get(0)); + verify(removeLocalAuthoritySolicitorService, never()).removeLocalAuthoritySolicitor(eq(caseData1)); + } + + @Test + void handleRemoveAboutToSubmit_authorised_callsService_andRemovesPolicyFromMap() { + // Arrange + Map inputData = new HashMap<>(); + // Seed the map with the policy key to verify it is removed + inputData.put( + LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY, + OrganisationPolicy.builder().build() + ); + + CaseDetails caseDetails = CaseDetails.builder().id(CASE_ID).data(inputData).build(); + CallbackRequest callbackRequest = CallbackRequest.builder().caseDetails(caseDetails).build(); + + CaseData caseData = buildCaseDataWithOrgPolicy("ORG-456"); + + when(authorisationService.isAuthorized(AUTH, S2S)).thenReturn(true); + when(objectMapper.convertValue(inputData, CaseData.class)).thenReturn(caseData); + + + // Act + AboutToStartOrSubmitCallbackResponse response = + controller.handleRemoveAboutToSubmit(AUTH, S2S, callbackRequest); + + // Assert + assertNotNull(response, "Response should not be null"); + assertNotNull(response.getData(), "Response data should not be null"); + assertTrue( + response.getData().containsKey(LOCAL_AUTHORITY_DATA), + "Expected LOCAL_AUTHORITY_INVOLVED_IN_CASE FLAG to be set in response map" + ); + assertEquals(LocalAuthority.builder().isLocalAuthorityInvolvedInCase(YesOrNo.No) + .localAuthoritySolicitorOrganisationName(null).build(), + response.getData().get(LOCAL_AUTHORITY_DATA)); + assertFalse( + response.getData().containsKey(LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY), + "Policy key should be removed from map" + ); + + ArgumentCaptor caseDataCaptor = ArgumentCaptor.forClass(CaseData.class); + verify(removeLocalAuthoritySolicitorService, times(1)) + .removeLocalAuthoritySolicitor(caseDataCaptor.capture()); + + CaseData passedToService = caseDataCaptor.getValue(); + assertNotNull(passedToService, "CaseData passed to service should not be null"); + assertEquals(CASE_ID, passedToService.getId(), "Case id passed to service should match"); + + verify(authorisationService, times(1)).isAuthorized(AUTH, S2S); + verify(objectMapper, times(1)).convertValue(inputData, CaseData.class); + } + + @Test + void handleRemoveAboutToSubmit_unauthorised_throwsRuntimeException() { + // Arrange + Map inputData = new HashMap<>(); + CaseDetails caseDetails = CaseDetails.builder().id(CASE_ID).data(inputData).build(); + CallbackRequest callbackRequest = CallbackRequest.builder().caseDetails(caseDetails).build(); + + when(authorisationService.isAuthorized(AUTH, S2S)).thenReturn(false); + + // Act + Assert + assertThrows( + RuntimeException.class, + () -> controller.handleRemoveAboutToSubmit(AUTH, S2S, callbackRequest), + "Expected RuntimeException for unauthorised request" + ); + + verify(authorisationService, times(1)).isAuthorized(AUTH, S2S); + verifyNoInteractions(objectMapper, removeLocalAuthoritySolicitorService); + } + + @Test + public void handleRemoveAboutToStartWhenNoLocalAuthorityOrganisationPolicyAdded() { + Map caseData = new HashMap<>(); + caseData.put("id", 12345L); + caseData.put("caseTypeOfApplication", "C100"); + + CaseData caseData1 = CaseData.builder() + .id(12345L) + .caseTypeOfApplication("C100") + .build(); + + CallbackRequest callbackRequest = CallbackRequest.builder() + .caseDetails(CaseDetails.builder() + .id(1L) + .data(caseData) + .build()) + .build(); + + when(objectMapper.convertValue(caseData, CaseData.class)).thenReturn(caseData1); + when(authorisationService.isAuthorized(AUTH, S2S)).thenReturn(true); + + + AboutToStartOrSubmitCallbackResponse callbackResponse = controller + .handleRemoveAboutToSubmit(AUTH, S2S, callbackRequest); + + assertEquals("No Local authority currently assigned to the case", callbackResponse.getErrors().get(0)); + verify(removeLocalAuthoritySolicitorService, never()).removeLocalAuthoritySolicitor(eq(caseData1)); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/prl/mapper/bundle/BundleCreateRequestMapperTest.java b/src/test/java/uk/gov/hmcts/reform/prl/mapper/bundle/BundleCreateRequestMapperTest.java index d1c3e47a1e2..13a6360c162 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/mapper/bundle/BundleCreateRequestMapperTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/mapper/bundle/BundleCreateRequestMapperTest.java @@ -39,6 +39,7 @@ import java.time.LocalDateTime; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; @@ -1047,4 +1048,264 @@ public void testAddOrderDocument_includesValidDocument() { } + private Document createDoc(String name) { + return Document.builder() + .documentFileName(name) + .documentUrl("url") + .documentBinaryUrl("binaryUrl") + .build(); + } + + @Test + public void testLocalAuthorityChild1ImpactDocumentsUpdatedInMap() { + final String categoryId = "childImpactReport1La"; + final String categoryName = "Child Impact Report 1"; + + QuarantineLegalDoc quarantineLegalDoc = QuarantineLegalDoc.builder() + .childImpactReport1LaDocument(createDoc(categoryId)) + .documentParty(DocumentPartyEnum.LOCAL_AUTHORITY.getDisplayedValue()) + .categoryName(categoryName) + .categoryId(categoryId) + .build(); + + CaseData caseData = CaseData.builder() + .reviewDocuments(ReviewDocuments.builder() + .courtStaffUploadDocListDocTab(Collections.singletonList(element( + quarantineLegalDoc))).build()) + .build(); + + List> result = bundleCreateRequestMapper.mapAllOtherDocuments(caseData); + + BundlingRequestDocument expected = result.getFirst().getValue(); + + assertFalse(result.isEmpty()); + assertEquals(categoryId, expected.getDocumentFileName()); + assertEquals(BundlingDocGroupEnum.laSectionChildImpactReport1Report, expected.getDocumentGroup()); + } + + @Test + public void testLocalAuthorityChild2ImpactDocumentsUpdatedInMap() { + final String categoryId = "childImpactReport2La"; + final String categoryName = "Child Impact Report 2"; + + QuarantineLegalDoc quarantineLegalDoc = QuarantineLegalDoc.builder() + .childImpactReport2LaDocument(createDoc(categoryId)) + .documentParty(DocumentPartyEnum.LOCAL_AUTHORITY.getDisplayedValue()) + .categoryName(categoryName) + .categoryId(categoryId) + .build(); + + CaseData caseData = CaseData.builder() + .reviewDocuments(ReviewDocuments.builder() + .courtStaffUploadDocListDocTab(Collections.singletonList(element( + quarantineLegalDoc))).build()) + .build(); + + List> result = bundleCreateRequestMapper.mapAllOtherDocuments(caseData); + + assertFalse(result.isEmpty()); + assertEquals(categoryId, result.get(0).getValue().getDocumentFileName()); + assertEquals(BundlingDocGroupEnum.laSectionChildImpactReport2Report, result.get(0).getValue().getDocumentGroup()); + } + + @Test + public void testLocalAuthoritySection37ReportUpdatedInMap() { + final String categoryId = "sec37Report"; + final String categoryName = "Section 37 (S37) report"; + + QuarantineLegalDoc quarantineLegalDoc = QuarantineLegalDoc.builder() + .sec37ReportDocument(createDoc(categoryId)) + .documentParty(DocumentPartyEnum.LOCAL_AUTHORITY.getDisplayedValue()) + .categoryName(categoryName) + .categoryId(categoryId) + .build(); + + CaseData caseData = CaseData.builder() + .reviewDocuments(ReviewDocuments.builder() + .courtStaffUploadDocListDocTab(Collections.singletonList(element( + quarantineLegalDoc))).build()) + .build(); + + List> result = bundleCreateRequestMapper.mapAllOtherDocuments(caseData); + + assertFalse(result.isEmpty()); + assertEquals(categoryId, result.get(0).getValue().getDocumentFileName()); + assertEquals(BundlingDocGroupEnum.laSection37Report, result.get(0).getValue().getDocumentGroup()); + } + + @Test + public void testLocalAuthoritySection7ReportUpdatedInMap() { + final String categoryId = "section7ReportLa"; + final String categoryName = "Section 7 report"; + + QuarantineLegalDoc quarantineLegalDoc = QuarantineLegalDoc.builder() + .section7ReportLaDocument(createDoc(categoryId)) + .documentParty(DocumentPartyEnum.LOCAL_AUTHORITY.getDisplayedValue()) + .categoryName(categoryName) + .categoryId(categoryId) + .build(); + + CaseData caseData = CaseData.builder() + .reviewDocuments(ReviewDocuments.builder() + .courtStaffUploadDocListDocTab(Collections.singletonList(element( + quarantineLegalDoc))).build()) + .build(); + + List> result = bundleCreateRequestMapper.mapAllOtherDocuments(caseData); + + assertFalse(result.isEmpty()); + assertEquals(categoryId, result.get(0).getValue().getDocumentFileName()); + assertEquals(BundlingDocGroupEnum.laSectionSection7ReportReport, result.get(0).getValue().getDocumentGroup()); + } + + @Test + public void testLocalAuthoritySection7AddendumReportUpdatedInMap() { + final String categoryId = "section7AddendumReportLa"; + final String categoryName = "Section 7 addendum report"; + + QuarantineLegalDoc quarantineLegalDoc = QuarantineLegalDoc.builder() + .section7AddendumReportLaDocument(createDoc(categoryId)) + .documentParty(DocumentPartyEnum.LOCAL_AUTHORITY.getDisplayedValue()) + .categoryName(categoryName) + .categoryId(categoryId) + .build(); + + CaseData caseData = CaseData.builder() + .reviewDocuments(ReviewDocuments.builder() + .courtStaffUploadDocListDocTab(Collections.singletonList(element( + quarantineLegalDoc))).build()) + .build(); + + List> result = bundleCreateRequestMapper.mapAllOtherDocuments(caseData); + + assertFalse(result.isEmpty()); + assertEquals(categoryId, result.get(0).getValue().getDocumentFileName()); + assertEquals(BundlingDocGroupEnum.laSectionSection7AddendumReportReport, result.get(0).getValue().getDocumentGroup()); + } + + @Test + public void testLocalAuthoritySectionInvolvementLetterUpdatedInMap() { + final String categoryId = "localAuthorityInvolvementLa"; + final String categoryName = "Local Authority involvement letter"; + + QuarantineLegalDoc quarantineLegalDoc = QuarantineLegalDoc.builder() + .localAuthorityInvolvementLaDocument(createDoc(categoryId)) + .documentParty(DocumentPartyEnum.LOCAL_AUTHORITY.getDisplayedValue()) + .categoryName(categoryName) + .categoryId(categoryId) + .build(); + + CaseData caseData = CaseData.builder() + .reviewDocuments(ReviewDocuments.builder() + .courtStaffUploadDocListDocTab(Collections.singletonList(element( + quarantineLegalDoc))).build()) + .build(); + + List> result = bundleCreateRequestMapper.mapAllOtherDocuments(caseData); + + assertFalse(result.isEmpty()); + assertEquals(categoryId, result.get(0).getValue().getDocumentFileName()); + assertEquals(BundlingDocGroupEnum.laSectionLocalAuthorityInvolvementReport, result.get(0).getValue().getDocumentGroup()); + } + + @Test + public void testLocalAuthoritySection47EnquiryUpdatedInMap() { + final String categoryId = "section47La"; + final String categoryName = "Section 47 enquiry"; + + QuarantineLegalDoc quarantineLegalDoc = QuarantineLegalDoc.builder() + .section47LaDocument(createDoc(categoryId)) + .documentParty(DocumentPartyEnum.LOCAL_AUTHORITY.getDisplayedValue()) + .categoryName(categoryName) + .categoryId(categoryId) + .build(); + + CaseData caseData = CaseData.builder() + .reviewDocuments(ReviewDocuments.builder() + .courtStaffUploadDocListDocTab(Collections.singletonList(element( + quarantineLegalDoc))).build()) + .build(); + + List> result = bundleCreateRequestMapper.mapAllOtherDocuments(caseData); + + assertFalse(result.isEmpty()); + assertEquals(categoryId, result.get(0).getValue().getDocumentFileName()); + assertEquals(BundlingDocGroupEnum.laSectionSection47EnquiryReport, result.get(0).getValue().getDocumentGroup()); + } + + @Test + public void testLocalAuthorityCirExtensionRequestUpdatedInMap() { + final String categoryId = "cirExtensionRequestLa"; + final String categoryName = "CIR extension request"; + + QuarantineLegalDoc quarantineLegalDoc = QuarantineLegalDoc.builder() + .cirExtensionRequestLaDocument(createDoc(categoryId)) + .documentParty(DocumentPartyEnum.LOCAL_AUTHORITY.getDisplayedValue()) + .categoryName(categoryName) + .categoryId(categoryId) + .build(); + + CaseData caseData = CaseData.builder() + .reviewDocuments(ReviewDocuments.builder() + .courtStaffUploadDocListDocTab(Collections.singletonList(element( + quarantineLegalDoc))).build()) + .build(); + + List> result = bundleCreateRequestMapper.mapAllOtherDocuments(caseData); + + assertFalse(result.isEmpty()); + assertEquals(categoryId, result.get(0).getValue().getDocumentFileName()); + assertEquals(BundlingDocGroupEnum.laSectionCirExtensionRequestReport, result.get(0).getValue().getDocumentGroup()); + } + + @Test + public void testLocalAuthorityCirTransferRequestUpdatedInMap() { + final String categoryId = "cirTransferRequestLa"; + final String categoryName = "CIR transfer request"; + + QuarantineLegalDoc quarantineLegalDoc = QuarantineLegalDoc.builder() + .cirTransferRequestLaDocument(createDoc(categoryId)) + .documentParty(DocumentPartyEnum.LOCAL_AUTHORITY.getDisplayedValue()) + .categoryName(categoryName) + .categoryId(categoryId) + .build(); + + CaseData caseData = CaseData.builder() + .reviewDocuments(ReviewDocuments.builder() + .courtStaffUploadDocListDocTab(Collections.singletonList(element( + quarantineLegalDoc))).build()) + .build(); + + List> result = bundleCreateRequestMapper.mapAllOtherDocuments(caseData); + + assertFalse(result.isEmpty()); + assertEquals(categoryId, result.get(0).getValue().getDocumentFileName()); + assertEquals(BundlingDocGroupEnum.laSectionCirTransferRequestReport, result.get(0).getValue().getDocumentGroup()); + } + + @Test + public void testLocalAuthorityOtherDocumentsUpdatedInMap() { + final String categoryId = "localAuthorityOtherDoc"; + final String categoryName = "Other"; + + QuarantineLegalDoc quarantineLegalDoc = QuarantineLegalDoc.builder() + .localAuthorityOtherDocDocument(createDoc(categoryId)) + .documentParty(DocumentPartyEnum.LOCAL_AUTHORITY.getDisplayedValue()) + .categoryName(categoryName) + .categoryId(categoryId) + .build(); + + CaseData caseData = CaseData.builder() + .reviewDocuments(ReviewDocuments.builder() + .courtStaffUploadDocListDocTab(Collections.singletonList(element( + quarantineLegalDoc))).build()) + .build(); + + List> result = bundleCreateRequestMapper.mapAllOtherDocuments(caseData); + + assertFalse(result.isEmpty()); + assertEquals(categoryId, result.get(0).getValue().getDocumentFileName()); + assertEquals(BundlingDocGroupEnum.laOtherDocuments, result.get(0).getValue().getDocumentGroup()); + } + } diff --git a/src/test/java/uk/gov/hmcts/reform/prl/services/ManageOrderServiceTest.java b/src/test/java/uk/gov/hmcts/reform/prl/services/ManageOrderServiceTest.java index 54994831a54..2f9e35eab7c 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/services/ManageOrderServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/services/ManageOrderServiceTest.java @@ -34,6 +34,7 @@ import uk.gov.hmcts.reform.prl.enums.State; import uk.gov.hmcts.reform.prl.enums.YesNoDontKnow; import uk.gov.hmcts.reform.prl.enums.YesNoNotApplicable; +import uk.gov.hmcts.reform.prl.enums.YesOrNo; import uk.gov.hmcts.reform.prl.enums.dio.DioBeforeAEnum; import uk.gov.hmcts.reform.prl.enums.editandapprove.OrderApprovalDecisionsForCourtAdminOrderEnum; import uk.gov.hmcts.reform.prl.enums.editandapprove.OrderApprovalDecisionsForSolicitorOrderEnum; @@ -66,6 +67,7 @@ import uk.gov.hmcts.reform.prl.models.OtherOrderDetails; import uk.gov.hmcts.reform.prl.models.SdoDetails; import uk.gov.hmcts.reform.prl.models.ServeOrderDetails; +import uk.gov.hmcts.reform.prl.models.caseaccess.OrganisationPolicy; import uk.gov.hmcts.reform.prl.models.common.dynamic.DynamicList; import uk.gov.hmcts.reform.prl.models.common.dynamic.DynamicListElement; import uk.gov.hmcts.reform.prl.models.common.dynamic.DynamicMultiSelectList; @@ -91,6 +93,7 @@ import uk.gov.hmcts.reform.prl.models.dto.ccd.CaseDetails; import uk.gov.hmcts.reform.prl.models.dto.ccd.HearingData; import uk.gov.hmcts.reform.prl.models.dto.ccd.HearingDataPrePopulatedDynamicLists; +import uk.gov.hmcts.reform.prl.models.dto.ccd.LocalAuthority; import uk.gov.hmcts.reform.prl.models.dto.ccd.ManageOrders; import uk.gov.hmcts.reform.prl.models.dto.ccd.ServeOrderData; import uk.gov.hmcts.reform.prl.models.dto.ccd.StandardDirectionOrder; @@ -108,6 +111,7 @@ import uk.gov.hmcts.reform.prl.models.user.UserRoles; import uk.gov.hmcts.reform.prl.services.dynamicmultiselectlist.DynamicMultiSelectListService; import uk.gov.hmcts.reform.prl.services.hearings.HearingService; +import uk.gov.hmcts.reform.prl.services.localauthority.RemoveLocalAuthoritySolicitorService; import uk.gov.hmcts.reform.prl.services.time.Time; import uk.gov.hmcts.reform.prl.utils.AutomatedHearingTransactionRequestMapper; import uk.gov.hmcts.reform.prl.utils.ElementUtils; @@ -134,13 +138,18 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.doCallRealMethod; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.C100_CASE_TYPE; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.CASE_TYPE_OF_APPLICATION; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.ENGLISH; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.FL401_CASE_TYPE; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.IS_INVOKED_FROM_TASK; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY_DATA; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.ORDER_HEARING_DETAILS; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.TASK_LIST_VERSION_V2; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.WA_IS_ORDER_APPROVED; @@ -234,6 +243,8 @@ class ManageOrderServiceTest { @Mock private FinalisationDetailsService finalisationDetailsService; + @Mock + private RemoveLocalAuthoritySolicitorService removeLocalAuthoritySolicitorService; public static final String authToken = "Bearer TestAuthToken"; @@ -6801,4 +6812,85 @@ public void validateAdditionalPartiesShouldReturnErrorsForInvalidEmails() { assertEquals(1, errors.size()); assertEquals(INVALID_EMAIL_ADDRESS_ERROR, errors.getFirst()); } + + @Test + public void shouldRemoveLocalAuthorityFromCase() { + OrganisationPolicy organisationPolicy = OrganisationPolicy.builder() + .organisation(Organisation.builder().organisationName("OrgName").build()) + .build(); + + Map caseDataUpdated = new HashMap<>(); + caseDataUpdated.put("id", 12345L); + caseDataUpdated.put("caseTypeOfApplication", "C100"); + caseDataUpdated.put(LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY, organisationPolicy); + LocalAuthority localAuthority = LocalAuthority.builder() + .localAuthoritySolicitorOrganisationName("OrgName").isLocalAuthorityInvolvedInCase(Yes).build(); + + caseDataUpdated.put(LOCAL_AUTHORITY_DATA, localAuthority); + + List> newOrderDetails = new ArrayList<>(); + newOrderDetails.add(ElementUtils.element(OrderDetails.builder().orderClosesCase(Yes) + .typeOfOrder(SelectTypeOfOrderEnum.finl.getDisplayedValue()) + .build())); + + CaseData caseData = CaseData.builder() + .id(12345L) + .caseTypeOfApplication("C100") + .orderCollection(newOrderDetails) + .localAuthoritySolicitorOrganisationPolicy(organisationPolicy) + .localAuthority(localAuthority) + .selectTypeOfOrder(SelectTypeOfOrderEnum.finl) + .doesOrderClosesCase(Yes) + .build(); + + manageOrderService.removeLocalAuthorityFromCase(caseData, caseDataUpdated); + + verify(removeLocalAuthoritySolicitorService, atLeast(1)).removeLocalAuthoritySolicitor(eq(caseData)); + assertNull(caseDataUpdated.get(LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY)); + LocalAuthority updated = (LocalAuthority) caseDataUpdated.get(LOCAL_AUTHORITY_DATA); + assertNull(updated.getLocalAuthoritySolicitorOrganisationName()); + assertEquals(No, updated.getIsLocalAuthorityInvolvedInCase()); + + } + + @Test + public void shouldNotRemoveLocalAuthorityWhenOrgPolicyIsNotSet() { + + Map caseDataUpdated = new HashMap<>(); + caseDataUpdated.put("id", 12345L); + caseDataUpdated.put("caseTypeOfApplication", "C100"); + LocalAuthority localAuthority = LocalAuthority.builder() + .localAuthoritySolicitorOrganisationName("OrgName").isLocalAuthorityInvolvedInCase(Yes).build(); + + caseDataUpdated.put(LOCAL_AUTHORITY_DATA, localAuthority); + + OrganisationPolicy organisationPolicy = OrganisationPolicy.builder() + .organisation(Organisation.builder().organisationName("OrgName").build()) + .build(); + caseDataUpdated.put(LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY, organisationPolicy); + + + List> newOrderDetails = new ArrayList<>(); + newOrderDetails.add(ElementUtils.element(OrderDetails.builder().orderClosesCase(Yes) + .typeOfOrder(SelectTypeOfOrderEnum.finl.getDisplayedValue()) + .build())); + + CaseData caseData = CaseData.builder() + .id(12345L) + .caseTypeOfApplication("C100") + .orderCollection(newOrderDetails) + .localAuthority(localAuthority) + .selectTypeOfOrder(SelectTypeOfOrderEnum.finl) + .doesOrderClosesCase(Yes) + .build(); + + manageOrderService.removeLocalAuthorityFromCase(caseData, caseDataUpdated); + + verify(removeLocalAuthoritySolicitorService, never()).removeLocalAuthoritySolicitor(eq(caseData)); + assertNotNull(caseDataUpdated.get(LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY)); + LocalAuthority updated = (LocalAuthority) caseDataUpdated.get(LOCAL_AUTHORITY_DATA); + assertNotNull(updated.getLocalAuthoritySolicitorOrganisationName()); + assertEquals(YesOrNo.Yes, updated.getIsLocalAuthorityInvolvedInCase()); + + } } diff --git a/src/test/java/uk/gov/hmcts/reform/prl/services/closingcase/ClosingCaseServiceTest.java b/src/test/java/uk/gov/hmcts/reform/prl/services/closingcase/ClosingCaseServiceTest.java index 22e09cd495f..7234e8617c9 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/services/closingcase/ClosingCaseServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/services/closingcase/ClosingCaseServiceTest.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; @@ -14,6 +15,8 @@ import uk.gov.hmcts.reform.prl.enums.YesOrNo; import uk.gov.hmcts.reform.prl.enums.closingcase.CaseClosingReasonEnum; import uk.gov.hmcts.reform.prl.models.Element; +import uk.gov.hmcts.reform.prl.models.Organisation; +import uk.gov.hmcts.reform.prl.models.caseaccess.OrganisationPolicy; import uk.gov.hmcts.reform.prl.models.common.dynamic.DynamicList; import uk.gov.hmcts.reform.prl.models.common.dynamic.DynamicListElement; import uk.gov.hmcts.reform.prl.models.common.dynamic.DynamicMultiSelectList; @@ -24,6 +27,7 @@ import uk.gov.hmcts.reform.prl.models.complextypes.closingcase.CaseClosingReasonForChildren; import uk.gov.hmcts.reform.prl.models.complextypes.closingcase.DateFinalDecisionWasMade; import uk.gov.hmcts.reform.prl.models.dto.ccd.CaseData; +import uk.gov.hmcts.reform.prl.models.dto.ccd.LocalAuthority; import uk.gov.hmcts.reform.prl.models.dto.ccd.closingcases.ClosingCaseOptions; import uk.gov.hmcts.reform.prl.models.roleassignment.addroleassignment.RoleAssignmentQueryRequest; import uk.gov.hmcts.reform.prl.models.roleassignment.deleteroleassignment.RoleAssignmentDeleteQueryRequest; @@ -32,6 +36,7 @@ import uk.gov.hmcts.reform.prl.services.ApplicationsTabService; import uk.gov.hmcts.reform.prl.services.ApplicationsTabServiceHelper; import uk.gov.hmcts.reform.prl.services.SystemUserService; +import uk.gov.hmcts.reform.prl.services.localauthority.RemoveLocalAuthoritySolicitorService; import uk.gov.hmcts.reform.prl.services.tab.summary.CaseSummaryTabService; import java.util.ArrayList; @@ -44,17 +49,26 @@ import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.http.HttpStatus.OK; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.CASE_CLOSED; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.CHILD_DETAILS_REVISED_TABLE; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.FINAL_CASE_CLOSED_DATE; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY_DATA; +import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.TASK_LIST_VERSION_V2; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.TASK_LIST_VERSION_V3; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.TEST_UUID; +import static uk.gov.hmcts.reform.prl.enums.YesOrNo.No; +import static uk.gov.hmcts.reform.prl.enums.YesOrNo.Yes; import static uk.gov.hmcts.reform.prl.services.closingcase.ClosingCaseService.CHILD_OPTIONS_FOR_FINAL_DECISION; import static uk.gov.hmcts.reform.prl.services.closingcase.ClosingCaseService.FINAL_OUTCOME_FOR_CHILDREN; import static uk.gov.hmcts.reform.prl.utils.ElementUtils.element; @@ -76,6 +90,8 @@ public class ClosingCaseServiceTest { private AuthTokenGenerator authTokenGenerator; @Mock private SystemUserService systemUserService; + @Mock + private RemoveLocalAuthoritySolicitorService removeLocalAuthoritySolicitorService; @InjectMocks ClosingCaseService closingCaseService; @@ -527,4 +543,67 @@ public void testUnAllocateCourtStaffs() { assertTrue(caseDataUpdated.containsKey("legalAdviserList")); } + @Test + public void shouldRemoveLocalAuthorityFromCase() { + OrganisationPolicy organisationPolicy = OrganisationPolicy.builder() + .organisation(Organisation.builder().organisationName("OrgName").build()) + .build(); + + Map caseDataUpdated = new HashMap<>(); + caseDataUpdated.put("id", 12345L); + caseDataUpdated.put("caseTypeOfApplication", "C100"); + caseDataUpdated.put(LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY, organisationPolicy); + + LocalAuthority localAuthority = LocalAuthority.builder() + .localAuthoritySolicitorOrganisationName("OrgName").isLocalAuthorityInvolvedInCase(Yes).build(); + caseDataUpdated.put(LOCAL_AUTHORITY_DATA, localAuthority); + + CaseData caseData = CaseData.builder() + .id(12345L) + .caseTypeOfApplication("C100") + .localAuthoritySolicitorOrganisationPolicy(organisationPolicy) + .localAuthority(localAuthority) + .build(); + + closingCaseService.removeLocalAuthorityFromCase(caseData, caseDataUpdated); + + verify(removeLocalAuthoritySolicitorService, atLeast(1)).removeLocalAuthoritySolicitor(eq(caseData)); + assertNull(caseDataUpdated.get(LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY)); + LocalAuthority updated = (LocalAuthority) caseDataUpdated.get(LOCAL_AUTHORITY_DATA); + assertNull(updated.getLocalAuthoritySolicitorOrganisationName()); + Assertions.assertEquals(No, updated.getIsLocalAuthorityInvolvedInCase()); + + } + + @Test + public void shouldNotRemoveLocalAuthorityWhenOrgPolicyIsNotSet() { + + Map caseDataUpdated = new HashMap<>(); + caseDataUpdated.put("id", 12345L); + caseDataUpdated.put("caseTypeOfApplication", "C100"); + + LocalAuthority localAuthority = LocalAuthority.builder() + .localAuthoritySolicitorOrganisationName("OrgName").isLocalAuthorityInvolvedInCase(Yes).build(); + caseDataUpdated.put(LOCAL_AUTHORITY_DATA, localAuthority); + + OrganisationPolicy organisationPolicy = OrganisationPolicy.builder() + .organisation(Organisation.builder().organisationName("OrgName").build()) + .build(); + caseDataUpdated.put(LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY, organisationPolicy); + + CaseData caseData = CaseData.builder() + .id(12345L) + .caseTypeOfApplication("C100") + .localAuthority(localAuthority) + .build(); + + closingCaseService.removeLocalAuthorityFromCase(caseData, caseDataUpdated); + + verify(removeLocalAuthoritySolicitorService, never()).removeLocalAuthoritySolicitor(eq(caseData)); + assertNotNull(caseDataUpdated.get(LOCAL_AUTHORITY_SOLICITOR_ORGANISATION_POLICY)); + LocalAuthority updated = (LocalAuthority) caseDataUpdated.get(LOCAL_AUTHORITY_DATA); + assertNotNull(updated.getLocalAuthoritySolicitorOrganisationName()); + Assertions.assertEquals(YesOrNo.Yes, updated.getIsLocalAuthorityInvolvedInCase()); + + } } diff --git a/src/test/java/uk/gov/hmcts/reform/prl/services/localauthority/RemoveLocalAuthoritySolicitorServiceTest.java b/src/test/java/uk/gov/hmcts/reform/prl/services/localauthority/RemoveLocalAuthoritySolicitorServiceTest.java new file mode 100644 index 00000000000..f30445e1c94 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/prl/services/localauthority/RemoveLocalAuthoritySolicitorServiceTest.java @@ -0,0 +1,202 @@ +package uk.gov.hmcts.reform.prl.services.localauthority; + +import feign.FeignException; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import uk.gov.hmcts.reform.authorisation.generators.AuthTokenGenerator; +import uk.gov.hmcts.reform.ccd.client.CaseAssignmentApi; +import uk.gov.hmcts.reform.ccd.client.model.CaseAssignmentUserRoleWithOrganisation; +import uk.gov.hmcts.reform.ccd.client.model.CaseAssignmentUserRolesRequest; +import uk.gov.hmcts.reform.prl.exception.GrantCaseAccessException; +import uk.gov.hmcts.reform.prl.models.Organisation; +import uk.gov.hmcts.reform.prl.models.caseaccess.OrganisationPolicy; +import uk.gov.hmcts.reform.prl.models.dto.ccd.CaseData; +import uk.gov.hmcts.reform.prl.models.roleassignment.getroleassignment.RoleAssignmentResponse; +import uk.gov.hmcts.reform.prl.models.roleassignment.getroleassignment.RoleAssignmentServiceResponse; +import uk.gov.hmcts.reform.prl.services.RoleAssignmentService; +import uk.gov.hmcts.reform.prl.services.SystemUserService; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@Slf4j +@ExtendWith(MockitoExtension.class) +public class RemoveLocalAuthoritySolicitorServiceTest { + + public static final String LOCAL_AUTHORITY_SOLICITOR_CASE_ROLE = "[LASOLICITOR]"; + @InjectMocks + public RemoveLocalAuthoritySolicitorService service; + + @Mock + private CaseAssignmentApi caseAssignmentApi; + @Mock + private SystemUserService systemUserService; + @Mock + private AuthTokenGenerator tokenGenerator; + @Mock + private RoleAssignmentService roleAssignmentService; + + private CaseData buildCaseData(long caseId, String orgId) { + return CaseData.builder() + .id(caseId) + .localAuthoritySolicitorOrganisationPolicy( + OrganisationPolicy.builder() + .organisation( + Organisation.builder() + .organisationID(orgId) + .organisationName("Some Org") + .build() + ) + .build() + ) + .build(); + } + + @Test + void removeLocalAuthoritySolicitors_shouldRemoveAllLocalAuthoritySolicitorRoles() { + // Arrange + long caseId = 1234567890123456L; + + // Mock role assignments: two with [LASOLICITOR], one with other role + RoleAssignmentResponse la1 = mock(RoleAssignmentResponse.class); + when(la1.getRoleName()).thenReturn(LOCAL_AUTHORITY_SOLICITOR_CASE_ROLE); + when(la1.getActorId()).thenReturn("user-1"); + + RoleAssignmentResponse la2 = mock(RoleAssignmentResponse.class); + when(la2.getRoleName()).thenReturn(LOCAL_AUTHORITY_SOLICITOR_CASE_ROLE); + when(la2.getActorId()).thenReturn("user-2"); + + RoleAssignmentResponse other = mock(RoleAssignmentResponse.class); + when(other.getRoleName()).thenReturn("[OTHERROLE]"); + + RoleAssignmentServiceResponse raResponse = mock(RoleAssignmentServiceResponse.class); + when(raResponse.getRoleAssignmentResponse()).thenReturn(Arrays.asList(la1, la2, other)); + when(roleAssignmentService.getRoleAssignmentForCase(String.valueOf(caseId))).thenReturn(raResponse); + + // Tokens + when(systemUserService.getSysUserToken()).thenReturn("sysToken"); + when(tokenGenerator.generate()).thenReturn("svcToken"); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(CaseAssignmentUserRolesRequest.class); + + String orgId = "ORG-123"; + CaseData caseData = buildCaseData(caseId, orgId); + + // Act + service.removeLocalAuthoritySolicitor(caseData); + + // Assert: CCD API called once with tokens and correctly built request + verify(caseAssignmentApi, times(1)) + .removeCaseUserRoles(eq("sysToken"), eq("svcToken"), requestCaptor.capture()); + + CaseAssignmentUserRolesRequest captured = requestCaptor.getValue(); + assertNotNull(captured, "Expected a CaseAssignmentUserRolesRequest"); + List entries = + captured.getCaseAssignmentUserRolesWithOrganisation(); + + assertNotNull(entries, "Entries list should not be null"); + assertEquals(2, entries.size(), "Only LASOLICITOR users must be included"); + + // Validate each entry + for (CaseAssignmentUserRoleWithOrganisation e : entries) { + assertEquals(String.valueOf(caseId), e.getCaseDataId(), "Case id must match"); + assertEquals(orgId, e.getOrganisationId(), "Org id must match"); + assertEquals(LOCAL_AUTHORITY_SOLICITOR_CASE_ROLE, e.getCaseRole(), "Case role must be LASOLICITOR"); + assertTrue( + Arrays.asList("user-1", "user-2").contains(e.getUserId()), + "Unexpected user id in request: " + e.getUserId() + ); + } + + // Make sure role assignment was fetched once + verify(roleAssignmentService, times(1)).getRoleAssignmentForCase(String.valueOf(caseId)); + } + + @Test + void removeLocalAuthoritySolicitor_whenCcdApiThrowsFeign_shouldThrowGrantCaseAccessException() { + // Arrange + long caseId = 9876543210L; + + // One matching LASOLICITOR actor + RoleAssignmentResponse la1 = mock(RoleAssignmentResponse.class); + when(la1.getRoleName()).thenReturn(LOCAL_AUTHORITY_SOLICITOR_CASE_ROLE); + when(la1.getActorId()).thenReturn("actor-77"); + + RoleAssignmentServiceResponse raResponse = mock(RoleAssignmentServiceResponse.class); + when(raResponse.getRoleAssignmentResponse()).thenReturn(Collections.singletonList(la1)); + when(roleAssignmentService.getRoleAssignmentForCase(String.valueOf(caseId))).thenReturn(raResponse); + + when(systemUserService.getSysUserToken()).thenReturn("sys"); + when(tokenGenerator.generate()).thenReturn("svc"); + + // Force CCD API to throw FeignException (mock instance is fine as FeignException is a RuntimeException) + doThrow(mock(FeignException.class)) + .when(caseAssignmentApi) + .removeCaseUserRoles(eq("sys"), eq("svc"), any(CaseAssignmentUserRolesRequest.class)); + + String orgId = "ORG-XYZ"; + CaseData caseData = buildCaseData(caseId, orgId); + + // Act + Assert + GrantCaseAccessException ex = assertThrows( + GrantCaseAccessException.class, + () -> service.removeLocalAuthoritySolicitor(caseData), + "Expected GrantCaseAccessException when FeignException occurs" + ); + + assertTrue( + ex.getMessage().contains(String.valueOf(caseId)) + && ex.getMessage().contains(LOCAL_AUTHORITY_SOLICITOR_CASE_ROLE), + "Error message should contain case id and role" + ); + + verify(caseAssignmentApi, times(1)) + .removeCaseUserRoles(eq("sys"), eq("svc"), any(CaseAssignmentUserRolesRequest.class)); + } + + @Test + void removeLocalAuthoritySolicitor_whenNoMatchingRoles_callsApiWithEmptyList() { + // Arrange + + RoleAssignmentResponse other1 = mock(RoleAssignmentResponse.class); + when(other1.getRoleName()).thenReturn("[CITIZEN]"); + + RoleAssignmentServiceResponse raResponse = mock(RoleAssignmentServiceResponse.class); + when(raResponse.getRoleAssignmentResponse()).thenReturn(Collections.singletonList(other1)); + long caseId = 1122334455L; + when(roleAssignmentService.getRoleAssignmentForCase(String.valueOf(caseId))).thenReturn(raResponse); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(CaseAssignmentUserRolesRequest.class); + + String orgId = "ORG-empty"; + CaseData caseData = buildCaseData(caseId, orgId); + + // Act + service.removeLocalAuthoritySolicitor(caseData); + + // Assert + verify(caseAssignmentApi, never()) + .removeCaseUserRoles(eq("sysTok"), eq("svcTok"), requestCaptor.capture()); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/prl/services/managedocuments/ManageDocumentsServiceTest.java b/src/test/java/uk/gov/hmcts/reform/prl/services/managedocuments/ManageDocumentsServiceTest.java index 3b79fc3e7c9..14527b8fb0f 100644 --- a/src/test/java/uk/gov/hmcts/reform/prl/services/managedocuments/ManageDocumentsServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/prl/services/managedocuments/ManageDocumentsServiceTest.java @@ -33,6 +33,7 @@ import uk.gov.hmcts.reform.prl.clients.RoleAssignmentApi; import uk.gov.hmcts.reform.prl.clients.ccd.records.StartAllTabsUpdateDataContent; import uk.gov.hmcts.reform.prl.config.launchdarkly.LaunchDarklyClient; +import uk.gov.hmcts.reform.prl.constants.ManageDocumentsCategoryConstants; import uk.gov.hmcts.reform.prl.constants.PrlAppsConstants; import uk.gov.hmcts.reform.prl.enums.Roles; import uk.gov.hmcts.reform.prl.enums.YesOrNo; @@ -48,6 +49,7 @@ import uk.gov.hmcts.reform.prl.models.dto.ccd.ReviewDocuments; import uk.gov.hmcts.reform.prl.models.roleassignment.getroleassignment.RoleAssignmentResponse; import uk.gov.hmcts.reform.prl.models.roleassignment.getroleassignment.RoleAssignmentServiceResponse; +import uk.gov.hmcts.reform.prl.services.RoleAssignmentService; import uk.gov.hmcts.reform.prl.services.SystemUserService; import uk.gov.hmcts.reform.prl.services.UserService; import uk.gov.hmcts.reform.prl.services.notifications.NotificationService; @@ -94,8 +96,12 @@ import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.RESTRICTED_DOCUMENTS; import static uk.gov.hmcts.reform.prl.constants.PrlAppsConstants.SOLICITOR_ROLE; import static uk.gov.hmcts.reform.prl.constants.PrlLaunchDarklyFlagConstants.ROLE_ASSIGNMENT_API_IN_ORDERS_JOURNEY; +import static uk.gov.hmcts.reform.prl.enums.Roles.LOCAL_AUTHORITY_SOLICITOR; +import static uk.gov.hmcts.reform.prl.enums.Roles.LOCAL_AUTHORITY_STAFF; +import static uk.gov.hmcts.reform.prl.enums.managedocuments.DocumentPartyEnum.LOCAL_AUTHORITY; import static uk.gov.hmcts.reform.prl.services.managedocuments.ManageDocumentsService.MANAGE_DOCUMENTS_RESTRICTED_FLAG; import static uk.gov.hmcts.reform.prl.services.managedocuments.ManageDocumentsService.MANAGE_DOCUMENTS_TRIGGERED_BY; +import static uk.gov.hmcts.reform.prl.services.managedocuments.ManageDocumentsService.MANAGE_DOCUMENTS_UPLOADED_CATEGORY; import static uk.gov.hmcts.reform.prl.utils.ElementUtils.element; import static uk.gov.hmcts.reform.prl.utils.ElementUtils.nullSafeCollection; @@ -150,6 +156,9 @@ public class ManageDocumentsServiceTest { @Mock private UserService userService; + @Mock + private RoleAssignmentService roleAssignmentService; + @Mock private StartAllTabsUpdateDataContent startAllTabsUpdateDataContent; @@ -183,6 +192,8 @@ public class ManageDocumentsServiceTest { List> cafcassQuarantineDocsList; + List> localAuthorityQuarantineDocsList; + List> cafcassUploadDocListDocTab; List> courtStaffQuarantineDocsList; @@ -353,12 +364,101 @@ public void init() { @Test public void testPopulateDocumentCategories() { when(authTokenGenerator.generate()).thenReturn(serviceAuthToken); - + when(roleAssignmentService.isUserAllocatedRoleForCase(anyString(), anyString(), anyString())).thenReturn(false); when(coreCaseDataApi.getCategoriesAndDocuments( any(), any(), any() )).thenReturn(categoriesAndDocuments); + when(userService.getUserDetails(auth)).thenReturn(userDetailsSolicitorRole); + + CaseData caseData = CaseData.builder().build(); + + CaseData updatedCaseData = manageDocumentsService.populateDocumentCategories(auth, caseData); + String docCode = updatedCaseData.getDocumentManagementDetails() + .getManageDocuments().get(0).getValue().getDocumentCategories().getListItems() + .get(0).getCode(); + assertEquals(subCategory2.getCategoryId(), docCode); + + } + + @Test + public void testPopulateDocumentCategoriesForLaParty() { + + Category laCategory = new Category("localAuthorityDocuments", "localAuthorityDocuments", + 2, List.of(document), List.of(subCategory1, subCategory2)); + CategoriesAndDocuments laCategoriesAndDocuments = new CategoriesAndDocuments(1, List.of(laCategory), List.of(document)); + + when(authTokenGenerator.generate()).thenReturn(serviceAuthToken); + when(roleAssignmentService.isUserAllocatedRoleForCase(anyString(), anyString(), anyString())).thenReturn(true); + when(userService.getUserDetails(auth)).thenReturn(userDetailsSolicitorRole); + + when(coreCaseDataApi.getCategoriesAndDocuments( + any(), + any(), + any() + )).thenReturn(laCategoriesAndDocuments); + + + CaseData caseData = CaseData.builder().build(); + + CaseData updatedCaseData = manageDocumentsService.populateDocumentCategories(auth, caseData); + String docCode = updatedCaseData.getDocumentManagementDetails() + .getManageDocuments().get(0).getValue().getDocumentCategories().getListItems() + .get(0).getCode(); + DocumentPartyEnum laParty = updatedCaseData.getDocumentManagementDetails() + .getManageDocuments().get(0).getValue().getDocumentParty(); + assertEquals(subCategory2.getCategoryId(), docCode); + assertEquals(LOCAL_AUTHORITY, laParty); + } + + @Test + public void testLaPartyWithRoleSocialWorker() { + + Category laCategory = new Category("localAuthorityDocuments", "localAuthorityDocuments", 2, + List.of(document), List.of(subCategory1, subCategory2)); + CategoriesAndDocuments laCategoriesAndDocuments = new CategoriesAndDocuments(1, List.of(laCategory), List.of(document)); + + when(authTokenGenerator.generate()).thenReturn(serviceAuthToken); + when(roleAssignmentService.isUserAllocatedRoleForCase(anyString(), anyString(), eq(LOCAL_AUTHORITY_STAFF.getValue()))).thenReturn(true); + when(userService.getUserDetails(auth)).thenReturn(userDetailsSolicitorRole); + + when(coreCaseDataApi.getCategoriesAndDocuments( + any(), + any(), + any() + )).thenReturn(laCategoriesAndDocuments); + + + CaseData caseData = CaseData.builder().build(); + + CaseData updatedCaseData = manageDocumentsService.populateDocumentCategories(auth, caseData); + String docCode = updatedCaseData.getDocumentManagementDetails() + .getManageDocuments().get(0).getValue().getDocumentCategories().getListItems() + .get(0).getCode(); + DocumentPartyEnum laParty = updatedCaseData.getDocumentManagementDetails() + .getManageDocuments().get(0).getValue().getDocumentParty(); + assertEquals(subCategory2.getCategoryId(), docCode); + assertEquals(LOCAL_AUTHORITY, laParty); + } + + @Test + public void testLaPartyWithRoleSolicitor() { + + Category laCategory = new Category("localAuthorityDocuments", "localAuthorityDocuments", 2, + List.of(document), List.of(subCategory1, subCategory2)); + CategoriesAndDocuments laCategoriesAndDocuments = new CategoriesAndDocuments(1, List.of(laCategory), List.of(document)); + + when(authTokenGenerator.generate()).thenReturn(serviceAuthToken); + when(roleAssignmentService.isUserAllocatedRoleForCase(anyString(), anyString(), eq(LOCAL_AUTHORITY_SOLICITOR.getValue()))).thenReturn(true); + when(userService.getUserDetails(auth)).thenReturn(userDetailsSolicitorRole); + + when(coreCaseDataApi.getCategoriesAndDocuments( + any(), + any(), + any() + )).thenReturn(laCategoriesAndDocuments); + CaseData caseData = CaseData.builder().build(); @@ -366,8 +466,37 @@ public void testPopulateDocumentCategories() { String docCode = updatedCaseData.getDocumentManagementDetails() .getManageDocuments().get(0).getValue().getDocumentCategories().getListItems() .get(0).getCode(); + DocumentPartyEnum laParty = updatedCaseData.getDocumentManagementDetails() + .getManageDocuments().get(0).getValue().getDocumentParty(); assertEquals(subCategory2.getCategoryId(), docCode); + assertEquals(LOCAL_AUTHORITY, laParty); + } + + + @Test + public void testDefaultDocumentPartyForNonLaParty() { + + when(authTokenGenerator.generate()).thenReturn(serviceAuthToken); + when(roleAssignmentService.isUserAllocatedRoleForCase(anyString(), anyString(), anyString())).thenReturn(false); + when(userService.getUserDetails(auth)).thenReturn(userDetailsSolicitorRole); + + when(coreCaseDataApi.getCategoriesAndDocuments( + any(), + any(), + any() + )).thenReturn(categoriesAndDocuments); + + + CaseData caseData = CaseData.builder().build(); + CaseData updatedCaseData = manageDocumentsService.populateDocumentCategories(auth, caseData); + String docCode = updatedCaseData.getDocumentManagementDetails() + .getManageDocuments().get(0).getValue().getDocumentCategories().getListItems() + .get(0).getCode(); + DocumentPartyEnum laParty = updatedCaseData.getDocumentManagementDetails() + .getManageDocuments().get(0).getValue().getDocumentParty(); + assertEquals(subCategory2.getCategoryId(), docCode); + assertNull(laParty); } @Test @@ -387,6 +516,8 @@ public void testPopulateDocumentCategoriesExcludeCategory() { Mockito.any(), Mockito.any() )).thenReturn(categoriesAndDocuments); + when(roleAssignmentService.isUserAllocatedRoleForCase(anyString(), anyString(), anyString())).thenReturn(true); + when(userService.getUserDetails(auth)).thenReturn(userDetailsSolicitorRole); CaseData caseData = CaseData.builder().build(); @@ -399,7 +530,10 @@ public void testPopulateDocumentCategoriesExcludeCategory() { @Test @DisplayName("test case for populateDocumentCategories Exception.") public void testPopulateDocumentCategoriesException() { + when(roleAssignmentService.isUserAllocatedRoleForCase(anyString(), anyString(), anyString())).thenReturn(true); when(authTokenGenerator.generate()).thenThrow(new RuntimeException()); + when(userService.getUserDetails(auth)).thenReturn(userDetailsSolicitorRole); + CaseData caseData = CaseData.builder().build(); CaseData updatedCaseData = manageDocumentsService.populateDocumentCategories(auth, caseData); List listItems = updatedCaseData.getDocumentManagementDetails().getManageDocuments() @@ -2579,6 +2713,22 @@ public void testLoggedInUserTypeCafcassWhenRolAssignApiRespIs() { assertNotNull(loggedInUserTypeList); } + @Test + public void testLoggedInUserIsLocalAuthorityWithSolicitorRole() { + RoleAssignmentServiceResponse roleAssignmentServiceResponse = setAndGetRoleAssignmentServiceResponse( + "[LASOLICITOR]"); + when(authTokenGenerator.generate()).thenReturn( + "serviceAuthToken"); + when(userService.getUserDetails(auth)).thenReturn((userDetailsSolicitorRole)); + when(launchDarklyClient.isFeatureEnabled(ROLE_ASSIGNMENT_API_IN_ORDERS_JOURNEY)).thenReturn(true); + when(roleAssignmentApi.getRoleAssignments(auth, authTokenGenerator.generate(), null, "123")).thenReturn( + roleAssignmentServiceResponse); + + List loggedInUserTypeList = manageDocumentsService.getLoggedInUserType(auth); + assertNotNull(loggedInUserTypeList); + assertTrue(loggedInUserTypeList.contains("LOCAL_AUTHORITY")); + } + @Test public void testAppendConfidentialDocumentNameForCourtAdmin() { Map caseDataUpdated1 = new HashMap<>(); @@ -2747,4 +2897,207 @@ public void shouldNotTryToCleanupConfidentialDocumentThatHasFailedToBeRenamed() verifyNoInteractions(caseDocumentClient); } + + @Test + public void testSetFlagsWaTaskWhenLocalAuthorityUploadsCirRequestDocumentsButNoTriggeredBySet() { + Map caseDataUpdated1 = new HashMap<>(); + List> localAuthorityQuarantineDocsListInitial = new ArrayList<>(); + Element element = element(QuarantineLegalDoc.builder().categoryId( + ManageDocumentsCategoryConstants.CIR_EXTENSION_REQUEST_LA).isRestricted(YesOrNo.Yes).build()); + localAuthorityQuarantineDocsListInitial.add(element); + + DocumentManagementDetails documentManagementDetails = DocumentManagementDetails.builder().build(); + documentManagementDetails.setLocalAuthorityQuarantineDocsList(localAuthorityQuarantineDocsListInitial); + + manageDocumentsService.setFlagsForWaTask( + CaseData.builder().documentManagementDetails(documentManagementDetails).build(), + caseDataUpdated1, "LOCAL_AUTHORITY", + element.getValue() + ); + assertEquals("True", caseDataUpdated1.get(MANAGE_DOCUMENTS_RESTRICTED_FLAG)); + assertNull(caseDataUpdated1.get(MANAGE_DOCUMENTS_TRIGGERED_BY)); + } + + @Test + public void testSetFlagsWaTaskWhenLocalAuthorityUploadsCirRequestDocumentsAndSetTriggeredBy() { + Map caseDataUpdated1 = new HashMap<>(); + List> localAuthorityQuarantineDocsListInitial = new ArrayList<>(); + Element element = element(QuarantineLegalDoc.builder().categoryId( + ManageDocumentsCategoryConstants.CIR_EXTENSION_REQUEST_LA).isRestricted(YesOrNo.Yes).build()); + + + DocumentManagementDetails documentManagementDetails = DocumentManagementDetails.builder().build(); + documentManagementDetails.setLocalAuthorityQuarantineDocsList(localAuthorityQuarantineDocsListInitial); + + manageDocumentsService.setFlagsForWaTask( + CaseData.builder().documentManagementDetails(documentManagementDetails).build(), + caseDataUpdated1, "LOCAL_AUTHORITY", + element.getValue() + ); + assertEquals("True", caseDataUpdated1.get(MANAGE_DOCUMENTS_RESTRICTED_FLAG)); + assertEquals("LOCAL_AUTHORITY", caseDataUpdated1.get(MANAGE_DOCUMENTS_TRIGGERED_BY)); + } + + @Test + public void testSetFlagsWaTaskWhenLocalAuthorityUploadsCirTransferDocumentsButNoTriggeredBySet() { + Map caseDataUpdated1 = new HashMap<>(); + List> localAuthorityQuarantineDocsListInitial = new ArrayList<>(); + Element element = element(QuarantineLegalDoc.builder().categoryId( + ManageDocumentsCategoryConstants.CIR_TRANSFER_REQUEST_LA).isRestricted(YesOrNo.Yes).build()); + localAuthorityQuarantineDocsListInitial.add(element); + + DocumentManagementDetails documentManagementDetails = DocumentManagementDetails.builder().build(); + documentManagementDetails.setLocalAuthorityQuarantineDocsList(localAuthorityQuarantineDocsListInitial); + + manageDocumentsService.setFlagsForWaTask( + CaseData.builder().documentManagementDetails(documentManagementDetails).build(), + caseDataUpdated1, "LOCAL_AUTHORITY", + element.getValue() + ); + assertEquals("True", caseDataUpdated1.get(MANAGE_DOCUMENTS_RESTRICTED_FLAG)); + assertNull(caseDataUpdated1.get(MANAGE_DOCUMENTS_TRIGGERED_BY)); + } + + @Test + public void testSetFlagsWaTaskWhenLocalAuthorityUploadsCirTransferDocumentsAndSetTriggeredBy() { + Map caseDataUpdated1 = new HashMap<>(); + List> localAuthorityQuarantineDocsListInitial = new ArrayList<>(); + Element element = element(QuarantineLegalDoc.builder().categoryId( + ManageDocumentsCategoryConstants.CIR_TRANSFER_REQUEST_LA).isRestricted(YesOrNo.Yes).build()); + + DocumentManagementDetails documentManagementDetails = DocumentManagementDetails.builder().build(); + documentManagementDetails.setLocalAuthorityQuarantineDocsList(localAuthorityQuarantineDocsListInitial); + + manageDocumentsService.setFlagsForWaTask( + CaseData.builder().documentManagementDetails(documentManagementDetails).build(), + caseDataUpdated1, "LOCAL_AUTHORITY", + element.getValue() + ); + assertEquals("True", caseDataUpdated1.get(MANAGE_DOCUMENTS_RESTRICTED_FLAG)); + assertEquals("LOCAL_AUTHORITY", caseDataUpdated1.get(MANAGE_DOCUMENTS_TRIGGERED_BY)); + } + + @Test + public void testSetFlagsWaTaskWhenLocalAuthorityUploadsNonCirDocumentsButNoTriggeredBySet() { + Map caseDataUpdated1 = new HashMap<>(); + List> localAuthorityQuarantineDocsListInitial = new ArrayList<>(); + Element element = element(QuarantineLegalDoc.builder().categoryId( + ManageDocumentsCategoryConstants.CHILD_IMPACT_REPORT_1_LA).isRestricted(YesOrNo.Yes).build()); + localAuthorityQuarantineDocsListInitial.add(element); + + DocumentManagementDetails documentManagementDetails = DocumentManagementDetails.builder().build(); + documentManagementDetails.setLocalAuthorityQuarantineDocsList(localAuthorityQuarantineDocsListInitial); + + manageDocumentsService.setFlagsForWaTask( + CaseData.builder().documentManagementDetails(documentManagementDetails).build(), + caseDataUpdated1, "LOCAL_AUTHORITY", + element.getValue() + ); + assertEquals("True", caseDataUpdated1.get(MANAGE_DOCUMENTS_RESTRICTED_FLAG)); + assertNull(caseDataUpdated1.get(MANAGE_DOCUMENTS_TRIGGERED_BY)); + } + + @Test + public void testSetFlagsWaTaskWhenLocalAuthorityUploadsNonCirDocumentsAndSetTriggeredBy() { + Map caseDataUpdated1 = new HashMap<>(); + List> localAuthorityQuarantineDocsListInitial = new ArrayList<>(); + Element element = element(QuarantineLegalDoc.builder().categoryId( + ManageDocumentsCategoryConstants.CHILD_IMPACT_REPORT_1_LA).isRestricted(YesOrNo.Yes).build()); + + DocumentManagementDetails documentManagementDetails = DocumentManagementDetails.builder().build(); + documentManagementDetails.setLocalAuthorityQuarantineDocsList(localAuthorityQuarantineDocsListInitial); + + manageDocumentsService.setFlagsForWaTask( + CaseData.builder().documentManagementDetails(documentManagementDetails).build(), + caseDataUpdated1, "LOCAL_AUTHORITY", + element.getValue() + ); + assertEquals("True", caseDataUpdated1.get(MANAGE_DOCUMENTS_RESTRICTED_FLAG)); + assertEquals("LOCAL_AUTHORITY", caseDataUpdated1.get(MANAGE_DOCUMENTS_TRIGGERED_BY)); + } + + @Test + public void testSetFlagsWaTaskWhenLocalAuthorityUploadsAnyDocumentsAndSetInCategoryMap() { + Map caseDataUpdated1 = new HashMap<>(); + List> localAuthorityQuarantineDocsListInitial = new ArrayList<>(); + Element element = element(QuarantineLegalDoc.builder().categoryId( + ManageDocumentsCategoryConstants.CHILD_IMPACT_REPORT_2_LA).isRestricted(YesOrNo.Yes).build()); + + DocumentManagementDetails documentManagementDetails = DocumentManagementDetails.builder().build(); + documentManagementDetails.setLocalAuthorityQuarantineDocsList(localAuthorityQuarantineDocsListInitial); + + manageDocumentsService.setFlagsForWaTask( + CaseData.builder().documentManagementDetails(documentManagementDetails).build(), + caseDataUpdated1, "LOCAL_AUTHORITY", + element.getValue() + ); + assertEquals("True", caseDataUpdated1.get(MANAGE_DOCUMENTS_RESTRICTED_FLAG)); + assertEquals( + ManageDocumentsCategoryConstants.CHILD_IMPACT_REPORT_2_LA, + caseDataUpdated1.get(MANAGE_DOCUMENTS_UPLOADED_CATEGORY) + ); + } + + @Test + public void testCopyDocumentForNonCirDocumentsIfRestrictedWithLocalAuthorityRole() { + + ManageDocuments manageDocuments = ManageDocuments.builder() + .documentParty(LOCAL_AUTHORITY) + .documentCategories(dynamicList) + .isRestricted(YesOrNo.Yes) + .isConfidential(YesOrNo.Yes) + .document(uk.gov.hmcts.reform.prl.models.documents.Document.builder().build()) + .build(); + + Map caseDataMapInitial = new HashMap<>(); + caseDataMapInitial.put("manageDocuments", manageDocuments); + + List> localAuthorityQuarantineDocsListInitial = new ArrayList<>(); + localAuthorityQuarantineDocsListInitial.add(element(QuarantineLegalDoc.builder().build())); + caseDataMapInitial.put("localAuthorityQuarantineDocsList", localAuthorityQuarantineDocsListInitial); + + List> localAuthorityUploadDocListDocTabInitial = new ArrayList<>(); + caseDataMapInitial.put("localAuthorityUploadDocListDocTab", localAuthorityUploadDocListDocTabInitial); + + manageDocumentsElement = element(manageDocuments); + + QuarantineLegalDoc quarantineLegalDoc = QuarantineLegalDoc.builder().build(); + quarantineLegalDocElement = element(quarantineLegalDoc); + + ReviewDocuments reviewDocuments = ReviewDocuments.builder().build(); + + CaseData caseData = CaseData.builder() + .reviewDocuments(reviewDocuments) + .documentManagementDetails(DocumentManagementDetails.builder() + .manageDocuments(List.of(manageDocumentsElement)) + .build()) + .build(); + CaseDetails caseDetails = CaseDetails.builder().id(12345L).data(caseDataMapInitial).build(); + CallbackRequest callbackRequest = CallbackRequest.builder().caseDetails(caseDetails).build(); + + when(objectMapper.convertValue(caseDetails.getData(), CaseData.class)).thenReturn(caseData); + when(userService.getUserDetails(auth)).thenReturn(userDetailsSolicitorRole); + + Map caseDataMapUpdated = manageDocumentsService.copyDocument(callbackRequest, auth); + + localAuthorityQuarantineDocsList = (List>) caseDataMapUpdated.get( + "localAuthorityQuarantineDocsList"); + assertNotNull(localAuthorityQuarantineDocsList); + assertEquals(1, localAuthorityQuarantineDocsList.size()); + assertNull(caseDataMapUpdated.get("manageDocuments")); + } + + @Test + public void testGetQuarantineDocumentForUploaderLocalAuthority() { + QuarantineLegalDoc quarantineLegalDoc = QuarantineLegalDoc.builder() + .localAuthorityQuarantineDocument(uk.gov.hmcts.reform.prl.models.documents.Document + .builder().documentUrl("http://test.com/documents/d848addb-c53f-4ac0-a8ce-0a9e7f4d17ba").build()).build(); + uk.gov.hmcts.reform.prl.models.documents.Document document1 = manageDocumentsService + .getQuarantineDocumentForUploader("LOCAL_AUTHORITY", quarantineLegalDoc + ); + + assertNotNull(document1); + assertEquals(quarantineLegalDoc.getLocalAuthorityQuarantineDocument().getDocumentUrl(),document1.getDocumentUrl()); + } + }