diff --git a/Jenkinsfile_CNP b/Jenkinsfile_CNP index d5a5a308605..b7c16bf6c94 100644 --- a/Jenkinsfile_CNP +++ b/Jenkinsfile_CNP @@ -43,7 +43,10 @@ def secrets = [ secret('ccd-importer-username', 'CCD_CONFIGURER_IMPORTER_USERNAME'), secret('ccd-importer-password', 'CCD_CONFIGURER_IMPORTER_PASSWORD'), secret('postgres-user', 'POSTGRES_USER'), - secret('postgres-password', 'POSTGRES_PASSWORD') + secret('postgres-password', 'POSTGRES_PASSWORD'), + secret('default-password','DEFAULT_PASSWORD'), + secret('judge-default-password','JUDGE_DEFAULT_PASSWORD'), + secret('iac-default-password','IAC_DEFAULT_PASSWORD') ] ] @@ -141,7 +144,7 @@ withPipeline(type, product, component) { env.CCD_DATA_STORE_URL = "https://civil-service-data-store-staging-aat.service.core-compute-aat.internal" env.DM_STORE_URL = "http://dm-store-aat.service.core-compute-aat.internal" env.CIVIL_SERVICE_URL="https://civil-service-staging.aat.platform.hmcts.net" - env.AAC_API_URL="https://manage-case-assignment-civil-service-staging-aat.service.core-compute-aat.internal" + env.AAC_API_URL="https://civil-service-manage-case-assignment-staging.aat.platform.hmcts.net" } afterAlways('functionalTest:aat') { diff --git a/Jenkinsfile_nightly b/Jenkinsfile_nightly index df67a421b16..4f66e24d074 100644 --- a/Jenkinsfile_nightly +++ b/Jenkinsfile_nightly @@ -14,6 +14,8 @@ properties([ description: 'The URL of service auth provider'), string(name: 'CCD_DATA_STORE_URL', defaultValue: 'http://ccd-data-store-api-aat.service.core-compute-aat.internal', description: 'The URL of ccd data store'), + string(name: 'AAC_API_URL', defaultValue: 'http://aac-manage-case-assignment-aat.service.core-compute-aat.internal', + description: 'The URL of AAC service'), string(name: 'CIVIL_SERVICE_URL', defaultValue: 'http://civil-service-aat.service.core-compute-aat.internal', description: 'The URL of civil service'), string(name: 'WAIT_FOR_TIMEOUT_MS', @@ -42,7 +44,10 @@ static Map secret(String secretName, String envVariable) { def secrets = [ 'civil-${env}': [ - secret('microservicekey-civil-service', 'S2S_SECRET') + secret('microservicekey-civil-service', 'S2S_SECRET'), + secret('default-password', 'DEFAULT_PASSWORD'), + secret('judge-default-password', 'JUDGE_DEFAULT_PASSWORD'), + secret('iac-default-password', 'IAC_DEFAULT_PASSWORD') ] ] @@ -57,6 +62,7 @@ withNightlyPipeline(type, product, component) { env.URL_FOR_SECURITY_SCAN = params.CIVIL_SERVICE_URL env.TESTS_FOR_ACCESSIBILITY = true env.NIGHTLY_RUN = true + env.AAC_API_URL = params.AAC_API_URL overrideVaultEnvironments([ 'aat': params.ENVIRONMENT ]) diff --git a/bin/add-roles.sh b/bin/add-roles.sh index 0022e535dcf..c02dcf797bc 100755 --- a/bin/add-roles.sh +++ b/bin/add-roles.sh @@ -30,6 +30,7 @@ ./bin/utils/ccd-add-role.sh "cui-admin-profile" ./bin/utils/ccd-add-role.sh "cui-nbc-profile" ./bin/utils/ccd-add-role.sh "citizen-profile" +./bin/utils/ccd-add-role.sh "caseworker-civil-citizen-ui-pcqextractor" roles=("solicitor" "systemupdate" "admin" "staff") for role in "${roles[@]}" diff --git a/build.gradle b/build.gradle index 8dff4a80948..7035befae45 100644 --- a/build.gradle +++ b/build.gradle @@ -75,8 +75,8 @@ allprojects { dependencyManagement { dependencies { - //CVE-2022-41881 - dependencySet(group: 'io.netty', version: '4.1.94.Final') { + //CVE-2023-44487 + dependencySet(group: 'io.netty', version: '4.1.100.Final') { entry 'netty-handler' entry 'netty-handler-proxy' entry 'netty-transport-native-epoll' @@ -369,7 +369,7 @@ configurations.all { } dependencies { - implementation 'com.github.hmcts:civil-commons:1.0.21' + implementation 'com.github.hmcts:civil-commons:1.0.33' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-actuator' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-aop' @@ -401,11 +401,18 @@ dependencies { implementation group: 'io.github.openfeign', name: 'feign-httpclient', version: '12.4' implementation group: 'org.springframework.retry', name: 'spring-retry' + implementation group: 'com.github.hmcts', name: 'java-logging', version: '6.0.1' + implementation group: 'com.github.hmcts', name: 'ccd-client', version: '4.9.1' implementation group: 'uk.gov.hmcts.reform', name: 'document-management-client', version: '7.0.0' implementation group: 'uk.gov.hmcts.reform', name: 'send-letter-client', version: '3.0.3' - implementation group: 'com.github.hmcts', name: 'fees-java-client', version: '0.0.6' - implementation group: 'com.github.hmcts', name: 'payments-java-client', version: '1.5.2' + implementation('com.github.hmcts:fees-java-client:0.0.6') { + exclude group: 'java-logging', module: ' java-logging' + } + + implementation('com.github.hmcts:payments-java-client:1.5.2') { + exclude group: 'java-logging', module: ' java-logging' + } implementation group: 'uk.gov.hmcts.reform', name: 'service-auth-provider-client', version: '4.0.0' implementation group: 'uk.gov.hmcts.reform', name: 'properties-volume-spring-boot-starter', version: '0.1.0' implementation group: 'uk.gov.service.notify', name: 'notifications-java-client', version: '4.1.0-RELEASE' @@ -433,8 +440,8 @@ dependencies { implementation group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.20.0' implementation group: 'org.apache.logging.log4j', name: 'log4j-to-slf4j', version: '2.20.0' implementation group: 'org.apache.commons', name: 'commons-text', version: '1.10.0' - implementation group: 'org.apache.tomcat.embed', name: 'tomcat-embed-core', version: '9.0.80' - implementation group: 'org.apache.tomcat.embed', name: 'tomcat-embed-websocket', version: '10.1.13' + implementation group: 'org.apache.tomcat.embed', name: 'tomcat-embed-core', version: '9.0.82' + implementation group: 'org.apache.tomcat.embed', name: 'tomcat-embed-websocket', version: '10.1.14' implementation group: 'org.elasticsearch', name: 'elasticsearch', version: '7.17.9' implementation group: 'com.networknt', name: 'json-schema-validator', version: '1.0.78' diff --git a/charts/civil-service/Chart.yaml b/charts/civil-service/Chart.yaml index 211625fdec0..dbf0c702042 100644 --- a/charts/civil-service/Chart.yaml +++ b/charts/civil-service/Chart.yaml @@ -2,13 +2,13 @@ apiVersion: v2 description: A Helm chart for civil-service App name: civil-service home: https://github.com/hmcts/civil-service -version: 0.0.48 +version: 0.0.52 maintainers: - name: HMCTS Civil team dependencies: - name: java - version: 4.0.13 + version: 5.0.0 repository: 'https://hmctspublic.azurecr.io/helm/v1/repo/' - name: ccd version: 8.0.29 diff --git a/charts/civil-service/values.aat.template.yaml b/charts/civil-service/values.aat.template.yaml index cbb0fb6ab4d..a9ec5ff1c97 100644 --- a/charts/civil-service/values.aat.template.yaml +++ b/charts/civil-service/values.aat.template.yaml @@ -24,6 +24,9 @@ java: - ordnance-survey-api-key - notification-caseworker-spec-receiver - launch-darkly-sdk-key + - default-password + - judge-default-password + - iac-default-password environment: CORE_CASE_DATA_API_URL: http://${SERVICE_NAME}-ccd-data-store-api OIDC_ISSUER: https://forgerock-am.service.core-compute-idam-aat2.internal:8443/openam/oauth2/realms/root/realms/hmcts @@ -42,6 +45,7 @@ java: DOCUMENT_MANAGEMENT_SECURED: true STITCHING_API_ENABLED: true RELEASE_REVISION: "{{ .Release.Revision }}" + ACA_SERVICE_API_BASEURL: http://${SERVICE_NAME}-aac-manage-case-assignment HMC_HEARINGS_SUBSCRIPTION_ENABLED: false postgresql: enabled: true @@ -212,7 +216,7 @@ aac-manage-case-assignment: imagePullPolicy: Always releaseNameOverride: ${SERVICE_NAME}-aac-manage-case-assignment image: hmctspublic.azurecr.io/aac/manage-case-assignment:latest - ingressHost: manage-case-assignment-civil-service-staging-aat.service.core-compute-aat.internal + ingressHost: civil-service-manage-case-assignment-staging.aat.platform.hmcts.net environment: IDAM_API_URL: https://idam-api.aat.platform.hmcts.net IDAM_OIDC_URL: https://idam-web-public.aat.platform.hmcts.net diff --git a/charts/civil-service/values.preview.template.yaml b/charts/civil-service/values.preview.template.yaml index cd8fd8b926f..bcc5e2468fb 100644 --- a/charts/civil-service/values.preview.template.yaml +++ b/charts/civil-service/values.preview.template.yaml @@ -25,6 +25,9 @@ java: - robotics-notification-multipartyrecipient - ordnance-survey-api-key - notification-caseworker-spec-receiver + - default-password + - judge-default-password + - iac-default-password environment: CORE_CASE_DATA_API_URL: http://${SERVICE_NAME}-ccd-data-store-api OIDC_ISSUER: https://forgerock-am.service.core-compute-idam-aat2.internal:8443/openam/oauth2/realms/root/realms/hmcts @@ -49,6 +52,8 @@ java: postgresql: enabled: true image: + registry: hmctspublic.azurecr.io + repository: imported/bitnami/postgresql tag: '11.6.0' primary: persistence: diff --git a/charts/civil-service/values.yaml b/charts/civil-service/values.yaml index ff91603a2fb..54a997ceadd 100644 --- a/charts/civil-service/values.yaml +++ b/charts/civil-service/values.yaml @@ -64,6 +64,7 @@ java: DOCUMENT_MANAGEMENT_SECURED: true REST_TEMPLATE_TIMEOUT: 30000 POLLING_EVENT_EMITTER_ENABLED: false + WA_TOGGLE: Prod HMC_HEARINGS_TOPIC_NAMESPACE: 'hmc-servicebus-{{ .Values.global.environment }}' HMC_HEARINGS_TOPIC_NAME: 'hmc-to-cft-{{ .Values.global.environment }}' HMC_HEARINGS_TOPIC_SUBSCRIPTION_NAME: 'hmc-to-civil-subscription-{{ .Values.global.environment }}' diff --git a/config/owasp/suppressions.xml b/config/owasp/suppressions.xml index a6482e093b1..8effe28d3c5 100644 --- a/config/owasp/suppressions.xml +++ b/config/owasp/suppressions.xml @@ -9,6 +9,7 @@ False positive. We don't have any reference to json-java_project:json-java nor any reference to hutool:hutool:5.8.10. Suppressed long-term to re-assess and possibly delete. CVE-2022-45688 + CVE-2023-5072 Temporarily suppressing it as the latest camunda connector 1.5.6 seem to have the vulnerability. @@ -30,7 +31,9 @@ CVE-2021-42306 CVE-2023-20861 CVE-2023-20883 - + CVE-2023-4586 + CVE-2023-5072 + CVE-2023-44487 diff --git a/docker/docmosis/templates/CV-SPC-CLM-ENG-01065-LIP.docx b/docker/docmosis/templates/CV-SPC-CLM-ENG-01065-LIP.docx new file mode 100644 index 00000000000..74d50312e95 Binary files /dev/null and b/docker/docmosis/templates/CV-SPC-CLM-ENG-01065-LIP.docx differ diff --git a/docker/docmosis/templates/CV-SPC-HRN-ENG-01362.docx b/docker/docmosis/templates/CV-SPC-HRN-ENG-01362.docx new file mode 100644 index 00000000000..b825b4efff4 Binary files /dev/null and b/docker/docmosis/templates/CV-SPC-HRN-ENG-01362.docx differ diff --git a/docker/docmosis/templates/CV-SPC-HRN-ENG-LIP-01283.docx b/docker/docmosis/templates/CV-SPC-HRN-ENG-LIP-01283.docx new file mode 100644 index 00000000000..d01a18bcf8a Binary files /dev/null and b/docker/docmosis/templates/CV-SPC-HRN-ENG-LIP-01283.docx differ diff --git a/docker/docmosis/templates/CV-UNS-DEC-ENG-01099.docx b/docker/docmosis/templates/CV-UNS-DEC-ENG-01099.docx index 6dabc929f07..495e2390a8e 100644 Binary files a/docker/docmosis/templates/CV-UNS-DEC-ENG-01099.docx and b/docker/docmosis/templates/CV-UNS-DEC-ENG-01099.docx differ diff --git a/docker/docmosis/templates/CV-UNS-DEC-ENG-01283.docx b/docker/docmosis/templates/CV-UNS-DEC-ENG-01283.docx index 5d303173c98..25eb2cf65c3 100644 Binary files a/docker/docmosis/templates/CV-UNS-DEC-ENG-01283.docx and b/docker/docmosis/templates/CV-UNS-DEC-ENG-01283.docx differ diff --git a/docker/docmosis/templates/CV-UNS-DEC-ENG-01323.docx b/docker/docmosis/templates/CV-UNS-DEC-ENG-01323.docx deleted file mode 100644 index 0f348ae789b..00000000000 Binary files a/docker/docmosis/templates/CV-UNS-DEC-ENG-01323.docx and /dev/null differ diff --git a/docker/docmosis/templates/CV-UNS-DEC-ENG-01329.docx b/docker/docmosis/templates/CV-UNS-DEC-ENG-01329.docx new file mode 100644 index 00000000000..f0c707b7449 Binary files /dev/null and b/docker/docmosis/templates/CV-UNS-DEC-ENG-01329.docx differ diff --git a/docker/docmosis/templates/CV-UNS-DEC-ENG-01322.docx b/docker/docmosis/templates/CV-UNS-DEC-ENG-01376.docx similarity index 54% rename from docker/docmosis/templates/CV-UNS-DEC-ENG-01322.docx rename to docker/docmosis/templates/CV-UNS-DEC-ENG-01376.docx index e372a907373..b4696ff615f 100644 Binary files a/docker/docmosis/templates/CV-UNS-DEC-ENG-01322.docx and b/docker/docmosis/templates/CV-UNS-DEC-ENG-01376.docx differ diff --git a/docker/docmosis/templates/CV-UNS-GAP-ENG-01067.docx b/docker/docmosis/templates/CV-UNS-GAP-ENG-01067.docx index 40b1316205a..bf518dcc5e4 100644 Binary files a/docker/docmosis/templates/CV-UNS-GAP-ENG-01067.docx and b/docker/docmosis/templates/CV-UNS-GAP-ENG-01067.docx differ diff --git a/docker/docmosis/templates/CV-UNS-GAP-ENG-01068.docx b/docker/docmosis/templates/CV-UNS-GAP-ENG-01068.docx index d715ec57053..07e3a3b1e8c 100644 Binary files a/docker/docmosis/templates/CV-UNS-GAP-ENG-01068.docx and b/docker/docmosis/templates/CV-UNS-GAP-ENG-01068.docx differ diff --git a/docker/docmosis/templates/CV-UNS-GAP-ENG-01069.docx b/docker/docmosis/templates/CV-UNS-GAP-ENG-01069.docx index 7178c49ce47..8a359232e14 100644 Binary files a/docker/docmosis/templates/CV-UNS-GAP-ENG-01069.docx and b/docker/docmosis/templates/CV-UNS-GAP-ENG-01069.docx differ diff --git a/docker/docmosis/templates/CV-UNS-GAP-ENG-01070.docx b/docker/docmosis/templates/CV-UNS-GAP-ENG-01070.docx index f2a28ab1f0b..3e9445b398d 100644 Binary files a/docker/docmosis/templates/CV-UNS-GAP-ENG-01070.docx and b/docker/docmosis/templates/CV-UNS-GAP-ENG-01070.docx differ diff --git a/docker/docmosis/templates/CV-UNS-GAP-ENG-01071.docx b/docker/docmosis/templates/CV-UNS-GAP-ENG-01071.docx index 1d62230dd42..57e6930dbe3 100644 Binary files a/docker/docmosis/templates/CV-UNS-GAP-ENG-01071.docx and b/docker/docmosis/templates/CV-UNS-GAP-ENG-01071.docx differ diff --git a/docker/docmosis/templates/CV-UNS-GAP-ENG-01072.docx b/docker/docmosis/templates/CV-UNS-GAP-ENG-01072.docx index ea860531487..d8f67ebaeec 100644 Binary files a/docker/docmosis/templates/CV-UNS-GAP-ENG-01072.docx and b/docker/docmosis/templates/CV-UNS-GAP-ENG-01072.docx differ diff --git a/docker/docmosis/templates/CV-UNS-GAP-ENG-01073.docx b/docker/docmosis/templates/CV-UNS-GAP-ENG-01073.docx index 7c1e209c543..75da4c61c2c 100644 Binary files a/docker/docmosis/templates/CV-UNS-GAP-ENG-01073.docx and b/docker/docmosis/templates/CV-UNS-GAP-ENG-01073.docx differ diff --git a/docker/docmosis/templates/CV-UNS-GAP-ENG-01074.docx b/docker/docmosis/templates/CV-UNS-GAP-ENG-01074.docx index 103eb0221db..d0ee5a8ec54 100644 Binary files a/docker/docmosis/templates/CV-UNS-GAP-ENG-01074.docx and b/docker/docmosis/templates/CV-UNS-GAP-ENG-01074.docx differ diff --git a/docker/docmosis/templates/CV-UNS-GAP-ENG-01075.docx b/docker/docmosis/templates/CV-UNS-GAP-ENG-01075.docx index c3c550658b0..6cd12684e8a 100644 Binary files a/docker/docmosis/templates/CV-UNS-GAP-ENG-01075.docx and b/docker/docmosis/templates/CV-UNS-GAP-ENG-01075.docx differ diff --git a/docker/docmosis/templates/CV-UNS-GAP-ENG-01076.docx b/docker/docmosis/templates/CV-UNS-GAP-ENG-01076.docx index 3eb45c9cadb..8c4163027d4 100644 Binary files a/docker/docmosis/templates/CV-UNS-GAP-ENG-01076.docx and b/docker/docmosis/templates/CV-UNS-GAP-ENG-01076.docx differ diff --git a/docker/docmosis/templates/CV-UNS-GAP-ENG-01077.docx b/docker/docmosis/templates/CV-UNS-GAP-ENG-01077.docx index 5ea73c5f3b1..d042f3bedbe 100644 Binary files a/docker/docmosis/templates/CV-UNS-GAP-ENG-01077.docx and b/docker/docmosis/templates/CV-UNS-GAP-ENG-01077.docx differ diff --git a/docker/docmosis/templates/CV-UNS-GAP-ENG-01078.docx b/docker/docmosis/templates/CV-UNS-GAP-ENG-01078.docx index 8b1a1541fc9..40d0ed38627 100644 Binary files a/docker/docmosis/templates/CV-UNS-GAP-ENG-01078.docx and b/docker/docmosis/templates/CV-UNS-GAP-ENG-01078.docx differ diff --git a/docker/docmosis/templates/CV-UNS-HNO-ENG-01196.docx b/docker/docmosis/templates/CV-UNS-HNO-ENG-01196.docx index 4ba5177d719..5653fd8cecd 100644 Binary files a/docker/docmosis/templates/CV-UNS-HNO-ENG-01196.docx and b/docker/docmosis/templates/CV-UNS-HNO-ENG-01196.docx differ diff --git a/docker/docmosis/templates/CV-UNS-HNO-ENG-01197.docx b/docker/docmosis/templates/CV-UNS-HNO-ENG-01197.docx index 12ca8fd309d..0199cf37ecc 100644 Binary files a/docker/docmosis/templates/CV-UNS-HNO-ENG-01197.docx and b/docker/docmosis/templates/CV-UNS-HNO-ENG-01197.docx differ diff --git a/docker/docmosis/templates/CV-UNS-HNO-ENG-01198.docx b/docker/docmosis/templates/CV-UNS-HNO-ENG-01198.docx index 5c95cf2cc0d..c04509eb39b 100644 Binary files a/docker/docmosis/templates/CV-UNS-HNO-ENG-01198.docx and b/docker/docmosis/templates/CV-UNS-HNO-ENG-01198.docx differ diff --git a/docker/docmosis/templates/CV-UNS-HNO-ENG-01199.docx b/docker/docmosis/templates/CV-UNS-HNO-ENG-01199.docx index 6f544923fe7..c09c508bf8c 100644 Binary files a/docker/docmosis/templates/CV-UNS-HNO-ENG-01199.docx and b/docker/docmosis/templates/CV-UNS-HNO-ENG-01199.docx differ diff --git a/docker/docmosis/templates/CV-UNS-HRN-ENG-01247-10180.docx b/docker/docmosis/templates/CV-UNS-HRN-ENG-01247-10180.docx new file mode 100644 index 00000000000..ddd7238dc38 Binary files /dev/null and b/docker/docmosis/templates/CV-UNS-HRN-ENG-01247-10180.docx differ diff --git a/docker/docmosis/templates/CV-UNS-HRN-ENG-01343.docx b/docker/docmosis/templates/CV-UNS-HRN-ENG-01343.docx index 9c1ef57554a..764c8978843 100644 Binary files a/docker/docmosis/templates/CV-UNS-HRN-ENG-01343.docx and b/docker/docmosis/templates/CV-UNS-HRN-ENG-01343.docx differ diff --git a/docker/docmosis/templates/CV-UNS-STD-ENG-01305.docx b/docker/docmosis/templates/CV-UNS-STD-ENG-01305.docx deleted file mode 100644 index 5b9f9a8e208..00000000000 Binary files a/docker/docmosis/templates/CV-UNS-STD-ENG-01305.docx and /dev/null differ diff --git a/docker/docmosis/templates/CV-UNS-STD-ENG-01308.docx b/docker/docmosis/templates/CV-UNS-STD-ENG-01308.docx deleted file mode 100644 index 30558f74753..00000000000 Binary files a/docker/docmosis/templates/CV-UNS-STD-ENG-01308.docx and /dev/null differ diff --git a/docker/docmosis/templates/CV-UNS-STD-ENG-01324.docx b/docker/docmosis/templates/CV-UNS-STD-ENG-01324.docx deleted file mode 100644 index 3223146dcd6..00000000000 Binary files a/docker/docmosis/templates/CV-UNS-STD-ENG-01324.docx and /dev/null differ diff --git a/docker/docmosis/templates/CV-UNS-STD-ENG-01325.docx b/docker/docmosis/templates/CV-UNS-STD-ENG-01325.docx deleted file mode 100644 index 58f8ae436f8..00000000000 Binary files a/docker/docmosis/templates/CV-UNS-STD-ENG-01325.docx and /dev/null differ diff --git a/docker/docmosis/templates/CV-UNS-STD-ENG-01326.docx b/docker/docmosis/templates/CV-UNS-STD-ENG-01326.docx deleted file mode 100644 index 182c66aa1d3..00000000000 Binary files a/docker/docmosis/templates/CV-UNS-STD-ENG-01326.docx and /dev/null differ diff --git a/docker/docmosis/templates/CV-UNS-STD-ENG-01377.docx b/docker/docmosis/templates/CV-UNS-STD-ENG-01377.docx new file mode 100644 index 00000000000..1f2a4fa3a0e Binary files /dev/null and b/docker/docmosis/templates/CV-UNS-STD-ENG-01377.docx differ diff --git a/docker/docmosis/templates/CV-UNS-STD-ENG-01378.docx b/docker/docmosis/templates/CV-UNS-STD-ENG-01378.docx new file mode 100644 index 00000000000..7fd14c6e545 Binary files /dev/null and b/docker/docmosis/templates/CV-UNS-STD-ENG-01378.docx differ diff --git a/docker/docmosis/templates/CV-UNS-STD-ENG-01380.docx b/docker/docmosis/templates/CV-UNS-STD-ENG-01380.docx new file mode 100644 index 00000000000..edadb96d535 Binary files /dev/null and b/docker/docmosis/templates/CV-UNS-STD-ENG-01380.docx differ diff --git a/docker/docmosis/templates/CV-UNS-STD-ENG-01381.docx b/docker/docmosis/templates/CV-UNS-STD-ENG-01381.docx new file mode 100644 index 00000000000..47f36303d60 Binary files /dev/null and b/docker/docmosis/templates/CV-UNS-STD-ENG-01381.docx differ diff --git a/docker/docmosis/templates/CV-UNS-STD-ENG-01382.docx b/docker/docmosis/templates/CV-UNS-STD-ENG-01382.docx new file mode 100644 index 00000000000..04d6afcfac7 Binary files /dev/null and b/docker/docmosis/templates/CV-UNS-STD-ENG-01382.docx differ diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/civil/controllers/cases/CasesControllerTest.java b/src/integrationTest/java/uk/gov/hmcts/reform/civil/controllers/cases/CasesControllerTest.java index 5e951ab7ef7..627fda38600 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/civil/controllers/cases/CasesControllerTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/civil/controllers/cases/CasesControllerTest.java @@ -12,18 +12,19 @@ import uk.gov.hmcts.reform.civil.exceptions.CaseDataInvalidException; import uk.gov.hmcts.reform.civil.exceptions.CaseNotFoundException; import uk.gov.hmcts.reform.civil.exceptions.UserNotFoundOnCaseException; -import uk.gov.hmcts.reform.civil.exceptions.CaseNotFoundException; -import uk.gov.hmcts.reform.civil.exceptions.UserNotFoundOnCaseException; import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.bulkclaims.CaseworkerSubmitEventDTo; import uk.gov.hmcts.reform.civil.model.citizenui.DashboardClaimInfo; import uk.gov.hmcts.reform.civil.model.citizenui.DashboardResponse; +import uk.gov.hmcts.reform.civil.model.citizenui.dto.ExtendedDeadlineDto; import uk.gov.hmcts.reform.civil.model.citizenui.dto.EventDto; +import uk.gov.hmcts.reform.civil.model.repaymentplan.ClaimantProposedPlan; import uk.gov.hmcts.reform.civil.service.CoreCaseDataService; import uk.gov.hmcts.reform.civil.service.RoleAssignmentsService; import uk.gov.hmcts.reform.civil.service.bulkclaims.CaseworkerCaseEventService; import uk.gov.hmcts.reform.civil.service.citizen.events.CaseEventService; +import uk.gov.hmcts.reform.civil.service.citizen.repaymentplan.RepaymentPlanDecisionService; import uk.gov.hmcts.reform.civil.service.citizenui.DashboardClaimInfoService; import uk.gov.hmcts.reform.civil.service.citizenui.responsedeadline.DeadlineExtensionCalculatorService; import uk.gov.hmcts.reform.civil.ras.model.RoleAssignmentResponse; @@ -40,11 +41,15 @@ import java.util.Map; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec.IMMEDIATELY; +import static uk.gov.hmcts.reform.civil.model.citizenui.dto.RepaymentDecisionType.IN_FAVOUR_OF_CLAIMANT; public class CasesControllerTest extends BaseIntegrationTest { @@ -68,6 +73,7 @@ public class CasesControllerTest extends BaseIntegrationTest { private static final String CALCULATE_DEADLINE_URL = "/cases/response/deadline"; private static final String AGREED_RESPONSE_DEADLINE_DATE_URL = "/cases/response/agreeddeadline/{claimId}"; private static final String USER_CASE_ROLES = "/cases/{caseId}/userCaseRoles"; + private static final String COURT_DECISION_URL = "/cases/{caseId}/courtDecision"; private static final List claimResults = Collections.singletonList(DashboardClaimInfo.builder() .claimAmount(new BigDecimal( @@ -117,6 +123,9 @@ public class CasesControllerTest extends BaseIntegrationTest { @MockBean private UserInformationService userInformationService; + @MockBean + private RepaymentPlanDecisionService repaymentPlanDecisionService; + @Test @SneakyThrows public void shouldReturnHttp200() { @@ -219,10 +228,10 @@ void shouldSubmitEventSuccessfully() { @SneakyThrows void shouldCalculateDeadlineSuccessfully() { LocalDate extensionDate = LocalDate.of(2022, 6, 6); - when(deadlineExtensionCalculatorService.calculateExtendedDeadline(any())).thenReturn(extensionDate); + when(deadlineExtensionCalculatorService.calculateExtendedDeadline(any(), anyInt())).thenReturn(extensionDate); doPost( BEARER_TOKEN, - extensionDate, + ExtendedDeadlineDto.builder().responseDate(extensionDate).plusDays(5).build(), CALCULATE_DEADLINE_URL ) .andExpect(content().json(toJson(extensionDate))) @@ -410,4 +419,14 @@ void shouldThrowUserNotFoundOnCaseExceptionWhenRolesIsEmpty() { } + @Test + @SneakyThrows + void shouldReturnDecisionMadeForTheClaimantRepaymentPlan() { + //Given + given(repaymentPlanDecisionService.getCalculatedDecision(any(), any())).willReturn(IN_FAVOUR_OF_CLAIMANT); + //When + doPost(BEARER_TOKEN, ClaimantProposedPlan.builder().proposedRepaymentType(IMMEDIATELY).build(), COURT_DECISION_URL, "1") + .andExpect(status().isOk()); + } + } diff --git a/src/integrationTest/java/uk/gov/hmcts/reform/civil/controllers/cases/HearingValuesControllerTest.java b/src/integrationTest/java/uk/gov/hmcts/reform/civil/controllers/cases/HearingValuesControllerTest.java index 3b7051d357b..3b993d3ecdb 100644 --- a/src/integrationTest/java/uk/gov/hmcts/reform/civil/controllers/cases/HearingValuesControllerTest.java +++ b/src/integrationTest/java/uk/gov/hmcts/reform/civil/controllers/cases/HearingValuesControllerTest.java @@ -4,7 +4,7 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import uk.gov.hmcts.reform.civil.controllers.BaseIntegrationTest; -import uk.gov.hmcts.reform.civil.exceptions.PartyIdsUpdatedException; +import uk.gov.hmcts.reform.civil.exceptions.MissingFieldsUpdatedException; import uk.gov.hmcts.reform.civil.model.HearingValuesRequest; import uk.gov.hmcts.reform.civil.exceptions.CaseNotFoundException; import uk.gov.hmcts.reform.civil.model.hearingvalues.ServiceHearingValuesModel; @@ -55,7 +55,7 @@ public void shouldReturnHttp400_whenCaseNotFoundExceptionThrown() { @SneakyThrows public void shouldReturnHttp404_whenPartyIdsUpdatedExceptionThrown() { when(hearingValuesService.getValues(anyLong(), anyString(), anyString())) - .thenThrow(PartyIdsUpdatedException.class); + .thenThrow(MissingFieldsUpdatedException.class); HearingValuesRequest requestBody = HearingValuesRequest.builder().caseReference(1L).hearingId("hearingid").build(); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/advice/ControllerExceptionHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/advice/ControllerExceptionHandler.java index 398d3e4c2e7..863716d2741 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/advice/ControllerExceptionHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/advice/ControllerExceptionHandler.java @@ -11,7 +11,7 @@ import uk.gov.hmcts.reform.civil.documentmanagement.DocumentUploadException; import uk.gov.hmcts.reform.civil.exceptions.CaseDataInvalidException; import uk.gov.hmcts.reform.civil.exceptions.CaseNotFoundException; -import uk.gov.hmcts.reform.civil.exceptions.PartyIdsUpdatedException; +import uk.gov.hmcts.reform.civil.exceptions.MissingFieldsUpdatedException; import uk.gov.hmcts.reform.civil.exceptions.UserNotFoundOnCaseException; import uk.gov.hmcts.reform.civil.service.pininpost.exception.PinNotMatchException; import uk.gov.hmcts.reform.civil.service.search.exceptions.SearchServiceCaseNotFoundException; @@ -50,10 +50,10 @@ public ResponseEntity documentUploadException(MaxUploadSizeExceededExcep return new ResponseEntity<>("Document upload unsuccessful", new HttpHeaders(), HttpStatus.BAD_REQUEST); } - @ExceptionHandler(PartyIdsUpdatedException.class) - public ResponseEntity partyIdsUpdatedException(PartyIdsUpdatedException partyIdsUpdatedException) { - log.error(partyIdsUpdatedException.getMessage()); - return new ResponseEntity<>("Party IDs updated", new HttpHeaders(), HttpStatus.NOT_FOUND); + @ExceptionHandler(MissingFieldsUpdatedException.class) + public ResponseEntity partyIdsUpdatedException(MissingFieldsUpdatedException missingFieldsUpdatedException) { + log.error(missingFieldsUpdatedException.getMessage()); + return new ResponseEntity<>("Missing fields updated", new HttpHeaders(), HttpStatus.NOT_FOUND); } @ExceptionHandler(CaseDataInvalidException.class) diff --git a/src/main/java/uk/gov/hmcts/reform/civil/advice/ResourceExceptionHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/advice/ResourceExceptionHandler.java index c4b12beb99d..0cedd50c432 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/advice/ResourceExceptionHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/advice/ResourceExceptionHandler.java @@ -2,6 +2,7 @@ import feign.FeignException; import lombok.extern.slf4j.Slf4j; +import org.apache.catalina.connector.ClientAbortException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -29,6 +30,14 @@ public ResponseEntity notFound(Exception exception) { return new ResponseEntity<>(exception.getMessage(), new HttpHeaders(), HttpStatus.NOT_FOUND); } + @ExceptionHandler({ClientAbortException.class}) + public ResponseEntity handleClientAbortException(Exception exception) { + log.debug(exception.getMessage(), exception); + return new ResponseEntity<>(exception.getMessage(), + new HttpHeaders(), HttpStatus.REQUEST_TIMEOUT + ); + } + @ExceptionHandler({ StateFlowException.class, IllegalArgumentException.class diff --git a/src/main/java/uk/gov/hmcts/reform/civil/callback/CaseEvent.java b/src/main/java/uk/gov/hmcts/reform/civil/callback/CaseEvent.java index de58acc4972..408de72f8a2 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/callback/CaseEvent.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/callback/CaseEvent.java @@ -19,6 +19,7 @@ public enum CaseEvent { ENTER_BREATHING_SPACE_LIP(USER), ENTER_BREATHING_SPACE_SPEC(USER), LIFT_BREATHING_SPACE_SPEC(USER), + LIFT_BREATHING_SPACE_LIP(USER), NOTIFY_DEFENDANT_OF_CLAIM(USER), NOTIFY_DEFENDANT_OF_CLAIM_DETAILS(USER), ADD_OR_AMEND_CLAIM_DOCUMENTS(USER), @@ -77,6 +78,7 @@ public enum CaseEvent { EVIDENCE_UPLOAD_RESPONDENT(USER), EVIDENCE_UPLOAD_CHECK(USER), CREATE_BUNDLE(USER), + asyncStitchingComplete(USER), EXTEND_RESPONSE_DEADLINE(USER), ADD_UNAVAILABLE_DATES(USER), @@ -91,11 +93,16 @@ public enum CaseEvent { GENERATE_TRIAL_READY_DOCUMENT_APPLICANT(USER), GENERATE_TRIAL_READY_DOCUMENT_RESPONDENT1(USER), GENERATE_TRIAL_READY_DOCUMENT_RESPONDENT2(USER), + LIP_CLAIM_SETTLED(USER), NOTIFY_FORMER_SOLICITOR(CAMUNDA), NOTIFY_OTHER_SOLICITOR_1(CAMUNDA), NOTIFY_OTHER_SOLICITOR_2(CAMUNDA), TRIAL_READINESS(USER), BUNDLE_CREATION_NOTIFICATION(USER), + RECORD_JUDGMENT(USER), + SET_ASIDE_JUDGMENT(USER), + JUDGMENT_PAID_IN_FULL(USER), + TRANSFER_ONLINE_CASE(USER), ASSIGN_CASE_TO_APPLICANT_SOLICITOR1(CAMUNDA), ASSIGN_CASE_TO_APPLICANT1(CAMUNDA), TRIGGER_APPLICATION_CLOSURE(CAMUNDA), @@ -106,7 +113,11 @@ public enum CaseEvent { NOTIFY_RESPONDENT_SOLICITOR1_BREATHING_SPACE_ENTER(CAMUNDA), NOTIFY_RESPONDENT_SOLICITOR2_BREATHING_SPACE_ENTER(CAMUNDA), NOTIFY_APPLICANT_SOLICITOR1_BREATHING_SPACE_LIFTED(CAMUNDA), + NOTIFY_LIP_APPLICANT1_BREATHING_SPACE_ENTER(CAMUNDA), + NOTIFY_LIP_RESPONDENT_BREATHING_SPACE_ENTER(CAMUNDA), NOTIFY_RESPONDENT_SOLICITOR1_BREATHING_SPACE_LIFTED(CAMUNDA), + NOTIFY_LIP_APPLICANT_BREATHING_SPACE_LIFTED(CAMUNDA), + NOTIFY_LIP_RESPONDENT_BREATHING_SPACE_LIFTED(CAMUNDA), NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIM_ISSUE(CAMUNDA), NOTIFY_RESPONDENT_SOLICITOR2_FOR_CLAIM_ISSUE(CAMUNDA), NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIM_ISSUE_CC(CAMUNDA), @@ -269,7 +280,7 @@ public enum CaseEvent { NOTIFY_CYA_ON_AGREED_MEDIATION(CAMUNDA), SEND_SDO_ORDER_TO_LIP_DEFENDANT(CAMUNDA), - UPDATE_PARTY_IDS(CAMUNDA), + UPDATE_MISSING_FIELDS(CAMUNDA), START_HEARING_NOTICE_BUSINESS_PROCESS(CAMUNDA), END_HEARING_NOTICE_BUSINESS_PROCESS(CAMUNDA), @@ -281,7 +292,12 @@ public enum CaseEvent { CREATE_SERVICE_REQUEST_API_HMC(CAMUNDA), UPDATE_PARTIES_NOTIFIED_HMC(CAMUNDA), UPDATE_CASE_PROGRESS_HMC(CAMUNDA), - SEND_CVP_JOIN_LINK(USER); + NOTIFY_APPLICANT1_CLAIM_SUBMITTED(CAMUNDA), + NOTIFY_DEFENDANT_CLAIMANT_SETTLE_THE_CLAIM(CAMUNDA), + SEND_CVP_JOIN_LINK(USER), + SET_LIP_RESPONDENT_RESPONSE_DEADLINE(CAMUNDA), + NOTIFY_LIP_RESPONDENT_CLAIMANT_CONFIRM_TO_PROCEED(CAMUNDA), + NOTIFY_LIP_APPLICANT_CLAIMANT_CONFIRM_TO_PROCEED(CAMUNDA); private final UserType userType; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/config/ToggleConfiguration.java b/src/main/java/uk/gov/hmcts/reform/civil/config/ToggleConfiguration.java new file mode 100644 index 00000000000..3ecfc0d2a78 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/config/ToggleConfiguration.java @@ -0,0 +1,17 @@ +package uk.gov.hmcts.reform.civil.config; + +import lombok.Data; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; + +@Data +@Configuration +public class ToggleConfiguration { + + private final String featureToggle; + + public ToggleConfiguration( + @Value("${wa.feature-toggle}") String featureToggle) { + this.featureToggle = featureToggle; + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/controllers/cases/CasesController.java b/src/main/java/uk/gov/hmcts/reform/civil/controllers/cases/CasesController.java index 7cfc34a5e57..b83ea9be12c 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/controllers/cases/CasesController.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/controllers/cases/CasesController.java @@ -24,7 +24,10 @@ import uk.gov.hmcts.reform.civil.exceptions.CaseDataInvalidException; import uk.gov.hmcts.reform.civil.model.bulkclaims.CaseworkerSubmitEventDTo; import uk.gov.hmcts.reform.civil.model.citizenui.DashboardResponse; +import uk.gov.hmcts.reform.civil.model.citizenui.dto.ExtendedDeadlineDto; import uk.gov.hmcts.reform.civil.model.citizenui.dto.EventDto; +import uk.gov.hmcts.reform.civil.model.citizenui.dto.RepaymentDecisionType; +import uk.gov.hmcts.reform.civil.model.repaymentplan.ClaimantProposedPlan; import uk.gov.hmcts.reform.civil.model.search.Query; import uk.gov.hmcts.reform.civil.ras.model.RoleAssignmentServiceResponse; import uk.gov.hmcts.reform.civil.service.CoreCaseDataService; @@ -34,6 +37,7 @@ import uk.gov.hmcts.reform.civil.service.bulkclaims.CaseworkerEventSubmissionParams; import uk.gov.hmcts.reform.civil.service.citizen.events.CaseEventService; import uk.gov.hmcts.reform.civil.service.citizen.events.EventSubmissionParams; +import uk.gov.hmcts.reform.civil.service.citizen.repaymentplan.RepaymentPlanDecisionService; import uk.gov.hmcts.reform.civil.service.citizenui.DashboardClaimInfoService; import uk.gov.hmcts.reform.civil.service.citizenui.responsedeadline.DeadlineExtensionCalculatorService; import uk.gov.hmcts.reform.civil.service.search.CaseSdtRequestSearchService; @@ -65,6 +69,7 @@ public class CasesController { private final DeadlineExtensionCalculatorService deadlineExtensionCalculatorService; private final PostcodeValidator postcodeValidator; private final UserInformationService userInformationService; + private final RepaymentPlanDecisionService repaymentPlanDecisionService; @GetMapping(path = { "/{caseId}", @@ -170,8 +175,9 @@ public ResponseEntity submitEvent( @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "401", description = "Not Authorized")}) - public ResponseEntity calculateNewResponseDeadline(@RequestBody LocalDate extendedDeadline) { - LocalDate calculatedDeadline = deadlineExtensionCalculatorService.calculateExtendedDeadline(extendedDeadline); + public ResponseEntity calculateNewResponseDeadline(@RequestBody ExtendedDeadlineDto deadlineDateDetails) { + LocalDate calculatedDeadline = deadlineExtensionCalculatorService.calculateExtendedDeadline( + deadlineDateDetails.getResponseDate(), deadlineDateDetails.getPlusDays()); return new ResponseEntity<>(calculatedDeadline, HttpStatus.OK); } @@ -256,4 +262,14 @@ public ResponseEntity> getUserInfo( return ResponseEntity.ok(userInformationService.getUserCaseRoles(caseId, authorization)); } + @PostMapping(path = "/{caseId}/courtDecision") + @Operation(summary = "Calculates decision on proposed claimant repayment") + public RepaymentDecisionType calculateDecisionOnClaimantProposedRepayment( + @PathVariable("caseId") Long caseId, + @RequestHeader(HttpHeaders.AUTHORIZATION) String authorisation, + @RequestBody ClaimantProposedPlan claimantProposedPlan) { + var caseDetails = coreCaseDataService.getCase(caseId, authorisation); + return repaymentPlanDecisionService.getCalculatedDecision(caseDetails, claimantProposedPlan); + } + } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/controllers/cases/DocumentController.java b/src/main/java/uk/gov/hmcts/reform/civil/controllers/cases/DocumentController.java index 01fe756c017..dc6e93169b6 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/controllers/cases/DocumentController.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/controllers/cases/DocumentController.java @@ -64,8 +64,9 @@ public ResponseEntity uploadAnyDocument( @GetMapping(value = "/downloadDocument/{documentId}") public @ResponseBody ResponseEntity downloadDocumentById( + @RequestHeader(HttpHeaders.AUTHORIZATION) String authorisation, @NotNull @PathVariable String documentId) { - DownloadedDocumentResponse documentResponse = claimFormService.downloadDocumentById(documentId); + DownloadedDocumentResponse documentResponse = claimFormService.downloadDocumentById(authorisation, documentId); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.valueOf(documentResponse.mimeType())); headers.set("original-file-name", documentResponse.fileName()); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/enums/DocCategory.java b/src/main/java/uk/gov/hmcts/reform/civil/enums/DocCategory.java new file mode 100644 index 00000000000..490f8a05ad1 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/enums/DocCategory.java @@ -0,0 +1,18 @@ +package uk.gov.hmcts.reform.civil.enums; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@Getter +@RequiredArgsConstructor +public enum DocCategory { + BUNDLES("bundles"), + DEF1_DEFENSE_DQ("defendant1DefenseDirectionsQuestionnaire"), + DEF2_DEFENSE_DQ("defendant2DefenseDirectionsQuestionnaire"), + APP1_DQ("directionsQuestionnaire"), + DQ_DEF1("DQRespondent"), + DQ_DEF2("DQRespondentTwo"), + HEARING_NOTICES("hearingNotices"); + + private final String value; +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/enums/caseprogression/BundleFileNameList.java b/src/main/java/uk/gov/hmcts/reform/civil/enums/caseprogression/BundleFileNameList.java index 1c3342d0f48..ec628a0643f 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/enums/caseprogression/BundleFileNameList.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/enums/caseprogression/BundleFileNameList.java @@ -17,6 +17,7 @@ public enum BundleFileNameList { WITNESS_STATEMENT_OTHER_DISPLAY_NAME("Witness Statement %s %s %s"), WITNESS_STATEMENT("Witness Statement"), WITNESS_SUMMARY("Witness Summary %s %s"), + DOC_REFERRED_TO("Documents referred to in statement %s %s"), HEARSAY_NOTICE("Hearsay notice %s %s"), NOTICE_TO_ADMIT_FACTS("Notice to admit facts %s %s"), DF_RESPONSE("DF Response %s"), @@ -25,7 +26,8 @@ public enum BundleFileNameList { QUESTIONS_TO("Questions to %s %s"), REPLIES_FROM("Replies from %s %s"), JOINT_STATEMENTS_OF_EXPERTS("Joint statement of experts %s %s %s"), - SKELETON_ARGUMENT("%s Skeleton argument %s"); + SKELETON_ARGUMENT("%s Skeleton argument %s"), + PARTICULARS_OF_CLAIM("Particulars Of Claim %s"); String displayName; public String getDisplayName() { diff --git a/src/main/java/uk/gov/hmcts/reform/civil/enums/dq/GeneralApplicationTypes.java b/src/main/java/uk/gov/hmcts/reform/civil/enums/dq/GeneralApplicationTypes.java index 0242e020e00..d915e45d301 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/enums/dq/GeneralApplicationTypes.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/enums/dq/GeneralApplicationTypes.java @@ -13,7 +13,7 @@ public enum GeneralApplicationTypes { AMEND_A_STMT_OF_CASE("Amend a statement of case"), RELIEF_FROM_SANCTIONS("Relief from sanctions"), SET_ASIDE_JUDGEMENT("Set aside judgment"), - SETTLE_OR_DISCONTINUE_CONSENT("Settle or Discontinue by consent"), + SETTLE_BY_CONSENT("Settle by consent"), VARY_ORDER("Vary order"), ADJOURN_HEARING("Adjourn a hearing"), UNLESS_ORDER("Unless order"), diff --git a/src/main/java/uk/gov/hmcts/reform/civil/enums/finalorders/ApplicationAppealList.java b/src/main/java/uk/gov/hmcts/reform/civil/enums/finalorders/ApplicationAppealList.java index 77c922d3901..bff5421ab67 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/enums/finalorders/ApplicationAppealList.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/enums/finalorders/ApplicationAppealList.java @@ -2,5 +2,7 @@ public enum ApplicationAppealList { GRANTED, - REFUSED + REFUSED, + CIRCUIT_COURT, + HIGH_COURT } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/enums/finalorders/CostEnums.java b/src/main/java/uk/gov/hmcts/reform/civil/enums/finalorders/CostEnums.java new file mode 100644 index 00000000000..d8b82a86527 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/enums/finalorders/CostEnums.java @@ -0,0 +1,13 @@ +package uk.gov.hmcts.reform.civil.enums.finalorders; + +public enum CostEnums { + + CLAIMANT, + DEFENDANT, + COSTS, + SUBJECT_DETAILED_ASSESSMENT, + YES, + NO, + STANDARD_BASIS, + INDEMNITY_BASIS +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/exceptions/MissingFieldsUpdatedException.java b/src/main/java/uk/gov/hmcts/reform/civil/exceptions/MissingFieldsUpdatedException.java new file mode 100644 index 00000000000..2e9b475a539 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/exceptions/MissingFieldsUpdatedException.java @@ -0,0 +1,8 @@ +package uk.gov.hmcts.reform.civil.exceptions; + +public class MissingFieldsUpdatedException extends Exception { + + public MissingFieldsUpdatedException() { + super("Missing fields updated"); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/exceptions/PartyIdsUpdatedException.java b/src/main/java/uk/gov/hmcts/reform/civil/exceptions/PartyIdsUpdatedException.java deleted file mode 100644 index 922ea930b77..00000000000 --- a/src/main/java/uk/gov/hmcts/reform/civil/exceptions/PartyIdsUpdatedException.java +++ /dev/null @@ -1,8 +0,0 @@ -package uk.gov.hmcts.reform.civil.exceptions; - -public class PartyIdsUpdatedException extends Exception { - - public PartyIdsUpdatedException() { - super("PartyIds updated"); - } -} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/ClaimIssueCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/ClaimIssueCallbackHandler.java index 0b2929a6fd0..2e40b32da3e 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/ClaimIssueCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/ClaimIssueCallbackHandler.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; @@ -9,7 +10,6 @@ import uk.gov.hmcts.reform.civil.callback.CallbackHandler; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; -import uk.gov.hmcts.reform.ccd.model.Organisation; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.IdamUserDetails; import uk.gov.hmcts.reform.civil.service.DeadlinesCalculator; @@ -21,11 +21,10 @@ import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.PROCESS_CLAIM_ISSUE; -import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; -import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; @Service @RequiredArgsConstructor +@Slf4j public class ClaimIssueCallbackHandler extends CallbackHandler { private static final List EVENTS = Collections.singletonList(PROCESS_CLAIM_ISSUE); @@ -54,9 +53,6 @@ private CallbackResponse addClaimNotificationDeadlineAndNextDeadline(CallbackPar clearSubmitterId(caseData, caseDataUpdated); - // don't display cases in unassigned case list before claim notified workaround. - clearOrganisationPolicyId(caseData, caseDataUpdated); - return AboutToStartOrSubmitCallbackResponse.builder() .data(caseDataUpdated.build().toMap(objectMapper)) .build(); @@ -69,34 +65,6 @@ private void clearSubmitterId(CaseData caseData, CaseData.CaseDataBuilder caseDa .build(); } - private void clearOrganisationPolicyId(CaseData caseData, CaseData.CaseDataBuilder caseDataBuilder) { - if (YES.equals(caseData.getRespondent1OrgRegistered())) { - caseDataBuilder.respondent1OrganisationIDCopy( - caseData.getRespondent1OrganisationPolicy().getOrganisation().getOrganisationID()); - - caseDataBuilder.respondent1OrganisationPolicy( - caseData - .getRespondent1OrganisationPolicy() - .toBuilder() - .organisation(Organisation.builder().build()) - .build() - ); - } - - if (NO.equals(caseData.getRespondent2SameLegalRepresentative())) { - caseDataBuilder.respondent2OrganisationIDCopy( - caseData.getRespondent2OrganisationPolicy().getOrganisation().getOrganisationID()); - - caseDataBuilder.respondent2OrganisationPolicy( - caseData - .getRespondent2OrganisationPolicy() - .toBuilder() - .organisation(Organisation.builder().build()) - .build() - ); - } - } - @Override public List handledEvents() { return EVENTS; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/RespondentResponseDeadlineCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/RespondentResponseDeadlineCallbackHandler.java new file mode 100644 index 00000000000..36b2ef92d65 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/RespondentResponseDeadlineCallbackHandler.java @@ -0,0 +1,62 @@ +package uk.gov.hmcts.reform.civil.handler.callback.camunda.caseevents; + +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.civil.callback.Callback; +import uk.gov.hmcts.reform.civil.callback.CallbackHandler; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.service.DeadlinesCalculator; + +import java.time.LocalDateTime; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.SET_LIP_RESPONDENT_RESPONSE_DEADLINE; + +@Service +@RequiredArgsConstructor +@SuppressWarnings("unchecked") +public class RespondentResponseDeadlineCallbackHandler extends CallbackHandler { + + private static final List EVENTS = Collections.singletonList(SET_LIP_RESPONDENT_RESPONSE_DEADLINE); + + public static final String TASK_ID = "SetRespondent1Deadline"; + private Map callbackMap = Map.of(callbackKey(ABOUT_TO_SUBMIT), this::updateRespondentDeadlineDate); + private final ObjectMapper objectMapper; + private final DeadlinesCalculator deadlinesCalculator; + + @Override + public String camundaActivityId(CallbackParams callbackParams) { + return TASK_ID; + } + + @Override + protected Map callbacks() { + return callbackMap; + } + + @Override + public List handledEvents() { + return EVENTS; + } + + private CallbackResponse updateRespondentDeadlineDate(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder() + .respondent1ResponseDeadline(deadlinesCalculator.plus28DaysAt4pmDeadline( + LocalDateTime.now())); + + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .build(); + } + +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/SendSDOToLiPDefendantCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/SendSDOToLiPDefendantCallbackHandler.java index 6e01a15caa0..77938e6206e 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/SendSDOToLiPDefendantCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/SendSDOToLiPDefendantCallbackHandler.java @@ -14,6 +14,7 @@ import java.util.List; import java.util.Map; +import static uk.gov.hmcts.reform.civil.callback.CallbackParams.Params.BEARER_TOKEN; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.SEND_SDO_ORDER_TO_LIP_DEFENDANT; @@ -44,7 +45,7 @@ public List handledEvents() { private CallbackResponse sendSDOLetter(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); - sendSDOBulkPrintService.sendSDOToDefendantLIP(caseData); + sendSDOBulkPrintService.sendSDOToDefendantLIP(callbackParams.getParams().get(BEARER_TOKEN).toString(), caseData); return AboutToStartOrSubmitCallbackResponse.builder() .build(); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/TriggerGenAppLocationUpdateCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/TriggerGenAppLocationUpdateCallbackHandler.java index 6b392415a0c..6a7c730596d 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/TriggerGenAppLocationUpdateCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/TriggerGenAppLocationUpdateCallbackHandler.java @@ -16,6 +16,7 @@ import java.util.List; import java.util.Map; +import static uk.gov.hmcts.reform.civil.callback.CallbackParams.Params.BEARER_TOKEN; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.TRIGGER_LOCATION_UPDATE; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.TRIGGER_UPDATE_GA_LOCATION; @@ -44,9 +45,10 @@ public List handledEvents() { private CallbackResponse triggerGaEvent(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); + String authToken = callbackParams.getParams().get(BEARER_TOKEN).toString(); try { if (caseData.getGeneralApplications() != null && !caseData.getGeneralApplications().isEmpty()) { - caseData = helperService.updateApplicationLocationDetailsInClaim(caseData); + caseData = helperService.updateApplicationLocationDetailsInClaim(caseData, authToken); helperService.triggerEvent(caseData, TRIGGER_LOCATION_UPDATE); } } catch (Exception e) { diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateAcknowledgementOfClaimCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateAcknowledgementOfClaimCallbackHandler.java index d5d40362d8f..e91de0ffd24 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateAcknowledgementOfClaimCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateAcknowledgementOfClaimCallbackHandler.java @@ -9,6 +9,7 @@ import uk.gov.hmcts.reform.civil.callback.CallbackHandler; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.enums.DocCategory; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.common.Element; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; @@ -17,6 +18,7 @@ import java.util.List; import java.util.Map; +import java.util.Objects; import static java.util.Objects.nonNull; import static uk.gov.hmcts.reform.civil.callback.CallbackParams.Params.BEARER_TOKEN; @@ -59,14 +61,20 @@ private CallbackResponse prepareAcknowledgementOfClaim(CallbackParams callbackPa caseData, callbackParams.getParams().get(BEARER_TOKEN).toString() ); - + CaseDocument copy = assignCategoryId.copyCaseDocumentWithCategoryId( + acknowledgementOfClaim, ""); List> systemGeneratedCaseDocuments = caseData.getSystemGeneratedCaseDocuments(); systemGeneratedCaseDocuments.add(element(acknowledgementOfClaim)); + if (Objects.nonNull(copy)) { + systemGeneratedCaseDocuments.add(element(copy)); + } caseDataBuilder.systemGeneratedCaseDocuments(systemGeneratedCaseDocuments); - assignCategoryId.assignCategoryIdToCaseDocument(acknowledgementOfClaim, "defendant1DefenseDirectionsQuestionnaire"); + assignCategoryId.assignCategoryIdToCaseDocument(acknowledgementOfClaim, DocCategory.DEF1_DEFENSE_DQ.getValue()); + assignCategoryId.assignCategoryIdToCaseDocument(copy, DocCategory.DQ_DEF1.getValue()); if (nonNull(caseData.getRespondent2DocumentGeneration()) && caseData.getRespondent2DocumentGeneration().equals("userRespondent2")) { - assignCategoryId.assignCategoryIdToCaseDocument(acknowledgementOfClaim, "defendant2DefenseDirectionsQuestionnaire"); + assignCategoryId.assignCategoryIdToCaseDocument(acknowledgementOfClaim, DocCategory.DEF2_DEFENSE_DQ.getValue()); + assignCategoryId.assignCategoryIdToCaseDocument(copy, DocCategory.DQ_DEF2.getValue()); } return AboutToStartOrSubmitCallbackResponse.builder() diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateClaimFormCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateClaimFormCallbackHandler.java index b96c1941b31..5b8cb3ec373 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateClaimFormCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateClaimFormCallbackHandler.java @@ -106,8 +106,8 @@ private CallbackResponse generateClaimForm(CallbackParams callbackParams) { civilDocumentStitchingService.bundle( documents, callbackParams.getParams().get(CallbackParams.Params.BEARER_TOKEN).toString(), - sealedClaim.getDocumentName(), BUNDLE_NAME, + sealedClaim.getDocumentName(), caseData ); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateClaimFormForSpecCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateClaimFormForSpecCallbackHandler.java index dfa92d4ab69..ad19e6b8e9f 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateClaimFormForSpecCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateClaimFormForSpecCallbackHandler.java @@ -74,8 +74,7 @@ public List handledEvents() { private CallbackResponse generateClaimFormForSpec(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); - - if (featureToggleService.isLipVLipEnabled()) { + if (featureToggleService.isLipVLipEnabled() && caseData.isApplicantNotRepresented()) { return AboutToStartOrSubmitCallbackResponse.builder() .build(); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionQuestionnaireLipCallBackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionQuestionnaireLipCallBackHandler.java index 058da4bea3e..92a4372bb1e 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionQuestionnaireLipCallBackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionQuestionnaireLipCallBackHandler.java @@ -13,7 +13,7 @@ import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.service.SystemGeneratedDocumentService; -import uk.gov.hmcts.reform.civil.service.docmosis.dq.DirectionsQuestionnaireLipGenerator; +import uk.gov.hmcts.reform.civil.service.docmosis.dq.DirectionQuestionnaireLipGeneratorFactory; import java.util.Collections; import java.util.List; @@ -32,7 +32,7 @@ public class GenerateDirectionQuestionnaireLipCallBackHandler extends CallbackHa ); private final ObjectMapper objectMapper; - private final DirectionsQuestionnaireLipGenerator directionsQuestionnaireLipGenerator; + private final DirectionQuestionnaireLipGeneratorFactory directionQuestionnaireLipGeneratorFactory; private final SystemGeneratedDocumentService systemGeneratedDocumentService; @Override @@ -52,15 +52,12 @@ private CallbackResponse prepareDirectionsQuestionnaire(CallbackParams callbackP .build(); } CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); - CaseDocument sealedDQForm = directionsQuestionnaireLipGenerator.generate( - caseData, - callbackParams.getParams().get( - BEARER_TOKEN).toString() - ); - caseDataBuilder.systemGeneratedCaseDocuments(systemGeneratedDocumentService.getSystemGeneratedDocumentsWithAddedDocument( - sealedDQForm, - caseData - )); + CaseDocument sealedDQForm = directionQuestionnaireLipGeneratorFactory + .getDirectionQuestionnaire() + .generate(caseData, callbackParams.getParams().get(BEARER_TOKEN).toString()); + caseDataBuilder + .systemGeneratedCaseDocuments(systemGeneratedDocumentService + .getSystemGeneratedDocumentsWithAddedDocument(sealedDQForm, caseData)); return AboutToStartOrSubmitCallbackResponse.builder() .data(caseDataBuilder.build().toMap(objectMapper)) diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionsQuestionnaireCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionsQuestionnaireCallbackHandler.java index 037515aa1fa..b826c6cd43d 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionsQuestionnaireCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionsQuestionnaireCallbackHandler.java @@ -9,6 +9,7 @@ import uk.gov.hmcts.reform.civil.callback.CallbackHandler; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.enums.DocCategory; import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec; import uk.gov.hmcts.reform.civil.service.FeatureToggleService; @@ -21,6 +22,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Objects; import static java.util.Objects.nonNull; import static uk.gov.hmcts.reform.civil.callback.CallbackParams.Params.BEARER_TOKEN; @@ -59,18 +61,21 @@ public List handledEvents() { public void generateDQ1v2SameSol(CallbackParams callbackParams, String sol) { CaseData caseData = callbackParams.getCaseData(); - CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); CaseDocument directionsQuestionnaire = directionsQuestionnaireGenerator.generateDQFor1v2SingleSolDiffResponse( caseData, callbackParams.getParams().get(BEARER_TOKEN).toString(), sol ); - assignCategoryId.assignCategoryIdToCaseDocument(directionsQuestionnaire, "defendant1DefenseDirectionsQuestionnaire"); - + assignCategoryId.assignCategoryIdToCaseDocument(directionsQuestionnaire, DocCategory.DEF1_DEFENSE_DQ.getValue()); + CaseDocument copy = assignCategoryId.copyCaseDocumentWithCategoryId(directionsQuestionnaire, DocCategory.DQ_DEF1.getValue()); List> systemGeneratedCaseDocuments = caseData.getSystemGeneratedCaseDocuments(); systemGeneratedCaseDocuments.add(element(directionsQuestionnaire)); + if (Objects.nonNull(copy)) { + systemGeneratedCaseDocuments.add(element(copy)); + } + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); caseDataBuilder.systemGeneratedCaseDocuments(systemGeneratedCaseDocuments); } @@ -119,7 +124,11 @@ private CallbackResponse prepareDirectionsQuestionnaire(CallbackParams callbackP ).ifPresent(document -> { updatedDocuments.add(element(document)); caseDataBuilder.respondent1DocumentURL(document.getDocumentLink().getDocumentUrl()); - assignCategoryId.assignCategoryIdToCaseDocument(document, "defendant1DefenseDirectionsQuestionnaire"); + assignCategoryId.assignCategoryIdToCaseDocument(document, DocCategory.DEF1_DEFENSE_DQ.getValue()); + CaseDocument copy = assignCategoryId.copyCaseDocumentWithCategoryId(document, DocCategory.DQ_DEF1.getValue()); + if (Objects.nonNull(copy)) { + updatedDocuments.add(element(copy)); + } }); } @@ -137,7 +146,11 @@ private CallbackResponse prepareDirectionsQuestionnaire(CallbackParams callbackP ).ifPresent(document -> { updatedDocuments.add(element(document)); caseDataBuilder.respondent2DocumentURL(document.getDocumentLink().getDocumentUrl()); - assignCategoryId.assignCategoryIdToCaseDocument(document, "defendant2DefenseDirectionsQuestionnaire"); + assignCategoryId.assignCategoryIdToCaseDocument(document, DocCategory.DEF2_DEFENSE_DQ.getValue()); + CaseDocument copy = assignCategoryId.copyCaseDocumentWithCategoryId(document, DocCategory.DQ_DEF2.getValue()); + if (Objects.nonNull(copy)) { + updatedDocuments.add(element(copy)); + } }); } @@ -189,24 +202,32 @@ private void singleResponseFile(String bearerToken, CaseData caseData, caseData, bearerToken ); - + CaseDocument copy = assignCategoryId.copyCaseDocumentWithCategoryId(directionsQuestionnaire, ""); if (UNSPEC_CLAIM.equals(caseData.getCaseAccessCategory())) { - assignCategoryId.assignCategoryIdToCaseDocument(directionsQuestionnaire, "directionsQuestionnaire"); + assignCategoryId.assignCategoryIdToCaseDocument(directionsQuestionnaire, DocCategory.APP1_DQ.getValue()); + assignCategoryId.assignCategoryIdToCaseDocument(copy, "DQApplicant"); if (directionsQuestionnaire.getDocumentName().contains("defendant")) { - assignCategoryId.assignCategoryIdToCaseDocument(directionsQuestionnaire, "defendant1DefenseDirectionsQuestionnaire"); + assignCategoryId.assignCategoryIdToCaseDocument(directionsQuestionnaire, DocCategory.DEF1_DEFENSE_DQ.getValue()); + assignCategoryId.assignCategoryIdToCaseDocument(copy, DocCategory.DQ_DEF1.getValue()); } if (nonNull(caseData.getRespondent2DocumentGeneration()) && caseData.getRespondent2DocumentGeneration().equals("userRespondent2")) { - assignCategoryId.assignCategoryIdToCaseDocument(directionsQuestionnaire, "defendant2DefenseDirectionsQuestionnaire"); + assignCategoryId.assignCategoryIdToCaseDocument(directionsQuestionnaire, DocCategory.DEF2_DEFENSE_DQ.getValue()); + assignCategoryId.assignCategoryIdToCaseDocument(copy, DocCategory.DQ_DEF2.getValue()); } } List> systemGeneratedCaseDocuments = caseData.getSystemGeneratedCaseDocuments(); systemGeneratedCaseDocuments.add(element(directionsQuestionnaire)); + if (Objects.nonNull(copy)) { + systemGeneratedCaseDocuments.add(element(copy)); + } caseDataBuilder.systemGeneratedCaseDocuments(systemGeneratedCaseDocuments); if (SPEC_CLAIM.equals(caseData.getCaseAccessCategory())) { - assignCategoryId.assignCategoryIdToCaseDocument(directionsQuestionnaire, "directionsQuestionnaire"); + assignCategoryId.assignCategoryIdToCaseDocument(directionsQuestionnaire, DocCategory.APP1_DQ.getValue()); + assignCategoryId.assignCategoryIdToCaseDocument(copy, "DQApplicant"); if (directionsQuestionnaire.getDocumentName().contains("defendant")) { - assignCategoryId.assignCategoryIdToCaseDocument(directionsQuestionnaire, "defendant1DefenseDirectionsQuestionnaire"); + assignCategoryId.assignCategoryIdToCaseDocument(directionsQuestionnaire, DocCategory.DEF1_DEFENSE_DQ.getValue()); + assignCategoryId.assignCategoryIdToCaseDocument(copy, DocCategory.DQ_DEF1.getValue()); } } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateResponseSealedSpec.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateResponseSealedSpec.java index e4db522d8a4..e09b0daf78e 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateResponseSealedSpec.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateResponseSealedSpec.java @@ -12,6 +12,7 @@ import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CallbackType; import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.enums.DocCategory; import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; @@ -27,6 +28,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Objects; import static java.util.Objects.nonNull; import static uk.gov.hmcts.reform.civil.callback.CallbackParams.Params.BEARER_TOKEN; @@ -65,15 +67,17 @@ public List handledEvents() { private CallbackResponse prepareSealedForm(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); - CaseData.CaseDataBuilder builder = caseData.toBuilder(); - CaseDocument sealedForm = formGenerator.generate( caseData, callbackParams.getParams().get(BEARER_TOKEN).toString() ); - assignCategoryId.assignCategoryIdToCaseDocument(sealedForm, "defendant1DefenseDirectionsQuestionnaire"); + CaseDocument copy = assignCategoryId.copyCaseDocumentWithCategoryId( + sealedForm, ""); + assignCategoryId.assignCategoryIdToCaseDocument(sealedForm, DocCategory.DEF1_DEFENSE_DQ.getValue()); + assignCategoryId.assignCategoryIdToCaseDocument(copy, DocCategory.DQ_DEF1.getValue()); if (nonNull(caseData.getRespondent2DocumentGeneration()) && caseData.getRespondent2DocumentGeneration().equals("userRespondent2")) { - assignCategoryId.assignCategoryIdToCaseDocument(sealedForm, "defendant2DefenseDirectionsQuestionnaire"); + assignCategoryId.assignCategoryIdToCaseDocument(sealedForm, DocCategory.DEF2_DEFENSE_DQ.getValue()); + assignCategoryId.assignCategoryIdToCaseDocument(copy, DocCategory.DQ_DEF2.getValue()); } if (stitchEnabled) { @@ -85,20 +89,24 @@ private CallbackResponse prepareSealedForm(CallbackParams callbackParams) { sealedForm.getDocumentName(), caseData ); - assignCategoryId.assignCategoryIdToCaseDocument(stitchedDocument, "defendant1DefenseDirectionsQuestionnaire"); + assignCategoryId.assignCategoryIdToCaseDocument(stitchedDocument, DocCategory.DEF1_DEFENSE_DQ.getValue()); + CaseDocument stitchedDocumentCopy = assignCategoryId.copyCaseDocumentWithCategoryId( + stitchedDocument, DocCategory.DQ_DEF1.getValue()); if (nonNull(caseData.getRespondent2DocumentGeneration()) && caseData.getRespondent2DocumentGeneration().equals("userRespondent2")) { - assignCategoryId.assignCategoryIdToCaseDocument(stitchedDocument, "defendant2DefenseDirectionsQuestionnaire"); - } - if (V_1.equals(callbackParams.getVersion()) && toggleService.isPinInPostEnabled()) { - builder.respondent1ClaimResponseDocumentSpec(stitchedDocument); + assignCategoryId.assignCategoryIdToCaseDocument(stitchedDocument, DocCategory.DEF2_DEFENSE_DQ.getValue()); + assignCategoryId.assignCategoryIdToCaseDocument(stitchedDocumentCopy, DocCategory.DQ_DEF2.getValue()); } caseData.getSystemGeneratedCaseDocuments().add(ElementUtils.element(stitchedDocument)); - } else { - if (V_1.equals(callbackParams.getVersion()) && toggleService.isPinInPostEnabled()) { - builder.respondent1ClaimResponseDocumentSpec(sealedForm); + if (Objects.nonNull(stitchedDocumentCopy)) { + caseData.getSystemGeneratedCaseDocuments().add(ElementUtils.element(stitchedDocumentCopy)); } + } else { caseData.getSystemGeneratedCaseDocuments().add(ElementUtils.element(sealedForm)); + if (Objects.nonNull(copy)) { + caseData.getSystemGeneratedCaseDocuments().add(ElementUtils.element(copy)); + } } + CaseData.CaseDataBuilder builder = caseData.toBuilder(); return AboutToStartOrSubmitCallbackResponse.builder() .data(builder.build().toMap(objectMapper)) diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateTrialReadyFormHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateTrialReadyFormHandler.java index 6791d2db88a..5b65eb6a041 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateTrialReadyFormHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateTrialReadyFormHandler.java @@ -10,6 +10,7 @@ import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; +import uk.gov.hmcts.reform.civil.enums.CaseRole; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.service.docmosis.trialready.TrialReadyFormGenerator; @@ -22,7 +23,7 @@ import static uk.gov.hmcts.reform.civil.callback.CaseEvent.GENERATE_TRIAL_READY_FORM_RESPONDENT1; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.GENERATE_TRIAL_READY_FORM_RESPONDENT2; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.element; -import static uk.gov.hmcts.reform.civil.utils.NotificationUtils.isRespondent1; +import static uk.gov.hmcts.reform.civil.utils.NotificationUtils.isEvent; @Service @RequiredArgsConstructor @@ -53,9 +54,9 @@ public List handledEvents() { @Override public String camundaActivityId(CallbackParams callbackParams) { - if (isApplicant(callbackParams, GENERATE_TRIAL_READY_FORM_APPLICANT)) { + if (isEvent(callbackParams, GENERATE_TRIAL_READY_FORM_APPLICANT)) { return TASK_ID_APPLICANT; - } else if (isRespondent1(callbackParams, GENERATE_TRIAL_READY_FORM_RESPONDENT1)) { + } else if (isEvent(callbackParams, GENERATE_TRIAL_READY_FORM_RESPONDENT1)) { return TASK_ID_RESPONDENT1; } else { return TASK_ID_RESPONDENT2; @@ -75,19 +76,23 @@ private CallbackResponse generateClaimForm(CallbackParams callbackParams) { private void buildDocument(CallbackParams callbackParams, CaseData.CaseDataBuilder caseDataBuilder, CaseData caseData) { + String activityID = camundaActivityId(callbackParams); + CaseRole role = switch (activityID) { + case TASK_ID_APPLICANT -> CaseRole.CLAIMANT; + case TASK_ID_RESPONDENT1 -> CaseRole.DEFENDANT; + case TASK_ID_RESPONDENT2 -> CaseRole.RESPONDENTSOLICITORTWO; + default -> null; + }; + CaseDocument caseDocument = trialReadyFormGenerator.generate( callbackParams.getCaseData(), callbackParams.getParams().get(BEARER_TOKEN).toString(), - camundaActivityId(callbackParams) + camundaActivityId(callbackParams), + role ); var documents = caseData.getTrialReadyDocuments(); documents.add(element(caseDocument)); caseDataBuilder.trialReadyDocuments(documents); } - private boolean isApplicant(CallbackParams callbackParams, CaseEvent matchEvent) { - CaseEvent caseEvent = CaseEvent.valueOf(callbackParams.getRequest().getEventId()); - return caseEvent.equals(matchEvent); - } - } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/noticeofchange/UpdateCaseDetailsAfterNoCHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/noticeofchange/UpdateCaseDetailsAfterNoCHandler.java index f78d721a010..22202b7c89a 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/noticeofchange/UpdateCaseDetailsAfterNoCHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/noticeofchange/UpdateCaseDetailsAfterNoCHandler.java @@ -161,7 +161,8 @@ private void updateRespondentSolicitor2Details( caseDataBuilder.respondent2OrgRegistered(YES) .respondentSolicitor2OrganisationDetails(null) - .respondent2Represented(YES); + .respondent2Represented(YES) + .defendant2LIPAtClaimIssued(NO); if (UNSPEC_CLAIM.equals(caseData.getCaseAccessCategory())) { caseDataBuilder.respondentSolicitor2ServiceAddress(null) @@ -188,7 +189,8 @@ private void updateRespondentSolicitor1Details(CaseData.CaseDataBuilder ca caseDataBuilder.respondent1OrgRegistered(YES) .respondentSolicitor1OrganisationDetails(null) - .respondent1Represented(YES); + .respondent1Represented(YES) + .defendant1LIPAtClaimIssued(NO); if (UNSPEC_CLAIM.equals(caseData.getCaseAccessCategory())) { caseDataBuilder.respondentSolicitor1ServiceAddress(null) diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AbstractCreateSDORespondentLRNotificationSender.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AbstractCreateSDORespondentLRNotificationSender.java index fd17d0f8f38..afd2aeee371 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AbstractCreateSDORespondentLRNotificationSender.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AbstractCreateSDORespondentLRNotificationSender.java @@ -5,6 +5,7 @@ import uk.gov.hmcts.reform.civil.notify.NotificationService; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; import uk.gov.hmcts.reform.civil.prd.model.Organisation; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.OrganisationService; import java.util.Optional; @@ -17,8 +18,9 @@ public abstract class AbstractCreateSDORespondentLRNotificationSender extends Ab public AbstractCreateSDORespondentLRNotificationSender( NotificationService notificationService, NotificationsProperties notificationsProperties, - OrganisationService organisationService) { - super(notificationService, notificationsProperties); + OrganisationService organisationService, + FeatureToggleService featureToggleService) { + super(notificationService, notificationsProperties, featureToggleService); this.organisationService = organisationService; } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AbstractCreateSDORespondentNotificationSender.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AbstractCreateSDORespondentNotificationSender.java index d8c85eaa3aa..ec43e59761f 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AbstractCreateSDORespondentNotificationSender.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AbstractCreateSDORespondentNotificationSender.java @@ -7,6 +7,7 @@ import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.notify.NotificationService; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import java.util.Map; @@ -20,6 +21,7 @@ public abstract class AbstractCreateSDORespondentNotificationSender implements N private final NotificationService notificationService; private final NotificationsProperties notificationsProperties; + private final FeatureToggleService featureToggleService; protected abstract String getDocReference(CaseData caseData); @@ -43,12 +45,14 @@ void notifyRespondentPartySDOTriggered(CaseData caseData) { private String getSDOTemplate(CaseData caseData) { if (caseData.getCaseAccessCategory() == CaseCategory.SPEC_CLAIM) { - if (caseData.isRespondentResponseBilingual()) { + if (caseData.isRespondentResponseBilingual()) { return notificationsProperties.getSdoOrderedSpecBilingual(); - } - return notificationsProperties.getSdoOrderedSpec(); + } + return featureToggleService.isEarlyAdoptersEnabled() + ? notificationsProperties.getSdoOrderedSpecEA() : notificationsProperties.getSdoOrderedSpec(); } - return notificationsProperties.getSdoOrdered(); + return featureToggleService.isEarlyAdoptersEnabled() + ? notificationsProperties.getSdoOrderedEA() : notificationsProperties.getSdoOrdered(); } /** diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AcknowledgeClaimApplicantNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AcknowledgeClaimApplicantNotificationHandler.java index b69de76b260..27c62f6d2a6 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AcknowledgeClaimApplicantNotificationHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AcknowledgeClaimApplicantNotificationHandler.java @@ -1,6 +1,7 @@ package uk.gov.hmcts.reform.civil.handler.callback.camunda.notification; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; @@ -29,6 +30,7 @@ import static uk.gov.hmcts.reform.civil.utils.PartyUtils.getPartyNameBasedOnType; import static uk.gov.hmcts.reform.civil.utils.PartyUtils.getResponseIntentionForEmail; +@Slf4j @Service @RequiredArgsConstructor public class AcknowledgeClaimApplicantNotificationHandler extends CallbackHandler implements NotificationData { @@ -67,12 +69,16 @@ private CallbackResponse notifyApplicantSolicitorForClaimAcknowledgement(Callbac ? getRespondentSolicitorEmailAddress(caseData) : caseData.getApplicantSolicitor1UserDetails().getEmail(); - notificationService.sendMail( - recipient, - notificationsProperties.getRespondentSolicitorAcknowledgeClaim(), - addProperties(caseData), - String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) - ); + if (recipient != null) { + notificationService.sendMail( + recipient, + notificationsProperties.getRespondentSolicitorAcknowledgeClaim(), + addProperties(caseData), + String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) + ); + } else { + log.info(String.format("Email address is null for %s", caseData.getLegacyCaseReference())); + } return AboutToStartOrSubmitCallbackResponse.builder().build(); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/BreathingSpaceEnteredLIPNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/BreathingSpaceEnteredLIPNotificationHandler.java new file mode 100644 index 00000000000..d34a2b6d278 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/BreathingSpaceEnteredLIPNotificationHandler.java @@ -0,0 +1,96 @@ +package uk.gov.hmcts.reform.civil.handler.callback.camunda.notification; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.civil.callback.Callback; +import uk.gov.hmcts.reform.civil.callback.CallbackHandler; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; + +import static org.apache.commons.lang3.StringUtils.isNotEmpty; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOTIFY_LIP_RESPONDENT_BREATHING_SPACE_ENTER; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Service +@RequiredArgsConstructor +public class BreathingSpaceEnteredLIPNotificationHandler extends CallbackHandler implements NotificationData { + + private static final List EVENTS = + List.of( + CaseEvent.NOTIFY_LIP_APPLICANT1_BREATHING_SPACE_ENTER, + CaseEvent.NOTIFY_LIP_RESPONDENT_BREATHING_SPACE_ENTER + ); + public static final String TASK_ID_Applicant1 = "NotifyApplicant1BreathingSpaceLIP"; + public static final String TASK_ID_RESPONDENT = "NotifyRespondentBreathingSpaceLIP"; + private static final String REFERENCE_TEMPLATE = "notify-breathing-space-lip-%s"; + private final NotificationService notificationService; + private final NotificationsProperties notificationsProperties; + private final Map callBackMap = Map.of( + callbackKey(ABOUT_TO_SUBMIT), this::notifyApplicant1BreathingSpaceEnteredLip + ); + + @Override + protected Map callbacks() { + return callBackMap; + } + + @Override + public String camundaActivityId(CallbackParams callbackParams) { + return isRespondentNotification(callbackParams) ? TASK_ID_RESPONDENT : TASK_ID_Applicant1; + } + + @Override + public List handledEvents() { + return EVENTS; + } + + @Override + public Map addProperties(CaseData caseData) { + return Map.of( + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + CLAIMANT_NAME, caseData.getApplicant1().getPartyName(), + RESPONDENT_NAME, caseData.getRespondent1().getPartyName() + ); + } + + private CallbackResponse notifyApplicant1BreathingSpaceEnteredLip(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + Map templateProperties = addProperties(caseData); + + if (isRespondentNotification(callbackParams)) { + String recipientEmail = Optional.ofNullable(caseData.getRespondent1()) + .map(Party::getPartyEmail).orElse(""); + if (isNotEmpty(recipientEmail)) { + notificationService.sendMail( + recipientEmail, + notificationsProperties.getNotifyEnteredBreathingSpaceForDefendantLip(), + templateProperties, + String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) + ); + } + } else { + notificationService.sendMail( + caseData.getApplicant1Email(), + notificationsProperties.getNotifyApplicant1EnteredBreathingSpaceLip(), + templateProperties, + String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) + ); + } + return AboutToStartOrSubmitCallbackResponse.builder().build(); + } + + private boolean isRespondentNotification(CallbackParams callbackParams) { + return callbackParams.getRequest().getEventId() + .equals(NOTIFY_LIP_RESPONDENT_BREATHING_SPACE_ENTER.name()); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/BreathingSpaceLiftedLIPNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/BreathingSpaceLiftedLIPNotificationHandler.java new file mode 100644 index 00000000000..579894bb745 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/BreathingSpaceLiftedLIPNotificationHandler.java @@ -0,0 +1,90 @@ +package uk.gov.hmcts.reform.civil.handler.callback.camunda.notification; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.civil.callback.Callback; +import uk.gov.hmcts.reform.civil.callback.CallbackHandler; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; + +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; + +@Service +@RequiredArgsConstructor +public class BreathingSpaceLiftedLIPNotificationHandler extends CallbackHandler implements NotificationData { + + private static final List EVENTS = + List.of( + CaseEvent. NOTIFY_LIP_APPLICANT_BREATHING_SPACE_LIFTED, + CaseEvent.NOTIFY_LIP_RESPONDENT_BREATHING_SPACE_LIFTED + ); + public static final String TASK_ID_APPLICANT = "NotifyApplicantBreathingSpaceLifted"; + public static final String TASK_ID_RESPONDENT = "NotifyRespondentBreathingSpaceLifted"; + private static final String REFERENCE_TEMPLATE = "notify-breathing-space-lifted-%s"; + private final NotificationService notificationService; + private final NotificationsProperties notificationsProperties; + private final Map callBackMap = Map.of( + callbackKey(ABOUT_TO_SUBMIT), this::notifyBreathingSpaceLifted + ); + + @Override + protected Map callbacks() { + return callBackMap; + } + + @Override + public String camundaActivityId(CallbackParams callbackParams) { + return isApplicantNotification(callbackParams) ? TASK_ID_APPLICANT : TASK_ID_RESPONDENT; + } + + @Override + public List handledEvents() { + return EVENTS; + } + + @Override + public Map addProperties(CaseData caseData) { + return Map.of( + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + CLAIMANT_NAME, caseData.getApplicant1().getPartyName(), + RESPONDENT_NAME, caseData.getRespondent1().getPartyName() + ); + } + + private CallbackResponse notifyBreathingSpaceLifted(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + Map templateProperties = addProperties(caseData); + final String applicantEmail = caseData.getApplicant1Email(); + + if (isApplicantNotification(callbackParams) && Objects.nonNull(applicantEmail)) { + notificationService.sendMail( + applicantEmail, + notificationsProperties.getNotifyLiPApplicantBreathingSpaceLifted(), + templateProperties, + String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) + ); + } else if (Objects.nonNull(caseData.getRespondent1().getPartyEmail())) { + notificationService.sendMail( + caseData.getRespondent1().getPartyEmail(), + notificationsProperties.getNotifyLiPRespondentBreathingSpaceLifted(), + templateProperties, + String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) + ); + } + return AboutToStartOrSubmitCallbackResponse.builder().build(); + } + + private boolean isApplicantNotification(CallbackParams callbackParams) { + return callbackParams.getRequest().getEventId() + .equals(CaseEvent.NOTIFY_LIP_APPLICANT_BREATHING_SPACE_LIFTED.name()); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseAgreedSettledPartAdmitDefendantLipNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseAgreedSettledPartAdmitDefendantLipNotificationHandler.java index b7099f54b06..916ed40a014 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseAgreedSettledPartAdmitDefendantLipNotificationHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseAgreedSettledPartAdmitDefendantLipNotificationHandler.java @@ -11,9 +11,11 @@ import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.notify.NotificationService; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; +import uk.gov.hmcts.reform.civil.service.OrganisationDetailsService; import java.util.List; import java.util.Map; +import java.util.Objects; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOTIFY_LIP_DEFENDANT_PART_ADMIT_CLAIM_SETTLED; @@ -29,6 +31,7 @@ public class ClaimantResponseAgreedSettledPartAdmitDefendantLipNotificationHandl private final NotificationService notificationService; private final NotificationsProperties notificationsProperties; + private final OrganisationDetailsService organisationDetailsService; @Override protected Map callbacks() { @@ -49,33 +52,38 @@ public List handledEvents() { @Override public Map addProperties(CaseData caseData) { + if (caseData.isRespondent1NotRepresented()) { + return Map.of( + RESPONDENT_NAME, getPartyNameBasedOnType(caseData.getRespondent1()), + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference() + ); + } return Map.of( - RESPONDENT_NAME, getPartyNameBasedOnType(caseData.getRespondent1()), - CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference() + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + CLAIM_LEGAL_ORG_NAME_SPEC, organisationDetailsService.getRespondentLegalOrganizationName(caseData) ); } private CallbackResponse notifyDefendantForPartAdmitClaimSettled(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); - if (!caseData.isLRvLipOneVOne() || caseData.getRespondent1().getPartyEmail() == null) { - return AboutToStartOrSubmitCallbackResponse.builder() - .build(); + if (Objects.nonNull(caseData.getRespondent1Email())) { + notificationService.sendMail( + caseData.getRespondent1Email(), + setUpEmailTemplate(caseData), + addProperties(caseData), + String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) + ); } - - notificationService.sendMail( - caseData.getRespondent1().getPartyEmail(), - setUpEmailTemplate(caseData), - addProperties(caseData), - String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) - ); - return AboutToStartOrSubmitCallbackResponse.builder() .build(); } private String setUpEmailTemplate(CaseData caseData) { - return caseData.isRespondentResponseBilingual() - ? notificationsProperties.getRespondentLipPartAdmitSettleClaimBilingualTemplate() - : notificationsProperties.getRespondentLipPartAdmitSettleClaimTemplate(); + if (caseData.isRespondent1NotRepresented()) { + return caseData.isRespondentResponseBilingual() + ? notificationsProperties.getRespondentLipPartAdmitSettleClaimBilingualTemplate() + : notificationsProperties.getRespondentLipPartAdmitSettleClaimTemplate(); + } + return notificationsProperties.getRespondentLrPartAdmitSettleClaimTemplate(); } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedApplicantNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedApplicantNotificationHandler.java new file mode 100644 index 00000000000..0a23dd890a1 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedApplicantNotificationHandler.java @@ -0,0 +1,77 @@ +package uk.gov.hmcts.reform.civil.handler.callback.camunda.notification; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.civil.callback.Callback; +import uk.gov.hmcts.reform.civil.callback.CallbackHandler; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; + +import java.util.List; +import java.util.Map; + +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOTIFY_LIP_APPLICANT_CLAIMANT_CONFIRM_TO_PROCEED; +import static uk.gov.hmcts.reform.civil.utils.PartyUtils.getPartyNameBasedOnType; + +@Service +@RequiredArgsConstructor +public class ClaimantResponseConfirmsToProceedApplicantNotificationHandler extends CallbackHandler + implements NotificationData { + + private static final List EVENTS = List.of(NOTIFY_LIP_APPLICANT_CLAIMANT_CONFIRM_TO_PROCEED); + + public static final String TASK_ID = "NotifyLiPApplicantClaimantConfirmToProceed"; + private static final String REFERENCE_TEMPLATE = "claimant-confirms-to-proceed-applicant-notification-%s"; + + private final NotificationService notificationService; + private final NotificationsProperties notificationsProperties; + + private final Map callbackMap = Map.of( + callbackKey(ABOUT_TO_SUBMIT), + this::notifyApplicantForClaimantConfirmsToProceed + ); + + @Override + protected Map callbacks() { + return callbackMap; + } + + @Override + public String camundaActivityId(CallbackParams callbackParams) { + return TASK_ID; + } + + @Override + public List handledEvents() { + return EVENTS; + } + + private CallbackResponse notifyApplicantForClaimantConfirmsToProceed(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + + if (caseData.getApplicant1Email() != null) { + notificationService.sendMail( + caseData.getApplicant1Email(), + notificationsProperties.getClaimantLipClaimUpdatedTemplate(), + addProperties(caseData), + String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) + ); + } + + return AboutToStartOrSubmitCallbackResponse.builder().build(); + } + + @Override + public Map addProperties(CaseData caseData) { + return Map.of( + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + APPLICANT_ONE_NAME, getPartyNameBasedOnType(caseData.getApplicant1()) + ); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedLiPRespondentNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedLiPRespondentNotificationHandler.java new file mode 100644 index 00000000000..73cfb5c570e --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedLiPRespondentNotificationHandler.java @@ -0,0 +1,73 @@ +package uk.gov.hmcts.reform.civil.handler.callback.camunda.notification; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.civil.callback.Callback; +import uk.gov.hmcts.reform.civil.callback.CallbackHandler; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; + +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOTIFY_LIP_RESPONDENT_CLAIMANT_CONFIRM_TO_PROCEED; +import static uk.gov.hmcts.reform.civil.utils.PartyUtils.getPartyNameBasedOnType; + +@Service +@RequiredArgsConstructor +public class ClaimantResponseConfirmsToProceedLiPRespondentNotificationHandler extends CallbackHandler + implements NotificationData { + + private static final List EVENTS = List.of(NOTIFY_LIP_RESPONDENT_CLAIMANT_CONFIRM_TO_PROCEED); + public static final String TASK_ID = "NotifyLiPRespondentClaimantConfirmToProceed"; + private static final String REFERENCE_TEMPLATE = "claimant-confirms-to-proceed-respondent-notification-%s"; + private final NotificationService notificationService; + private final NotificationsProperties notificationsProperties; + private final Map callbackMap = Map.of( + callbackKey(ABOUT_TO_SUBMIT), + this::notifyRespondentForClaimantConfirmsToProceed + ); + + private CallbackResponse notifyRespondentForClaimantConfirmsToProceed(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + if (Objects.nonNull(caseData.getRespondent1().getPartyEmail())) { + notificationService.sendMail( + caseData.getRespondent1().getPartyEmail(), + notificationsProperties.getRespondent1LipClaimUpdatedTemplate(), + addProperties(caseData), + String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) + ); + } + return AboutToStartOrSubmitCallbackResponse.builder().build(); + } + + @Override + protected Map callbacks() { + return callbackMap; + } + + @Override + public String camundaActivityId(CallbackParams callbackParams) { + return TASK_ID; + } + + @Override + public List handledEvents() { + return EVENTS; + } + + @Override + public Map addProperties(CaseData caseData) { + return Map.of( + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + RESPONDENT_NAME, getPartyNameBasedOnType(caseData.getRespondent1()) + ); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedRespondentNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedRespondentNotificationHandler.java index 68875305644..3f80be153d4 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedRespondentNotificationHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedRespondentNotificationHandler.java @@ -9,15 +9,20 @@ import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; -import uk.gov.hmcts.reform.civil.service.FeatureToggleService; +import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.SmallClaimMedicalLRspec; import uk.gov.hmcts.reform.civil.notify.NotificationService; -import uk.gov.hmcts.reform.civil.service.OrganisationService; +import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; import uk.gov.hmcts.reform.civil.prd.model.Organisation; +import uk.gov.hmcts.reform.civil.service.OrganisationService; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; +import java.util.stream.Stream; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIMANT_CONFIRMS_TO_PROCEED; @@ -48,7 +53,6 @@ public class ClaimantResponseConfirmsToProceedRespondentNotificationHandler exte private final NotificationService notificationService; private final NotificationsProperties notificationsProperties; private final OrganisationService organisationService; - private final FeatureToggleService featureToggleService; @Override protected Map callbacks() { @@ -72,7 +76,7 @@ public List handledEvents() { private CallbackResponse notifyRespondentSolicitorForClaimantConfirmsToProceed(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); - String template = null; + String template; var recipient = isCcNotification(callbackParams) ? caseData.getApplicantSolicitor1UserDetails().getEmail() : caseData.getRespondentSolicitor1EmailAddress(); @@ -92,7 +96,6 @@ private CallbackResponse notifyRespondentSolicitorForClaimantConfirmsToProceed(C } return AboutToStartOrSubmitCallbackResponse.builder().build(); } - if ((isRespondentSolicitor2Notification(callbackParams) && NO.equals(caseData.getApplicant1ProceedWithClaimAgainstRespondent2MultiParty1v2())) || (!isRespondentSolicitor2Notification(callbackParams) @@ -106,9 +109,7 @@ private CallbackResponse notifyRespondentSolicitorForClaimantConfirmsToProceed(C return AboutToStartOrSubmitCallbackResponse.builder().build(); } if (SPEC_CLAIM.equals(caseData.getCaseAccessCategory())) { - template = isCcNotification(callbackParams) - ? notificationsProperties.getClaimantSolicitorConfirmsToProceedSpec() - : notificationsProperties.getRespondentSolicitorNotifyToProceedSpec(); + template = getSpecTemplate(callbackParams, caseData); } else { template = notificationsProperties.getClaimantSolicitorConfirmsToProceed(); } @@ -126,6 +127,50 @@ private CallbackResponse notifyRespondentSolicitorForClaimantConfirmsToProceed(C return AboutToStartOrSubmitCallbackResponse.builder().build(); } + private String getSpecTemplate(CallbackParams callbackParams, CaseData caseData) { + String template; + if (isCcNotification(callbackParams)) { + if (rejectedAll(caseData) && mediationRejected(caseData)) { + template = notificationsProperties.getClaimantSolicitorConfirmsToProceedSpecWithAction(); + } else { + template = notificationsProperties.getClaimantSolicitorConfirmsToProceedSpec(); + } + } else { + if (rejectedAll(caseData) && mediationRejected(caseData)) { + template = notificationsProperties.getRespondentSolicitorNotifyToProceedSpecWithAction(); + } else { + template = notificationsProperties.getRespondentSolicitorNotifyToProceedSpec(); + } + } + return template; + } + + /** + * Consider that reject all is true if any respondent rejected all the claim. + * + * @param caseData the case data of a spec claim + * @return true if and only if at least one respondent rejected all the claim + */ + private boolean rejectedAll(CaseData caseData) { + return caseData.getRespondent1ClaimResponseTypeForSpec() == RespondentResponseTypeSpec.FULL_DEFENCE + || caseData.getRespondent2ClaimResponseTypeForSpec() == RespondentResponseTypeSpec.FULL_DEFENCE; + } + + /** + * Mediation is applicable only when all parties are willing to try it. + * + * @param caseData a spec claim + * @return true if and only if at least one party did not agree to mediation + */ + private boolean mediationRejected(CaseData caseData) { + return Stream.of( + caseData.getResponseClaimMediationSpecRequired(), + caseData.getResponseClaimMediationSpec2Required(), + Optional.ofNullable(caseData.getApplicant1ClaimMediationSpecRequired()) + .map(SmallClaimMedicalLRspec::getHasAgreedFreeMediation).orElse(null) + ).filter(Objects::nonNull).anyMatch(YesOrNo.NO::equals); + } + @Override public Map addProperties(CaseData caseData) { return Map.of( @@ -161,12 +206,12 @@ private boolean isRespondentSolicitor2Notification(CallbackParams callbackParams } //finding legal org name - private String getLegalOrganisationName(CaseData caseData, CaseEvent caseEvent) { + private String getLegalOrganisationName(CaseData caseData, CaseEvent caseEvent) { String organisationID; if (caseEvent.equals(NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIMANT_CONFIRMS_TO_PROCEED_CC)) { organisationID = caseData.getApplicant1OrganisationPolicy().getOrganisation().getOrganisationID(); } else { - organisationID = caseEvent.equals(NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIMANT_CONFIRMS_TO_PROCEED) + organisationID = caseEvent.equals(NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIMANT_CONFIRMS_TO_PROCEED) ? caseData.getRespondent1OrganisationPolicy().getOrganisation().getOrganisationID() : caseData.getRespondent2OrganisationPolicy().getOrganisation().getOrganisationID(); } @@ -178,7 +223,8 @@ private String getLegalOrganisationName(CaseData caseData, CaseEvent caseEvent) private boolean isLRvLipToDefendant(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); return SPEC_CLAIM.equals(caseData.getCaseAccessCategory()) - && caseData.isLRvLipOneVOne() + && (caseData.isLRvLipOneVOne() + || caseData.isLipvLipOneVOne()) && !isCcNotification(callbackParams); } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseNotAgreedRepaymentDefendantLipNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseNotAgreedRepaymentDefendantLipNotificationHandler.java index ab487f9b876..86c0bb6a239 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseNotAgreedRepaymentDefendantLipNotificationHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseNotAgreedRepaymentDefendantLipNotificationHandler.java @@ -8,13 +8,14 @@ import uk.gov.hmcts.reform.civil.callback.CallbackHandler; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; -import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.notify.NotificationService; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; +import uk.gov.hmcts.reform.civil.service.OrganisationDetailsService; import java.util.List; import java.util.Map; +import java.util.Objects; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.utils.PartyUtils.getPartyNameBasedOnType; @@ -25,6 +26,7 @@ public class ClaimantResponseNotAgreedRepaymentDefendantLipNotificationHandler e private final NotificationService notificationService; private final NotificationsProperties notificationsProperties; + private final OrganisationDetailsService organisationDetailsService; private static final List EVENTS = List.of(CaseEvent.NOTIFY_LIP_DEFENDANT_REJECT_REPAYMENT); private static final String REFERENCE_TEMPLATE_LIP = "claimant-reject-repayment-respondent-notification-%s"; public static final String TASK_ID_LIP = "ClaimantDisAgreedRepaymentPlanNotifyLip"; @@ -43,15 +45,15 @@ public String camundaActivityId(CallbackParams callbackParams) { private CallbackResponse notifyDefendantLip(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); - if (isRespondentNotRepresented(caseData) && caseData.getRespondent1().getPartyEmail() != null) { + if (Objects.nonNull(caseData.getRespondent1Email())) { notificationService.sendMail( - addEmail(caseData), + caseData.getRespondent1Email(), addTemplate(caseData), addProperties(caseData), - String.format(REFERENCE_TEMPLATE_LIP, caseData.getLegacyCaseReference())); + String.format(REFERENCE_TEMPLATE_LIP, caseData.getLegacyCaseReference()) + ); } return AboutToStartOrSubmitCallbackResponse.builder().build(); - } @Override @@ -61,32 +63,30 @@ public List handledEvents() { @Override public Map addProperties(CaseData caseData) { - - if (isRespondentNotRepresented(caseData)) { + if (caseData.isRespondent1NotRepresented()) { return Map.of( CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), DEFENDANT_NAME, getPartyNameBasedOnType(caseData.getRespondent1()) ); } - return null; + return Map.of( + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + CLAIM_LEGAL_ORG_NAME_SPEC, organisationDetailsService.getRespondentLegalOrganizationName(caseData) + ); + } - private String addEmail(CaseData caseData) { - if (isRespondentNotRepresented(caseData)) { - return caseData.getRespondent1().getPartyEmail(); + private String addTemplate(CaseData caseData) { + if (caseData.isRespondent1NotRepresented()) { + return getRespondentLipTemplate(caseData); } - return null; + return notificationsProperties.getNotifyDefendantLrTemplate(); } - private String addTemplate(CaseData caseData) { + private String getRespondentLipTemplate(CaseData caseData) { if (caseData.isRespondentResponseBilingual()) { return notificationsProperties.getNotifyDefendantLipWelshTemplate(); - } else { - return notificationsProperties.getNotifyDefendantLipTemplate(); } - } - - public boolean isRespondentNotRepresented(CaseData caseData) { - return YesOrNo.NO.equals(caseData.getSpecRespondent1Represented()); + return notificationsProperties.getNotifyDefendantLipTemplate(); } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateClaimRespondentNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateClaimRespondentNotificationHandler.java index adade9c1a72..7f8ffaff36d 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateClaimRespondentNotificationHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateClaimRespondentNotificationHandler.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; @@ -26,6 +27,7 @@ import static uk.gov.hmcts.reform.civil.utils.PartyUtils.buildPartiesReferences; import static uk.gov.hmcts.reform.civil.utils.PartyUtils.getPartyNameBasedOnType; +@Slf4j @Service @RequiredArgsConstructor public class CreateClaimRespondentNotificationHandler extends CallbackHandler implements NotificationData { @@ -109,7 +111,15 @@ private CallbackResponse notifyARespondentSolicitorForClaimIssue(CallbackParams throw new CallbackException(String.format("Callback handler received illegal event: %s", caseEvent)); } - sendNotificationToSolicitor(caseData, recipient); + if (recipient != null) { + sendNotificationToSolicitor(caseData, recipient); + } else { + log.info(String.format( + "Email address is null for caseEvent: %s for: %s", + caseEvent, + caseData.getLegacyCaseReference() + )); + } return AboutToStartOrSubmitCallbackResponse.builder() .data(caseData.toMap(objectMapper)) diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDOApplicantsNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDOApplicantsNotificationHandler.java index 2d0436508a2..7c69a19f9fe 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDOApplicantsNotificationHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDOApplicantsNotificationHandler.java @@ -12,6 +12,7 @@ import uk.gov.hmcts.reform.civil.enums.CaseCategory; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.OrganisationService; import uk.gov.hmcts.reform.civil.prd.model.Organisation; @@ -34,6 +35,7 @@ public class CreateSDOApplicantsNotificationHandler extends CallbackHandler impl private final NotificationService notificationService; private final NotificationsProperties notificationsProperties; private final OrganisationService organisationService; + private final FeatureToggleService featureToggleService; @Override protected Map callbacks() { @@ -55,11 +57,17 @@ public List handledEvents() { private CallbackResponse notifyApplicantsSolicitorSDOTriggered(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); + String unspecTemplate = featureToggleService.isEarlyAdoptersEnabled() + ? notificationsProperties.getSdoOrderedEA() : notificationsProperties.getSdoOrdered(); + + String specTemplate = featureToggleService.isEarlyAdoptersEnabled() + ? notificationsProperties.getSdoOrderedSpecEA() : notificationsProperties.getSdoOrderedSpec(); + notificationService.sendMail( caseData.getApplicantSolicitor1UserDetails().getEmail(), caseData.getCaseAccessCategory() == CaseCategory.SPEC_CLAIM - ? notificationsProperties.getSdoOrderedSpec() - : notificationsProperties.getSdoOrdered(), + ? specTemplate + : unspecTemplate, addProperties(caseData), String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) ); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent1LRNotificationSender.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent1LRNotificationSender.java index 0eb6774a5b7..27679b3dd3b 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent1LRNotificationSender.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent1LRNotificationSender.java @@ -4,6 +4,7 @@ import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.notify.NotificationService; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.OrganisationService; /** @@ -18,8 +19,9 @@ public class CreateSDORespondent1LRNotificationSender extends AbstractCreateSDOR public CreateSDORespondent1LRNotificationSender( NotificationService notificationService, NotificationsProperties notificationsProperties, - OrganisationService organisationService) { - super(notificationService, notificationsProperties, organisationService); + OrganisationService organisationService, + FeatureToggleService featureToggleService) { + super(notificationService, notificationsProperties, organisationService, featureToggleService); } @Override diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent1LiPNotificationSender.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent1LiPNotificationSender.java index 7ce54d7a3c8..1f6649094d7 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent1LiPNotificationSender.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent1LiPNotificationSender.java @@ -4,6 +4,7 @@ import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.notify.NotificationService; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; /** * When an SDO is created it is notified to applicants and defendants. @@ -16,8 +17,9 @@ public class CreateSDORespondent1LiPNotificationSender extends AbstractCreateSDO public CreateSDORespondent1LiPNotificationSender( NotificationService notificationService, - NotificationsProperties notificationsProperties) { - super(notificationService, notificationsProperties); + NotificationsProperties notificationsProperties, + FeatureToggleService featureToggleService) { + super(notificationService, notificationsProperties, featureToggleService); } @Override diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent2LRNotificationSender.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent2LRNotificationSender.java index edb0ef81754..6a92c5e0558 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent2LRNotificationSender.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent2LRNotificationSender.java @@ -8,6 +8,7 @@ import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.notify.NotificationService; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.OrganisationService; import java.util.Optional; @@ -24,8 +25,9 @@ public class CreateSDORespondent2LRNotificationSender extends AbstractCreateSDOR public CreateSDORespondent2LRNotificationSender( NotificationService notificationService, NotificationsProperties notificationsProperties, - OrganisationService organisationService) { - super(notificationService, notificationsProperties, organisationService); + OrganisationService organisationService, + FeatureToggleService featureToggleService) { + super(notificationService, notificationsProperties, organisationService, featureToggleService); } @Override diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent2LiPNotificationSender.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent2LiPNotificationSender.java index 248ba30ee12..cbeb99613e9 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent2LiPNotificationSender.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent2LiPNotificationSender.java @@ -4,6 +4,7 @@ import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.notify.NotificationService; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; /** * When an SDO is created it is notified to applicants and defendants. @@ -16,8 +17,9 @@ public class CreateSDORespondent2LiPNotificationSender extends AbstractCreateSDO public CreateSDORespondent2LiPNotificationSender( NotificationService notificationService, - NotificationsProperties notificationsProperties) { - super(notificationService, notificationsProperties); + NotificationsProperties notificationsProperties, + FeatureToggleService featureToggleService) { + super(notificationService, notificationsProperties, featureToggleService); } @Override diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DJApplicantReceivedNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DJApplicantReceivedNotificationHandler.java index 43ea2b91599..abbfeeeb51d 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DJApplicantReceivedNotificationHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DJApplicantReceivedNotificationHandler.java @@ -11,6 +11,7 @@ import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.OrganisationService; import uk.gov.hmcts.reform.civil.prd.model.Organisation; @@ -37,6 +38,8 @@ public class DJApplicantReceivedNotificationHandler extends CallbackHandler impl private static final String REFERENCE_TEMPLATE_REQUESTED = "default-judgment-applicant-requested-notification-%s"; private String templateReference; + private final FeatureToggleService toggleService; + @Override protected Map callbacks() { return Map.of(callbackKey(ABOUT_TO_SUBMIT), this::notifyApplicantSolicitorDefaultJudgmentReceived); @@ -68,10 +71,15 @@ private String identifyTemplate(CaseData caseData) { template = notificationsProperties.getApplicantSolicitor1DefaultJudgmentRequested(); templateReference = REFERENCE_TEMPLATE_REQUESTED; } - if (ofNullable(caseData.getRespondent2()).isEmpty()) { + if (ofNullable(caseData.getRespondent2()).isEmpty() && !caseData.isLipvLipOneVOne()) { template = notificationsProperties.getApplicantSolicitor1DefaultJudgmentReceived(); templateReference = REFERENCE_TEMPLATE_RECEIVED; } + if (caseData.isLipvLipOneVOne() + && toggleService.isLipVLipEnabled()) { + template = notificationsProperties.getApplicantLiPDefaultJudgmentRequested(); + templateReference = REFERENCE_TEMPLATE_RECEIVED; + } return template; } @@ -106,7 +114,7 @@ private CallbackResponse notifyApplicantSolicitorDefaultJudgmentReceived(Callbac String.format(templateReference, caseData.getLegacyCaseReference()) ); } - if (ofNullable(caseData.getRespondent2()).isEmpty()) { + if (ofNullable(caseData.getRespondent2()).isEmpty() && !caseData.isLipvLipOneVOne()) { notificationService.sendMail( caseData.getApplicantSolicitor1UserDetails().getEmail(), identifyTemplate(caseData), @@ -114,6 +122,18 @@ private CallbackResponse notifyApplicantSolicitorDefaultJudgmentReceived(Callbac String.format(templateReference, caseData.getLegacyCaseReference()) ); } + + if (caseData.isLipvLipOneVOne() + && toggleService.isLipVLipEnabled()) { + notificationService.sendMail( + caseData.getApplicant1Email(), + identifyTemplate(caseData), + addLipvsLiPProperties(caseData), + String.format(templateReference, caseData.getLegacyCaseReference()) + ); + + } + return AboutToStartOrSubmitCallbackResponse.builder().build(); } @@ -128,6 +148,14 @@ DEFENDANT_NAME, getPartyNameBasedOnType(caseData.getRespondent1()) ); } + public Map addLipvsLiPProperties(CaseData caseData) { + return Map.of( + APPLICANT_ONE_NAME, getPartyNameBasedOnType(caseData.getApplicant1()), + CLAIM_NUMBER, caseData.getLegacyCaseReference(), + DEFENDANT_NAME, getPartyNameBasedOnType(caseData.getRespondent1()) + ); + } + public Map addProperties2(CaseData caseData) { return Map.of( LEGAL_ORG_APPLICANT1, getLegalOrganizationName(caseData.getApplicant1OrganisationPolicy() diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DJRespondentReceivedNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DJRespondentReceivedNotificationHandler.java index ddcdf9fe75a..183977493c0 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DJRespondentReceivedNotificationHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DJRespondentReceivedNotificationHandler.java @@ -64,7 +64,7 @@ public String camundaActivityId(CallbackParams callbackParams) { private EmailTemplateReference identifyTemplate(CaseData caseData) { EmailTemplateReference emailTemplate = new EmailTemplateReference(); - if (caseData.isLRvLipOneVOne()) { + if (caseData.isLRvLipOneVOne() || (caseData.isLipvLipOneVOne() && toggleService.isLipVLipEnabled())) { emailTemplate.template = notificationsProperties.getRespondent1DefaultJudgmentRequestedTemplate(); emailTemplate.templateReference = REFERENCE_TEMPLATE_REQUESTED; return emailTemplate; @@ -93,7 +93,7 @@ private EmailTemplateReference identifyTemplate(CaseData caseData) { private CallbackResponse notifyRespondentSolicitorDefaultJudgmentReceived(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); EmailTemplateReference emailTemplate = identifyTemplate(caseData); - if (caseData.isLRvLipOneVOne() + if ((caseData.isLRvLipOneVOne() || (caseData.isLipvLipOneVOne() && toggleService.isLipVLipEnabled())) && toggleService.isPinInPostEnabled() && V_1.equals(callbackParams.getVersion())) { if (caseData.getRespondent1().getPartyEmail() != null) { diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantClaimDetailsNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantClaimDetailsNotificationHandler.java index 58a066e02e8..488e5641b28 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantClaimDetailsNotificationHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantClaimDetailsNotificationHandler.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; @@ -10,6 +11,7 @@ import uk.gov.hmcts.reform.civil.callback.CallbackHandler; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.config.ToggleConfiguration; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.common.DynamicList; @@ -29,6 +31,7 @@ import static uk.gov.hmcts.reform.civil.helpers.DateFormatHelper.formatLocalDate; import static uk.gov.hmcts.reform.civil.utils.PartyUtils.buildPartiesReferences; +@Slf4j @Service @RequiredArgsConstructor public class DefendantClaimDetailsNotificationHandler extends CallbackHandler implements NotificationData { @@ -49,6 +52,7 @@ public class DefendantClaimDetailsNotificationHandler extends CallbackHandler im private final NotificationsProperties notificationsProperties; private final ObjectMapper objectMapper; private final DeadlinesCalculator deadlinesCalculator; + private final ToggleConfiguration toggleConfiguration; @Override protected Map callbacks() { @@ -79,16 +83,25 @@ public List handledEvents() { private CallbackResponse notifyRespondentSolicitorForClaimDetails(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); + caseData.setFeatureToggleWA(toggleConfiguration.getFeatureToggle()); CaseEvent caseEvent = CaseEvent.valueOf(callbackParams.getRequest().getEventId()); String recipient = getRecipientEmail(caseData, caseEvent); String emailTemplate = notificationsProperties.getRespondentSolicitorClaimDetailsEmailTemplate(); - notificationService.sendMail( - recipient, - emailTemplate, - addProperties(caseData), - String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) - ); + if (recipient != null) { + notificationService.sendMail( + recipient, + emailTemplate, + addProperties(caseData), + String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) + ); + } else { + log.info(String.format( + "Email address is null for caseEvent: %s for: %s", + caseEvent, + caseData.getLegacyCaseReference() + )); + } return AboutToStartOrSubmitCallbackResponse.builder() .data(caseData.toMap(objectMapper)) diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantResponseApplicantNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantResponseApplicantNotificationHandler.java index b047d927cf9..cf52061b65c 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantResponseApplicantNotificationHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantResponseApplicantNotificationHandler.java @@ -33,7 +33,9 @@ import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.ONE_V_TWO_TWO_LEGAL_REP; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.TWO_V_ONE; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.getMultiPartyScenario; +import static uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec.BY_SET_DATE; import static uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec.IMMEDIATELY; +import static uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec.SUGGESTION_OF_REPAYMENT_PLAN; import static uk.gov.hmcts.reform.civil.utils.PartyUtils.buildPartiesReferences; import static uk.gov.hmcts.reform.civil.utils.PartyUtils.getPartyNameBasedOnType; @@ -159,7 +161,11 @@ private void sendNotificationToSolicitorSpec(CaseData caseData, String recipient String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) ); } else if (caseEvent.equals(NOTIFY_APPLICANT_SOLICITOR1_FOR_DEFENDANT_RESPONSE_CC)) { - emailTemplate = notificationsProperties.getRespondentSolicitorDefendantResponseForSpec(); + if (MultiPartyScenario.getMultiPartyScenario(caseData).equals(ONE_V_TWO_TWO_LEGAL_REP)) { + emailTemplate = notificationsProperties.getRespondentSolicitorDefendantResponseForSpec(); + } else { + emailTemplate = getTemplateForSpecOtherThan1v2DS(caseData); + } if (caseData.getRespondent1ResponseDate() == null || !MultiPartyScenario.getMultiPartyScenario(caseData) .equals(ONE_V_TWO_TWO_LEGAL_REP)) { notificationService.sendMail( @@ -171,7 +177,11 @@ private void sendNotificationToSolicitorSpec(CaseData caseData, String recipient } } else { - emailTemplate = notificationsProperties.getRespondentSolicitorDefendantResponseForSpec(); + if (MultiPartyScenario.getMultiPartyScenario(caseData).equals(ONE_V_TWO_TWO_LEGAL_REP)) { + emailTemplate = notificationsProperties.getRespondentSolicitorDefendantResponseForSpec(); + } else { + emailTemplate = getTemplateForSpecOtherThan1v2DS(caseData); + } notificationService.sendMail( recipient, emailTemplate, @@ -181,6 +191,23 @@ private void sendNotificationToSolicitorSpec(CaseData caseData, String recipient } } + private String getTemplateForSpecOtherThan1v2DS(CaseData caseData) { + + String emailTemplate; + if ((caseData.getDefenceAdmitPartPaymentTimeRouteRequired() == IMMEDIATELY + || caseData.getDefenceAdmitPartPaymentTimeRouteRequired() == BY_SET_DATE + || caseData.getDefenceAdmitPartPaymentTimeRouteRequired() == SUGGESTION_OF_REPAYMENT_PLAN) + && + (RespondentResponseTypeSpec.PART_ADMISSION.equals(caseData.getRespondent1ClaimResponseTypeForSpec())) + ) { + emailTemplate = notificationsProperties.getRespondentSolicitorDefResponseSpecWithClaimantAction(); + } else { + emailTemplate = notificationsProperties.getRespondentSolicitorDefendantResponseForSpec(); + } + + return emailTemplate; + } + @Override public Map addProperties(CaseData caseData) { if (getMultiPartyScenario(caseData).equals(ONE_V_ONE) || getMultiPartyScenario(caseData).equals(TWO_V_ONE)) { @@ -216,10 +243,10 @@ public Map addPropertiesSpec(CaseData caseData, CaseEvent caseEv + " " + caseData.getRespondToClaimAdmitPartLRspec().getWhenWillThisAmountBePaid().getMonth() + " " + caseData.getRespondToClaimAdmitPartLRspec().getWhenWillThisAmountBePaid().getYear(); return Map.of( - CLAIM_LEGAL_ORG_NAME_SPEC, getLegalOrganisationName(caseData, caseEvent), - CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), - RESPONDENT_NAME, getPartyNameBasedOnType(caseData.getApplicant1()), - WHEN_WILL_BE_PAID_IMMEDIATELY, shouldBePaidBy + CLAIM_LEGAL_ORG_NAME_SPEC, getLegalOrganisationName(caseData, caseEvent), + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + RESPONDENT_NAME, getPartyNameBasedOnType(caseData.getApplicant1()), + WHEN_WILL_BE_PAID_IMMEDIATELY, shouldBePaidBy ); } else { return Map.of( diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotificationClaimantOfHearingHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotificationClaimantOfHearingHandler.java index 59e5efc7365..8266182b1cb 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotificationClaimantOfHearingHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotificationClaimantOfHearingHandler.java @@ -19,7 +19,6 @@ import uk.gov.hmcts.reform.civil.service.hearingnotice.HearingNoticeCamundaService; import uk.gov.hmcts.reform.civil.service.hearings.HearingFeesService; -import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; @@ -126,8 +125,13 @@ public Map addProperties(final CaseData caseData) { && nonNull(caseData.getSolicitorReferences().getApplicantSolicitor1Reference())) { reference = caseData.getSolicitorReferences().getApplicantSolicitor1Reference(); } - map.put(HEARING_FEE, caseData.getHearingFee() == null ? "£0.00" : String.valueOf(caseData.getHearingFee().formData())); - map.put(HEARING_DUE_DATE, caseData.getHearingDueDate() == null ? "" : NotificationUtils.getFormattedHearingDate(caseData.getHearingDueDate())); + if (caseData.getHearingFeePaymentDetails() == null + || !SUCCESS.equals(caseData.getHearingFeePaymentDetails().getStatus())) { + map.put(HEARING_FEE, caseData.getHearingFee() == null + ? "£0.00" : String.valueOf(caseData.getHearingFee().formData())); + map.put(HEARING_DUE_DATE, caseData.getHearingDueDate() == null + ? "" : NotificationUtils.getFormattedHearingDate(caseData.getHearingDueDate())); + } map.put(CLAIMANT_REFERENCE_NUMBER, reference); } return map; @@ -151,10 +155,11 @@ private String getEmailTemplate(CaseData caseData, boolean isApplicantLip) { if (isApplicantLip) { return notificationsProperties.getHearingNotificationLipDefendantTemplate(); } - if (nonNull(caseData.getHearingFee()) && caseData.getHearingFee().getCalculatedAmountInPence().compareTo(BigDecimal.ZERO) > 0) { - return notificationsProperties.getHearingListedFeeClaimantLrTemplate(); - } else { + if (caseData.getHearingFeePaymentDetails() != null + && SUCCESS.equals(caseData.getHearingFeePaymentDetails().getStatus())) { return notificationsProperties.getHearingListedNoFeeClaimantLrTemplate(); + } else { + return notificationsProperties.getHearingListedFeeClaimantLrTemplate(); } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotificationData.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotificationData.java index d55b1b7339b..811456c2cc9 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotificationData.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotificationData.java @@ -84,6 +84,9 @@ public interface NotificationData { String OTHER_SOL_NAME = "other solicitor name"; String EXTERNAL_ID = "externalId"; + // evidence upload + String UPLOADED_DOCUMENTS = "uploaded documents"; + Map addProperties(CaseData caseData); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotifyClaimantClaimSubmitted.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotifyClaimantClaimSubmitted.java new file mode 100644 index 00000000000..5904bcff271 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotifyClaimantClaimSubmitted.java @@ -0,0 +1,78 @@ +package uk.gov.hmcts.reform.civil.handler.callback.camunda.notification; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.civil.callback.Callback; +import uk.gov.hmcts.reform.civil.callback.CallbackHandler; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; + +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.utils.PartyUtils.getPartyNameBasedOnType; + +@Service +@RequiredArgsConstructor +public class NotifyClaimantClaimSubmitted extends CallbackHandler implements NotificationData { + + private static final List EVENTS = List.of(CaseEvent.NOTIFY_APPLICANT1_CLAIM_SUBMITTED); + public static final String TASK_ID_Applicant1 = "NotifyApplicant1ClaimSubmitted"; + private static final String REFERENCE_TEMPLATE = "claim-submitted-notification-%s"; + private final NotificationService notificationService; + private final NotificationsProperties notificationsProperties; + private final Map callBackMap = Map.of( + callbackKey(ABOUT_TO_SUBMIT), this::notifyApplicantForClaimSubmitted + ); + + @Override + protected Map callbacks() { + return callBackMap; + } + + @Override + public String camundaActivityId(CallbackParams callbackParams) { + return TASK_ID_Applicant1; + } + + private CallbackResponse notifyApplicantForClaimSubmitted(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + + if (Objects.isNull(caseData.getHelpWithFeesReferenceNumber())) { + generateEmail(caseData); + } + + return AboutToStartOrSubmitCallbackResponse.builder() + .build(); + } + + @Override + public List handledEvents() { + return EVENTS; + } + + @Override + public Map addProperties(CaseData caseData) { + return Map.of( + CLAIMANT_NAME, getPartyNameBasedOnType(caseData.getApplicant1()) + ); + } + + private void generateEmail(CaseData caseData) { + if (Objects.nonNull(caseData.getApplicant1Email())) { + notificationService.sendMail( + caseData.getApplicant1Email(), + notificationsProperties.getNotifyLiPClaimantClaimSubmittedAndPayClaimFeeTemplate(), + addProperties(caseData), + String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) + ); + } + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotifyLIPDefendantClaimantSettleTheClaim.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotifyLIPDefendantClaimantSettleTheClaim.java new file mode 100644 index 00000000000..9d7250cce0c --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotifyLIPDefendantClaimantSettleTheClaim.java @@ -0,0 +1,74 @@ +package uk.gov.hmcts.reform.civil.handler.callback.camunda.notification; + +import lombok.RequiredArgsConstructor; +import org.apache.commons.lang.StringUtils; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.civil.callback.Callback; +import uk.gov.hmcts.reform.civil.callback.CallbackHandler; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOTIFY_DEFENDANT_CLAIMANT_SETTLE_THE_CLAIM; + +@Service +@RequiredArgsConstructor +public class NotifyLIPDefendantClaimantSettleTheClaim extends CallbackHandler implements NotificationData { + + private final NotificationService notificationService; + private final NotificationsProperties notificationsProperties; + private static final String REFERENCE_TEMPLATE = "notify-defendant-claimant-settle-the-claim-notification-%s"; + public static final String TASK_ID = "NotifyDefendantClaimantSettleTheClaim"; + private final Map callbackMap = Map.of( + callbackKey(ABOUT_TO_SUBMIT), this::notifyDefendantLIP + ); + + @Override + protected Map callbacks() { + return callbackMap; + } + + @Override + public String camundaActivityId(CallbackParams callbackParams) { + return TASK_ID; + } + + private CallbackResponse notifyDefendantLIP(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + + if (StringUtils.isNotEmpty(caseData.getRespondent1().getPartyEmail())) { + notificationService.sendMail( + caseData.getRespondent1().getPartyEmail(), + notificationsProperties.getNotifyDefendantLIPClaimantSettleTheClaimTemplate(), + addProperties(caseData), + String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) + ); + } + return AboutToStartOrSubmitCallbackResponse.builder().build(); + } + + @Override + public List handledEvents() { + return Collections.singletonList( + NOTIFY_DEFENDANT_CLAIMANT_SETTLE_THE_CLAIM + ); + } + + @Override + public Map addProperties(CaseData caseData) { + return Map.of( + RESPONDENT_NAME, caseData.getRespondent1().getPartyName(), + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + CLAIMANT_NAME, caseData.getApplicant1().getPartyName() + ); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ResponseDeadlineExtensionClaimantNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ResponseDeadlineExtensionClaimantNotificationHandler.java index d531ac5c227..983b12b5b1d 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ResponseDeadlineExtensionClaimantNotificationHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ResponseDeadlineExtensionClaimantNotificationHandler.java @@ -8,9 +8,11 @@ import uk.gov.hmcts.reform.civil.callback.CallbackHandler; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.config.PinInPostConfiguration; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.OrganisationService; import uk.gov.hmcts.reform.civil.prd.model.Organisation; @@ -39,6 +41,8 @@ public class ResponseDeadlineExtensionClaimantNotificationHandler private final NotificationService notificationService; private final NotificationsProperties notificationsProperties; private final OrganisationService organisationService; + private final FeatureToggleService toggleService; + private final PinInPostConfiguration pipInPostConfiguration; @Override protected Map callbacks() { @@ -61,8 +65,8 @@ private CallbackResponse notifyClaimantForDeadlineExtension(CallbackParams callb CaseData caseData = callbackParams.getCaseData(); notificationService.sendMail( - caseData.getApplicantSolicitor1UserDetails().getEmail(), - notificationsProperties.getClaimantDeadlineExtension(), + getEmail(caseData), + getTemplate(caseData), addProperties(caseData), String.format(REFERENCE_TEMPLATE, caseData.getLegacyCaseReference()) ); @@ -72,6 +76,17 @@ private CallbackResponse notifyClaimantForDeadlineExtension(CallbackParams callb @Override public Map addProperties(CaseData caseData) { + if (caseData.isLipvLipOneVOne() && toggleService.isLipVLipEnabled()) { + return Map.of( + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + CLAIMANT_NAME, getPartyNameBasedOnType(caseData.getApplicant1()), + DEFENDANT_NAME, getPartyNameBasedOnType(caseData.getRespondent1()), + FRONTEND_URL, pipInPostConfiguration.getCuiFrontEndUrl(), + RESPONSE_DEADLINE, formatLocalDate( + caseData.getRespondent1ResponseDeadline().toLocalDate(), DATE + ) + ); + } return Map.of( CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), RESPONDENT_NAME, getPartyNameBasedOnType(caseData.getRespondent1()), @@ -88,4 +103,18 @@ public String getApplicantLegalOrganizationName(CaseData caseData) { return organisation.isPresent() ? organisation.get().getName() : caseData.getApplicantSolicitor1ClaimStatementOfTruth().getName(); } + + private String getTemplate(CaseData caseData) { + if (caseData.isLipvLipOneVOne() && toggleService.isLipVLipEnabled()) { + return notificationsProperties.getClaimantLipDeadlineExtension(); + } + return notificationsProperties.getClaimantDeadlineExtension(); + } + + private String getEmail(CaseData caseData) { + if (caseData.isLipvLipOneVOne() && toggleService.isLipVLipEnabled()) { + return caseData.getApplicant1Email(); + } + return caseData.getApplicantSolicitor1UserDetails().getEmail(); + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/AcknowledgeClaimCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/AcknowledgeClaimCallbackHandler.java index 934fa3e8c4d..9d9097e0e2c 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/AcknowledgeClaimCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/AcknowledgeClaimCallbackHandler.java @@ -175,6 +175,7 @@ private CallbackResponse setNewResponseDeadline(CallbackParams callbackParams) { var updatedRespondent1 = caseData.getRespondent1().toBuilder() .primaryAddress(caseData.getRespondent1Copy().getPrimaryAddress()) + .flags(caseData.getRespondent1Copy().getFlags()) .build(); CaseData.CaseDataBuilder caseDataUpdated = caseData.toBuilder(); @@ -233,6 +234,7 @@ && respondent2HasSameLegalRep(caseData)) { //1v2 same var updatedRespondent2 = caseData.getRespondent2().toBuilder() .primaryAddress(caseData.getRespondent2Copy().getPrimaryAddress()) + .flags(caseData.getRespondent2Copy().getFlags()) .build(); caseDataUpdated.respondent1AcknowledgeNotificationDate(time.now()) @@ -277,6 +279,7 @@ && respondent2HasSameLegalRep(caseData)) { && respondent1Check.equals(NO) && !respondent2HasSameLegalRep(caseData)) { var updatedRespondent2 = caseData.getRespondent2Copy().toBuilder() .primaryAddress(caseData.getRespondent2Copy().getPrimaryAddress()) + .flags(caseData.getRespondent2Copy().getFlags()) .build(); //1v2 diff login 2 caseDataUpdated diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/AcknowledgeOfServiceCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/AcknowledgeOfServiceCallbackHandler.java index aa57495e51b..8d1d356ffd0 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/AcknowledgeOfServiceCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/AcknowledgeOfServiceCallbackHandler.java @@ -27,6 +27,7 @@ import java.util.Map; import static java.lang.String.format; +import static java.util.Optional.ofNullable; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; @@ -74,6 +75,12 @@ private CallbackResponse populateRespondent1Copy(CallbackParams callbackParams) var updatedCaseData = caseData.toBuilder() .respondent1Copy(caseData.getRespondent1()) .build(); + + ofNullable(caseData.getRespondent2()) + .ifPresent(r2 -> updatedCaseData.toBuilder() + .respondent2Copy(r2) + .respondent2DetailsForClaimDetailsTab(r2.toBuilder().flags(null).build()).build()); + List errors = new ArrayList<>(); var responseDedline = caseData.getRespondent1ResponseDeadline(); if (dateTime.toLocalDate().isAfter(responseDedline.toLocalDate())) { @@ -114,9 +121,10 @@ private CallbackResponse setNewResponseDeadline(CallbackParams callbackParams) { LocalDateTime newResponseDate = deadlinesCalculator.plus14DaysAt4pmDeadline(responseDeadline); var updatedRespondent1 = caseData.getRespondent1().toBuilder() .primaryAddress(caseData.getRespondent1Copy().getPrimaryAddress()) + .flags(caseData.getRespondent1Copy().getFlags()) .build(); - CaseData caseDataUpdated = caseData.toBuilder() + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder() .respondent1AcknowledgeNotificationDate(time.now()) .respondent1ResponseDeadline(newResponseDate) .businessProcess(BusinessProcess.ready(ACKNOWLEDGEMENT_OF_SERVICE)) @@ -125,11 +133,21 @@ private CallbackResponse setNewResponseDeadline(CallbackParams callbackParams) { .specRespondentCorrespondenceAddressRequired(caseData.getSpecAoSApplicantCorrespondenceAddressRequired()) .specRespondentCorrespondenceAddressdetails(caseData.getSpecAoSApplicantCorrespondenceAddressdetails()) .respondentSolicitor1ServiceAddressRequired(caseData.getSpecAoSRespondentCorrespondenceAddressRequired()) - .respondentSolicitor1ServiceAddress(caseData.getSpecAoSRespondentCorrespondenceAddressdetails()) - .build(); + .respondentSolicitor1ServiceAddress(caseData.getSpecAoSRespondentCorrespondenceAddressdetails()); + + // if present, persist the 2nd respondent address in the same fashion as above, i.e ignore for 1v1 + if (ofNullable(caseData.getRespondent2()).isPresent() + && ofNullable(caseData.getRespondent2Copy()).isPresent()) { + var updatedRespondent2 = caseData.getRespondent2().toBuilder() + .primaryAddress(caseData.getRespondent2Copy().getPrimaryAddress()) + .flags(caseData.getRespondent2Copy().getFlags()) + .build(); + caseDataBuilder.respondent2(updatedRespondent2).respondent2Copy(null); + caseDataBuilder.respondent2DetailsForClaimDetailsTab(updatedRespondent2.toBuilder().flags(null).build()); + } return AboutToStartOrSubmitCallbackResponse.builder() - .data(caseDataUpdated.toMap(objectMapper)) + .data(caseDataBuilder.build().toMap(objectMapper)) .build(); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/AddCaseNoteCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/AddCaseNoteCallbackHandler.java index faf0019315e..cd9c513d93c 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/AddCaseNoteCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/AddCaseNoteCallbackHandler.java @@ -56,7 +56,7 @@ private CallbackResponse moveNotesIntoList(CallbackParams callbackParams) { caseData.getCaseNote() ); - List> caseNotes = caseNoteService.addNoteToList(caseNote, caseData.getCaseNotes()); + List> caseNotes = caseNoteService.addNoteToListStart(caseNote, caseData.getCaseNotes()); CaseData updatedCaseData = caseData.toBuilder() .caseNotes(caseNotes) diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ChangeSolicitorEmailCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ChangeSolicitorEmailCallbackHandler.java index 84e15742259..aa1ffccf6c5 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ChangeSolicitorEmailCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ChangeSolicitorEmailCallbackHandler.java @@ -27,6 +27,7 @@ import uk.gov.hmcts.reform.idam.client.models.UserInfo; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; @@ -383,10 +384,16 @@ private CallbackResponse buildConfirmation(CallbackParams callbackParams) { } private List validateAddress(Address address) { - String postCode = Optional.ofNullable(address) - .map(Address::getPostCode) - .orElse(null); - return postcodeValidator.validate(postCode); + if (address != null) { + String postCode = address.getPostCode(); + if (StringUtils.isBlank(postCode)) { + // postcode validator is ok with null but not "" + postCode = null; + } + return postcodeValidator.validate(postCode); + } else { + return Collections.emptyList(); + } } private CallbackResponse validateApplicant1SolicitorEmail(CallbackParams callbackParams) { diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ClaimantResponseCuiCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ClaimantResponseCuiCallbackHandler.java index ee62053c41c..b42f274c8df 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ClaimantResponseCuiCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ClaimantResponseCuiCallbackHandler.java @@ -10,9 +10,13 @@ import uk.gov.hmcts.reform.civil.callback.CallbackHandler; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.enums.CaseState; import uk.gov.hmcts.reform.civil.model.BusinessProcess; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.service.citizenui.ResponseOneVOneShowTagService; +import uk.gov.hmcts.reform.civil.service.citizen.UpdateCaseManagementDetailsService; +import java.time.LocalDateTime; import java.util.Collections; import java.util.List; import java.util.Map; @@ -29,12 +33,15 @@ public class ClaimantResponseCuiCallbackHandler extends CallbackHandler { private static final List EVENTS = Collections.singletonList(CLAIMANT_RESPONSE_CUI); + private final ResponseOneVOneShowTagService responseOneVOneService; + private final ObjectMapper objectMapper; + private final UpdateCaseManagementDetailsService updateCaseManagementLocationDetailsService; @Override protected Map callbacks() { return Map.of( - callbackKey(ABOUT_TO_START), this::emptyCallbackResponse, + callbackKey(ABOUT_TO_START), this::populateCaseData, callbackKey(ABOUT_TO_SUBMIT), this::aboutToSubmit, callbackKey(SUBMITTED), this::emptySubmittedCallbackResponse ); @@ -45,14 +52,42 @@ public List handledEvents() { return EVENTS; } - private CallbackResponse aboutToSubmit(CallbackParams callbackParams) { - CaseData caseData = callbackParams.getCaseData(); - CaseData updatedData = caseData.toBuilder() - .businessProcess(BusinessProcess.ready(CLAIMANT_RESPONSE_CUI)) - .build(); + private CallbackResponse populateCaseData(CallbackParams callbackParams) { + var caseData = callbackParams.getCaseData(); + CaseData.CaseDataBuilder updatedCaseData = caseData.toBuilder(); + updatedCaseData.showResponseOneVOneFlag(responseOneVOneService.setUpOneVOneFlow(caseData)); + return AboutToStartOrSubmitCallbackResponse.builder() - .data(updatedData.toMap(objectMapper)) + .data(updatedCaseData.build().toMap(objectMapper)) .build(); } + private CallbackResponse aboutToSubmit(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .applicant1ResponseDate(LocalDateTime.now()) + .businessProcess(BusinessProcess.ready(CLAIMANT_RESPONSE_CUI)); + + updateCaseManagementLocationDetailsService.updateCaseManagementDetails(builder, callbackParams); + + CaseData updatedData = builder.build(); + AboutToStartOrSubmitCallbackResponse.AboutToStartOrSubmitCallbackResponseBuilder response = + AboutToStartOrSubmitCallbackResponse.builder() + .data(updatedData.toMap(objectMapper)); + + updateClaimEndState(response, updatedData); + + return response.build(); + } + + private void updateClaimEndState(AboutToStartOrSubmitCallbackResponse.AboutToStartOrSubmitCallbackResponseBuilder response, CaseData updatedData) { + if (updatedData.hasClaimantAgreedToFreeMediation()) { + response.state(CaseState.IN_MEDIATION.name()); + } else if (updatedData.hasApplicantRejectedRepaymentPlan() && updatedData.getRespondent1().isCompanyOROrganisation()) { + response.state(CaseState.PROCEEDS_IN_HERITAGE_SYSTEM.name()); + } else { + response.state(CaseState.JUDICIAL_REFERRAL.name()); + } + } + } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimCallbackHandler.java index b796643e4cd..2f19c71c23e 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimCallbackHandler.java @@ -4,6 +4,7 @@ import com.google.common.collect.ImmutableMap; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; @@ -15,6 +16,7 @@ import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; import uk.gov.hmcts.reform.civil.config.ClaimUrlsConfiguration; +import uk.gov.hmcts.reform.civil.config.ToggleConfiguration; import uk.gov.hmcts.reform.civil.enums.CaseCategory; import uk.gov.hmcts.reform.civil.enums.CaseState; import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; @@ -140,6 +142,7 @@ public class CreateClaimCallbackHandler extends CallbackHandler implements Parti private final CourtLocationUtils courtLocationUtils; private final AssignCategoryId assignCategoryId; private final CaseFlagsInitialiser caseFlagInitialiser; + private final ToggleConfiguration toggleConfiguration; private final String caseDocLocation = "/cases/case-details/%s#CaseDocuments"; @Value("${court-location.unspecified-claim.region-id}") @@ -181,6 +184,7 @@ private CallbackResponse startClaim(CallbackParams callbackParams) { caseDataBuilder .claimStarted(YES) + .featureToggleWA(toggleConfiguration.getFeatureToggle()) .courtLocation(CourtLocation.builder() .applicantPreferredCourtLocationList(courtLocationUtils.getLocationsFromList(locations)) .build()); @@ -355,8 +359,50 @@ private CallbackResponse resetStatementOfTruth(CallbackParams callbackParams) { .build(); } + private void clearOrganisationPolicyId(CaseData caseData, CaseData.CaseDataBuilder caseDataBuilder) { + if (YES.equals(caseData.getRespondent1Represented())) { + if (StringUtils.isBlank(caseData.getRespondent1OrganisationIDCopy())) { + String id = Optional.ofNullable(caseData.getRespondent1OrganisationPolicy()) + .map(OrganisationPolicy::getOrganisation) + .map(uk.gov.hmcts.reform.ccd.model.Organisation::getOrganisationID) + .orElse(null); + if (id != null) { + caseDataBuilder.respondent1OrganisationIDCopy(id); + } + } + + caseDataBuilder.respondent1OrganisationPolicy( + caseData + .getRespondent1OrganisationPolicy() + .toBuilder() + .organisation(uk.gov.hmcts.reform.ccd.model.Organisation.builder().build()) + .build() + ); + } + + if (NO.equals(caseData.getRespondent2SameLegalRepresentative()) && YES.equals(caseData.getRespondent2Represented())) { + if (StringUtils.isBlank(caseData.getRespondent2OrganisationIDCopy())) { + String id = Optional.ofNullable(caseData.getRespondent2OrganisationPolicy()) + .map(OrganisationPolicy::getOrganisation) + .map(uk.gov.hmcts.reform.ccd.model.Organisation::getOrganisationID) + .orElse(null); + if (id != null) { + caseDataBuilder.respondent2OrganisationIDCopy(id); + } + } + + caseDataBuilder.respondent2OrganisationPolicy( + caseData + .getRespondent2OrganisationPolicy() + .toBuilder() + .organisation(uk.gov.hmcts.reform.ccd.model.Organisation.builder().build()) + .build() + ); + } + } + private void addOrgPolicy2ForSameLegalRepresentative(CaseData caseData, CaseData.CaseDataBuilder caseDataBuilder) { - if (caseData.getRespondent2SameLegalRepresentative() == YES) { + if (YES.equals(caseData.getRespondent2SameLegalRepresentative())) { OrganisationPolicy.OrganisationPolicyBuilder organisationPolicy2Builder = OrganisationPolicy.builder(); OrganisationPolicy respondent1OrganisationPolicy = caseData.getRespondent1OrganisationPolicy(); @@ -365,7 +411,16 @@ private void addOrgPolicy2ForSameLegalRepresentative(CaseData caseData, CaseData .build(); organisationPolicy2Builder.orgPolicyCaseAssignedRole(RESPONDENTSOLICITORTWO.getFormattedName()); - caseDataBuilder.respondent2OrganisationPolicy(organisationPolicy2Builder.build()); + + caseDataBuilder.respondent2OrganisationPolicy( + organisationPolicy2Builder + .organisation(uk.gov.hmcts.reform.ccd.model.Organisation.builder().build()) + .build() + ); + + caseDataBuilder.respondent2OrganisationIDCopy( + caseData.getRespondent1OrganisationPolicy().getOrganisation().getOrganisationID() + ); } } @@ -379,6 +434,7 @@ private CallbackResponse submitClaim(CallbackParams callbackParams) { // second idam call is workaround for null pointer when hiding field in getIdamEmail callback CaseData.CaseDataBuilder dataBuilder = getSharedData(callbackParams); + clearOrganisationPolicyId(caseData, dataBuilder); addOrgPolicy2ForSameLegalRepresentative(caseData, dataBuilder); // temporarily remove respondent1OrgRegistered() for CIV-2659 @@ -409,7 +465,7 @@ private CallbackResponse submitClaim(CallbackParams callbackParams) { dataBuilder .uiStatementOfTruth(StatementOfTruth.builder().build()) .applicantSolicitor1ClaimStatementOfTruth(statementOfTruth) - .respondent1DetailsForClaimDetailsTab(caseData.getRespondent1()); + .respondent1DetailsForClaimDetailsTab(caseData.getRespondent1().toBuilder().flags(null).build()); // data for case list and unassigned list dataBuilder @@ -418,7 +474,7 @@ private CallbackResponse submitClaim(CallbackParams callbackParams) { .caseListDisplayDefendantSolicitorReferences(getAllDefendantSolicitorReferences(caseData)); if (ofNullable(caseData.getRespondent2()).isPresent()) { - dataBuilder.respondent2DetailsForClaimDetailsTab(caseData.getRespondent2()); + dataBuilder.respondent2DetailsForClaimDetailsTab(caseData.getRespondent2().toBuilder().flags(null).build()); } dataBuilder @@ -475,6 +531,7 @@ private CallbackResponse submitClaim(CallbackParams callbackParams) { assignParticularOfClaimCategoryIds(caseData); dataBuilder.caseNamePublic(CaseNameUtils.buildCaseNamePublic(caseData)); + caseFlagInitialiser.initialiseCaseFlags(CREATE_CLAIM, dataBuilder); dataBuilder.ccdState(CaseState.PENDING_CASE_ISSUED); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimLipCallBackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimLipCallBackHandler.java index d7ec202f9b5..6ef4866acea 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimLipCallBackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimLipCallBackHandler.java @@ -25,6 +25,7 @@ import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; import static uk.gov.hmcts.reform.civil.callback.CallbackVersion.V_1; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CREATE_LIP_CLAIM; import static uk.gov.hmcts.reform.civil.enums.CaseCategory.SPEC_CLAIM; @@ -46,6 +47,7 @@ protected Map callbacks() { .put(callbackKey(V_1, ABOUT_TO_START), this::lipClaimInitialState) .put(callbackKey(ABOUT_TO_SUBMIT), this::submitClaim) .put(callbackKey(V_1, ABOUT_TO_SUBMIT), this::submitClaim) + .put(callbackKey(SUBMITTED), this::emptySubmittedCallbackResponse) .build(); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimSpecCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimSpecCallbackHandler.java index 21fb140cca7..ffc3d2b47b4 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimSpecCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimSpecCallbackHandler.java @@ -14,6 +14,7 @@ import uk.gov.hmcts.reform.civil.callback.CallbackHandler; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.config.ToggleConfiguration; import uk.gov.hmcts.reform.civil.config.ClaimUrlsConfiguration; import uk.gov.hmcts.reform.civil.enums.CaseCategory; import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; @@ -173,6 +174,7 @@ public class CreateClaimSpecCallbackHandler extends CallbackHandler implements P private final FeatureToggleService toggleService; private final StateFlowEngine stateFlowEngine; private final CaseFlagsInitialiser caseFlagInitialiser; + private final ToggleConfiguration toggleConfiguration; private final String caseDocLocation = "/cases/case-details/%s#CaseDocuments"; @Value("${court-location.specified-claim.region-id}") @@ -446,10 +448,15 @@ private CallbackResponse submitClaim(CallbackParams callbackParams) { dataBuilder .caseManagementLocation(CaseLocationCivil.builder().region(regionId).baseLocation(epimmsId).build()) - .respondent1DetailsForClaimDetailsTab(caseData.getRespondent1()) + .respondent1DetailsForClaimDetailsTab(caseData.getRespondent1().toBuilder().flags(null).build()) .caseAccessCategory(CaseCategory.SPEC_CLAIM); - ofNullable(caseData.getRespondent2()).ifPresent(dataBuilder::respondent2DetailsForClaimDetailsTab); + if (ofNullable(caseData.getRespondent2()).isPresent()) { + dataBuilder.respondent2DetailsForClaimDetailsTab(caseData.getRespondent2().toBuilder().flags(null).build()); + } + + dataBuilder.caseAccessCategory(CaseCategory.SPEC_CLAIM); + dataBuilder.featureToggleWA(toggleConfiguration.getFeatureToggle()); //assign case management category to the case and caseNameHMCTSinternal dataBuilder.caseNameHmctsInternal(caseParticipants(caseData).toString()); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateSDOCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateSDOCallbackHandler.java index fb8df8c0f74..32770c5f47a 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateSDOCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateSDOCallbackHandler.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; @@ -13,30 +14,26 @@ import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; import uk.gov.hmcts.reform.civil.crd.model.CategorySearchResult; +import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.enums.CaseCategory; import uk.gov.hmcts.reform.civil.enums.YesOrNo; -import uk.gov.hmcts.reform.civil.enums.sdo.ClaimsTrack; +import uk.gov.hmcts.reform.civil.enums.sdo.DateToShowToggle; import uk.gov.hmcts.reform.civil.enums.sdo.DisposalHearingMethod; import uk.gov.hmcts.reform.civil.enums.sdo.FastTrackMethod; import uk.gov.hmcts.reform.civil.enums.sdo.FastTrackTrialBundleType; import uk.gov.hmcts.reform.civil.enums.sdo.HearingMethod; import uk.gov.hmcts.reform.civil.enums.sdo.OrderDetailsPagesSectionsToggle; import uk.gov.hmcts.reform.civil.enums.sdo.SmallClaimsMethod; -import uk.gov.hmcts.reform.civil.enums.sdo.DateToShowToggle; import uk.gov.hmcts.reform.civil.helpers.DateFormatHelper; import uk.gov.hmcts.reform.civil.helpers.LocationHelper; import uk.gov.hmcts.reform.civil.helpers.sdo.SdoHelper; -import uk.gov.hmcts.reform.civil.service.CategoryService; -import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.model.BusinessProcess; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.Party; import uk.gov.hmcts.reform.civil.model.common.DynamicList; import uk.gov.hmcts.reform.civil.model.common.DynamicListElement; import uk.gov.hmcts.reform.civil.model.common.Element; -import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.model.dq.RequestedCourt; -import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; import uk.gov.hmcts.reform.civil.model.sdo.DisposalHearingBundle; import uk.gov.hmcts.reform.civil.model.sdo.DisposalHearingDisclosureOfDocuments; import uk.gov.hmcts.reform.civil.model.sdo.DisposalHearingFinalDisposalHearing; @@ -73,15 +70,19 @@ import uk.gov.hmcts.reform.civil.model.sdo.SmallClaimsNotes; import uk.gov.hmcts.reform.civil.model.sdo.SmallClaimsRoadTrafficAccident; import uk.gov.hmcts.reform.civil.model.sdo.SmallClaimsWitnessStatement; +import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; +import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; +import uk.gov.hmcts.reform.civil.service.CategoryService; import uk.gov.hmcts.reform.civil.service.DeadlinesCalculator; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.docmosis.sdo.SdoGeneratorService; -import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; import uk.gov.hmcts.reform.civil.utils.AssignCategoryId; import uk.gov.hmcts.reform.civil.utils.HearingMethodUtils; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; +import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; @@ -97,10 +98,14 @@ import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; import static uk.gov.hmcts.reform.civil.callback.CallbackVersion.V_1; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CREATE_SDO; +import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; +import static uk.gov.hmcts.reform.civil.enums.sdo.OrderDetailsPagesSectionsToggle.SHOW; +import static uk.gov.hmcts.reform.civil.enums.sdo.OrderType.DISPOSAL; import static uk.gov.hmcts.reform.civil.helpers.DateFormatHelper.DATE; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.element; import static uk.gov.hmcts.reform.civil.utils.HearingUtils.getHearingNotes; +@Slf4j @Service @RequiredArgsConstructor public class CreateSDOCallbackHandler extends CallbackHandler { @@ -159,6 +164,7 @@ protected Map callbacks() { .put(callbackKey(V_1, ABOUT_TO_START), this::prePopulateOrderDetailsPages) .put(callbackKey(MID, "order-details-navigation"), this::setOrderDetailsFlags) .put(callbackKey(MID, "generate-sdo-order"), this::generateSdoOrder) + .put(callbackKey(MID, "validateInputValue"), this::validateInputValue) .put(callbackKey(V_1, MID, "generate-sdo-order"), this::generateSdoOrder) .put(callbackKey(ABOUT_TO_SUBMIT), this::submitSDO) .put(callbackKey(SUBMITTED), this::buildConfirmation) @@ -216,7 +222,7 @@ private CallbackResponse prePopulateOrderDetailsPages(CallbackParams callbackPar updatedData.fastTrackMethodInPerson(locationsList); updatedData.smallClaimsMethodInPerson(locationsList); - List checkList = List.of(OrderDetailsPagesSectionsToggle.SHOW); + List checkList = List.of(SHOW); setCheckList(updatedData, checkList); DisposalHearingJudgesRecital tempDisposalHearingJudgesRecital = DisposalHearingJudgesRecital.builder() @@ -708,17 +714,21 @@ private DynamicList getLocationList(CallbackParams callbackParams, )); DynamicList locationsList; if (matchingLocation.isPresent()) { - locationsList = DynamicList.fromList(locations, LocationRefDataService::getDisplayEntry, + locationsList = DynamicList.fromList(locations, this::getLocationEpimms, LocationRefDataService::getDisplayEntry, matchingLocation.get(), true ); } else { - locationsList = DynamicList.fromList(locations, LocationRefDataService::getDisplayEntry, + locationsList = DynamicList.fromList(locations, this::getLocationEpimms, LocationRefDataService::getDisplayEntry, null, true ); } return locationsList; } + private String getLocationEpimms(LocationRefData location) { + return location.getEpimmsId(); + } + private CallbackResponse setOrderDetailsFlags(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); CaseData.CaseDataBuilder updatedData = caseData.toBuilder(); @@ -729,9 +739,9 @@ private CallbackResponse setOrderDetailsFlags(CallbackParams callbackParams) { updatedData.setFastTrackFlag(YesOrNo.NO).build(); if (SdoHelper.isSmallClaimsTrack(caseData)) { - updatedData.setSmallClaimsFlag(YesOrNo.YES).build(); + updatedData.setSmallClaimsFlag(YES).build(); } else if (SdoHelper.isFastTrack(caseData)) { - updatedData.setFastTrackFlag(YesOrNo.YES).build(); + updatedData.setFastTrackFlag(YES).build(); } return AboutToStartOrSubmitCallbackResponse.builder() @@ -816,39 +826,11 @@ private String getHearingInPersonFast(CaseData caseData) { return null; } - private String getHearingInPersonLocation(CaseData caseData) { - if (caseData.getDrawDirectionsOrderRequired() == YesOrNo.YES) { - if (caseData.getDrawDirectionsOrderSmallClaims() == YesOrNo.YES) { - return getHearingInPersonSmall(caseData); - } else { - return getHearingInPersonFast(caseData); - } - } else if (caseData.getClaimsTrack() == ClaimsTrack.fastTrack) { - return getHearingInPersonFast(caseData); - } else if (caseData.getClaimsTrack() == ClaimsTrack.smallClaimsTrack) { - return getHearingInPersonSmall(caseData); - } else if (Optional.ofNullable(caseData.getDisposalHearingMethodToggle()) - .map(c -> c.contains(OrderDetailsPagesSectionsToggle.SHOW)).orElse(Boolean.FALSE) - && caseData.getDisposalHearingMethod() == DisposalHearingMethod.disposalHearingMethodInPerson - && Optional.ofNullable(caseData.getDisposalHearingMethodInPerson()) - .map(DynamicList::getValue).isPresent()) { - return caseData.getDisposalHearingMethodInPerson().getValue().getLabel(); - } - return null; - } - private CallbackResponse submitSDO(CallbackParams callbackParams) { CaseData.CaseDataBuilder dataBuilder = getSharedData(callbackParams); CaseData caseData = callbackParams.getCaseData(); - String hearingInPersonLocation = getHearingInPersonLocation(caseData); - locationRefDataService.getLocationMatchingLabel( - hearingInPersonLocation, - callbackParams.getParams().get(BEARER_TOKEN).toString() - ) - .ifPresent(locationRefData -> LocationHelper.updateWithLocation(dataBuilder, locationRefData)); - CaseDocument document = caseData.getSdoOrderDocument(); if (document != null) { List> generatedDocuments = callbackParams.getCaseData() @@ -861,11 +843,82 @@ private CallbackResponse submitSDO(CallbackParams callbackParams) { dataBuilder.hearingNotes(getHearingNotes(caseData)); + if (featureToggleService.isEarlyAdoptersEnabled()) { + if (featureToggleService.isLocationWhiteListedForCaseProgression( + getEpimmsId(caseData))) { + log.info("Case {} is whitelisted for case progression.", caseData.getCcdCaseReference()); + dataBuilder.eaCourtLocation(YES); + } else { + log.info("Case {} is NOT whitelisted for case progression.", caseData.getCcdCaseReference()); + dataBuilder.eaCourtLocation(YesOrNo.NO); + } + } + + System.out.println("before about to submit"); + return AboutToStartOrSubmitCallbackResponse.builder() .data(dataBuilder.build().toMap(objectMapper)) .build(); } + private String getEpimmsId(CaseData caseData) { + + if (caseData.getOrderType() != null && caseData.getOrderType().equals(DISPOSAL)) { + return caseData.getDisposalHearingMethodInPerson().getValue().getCode(); + } + if (SdoHelper.isFastTrack(caseData)) { + return caseData.getFastTrackMethodInPerson().getValue().getCode(); + } + if (SdoHelper.isSmallClaimsTrack(caseData)) { + return caseData.getSmallClaimsMethodInPerson().getValue().getCode(); + } + throw new IllegalArgumentException("Could not determine claim track"); + } + + private boolean nonNull(Object object) { + if (object != null) { + return true; + } else { + return false; + } + } + + private CallbackResponse validateInputValue(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + //CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + List errors = new ArrayList<>(); + if (nonNull(caseData.getSmallClaimsWitnessStatement())) { + String inputValue1 = caseData.getSmallClaimsWitnessStatement().getInput2(); + String inputValue2 = caseData.getSmallClaimsWitnessStatement().getInput3(); + if (validateNegativeWitness(errors, inputValue1, inputValue2)) { + return AboutToStartOrSubmitCallbackResponse.builder() + .errors(errors) + .build(); + } + } else if (nonNull(caseData.getFastTrackWitnessOfFact())) { + String inputValue1 = caseData.getFastTrackWitnessOfFact().getInput2(); + String inputValue2 = caseData.getFastTrackWitnessOfFact().getInput3(); + if (validateNegativeWitness(errors, inputValue1, inputValue2)) { + return AboutToStartOrSubmitCallbackResponse.builder() + .errors(errors) + .build(); + } + } + return generateSdoOrder(callbackParams); + } + + private boolean validateNegativeWitness(List errors, String inputValue1, String inputValue2) { + if (inputValue1 != null && inputValue2 != null) { + int number1 = Integer.parseInt(inputValue1); + int number2 = Integer.parseInt(inputValue2); + if (number1 < 0 || number2 < 0) { + errors.add("The number entered cannot be less than zero"); + return true; + } + } + return false; + } + private CaseData.CaseDataBuilder getSharedData(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); CaseData.CaseDataBuilder dataBuilder = caseData.toBuilder(); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/DefaultJudgementSpecHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/DefaultJudgementSpecHandler.java index e5b245cc629..773cd79c2d6 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/DefaultJudgementSpecHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/DefaultJudgementSpecHandler.java @@ -56,6 +56,8 @@ public class DefaultJudgementSpecHandler extends CallbackHandler { public static final String NOT_VALID_DJ = "The Claim is not eligible for Default Judgment until %s."; public static final String JUDGMENT_GRANTED_HEADER = "# Default Judgment Granted "; public static final String JUDGMENT_GRANTED = "
Download default judgment " + + "%n%n The defendant will be served with the Default Judgment."; + public static final String JUDGMENT_GRANTED_OLD = "
Download default judgment " + "%n%n The defendant will be served the Default Judgment."; public static final String JUDGMENT_REQUESTED_HEADER = "# Default judgment requested"; public static final String JUDGMENT_REQUESTED = "A default judgment has been sent to %s. " @@ -125,10 +127,17 @@ private String getBody(CaseData caseData) { .getLabel().startsWith("Both")) { return format(JUDGMENT_REQUESTED, caseData.getDefendantDetailsSpec().getValue().getLabel()); } else { - return format(JUDGMENT_GRANTED, format( - "/cases/case-details/%s#Claim documents", - caseData.getCcdCaseReference() - )); + if (caseData.getRespondent2() != null) { + return format(JUDGMENT_GRANTED_OLD, format( + "/cases/case-details/%s#Claim documents", + caseData.getCcdCaseReference() + )); + } else { + return format(JUDGMENT_GRANTED, format( + "/cases/case-details/%s#Claim documents", + caseData.getCcdCaseReference() + )); + } } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadHandlerBase.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadHandlerBase.java index 48d02d93648..5277c8351c6 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadHandlerBase.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadHandlerBase.java @@ -2,6 +2,7 @@ import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; @@ -44,6 +45,7 @@ import uk.gov.hmcts.reform.civil.utils.ElementUtils; import uk.gov.hmcts.reform.idam.client.models.UserInfo; +import static java.lang.String.format; import static java.util.Objects.nonNull; import static uk.gov.hmcts.reform.civil.callback.CallbackParams.Params.BEARER_TOKEN; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; @@ -115,23 +117,40 @@ abstract class EvidenceUploadHandlerBase extends CallbackHandler { protected static final String RESPONDENT_ONE_DISCLOSURE_LIST = "RespondentOneDisclosureList"; protected static final String RESPONDENT_ONE_PRE_TRIAL_SUMMARY = "RespondentOnePreTrialSummary"; protected static final String RESPONDENT_ONE_TRIAL_SKELETON = "RespondentOneTrialSkeleton"; - protected static final String RESPONDENT_ONE_TRIAL_AUTHORITIES = "RespondentOneTrialAuthorities"; - protected static final String RESPONDENT_ONE_TRIAL_COSTS = "respondentOneTrialCosts"; + protected static final String RESPONDENT_ONE_PRECEDENT_H = "RespondentOneUploadedPrecedentH"; protected static final String RESPONDENT_TWO_DISCLOSURE_LIST = "RespondentTwoDisclosureList"; protected static final String RESPONDENT_TWO_PRE_TRIAL_SUMMARY = "RespondentTwoPreTrialSummary"; protected static final String RESPONDENT_TWO_TRIAL_SKELETON = "RespondentTwoTrialSkeleton"; - protected static final String RESPONDENT_TWO_TRIAL_AUTHORITIES = "RespondentTwoTrialAuthorities"; - protected static final String RESPONDENT_TWO_TRIAL_COSTS = "respondentTwoTrialCosts"; + protected static final String RESPONDENT_TWO_PRECEDENT_H = "RespondentTwoUploadedPrecedentH"; + protected static final String RESPONDENT_ONE_SCHEDULE_OF_COSTS = "RespondentSchedulesOfCost"; + protected static final String RESPONDENT_TWO_SCHEDULE_OF_COSTS = "RespondentTwoSchedulesOfCost"; protected static final String APPLICANT_DISCLOSURE_LIST = "ApplicantDisclosureList"; protected static final String APPLICANT_PRE_TRIAL_SUMMARY = "ApplicantPreTrialSummary"; protected static final String APPLICANT_TRIAL_SKELETON = "ApplicantTrialSkeleton"; - protected static final String APPLICANT_TRIAL_AUTHORITIES = "ApplicantTrialAuthorities"; - protected static final String APPLICANT_TRIAL_COSTS = "ApplicantTrialCosts"; + protected static final String APPLICANT_PRECEDENT_H = "ApplicantUploadedPrecedentH"; protected static final String APPLICANT_TWO_DISCLOSURE_LIST = "ApplicantTwoDisclosureList"; protected static final String APPLICANT_TWO_PRE_TRIAL_SUMMARY = "ApplicantTwoPreTrialSummary"; protected static final String APPLICANT_TWO_TRIAL_SKELETON = "ApplicantTwoTrialSkeleton"; - protected static final String APPLICANT_TWO_TRIAL_AUTHORITIES = "ApplicantTwoTrialAuthorities"; - protected static final String APPLICANT_TWO_TRIAL_COSTS = "ApplicantTwoTrialCosts"; + protected static final String APPLICANT_TWO_PRECEDENT_H = "ApplicantTwoUploadedPrecedentH"; + protected static final String APPLICANT_SCHEDULE_OF_COSTS = "ApplicantSchedulesOfCost"; + protected static final String APPLICANT_TWO_SCHEDULE_OF_COSTS = "ApplicantTwoSchedulesOfCost"; + // Notification Strings used for email + protected static StringBuilder notificationString = new StringBuilder(); + protected static final String DISCLOSURE_LIST_TEXT = "%s - Disclosure list"; + protected static final String DISCLOSURE_TEXT = "%s - Documents for disclosure"; + protected static final String WITNESS_STATEMENT_TEXT = "%s - Witness statement"; + protected static final String WITNESS_SUMMARY_TEXT = "%s - Witness summary"; + protected static final String WITNESS_HEARSAY_TEXT = "%s - Notice of the intention to rely on hearsay evidence"; + protected static final String WITNESS_REFERRED_TEXT = "%s - Documents referred to in the statement"; + protected static final String EXPERT_REPORT_TEXT = "%s - Expert's report"; + protected static final String EXPERT_JOINT_STATEMENT_TEXT = "%s - Joint Statement of Experts / Single Joint Expert Report"; + protected static final String EXPERT_QUESTIONS_TEXT = "%s - Questions for other party's expert or joint experts"; + protected static final String EXPERT_ANSWERS_TEXT = "%s - Answer to questions asked"; + protected static final String PRE_TRIAL_SUMMARY_TEXT = "%s - Case Summary"; + protected static final String TRIAL_SKELETON_TEXT = "%s - Skeleton argument"; + protected static final String TRIAL_AUTHORITIES_TEXT = "%s - Authorities"; + protected static final String TRIAL_COSTS_TEXT = "%s - Costs"; + protected static final String TRIAL_DOC_CORRESPONDENCE_TEXT = "%s - Documentary evidence for trial"; protected static final String OPTION_APP1 = "Claimant 1 - "; protected static final String OPTION_APP2 = "Claimant 2 - "; @@ -166,8 +185,6 @@ protected EvidenceUploadHandlerBase(UserService userService, CoreCaseUserService abstract void applyDocumentUploadDate(CaseData.CaseDataBuilder caseDataBuilder, LocalDateTime now); - abstract void updateDocumentListUploadedAfterBundle(CaseData.CaseDataBuilder caseDataBuilder, CaseData caseData); - @Override public List handledEvents() { return events; @@ -208,6 +225,11 @@ CallbackResponse setOptions(CallbackParams callbackParams) { caseDataBuilder.caseProgAllocatedTrack(getAllocatedTrack(caseData.getClaimValue().toPounds(), caseData.getClaimType()).name()); } caseDataBuilder.evidenceUploadOptions(DynamicList.fromList(dynamicListOptions)); + // was unable to null value properly in EvidenceUploadNotificationEventHandler after emails are sent, + // so do it here if required. + if (nonNull(caseData.getNotificationText()) && caseData.getNotificationText().equals("NULLED")) { + caseDataBuilder.notificationText(null); + } return AboutToStartOrSubmitCallbackResponse.builder() .data(caseDataBuilder.build().toMap(objectMapper)) .build(); @@ -399,14 +421,23 @@ void checkDateCorrectness(Time time, List errors, List> d } public void setCategoryIdAndRenameDoc(List> documentUpload, Function, - Document> documentExtractor, String theID) { + Document> documentExtractor, String theID, String docNotificationText, Function, + LocalDateTime> documentDateTimeExtractor, String claimantDefendantString) { if (documentUpload == null || documentUpload.isEmpty()) { return; } + LocalDateTime midnight = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT); renameDocuments(documentUpload, theID); documentUpload.forEach(document -> { Document documentToAddId = documentExtractor.apply(document); documentToAddId.setCategoryID(theID); + LocalDateTime dateTime = documentDateTimeExtractor.apply(document); + if (dateTime.isAfter(midnight)) { + String updateNotificationText = format(docNotificationText, claimantDefendantString); + if (!notificationString.toString().contains(updateNotificationText)) { + notificationString.append("\n").append(updateNotificationText); + } + } }); } @@ -548,92 +579,175 @@ private void renameUploadEvidenceDocumentType(final List> documen }); } - CallbackResponse documentUploadTime(CallbackParams callbackParams) { - CaseData caseData = callbackParams.getCaseData(); - CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + static void getNotificationText(CaseData caseData) { + notificationString = new StringBuilder(); + if (caseData.getNotificationText() != null) { + notificationString = new StringBuilder(caseData.getNotificationText()); + } + } - String selectedRole = getSelectedRole(callbackParams); + abstract void updateDocumentListUploadedAfterBundle(CaseData.CaseDataBuilder caseDataBuilder, CaseData caseData); - applyDocumentUploadDate(caseDataBuilder, time.now()); + private void updateDocumentListUploadedAfterBundle(CaseData caseData, CaseData.CaseDataBuilder caseDataBuilder) { if (nonNull(caseData.getCaseBundles()) && !caseData.getCaseBundles().isEmpty()) { updateDocumentListUploadedAfterBundle(caseDataBuilder, caseData); } + } + + CallbackResponse documentUploadTime(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + // If notification has already been populated in current day, we want to append to that existing notification + getNotificationText(caseData); + applyDocumentUploadDate(caseDataBuilder, time.now()); + updateDocumentListUploadedAfterBundle(caseData, caseDataBuilder); + String selectedRole = getSelectedRole(callbackParams); if (selectedRole.equals(RESPONDENTSOLICITORONE.name()) || selectedRole.equals(SELECTED_VALUE_DEF_BOTH)) { - setCategoryIdAndRenameDoc(caseData.getDocumentDisclosureListRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_DISCLOSURE_LIST); - setCategoryIdAndRenameDoc(caseData.getDocumentForDisclosureRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_DISCLOSURE); - setCategoryIdAndRenameDoc(caseData.getDocumentWitnessStatementRes(), document -> document.getValue().getWitnessOptionDocument(), RESPONDENT_ONE_WITNESS_STATEMENT); - setCategoryIdAndRenameDoc(caseData.getDocumentWitnessSummaryRes(), document -> document.getValue().getWitnessOptionDocument(), RESPONDENT_ONE_WITNESS_SUMMARY); - setCategoryIdAndRenameDoc(caseData.getDocumentHearsayNoticeRes(), document -> document.getValue().getWitnessOptionDocument(), RESPONDENT_ONE_WITNESS_HEARSAY); - setCategoryIdAndRenameDoc(caseData.getDocumentReferredInStatementRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_WITNESS_REFERRED); - setCategoryIdAndRenameDoc(caseData.getDocumentExpertReportRes(), document -> document.getValue().getExpertDocument(), RESPONDENT_ONE_EXPERT_REPORT); - setCategoryIdAndRenameDoc(caseData.getDocumentJointStatementRes(), document -> document.getValue().getExpertDocument(), RESPONDENT_ONE_EXPERT_JOINT_STATEMENT); - setCategoryIdAndRenameDoc(caseData.getDocumentQuestionsRes(), document -> document.getValue().getExpertDocument(), RESPONDENT_ONE_EXPERT_QUESTIONS); - setCategoryIdAndRenameDoc(caseData.getDocumentAnswersRes(), document -> document.getValue().getExpertDocument(), RESPONDENT_ONE_EXPERT_ANSWERS); - setCategoryIdAndRenameDoc(caseData.getDocumentCaseSummaryRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_PRE_TRIAL_SUMMARY); - setCategoryIdAndRenameDoc(caseData.getDocumentSkeletonArgumentRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_TRIAL_SKELETON); - setCategoryIdAndRenameDoc(caseData.getDocumentAuthoritiesRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_TRIAL_AUTHORITIES); - setCategoryIdAndRenameDoc(caseData.getDocumentCostsRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_TRIAL_COSTS); - setCategoryIdAndRenameDoc(caseData.getDocumentEvidenceForTrialRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_TRIAL_DOC_CORRESPONDENCE); + String defendantString = "Defendant 1"; + if (selectedRole.equals(SELECTED_VALUE_DEF_BOTH)) { + defendantString = "Both defendants"; + } + setCategoryIdAndRenameDoc(caseData.getDocumentDisclosureListRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_DISCLOSURE_LIST, + DISCLOSURE_LIST_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentForDisclosureRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_DISCLOSURE, + DISCLOSURE_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentWitnessStatementRes(), document -> document.getValue().getWitnessOptionDocument(), RESPONDENT_ONE_WITNESS_STATEMENT, + WITNESS_STATEMENT_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentWitnessSummaryRes(), document -> document.getValue().getWitnessOptionDocument(), RESPONDENT_ONE_WITNESS_SUMMARY, + WITNESS_SUMMARY_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentHearsayNoticeRes(), document -> document.getValue().getWitnessOptionDocument(), RESPONDENT_ONE_WITNESS_HEARSAY, + WITNESS_HEARSAY_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentReferredInStatementRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_WITNESS_REFERRED, + WITNESS_REFERRED_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentExpertReportRes(), document -> document.getValue().getExpertDocument(), RESPONDENT_ONE_EXPERT_REPORT, + EXPERT_REPORT_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentJointStatementRes(), document -> document.getValue().getExpertDocument(), RESPONDENT_ONE_EXPERT_JOINT_STATEMENT, + EXPERT_JOINT_STATEMENT_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentQuestionsRes(), document -> document.getValue().getExpertDocument(), RESPONDENT_ONE_EXPERT_QUESTIONS, + EXPERT_QUESTIONS_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentAnswersRes(), document -> document.getValue().getExpertDocument(), RESPONDENT_ONE_EXPERT_ANSWERS, + EXPERT_ANSWERS_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentCaseSummaryRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_PRE_TRIAL_SUMMARY, + PRE_TRIAL_SUMMARY_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentSkeletonArgumentRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_TRIAL_SKELETON, + TRIAL_SKELETON_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentAuthoritiesRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_PRECEDENT_H, + TRIAL_AUTHORITIES_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentCostsRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_SCHEDULE_OF_COSTS, + TRIAL_COSTS_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentEvidenceForTrialRes(), document -> document.getValue().getDocumentUpload(), RESPONDENT_ONE_TRIAL_DOC_CORRESPONDENCE, + TRIAL_DOC_CORRESPONDENCE_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); if (selectedRole.equals(SELECTED_VALUE_DEF_BOTH)) { caseData = copyResp1ChangesToResp2(caseData, caseDataBuilder); } } if (selectedRole.equals(RESPONDENTSOLICITORTWO.name())) { - setCategoryIdAndRenameDoc(caseData.getDocumentDisclosureListRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_DISCLOSURE_LIST); - setCategoryIdAndRenameDoc(caseData.getDocumentForDisclosureRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_DISCLOSURE); - setCategoryIdAndRenameDoc(caseData.getDocumentWitnessStatementRes2(), document -> document.getValue().getWitnessOptionDocument(), RESPONDENT_TWO_WITNESS_STATEMENT); - setCategoryIdAndRenameDoc(caseData.getDocumentWitnessSummaryRes2(), document -> document.getValue().getWitnessOptionDocument(), RESPONDENT_TWO_WITNESS_SUMMARY); - setCategoryIdAndRenameDoc(caseData.getDocumentHearsayNoticeRes2(), document -> document.getValue().getWitnessOptionDocument(), RESPONDENT_TWO_WITNESS_HEARSAY); - setCategoryIdAndRenameDoc(caseData.getDocumentReferredInStatementRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_WITNESS_REFERRED); - setCategoryIdAndRenameDoc(caseData.getDocumentExpertReportRes2(), document -> document.getValue().getExpertDocument(), RESPONDENT_TWO_EXPERT_REPORT); - setCategoryIdAndRenameDoc(caseData.getDocumentJointStatementRes2(), document -> document.getValue().getExpertDocument(), RESPONDENT_TWO_EXPERT_JOINT_STATEMENT); - setCategoryIdAndRenameDoc(caseData.getDocumentQuestionsRes2(), document -> document.getValue().getExpertDocument(), RESPONDENT_TWO_EXPERT_QUESTIONS); - setCategoryIdAndRenameDoc(caseData.getDocumentAnswersRes2(), document -> document.getValue().getExpertDocument(), RESPONDENT_TWO_EXPERT_ANSWERS); - setCategoryIdAndRenameDoc(caseData.getDocumentCaseSummaryRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_PRE_TRIAL_SUMMARY); - setCategoryIdAndRenameDoc(caseData.getDocumentSkeletonArgumentRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_TRIAL_SKELETON); - setCategoryIdAndRenameDoc(caseData.getDocumentAuthoritiesRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_TRIAL_AUTHORITIES); - setCategoryIdAndRenameDoc(caseData.getDocumentCostsRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_TRIAL_COSTS); - setCategoryIdAndRenameDoc(caseData.getDocumentEvidenceForTrialRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_TRIAL_DOC_CORRESPONDENCE); + String defendantString = "Defendant 2"; + setCategoryIdAndRenameDoc(caseData.getDocumentDisclosureListRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_DISCLOSURE_LIST, + DISCLOSURE_LIST_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentForDisclosureRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_DISCLOSURE, + DISCLOSURE_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentWitnessStatementRes2(), document -> document.getValue().getWitnessOptionDocument(), RESPONDENT_TWO_WITNESS_STATEMENT, + WITNESS_STATEMENT_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentWitnessSummaryRes2(), document -> document.getValue().getWitnessOptionDocument(), RESPONDENT_TWO_WITNESS_SUMMARY, + WITNESS_SUMMARY_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentHearsayNoticeRes2(), document -> document.getValue().getWitnessOptionDocument(), RESPONDENT_TWO_WITNESS_HEARSAY, + WITNESS_HEARSAY_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentReferredInStatementRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_WITNESS_REFERRED, + WITNESS_REFERRED_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentExpertReportRes2(), document -> document.getValue().getExpertDocument(), RESPONDENT_TWO_EXPERT_REPORT, + EXPERT_REPORT_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentJointStatementRes2(), document -> document.getValue().getExpertDocument(), RESPONDENT_TWO_EXPERT_JOINT_STATEMENT, + EXPERT_JOINT_STATEMENT_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentQuestionsRes2(), document -> document.getValue().getExpertDocument(), RESPONDENT_TWO_EXPERT_QUESTIONS, + EXPERT_QUESTIONS_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentAnswersRes2(), document -> document.getValue().getExpertDocument(), RESPONDENT_TWO_EXPERT_ANSWERS, + EXPERT_ANSWERS_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentCaseSummaryRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_PRE_TRIAL_SUMMARY, + PRE_TRIAL_SUMMARY_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentSkeletonArgumentRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_TRIAL_SKELETON, + TRIAL_SKELETON_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentAuthoritiesRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_PRECEDENT_H, + TRIAL_AUTHORITIES_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentCostsRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_SCHEDULE_OF_COSTS, + TRIAL_COSTS_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); + setCategoryIdAndRenameDoc(caseData.getDocumentEvidenceForTrialRes2(), document -> document.getValue().getDocumentUpload(), RESPONDENT_TWO_TRIAL_DOC_CORRESPONDENCE, + TRIAL_DOC_CORRESPONDENCE_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), defendantString); } if (selectedRole.equals(CaseRole.APPLICANTSOLICITORONE.name()) || selectedRole.equals(SELECTED_VALUE_APP_BOTH)) { - setCategoryIdAndRenameDoc(caseData.getDocumentDisclosureList(), document -> document.getValue().getDocumentUpload(), APPLICANT_DISCLOSURE_LIST); - setCategoryIdAndRenameDoc(caseData.getDocumentForDisclosure(), document -> document.getValue().getDocumentUpload(), APPLICANT_DISCLOSURE); - setCategoryIdAndRenameDoc(caseData.getDocumentWitnessStatement(), document -> document.getValue().getWitnessOptionDocument(), APPLICANT_WITNESS_STATEMENT); - setCategoryIdAndRenameDoc(caseData.getDocumentWitnessSummary(), document -> document.getValue().getWitnessOptionDocument(), APPLICANT_WITNESS_SUMMARY); - setCategoryIdAndRenameDoc(caseData.getDocumentHearsayNotice(), document -> document.getValue().getWitnessOptionDocument(), APPLICANT_WITNESS_HEARSAY); - setCategoryIdAndRenameDoc(caseData.getDocumentReferredInStatement(), document -> document.getValue().getDocumentUpload(), APPLICANT_WITNESS_REFERRED); - setCategoryIdAndRenameDoc(caseData.getDocumentExpertReport(), document -> document.getValue().getExpertDocument(), APPLICANT_EXPERT_REPORT); - setCategoryIdAndRenameDoc(caseData.getDocumentJointStatement(), document -> document.getValue().getExpertDocument(), APPLICANT_EXPERT_JOINT_STATEMENT); - setCategoryIdAndRenameDoc(caseData.getDocumentQuestions(), document -> document.getValue().getExpertDocument(), APPLICANT_EXPERT_QUESTIONS); - setCategoryIdAndRenameDoc(caseData.getDocumentAnswers(), document -> document.getValue().getExpertDocument(), APPLICANT_EXPERT_ANSWERS); - setCategoryIdAndRenameDoc(caseData.getDocumentCaseSummary(), document -> document.getValue().getDocumentUpload(), APPLICANT_PRE_TRIAL_SUMMARY); - setCategoryIdAndRenameDoc(caseData.getDocumentSkeletonArgument(), document -> document.getValue().getDocumentUpload(), APPLICANT_TRIAL_SKELETON); - setCategoryIdAndRenameDoc(caseData.getDocumentAuthorities(), document -> document.getValue().getDocumentUpload(), APPLICANT_TRIAL_AUTHORITIES); - setCategoryIdAndRenameDoc(caseData.getDocumentCosts(), document -> document.getValue().getDocumentUpload(), APPLICANT_TRIAL_COSTS); - setCategoryIdAndRenameDoc(caseData.getDocumentEvidenceForTrial(), document -> document.getValue().getDocumentUpload(), APPLICANT_TRIAL_DOC_CORRESPONDENCE); + String claimantString = "Claimant 1"; + if (selectedRole.equals(SELECTED_VALUE_APP_BOTH)) { + claimantString = "Both claimants"; + } + setCategoryIdAndRenameDoc(caseData.getDocumentDisclosureList(), document -> document.getValue().getDocumentUpload(), APPLICANT_DISCLOSURE_LIST, + DISCLOSURE_LIST_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentForDisclosure(), document -> document.getValue().getDocumentUpload(), APPLICANT_DISCLOSURE, + DISCLOSURE_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentWitnessStatement(), document -> document.getValue().getWitnessOptionDocument(), APPLICANT_WITNESS_STATEMENT, + WITNESS_STATEMENT_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentWitnessSummary(), document -> document.getValue().getWitnessOptionDocument(), APPLICANT_WITNESS_SUMMARY, + WITNESS_SUMMARY_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentHearsayNotice(), document -> document.getValue().getWitnessOptionDocument(), APPLICANT_WITNESS_HEARSAY, + WITNESS_HEARSAY_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentReferredInStatement(), document -> document.getValue().getDocumentUpload(), APPLICANT_WITNESS_REFERRED, + WITNESS_REFERRED_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentExpertReport(), document -> document.getValue().getExpertDocument(), APPLICANT_EXPERT_REPORT, + EXPERT_REPORT_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentJointStatement(), document -> document.getValue().getExpertDocument(), APPLICANT_EXPERT_JOINT_STATEMENT, + EXPERT_JOINT_STATEMENT_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentQuestions(), document -> document.getValue().getExpertDocument(), APPLICANT_EXPERT_QUESTIONS, + EXPERT_QUESTIONS_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentAnswers(), document -> document.getValue().getExpertDocument(), APPLICANT_EXPERT_ANSWERS, + EXPERT_ANSWERS_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentCaseSummary(), document -> document.getValue().getDocumentUpload(), APPLICANT_PRE_TRIAL_SUMMARY, + PRE_TRIAL_SUMMARY_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentSkeletonArgument(), document -> document.getValue().getDocumentUpload(), APPLICANT_TRIAL_SKELETON, + TRIAL_SKELETON_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentAuthorities(), document -> document.getValue().getDocumentUpload(), APPLICANT_PRECEDENT_H, + TRIAL_AUTHORITIES_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentCosts(), document -> document.getValue().getDocumentUpload(), APPLICANT_SCHEDULE_OF_COSTS, + TRIAL_COSTS_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentEvidenceForTrial(), document -> document.getValue().getDocumentUpload(), APPLICANT_TRIAL_DOC_CORRESPONDENCE, + TRIAL_DOC_CORRESPONDENCE_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); if (selectedRole.equals(SELECTED_VALUE_APP_BOTH)) { caseData = copyApp1ChangesToApp2(caseData, caseDataBuilder); } } if (selectedRole.equals("APPLICANTSOLICITORTWO")) { - setCategoryIdAndRenameDoc(caseData.getDocumentDisclosureListApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_DISCLOSURE_LIST); - setCategoryIdAndRenameDoc(caseData.getDocumentForDisclosureApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_DISCLOSURE); - setCategoryIdAndRenameDoc(caseData.getDocumentWitnessStatementApp2(), document -> document.getValue().getWitnessOptionDocument(), APPLICANT_TWO_WITNESS_STATEMENT); - setCategoryIdAndRenameDoc(caseData.getDocumentWitnessSummaryApp2(), document -> document.getValue().getWitnessOptionDocument(), APPLICANT_TWO_WITNESS_SUMMARY); - setCategoryIdAndRenameDoc(caseData.getDocumentHearsayNoticeApp2(), document -> document.getValue().getWitnessOptionDocument(), APPLICANT_TWO_WITNESS_HEARSAY); - setCategoryIdAndRenameDoc(caseData.getDocumentReferredInStatementApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_WITNESS_REFERRED); - setCategoryIdAndRenameDoc(caseData.getDocumentExpertReportApp2(), document -> document.getValue().getExpertDocument(), APPLICANT_TWO_EXPERT_REPORT); - setCategoryIdAndRenameDoc(caseData.getDocumentJointStatementApp2(), document -> document.getValue().getExpertDocument(), APPLICANT_TWO_EXPERT_JOINT_STATEMENT); - setCategoryIdAndRenameDoc(caseData.getDocumentQuestionsApp2(), document -> document.getValue().getExpertDocument(), APPLICANT_TWO_EXPERT_QUESTIONS); - setCategoryIdAndRenameDoc(caseData.getDocumentAnswersApp2(), document -> document.getValue().getExpertDocument(), APPLICANT_TWO_EXPERT_ANSWERS); - setCategoryIdAndRenameDoc(caseData.getDocumentCaseSummaryApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_PRE_TRIAL_SUMMARY); - setCategoryIdAndRenameDoc(caseData.getDocumentSkeletonArgumentApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_TRIAL_SKELETON); - setCategoryIdAndRenameDoc(caseData.getDocumentAuthoritiesApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_TRIAL_AUTHORITIES); - setCategoryIdAndRenameDoc(caseData.getDocumentCostsApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_TRIAL_COSTS); - setCategoryIdAndRenameDoc(caseData.getDocumentEvidenceForTrialApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_TRIAL_DOC_CORRESPONDENCE); + String claimantString = "Claimant 2"; + setCategoryIdAndRenameDoc(caseData.getDocumentDisclosureListApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_DISCLOSURE_LIST, + DISCLOSURE_LIST_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentForDisclosureApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_DISCLOSURE, + DISCLOSURE_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentWitnessStatementApp2(), document -> document.getValue().getWitnessOptionDocument(), APPLICANT_TWO_WITNESS_STATEMENT, + WITNESS_STATEMENT_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentWitnessSummaryApp2(), document -> document.getValue().getWitnessOptionDocument(), APPLICANT_TWO_WITNESS_SUMMARY, + WITNESS_SUMMARY_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentHearsayNoticeApp2(), document -> document.getValue().getWitnessOptionDocument(), APPLICANT_TWO_WITNESS_HEARSAY, + WITNESS_HEARSAY_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentReferredInStatementApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_WITNESS_REFERRED, + WITNESS_REFERRED_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentExpertReportApp2(), document -> document.getValue().getExpertDocument(), APPLICANT_TWO_EXPERT_REPORT, + EXPERT_REPORT_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentJointStatementApp2(), document -> document.getValue().getExpertDocument(), APPLICANT_TWO_EXPERT_JOINT_STATEMENT, + EXPERT_JOINT_STATEMENT_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentQuestionsApp2(), document -> document.getValue().getExpertDocument(), APPLICANT_TWO_EXPERT_QUESTIONS, + EXPERT_QUESTIONS_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentAnswersApp2(), document -> document.getValue().getExpertDocument(), APPLICANT_TWO_EXPERT_ANSWERS, + EXPERT_ANSWERS_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentCaseSummaryApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_PRE_TRIAL_SUMMARY, + PRE_TRIAL_SUMMARY_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentSkeletonArgumentApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_TRIAL_SKELETON, + TRIAL_SKELETON_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentAuthoritiesApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_PRECEDENT_H, + TRIAL_AUTHORITIES_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentCostsApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_SCHEDULE_OF_COSTS, + TRIAL_COSTS_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); + setCategoryIdAndRenameDoc(caseData.getDocumentEvidenceForTrialApp2(), document -> document.getValue().getDocumentUpload(), APPLICANT_TWO_TRIAL_DOC_CORRESPONDENCE, + TRIAL_DOC_CORRESPONDENCE_TEXT, documentDateTime -> documentDateTime.getValue().getCreatedDatetime(), claimantString); } // null the values of the lists, so that on future retriggers of the event, they are blank @@ -651,7 +765,7 @@ CallbackResponse documentUploadTime(CallbackParams callbackParams) { caseDataBuilder.trialSelectionEvidenceSmallClaim(null); caseDataBuilder.trialSelectionEvidenceRes(null); caseDataBuilder.trialSelectionEvidenceSmallClaimRes(null); - + caseDataBuilder.notificationText(notificationString.toString()); return AboutToStartOrSubmitCallbackResponse.builder() .data(caseDataBuilder.build().toMap(objectMapper)) .build(); @@ -751,13 +865,13 @@ private CaseData copyResp1ChangesToResp2(CaseData caseData, CaseData.CaseDataBui evidenceDocToCopy = compareAndCopy(caseDataBefore.getDocumentAuthoritiesRes(), caseData.getDocumentAuthoritiesRes(), caseData.getDocumentAuthoritiesRes2()); - evidenceDocToAdd = deepCopyUploadEvidenceDocumentType(evidenceDocToCopy, RESPONDENT_TWO_TRIAL_AUTHORITIES); + evidenceDocToAdd = deepCopyUploadEvidenceDocumentType(evidenceDocToCopy, RESPONDENT_TWO_PRECEDENT_H); builder.documentAuthoritiesRes2(evidenceDocToAdd); evidenceDocToCopy = compareAndCopy(caseDataBefore.getDocumentCostsRes(), caseData.getDocumentCostsRes(), caseData.getDocumentCostsRes2()); - evidenceDocToAdd = deepCopyUploadEvidenceDocumentType(evidenceDocToCopy, RESPONDENT_TWO_TRIAL_COSTS); + evidenceDocToAdd = deepCopyUploadEvidenceDocumentType(evidenceDocToCopy, RESPONDENT_TWO_SCHEDULE_OF_COSTS); builder.documentCostsRes2(evidenceDocToAdd); evidenceDocToCopy = compareAndCopy(caseDataBefore.getDocumentEvidenceForTrialRes(), @@ -863,13 +977,13 @@ private CaseData copyApp1ChangesToApp2(CaseData caseData, CaseData.CaseDataBuild evidenceDocToCopy = compareAndCopy(caseDataBefore.getDocumentAuthorities(), caseData.getDocumentAuthorities(), caseData.getDocumentAuthoritiesApp2()); - evidenceDocToAdd = deepCopyUploadEvidenceDocumentType(evidenceDocToCopy, APPLICANT_TWO_TRIAL_AUTHORITIES); + evidenceDocToAdd = deepCopyUploadEvidenceDocumentType(evidenceDocToCopy, APPLICANT_TWO_PRECEDENT_H); builder.documentAuthoritiesApp2(evidenceDocToAdd); evidenceDocToCopy = compareAndCopy(caseDataBefore.getDocumentCosts(), caseData.getDocumentCosts(), caseData.getDocumentCostsApp2()); - evidenceDocToAdd = deepCopyUploadEvidenceDocumentType(evidenceDocToCopy, APPLICANT_TWO_TRIAL_COSTS); + evidenceDocToAdd = deepCopyUploadEvidenceDocumentType(evidenceDocToCopy, APPLICANT_TWO_SCHEDULE_OF_COSTS); builder.documentCostsApp2(evidenceDocToAdd); evidenceDocToCopy = compareAndCopy(caseDataBefore.getDocumentEvidenceForTrial(), diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadJudgeHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadJudgeHandler.java index 46620e931b3..12ca69bdb86 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadJudgeHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadJudgeHandler.java @@ -12,14 +12,19 @@ import uk.gov.hmcts.reform.civil.callback.CaseEvent; import uk.gov.hmcts.reform.civil.enums.CaseNoteType; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.CaseNote; +import uk.gov.hmcts.reform.civil.model.common.Element; +import uk.gov.hmcts.reform.civil.model.documents.DocumentAndNote; +import uk.gov.hmcts.reform.civil.model.documents.DocumentWithName; +import uk.gov.hmcts.reform.civil.service.CaseNoteService; -import java.time.LocalDateTime; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.IntStream; import static java.lang.String.format; +import static uk.gov.hmcts.reform.civil.callback.CallbackParams.Params.BEARER_TOKEN; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; @@ -31,14 +36,17 @@ public class EvidenceUploadJudgeHandler extends CallbackHandler { private static final List EVENTS = Collections.singletonList(EVIDENCE_UPLOAD_JUDGE); private final ObjectMapper objectMapper; + + public static final String EVIDENCE_UPLOAD_HEADER_THREE = "# Case note added \n # %s"; public static final String EVIDENCE_UPLOAD_HEADER_TWO = "# Document uploaded \n # %s"; public static final String EVIDENCE_UPLOAD_HEADER_ONE = "# Document uploaded and note added \n # %s"; public static final String EVIDENCE_UPLOAD_BODY_ONE = "## You have uploaded: \n %s"; + private final CaseNoteService caseNoteService; @Override protected Map callbacks() { return new ImmutableMap.Builder() - .put(callbackKey(ABOUT_TO_START), this::emptyCallbackResponse) + .put(callbackKey(ABOUT_TO_START), this::removeCaseNoteType) .put(callbackKey(ABOUT_TO_SUBMIT), this::populateSubmittedDateTime) .put(callbackKey(SUBMITTED), this::buildConfirmation) .build(); @@ -49,12 +57,70 @@ public List handledEvents() { return EVENTS; } + private AboutToStartOrSubmitCallbackResponse removeCaseNoteType(CallbackParams callbackParams) { + var caseData = callbackParams.getCaseData(); + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + + caseDataBuilder + .caseNoteType(null) + .documentAndNameToAdd(null) + .documentAndNoteToAdd(null) + .build(); + + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .build(); + } + private AboutToStartOrSubmitCallbackResponse populateSubmittedDateTime(CallbackParams callbackParams) { var caseData = callbackParams.getCaseData(); CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); - if (caseData.getCaseNoteTypeNoteTA() != null) { - caseDataBuilder.noteAdditionDateTime(LocalDateTime.now()); + if (caseData.getCaseNoteType().equals(CaseNoteType.NOTE_ONLY)) { + CaseNote caseNoteTA = caseNoteService.buildCaseNote( + callbackParams.getParams().get(BEARER_TOKEN).toString(), + caseData.getCaseNoteTA() + ); + + List> caseNotesTa = caseNoteService.addNoteToListEnd(caseNoteTA, caseData.getCaseNotesTA()); + + caseDataBuilder + .caseNotesTA(caseNotesTa) + .caseNoteTA(null) + .build(); + } + + if (caseData.getCaseNoteType().equals(CaseNoteType.DOCUMENT_ONLY)) { + List> documentAndNameToAdd = caseData.getDocumentAndNameToAdd(); + List> documentAndNameCurrent = caseData.getDocumentAndName(); + + if (documentAndNameCurrent == null) { + documentAndNameCurrent = documentAndNameToAdd; + } else { + for (Element document : documentAndNameToAdd) { + documentAndNameCurrent.add(document); + } + } + caseDataBuilder + .documentAndName(documentAndNameCurrent) + .build(); + } + + if (caseData.getCaseNoteType().equals(CaseNoteType.DOCUMENT_AND_NOTE)) { + List> documentAndNoteToAdd = caseData.getDocumentAndNoteToAdd(); + List> documentAndNoteCurrent = caseData.getDocumentAndNote(); + + if (documentAndNoteCurrent == null) { + documentAndNoteCurrent = documentAndNoteToAdd; + } else { + for (Element document : documentAndNoteToAdd) { + documentAndNoteCurrent.add(document); + } + } + caseDataBuilder + .documentAndNote(documentAndNoteCurrent) + .build(); + } return AboutToStartOrSubmitCallbackResponse.builder() @@ -72,28 +138,32 @@ private SubmittedCallbackResponse buildConfirmation(CallbackParams callbackParam } private String getHeader(CaseData caseData) { - if (null != caseData.getCaseNoteType() && caseData.getCaseNoteType().equals(CaseNoteType.DOCUMENT_ONLY)) { - return format(EVIDENCE_UPLOAD_HEADER_TWO, caseData.getLegacyCaseReference()); - } - if (caseData.getCaseNoteType().equals(CaseNoteType.DOCUMENT_AND_NOTE)) { - return format(EVIDENCE_UPLOAD_HEADER_ONE, caseData.getLegacyCaseReference()); + + switch (caseData.getCaseNoteType()) { + case NOTE_ONLY: + return format(EVIDENCE_UPLOAD_HEADER_THREE, caseData.getLegacyCaseReference()); + case DOCUMENT_ONLY: + return format(EVIDENCE_UPLOAD_HEADER_TWO, caseData.getLegacyCaseReference()); + case DOCUMENT_AND_NOTE: + return format(EVIDENCE_UPLOAD_HEADER_ONE, caseData.getLegacyCaseReference()); + default: + return null; } - return null; } private String getBody(CaseData caseData) { StringBuilder stringBuilder = new StringBuilder(); if (null != caseData.getCaseNoteType() && caseData.getCaseNoteType().equals(CaseNoteType.DOCUMENT_ONLY)) { - IntStream.range(0, caseData.getDocumentAndName() + IntStream.range(0, caseData.getDocumentAndNameToAdd() .size()).forEachOrdered(i -> stringBuilder.append("* ").append( - caseData.getDocumentAndName().get(i).getValue().getDocument().getDocumentFileName()).append("\n")); + caseData.getDocumentAndNameToAdd().get(i).getValue().getDocument().getDocumentFileName()).append("\n")); return format(EVIDENCE_UPLOAD_BODY_ONE, stringBuilder); } if (caseData.getCaseNoteType().equals(CaseNoteType.DOCUMENT_AND_NOTE)) { - IntStream.range(0, caseData.getDocumentAndNote() + IntStream.range(0, caseData.getDocumentAndNoteToAdd() .size()).forEachOrdered(i -> stringBuilder.append("* ").append( - caseData.getDocumentAndNote().get(i) + caseData.getDocumentAndNoteToAdd().get(i) .getValue() .getDocument() .getDocumentFileName()).append("\n")); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/GenerateDirectionOrderCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/GenerateDirectionOrderCallbackHandler.java index e9d8d00a50a..91e5960c66b 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/GenerateDirectionOrderCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/GenerateDirectionOrderCallbackHandler.java @@ -14,9 +14,13 @@ import uk.gov.hmcts.reform.civil.enums.CaseState; import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.enums.finalorders.CostEnums; +import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrderToggle; +import uk.gov.hmcts.reform.civil.enums.finalorders.HearingLengthFinalOrderList; import uk.gov.hmcts.reform.civil.model.BusinessProcess; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.HearingNotes; import uk.gov.hmcts.reform.civil.model.caseprogression.FreeFormOrderValues; import uk.gov.hmcts.reform.civil.model.common.DynamicList; import uk.gov.hmcts.reform.civil.model.common.DynamicListElement; @@ -43,6 +47,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import static java.util.Objects.nonNull; @@ -57,11 +62,15 @@ import static uk.gov.hmcts.reform.civil.callback.CaseEvent.GENERATE_ORDER_NOTIFICATION; import static uk.gov.hmcts.reform.civil.enums.CaseState.All_FINAL_ORDERS_ISSUED; import static uk.gov.hmcts.reform.civil.enums.CaseState.CASE_PROGRESSION; -import static uk.gov.hmcts.reform.civil.enums.CaseState.JUDICIAL_REFERRAL; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.ONE_V_TWO_ONE_LEGAL_REP; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.ONE_V_TWO_TWO_LEGAL_REP; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.TWO_V_ONE; +import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.getMultiPartyScenario; import static uk.gov.hmcts.reform.civil.enums.caseprogression.FinalOrderSelection.ASSISTED_ORDER; +import static uk.gov.hmcts.reform.civil.enums.finalorders.CostEnums.CLAIMANT; +import static uk.gov.hmcts.reform.civil.enums.finalorders.CostEnums.STANDARD_BASIS; +import static uk.gov.hmcts.reform.civil.enums.finalorders.CostEnums.SUBJECT_DETAILED_ASSESSMENT; +import static uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrderRepresentationList.CLAIMANT_AND_DEFENDANT; import static uk.gov.hmcts.reform.civil.model.common.DynamicList.fromList; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.element; @@ -85,8 +94,11 @@ public class GenerateDirectionOrderCallbackHandler extends CallbackHandler { public static final String NOT_ALLOWED_DATE = "The date in %s may not be later than the established date"; public static final String NOT_ALLOWED_DATE_RANGE = "The date range in %s may not have a 'from date', that is after the 'date to'"; public static final String NOT_ALLOWED_DATE_PAST = "The date in %s may not be before the established date"; + public static final String JUDGE_HEARD_FROM_EMPTY = "Judge Heard from: 'Claimant(s) and defendant(s)' section for %s, requires a selection to be made"; + public static final String FURTHER_HEARING_OTHER_EMPTY = "Further hearing, Length of new hearing, Other is empty"; public String defendantTwoPartyName; public String claimantTwoPartyName; + public static final String APPEAL_NOTICE_DATE = "Appeal notice date"; private final LocationRefDataService locationRefDataService; private final ObjectMapper objectMapper; private final JudgeFinalOrderGenerator judgeFinalOrderGenerator; @@ -95,7 +107,7 @@ public class GenerateDirectionOrderCallbackHandler extends CallbackHandler { @Override protected Map callbacks() { return Map.of( - callbackKey(ABOUT_TO_START), this::emptyCallbackResponse, + callbackKey(ABOUT_TO_START), this::nullPreviousSelections, callbackKey(MID, "populate-form-values"), this::populateFormValues, callbackKey(MID, "validate-and-generate-document"), this::validateFormAndGeneratePreviewDocument, callbackKey(ABOUT_TO_SUBMIT), this::addGeneratedDocumentToCollection, @@ -108,6 +120,39 @@ public List handledEvents() { return EVENTS; } + // Final orders can be submitted multiple times, we want each one to be a "clean slate" + // so we remove previously selected options from both Free form orders and assisted orders. + // Exception is fields which we specifically prepopulate e.g. date fields, or specific text. + private CallbackResponse nullPreviousSelections(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + + caseDataBuilder.finalOrderSelection(null); + // Free form orders + caseDataBuilder + .freeFormRecordedTextArea(null) + .freeFormOrderedTextArea(null) + .orderOnCourtsList(null) + .freeFormHearingNotes(null); + // Assisted orders + caseDataBuilder + .finalOrderMadeSelection(null).finalOrderDateHeardComplex(null) + .finalOrderJudgePapers(null) + .finalOrderJudgeHeardFrom(null) + .finalOrderRepresentation(null) + .finalOrderRecitals(null) + .finalOrderRecitalsRecorded(null) + .finalOrderOrderedThatText(null) + .finalOrderFurtherHearingToggle(null).finalOrderFurtherHearingComplex(null) + .assistedOrderCostList(null).assistedOrderCostsReserved(null).assistedOrderMakeAnOrderForCosts(null).assistedOrderCostsBespoke(null) + .finalOrderAppealToggle(null).finalOrderAppealComplex(null) + .orderMadeOnDetailsList(null).finalOrderGiveReasonsComplex(null); + + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .build(); + } + private CallbackResponse populateFormValues(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); @@ -129,13 +174,16 @@ private CallbackResponse validateFormAndGeneratePreviewDocument(CallbackParams c CaseData caseData = callbackParams.getCaseData(); CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); List errors = new ArrayList<>(); + if (ASSISTED_ORDER.equals(caseData.getFinalOrderSelection())) { + checkJudgeHeardFrom(caseData, errors); checkFieldDate(caseData, errors); + checkFurtherHearingOther(caseData, errors); } CaseDocument finalDocument = judgeFinalOrderGenerator.generate( caseData, callbackParams.getParams().get(BEARER_TOKEN).toString()); - caseDataBuilder.finalOrderDocument(finalDocument.getDocumentLink()); + caseDataBuilder.finalOrderDocument(finalDocument); return AboutToStartOrSubmitCallbackResponse.builder() .data(caseDataBuilder.build().toMap(objectMapper)) @@ -143,15 +191,47 @@ private CallbackResponse validateFormAndGeneratePreviewDocument(CallbackParams c .build(); } + private void checkFurtherHearingOther(final CaseData caseData, final List errors) { + if (caseData.getFinalOrderFurtherHearingToggle() != null + && !caseData.getFinalOrderFurtherHearingToggle().isEmpty() + && caseData.getFinalOrderFurtherHearingToggle().get(0).equals(FinalOrderToggle.SHOW) + && caseData.getFinalOrderFurtherHearingComplex().getLengthList() + .equals(HearingLengthFinalOrderList.OTHER) + && Objects.isNull(caseData.getFinalOrderFurtherHearingComplex() + .getLengthListOther())) { + errors.add(FURTHER_HEARING_OTHER_EMPTY); + } + } + + private void checkJudgeHeardFrom(CaseData caseData, List errors) { + if (caseData.getFinalOrderRepresentation() != null + && caseData.getFinalOrderRepresentation().getTypeRepresentationList().equals(CLAIMANT_AND_DEFENDANT)) { + if (caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationClaimantList() == null) { + errors.add(format(JUDGE_HEARD_FROM_EMPTY, "claimant")); + } + if (caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationDefendantList() == null) { + errors.add(format(JUDGE_HEARD_FROM_EMPTY, "defendant")); + } + if (getMultiPartyScenario(caseData).equals(TWO_V_ONE) + && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationClaimantListTwo() == null) { + errors.add(format(JUDGE_HEARD_FROM_EMPTY, "second claimant")); + } + if ((getMultiPartyScenario(caseData).equals(ONE_V_TWO_ONE_LEGAL_REP) || getMultiPartyScenario(caseData).equals(ONE_V_TWO_TWO_LEGAL_REP)) + && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationDefendantTwoList() == null) { + errors.add(format(JUDGE_HEARD_FROM_EMPTY, "second defendant")); + } + } + } + private CaseData.CaseDataBuilder populateFreeFormFields(CaseData.CaseDataBuilder builder) { return builder .orderOnCourtInitiative(FreeFormOrderValues.builder() .onInitiativeSelectionTextArea(ON_INITIATIVE_SELECTION_TEXT) - .onInitiativeSelectionDate(LocalDate.now()) + .onInitiativeSelectionDate(LocalDate.now().plusDays(7)) .build()) .orderWithoutNotice(FreeFormOrderValues.builder() .withoutNoticeSelectionTextArea(WITHOUT_NOTICE_SELECTION_TEXT) - .withoutNoticeSelectionDate(LocalDate.now()) + .withoutNoticeSelectionDate(LocalDate.now().plusDays(7)) .build()); } @@ -164,12 +244,8 @@ private DynamicList getLocationsFromList(final List locations) } private DynamicList populateCurrentHearingLocation(CaseData caseData, String authorisation) { - LocationRefData locationRefData; - if (hasSDOBeenMade(caseData.getCcdState())) { - locationRefData = locationHelper.getHearingLocation(null, caseData, authorisation); - } else { - locationRefData = locationRefDataService.getCcmccLocation(authorisation); - } + LocationRefData locationRefData = locationHelper.getHearingLocation(null, caseData, authorisation); + return DynamicList.builder().listItems(List.of(DynamicListElement.builder() .code("LOCATION_LIST") .label(locationRefData.getSiteName()) @@ -185,10 +261,6 @@ private DynamicList populateCurrentHearingLocation(CaseData caseData, String aut .build(); } - private boolean hasSDOBeenMade(CaseState state) { - return !JUDICIAL_REFERRAL.equals(state); - } - private CaseData.CaseDataBuilder populateFields( CaseData.CaseDataBuilder builder, List locations, CaseData caseData, String authToken) { LocalDate advancedDate = LocalDate.now().plusDays(14); @@ -213,18 +285,22 @@ private boolean hasSDOBeenMade(CaseState state) { .datesToAvoidDates(LocalDate.now().plusDays(7)).build()).build()) .orderMadeOnDetailsOrderCourt( OrderMadeOnDetails.builder().ownInitiativeDate( - LocalDate.now()).ownInitiativeText(ON_INITIATIVE_SELECTION_TEXT).build()) + LocalDate.now().plusDays(7)).ownInitiativeText(ON_INITIATIVE_SELECTION_TEXT).build()) .orderMadeOnDetailsOrderWithoutNotice( OrderMadeOnDetailsOrderWithoutNotice.builder().withOutNoticeDate( - LocalDate.now()).withOutNoticeText(WITHOUT_NOTICE_SELECTION_TEXT).build()) + LocalDate.now().plusDays(7)).withOutNoticeText(WITHOUT_NOTICE_SELECTION_TEXT).build()) .assistedOrderMakeAnOrderForCosts(AssistedOrderCostDetails.builder() .assistedOrderCostsFirstDropdownDate(advancedDate) .assistedOrderAssessmentThirdDropdownDate(advancedDate) .makeAnOrderForCostsYesOrNo(YesOrNo.NO) + .makeAnOrderForCostsList(CLAIMANT) + .assistedOrderClaimantDefendantFirstDropdown(SUBJECT_DETAILED_ASSESSMENT) + .assistedOrderAssessmentSecondDropdownList1(STANDARD_BASIS) + .assistedOrderAssessmentSecondDropdownList2(CostEnums.NO) .build()) .publicFundingCostsProtection(YesOrNo.NO) .finalOrderAppealComplex(FinalOrderAppeal.builder() - .appealGrantedRefusedDropdown(AppealGrantedRefused.builder() + .appealGrantedDropdown(AppealGrantedRefused.builder() .appealChoiceSecondDropdownA( AppealChoiceSecondDropdown.builder() .appealGrantedRefusedDate(LocalDate.now().plusDays(21)) @@ -233,7 +309,19 @@ private boolean hasSDOBeenMade(CaseState state) { AppealChoiceSecondDropdown.builder() .appealGrantedRefusedDate(LocalDate.now().plusDays(21)) .build()) - .build()).build()); + .build()) + .appealRefusedDropdown(AppealGrantedRefused.builder() + .appealChoiceSecondDropdownA( + AppealChoiceSecondDropdown.builder() + .appealGrantedRefusedDate(LocalDate.now().plusDays(21)) + .build()) + .appealChoiceSecondDropdownB( + AppealChoiceSecondDropdown.builder() + .appealGrantedRefusedDate(LocalDate.now().plusDays(21)) + .build()) + + .build()).build()) + .finalOrderGiveReasonsYesNo(YesOrNo.NO); } private void populateClaimant2Defendant2PartyNames(CaseData caseData) { @@ -288,6 +376,14 @@ private void checkFieldDate(CaseData caseData, List errors) { .map(DatesFinalOrders::getDatesToAvoidDates).orElse(null), "Further hearing", NOT_ALLOWED_DATE_PAST, errors, true); + if (nonNull(caseData.getFinalOrderFurtherHearingComplex())) { + if (nonNull(caseData.getFinalOrderFurtherHearingComplex().getDateToDate()) + && caseData.getFinalOrderFurtherHearingComplex().getDateToDate() + .isBefore(caseData.getFinalOrderFurtherHearingComplex().getListFromDate())) { + errors.add(String.format(NOT_ALLOWED_DATE_RANGE, "Further hearing")); + } + } + validateDate(Optional.ofNullable(caseData.getAssistedOrderMakeAnOrderForCosts()) .map(AssistedOrderCostDetails::getAssistedOrderCostsFirstDropdownDate).orElse(null), "Make an order for detailed/summary costs", NOT_ALLOWED_DATE_PAST, errors, true); @@ -297,24 +393,35 @@ private void checkFieldDate(CaseData caseData, List errors) { "Make an order for detailed/summary costs", NOT_ALLOWED_DATE_PAST, errors, true); validateDate(Optional.ofNullable(caseData.getFinalOrderAppealComplex()) - .map(FinalOrderAppeal::getAppealGrantedRefusedDropdown) + .map(FinalOrderAppeal::getAppealGrantedDropdown) .map(AppealGrantedRefused::getAppealChoiceSecondDropdownA) .map(AppealChoiceSecondDropdown::getAppealGrantedRefusedDate).orElse(null), - "Appeal notice date", NOT_ALLOWED_DATE_PAST, errors, true); + APPEAL_NOTICE_DATE, NOT_ALLOWED_DATE_PAST, errors, true); validateDate(Optional.ofNullable(caseData.getFinalOrderAppealComplex()) - .map(FinalOrderAppeal::getAppealGrantedRefusedDropdown) + .map(FinalOrderAppeal::getAppealGrantedDropdown) .map(AppealGrantedRefused::getAppealChoiceSecondDropdownB) .map(AppealChoiceSecondDropdown::getAppealGrantedRefusedDate).orElse(null), - "Appeal notice date", NOT_ALLOWED_DATE_PAST, errors, true); + APPEAL_NOTICE_DATE, NOT_ALLOWED_DATE_PAST, errors, true); + + validateDate(Optional.ofNullable(caseData.getFinalOrderAppealComplex()) + .map(FinalOrderAppeal::getAppealRefusedDropdown) + .map(AppealGrantedRefused::getAppealChoiceSecondDropdownA) + .map(AppealChoiceSecondDropdown::getAppealGrantedRefusedDate).orElse(null), + APPEAL_NOTICE_DATE, NOT_ALLOWED_DATE_PAST, errors, true); + + validateDate(Optional.ofNullable(caseData.getFinalOrderAppealComplex()) + .map(FinalOrderAppeal::getAppealRefusedDropdown) + .map(AppealGrantedRefused::getAppealChoiceSecondDropdownB) + .map(AppealChoiceSecondDropdown::getAppealGrantedRefusedDate).orElse(null), + APPEAL_NOTICE_DATE, NOT_ALLOWED_DATE_PAST, errors, true); } private CallbackResponse addGeneratedDocumentToCollection(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); - CaseDocument finalDocument = judgeFinalOrderGenerator.generate( - caseData, callbackParams.getParams().get(BEARER_TOKEN).toString()); + CaseDocument finalDocument = caseData.getFinalOrderDocument(); List> finalCaseDocuments = new ArrayList<>(); finalCaseDocuments.add(element(finalDocument)); @@ -335,6 +442,24 @@ private CallbackResponse addGeneratedDocumentToCollection(CallbackParams callbac state = CASE_PROGRESSION; } + // populate hearing notes in listing tab with hearing notes from either assisted or freeform order, if either exist. + if (caseData.getFinalOrderSelection().equals(ASSISTED_ORDER)) { + if (caseData.getFinalOrderFurtherHearingComplex() != null + && caseData.getFinalOrderFurtherHearingComplex().getHearingNotesText() != null) { + caseDataBuilder.hearingNotes(HearingNotes.builder() + .date(LocalDate.now()) + .notes(caseData.getFinalOrderFurtherHearingComplex().getHearingNotesText()) + .build()); + } + } else { + if (nonNull(caseData.getFreeFormHearingNotes())) { + caseDataBuilder.hearingNotes(HearingNotes.builder() + .date(LocalDate.now()) + .notes(caseData.getFreeFormHearingNotes()) + .build()); + } + } + return AboutToStartOrSubmitCallbackResponse.builder() .data(caseDataBuilder.build().toMap(objectMapper)) .state(state.name()) diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/HearingScheduledHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/HearingScheduledHandler.java index d93eb1087ea..f378b489e01 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/HearingScheduledHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/HearingScheduledHandler.java @@ -66,7 +66,7 @@ public class HearingScheduledHandler extends CallbackHandler { @Override protected Map callbacks() { return new ImmutableMap.Builder() - .put(callbackKey(ABOUT_TO_START), this::emptyCallbackResponse) + .put(callbackKey(ABOUT_TO_START), this::clearPreviousSelections) .put(callbackKey(MID, "locationName"), this::locationList) .put(callbackKey(MID, "checkPastDate"), this::checkPastDate) .put(callbackKey(MID, "checkFutureDate"), this::checkFutureDate) @@ -83,6 +83,27 @@ private String getHeader(CaseData caseData) { return format(HEARING_CREATED_HEADER, caseData.getHearingReferenceNumber()); } + // hearing notices can be retriggered i.e. relisted, in such case we clear previous selections + private CallbackResponse clearPreviousSelections(CallbackParams callbackParams) { + var caseData = callbackParams.getCaseData(); + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + + caseDataBuilder + .hearingNoticeList(null) + .listingOrRelisting(null) + .hearingLocation(null) + .channel(null) + .hearingDate(null) + .hearingTimeHourMinute(null) + .hearingDuration(null) + .information(null) + .hearingNoticeListOther(null); + + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .build(); + } + private SubmittedCallbackResponse buildConfirmation(CallbackParams callbackParams) { var caseData = callbackParams.getCaseData(); return SubmittedCallbackResponse.builder() @@ -110,6 +131,7 @@ private DynamicList getLocationsFromList(final List locations) return fromList(locations.stream().map(location -> new StringBuilder().append(location.getSiteName()) .append(" - ").append(location.getCourtAddress()) .append(" - ").append(location.getPostcode()).toString()) + .sorted() .collect(Collectors.toList())); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/InitiateGeneralApplicationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/InitiateGeneralApplicationHandler.java index bef3248bba4..c91192fbf10 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/InitiateGeneralApplicationHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/InitiateGeneralApplicationHandler.java @@ -20,11 +20,11 @@ import uk.gov.hmcts.reform.civil.model.genapplication.GAInformOtherParty; import uk.gov.hmcts.reform.civil.model.genapplication.GAPbaDetails; import uk.gov.hmcts.reform.civil.model.genapplication.GAUrgencyRequirement; +import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; import uk.gov.hmcts.reform.civil.service.GeneralAppFeesService; import uk.gov.hmcts.reform.civil.service.InitiateGeneralApplicationService; -import uk.gov.hmcts.reform.civil.service.OrganisationService; -import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; +import uk.gov.hmcts.reform.civil.utils.UserRoleCaching; import uk.gov.hmcts.reform.idam.client.IdamClient; import uk.gov.hmcts.reform.idam.client.models.UserDetails; @@ -45,7 +45,7 @@ import static uk.gov.hmcts.reform.civil.callback.CaseEvent.INITIATE_GENERAL_APPLICATION; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; import static uk.gov.hmcts.reform.civil.model.common.DynamicList.fromList; -import static uk.gov.hmcts.reform.civil.service.InitiateGeneralApplicationService.INVALID_SETTLE_OR_DISCONTINUE_CONSENT; +import static uk.gov.hmcts.reform.civil.service.InitiateGeneralApplicationService.INVALID_SETTLE_BY_CONSENT; @Service @RequiredArgsConstructor @@ -64,15 +64,15 @@ public class InitiateGeneralApplicationHandler extends CallbackHandler { + "respondent solicitor are assigned to the case."; private final InitiateGeneralApplicationService initiateGeneralApplicationService; private final ObjectMapper objectMapper; - private final OrganisationService organisationService; private final IdamClient idamClient; + private final UserRoleCaching userRoleCaching; private final GeneralAppFeesService feesService; private final LocationRefDataService locationRefDataService; @Override protected Map callbacks() { return Map.of( - callbackKey(ABOUT_TO_START), this::aboutToStartValidattionAndSetup, + callbackKey(ABOUT_TO_START), this::aboutToStartValidationAndSetup, callbackKey(MID, VALIDATE_GA_TYPE), this::gaValidateType, callbackKey(MID, VALIDATE_HEARING_DATE), this::gaValidateHearingDate, callbackKey(MID, VALIDATE_GA_CONSENT), this::gaValidateConsent, @@ -89,16 +89,15 @@ public List handledEvents() { return EVENTS; } - private CallbackResponse aboutToStartValidattionAndSetup(CallbackParams callbackParams) { + private CallbackResponse aboutToStartValidationAndSetup(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + String authToken = callbackParams.getParams().get(BEARER_TOKEN).toString(); List errors = new ArrayList<>(); - if (!initiateGeneralApplicationService.respondentAssigned(caseData)) { + if (!initiateGeneralApplicationService.respondentAssigned(caseData, authToken)) { errors.add(RESP_NOT_ASSIGNED_ERROR); } - - CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); - String authToken = callbackParams.getParams().get(BEARER_TOKEN).toString(); caseDataBuilder .generalAppHearingDetails( GAHearingDetails @@ -127,9 +126,9 @@ private CallbackResponse gaValidateConsent(CallbackParams callbackParams) { && YES.equals(caseData.getGeneralAppRespondentAgreement().getHasAgreed()); List errors = new ArrayList<>(); if (generalAppTypes.size() == 1 - && generalAppTypes.contains(GeneralApplicationTypes.SETTLE_OR_DISCONTINUE_CONSENT) + && generalAppTypes.contains(GeneralApplicationTypes.SETTLE_BY_CONSENT) && !consent) { - errors.add(INVALID_SETTLE_OR_DISCONTINUE_CONSENT); + errors.add(INVALID_SETTLE_BY_CONSENT); } return AboutToStartOrSubmitCallbackResponse.builder() .data(caseDataBuilder.build().toMap(objectMapper)) @@ -149,9 +148,9 @@ private CallbackResponse gaValidateType(CallbackParams callbackParams) { errors.add("It is not possible to select an additional application type when applying to vary judgment"); } if (generalAppTypes.size() > 1 - && generalAppTypes.contains(GeneralApplicationTypes.SETTLE_OR_DISCONTINUE_CONSENT)) { + && generalAppTypes.contains(GeneralApplicationTypes.SETTLE_BY_CONSENT)) { errors.add("It is not possible to select an additional application type " + - "when applying to settle or discontinue by consent"); + "when applying to Settle by consent"); } if (generalAppTypes.size() == 1 @@ -162,10 +161,9 @@ private CallbackResponse gaValidateType(CallbackParams callbackParams) { } else { caseDataBuilder.generalAppVaryJudgementType(YesOrNo.NO); } - - UserDetails userDetails = idamClient.getUserDetails(callbackParams.getParams().get(BEARER_TOKEN).toString()); + String token = callbackParams.getParams().get(BEARER_TOKEN).toString(); boolean isGAApplicantSameAsParentCaseClaimant = initiateGeneralApplicationService - .isGAApplicantSameAsParentCaseClaimant(caseData, userDetails); + .isGAApplicantSameAsParentCaseClaimant(caseData, token); caseDataBuilder .generalAppParentClaimantIsApplicant(isGAApplicantSameAsParentCaseClaimant ? YES : YesOrNo.NO).build(); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/JudgmentPaidInFullCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/JudgmentPaidInFullCallbackHandler.java new file mode 100644 index 00000000000..4040c589d82 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/JudgmentPaidInFullCallbackHandler.java @@ -0,0 +1,113 @@ +package uk.gov.hmcts.reform.civil.handler.callback.user; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.SubmittedCallbackResponse; +import uk.gov.hmcts.reform.civil.callback.Callback; +import uk.gov.hmcts.reform.civil.callback.CallbackHandler; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.helpers.judgmentsonline.JudgmentsOnlineHelper; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentStatusType; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static java.lang.String.format; +import static java.util.Objects.nonNull; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.JUDGMENT_PAID_IN_FULL; + +@Service +@RequiredArgsConstructor +public class JudgmentPaidInFullCallbackHandler extends CallbackHandler { + + private static final List EVENTS = Collections.singletonList(JUDGMENT_PAID_IN_FULL); + protected final ObjectMapper objectMapper; + private static final String ERROR_MESSAGE_DATE_MUST_BE_IN_PAST = "Date must be in past"; + + @Override + protected Map callbacks() { + return new ImmutableMap.Builder() + .put(callbackKey(ABOUT_TO_START), this::emptyCallbackResponse) + .put(callbackKey(MID, "validate-payment-date"), this::validatePaymentDate) + .put(callbackKey(ABOUT_TO_SUBMIT), this::saveJudgmentPaidInFullDetails) + .put(callbackKey(SUBMITTED), this::buildConfirmation) + .build(); + } + + private CallbackResponse buildConfirmation(CallbackParams callbackParams) { + return SubmittedCallbackResponse.builder() + .confirmationHeader(getHeader()) + .confirmationBody(getBody()) + .build(); + } + + private String getHeader() { + return format("# Judgment marked as paid in full"); + } + + private String getBody() { + return format("# The judgment has been marked as paid in full"); + } + + private CallbackResponse saveJudgmentPaidInFullDetails(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + List errors = new ArrayList<>(); + + if (nonNull(caseData.getJoOrderMadeDate()) + && nonNull(caseData.getJoJudgmentPaidInFull().getDateOfFullPaymentMade())) { + boolean paidAfter30Days = JudgmentsOnlineHelper.checkIfDateDifferenceIsGreaterThan30Days(caseData.getJoOrderMadeDate(), + caseData.getJoJudgmentPaidInFull().getDateOfFullPaymentMade()); + if (paidAfter30Days) { + caseData.getJoJudgmentStatusDetails().setJudgmentStatusTypes(JudgmentStatusType.SATISFIED); + if (caseData.getJoIsRegisteredWithRTL() == YesOrNo.YES) { + caseData.getJoJudgmentStatusDetails().setJoRtlState(JudgmentsOnlineHelper.getRTLStatusBasedOnJudgementStatus(JudgmentStatusType.SATISFIED)); + } + } else { + caseData.getJoJudgmentStatusDetails().setJudgmentStatusTypes(JudgmentStatusType.CANCELLED); + if (caseData.getJoIsRegisteredWithRTL() == YesOrNo.YES) { + caseData.getJoJudgmentStatusDetails().setJoRtlState(JudgmentsOnlineHelper.getRTLStatusBasedOnJudgementStatus(JudgmentStatusType.CANCELLED)); + } + } + caseData.getJoJudgmentStatusDetails().setLastUpdatedDate(LocalDateTime.now()); + caseData.setJoIsLiveJudgmentExists(YesOrNo.NO); + } + + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .build(); + } + + private CallbackResponse validatePaymentDate(CallbackParams callbackParams) { + List errors = new ArrayList<>(); + CaseData caseData = callbackParams.getCaseData(); + LocalDate dateOfPaymentMade = caseData.getJoJudgmentPaidInFull().getDateOfFullPaymentMade(); + + if (JudgmentsOnlineHelper.validateIfFutureDate(dateOfPaymentMade)) { + errors.add(ERROR_MESSAGE_DATE_MUST_BE_IN_PAST); + } + return AboutToStartOrSubmitCallbackResponse.builder() + .errors(errors) + .build(); + } + + @Override + public List handledEvents() { + return EVENTS; + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/LIPClaimSettledCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/LIPClaimSettledCallbackHandler.java new file mode 100644 index 00000000000..96072989d4c --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/LIPClaimSettledCallbackHandler.java @@ -0,0 +1,55 @@ +package uk.gov.hmcts.reform.civil.handler.callback.user; + +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.civil.callback.Callback; +import uk.gov.hmcts.reform.civil.callback.CallbackHandler; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.model.BusinessProcess; +import uk.gov.hmcts.reform.civil.model.CaseData; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.LIP_CLAIM_SETTLED; + +@Service +@RequiredArgsConstructor +public class LIPClaimSettledCallbackHandler extends CallbackHandler { + + private final ObjectMapper objectMapper; + + private final Map callbackMap = Map.of( + callbackKey(ABOUT_TO_START), this::emptyCallbackResponse, + callbackKey(ABOUT_TO_SUBMIT), this::aboutToSubmit, + callbackKey(SUBMITTED), this::emptySubmittedCallbackResponse); + + @Override + protected Map callbacks() { + return callbackMap; + } + + @Override + public List handledEvents() { + return Collections.singletonList( + LIP_CLAIM_SETTLED + ); + } + + private CallbackResponse aboutToSubmit(CallbackParams callbackParams) { + CaseData caseDataUpdated = callbackParams.getCaseData().toBuilder() + .businessProcess(BusinessProcess.ready(LIP_CLAIM_SETTLED)) + .build(); + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataUpdated.toMap(objectMapper)) + .build(); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/LiftBreathingSpaceLipCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/LiftBreathingSpaceLipCallbackHandler.java new file mode 100644 index 00000000000..413289d07b9 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/LiftBreathingSpaceLipCallbackHandler.java @@ -0,0 +1,57 @@ +package uk.gov.hmcts.reform.civil.handler.callback.user; + +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.civil.callback.Callback; +import uk.gov.hmcts.reform.civil.callback.CallbackHandler; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.model.BusinessProcess; +import uk.gov.hmcts.reform.civil.model.CaseData; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.LIFT_BREATHING_SPACE_LIP; + +@Service +@RequiredArgsConstructor +public class LiftBreathingSpaceLipCallbackHandler extends CallbackHandler { + + private static final List EVENTS = Collections.singletonList(LIFT_BREATHING_SPACE_LIP); + private final Map callbacksMap = Map.of( + callbackKey(ABOUT_TO_START), this::emptyCallbackResponse, + callbackKey(ABOUT_TO_SUBMIT), this::submitLiftBreathingSpace, + callbackKey(SUBMITTED), this::emptySubmittedCallbackResponse + ); + + private final ObjectMapper objectMapper; + + @Override + public List handledEvents() { + return EVENTS; + } + + @Override + protected Map callbacks() { + return callbacksMap; + } + + private CallbackResponse submitLiftBreathingSpace(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + + CaseData.CaseDataBuilder updatedData = caseData.toBuilder() + .businessProcess(BusinessProcess.ready(LIFT_BREATHING_SPACE_LIP)); + + return AboutToStartOrSubmitCallbackResponse.builder() + .data(updatedData.build().toMap(objectMapper)) + .build(); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ManageContactInformationCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ManageContactInformationCallbackHandler.java index 9183d1089c3..1ce5e75b370 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ManageContactInformationCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ManageContactInformationCallbackHandler.java @@ -6,37 +6,75 @@ import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.SubmittedCallbackResponse; import uk.gov.hmcts.reform.civil.callback.Callback; import uk.gov.hmcts.reform.civil.callback.CallbackException; import uk.gov.hmcts.reform.civil.callback.CallbackHandler; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.LitigationFriend; +import uk.gov.hmcts.reform.civil.model.Party; import uk.gov.hmcts.reform.civil.model.UpdateDetailsForm; +import uk.gov.hmcts.reform.civil.model.UpdatePartyDetailsForm; import uk.gov.hmcts.reform.civil.model.common.DynamicList; import uk.gov.hmcts.reform.civil.model.common.DynamicListElement; +import uk.gov.hmcts.reform.civil.model.common.Element; +import uk.gov.hmcts.reform.civil.model.dq.Expert; +import uk.gov.hmcts.reform.civil.model.dq.Witness; import uk.gov.hmcts.reform.civil.service.CoreCaseUserService; import uk.gov.hmcts.reform.civil.service.UserService; +import uk.gov.hmcts.reform.civil.utils.CaseFlagsInitialiser; +import uk.gov.hmcts.reform.civil.validation.PostcodeValidator; import uk.gov.hmcts.reform.idam.client.models.UserInfo; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Map; - +import static java.lang.String.format; +import static java.util.Optional.ofNullable; import static uk.gov.hmcts.reform.civil.callback.CallbackParams.Params.BEARER_TOKEN; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.MANAGE_CONTACT_INFORMATION; +import static uk.gov.hmcts.reform.civil.enums.CaseCategory.SPEC_CLAIM; import static uk.gov.hmcts.reform.civil.enums.CaseState.AWAITING_APPLICANT_INTENTION; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.ONE_V_TWO_TWO_LEGAL_REP; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.getMultiPartyScenario; +import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; +import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.addApplicantExpertAndWitnessFlagsStructure; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.addRespondentDQPartiesFlagStructure; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_EXPERTS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_WITNESSES_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_TWO_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_TWO_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_EXPERTS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_WITNESSES_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_EXPERTS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_WITNESSES_ID; import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.addApplicant1Options; import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.addApplicantOptions2v1; import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.addDefendant1Options; import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.addDefendant2Options; import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.addDefendantOptions1v2SameSolicitor; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.appendUserAndType; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.mapExpertsToUpdatePartyDetailsForm; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.mapUpdatePartyDetailsFormToDQExperts; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.mapUpdatePartyDetailsFormToDQWitnesses; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.mapWitnessesToUpdatePartyDetailsForm; import static uk.gov.hmcts.reform.civil.utils.UserRoleUtils.isApplicantSolicitor; import static uk.gov.hmcts.reform.civil.utils.UserRoleUtils.isRespondentSolicitorOne; import static uk.gov.hmcts.reform.civil.utils.UserRoleUtils.isRespondentSolicitorTwo; @@ -47,6 +85,9 @@ public class ManageContactInformationCallbackHandler extends CallbackHandler { private static final String INVALID_CASE_STATE_ERROR = "You will be able run the manage contact information " + "event once the claimant has responded."; + private static final String CHECK_LITIGATION_FRIEND_ERROR_TITLE = "Check the litigation friend's details"; + private static final String CHECK_LITIGATION_FRIEND_ERROR = "After making these changes, please ensure that the " + + "litigation friend's contact information is also up to date."; private static final List ADMIN_ROLES = List.of( "caseworker-civil-admin"); private static final List EVENTS = List.of( @@ -56,13 +97,18 @@ public class ManageContactInformationCallbackHandler extends CallbackHandler { private final CoreCaseUserService coreCaseUserService; private final UserService userService; private final ObjectMapper objectMapper; + private final CaseDetailsConverter caseDetailsConverter; + private final CaseFlagsInitialiser caseFlagsInitialiser; + private final PostcodeValidator postcodeValidator; @Override protected Map callbacks() { return new ImmutableMap.Builder() - .put(callbackKey(ABOUT_TO_START), this::validateUserCanTriggerEvent) - .put(callbackKey(ABOUT_TO_SUBMIT), this::emptyCallbackResponse) - .put(callbackKey(SUBMITTED), this::emptyCallbackResponse) + .put(callbackKey(ABOUT_TO_START), this::prepareEvent) + .put(callbackKey(MID, "show-party-field"), this::showPartyField) + .put(callbackKey(MID, "show-warning"), this::showWarning) + .put(callbackKey(ABOUT_TO_SUBMIT), this::submitChanges) + .put(callbackKey(SUBMITTED), this::buildConfirmation) .build(); } @@ -71,7 +117,8 @@ public List handledEvents() { return EVENTS; } - private CallbackResponse validateUserCanTriggerEvent(CallbackParams callbackParams) { + private CallbackResponse prepareEvent(CallbackParams callbackParams) { + //TODO: 1v2DS/SS -> LR to show LR org 1/2 dependning on MP CaseData caseData = callbackParams.getCaseData(); String authToken = callbackParams.getParams().get(BEARER_TOKEN).toString(); @@ -146,6 +193,279 @@ private CallbackResponse validateUserCanTriggerEvent(CallbackParams callbackPara .build(); } + private List> prepareExperts(String partyId, CaseData caseData) { + if (partyId.equals(CLAIMANT_ONE_EXPERTS_ID)) { + return mapExpertsToUpdatePartyDetailsForm(caseData.getApplicant1DQ().getExperts().getDetails()); + } else if (partyId.equals(DEFENDANT_ONE_EXPERTS_ID)) { + return mapExpertsToUpdatePartyDetailsForm(caseData.getRespondent1DQ().getExperts().getDetails()); + } else if (partyId.equals(DEFENDANT_TWO_EXPERTS_ID)) { + return mapExpertsToUpdatePartyDetailsForm(caseData.getRespondent2DQ().getExperts().getDetails()); + } + return Collections.emptyList(); + } + + private List> prepareWitnesses(String partyId, CaseData caseData) { + if (partyId.equals(CLAIMANT_ONE_WITNESSES_ID)) { + return mapWitnessesToUpdatePartyDetailsForm(caseData.getApplicant1DQ().getWitnesses().getDetails()); + } else if (partyId.equals(DEFENDANT_ONE_WITNESSES_ID)) { + return mapWitnessesToUpdatePartyDetailsForm(caseData.getRespondent1DQ().getWitnesses().getDetails()); + } else if (partyId.equals(DEFENDANT_TWO_WITNESSES_ID)) { + return mapWitnessesToUpdatePartyDetailsForm(caseData.getRespondent2DQ().getWitnesses().getDetails()); + } + return Collections.emptyList(); + } + + private String getPostCode(String partyChosen, CaseData caseData) { + switch (partyChosen) { + case CLAIMANT_ONE_ID: { + return getPartyPostCode(caseData.getApplicant1()); + } + case CLAIMANT_TWO_ID: { + return getPartyPostCode(caseData.getApplicant2()); + } + case DEFENDANT_ONE_ID: { + return getPartyPostCode(caseData.getRespondent1()); + } + case DEFENDANT_TWO_ID: { + return getPartyPostCode(caseData.getRespondent2()); + } + case CLAIMANT_ONE_LITIGATION_FRIEND_ID: { + return getPartyPostCode(caseData.getApplicant1LitigationFriend()); + } + case CLAIMANT_TWO_LITIGATION_FRIEND_ID: { + return getPartyPostCode(caseData.getApplicant2LitigationFriend()); + } + case DEFENDANT_ONE_LITIGATION_FRIEND_ID: { + return getPartyPostCode(caseData.getRespondent1LitigationFriend()); + } + case DEFENDANT_TWO_LITIGATION_FRIEND_ID: { + return getPartyPostCode(caseData.getRespondent2LitigationFriend()); + } + default: { + return null; + } + } + } + + private String getPartyPostCode(Party party) { + return party.getPrimaryAddress().getPostCode(); + } + + private String getPartyPostCode(LitigationFriend party) { + return party.getPrimaryAddress().getPostCode(); + } + + private CallbackResponse showWarning(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + String partyChosen = caseData.getUpdateDetailsForm().getPartyChosen().getValue().getCode(); + ArrayList warnings = new ArrayList<>(); + List errors = new ArrayList<>(); + + if (partyHasLitigationFriend(partyChosen, caseData)) { + warnings.add(CHECK_LITIGATION_FRIEND_ERROR_TITLE); + warnings.add(CHECK_LITIGATION_FRIEND_ERROR); + } + + if (SPEC_CLAIM.equals(caseData.getCaseAccessCategory())) { + errors = postcodeValidator.validate(getPostCode(partyChosen, caseData)); + } + + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .warnings(warnings) + .errors(errors) + .build(); + } + + private Boolean partyHasLitigationFriend(String partyChosen, CaseData caseData) { + if (hasLitigationFriend(CLAIMANT_ONE_ID, partyChosen, caseData.getApplicant1LitigationFriendRequired()) + || hasLitigationFriend(CLAIMANT_TWO_ID, partyChosen, caseData.getApplicant2LitigationFriendRequired()) + || hasLitigationFriend(DEFENDANT_ONE_ID, partyChosen, caseData.getRespondent1LitigationFriend()) + || hasLitigationFriend(DEFENDANT_TWO_ID, partyChosen, caseData.getRespondent2LitigationFriend()) + ) { + return true; + } + return false; + } + + private Boolean hasLitigationFriend(String id, String partyChosen, YesOrNo litigationFriend) { + return id.equals(partyChosen) && YES.equals(litigationFriend); + } + + private Boolean hasLitigationFriend(String id, String partyChosen, LitigationFriend litigationFriend) { + return id.equals(partyChosen) && litigationFriend != null; + } + + private CallbackResponse showPartyField(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + CaseData.CaseDataBuilder builder = caseData.toBuilder(); + + String partyChosen = caseData.getUpdateDetailsForm().getPartyChosen().getValue().getCode(); + String partyChosenType = null; + + if (isParty(partyChosen) || isLitigationFriend(partyChosen)) { + // Party fields are empty in this mid event, this is a workaround + CaseData oldCaseData = caseDetailsConverter.toCaseData(callbackParams.getRequest().getCaseDetailsBefore()); + String authToken = callbackParams.getParams().get(BEARER_TOKEN).toString(); + boolean isAdmin = isAdmin(authToken); + partyChosenType = appendUserAndType(partyChosen, oldCaseData, isAdmin); + } + + UpdateDetailsForm.UpdateDetailsFormBuilder formBuilder = caseData.getUpdateDetailsForm().toBuilder() + .partyChosenId(partyChosen) + .partyChosenType(partyChosenType) + .updateExpertsDetailsForm(prepareExperts(partyChosen, caseData)) + .updateWitnessesDetailsForm(prepareWitnesses(partyChosen, caseData)) + .build().toBuilder(); + + builder.updateDetailsForm(formBuilder.build()); + + return AboutToStartOrSubmitCallbackResponse.builder() + .data(builder.build().toMap(objectMapper)) + .build(); + } + + private Boolean isParty(String partyChosen) { + return CLAIMANT_ONE_ID.equals(partyChosen) + || CLAIMANT_TWO_ID.equals(partyChosen) + || DEFENDANT_ONE_ID.equals(partyChosen) + || DEFENDANT_TWO_ID.equals(partyChosen); + } + + private Boolean isLitigationFriend(String partyChosen) { + return CLAIMANT_ONE_LITIGATION_FRIEND_ID.equals(partyChosen) + || CLAIMANT_TWO_LITIGATION_FRIEND_ID.equals(partyChosen) + || DEFENDANT_ONE_LITIGATION_FRIEND_ID.equals(partyChosen) + || DEFENDANT_TWO_LITIGATION_FRIEND_ID.equals(partyChosen); + } + + private CallbackResponse submitChanges(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + CaseData.CaseDataBuilder builder = caseData.toBuilder(); + + updateExperts(caseData.getUpdateDetailsForm().getPartyChosenId(), caseData, builder); + updateWitnesses(caseData.getUpdateDetailsForm().getPartyChosenId(), caseData, builder); + + // last step before clearing update details form + caseFlagsInitialiser.initialiseCaseFlags(MANAGE_CONTACT_INFORMATION, builder); + + // clear updateDetailsForm + builder.updateDetailsForm(UpdateDetailsForm.builder().manageContactDetailsEventUsed(YES).build()); + + // update claim details tab + updateClaimDetailsTab(caseData, builder); + + return AboutToStartOrSubmitCallbackResponse.builder() + .data(builder.build().toMap(objectMapper)) + .build(); + } + + private void updateClaimDetailsTab(CaseData caseData, CaseData.CaseDataBuilder builder) { + builder.respondent1DetailsForClaimDetailsTab(caseData.getRespondent1().toBuilder().flags(null).build()); + + if (ofNullable(caseData.getRespondent2()).isPresent()) { + builder.respondent2DetailsForClaimDetailsTab(caseData.getRespondent2().toBuilder().flags(null).build()); + } + } + + // wip can't be tested yet because need to get ids from new ticket: CIV-10382 + // have to delete experts (yes/no etc) if the experts are removed, same as witnesses + + private void updateExperts(String partyId, CaseData caseData, CaseData.CaseDataBuilder builder) { + List> formData = caseData.getUpdateDetailsForm().getUpdateExpertsDetailsForm(); + List> mappedExperts; + + if (partyId.equals(CLAIMANT_ONE_EXPERTS_ID)) { + mappedExperts = mapUpdatePartyDetailsFormToDQExperts( + caseData.getApplicant1DQ().getApplicant1DQExperts().getDetails(), formData); + builder.applicant1DQ(caseData.getApplicant1DQ().toBuilder() + .applicant1DQExperts( + caseData.getApplicant1DQ().getApplicant1DQExperts().toBuilder() + .expertRequired(mappedExperts.size() >= 1 ? YES : NO) + .details(mappedExperts) + .build()) + .build()); + addApplicantExpertAndWitnessFlagsStructure(builder, caseData); + //TODO: need to add it to top level party object + } else if (partyId.equals(DEFENDANT_ONE_EXPERTS_ID)) { + mappedExperts = mapUpdatePartyDetailsFormToDQExperts( + caseData.getRespondent1DQ().getRespondent1DQExperts().getDetails(), formData); + builder.respondent1DQ(caseData.getRespondent1DQ().toBuilder() + .respondent1DQExperts( + caseData.getRespondent1DQ().getRespondent1DQExperts().toBuilder() + .expertRequired(mappedExperts.size() >= 1 ? YES : NO) + .details(mappedExperts) + .build()) + .build()); + addRespondentDQPartiesFlagStructure(builder, caseData); + //TODO: need to add it to top level party object + } else if (partyId.equals(DEFENDANT_TWO_EXPERTS_ID)) { + mappedExperts = mapUpdatePartyDetailsFormToDQExperts( + caseData.getRespondent2DQ().getRespondent2DQExperts().getDetails(), formData); + builder.respondent2DQ(caseData.getRespondent2DQ().toBuilder() + .respondent2DQExperts( + caseData.getRespondent2DQ().getRespondent2DQExperts().toBuilder() + .expertRequired(mappedExperts.size() >= 1 ? YES : NO) + .details(mappedExperts) + .build()) + .build()); + addRespondentDQPartiesFlagStructure(builder, caseData); + //TODO: need to add it to top level party object + } + + } + + private void updateWitnesses(String partyId, CaseData caseData, CaseData.CaseDataBuilder builder) { + List> formData = caseData.getUpdateDetailsForm().getUpdateWitnessesDetailsForm(); + List> mappedWitnesses; + + if (partyId.equals(CLAIMANT_ONE_WITNESSES_ID)) { + mappedWitnesses = mapUpdatePartyDetailsFormToDQWitnesses( + caseData.getApplicant1DQ().getApplicant1DQWitnesses().getDetails(), formData); + builder.applicant1DQ(caseData.getApplicant1DQ().toBuilder() + .applicant1DQWitnesses( + caseData.getApplicant1DQ().getApplicant1DQWitnesses().toBuilder() + .witnessesToAppear(mappedWitnesses.size() >= 1 ? YES : NO) + .details(mappedWitnesses) + .build()) + .build()); + addApplicantExpertAndWitnessFlagsStructure(builder, caseData); + //TODO: need to add it to top level party object + } else if (partyId.equals(DEFENDANT_ONE_WITNESSES_ID)) { + mappedWitnesses = mapUpdatePartyDetailsFormToDQWitnesses( + caseData.getRespondent1DQ().getRespondent1DQWitnesses().getDetails(), formData); + builder.respondent1DQ(caseData.getRespondent1DQ().toBuilder() + .respondent1DQWitnesses( + caseData.getRespondent1DQ().getRespondent1DQWitnesses().toBuilder() + .witnessesToAppear(mappedWitnesses.size() >= 1 ? YES : NO) + .details(mappedWitnesses) + .build()) + .build()); + addRespondentDQPartiesFlagStructure(builder, caseData); + //TODO: need to add it to top level party object + } else if (partyId.equals(DEFENDANT_TWO_WITNESSES_ID)) { + mappedWitnesses = mapUpdatePartyDetailsFormToDQWitnesses( + caseData.getRespondent2DQ().getRespondent2DQWitnesses().getDetails(), formData); + builder.respondent2DQ(caseData.getRespondent2DQ().toBuilder() + .respondent2DQWitnesses( + caseData.getRespondent2DQ().getRespondent2DQWitnesses().toBuilder() + .witnessesToAppear(mappedWitnesses.size() >= 1 ? YES : NO) + .details(mappedWitnesses) + .build()) + .build()); + addRespondentDQPartiesFlagStructure(builder, caseData); + //TODO: need to add it to top level party object + } + } + + private SubmittedCallbackResponse buildConfirmation(CallbackParams callbackParams) { + return SubmittedCallbackResponse.builder() + .confirmationHeader(format("# Contact information changed")) + .confirmationBody(format("### What happens next\nAny changes made to contact details have been updated in the Claim Details tab.")) + .build(); + } + private boolean isAwaitingClaimantIntention(CaseData caseData) { return caseData.getCcdState().equals(AWAITING_APPLICANT_INTENTION); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ManageDocumentsHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ManageDocumentsHandler.java index 448948a0c25..f4ed2daf9cb 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ManageDocumentsHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/ManageDocumentsHandler.java @@ -44,5 +44,4 @@ private CallbackResponse uploadManageDocuments(CallbackParams callbackParams) { .data(callbackParams.getCaseData().toMap(objectMapper)) .build(); } - } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/MediationSuccessfulCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/MediationSuccessfulCallbackHandler.java index d3638000a4a..8e1551a28f4 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/MediationSuccessfulCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/MediationSuccessfulCallbackHandler.java @@ -12,13 +12,21 @@ import uk.gov.hmcts.reform.civil.callback.CaseEvent; import uk.gov.hmcts.reform.civil.model.BusinessProcess; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.Mediation; +import uk.gov.hmcts.reform.civil.model.MediationSuccessful; +import uk.gov.hmcts.reform.civil.model.MediationAgreementDocument; +import uk.gov.hmcts.reform.civil.model.citizenui.DocumentTypeMapper; +import uk.gov.hmcts.reform.civil.model.citizenui.ManageDocument; +import uk.gov.hmcts.reform.civil.model.common.Element; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Optional; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.MEDIATION_SUCCESSFUL; import static uk.gov.hmcts.reform.civil.enums.CaseState.CASE_STAYED; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.element; @Service @RequiredArgsConstructor @@ -41,12 +49,36 @@ public List handledEvents() { } private CallbackResponse submitSuccessfulMediation(CallbackParams callbackParams) { + List> updatedManageDocumentsList = + updateManageDocumentsListWithMediationAgreementDocument(callbackParams); + CaseData caseDataUpdated = callbackParams.getCaseData().toBuilder() .businessProcess(BusinessProcess.ready(MEDIATION_SUCCESSFUL)) + .manageDocuments(updatedManageDocumentsList) .build(); + return AboutToStartOrSubmitCallbackResponse.builder() .data(caseDataUpdated.toMap(objectMapper)) .state(CASE_STAYED.name()) .build(); } + + private List> updateManageDocumentsListWithMediationAgreementDocument( + CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + List> manageDocumentsList = caseData.getManageDocumentsList(); + Optional mediationAgreementDocument = Optional.ofNullable(caseData.getMediation()) + .map(Mediation::getMediationSuccessful) + .map(MediationSuccessful::getMediationAgreement); + + mediationAgreementDocument.ifPresent(document -> { + ManageDocument manageDocument = ManageDocument.builder() + .documentLink(document.getDocument()) + .documentName(document.getName()) + .documentType(DocumentTypeMapper.mapDocumentTypeToManageDocumentType(document.getDocumentType())) + .build(); + manageDocumentsList.add(element(manageDocument)); + }); + return manageDocumentsList; + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/NotSuitableSDOCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/NotSuitableSDOCallbackHandler.java index e1f2c8cb218..2b016d5542a 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/NotSuitableSDOCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/NotSuitableSDOCallbackHandler.java @@ -11,10 +11,13 @@ import uk.gov.hmcts.reform.civil.callback.CallbackHandler; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.model.transferonlinecase.NotSuitableSdoOptions; import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.model.BusinessProcess; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.sdo.OtherDetails; +import uk.gov.hmcts.reform.civil.model.transferonlinecase.TransferCaseDetails; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.Time; import java.util.ArrayList; @@ -38,10 +41,15 @@ public class NotSuitableSDOCallbackHandler extends CallbackHandler { + "a notification will be sent to the listing officer to look at this case offline." + "%n%nIf a legal adviser has submitted this information a notification will be sent to a judge for review."; + public static final String NOT_SUITABLE_SDO_TRANSFER_CASE_CONFIRMATION_BODY = "
A notification will be sent" + + " to the listing officer to look at this case and process the transfer of case."; + private final ObjectMapper objectMapper; private final Time time; + private final FeatureToggleService toggleService; + @Override protected Map callbacks() { return new ImmutableMap.Builder() @@ -59,14 +67,24 @@ public List handledEvents() { private CallbackResponse submitNotSuitableSDO(CallbackParams callbackParams) { CaseData.CaseDataBuilder dataBuilder = getSharedData(callbackParams); - OtherDetails tempOtherDetails = OtherDetails.builder() .notSuitableForSDO(YesOrNo.YES) - .reasonNotSuitableForSDO(callbackParams.getCaseData().getReasonNotSuitableSDO().getInput()) .build(); - + if (toggleService.isTransferOnlineCaseEnabled()) { + if (callbackParams.getCaseData().getNotSuitableSdoOptions() == NotSuitableSdoOptions.CHANGE_LOCATION) { + dataBuilder.notSuitableSdoOptions(NotSuitableSdoOptions.CHANGE_LOCATION); + TransferCaseDetails transferCaseDetails = TransferCaseDetails.builder() + .reasonForTransferCaseTxt(callbackParams.getCaseData().getTocTransferCaseReason().getReasonForCaseTransferJudgeTxt()) + .build(); + dataBuilder.transferCaseDetails(transferCaseDetails).build(); + } else { + dataBuilder.notSuitableSdoOptions(NotSuitableSdoOptions.OTHER_REASONS); + tempOtherDetails.setReasonNotSuitableForSDO(callbackParams.getCaseData().getReasonNotSuitableSDO().getInput()); + } + } else { + tempOtherDetails.setReasonNotSuitableForSDO(callbackParams.getCaseData().getReasonNotSuitableSDO().getInput()); + } dataBuilder.otherDetails(tempOtherDetails).build(); - return AboutToStartOrSubmitCallbackResponse.builder() .data(dataBuilder.build().toMap(objectMapper)) .build(); @@ -74,14 +92,17 @@ private CallbackResponse submitNotSuitableSDO(CallbackParams callbackParams) { private CallbackResponse validateNotSuitableReason(CallbackParams callbackParams) { final int lengthAllowed = 150; - List errors = new ArrayList<>(); - var reason = callbackParams.getCaseData().getReasonNotSuitableSDO().getInput(); - + String reason; + if (isTransferOnlineCase(callbackParams.getCaseData())) { + reason = callbackParams.getCaseData().getTocTransferCaseReason().getReasonForCaseTransferJudgeTxt(); + } else { + reason = callbackParams.getCaseData().getReasonNotSuitableSDO().getInput(); + } if (reason.length() > lengthAllowed) { errors.add("Character Limit Reached: " - + "Reason for not drawing Standard Directions order cannot exceed " - + lengthAllowed + " characters."); + + "Reason for not drawing Standard Directions order cannot exceed " + + lengthAllowed + " characters."); } return AboutToStartOrSubmitCallbackResponse.builder() .errors(errors) @@ -101,19 +122,27 @@ private CallbackResponse addUnsuitableSDODate(CallbackParams callbackParams) { private CaseData.CaseDataBuilder getSharedData(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); CaseData.CaseDataBuilder dataBuilder = caseData.toBuilder(); - - dataBuilder.businessProcess(BusinessProcess.ready(NotSuitable_SDO)); - + if (isTransferOnlineCase(caseData)) { + return dataBuilder; + } else { + dataBuilder.businessProcess(BusinessProcess.ready(NotSuitable_SDO)); + } return dataBuilder; } private SubmittedCallbackResponse buildConfirmation(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); - - return SubmittedCallbackResponse.builder() - .confirmationHeader(getHeader(caseData)) - .confirmationBody(getBody(caseData)) - .build(); + if (isTransferOnlineCase(caseData)) { + return SubmittedCallbackResponse.builder() + .confirmationHeader(getHeaderTOC(caseData)) + .confirmationBody(getBodyTOC(caseData)) + .build(); + } else { + return SubmittedCallbackResponse.builder() + .confirmationHeader(getHeader(caseData)) + .confirmationBody(getBody(caseData)) + .build(); + } } private String getHeader(CaseData caseData) { @@ -124,4 +153,19 @@ private String getBody(CaseData caseData) { return format(NotSuitableSDO_CONFIRMATION_BODY); } + private boolean isTransferOnlineCase(CaseData caseData) { + if (toggleService.isTransferOnlineCaseEnabled() && caseData.getNotSuitableSdoOptions() == NotSuitableSdoOptions.CHANGE_LOCATION) { + return true; + } else { + return false; + } + } + + private String getHeaderTOC(CaseData caseData) { + return format("# Your request was successful%n## This claim will be transferred to a different location"); + } + + private String getBodyTOC(CaseData caseData) { + return format(NOT_SUITABLE_SDO_TRANSFER_CASE_CONFIRMATION_BODY); + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RecordJudgmentCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RecordJudgmentCallbackHandler.java new file mode 100644 index 00000000000..820ba3c46a2 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RecordJudgmentCallbackHandler.java @@ -0,0 +1,126 @@ +package uk.gov.hmcts.reform.civil.handler.callback.user; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.SubmittedCallbackResponse; +import uk.gov.hmcts.reform.civil.callback.Callback; +import uk.gov.hmcts.reform.civil.callback.CallbackHandler; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.helpers.judgmentsonline.JudgmentsOnlineHelper; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentStatusDetails; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentStatusType; +import uk.gov.hmcts.reform.civil.model.judgmentonline.PaymentPlanSelection; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.RECORD_JUDGMENT; + +@Service +@RequiredArgsConstructor +public class RecordJudgmentCallbackHandler extends CallbackHandler { + + private static final List EVENTS = Collections.singletonList(RECORD_JUDGMENT); + protected final ObjectMapper objectMapper; + private static final String ERROR_MESSAGE_DATE_PAID_BY_MUST_BE_IN_FUTURE = "Date the judgment will be paid by must be in the future"; + private static final String ERROR_MESSAGE_DATE_FIRST_INSTALMENT_MUST_BE_IN_FUTURE = "Date of first instalment must be in the future"; + private static final String ERROR_MESSAGE_DATE_ORDER_MUST_BE_IN_PAST = "Date judge made the order must be in the past"; + + @Override + protected Map callbacks() { + return new ImmutableMap.Builder() + .put(callbackKey(ABOUT_TO_START), this::clearAllFields) + .put(callbackKey(MID, "validateDates"), this::validateDates) + .put(callbackKey(ABOUT_TO_SUBMIT), this::saveJudgmentDetails) + .put(callbackKey(SUBMITTED), this::buildConfirmation) + .build(); + } + + private CallbackResponse validateDates(CallbackParams callbackParams) { + var caseData = callbackParams.getCaseData(); + List errors = new ArrayList<>(); + boolean isOrderMadeFutureDate = + JudgmentsOnlineHelper.validateIfFutureDate(callbackParams.getCaseData().getJoOrderMadeDate()); + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + if (isOrderMadeFutureDate) { + errors.add(ERROR_MESSAGE_DATE_ORDER_MUST_BE_IN_PAST); + } + if (callbackParams.getCaseData().getJoPaymentPlanSelection().equals(PaymentPlanSelection.PAY_BY_DATE)) { + boolean isFutureDate = + JudgmentsOnlineHelper.validateIfFutureDate(callbackParams.getCaseData().getJoPaymentToBeMadeByDate()); + if (!isFutureDate) { + errors.add(ERROR_MESSAGE_DATE_PAID_BY_MUST_BE_IN_FUTURE); + } + } else if (callbackParams.getCaseData().getJoPaymentPlanSelection().equals(PaymentPlanSelection.PAY_IN_INSTALMENTS)) { + boolean isFutureDate = + JudgmentsOnlineHelper.validateIfFutureDate(callbackParams.getCaseData().getJoJudgmentInstalmentDetails().getFirstInstalmentDate()); + if (!isFutureDate) { + errors.add(ERROR_MESSAGE_DATE_FIRST_INSTALMENT_MUST_BE_IN_FUTURE); + } + } + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .errors(errors) + .build(); + } + + private CallbackResponse clearAllFields(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + caseData.setJoOrderMadeDate(null); + caseData.setJoJudgmentStatusDetails(null); + caseData.setJoPaymentPlanSelection(null); + caseData.setJoJudgmentInstalmentDetails(null); + caseData.setJoJudgmentRecordReason(null); + caseData.setJoAmountOrdered(null); + caseData.setJoAmountCostOrdered(null); + caseData.setJoIsRegisteredWithRTL(null); + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .build(); + } + + private CallbackResponse buildConfirmation(CallbackParams callbackParams) { + return SubmittedCallbackResponse.builder() + .confirmationHeader("# Judgment recorded") + .confirmationBody("The judgment has been recorded") + .build(); + } + + private CallbackResponse saveJudgmentDetails(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + JudgmentStatusDetails judgmentStatusDetails = JudgmentStatusDetails.builder() + .judgmentStatusTypes(JudgmentStatusType.ISSUED) + .lastUpdatedDate(LocalDateTime.now()).build(); + if (caseData.getJoIsRegisteredWithRTL() == YesOrNo.YES) { + judgmentStatusDetails.setJoRtlState(JudgmentsOnlineHelper.getRTLStatusBasedOnJudgementStatus(JudgmentStatusType.ISSUED)); + } + caseData.setJoJudgmentStatusDetails(judgmentStatusDetails); + caseData.setJoIsLiveJudgmentExists(YesOrNo.YES); + caseData.setJoSetAsideDate(null); + caseData.setJoJudgmentPaidInFull(null); + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .build(); + } + + @Override + public List handledEvents() { + return EVENTS; + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RequestJudgementByAdmissionForSpecCuiCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RequestJudgementByAdmissionForSpecCuiCallbackHandler.java index 37214488388..aebd58fee07 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RequestJudgementByAdmissionForSpecCuiCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RequestJudgementByAdmissionForSpecCuiCallbackHandler.java @@ -14,7 +14,9 @@ import uk.gov.hmcts.reform.civil.enums.CaseState; import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; import uk.gov.hmcts.reform.civil.model.BusinessProcess; +import uk.gov.hmcts.reform.civil.model.CCJPaymentDetails; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.JudgementService; import java.util.ArrayList; @@ -38,6 +40,7 @@ public class RequestJudgementByAdmissionForSpecCuiCallbackHandler extends Callba private final ObjectMapper objectMapper; private final JudgementService judgementService; private final CaseDetailsConverter caseDetailsConverter; + private final FeatureToggleService featureToggleService; @Override protected Map callbacks() { @@ -61,7 +64,7 @@ private CallbackResponse validateDefaultJudgementEligibility(CallbackParams call CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); ArrayList errors = new ArrayList<>(); if (caseData.isJudgementDateNotPermitted()) { - errors.add(format(NOT_VALID_DJ_BY_ADMISSION, caseData.setUpJudgementFormattedPermittedDate())); + errors.add(format(NOT_VALID_DJ_BY_ADMISSION, caseData.setUpJudgementFormattedPermittedDate(caseData.getRespondToClaimAdmitPartLRspec().getWhenWillThisAmountBePaid()))); } return AboutToStartOrSubmitCallbackResponse.builder() @@ -91,9 +94,13 @@ private CallbackResponse validateAmountPaid(CallbackParams callbackParams) { private CallbackResponse updateBusinessProcessToReady(CallbackParams callbackParams) { CaseData data = caseDetailsConverter.toCaseData(callbackParams.getRequest().getCaseDetails()); - + CCJPaymentDetails + ccjPaymentDetails = data.isLipvLipOneVOne() && featureToggleService.isLipVLipEnabled() + ? judgementService.buildJudgmentAmountSummaryDetails(data) : + data.getCcjPaymentDetails(); CaseData.CaseDataBuilder caseDataBuilder = data.toBuilder() - .businessProcess(BusinessProcess.ready(REQUEST_JUDGEMENT_ADMISSION_SPEC)); + .businessProcess(BusinessProcess.ready(REQUEST_JUDGEMENT_ADMISSION_SPEC)) + .ccjPaymentDetails(ccjPaymentDetails); return AboutToStartOrSubmitCallbackResponse.builder() .data(caseDataBuilder.build().toMap(objectMapper)) diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimCallbackHandler.java index 945e64a2e60..3eb2b56f0e8 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimCallbackHandler.java @@ -13,6 +13,7 @@ import uk.gov.hmcts.reform.civil.callback.CaseEvent; import uk.gov.hmcts.reform.civil.enums.AllocatedTrack; import uk.gov.hmcts.reform.civil.enums.CaseRole; +import uk.gov.hmcts.reform.civil.enums.DocCategory; import uk.gov.hmcts.reform.civil.enums.MultiPartyResponseTypeFlags; import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; import uk.gov.hmcts.reform.civil.enums.RespondentResponseType; @@ -46,6 +47,7 @@ import uk.gov.hmcts.reform.civil.utils.AssignCategoryId; import uk.gov.hmcts.reform.civil.utils.CaseFlagsInitialiser; import uk.gov.hmcts.reform.civil.utils.CourtLocationUtils; +import uk.gov.hmcts.reform.civil.utils.ElementUtils; import uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils; import uk.gov.hmcts.reform.civil.validation.DateOfBirthValidator; import uk.gov.hmcts.reform.civil.validation.UnavailableDateValidator; @@ -59,6 +61,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import static java.lang.String.format; @@ -77,13 +80,14 @@ import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.getMultiPartyScenario; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; +import static uk.gov.hmcts.reform.civil.handler.tasks.BaseExternalTaskHandler.log; import static uk.gov.hmcts.reform.civil.helpers.DateFormatHelper.DATE; import static uk.gov.hmcts.reform.civil.helpers.DateFormatHelper.formatLocalDateTime; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowFlag.TWO_RESPONDENT_REPRESENTATIVES; import static uk.gov.hmcts.reform.civil.utils.CaseListSolicitorReferenceUtils.getAllDefendantSolicitorReferences; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.buildElemCaseDocument; import static uk.gov.hmcts.reform.civil.utils.ExpertUtils.addEventAndDateAddedToRespondentExperts; -import static uk.gov.hmcts.reform.civil.utils.PartyUtils.populateWithPartyIds; +import static uk.gov.hmcts.reform.civil.utils.PartyUtils.populateDQPartyIds; import static uk.gov.hmcts.reform.civil.utils.WitnessUtils.addEventAndDateAddedToRespondentWitnesses; @Service @@ -202,12 +206,14 @@ private CallbackResponse populateRespondentCopyObjects(CallbackParams callbackPa .respondent2DQRequestedCourt(requestedCourt1.build()).build()); } - updatedCaseData.respondent1DetailsForClaimDetailsTab(updatedCaseData.build().getRespondent1()); + updatedCaseData.respondent1DetailsForClaimDetailsTab(updatedCaseData.build().getRespondent1() + .toBuilder().flags(null).build()); if (ofNullable(caseData.getRespondent2()).isPresent()) { updatedCaseData .respondent2Copy(caseData.getRespondent2()) - .respondent2DetailsForClaimDetailsTab(updatedCaseData.build().getRespondent2()); + .respondent2DetailsForClaimDetailsTab(updatedCaseData.build().getRespondent2() + .toBuilder().flags(null).build()); } return AboutToStartOrSubmitCallbackResponse.builder() .data(updatedCaseData.build().toMap(objectMapper)) @@ -356,6 +362,7 @@ private CallbackResponse setApplicantResponseDeadline(CallbackParams callbackPar // persist respondent address (ccd issue) var updatedRespondent1 = caseData.getRespondent1().toBuilder() .primaryAddress(caseData.getRespondent1Copy().getPrimaryAddress()) + .flags(caseData.getRespondent1Copy().getFlags()) .build(); CaseData.CaseDataBuilder updatedData = caseData.toBuilder() @@ -367,6 +374,7 @@ private CallbackResponse setApplicantResponseDeadline(CallbackParams callbackPar && ofNullable(caseData.getRespondent2Copy()).isPresent()) { var updatedRespondent2 = caseData.getRespondent2().toBuilder() .primaryAddress(caseData.getRespondent2Copy().getPrimaryAddress()) + .flags(caseData.getRespondent2Copy().getFlags()) .build(); updatedData.respondent2(updatedRespondent2).respondent2Copy(null); @@ -484,7 +492,7 @@ && ofNullable(caseData.getRespondent2Copy()).isPresent()) { updatedData .respondent2(updatedRespondent2) .respondent2Copy(null) - .respondent2DetailsForClaimDetailsTab(updatedRespondent2); + .respondent2DetailsForClaimDetailsTab(updatedRespondent2.toBuilder().flags(null).build()); if (caseData.getRespondent2ResponseDate() == null) { updatedData.nextDeadline(caseData.getRespondent2ResponseDeadline().toLocalDate()); @@ -523,9 +531,13 @@ && ofNullable(caseData.getRespondent2Copy()).isPresent()) { UnavailabilityDatesUtils.rollUpUnavailabilityDatesForRespondent(updatedData, toggleService.isUpdateContactDetailsEnabled()); - updatedData.respondent1DetailsForClaimDetailsTab(updatedData.build().getRespondent1()); + updatedData.respondent1DetailsForClaimDetailsTab(updatedData.build().getRespondent1().toBuilder().flags(null).build()); if (ofNullable(caseData.getRespondent2()).isPresent()) { - updatedData.respondent2DetailsForClaimDetailsTab(updatedData.build().getRespondent2()); + updatedData.respondent2DetailsForClaimDetailsTab(updatedData.build().getRespondent2().toBuilder().flags(null).build()); + } + + if (toggleService.isHmcEnabled()) { + populateDQPartyIds(updatedData); } caseFlagsInitialiser.initialiseCaseFlags(DEFENDANT_RESPONSE, updatedData); @@ -552,8 +564,16 @@ && isAwaitingAnotherDefendantResponse(caseData)) { .build(); } - if (toggleService.isHmcEnabled()) { - populateWithPartyIds(updatedData); + // these documents are added to defendantUploads, if we do not remove/null the original, + // case file view will show duplicate documents + if (toggleService.isCaseFileViewEnabled()) { + log.info("Null placeholder documents"); + updatedData.respondent1ClaimResponseDocument(null); + updatedData.respondent2ClaimResponseDocument(null); + updatedData.respondent1DQ(updatedData.build().getRespondent1DQ().toBuilder().respondent1DQDraftDirections(null).build()); + if (caseData.getRespondent2() != null) { + updatedData.respondent2DQ(updatedData.build().getRespondent2DQ().toBuilder().respondent2DQDraftDirections(null).build()); + } } return AboutToStartOrSubmitCallbackResponse.builder() @@ -616,13 +636,19 @@ private void assembleResponseDocuments(CaseData caseData, CaseData.CaseDataBuild if (respondent1ClaimResponseDocument != null) { uk.gov.hmcts.reform.civil.documentmanagement.model.Document respondent1ClaimDocument = respondent1ClaimResponseDocument.getFile(); if (respondent1ClaimDocument != null) { - defendantUploads.add( - buildElemCaseDocument(respondent1ClaimDocument, "Defendant", - updatedCaseData.build().getRespondent1ResponseDate(), - DocumentType.DEFENDANT_DEFENCE - )); + Element documentElement = + buildElemCaseDocument(respondent1ClaimDocument, "Defendant", + updatedCaseData.build().getRespondent1ResponseDate(), + DocumentType.DEFENDANT_DEFENCE + ); assignCategoryId.assignCategoryIdToDocument(respondent1ClaimDocument, - "defendant1DefenseDirectionsQuestionnaire"); + DocCategory.DEF1_DEFENSE_DQ.getValue()); + CaseDocument copy = assignCategoryId + .copyCaseDocumentWithCategoryId(documentElement.getValue(), DocCategory.DQ_DEF1.getValue()); + defendantUploads.add(documentElement); + if (Objects.nonNull(copy)) { + defendantUploads.add(ElementUtils.element(copy)); + } } } @@ -630,15 +656,20 @@ private void assembleResponseDocuments(CaseData caseData, CaseData.CaseDataBuild if (respondent1DQ != null) { uk.gov.hmcts.reform.civil.documentmanagement.model.Document respondent1DQDraftDirections = respondent1DQ.getRespondent1DQDraftDirections(); if (respondent1DQDraftDirections != null) { - defendantUploads.add( - buildElemCaseDocument( + Element documentElement = buildElemCaseDocument( respondent1DQDraftDirections, "Defendant", updatedCaseData.build().getRespondent1ResponseDate(), DocumentType.DEFENDANT_DRAFT_DIRECTIONS - )); + ); assignCategoryId.assignCategoryIdToDocument(respondent1DQDraftDirections, - "defendant1DefenseDirectionsQuestionnaire"); + DocCategory.DEF1_DEFENSE_DQ.getValue()); + CaseDocument copy = assignCategoryId + .copyCaseDocumentWithCategoryId(documentElement.getValue(), DocCategory.DQ_DEF1.getValue()); + defendantUploads.add(documentElement); + if (Objects.nonNull(copy)) { + defendantUploads.add(ElementUtils.element(copy)); + } } } @@ -646,28 +677,39 @@ private void assembleResponseDocuments(CaseData caseData, CaseData.CaseDataBuild if (respondent2ClaimResponseDocument != null) { uk.gov.hmcts.reform.civil.documentmanagement.model.Document respondent2ClaimDocument = respondent2ClaimResponseDocument.getFile(); if (respondent2ClaimDocument != null) { - defendantUploads.add( - buildElemCaseDocument(respondent2ClaimDocument, "Defendant 2", - updatedCaseData.build().getRespondent2ResponseDate(), - DocumentType.DEFENDANT_DEFENCE - )); + Element documentElement = buildElemCaseDocument( + respondent2ClaimDocument, "Defendant 2", + updatedCaseData.build().getRespondent2ResponseDate(), + DocumentType.DEFENDANT_DEFENCE + ); + CaseDocument copy = assignCategoryId + .copyCaseDocumentWithCategoryId(documentElement.getValue(), DocCategory.DQ_DEF2.getValue()); assignCategoryId.assignCategoryIdToDocument(respondent2ClaimDocument, - "defendant2DefenseDirectionsQuestionnaire"); + DocCategory.DEF2_DEFENSE_DQ.getValue()); + defendantUploads.add(documentElement); + if (Objects.nonNull(copy)) { + defendantUploads.add(ElementUtils.element(copy)); + } } } Respondent2DQ respondent2DQ = caseData.getRespondent2DQ(); if (respondent2DQ != null) { uk.gov.hmcts.reform.civil.documentmanagement.model.Document respondent2DQDraftDirections = respondent2DQ.getRespondent2DQDraftDirections(); if (respondent2DQDraftDirections != null) { - defendantUploads.add( - buildElemCaseDocument( + Element documentElement = buildElemCaseDocument( respondent2DQDraftDirections, "Defendant 2", updatedCaseData.build().getRespondent2ResponseDate(), DocumentType.DEFENDANT_DRAFT_DIRECTIONS - )); + ); + CaseDocument copy = assignCategoryId + .copyCaseDocumentWithCategoryId(documentElement.getValue(), DocCategory.DQ_DEF2.getValue()); assignCategoryId.assignCategoryIdToDocument(respondent2DQDraftDirections, - "defendant2DefenseDirectionsQuestionnaire"); + DocCategory.DEF2_DEFENSE_DQ.getValue()); + defendantUploads.add(documentElement); + if (Objects.nonNull(copy)) { + defendantUploads.add(ElementUtils.element(copy)); + } } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimCuiCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimCuiCallbackHandler.java index 862e5297404..b4ce2c6b1b2 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimCuiCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimCuiCallbackHandler.java @@ -69,7 +69,7 @@ private CallbackResponse aboutToSubmit(CallbackParams callbackParams) { private CaseData getUpdatedCaseData(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); - CaseDocument dummyDocument = new CaseDocument(null, null, null, 0, null, null); + CaseDocument dummyDocument = new CaseDocument(null, null, null, 0, null, null, null); LocalDateTime responseDate = time.now(); AllocatedTrack allocatedTrack = caseData.getAllocatedTrack(); CaseData updatedData = caseData.toBuilder() diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimSpecCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimSpecCallbackHandler.java index cd427bee902..df862ffbf82 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimSpecCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimSpecCallbackHandler.java @@ -17,8 +17,10 @@ import uk.gov.hmcts.reform.civil.enums.AllocatedTrack; import uk.gov.hmcts.reform.civil.enums.CaseRole; import uk.gov.hmcts.reform.civil.enums.CaseState; +import uk.gov.hmcts.reform.civil.enums.DocCategory; import uk.gov.hmcts.reform.civil.enums.MultiPartyResponseTypeFlags; import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; +import uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec; import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec; import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpecPaidStatus; import uk.gov.hmcts.reform.civil.enums.TimelineUploadTypeSpec; @@ -54,10 +56,12 @@ import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.Time; import uk.gov.hmcts.reform.civil.service.UserService; +import uk.gov.hmcts.reform.civil.service.citizenui.responsedeadline.DeadlineExtensionCalculatorService; import uk.gov.hmcts.reform.civil.service.flowstate.StateFlowEngine; import uk.gov.hmcts.reform.civil.utils.AssignCategoryId; import uk.gov.hmcts.reform.civil.utils.CaseFlagsInitialiser; import uk.gov.hmcts.reform.civil.utils.CourtLocationUtils; +import uk.gov.hmcts.reform.civil.utils.ElementUtils; import uk.gov.hmcts.reform.civil.utils.MonetaryConversions; import uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils; import uk.gov.hmcts.reform.civil.validation.DateOfBirthValidator; @@ -133,6 +137,7 @@ import static uk.gov.hmcts.reform.civil.utils.ElementUtils.buildElemCaseDocument; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; import static uk.gov.hmcts.reform.civil.utils.ExpertUtils.addEventAndDateAddedToRespondentExperts; +import static uk.gov.hmcts.reform.civil.utils.PartyUtils.populateDQPartyIds; import static uk.gov.hmcts.reform.civil.utils.PartyUtils.populateWithPartyIds; import static uk.gov.hmcts.reform.civil.utils.WitnessUtils.addEventAndDateAddedToRespondentWitnesses; @@ -142,6 +147,7 @@ public class RespondToClaimSpecCallbackHandler extends CallbackHandler implements ExpertsValidator, WitnessesValidator, DefendantAddressValidator { private static final List EVENTS = Collections.singletonList(DEFENDANT_RESPONSE_SPEC); + private static final String DEF2 = "Defendant 2"; private final DateOfBirthValidator dateOfBirthValidator; private final UnavailableDateValidator unavailableDateValidator; @@ -160,6 +166,7 @@ public class RespondToClaimSpecCallbackHandler extends CallbackHandler private final CourtLocationUtils courtLocationUtils; private final CaseFlagsInitialiser caseFlagsInitialiser; private final AssignCategoryId assignCategoryId; + private final DeadlineExtensionCalculatorService deadlineCalculatorService; @Override public List handledEvents() { @@ -177,7 +184,7 @@ protected Map callbacks() { .put(callbackKey(MID, "upload"), this::emptyCallbackResponse) .put(callbackKey(MID, "statement-of-truth"), this::resetStatementOfTruth) .put(callbackKey(MID, "validate-payment-date"), this::validateRespondentPaymentDate) - .put(callbackKey(MID, "specCorrespondenceAddress"), this::validateCorrespondenceApplicantAddress) + .put(callbackKey(MID, "specCorrespondenceAddress"), this::validateCorrespondenceAddress) .put(callbackKey(MID, "determineLoggedInSolicitor"), this::determineLoggedInSolicitor) .put(callbackKey(MID, "track"), this::handleDefendAllClaim) .put(callbackKey(MID, "specHandleResponseType"), this::handleRespondentResponseTypeForSpec) @@ -1053,12 +1060,26 @@ private AllocatedTrack getAllocatedTrack(CaseData caseData) { ); } - private CallbackResponse validateCorrespondenceApplicantAddress(CallbackParams callbackParams) { - if (SpecJourneyConstantLRSpec.DEFENDANT_RESPONSE_SPEC.equals(callbackParams.getRequest().getEventId())) { - return validateCorrespondenceApplicantAddress(callbackParams, postcodeValidator); + private CallbackResponse validateCorrespondenceAddress(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + if (caseData.getIsRespondent1() == YES + && caseData.getRespondentSolicitor1ServiceAddressRequired() == NO) { + List errors = postcodeValidator.validate( + caseData.getRespondentSolicitor1ServiceAddress().getPostCode()); + + return AboutToStartOrSubmitCallbackResponse.builder() + .errors(errors) + .build(); + } else if (caseData.getIsRespondent2() == YES + && caseData.getRespondentSolicitor2ServiceAddressRequired() == NO) { + List errors = postcodeValidator.validate( + caseData.getRespondentSolicitor2ServiceAddress().getPostCode()); + + return AboutToStartOrSubmitCallbackResponse.builder() + .errors(errors) + .build(); } - return AboutToStartOrSubmitCallbackResponse.builder() - .build(); + return AboutToStartOrSubmitCallbackResponse.builder().build(); } private CallbackResponse determineLoggedInSolicitor(CallbackParams callbackParams) { @@ -1111,13 +1132,17 @@ private CallbackResponse populateRespondent1Copy(CallbackParams callbackParams) .respondent1Copy(caseData.getRespondent1()) .respondent1ClaimResponseTestForSpec(caseData.getRespondent1ClaimResponseTypeForSpec()) .respondent2ClaimResponseTestForSpec(caseData.getRespondent2ClaimResponseTypeForSpec()) + .respondentSolicitor1ServiceAddress(Address.builder().build()) + .respondentSolicitor2ServiceAddress(Address.builder().build()) + .respondentSolicitor1ServiceAddressRequired(null) + .respondentSolicitor2ServiceAddressRequired(null) .showConditionFlags(initialShowTags); - updatedCaseData.respondent1DetailsForClaimDetailsTab(caseData.getRespondent1()); + updatedCaseData.respondent1DetailsForClaimDetailsTab(caseData.getRespondent1().toBuilder().flags(null).build()); ofNullable(caseData.getRespondent2()) .ifPresent(r2 -> updatedCaseData.respondent2Copy(r2) - .respondent2DetailsForClaimDetailsTab(r2) + .respondent2DetailsForClaimDetailsTab(r2.toBuilder().flags(null).build()) ); DynamicList courtLocationList = courtLocationUtils.getLocationsFromList(fetchLocationData(callbackParams)); @@ -1258,9 +1283,9 @@ private CallbackResponse validateUnavailableDates(CallbackParams callbackParams) } private CallbackResponse validateDateOfBirth(CallbackParams callbackParams) { - Party respondent = callbackParams.getCaseData().getRespondent1(); - if (respondent == null && callbackParams.getCaseData().getRespondent2() != null) { - respondent = callbackParams.getCaseData().getRespondent2(); + Party respondent = callbackParams.getCaseData().getRespondent1Copy(); + if (respondent == null && callbackParams.getCaseData().getRespondent2Copy() != null) { + respondent = callbackParams.getCaseData().getRespondent2Copy(); } List errors = dateOfBirthValidator.validate(respondent); @@ -1338,12 +1363,18 @@ private CallbackResponse setApplicantResponseDeadline(CallbackParams callbackPar AllocatedTrack allocatedTrack = caseData.getAllocatedTrack(); Party updatedRespondent1; - if (NO.equals(caseData.getSpecAoSApplicantCorrespondenceAddressRequired())) { + if (NO.equals(caseData.getTempCorrespondenceAddress1Required())) { updatedRespondent1 = caseData.getRespondent1().toBuilder() - .primaryAddress(caseData.getSpecAoSApplicantCorrespondenceAddressdetails()).build(); + .primaryAddress(caseData.getTempCorrespondenceAddress1()).build(); } else { updatedRespondent1 = caseData.getRespondent1().toBuilder() - .primaryAddress(caseData.getRespondent1Copy().getPrimaryAddress()).build(); + .primaryAddress(caseData.getRespondent1Copy().getPrimaryAddress()) + .build(); + } + + if (caseData.getRespondent1Copy() != null) { + updatedRespondent1 = + updatedRespondent1.toBuilder().flags(caseData.getRespondent1Copy().getFlags()).build(); } CaseData.CaseDataBuilder updatedData = caseData.toBuilder() @@ -1364,15 +1395,18 @@ private CallbackResponse setApplicantResponseDeadline(CallbackParams callbackPar && ofNullable(caseData.getRespondent2Copy()).isPresent()) { var updatedRespondent2 = caseData.getRespondent2().toBuilder() .primaryAddress(caseData.getRespondent2Copy().getPrimaryAddress()) + .flags(caseData.getRespondent2Copy().getFlags()) .build(); updatedData.respondent2(updatedRespondent2).respondent2Copy(null); - updatedData.respondent2DetailsForClaimDetailsTab(updatedRespondent2); + updatedData.respondent2DetailsForClaimDetailsTab(updatedRespondent2.toBuilder().flags(null).build()); } if (caseData.getDefenceAdmitPartPaymentTimeRouteRequired() != null && caseData.getDefenceAdmitPartPaymentTimeRouteRequired() == IMMEDIATELY && ifResponseTypeIsPartOrFullAdmission(caseData)) { - LocalDate whenBePaid = deadlinesCalculator.calculateWhenToBePaid(responseDate); + LocalDate whenBePaid = deadlineCalculatorService.calculateExtendedDeadline( + LocalDate.now(), + RespondentResponsePartAdmissionPaymentTimeLRspec.DAYS_TO_PAY_IMMEDIATELY); updatedData.respondToClaimAdmitPartLRspec(RespondToClaimAdmitPartLRspec.builder() .whenWillThisAmountBePaid(whenBePaid).build()); } @@ -1408,17 +1442,7 @@ && ifResponseTypeIsPartOrFullAdmission(caseData)) { .businessProcess(BusinessProcess.ready(DEFENDANT_RESPONSE_SPEC)); if (caseData.getRespondent2() != null && caseData.getRespondent2Copy() != null) { - Party updatedRespondent2; - - if (NO.equals(caseData.getSpecAoSRespondent2HomeAddressRequired())) { - updatedRespondent2 = caseData.getRespondent2().toBuilder() - .primaryAddress(caseData.getSpecAoSRespondent2HomeAddressDetails()).build(); - } else { - updatedRespondent2 = caseData.getRespondent2().toBuilder() - .primaryAddress(caseData.getRespondent2Copy().getPrimaryAddress()).build(); - } - - updatedData.respondent2(updatedRespondent2).respondent2Copy(null); + Party updatedRespondent2 = applyRespondent2Address(caseData, updatedData); updatedData.respondent2DetailsForClaimDetailsTab(updatedRespondent2); } @@ -1476,12 +1500,14 @@ && ifResponseTypeIsPartOrFullAdmission(caseData)) { .build()); } - UnavailabilityDatesUtils.rollUpUnavailabilityDatesForRespondent(updatedData, - toggleService.isUpdateContactDetailsEnabled()); + UnavailabilityDatesUtils.rollUpUnavailabilityDatesForRespondent( + updatedData, + toggleService.isUpdateContactDetailsEnabled() + ); - updatedData.respondent1DetailsForClaimDetailsTab(updatedData.build().getRespondent1()); + updatedData.respondent1DetailsForClaimDetailsTab(updatedData.build().getRespondent1().toBuilder().flags(null).build()); if (ofNullable(caseData.getRespondent2()).isPresent()) { - updatedData.respondent2DetailsForClaimDetailsTab(updatedData.build().getRespondent2()); + updatedData.respondent2DetailsForClaimDetailsTab(updatedData.build().getRespondent2().toBuilder().flags(null).build()); } if (toggleService.isUpdateContactDetailsEnabled()) { @@ -1489,6 +1515,10 @@ && ifResponseTypeIsPartOrFullAdmission(caseData)) { addEventAndDateAddedToRespondentWitnesses(updatedData); } + if (toggleService.isHmcEnabled()) { + populateDQPartyIds(updatedData); + } + caseFlagsInitialiser.initialiseCaseFlags(DEFENDANT_RESPONSE_SPEC, updatedData); if (toggleService.isCaseFileViewEnabled()) { @@ -1507,7 +1537,6 @@ && ifResponseTypeIsPartOrFullAdmission(caseData)) { if (toggleService.isHmcEnabled()) { populateWithPartyIds(updatedData); - } updateCorrespondenceAddress(callbackParams, updatedData, caseData); @@ -1546,6 +1575,21 @@ && isAwaitingAnotherDefendantResponse(caseData)) { .build(); } + private static Party applyRespondent2Address(CaseData caseData, CaseData.CaseDataBuilder updatedData) { + Party updatedRespondent2; + + if (NO.equals(caseData.getTempCorrespondenceAddress2Required())) { + updatedRespondent2 = caseData.getRespondent2().toBuilder() + .primaryAddress(caseData.getTempCorrespondenceAddress2()).build(); + } else { + updatedRespondent2 = caseData.getRespondent2().toBuilder() + .primaryAddress(caseData.getRespondent2Copy().getPrimaryAddress()).build(); + } + + updatedData.respondent2(updatedRespondent2).respondent2Copy(null); + return updatedRespondent2; + } + private boolean ifResponseTypeIsPartOrFullAdmission(CaseData caseData) { return (RespondentResponseTypeSpec.PART_ADMISSION.equals(caseData.getRespondent1ClaimResponseTypeForSpec()) || RespondentResponseTypeSpec.PART_ADMISSION.equals( @@ -1560,19 +1604,19 @@ private void updateCorrespondenceAddress(CallbackParams callbackParams, CaseData.CaseDataBuilder updatedCaseData, CaseData caseData) { if (solicitorHasCaseRole(callbackParams, RESPONDENTSOLICITORONE) - && caseData.getSpecAoSRespondentCorrespondenceAddressRequired() == YesOrNo.NO) { - Address newAddress = caseData.getSpecAoSRespondentCorrespondenceAddressdetails(); + && caseData.getRespondentSolicitor1ServiceAddressRequired() == YesOrNo.NO) { + Address newAddress = caseData.getRespondentSolicitor1ServiceAddress(); updatedCaseData.specRespondentCorrespondenceAddressdetails(newAddress) - .specAoSRespondentCorrespondenceAddressdetails(Address.builder().build()); + .respondentSolicitor1ServiceAddress(Address.builder().build()); if (getMultiPartyScenario(caseData) == ONE_V_TWO_ONE_LEGAL_REP) { // to keep with heading tab updatedCaseData.specRespondent2CorrespondenceAddressdetails(newAddress); } } else if (solicitorHasCaseRole(callbackParams, RESPONDENTSOLICITORTWO) - && caseData.getSpecAoSRespondent2CorrespondenceAddressRequired() == YesOrNo.NO) { + && caseData.getRespondentSolicitor2ServiceAddressRequired() == YesOrNo.NO) { updatedCaseData.specRespondent2CorrespondenceAddressdetails( - caseData.getSpecAoSRespondent2CorrespondenceAddressdetails()) - .specAoSRespondent2CorrespondenceAddressdetails(Address.builder().build()); + caseData.getRespondentSolicitor2ServiceAddress()) + .respondentSolicitor2ServiceAddress(Address.builder().build()); } } @@ -1582,46 +1626,63 @@ private void assembleResponseDocumentsSpec(CaseData caseData, CaseData.CaseDataB if (respondent1SpecDefenceResponseDocument != null) { uk.gov.hmcts.reform.civil.documentmanagement.model.Document respondent1ClaimDocument = respondent1SpecDefenceResponseDocument.getFile(); if (respondent1ClaimDocument != null) { - defendantUploads.add( - buildElemCaseDocument(respondent1ClaimDocument, "Defendant", - updatedCaseData.build().getRespondent1ResponseDate(), - DocumentType.DEFENDANT_DEFENCE - )); + Element documentElement = buildElemCaseDocument( + respondent1ClaimDocument, "Defendant", + updatedCaseData.build().getRespondent1ResponseDate(), + DocumentType.DEFENDANT_DEFENCE + ); + CaseDocument copy = assignCategoryId + .copyCaseDocumentWithCategoryId(documentElement.getValue(), DocCategory.DQ_DEF1.getValue()); assignCategoryId.assignCategoryIdToDocument( respondent1ClaimDocument, - "defendant1DefenseDirectionsQuestionnaire" + DocCategory.DEF1_DEFENSE_DQ.getValue() ); + defendantUploads.add(documentElement); + if (Objects.nonNull(copy)) { + defendantUploads.add(ElementUtils.element(copy)); + } } } Respondent1DQ respondent1DQ = caseData.getRespondent1DQ(); if (respondent1DQ != null) { uk.gov.hmcts.reform.civil.documentmanagement.model.Document respondent1DQDraftDirections = respondent1DQ.getRespondent1DQDraftDirections(); if (respondent1DQDraftDirections != null) { - defendantUploads.add( - buildElemCaseDocument( + Element documentElement = buildElemCaseDocument( respondent1DQDraftDirections, "Defendant", updatedCaseData.build().getRespondent1ResponseDate(), DocumentType.DEFENDANT_DRAFT_DIRECTIONS - )); + ); assignCategoryId.assignCategoryIdToDocument( respondent1DQDraftDirections, - "defendant1DefenseDirectionsQuestionnaire" + DocCategory.DEF1_DEFENSE_DQ.getValue() ); + CaseDocument copy = assignCategoryId + .copyCaseDocumentWithCategoryId(documentElement.getValue(), DocCategory.DQ_DEF1.getValue()); + defendantUploads.add(documentElement); + if (Objects.nonNull(copy)) { + defendantUploads.add(ElementUtils.element(copy)); + } } ResponseDocument respondent2SpecDefenceResponseDocument = caseData.getRespondent2SpecDefenceResponseDocument(); if (respondent2SpecDefenceResponseDocument != null) { uk.gov.hmcts.reform.civil.documentmanagement.model.Document respondent2ClaimDocument = respondent2SpecDefenceResponseDocument.getFile(); if (respondent2ClaimDocument != null) { - defendantUploads.add( - buildElemCaseDocument(respondent2ClaimDocument, "Defendant 2", - updatedCaseData.build().getRespondent2ResponseDate(), - DocumentType.DEFENDANT_DEFENCE - )); + Element documentElement = buildElemCaseDocument( + respondent2ClaimDocument, DEF2, + updatedCaseData.build().getRespondent2ResponseDate(), + DocumentType.DEFENDANT_DEFENCE + ); + CaseDocument copy = assignCategoryId + .copyCaseDocumentWithCategoryId(documentElement.getValue(), DocCategory.DQ_DEF2.getValue()); assignCategoryId.assignCategoryIdToDocument( respondent2ClaimDocument, - "defendant2DefenseDirectionsQuestionnaire" + DocCategory.DEF2_DEFENSE_DQ.getValue() ); + defendantUploads.add(documentElement); + if (Objects.nonNull(copy)) { + defendantUploads.add(ElementUtils.element(copy)); + } } } } else { @@ -1629,15 +1690,21 @@ private void assembleResponseDocumentsSpec(CaseData caseData, CaseData.CaseDataB if (respondent2SpecDefenceResponseDocument != null) { uk.gov.hmcts.reform.civil.documentmanagement.model.Document respondent2ClaimDocument = respondent2SpecDefenceResponseDocument.getFile(); if (respondent2ClaimDocument != null) { - defendantUploads.add( - buildElemCaseDocument(respondent2ClaimDocument, "Defendant 2", - updatedCaseData.build().getRespondent2ResponseDate(), - DocumentType.DEFENDANT_DEFENCE - )); + Element documentElement = buildElemCaseDocument( + respondent2ClaimDocument, DEF2, + updatedCaseData.build().getRespondent2ResponseDate(), + DocumentType.DEFENDANT_DEFENCE + ); assignCategoryId.assignCategoryIdToDocument( respondent2ClaimDocument, - "defendant2DefenseDirectionsQuestionnaire" + DocCategory.DEF2_DEFENSE_DQ.getValue() ); + CaseDocument copy = assignCategoryId + .copyCaseDocumentWithCategoryId(documentElement.getValue(), DocCategory.DQ_DEF2.getValue()); + defendantUploads.add(documentElement); + if (Objects.nonNull(copy)) { + defendantUploads.add(ElementUtils.element(copy)); + } } } } @@ -1645,17 +1712,22 @@ private void assembleResponseDocumentsSpec(CaseData caseData, CaseData.CaseDataB if (respondent2DQ != null) { uk.gov.hmcts.reform.civil.documentmanagement.model.Document respondent2DQDraftDirections = respondent2DQ.getRespondent2DQDraftDirections(); if (respondent2DQDraftDirections != null) { - defendantUploads.add( - buildElemCaseDocument( + Element documentElement = buildElemCaseDocument( respondent2DQDraftDirections, - "Defendant 2", + DEF2, updatedCaseData.build().getRespondent2ResponseDate(), DocumentType.DEFENDANT_DRAFT_DIRECTIONS - )); + ); assignCategoryId.assignCategoryIdToDocument( respondent2DQDraftDirections, - "defendant2DefenseDirectionsQuestionnaire" + DocCategory.DEF2_DEFENSE_DQ.getValue() ); + CaseDocument copy = assignCategoryId + .copyCaseDocumentWithCategoryId(documentElement.getValue(), DocCategory.DQ_DEF2.getValue()); + defendantUploads.add(documentElement); + if (Objects.nonNull(copy)) { + defendantUploads.add(ElementUtils.element(copy)); + } } } if (!defendantUploads.isEmpty()) { diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceCallbackHandler.java index e7a2a03ffb7..7b1599b7eb8 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceCallbackHandler.java @@ -11,13 +11,13 @@ import uk.gov.hmcts.reform.civil.callback.CallbackHandler; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.config.ToggleConfiguration; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType; -import uk.gov.hmcts.reform.civil.enums.AllocatedTrack; import uk.gov.hmcts.reform.civil.enums.CaseCategory; import uk.gov.hmcts.reform.civil.enums.CaseState; +import uk.gov.hmcts.reform.civil.enums.DocCategory; import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; -import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.helpers.LocationHelper; import uk.gov.hmcts.reform.civil.model.BusinessProcess; import uk.gov.hmcts.reform.civil.model.CaseData; @@ -34,6 +34,7 @@ import uk.gov.hmcts.reform.civil.service.Time; import uk.gov.hmcts.reform.civil.utils.AssignCategoryId; import uk.gov.hmcts.reform.civil.utils.CaseFlagsInitialiser; +import uk.gov.hmcts.reform.civil.utils.JudicialReferralUtils; import uk.gov.hmcts.reform.civil.utils.LocationRefDataUtil; import uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils; import uk.gov.hmcts.reform.civil.validation.UnavailableDateValidator; @@ -45,6 +46,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import static java.lang.String.format; @@ -53,7 +55,6 @@ import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CLAIMANT_RESPONSE; -import static uk.gov.hmcts.reform.civil.enums.AllocatedTrack.getAllocatedTrack; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.ONE_V_TWO_ONE_LEGAL_REP; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.ONE_V_TWO_TWO_LEGAL_REP; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.TWO_V_ONE; @@ -62,7 +63,7 @@ import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.buildElemCaseDocument; import static uk.gov.hmcts.reform.civil.utils.ExpertUtils.addEventAndDateAddedToApplicantExperts; -import static uk.gov.hmcts.reform.civil.utils.PartyUtils.populateWithPartyIds; +import static uk.gov.hmcts.reform.civil.utils.PartyUtils.populateDQPartyIds; import static uk.gov.hmcts.reform.civil.utils.WitnessUtils.addEventAndDateAddedToApplicantWitnesses; @Service @@ -81,6 +82,7 @@ public class RespondToDefenceCallbackHandler extends CallbackHandler implements private final LocationRefDataUtil locationRefDataUtil; private final LocationHelper locationHelper; private final CaseFlagsInitialiser caseFlagsInitialiser; + private final ToggleConfiguration toggleConfiguration; private final AssignCategoryId assignCategoryId; @Override @@ -108,10 +110,21 @@ private CallbackResponse populateClaimantResponseScenarioFlag(CallbackParams cal updatedData.claimantResponseScenarioFlag(getMultiPartyScenario(caseData)) .caseAccessCategory(CaseCategory.UNSPEC_CLAIM); - - if ((getMultiPartyScenario(caseData) == ONE_V_TWO_ONE_LEGAL_REP)) { - updatedData.respondentSharedClaimResponseDocument(caseData.getRespondent1ClaimResponseDocument()); - } + updatedData.featureToggleWA(toggleConfiguration.getFeatureToggle()); + + // add document from defendant response documents, to placeholder field for preview during event. + caseData.getDefendantResponseDocuments().forEach(document -> { + if (document.getValue().getDocumentType().equals(DocumentType.DEFENDANT_DEFENCE)) { + updatedData.respondent1ClaimResponseDocument(ResponseDocument.builder() + .file(document.getValue().getDocumentLink()) + .build()); + if ((getMultiPartyScenario(caseData) == ONE_V_TWO_ONE_LEGAL_REP)) { + updatedData.respondentSharedClaimResponseDocument(ResponseDocument.builder() + .file(document.getValue().getDocumentLink()) + .build()); + } + } + }); return AboutToStartOrSubmitCallbackResponse.builder() .data(updatedData.build().toMap(objectMapper)) @@ -246,12 +259,12 @@ private CallbackResponse aboutToSubmit(CallbackParams callbackParams) { addEventAndDateAddedToApplicantWitnesses(builder); } - caseFlagsInitialiser.initialiseCaseFlags(CLAIMANT_RESPONSE, builder); - if (featureToggleService.isHmcEnabled()) { - populateWithPartyIds(builder); + populateDQPartyIds(builder); } + caseFlagsInitialiser.initialiseCaseFlags(CLAIMANT_RESPONSE, builder); + if (multiPartyScenario == ONE_V_TWO_ONE_LEGAL_REP) { builder.respondentSharedClaimResponseDocument(null); } @@ -259,59 +272,26 @@ private CallbackResponse aboutToSubmit(CallbackParams callbackParams) { //Set to null because there are no more deadlines builder.nextDeadline(null); + // null/delete the document used for preview, otherwise it will show as duplicate within case file view + // and documents are added to claimantUploads, if we do not remove/null the original, + if (featureToggleService.isCaseFileViewEnabled()) { + builder.applicant1DefenceResponseDocument(null); + builder.respondent1ClaimResponseDocument(null); + builder.respondentSharedClaimResponseDocument(null); + builder.applicant1DQ(builder.build().getApplicant1DQ().toBuilder().applicant1DQDraftDirections(null).build()); + if (caseData.getApplicant2DQ() != null) { + builder.applicant2DQ(builder.build().getApplicant2DQ().toBuilder().applicant2DQDraftDirections(null).build()); + } + } + return AboutToStartOrSubmitCallbackResponse.builder() .data(builder.build().toMap(objectMapper)) - .state((shouldMoveToJudicialReferral(caseData) + .state((JudicialReferralUtils.shouldMoveToJudicialReferral(caseData) ? CaseState.JUDICIAL_REFERRAL : CaseState.PROCEEDS_IN_HERITAGE_SYSTEM).name()) .build(); } - /** - * Computes whether the case data should move to judicial referral or not. - * - * @param caseData a case data such that defendants rejected the claim, and claimant(s) wants to proceed - * vs all the defendants - * @return true if and only if the case should move to judicial referral - */ - public static boolean shouldMoveToJudicialReferral(CaseData caseData) { - CaseCategory caseCategory = caseData.getCaseAccessCategory(); - - if (CaseCategory.SPEC_CLAIM.equals(caseCategory)) { - MultiPartyScenario multiPartyScenario = getMultiPartyScenario(caseData); - boolean addRespondent2 = YES.equals(caseData.getAddRespondent2()); - - return switch (multiPartyScenario) { - case ONE_V_ONE -> caseData.getApplicant1ProceedWithClaim() == YesOrNo.YES; - case TWO_V_ONE -> caseData.getApplicant1ProceedWithClaimSpec2v1() == YesOrNo.YES; - case ONE_V_TWO_ONE_LEGAL_REP -> addRespondent2 - && YES.equals(caseData.getRespondentResponseIsSame()); - case ONE_V_TWO_TWO_LEGAL_REP -> addRespondent2 - && caseData.getRespondentResponseIsSame() == null; - }; - } else { - AllocatedTrack allocatedTrack = - getAllocatedTrack( - CaseCategory.UNSPEC_CLAIM.equals(caseCategory) - ? caseData.getClaimValue().toPounds() - : caseData.getTotalClaimAmount(), - caseData.getClaimType() - ); - if (AllocatedTrack.MULTI_CLAIM.equals(allocatedTrack)) { - return false; - } - MultiPartyScenario multiPartyScenario = getMultiPartyScenario(caseData); - return switch (multiPartyScenario) { - case ONE_V_ONE -> caseData.getApplicant1ProceedWithClaim() == YesOrNo.YES; - case TWO_V_ONE -> caseData.getApplicant1ProceedWithClaimMultiParty2v1() == YES - && caseData.getApplicant2ProceedWithClaimMultiParty2v1() == YES; - case ONE_V_TWO_ONE_LEGAL_REP, ONE_V_TWO_TWO_LEGAL_REP -> - caseData.getApplicant1ProceedWithClaimAgainstRespondent1MultiParty1v2() == YES - && caseData.getApplicant1ProceedWithClaimAgainstRespondent2MultiParty1v2() == YES; - }; - } - } - private void updateApplicants(CaseData caseData, CaseData.CaseDataBuilder builder, StatementOfTruth statementOfTruth) { if (caseData.getApplicant1DQ() != null && caseData.getApplicant1DQ().getApplicant1DQFileDirectionsQuestionnaire() != null) { @@ -388,12 +368,17 @@ private void assembleResponseDocuments(CaseData caseData, CaseData.CaseDataBuild DocumentType.CLAIMANT_DRAFT_DIRECTIONS ))); if (!claimantUploads.isEmpty()) { - updatedCaseData.claimantResponseDocuments(claimantUploads); assignCategoryId.assignCategoryIdToCollection( claimantUploads, document -> document.getValue().getDocumentLink(), - "directionsQuestionnaire" + DocCategory.APP1_DQ.getValue() ); + List> copy = assignCategoryId.copyCaseDocumentListWithCategoryId( + claimantUploads, "DQApplicant"); + if (Objects.nonNull(copy)) { + claimantUploads.addAll(copy); + } + updatedCaseData.claimantResponseDocuments(claimantUploads); } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceSpecCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceSpecCallbackHandler.java index be9d7605831..ecbac578256 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceSpecCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceSpecCallbackHandler.java @@ -16,13 +16,13 @@ import uk.gov.hmcts.reform.civil.enums.AllocatedTrack; import uk.gov.hmcts.reform.civil.enums.CaseCategory; import uk.gov.hmcts.reform.civil.enums.CaseState; +import uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec; import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec; import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.handler.callback.user.spec.CaseDataToTextGenerator; import uk.gov.hmcts.reform.civil.handler.callback.user.spec.RespondToResponseConfirmationHeaderGenerator; import uk.gov.hmcts.reform.civil.handler.callback.user.spec.RespondToResponseConfirmationTextGenerator; import uk.gov.hmcts.reform.civil.handler.callback.user.spec.show.DefendantResponseShowTag; -import uk.gov.hmcts.reform.civil.handler.callback.user.spec.show.ResponseOneVOneShowTag; import uk.gov.hmcts.reform.civil.helpers.LocationHelper; import uk.gov.hmcts.reform.civil.model.BusinessProcess; import uk.gov.hmcts.reform.civil.model.CaseData; @@ -41,8 +41,11 @@ import uk.gov.hmcts.reform.civil.service.PaymentDateService; import uk.gov.hmcts.reform.civil.service.Time; import uk.gov.hmcts.reform.civil.service.citizenui.RespondentMediationService; +import uk.gov.hmcts.reform.civil.service.citizenui.ResponseOneVOneShowTagService; +import uk.gov.hmcts.reform.civil.service.citizenui.responsedeadline.DeadlineExtensionCalculatorService; import uk.gov.hmcts.reform.civil.utils.CaseFlagsInitialiser; import uk.gov.hmcts.reform.civil.utils.CourtLocationUtils; +import uk.gov.hmcts.reform.civil.utils.JudicialReferralUtils; import uk.gov.hmcts.reform.civil.utils.MonetaryConversions; import uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils; import uk.gov.hmcts.reform.civil.validation.UnavailableDateValidator; @@ -71,7 +74,6 @@ import static uk.gov.hmcts.reform.civil.callback.CallbackVersion.V_1; import static uk.gov.hmcts.reform.civil.callback.CallbackVersion.V_2; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CLAIMANT_RESPONSE_SPEC; -import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.ONE_V_ONE; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.TWO_V_ONE; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.getMultiPartyScenario; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.isOneVOne; @@ -85,7 +87,7 @@ import static uk.gov.hmcts.reform.civil.model.dq.Expert.fromSmallClaimExpertDetails; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; import static uk.gov.hmcts.reform.civil.utils.ExpertUtils.addEventAndDateAddedToApplicantExperts; -import static uk.gov.hmcts.reform.civil.utils.PartyUtils.populateWithPartyIds; +import static uk.gov.hmcts.reform.civil.utils.PartyUtils.populateDQPartyIds; import static uk.gov.hmcts.reform.civil.utils.WitnessUtils.addEventAndDateAddedToApplicantWitnesses; @Service @@ -109,6 +111,8 @@ public class RespondToDefenceSpecCallbackHandler extends CallbackHandler private static final String datePattern = "dd MMMM yyyy"; private final RespondentMediationService respondentMediationService; private final PaymentDateService paymentDateService; + private final ResponseOneVOneShowTagService responseOneVOneShowTagService; + private final DeadlineExtensionCalculatorService deadlineCalculatorService; @Override public List handledEvents() { @@ -267,6 +271,7 @@ private CallbackResponse aboutToSubmit(CallbackParams callbackParams) { if (featureToggleService.isCaseFileViewEnabled()) { builder.respondent1GeneratedResponseDocument(null); builder.respondent2GeneratedResponseDocument(null); + builder.respondent1ClaimResponseDocumentSpec(null); } locationHelper.getCaseManagementLocation(caseData) @@ -334,12 +339,12 @@ private CallbackResponse aboutToSubmit(CallbackParams callbackParams) { addEventAndDateAddedToApplicantWitnesses(builder); } - caseFlagsInitialiser.initialiseCaseFlags(CLAIMANT_RESPONSE_SPEC, builder); - if (featureToggleService.isHmcEnabled()) { - populateWithPartyIds(builder); + populateDQPartyIds(builder); } + caseFlagsInitialiser.initialiseCaseFlags(CLAIMANT_RESPONSE_SPEC, builder); + AboutToStartOrSubmitCallbackResponse.AboutToStartOrSubmitCallbackResponseBuilder response = AboutToStartOrSubmitCallbackResponse.builder() .data(builder.build().toMap(objectMapper)); @@ -383,7 +388,7 @@ private void updateDQCourtLocations(CallbackParams callbackParams, CaseData case private void putCaseStateInJudicialReferral(CaseData caseData, AboutToStartOrSubmitCallbackResponse.AboutToStartOrSubmitCallbackResponseBuilder response) { if (caseData.isRespondentResponseFullDefence() - && RespondToDefenceCallbackHandler.shouldMoveToJudicialReferral(caseData)) { + && JudicialReferralUtils.shouldMoveToJudicialReferral(caseData)) { response.state(CaseState.JUDICIAL_REFERRAL.name()); } } @@ -414,7 +419,7 @@ private CallbackResponse populateCaseData(CallbackParams callbackParams) { if (isDefendantFullAdmitPayImmediately(caseData)) { LocalDate whenBePaid = paymentDateService.getPaymentDateAdmittedClaim(caseData); - updatedCaseData.showResponseOneVOneFlag(setUpOneVOneFlow(caseData)); + updatedCaseData.showResponseOneVOneFlag(responseOneVOneShowTagService.setUpOneVOneFlow(caseData)); updatedCaseData.whenToBePaidText(formatLocalDate(whenBePaid, DATE)); } @@ -430,7 +435,7 @@ private CallbackResponse populateCaseData(CallbackParams callbackParams) { ).build()); if (V_2.equals(callbackParams.getVersion()) && featureToggleService.isPinInPostEnabled()) { - updatedCaseData.showResponseOneVOneFlag(setUpOneVOneFlow(caseData)); + updatedCaseData.showResponseOneVOneFlag(responseOneVOneShowTagService.setUpOneVOneFlow(caseData)); updatedCaseData.respondent1PaymentDateToStringSpec(setUpPayDateToString(caseData)); Optional howMuchWasPaid = Optional.ofNullable(caseData.getRespondToAdmittedClaim()) @@ -444,8 +449,17 @@ private CallbackResponse populateCaseData(CallbackParams callbackParams) { null ).name()); } + // add direction questionaire document from system generated documents, to placeholder field for preview during event. + // Or add sealed response form from system generated documents, to placeholder field for preview during event. + populatePreviewDocuments(caseData, updatedCaseData); + + return AboutToStartOrSubmitCallbackResponse.builder() + .data(updatedCaseData.build().toMap(objectMapper)) + .build(); + } - // add document from system generated documents, to placeholder field for preview during event. + private void populatePreviewDocuments(CaseData caseData, CaseData.CaseDataBuilder updatedCaseData) { + // add direction questionaire document from system generated documents, to placeholder field for preview during event. if (caseData.getRespondent2DocumentURL() == null) { caseData.getSystemGeneratedCaseDocuments().forEach(document -> { if (document.getValue().getDocumentName().contains("defendant_directions_questionnaire_form")) { @@ -462,10 +476,14 @@ private CallbackResponse populateCaseData(CallbackParams callbackParams) { } }); } - - return AboutToStartOrSubmitCallbackResponse.builder() - .data(updatedCaseData.build().toMap(objectMapper)) - .build(); + // add sealed response form from system generated documents, to placeholder field for preview during event. + if (featureToggleService.isPinInPostEnabled()) { + caseData.getSystemGeneratedCaseDocuments().forEach(document -> { + if (document.getValue().getDocumentName().contains("response_sealed_form.pdf")) { + updatedCaseData.respondent1ClaimResponseDocumentSpec(document.getValue()); + } + }); + } } private List fetchLocationData(CallbackParams callbackParams) { @@ -539,27 +557,6 @@ private String getDefaultConfirmationHeader(CaseData caseData) { } } - private ResponseOneVOneShowTag setUpOneVOneFlow(CaseData caseData) { - if (ONE_V_ONE.equals(getMultiPartyScenario(caseData))) { - if (caseData.getRespondent1ClaimResponseTypeForSpec() == null) { - return null; - } - switch (caseData.getRespondent1ClaimResponseTypeForSpec()) { - case FULL_DEFENCE: - return ResponseOneVOneShowTag.ONE_V_ONE_FULL_DEFENCE; - case FULL_ADMISSION: - return setUpOneVOneFlowForFullAdmit(caseData); - case PART_ADMISSION: - return setUpOneVOneFlowForPartAdmit(caseData); - case COUNTER_CLAIM: - return ResponseOneVOneShowTag.ONE_V_ONE_COUNTER_CLAIM; - default: - return null; - } - } - return null; - } - private String setUpPayDateToString(CaseData caseData) { if (caseData.getRespondToClaimAdmitPartLRspec() != null && caseData.getRespondToClaimAdmitPartLRspec().getWhenWillThisAmountBePaid() != null) { @@ -572,44 +569,14 @@ private String setUpPayDateToString(CaseData caseData) { .format(DateTimeFormatter.ofPattern(datePattern, Locale.ENGLISH)); } if (caseData.getRespondent1ResponseDate() != null) { - return caseData.getRespondent1ResponseDate().plusDays(5) + return deadlineCalculatorService.calculateExtendedDeadline( + caseData.getRespondent1ResponseDate().toLocalDate(), + RespondentResponsePartAdmissionPaymentTimeLRspec.DAYS_TO_PAY_IMMEDIATELY) .format(DateTimeFormatter.ofPattern(datePattern, Locale.ENGLISH)); } return null; } - private ResponseOneVOneShowTag setUpOneVOneFlowForPartAdmit(CaseData caseData) { - if (YES.equals(caseData.getSpecDefenceAdmittedRequired())) { - return ResponseOneVOneShowTag.ONE_V_ONE_PART_ADMIT_HAS_PAID; - } - switch (caseData.getDefenceAdmitPartPaymentTimeRouteRequired()) { - case IMMEDIATELY: - return ResponseOneVOneShowTag.ONE_V_ONE_PART_ADMIT_PAY_IMMEDIATELY; - case BY_SET_DATE: - return ResponseOneVOneShowTag.ONE_V_ONE_PART_ADMIT_PAY_BY_SET_DATE; - case SUGGESTION_OF_REPAYMENT_PLAN: - return ResponseOneVOneShowTag.ONE_V_ONE_PART_ADMIT_PAY_INSTALMENT; - default: - return ResponseOneVOneShowTag.ONE_V_ONE_PART_ADMIT; - } - } - - private ResponseOneVOneShowTag setUpOneVOneFlowForFullAdmit(CaseData caseData) { - if (YES.equals(caseData.getSpecDefenceFullAdmittedRequired())) { - return ResponseOneVOneShowTag.ONE_V_ONE_FULL_ADMIT_HAS_PAID; - } - switch (caseData.getDefenceAdmitPartPaymentTimeRouteRequired()) { - case IMMEDIATELY: - return ResponseOneVOneShowTag.ONE_V_ONE_FULL_ADMIT_PAY_IMMEDIATELY; - case BY_SET_DATE: - return ResponseOneVOneShowTag.ONE_V_ONE_FULL_ADMIT_PAY_BY_SET_DATE; - case SUGGESTION_OF_REPAYMENT_PLAN: - return ResponseOneVOneShowTag.ONE_V_ONE_FULL_ADMIT_PAY_INSTALMENT; - default: - return ResponseOneVOneShowTag.ONE_V_ONE_FULL_ADMIT; - } - } - private CallbackResponse validatePaymentDate(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/SetAsideJudgmentCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/SetAsideJudgmentCallbackHandler.java new file mode 100644 index 00000000000..2edc1c734a5 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/SetAsideJudgmentCallbackHandler.java @@ -0,0 +1,92 @@ +package uk.gov.hmcts.reform.civil.handler.callback.user; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.SubmittedCallbackResponse; +import uk.gov.hmcts.reform.civil.callback.Callback; +import uk.gov.hmcts.reform.civil.callback.CallbackHandler; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.enums.CaseState; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.helpers.judgmentsonline.JudgmentsOnlineHelper; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentStatusDetails; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentStatusType; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.SET_ASIDE_JUDGMENT; + +@Service +@RequiredArgsConstructor +public class SetAsideJudgmentCallbackHandler extends CallbackHandler { + + private static final List EVENTS = Collections.singletonList(SET_ASIDE_JUDGMENT); + protected final ObjectMapper objectMapper; + private static final String ERROR_MESSAGE_DATE_ORDER_MUST_BE_IN_PAST = "Date must be in the past"; + + @Override + protected Map callbacks() { + return new ImmutableMap.Builder() + .put(callbackKey(MID, "validate-setAside-date"), this::validateDates) + .put(callbackKey(ABOUT_TO_SUBMIT), this::saveJudgmentDetails) + .put(callbackKey(SUBMITTED), this::buildConfirmation) + .build(); + } + + private CallbackResponse validateDates(CallbackParams callbackParams) { + var caseData = callbackParams.getCaseData(); + List errors = new ArrayList<>(); + boolean isSetAsideFutureDate = + JudgmentsOnlineHelper.validateIfFutureDate(callbackParams.getCaseData().getJoSetAsideDate()); + if (isSetAsideFutureDate) { + errors.add(ERROR_MESSAGE_DATE_ORDER_MUST_BE_IN_PAST); + } + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .errors(errors) + .build(); + } + + private CallbackResponse buildConfirmation(CallbackParams callbackParams) { + return SubmittedCallbackResponse.builder() + .confirmationHeader("# Judgment set aside") + .confirmationBody("The judgment has been set aside") + .build(); + } + + private CallbackResponse saveJudgmentDetails(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + JudgmentStatusDetails judgmentStatusDetails = JudgmentStatusDetails.builder() + .judgmentStatusTypes(JudgmentStatusType.SET_ASIDE) + .lastUpdatedDate(LocalDateTime.now()).build(); + if (caseData.getJoIsRegisteredWithRTL() == YesOrNo.YES) { + judgmentStatusDetails.setJoRtlState(JudgmentsOnlineHelper.getRTLStatusBasedOnJudgementStatus(JudgmentStatusType.SET_ASIDE)); + } + caseData.setJoJudgmentStatusDetails(judgmentStatusDetails); + caseData.setJoIsLiveJudgmentExists(YesOrNo.NO); + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .state(CaseState.AWAITING_RESPONDENT_ACKNOWLEDGEMENT.name()) + .build(); + } + + @Override + public List handledEvents() { + return EVENTS; + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/StandardDirectionOrderDJ.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/StandardDirectionOrderDJ.java index e84e4883b36..70020cfb326 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/StandardDirectionOrderDJ.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/StandardDirectionOrderDJ.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; @@ -14,19 +15,19 @@ import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; import uk.gov.hmcts.reform.civil.crd.model.CategorySearchResult; +import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.enums.CaseCategory; import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.enums.dj.DisposalAndTrialHearingDJToggle; import uk.gov.hmcts.reform.civil.enums.dj.DisposalHearingMethodDJ; -import uk.gov.hmcts.reform.civil.enums.sdo.HearingMethod; import uk.gov.hmcts.reform.civil.enums.sdo.DateToShowToggle; +import uk.gov.hmcts.reform.civil.enums.sdo.HearingMethod; import uk.gov.hmcts.reform.civil.helpers.LocationHelper; -import uk.gov.hmcts.reform.civil.model.common.DynamicListElement; -import uk.gov.hmcts.reform.civil.service.CategoryService; -import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.model.BusinessProcess; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.common.DynamicList; +import uk.gov.hmcts.reform.civil.model.common.DynamicListElement; import uk.gov.hmcts.reform.civil.model.common.Element; import uk.gov.hmcts.reform.civil.model.defaultjudgment.DisposalHearingBundleDJ; import uk.gov.hmcts.reform.civil.model.defaultjudgment.DisposalHearingDisclosureOfDocumentsDJ; @@ -49,15 +50,17 @@ import uk.gov.hmcts.reform.civil.model.defaultjudgment.TrialHousingDisrepair; import uk.gov.hmcts.reform.civil.model.defaultjudgment.TrialPersonalInjury; import uk.gov.hmcts.reform.civil.model.defaultjudgment.TrialRoadTrafficAccident; -import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; +import uk.gov.hmcts.reform.civil.model.dq.RequestedCourt; import uk.gov.hmcts.reform.civil.model.sdo.DisposalHearingFinalDisposalHearingTimeDJ; import uk.gov.hmcts.reform.civil.model.sdo.DisposalHearingOrderMadeWithoutHearingDJ; import uk.gov.hmcts.reform.civil.model.sdo.TrialHearingTimeDJ; import uk.gov.hmcts.reform.civil.model.sdo.TrialOrderMadeWithoutHearingDJ; +import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; +import uk.gov.hmcts.reform.civil.service.CategoryService; import uk.gov.hmcts.reform.civil.service.DeadlinesCalculator; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.docmosis.dj.DefaultJudgmentOrderFormGenerator; -import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; import uk.gov.hmcts.reform.civil.utils.AssignCategoryId; import uk.gov.hmcts.reform.civil.utils.HearingMethodUtils; import uk.gov.hmcts.reform.idam.client.IdamClient; @@ -85,10 +88,10 @@ import static uk.gov.hmcts.reform.civil.callback.CallbackVersion.V_1; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.STANDARD_DIRECTION_ORDER_DJ; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.getMultiPartyScenario; -import static uk.gov.hmcts.reform.civil.model.common.DynamicList.fromList; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.element; import static uk.gov.hmcts.reform.civil.utils.HearingUtils.getHearingNotes; +@Slf4j @Service @RequiredArgsConstructor public class StandardDirectionOrderDJ extends CallbackHandler { @@ -111,6 +114,7 @@ public class StandardDirectionOrderDJ extends CallbackHandler { private final IdamClient idamClient; private final AssignCategoryId assignCategoryId; private final CategoryService categoryService; + private final LocationHelper locationHelper; @Autowired private final DeadlinesCalculator deadlinesCalculator; @@ -166,25 +170,16 @@ private CallbackResponse initiateSDO(CallbackParams callbackParams) { public String caseParticipants(CaseData caseData) { MultiPartyScenario multiPartyScenario = getMultiPartyScenario(caseData); switch (multiPartyScenario) { - - case ONE_V_ONE: + case ONE_V_ONE -> participantString = (caseData.getApplicant1().getPartyName() + " v " + caseData.getRespondent1() .getPartyName()); - break; - case ONE_V_TWO_ONE_LEGAL_REP: + case ONE_V_TWO_ONE_LEGAL_REP, ONE_V_TWO_TWO_LEGAL_REP -> participantString = (caseData.getApplicant1().getPartyName() + " v " + caseData.getRespondent1() .getPartyName() + " and " + caseData.getRespondent2().getPartyName()); - break; - case ONE_V_TWO_TWO_LEGAL_REP: - participantString = (caseData.getApplicant1().getPartyName() + " v " + caseData.getRespondent1() - .getPartyName() + " and " + caseData.getRespondent2().getPartyName()); - break; - case TWO_V_ONE: + case TWO_V_ONE -> participantString = (caseData.getApplicant1().getPartyName() + " and " + caseData.getApplicant2() .getPartyName() + " v " + caseData.getRespondent1().getPartyName()); - break; - default: - throw new CallbackException(String.format("Invalid participants")); + default -> throw new CallbackException("Invalid participants"); } return participantString; @@ -201,9 +196,8 @@ private CallbackResponse populateDisposalTrialScreen(CallbackParams callbackPara } CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); String authToken = callbackParams.getParams().get(BEARER_TOKEN).toString(); - List locations = (locationRefDataService - .getCourtLocationsForDefaultJudgments(authToken)); - DynamicList locationsList = getLocationsFromList(locations); + Optional preferredCourt = locationHelper.getCaseManagementLocation(caseData); + DynamicList locationsList = getLocationList(callbackParams, preferredCourt.orElse(null)); caseDataBuilder.trialHearingMethodInPersonDJ(locationsList); caseDataBuilder.disposalHearingMethodInPersonDJ(locationsList); @@ -632,6 +626,31 @@ private CallbackResponse populateDisposalTrialScreen(CallbackParams callbackPara .build(); } + private DynamicList getLocationList(CallbackParams callbackParams, + RequestedCourt preferredCourt) { + List locations = locationRefDataService.getCourtLocationsForDefaultJudgments( + callbackParams.getParams().get(BEARER_TOKEN).toString() + ); + Optional matchingLocation = Optional.ofNullable(preferredCourt) + .flatMap(requestedCourt -> locationHelper.getMatching(locations, preferredCourt)); + + DynamicList locationsList; + if (matchingLocation.isPresent()) { + locationsList = DynamicList.fromList(locations, this::getLocationEpimms, LocationRefDataService::getDisplayEntry, + matchingLocation.get(), true + ); + } else { + locationsList = DynamicList.fromList(locations, this::getLocationEpimms, LocationRefDataService::getDisplayEntry, + null, true + ); + } + return locationsList; + } + + private String getLocationEpimms(LocationRefData location) { + return location.getEpimmsId(); + } + private CallbackResponse generateSDONotifications(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); @@ -642,31 +661,46 @@ private CallbackResponse generateSDONotifications(CallbackParams callbackParams) caseDataBuilder.orderSDODocumentDJ(null); assignCategoryId.assignCategoryIdToCollection(caseData.getOrderSDODocumentDJCollection(), document -> document.getValue().getDocumentLink(), "sdo"); caseDataBuilder.businessProcess(BusinessProcess.ready(STANDARD_DIRECTION_ORDER_DJ)); - var state = "CASE_PROGRESSION"; String authToken = callbackParams.getParams().get(BEARER_TOKEN).toString(); List locations = (locationRefDataService .getCourtLocationsForDefaultJudgments(authToken)); - LocationRefData location = null; if (nonNull(locations)) { - location = fillPreferredLocationData(locations, getLocationListFromCaseData( + LocationRefData location = fillPreferredLocationData(locations, getLocationListFromCaseData( caseData.getDisposalHearingMethodInPersonDJ(), caseData.getTrialHearingMethodInPersonDJ())); Optional.ofNullable(location) - .map(LocationHelper::buildCaseLocation) - .ifPresent(caseDataBuilder::caseManagementLocation); - Optional.ofNullable(location) - .map(value -> value.getSiteName()) + .map(LocationRefData::getSiteName) .ifPresent(caseDataBuilder::locationName); } - + var state = "CASE_PROGRESSION"; caseDataBuilder.hearingNotes(getHearingNotes(caseData)); + if (featureToggleService.isEarlyAdoptersEnabled()) { + if (featureToggleService.isLocationWhiteListedForCaseProgression( + getEpimmsId(caseData))) { + log.info("Case {} is whitelisted for case progression.", caseData.getCcdCaseReference()); + caseDataBuilder.eaCourtLocation(YesOrNo.YES); + } else { + log.info("Case {} is NOT whitelisted for case progression.", caseData.getCcdCaseReference()); + caseDataBuilder.eaCourtLocation(YesOrNo.NO); + } + } + return AboutToStartOrSubmitCallbackResponse.builder() .data(caseDataBuilder.build().toMap(objectMapper)) .state(state) .build(); } + private String getEpimmsId(CaseData caseData) { + if (caseData.getTrialHearingMethodInPersonDJ() != null) { + return caseData.getTrialHearingMethodInPersonDJ().getValue().getCode(); + } else if (caseData.getDisposalHearingMethodInPersonDJ() != null) { + return caseData.getDisposalHearingMethodInPersonDJ().getValue().getCode(); + } + throw new IllegalArgumentException("Epimms Id is not provided"); + } + private SubmittedCallbackResponse buildConfirmation(CallbackParams callbackParams) { var caseData = callbackParams.getCaseData(); return SubmittedCallbackResponse.builder() @@ -676,6 +710,11 @@ private SubmittedCallbackResponse buildConfirmation(CallbackParams callbackParam } private CallbackResponse createOrderScreen(CallbackParams callbackParams) { + var response = (AboutToStartOrSubmitCallbackResponse) validateInputValue(callbackParams); + if (response.getErrors() != null) { + return response; + } + CaseData caseData = V_1.equals(callbackParams.getVersion()) ? mapHearingMethodFields(callbackParams.getCaseData()) : callbackParams.getCaseData(); @@ -755,15 +794,6 @@ private CaseData fillTrialToggle(CaseData caseData, List locations) { - return fromList(locations.stream() - .map(location -> location.getSiteName() - + " - " + location.getCourtAddress() - + " - " + location.getPostcode()) - .sorted() - .collect(Collectors.toList())); - } - private DynamicList deleteLocationList(DynamicList list) { if (isNull(list)) { return null; @@ -803,4 +833,28 @@ private DynamicList getLocationListFromCaseData(DynamicList hearingList, Dynamic return null; } } + + private CallbackResponse validateInputValue(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + if (nonNull(caseData.getTrialHearingWitnessOfFactDJ())) { + String inputValue1 = caseData.getTrialHearingWitnessOfFactDJ().getInput2(); + String inputValue2 = caseData.getTrialHearingWitnessOfFactDJ().getInput3(); + List errors = new ArrayList<>(); + if (inputValue1 != null && inputValue2 != null) { + int number1 = Integer.parseInt(inputValue1); + int number2 = Integer.parseInt(inputValue2); + if (number1 < 0 || number2 < 0) { + errors.add("The number entered cannot be less than zero"); + return AboutToStartOrSubmitCallbackResponse.builder() + .errors(errors) + .build(); + } + } + } + + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .build(); + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/TransferOnlineCaseCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/TransferOnlineCaseCallbackHandler.java new file mode 100644 index 00000000000..85837b957ac --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/TransferOnlineCaseCallbackHandler.java @@ -0,0 +1,147 @@ +package uk.gov.hmcts.reform.civil.handler.callback.user; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.SubmittedCallbackResponse; +import uk.gov.hmcts.reform.civil.callback.Callback; +import uk.gov.hmcts.reform.civil.callback.CallbackHandler; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.helpers.LocationHelper; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.common.DynamicList; +import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; +import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; +import uk.gov.hmcts.reform.civil.utils.CourtLocationUtils; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static java.util.Objects.nonNull; +import static uk.gov.hmcts.reform.civil.callback.CallbackParams.Params.BEARER_TOKEN; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.TRANSFER_ONLINE_CASE; +import static uk.gov.hmcts.reform.civil.model.common.DynamicList.fromList; + +@Service +@RequiredArgsConstructor +public class TransferOnlineCaseCallbackHandler extends CallbackHandler { + + private static final List EVENTS = Collections.singletonList(TRANSFER_ONLINE_CASE); + protected final ObjectMapper objectMapper; + private final LocationRefDataService locationRefDataService; + private final CourtLocationUtils courtLocationUtils; + private static final String ERROR_SELECT_DIFF_LOCATION = "Select a different hearing court location to transfer!"; + private static final String CONFIRMATION_HEADER = "# Case transferred to new location"; + + @Override + protected Map callbacks() { + return new ImmutableMap.Builder() + .put(callbackKey(ABOUT_TO_START), this::locationList) + .put(callbackKey(MID, "validate-court-location"), this::validateCourtLocation) + .put(callbackKey(ABOUT_TO_SUBMIT), this::saveTransferOnlineCase) + .put(callbackKey(SUBMITTED), this::buildConfirmation) + .build(); + } + + private CallbackResponse validateCourtLocation(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + List errors = new ArrayList<>(); + + if (ifSameCourtSelected(callbackParams)) { + errors.add(ERROR_SELECT_DIFF_LOCATION); + } + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .errors(errors) + .build(); + } + + private CallbackResponse buildConfirmation(CallbackParams callbackParams) { + String newCourtLocationSiteName = courtLocationUtils.findPreferredLocationData( + fetchLocationData(callbackParams), + callbackParams.getCaseData().getTransferCourtLocationList()).getSiteName(); + return SubmittedCallbackResponse.builder() + .confirmationHeader(CONFIRMATION_HEADER) + .confirmationBody(getBody(newCourtLocationSiteName)) + .build(); + } + + private CallbackResponse locationList(CallbackParams callbackParams) { + var caseData = callbackParams.getCaseData(); + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + List locations = fetchLocationData(callbackParams); + caseDataBuilder.transferCourtLocationList(getLocationsFromList(locations)); + + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .build(); + } + + private DynamicList getLocationsFromList(final List locations) { + return fromList(locations.stream().map(location -> new StringBuilder().append(location.getSiteName()) + .append(" - ").append(location.getCourtAddress()) + .append(" - ").append(location.getPostcode()).toString()) + .toList()); + } + + private String getBody(String siteName) { + return "

What happens next

" + + "The case has now been transferred to " + + siteName + + ". If the case has moved out of your region, you will no longer see it.

"; + } + + private CallbackResponse saveTransferOnlineCase(CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); + LocationRefData newCourtLocation = courtLocationUtils.findPreferredLocationData( + fetchLocationData(callbackParams), + callbackParams.getCaseData().getTransferCourtLocationList()); + if (nonNull(newCourtLocation)) { + caseDataBuilder.caseManagementLocation(LocationHelper.buildCaseLocation(newCourtLocation)); + } + DynamicList tempLocationList = caseData.getTransferCourtLocationList(); + tempLocationList.setListItems(null); + caseDataBuilder.transferCourtLocationList(tempLocationList); + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseDataBuilder.build().toMap(objectMapper)) + .build(); + } + + private boolean ifSameCourtSelected(CallbackParams callbackParams) { + LocationRefData newCourtLocation = courtLocationUtils.findPreferredLocationData( + fetchLocationData(callbackParams), + callbackParams.getCaseData().getTransferCourtLocationList()); + LocationRefData caseManagementLocation = + getLocationRefData(callbackParams); + return caseManagementLocation != null && newCourtLocation.getCourtLocationCode().equals(caseManagementLocation.getCourtLocationCode()); + } + + private LocationRefData getLocationRefData(CallbackParams callbackParams) { + List locations = fetchLocationData(callbackParams); + String baseLocation = callbackParams.getCaseData().getCaseManagementLocation() == null ? null : callbackParams.getCaseData().getCaseManagementLocation().getBaseLocation(); + var matchedLocations = locations.stream().filter(loc -> loc.getEpimmsId().equals(baseLocation)).toList(); + return matchedLocations.size() > 0 ? matchedLocations.get(0) : null; + } + + private List fetchLocationData(CallbackParams callbackParams) { + String authToken = callbackParams.getParams().get(BEARER_TOKEN).toString(); + return locationRefDataService.getCourtLocationsForDefaultJudgments(authToken); + } + + @Override + public List handledEvents() { + return EVENTS; + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/TrialReadinessCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/TrialReadinessCallbackHandler.java index 990be585fa8..fcf84a5bc97 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/TrialReadinessCallbackHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/TrialReadinessCallbackHandler.java @@ -10,7 +10,6 @@ import uk.gov.hmcts.reform.civil.callback.CallbackHandler; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; -import uk.gov.hmcts.reform.civil.enums.CaseRole; import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.model.BusinessProcess; import uk.gov.hmcts.reform.civil.model.CaseData; @@ -39,6 +38,10 @@ import static uk.gov.hmcts.reform.civil.callback.CaseEvent.RESPONDENT2_TRIAL_READY_NOTIFY_OTHERS; import static uk.gov.hmcts.reform.civil.enums.AllocatedTrack.SMALL_CLAIM; import static uk.gov.hmcts.reform.civil.utils.HearingUtils.formatHearingDuration; +import static uk.gov.hmcts.reform.civil.utils.UserRoleUtils.isApplicantSolicitor; +import static uk.gov.hmcts.reform.civil.utils.UserRoleUtils.isLIPClaimant; +import static uk.gov.hmcts.reform.civil.utils.UserRoleUtils.isLIPDefendant; +import static uk.gov.hmcts.reform.civil.utils.UserRoleUtils.isRespondentSolicitorOne; @Service @RequiredArgsConstructor @@ -54,14 +57,15 @@ public class TrialReadinessCallbackHandler extends CallbackHandler { + "you will need to make an application as soon as possible and pay the appropriate fee."; public static final String NOT_READY_HEADER = "## You have said this case is not ready for trial or hearing"; public static final String NOT_READY_BODY = "### What happens next \n\n" - + "You can view your and other party's trial arrangements in documents in the case details. " - + "If there are any additional changes between now and the hearing date, " - + "you will need to make an application as soon as possible and pay the appropriate fee.\n\n" - + "The trial will go ahead on the specified date " - + "unless a judge makes an order changing the date of the hearing. " - + "If you want the date of the hearing to be changed (or any other order to make the case ready for trial)" - + "you will need to make an application to the court and pay the appropriate fee."; + + "You can view your and other party's trial arrangements in documents in the case details. " + + "If there are any additional changes between now and the hearing date, " + + "you will need to make an application as soon as possible and pay the appropriate fee.\n\n" + + "The trial will go ahead on the specified date " + + "unless a judge makes an order changing the date of the hearing. " + + "If you want the date of the hearing to be changed (or any other order to make the case ready for trial)" + + "you will need to make an application to the court and pay the appropriate fee."; private final ObjectMapper objectMapper; + private final UserService userService; private final CoreCaseUserService coreCaseUserService; @@ -77,14 +81,15 @@ protected Map callbacks() { private CallbackResponse populateValues(CallbackParams callbackParams) { var caseData = callbackParams.getCaseData(); CaseData.CaseDataBuilder updatedData = caseData.toBuilder(); + List userRoles = getUserRoles(callbackParams); var isApplicant = YesOrNo.NO; var isRespondent1 = YesOrNo.NO; var isRespondent2 = YesOrNo.NO; - if (checkUserRoles(callbackParams, CaseRole.APPLICANTSOLICITORONE)) { + if (isApplicantSolicitor(userRoles)) { isApplicant = YesOrNo.YES; updatedData.hearingDurationTextApplicant(formatHearingDuration(caseData.getHearingDuration())); - } else if (checkUserRoles(callbackParams, CaseRole.RESPONDENTSOLICITORONE)) { + } else if (isRespondentSolicitorOne(userRoles)) { isRespondent1 = YesOrNo.YES; updatedData.hearingDurationTextRespondent1(formatHearingDuration(caseData.getHearingDuration())); } else { @@ -108,22 +113,22 @@ private CallbackResponse populateValues(CallbackParams callbackParams) { return AboutToStartOrSubmitCallbackResponse.builder() .errors(errors) - .data(errors.size() == 0 - ? updatedData.build().toMap(objectMapper) : null) + .data(errors.isEmpty() ? updatedData.build().toMap(objectMapper) : null) .build(); } private CallbackResponse setBusinessProcess(CallbackParams callbackParams) { var caseData = callbackParams.getCaseData(); - CaseData.CaseDataBuilder updatedData = caseData.toBuilder(); + CaseData.CaseDataBuilder updatedData = caseData.toBuilder(); + List userRoles = getUserRoles(callbackParams); - if (checkUserRoles(callbackParams, CaseRole.APPLICANTSOLICITORONE) || checkUserRoles(callbackParams, CaseRole.CLAIMANT)) { + if (isApplicantSolicitor(userRoles) || isLIPClaimant(userRoles)) { if (caseData.getTrialReadyApplicant() == YesOrNo.YES) { updatedData.businessProcess(BusinessProcess.ready(APPLICANT_TRIAL_READY_NOTIFY_OTHERS)); } else { updatedData.businessProcess(BusinessProcess.ready(GENERATE_TRIAL_READY_DOCUMENT_APPLICANT)); } - } else if (checkUserRoles(callbackParams, CaseRole.RESPONDENTSOLICITORONE) || checkUserRoles(callbackParams, CaseRole.DEFENDANT)) { + } else if (isRespondentSolicitorOne(userRoles) || isLIPDefendant(userRoles)) { if (caseData.getTrialReadyRespondent1() == YesOrNo.YES) { updatedData.businessProcess(BusinessProcess.ready(RESPONDENT1_TRIAL_READY_NOTIFY_OTHERS)); } else { @@ -143,29 +148,31 @@ private CallbackResponse setBusinessProcess(CallbackParams callbackParams) { } private SubmittedCallbackResponse buildConfirmation(CallbackParams callbackParams) { + List userRoles = getUserRoles(callbackParams); return SubmittedCallbackResponse.builder() - .confirmationHeader(checkUserReady(callbackParams).equals(YesOrNo.YES) ? READY_HEADER : NOT_READY_HEADER) - .confirmationBody(checkUserReady(callbackParams).equals(YesOrNo.YES) ? READY_BODY : NOT_READY_BODY) + .confirmationHeader(checkUserReady(callbackParams, userRoles).equals(YesOrNo.YES) ? READY_HEADER : NOT_READY_HEADER) + .confirmationBody(checkUserReady(callbackParams, userRoles).equals(YesOrNo.YES) ? READY_BODY : NOT_READY_BODY) .build(); } - private YesOrNo checkUserReady(CallbackParams callbackParams) { + private YesOrNo checkUserReady(CallbackParams callbackParams, List userRoles) { var caseData = callbackParams.getCaseData(); - if (checkUserRoles(callbackParams, CaseRole.APPLICANTSOLICITORONE)) { + if (isApplicantSolicitor(userRoles) || isLIPClaimant(userRoles)) { return caseData.getTrialReadyApplicant(); - } else if (checkUserRoles(callbackParams, CaseRole.RESPONDENTSOLICITORONE)) { + } else if (isRespondentSolicitorOne(userRoles) || isLIPDefendant(userRoles)) { return caseData.getTrialReadyRespondent1(); } else { return caseData.getTrialReadyRespondent2(); } } - private boolean checkUserRoles(CallbackParams callbackParams, CaseRole userRole) { - UserInfo userInfo = userService.getUserInfo(callbackParams.getParams().get(BEARER_TOKEN).toString()); - return coreCaseUserService.userHasCaseRole(callbackParams.getCaseData().getCcdCaseReference().toString(), - userInfo.getUid(), userRole); + private List getUserRoles(CallbackParams callbackParams) { + String bearerToken = callbackParams.getParams().get(BEARER_TOKEN).toString(); + String ccdCaseRef = callbackParams.getCaseData().getCcdCaseReference().toString(); + UserInfo userInfo = userService.getUserInfo(bearerToken); + return coreCaseUserService.getUserCaseRoles(ccdCaseRef, userInfo.getUid()); } @Override diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/FullAdmitSetDateConfirmationText.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/FullAdmitSetDateConfirmationText.java index 05da7c87f7f..36d77cc475f 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/FullAdmitSetDateConfirmationText.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/FullAdmitSetDateConfirmationText.java @@ -63,11 +63,7 @@ public Optional generateTextFor(CaseData caseData) { } sb.append(" legal representative if you need details on how to pay.

") .append("

If you do not pay immediately, ").append(applicantName) - .append(" can either:

") - .append("
    ") - .append("
  • ask you to sign a settlement agreement to formalise the repayment plan
  • ") - .append("
  • request a county court judgment against you
  • ") - .append("
") + .append(" can request a county court judgment against you.

") .append("

If ") .append(applicantName); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/PartialAdmitPayImmediatelyConfirmationText.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/PartialAdmitPayImmediatelyConfirmationText.java index 2c67ef199a5..795c06132bc 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/PartialAdmitPayImmediatelyConfirmationText.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/PartialAdmitPayImmediatelyConfirmationText.java @@ -2,6 +2,7 @@ import org.springframework.stereotype.Component; import uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec; +import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec; import uk.gov.hmcts.reform.civil.handler.callback.user.spec.RespondToClaimConfirmationTextSpecGenerator; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.RespondToClaimAdmitPartLRspec; @@ -41,8 +42,14 @@ public Optional generateTextFor(CaseData caseData) { .append(formattedWhenBePaid).append("") .append("
  • keep proof of any payments you make
  • ") .append("
  • make sure ").append(applicantName).append(" tells the court that you've paid").append("
  • ") - .append("") - .append("

    Contact ") + .append(""); + if (caseData.getRespondent2() == null && caseData.getApplicant2() == null) { + if (!RespondentResponseTypeSpec.PART_ADMISSION.equals(caseData.getRespondent1ClaimResponseTypeForSpec())) { + sb.append("

    If you do not pay:

    ") + .append("

    If you do not pay, the claimant can request a County Court Judgment against you.

    "); + } + } + sb.append("

    Contact ") .append(applicantName); if (applicantName.endsWith("s")) { sb.append("'"); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/PartialAdmitSetDateConfirmationText.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/PartialAdmitSetDateConfirmationText.java index e6ab2b4e24a..c694bceb407 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/PartialAdmitSetDateConfirmationText.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/PartialAdmitSetDateConfirmationText.java @@ -91,25 +91,25 @@ public Optional generateTextFor(CaseData caseData) { .append("

    Because you've said you will not pay immediately, ") .append(applicantName) - .append(" can either:

    ") - .append("
      ") - .append("
    • ask you to sign a settlement agreement to formalise the repayment plan
    • ") - .append("
    • request a county court judgment against you for £") - .append(admitOwed).append("
    • ") - .append("
    ") + .append(" can request a county court judgment against you for £") + .append(admitOwed).append(".

    ") .append("

    If ") .append(applicantName) .append(" disagrees that you only owe £") .append(admitOwed) - .append("

    ") - .append("

    We'll ask if they want to try mediation. ") - .append("If they agree we'll contact you to arrange a call with the mediator.

    ") - .append( - "

    If they do not want to try mediation the court will review the case for the full amount of £") - .append(totalClaimAmount).append(".

    ") - - .append("

    If ") + .append("

    "); + if (caseData.hasDefendantAgreedToFreeMediation()) { + sb.append("

    We'll ask if they want to try mediation. ") + .append("If they agree we'll contact you to arrange a call with the mediator.

    ") + .append( + "

    If they do not want to try mediation the court will review the case for the full amount of £") + .append(totalClaimAmount).append(".

    "); + } else { + sb.append("

    The court will review the case for the full amount of £") + .append(totalClaimAmount).append(".

    "); + } + sb.append("

    If ") .append(applicantName) .append(" rejects your offer to pay by ") .append(DateFormatHelper.formatLocalDate(whenWillYouPay, DATE)) diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/RepayPlanConfirmationText.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/RepayPlanConfirmationText.java index ef04052829a..8ff66d373c0 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/RepayPlanConfirmationText.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/spec/response/confirmation/RepayPlanConfirmationText.java @@ -74,7 +74,6 @@ public Optional generateTextFor(CaseData caseData) { } sb.append("
  • request a county court judgment against you
  • ") .append("") - .append("

    If ") .append(applicantName); if (caseData.getApplicant2() != null) { diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/strategy/translateddocuments/UploadTranslatedDocumentDefaultStrategy.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/strategy/translateddocuments/UploadTranslatedDocumentDefaultStrategy.java index f264ee32e85..2406f9c3b39 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/strategy/translateddocuments/UploadTranslatedDocumentDefaultStrategy.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/callback/user/strategy/translateddocuments/UploadTranslatedDocumentDefaultStrategy.java @@ -10,14 +10,13 @@ import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.model.BusinessProcess; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; import uk.gov.hmcts.reform.civil.model.citizenui.TranslatedDocument; import uk.gov.hmcts.reform.civil.model.common.Element; import uk.gov.hmcts.reform.civil.service.SystemGeneratedDocumentService; import java.util.List; -import java.util.Optional; - -import static uk.gov.hmcts.reform.civil.enums.CaseState.AWAITING_APPLICANT_INTENTION; +import java.util.Objects; @Component @RequiredArgsConstructor @@ -28,33 +27,27 @@ public class UploadTranslatedDocumentDefaultStrategy implements UploadTranslated @Override public CallbackResponse uploadDocument(CallbackParams callbackParams) { - List> updatedDocumentList = updateSystemGeneratedDocumentsWithTranslationDocument( + List> updatedDocumentList = updateSystemGeneratedDocumentsWithTranslationDocuments( callbackParams); + CaseDataLiP caseDataLip = callbackParams.getCaseData().getCaseDataLiP(); + + if (Objects.nonNull(caseDataLip)) { + caseDataLip.setTranslatedDocuments(null); + } + CaseData updatedCaseData = callbackParams.getCaseData().toBuilder().systemGeneratedCaseDocuments( - updatedDocumentList) - .respondent1ClaimResponseDocumentSpec(getTranslatedDocumentAsCaseDocument(callbackParams)) + updatedDocumentList) + .caseDataLiP(caseDataLip) .businessProcess(BusinessProcess.ready(CaseEvent.UPLOAD_TRANSLATED_DOCUMENT)).build(); + return AboutToStartOrSubmitCallbackResponse.builder() - .state(AWAITING_APPLICANT_INTENTION.name()) .data(updatedCaseData.toMap(objectMapper)) .build(); } - private List> updateSystemGeneratedDocumentsWithTranslationDocument(CallbackParams callbackParams) { + private List> updateSystemGeneratedDocumentsWithTranslationDocuments(CallbackParams callbackParams) { CaseData caseData = callbackParams.getCaseData(); - Optional translatedDocument = caseData.getTranslatedDocument(); - return translatedDocument.map(document -> systemGeneratedDocumentService.getSystemGeneratedDocumentsWithAddedDocument( - document.getFile(), - document.getCorrespondingDocumentType(), - callbackParams - )).orElse(caseData.getSystemGeneratedCaseDocuments()); - } - - private CaseDocument getTranslatedDocumentAsCaseDocument(CallbackParams callbackParams) { - Optional translatedDocument = callbackParams.getCaseData().getTranslatedDocument(); - return translatedDocument.map(document -> CaseDocument.toCaseDocument( - document.getFile(), - document.getCorrespondingDocumentType() - )).orElse(null); + List> translatedDocuments = caseData.getTranslatedDocuments(); + return systemGeneratedDocumentService.getSystemGeneratedDocumentsWithAddedDocument(translatedDocuments, callbackParams); } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/event/BundleCreationTriggerEventHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/event/BundleCreationTriggerEventHandler.java index 2389582acf2..abf03c46ba8 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/event/BundleCreationTriggerEventHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/event/BundleCreationTriggerEventHandler.java @@ -2,7 +2,6 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.ccd.client.model.CaseDataContent; @@ -21,6 +20,7 @@ import uk.gov.hmcts.reform.civil.utils.ElementUtils; import java.time.LocalDateTime; +import java.time.ZoneId; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -35,7 +35,6 @@ @AllArgsConstructor public class BundleCreationTriggerEventHandler { - @Autowired private BundleCreationService bundleCreationService; private final CoreCaseDataService coreCaseDataService; private final CaseDetailsConverter caseDetailsConverter; @@ -67,12 +66,12 @@ IdValue prepareNewBundle(uk.gov.hmcts.reform.civil.model.bundle.Bundle b Bundle result = Bundle.builder() .bundleHearingDate(Optional.of(caseData.getHearingDate())) .stitchedDocument(Optional.ofNullable(bundle.getValue().getStitchedDocument())) - .filename(bundle.getValue().getFileName()) + .fileName(bundle.getValue().getFileName()) .title(bundle.getValue().getTitle()) .description(null != bundle.getValue().getDescription() ? Optional.of(bundle.getValue().getDescription()).get() : "") .stitchStatus(Optional.ofNullable(bundle.getValue().getStitchStatus())) - .createdOn(Optional.of(LocalDateTime.now())) + .createdOn(Optional.of(LocalDateTime.now(ZoneId.of("Europe/London")))) .id(bundle.getValue().getId()).build(); return new IdValue<>(result.getId(), result); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/event/EvidenceUploadNotificationEventHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/event/EvidenceUploadNotificationEventHandler.java index ed52e4d8582..84adb0d19a8 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/event/EvidenceUploadNotificationEventHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/event/EvidenceUploadNotificationEventHandler.java @@ -4,7 +4,10 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.CaseDataContent; import uk.gov.hmcts.reform.ccd.client.model.CaseDetails; +import uk.gov.hmcts.reform.ccd.client.model.Event; +import uk.gov.hmcts.reform.ccd.client.model.StartEventResponse; import uk.gov.hmcts.reform.civil.event.EvidenceUploadNotificationEvent; import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; import uk.gov.hmcts.reform.civil.model.CaseData; @@ -12,6 +15,10 @@ import uk.gov.hmcts.reform.civil.notification.EvidenceUploadRespondentNotificationHandler; import uk.gov.hmcts.reform.civil.service.CoreCaseDataService; +import java.util.Map; + +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.EVIDENCE_UPLOAD_CHECK; + @Slf4j @Service @RequiredArgsConstructor @@ -50,5 +57,19 @@ public void sendEvidenceUploadNotification(EvidenceUploadNotificationEvent event } catch (Exception e) { log.warn("Failed to send email notification to respondent solicitor2 for case '{}'", event.getCaseId()); } + // null notificationText so it cleared each day, for any future evidence uploads + StartEventResponse startEventResponse = coreCaseDataService.startUpdate(event.getCaseId().toString(), EVIDENCE_UPLOAD_CHECK); + CaseDataContent caseContent = getCaseContent(startEventResponse); + coreCaseDataService.submitUpdate(event.getCaseId().toString(), caseContent); + } + + private CaseDataContent getCaseContent(StartEventResponse startEventResponse) { + Map data = startEventResponse.getCaseDetails().getData(); + data.put("notificationText", "NULLED"); + return CaseDataContent.builder() + .eventToken(startEventResponse.getToken()) + .event(Event.builder().id(startEventResponse.getEventId()).build()) + .data(data) + .build(); } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/event/StitchingCompleteCallbackHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/event/StitchingCompleteCallbackHandler.java new file mode 100644 index 00000000000..71201b2e620 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/event/StitchingCompleteCallbackHandler.java @@ -0,0 +1,61 @@ +package uk.gov.hmcts.reform.civil.handler.event; + +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; +import uk.gov.hmcts.reform.civil.callback.Callback; +import uk.gov.hmcts.reform.civil.callback.CallbackHandler; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.enums.DocCategory; +import uk.gov.hmcts.reform.civil.model.CaseData; + +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.asyncStitchingComplete; + +@Slf4j +@Service +@RequiredArgsConstructor +public class StitchingCompleteCallbackHandler extends CallbackHandler { + + private static final List EVENTS = List.of(asyncStitchingComplete); + private final ObjectMapper objectMapper; + + @Override + protected Map callbacks() { + return Map.of( + callbackKey(ABOUT_TO_START), this::emptyCallbackResponse, + callbackKey(ABOUT_TO_SUBMIT), this::triggerUpdateBundleCategoryId, + callbackKey(SUBMITTED), this::emptySubmittedCallbackResponse + ); + } + + @Override + public List handledEvents() { + return EVENTS; + } + + private CallbackResponse triggerUpdateBundleCategoryId(final CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + caseData.getCaseBundles().forEach(bundleIdValue -> bundleIdValue + .getValue().getStitchedDocument().ifPresent( + (document) -> { + if (Objects.isNull(document.getCategoryID())) { + document.setCategoryID(DocCategory.BUNDLES.getValue()); + } + } + )); + return AboutToStartOrSubmitCallbackResponse.builder() + .data(caseData.toMap(objectMapper)) + .build(); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/handler/tasks/UpdateFromGACaseEventTaskHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/handler/tasks/UpdateFromGACaseEventTaskHandler.java index 7a1c766c57c..5a4e14a3ce4 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/handler/tasks/UpdateFromGACaseEventTaskHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/handler/tasks/UpdateFromGACaseEventTaskHandler.java @@ -100,6 +100,7 @@ private Map getUpdatedCaseData(CaseData civilCaseData, CaseData updateDocCollectionField(output, civilCaseData, generalAppCaseData, "writtenRepConcurrent"); updateDocCollectionField(output, civilCaseData, generalAppCaseData, "consentOrder"); updateDocCollectionField(output, civilCaseData, generalAppCaseData, gaDraft); + updateDocCollectionField(output, civilCaseData, generalAppCaseData, "gaResp"); updateDocCollection(output, generalAppCaseData, "gaRespondDoc", civilCaseData, "gaRespondDoc"); } catch (Exception e) { diff --git a/src/main/java/uk/gov/hmcts/reform/civil/helpers/bundle/BundleFileNameHelper.java b/src/main/java/uk/gov/hmcts/reform/civil/helpers/bundle/BundleFileNameHelper.java index ca7dfe2808b..907a344b774 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/helpers/bundle/BundleFileNameHelper.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/helpers/bundle/BundleFileNameHelper.java @@ -7,6 +7,7 @@ import uk.gov.hmcts.reform.civil.model.caseprogression.UploadEvidenceWitness; import uk.gov.hmcts.reform.civil.model.common.Element; +import java.util.Collections; import java.util.List; public class BundleFileNameHelper { @@ -21,37 +22,37 @@ protected static List> getWitnessDocsByPartyAndDo case WITNESS_STATEMENT : { return switch (partyType) { case CLAIMANT1 -> caseData.getDocumentWitnessStatement() != null - ? caseData.getDocumentWitnessStatement() : null; + ? caseData.getDocumentWitnessStatement() : Collections.emptyList(); case CLAIMANT2 -> caseData.getDocumentWitnessStatementApp2() != null - ? caseData.getDocumentWitnessStatementApp2() : null; + ? caseData.getDocumentWitnessStatementApp2() : Collections.emptyList(); case DEFENDANT1 -> caseData.getDocumentWitnessStatementRes() != null - ? caseData.getDocumentWitnessStatementRes() : null; + ? caseData.getDocumentWitnessStatementRes() : Collections.emptyList(); case DEFENDANT2 -> caseData.getDocumentWitnessStatementRes2() != null - ? caseData.getDocumentWitnessStatementRes2() : null; + ? caseData.getDocumentWitnessStatementRes2() : Collections.emptyList(); }; } case WITNESS_SUMMARY : { return switch (partyType) { case CLAIMANT1 -> caseData.getDocumentWitnessSummary() != null - ? caseData.getDocumentWitnessSummary() : null; + ? caseData.getDocumentWitnessSummary() : Collections.emptyList(); case CLAIMANT2 -> caseData.getDocumentWitnessSummaryApp2() != null - ? caseData.getDocumentWitnessSummaryApp2() : null; + ? caseData.getDocumentWitnessSummaryApp2() : Collections.emptyList(); case DEFENDANT1 -> caseData.getDocumentWitnessSummaryRes() != null - ? caseData.getDocumentWitnessSummaryRes() : null; + ? caseData.getDocumentWitnessSummaryRes() : Collections.emptyList(); case DEFENDANT2 -> caseData.getDocumentWitnessSummaryRes2() != null - ? caseData.getDocumentWitnessSummaryRes2() : null; + ? caseData.getDocumentWitnessSummaryRes2() : Collections.emptyList(); }; } case NOTICE_OF_INTENTION : { return switch (partyType) { case CLAIMANT1 -> caseData.getDocumentHearsayNotice() != null - ? caseData.getDocumentHearsayNotice() : null; + ? caseData.getDocumentHearsayNotice() : Collections.emptyList(); case CLAIMANT2 -> caseData.getDocumentHearsayNoticeApp2() != null - ? caseData.getDocumentHearsayNoticeApp2() : null; + ? caseData.getDocumentHearsayNoticeApp2() : Collections.emptyList(); case DEFENDANT1 -> caseData.getDocumentHearsayNoticeRes() != null - ? caseData.getDocumentHearsayNoticeRes() : null; + ? caseData.getDocumentHearsayNoticeRes() : Collections.emptyList(); case DEFENDANT2 -> caseData.getDocumentHearsayNoticeRes2() != null - ? caseData.getDocumentHearsayNoticeRes2() : null; + ? caseData.getDocumentHearsayNoticeRes2() : Collections.emptyList(); }; } default: return null; @@ -65,49 +66,49 @@ protected static List> getExpertDocsByPartyAndDocT case EXPERT_REPORT : { return switch (partyType) { case CLAIMANT1 -> caseData.getDocumentExpertReport() != null - ? caseData.getDocumentExpertReport() : null; + ? caseData.getDocumentExpertReport() : Collections.emptyList(); case CLAIMANT2 -> caseData.getDocumentExpertReportApp2() != null - ? caseData.getDocumentExpertReportApp2() : null; + ? caseData.getDocumentExpertReportApp2() : Collections.emptyList(); case DEFENDANT1 -> caseData.getDocumentExpertReportRes() != null - ? caseData.getDocumentExpertReportRes() : null; + ? caseData.getDocumentExpertReportRes() : Collections.emptyList(); case DEFENDANT2 -> caseData.getDocumentExpertReportRes2() != null - ? caseData.getDocumentExpertReportRes2() : null; + ? caseData.getDocumentExpertReportRes2() : Collections.emptyList(); }; } case QUESTIONS_FOR_EXPERTS: { return switch (partyType) { case CLAIMANT1 -> caseData.getDocumentQuestions() != null - ? caseData.getDocumentQuestions() : null; + ? caseData.getDocumentQuestions() : Collections.emptyList(); case CLAIMANT2 -> caseData.getDocumentQuestionsApp2() != null - ? caseData.getDocumentQuestionsApp2() : null; + ? caseData.getDocumentQuestionsApp2() : Collections.emptyList(); case DEFENDANT1 -> caseData.getDocumentQuestionsRes() != null - ? caseData.getDocumentQuestionsRes() : null; + ? caseData.getDocumentQuestionsRes() : Collections.emptyList(); case DEFENDANT2 -> caseData.getDocumentQuestionsRes2() != null - ? caseData.getDocumentQuestionsRes2() : null; + ? caseData.getDocumentQuestionsRes2() : Collections.emptyList(); }; } case ANSWERS_FOR_EXPERTS: { return switch (partyType) { case CLAIMANT1 -> caseData.getDocumentAnswers() != null - ? caseData.getDocumentAnswers() : null; + ? caseData.getDocumentAnswers() : Collections.emptyList(); case CLAIMANT2 -> caseData.getDocumentAnswersApp2() != null - ? caseData.getDocumentAnswersApp2() : null; + ? caseData.getDocumentAnswersApp2() : Collections.emptyList(); case DEFENDANT1 -> caseData.getDocumentAnswersRes() != null - ? caseData.getDocumentAnswersRes() : null; + ? caseData.getDocumentAnswersRes() : Collections.emptyList(); case DEFENDANT2 -> caseData.getDocumentAnswersRes2() != null - ? caseData.getDocumentAnswersRes2() : null; + ? caseData.getDocumentAnswersRes2() : Collections.emptyList(); }; } case JOINT_STATEMENT: { return switch (partyType) { case CLAIMANT1 -> caseData.getDocumentJointStatement() != null - ? caseData.getDocumentJointStatement() : null; + ? caseData.getDocumentJointStatement() : Collections.emptyList(); case CLAIMANT2 -> caseData.getDocumentJointStatementApp2() != null - ? caseData.getDocumentJointStatementApp2() : null; + ? caseData.getDocumentJointStatementApp2() : Collections.emptyList(); case DEFENDANT1 -> caseData.getDocumentJointStatementRes() != null - ? caseData.getDocumentJointStatementRes() : null; + ? caseData.getDocumentJointStatementRes() : Collections.emptyList(); case DEFENDANT2 -> caseData.getDocumentJointStatementRes2() != null - ? caseData.getDocumentJointStatementRes2() : null; + ? caseData.getDocumentJointStatementRes2() : Collections.emptyList(); }; } default: return null; @@ -121,85 +122,85 @@ protected static List> getEvidenceUploadDocs case DOCUMENTS_FOR_DISCLOSURE: { return switch (partyType) { case CLAIMANT1 -> caseData.getDocumentForDisclosure() != null - ? caseData.getDocumentForDisclosure() : null; + ? caseData.getDocumentForDisclosure() : Collections.emptyList(); case CLAIMANT2 -> caseData.getDocumentForDisclosureApp2() != null - ? caseData.getDocumentForDisclosureApp2() : null; + ? caseData.getDocumentForDisclosureApp2() : Collections.emptyList(); case DEFENDANT1 -> caseData.getDocumentForDisclosureRes() != null - ? caseData.getDocumentForDisclosureRes() : null; + ? caseData.getDocumentForDisclosureRes() : Collections.emptyList(); case DEFENDANT2 -> caseData.getDocumentForDisclosureRes2() != null - ? caseData.getDocumentForDisclosureRes2() : null; + ? caseData.getDocumentForDisclosureRes2() : Collections.emptyList(); }; } case DISCLOSURE_LIST: { return switch (partyType) { case CLAIMANT1 -> caseData.getDocumentDisclosureList() != null - ? caseData.getDocumentDisclosureList() : null; + ? caseData.getDocumentDisclosureList() : Collections.emptyList(); case CLAIMANT2 -> caseData.getDocumentDisclosureListApp2() != null - ? caseData.getDocumentDisclosureListApp2() : null; + ? caseData.getDocumentDisclosureListApp2() : Collections.emptyList(); case DEFENDANT1 -> caseData.getDocumentDisclosureListRes() != null - ? caseData.getDocumentDisclosureListRes() : null; + ? caseData.getDocumentDisclosureListRes() : Collections.emptyList(); case DEFENDANT2 -> caseData.getDocumentDisclosureListRes2() != null - ? caseData.getDocumentDisclosureListRes2() : null; + ? caseData.getDocumentDisclosureListRes2() : Collections.emptyList(); }; } case DOCUMENTS_REFERRED: { return switch (partyType) { case CLAIMANT1 -> caseData.getDocumentReferredInStatement() != null - ? caseData.getDocumentReferredInStatement() : null; + ? caseData.getDocumentReferredInStatement() : Collections.emptyList(); case CLAIMANT2 -> caseData.getDocumentReferredInStatementApp2() != null - ? caseData.getDocumentReferredInStatementApp2() : null; + ? caseData.getDocumentReferredInStatementApp2() : Collections.emptyList(); case DEFENDANT1 -> caseData.getDocumentReferredInStatementRes() != null - ? caseData.getDocumentReferredInStatementRes() : null; + ? caseData.getDocumentReferredInStatementRes() : Collections.emptyList(); case DEFENDANT2 -> caseData.getDocumentReferredInStatementRes2() != null - ? caseData.getDocumentReferredInStatementRes2() : null; + ? caseData.getDocumentReferredInStatementRes2() : Collections.emptyList(); }; } case DOCUMENTARY: { return switch (partyType) { case CLAIMANT1 -> caseData.getDocumentEvidenceForTrial() != null - ? caseData.getDocumentEvidenceForTrial() : null; + ? caseData.getDocumentEvidenceForTrial() : Collections.emptyList(); case CLAIMANT2 -> caseData.getDocumentEvidenceForTrialApp2() != null - ? caseData.getDocumentEvidenceForTrialApp2() : null; + ? caseData.getDocumentEvidenceForTrialApp2() : Collections.emptyList(); case DEFENDANT1 -> caseData.getDocumentEvidenceForTrialRes() != null - ? caseData.getDocumentEvidenceForTrialRes() : null; + ? caseData.getDocumentEvidenceForTrialRes() : Collections.emptyList(); case DEFENDANT2 -> caseData.getDocumentEvidenceForTrialRes2() != null - ? caseData.getDocumentEvidenceForTrialRes2() : null; + ? caseData.getDocumentEvidenceForTrialRes2() : Collections.emptyList(); }; } case CASE_SUMMARY: { return switch (partyType) { case CLAIMANT1 -> caseData.getDocumentCaseSummary() != null - ? caseData.getDocumentCaseSummary() : null; + ? caseData.getDocumentCaseSummary() : Collections.emptyList(); case CLAIMANT2 -> caseData.getDocumentCaseSummaryApp2() != null - ? caseData.getDocumentCaseSummaryApp2() : null; + ? caseData.getDocumentCaseSummaryApp2() : Collections.emptyList(); case DEFENDANT1 -> caseData.getDocumentCaseSummaryRes() != null - ? caseData.getDocumentCaseSummaryRes() : null; + ? caseData.getDocumentCaseSummaryRes() : Collections.emptyList(); case DEFENDANT2 -> caseData.getDocumentCaseSummaryRes2() != null - ? caseData.getDocumentCaseSummaryRes2() : null; + ? caseData.getDocumentCaseSummaryRes2() : Collections.emptyList(); }; } case COSTS: { return switch (partyType) { case CLAIMANT1 -> caseData.getDocumentCosts() != null - ? caseData.getDocumentCosts() : null; + ? caseData.getDocumentCosts() : Collections.emptyList(); case CLAIMANT2 -> caseData.getDocumentCostsApp2() != null - ? caseData.getDocumentCostsApp2() : null; + ? caseData.getDocumentCostsApp2() : Collections.emptyList(); case DEFENDANT1 -> caseData.getDocumentCostsRes() != null - ? caseData.getDocumentCostsRes() : null; + ? caseData.getDocumentCostsRes() : Collections.emptyList(); case DEFENDANT2 -> caseData.getDocumentCostsRes2() != null - ? caseData.getDocumentCostsRes2() : null; + ? caseData.getDocumentCostsRes2() : Collections.emptyList(); }; } case SKELETON_ARGUMENT: { return switch (partyType) { case CLAIMANT1 -> caseData.getDocumentSkeletonArgument() != null - ? caseData.getDocumentSkeletonArgument() : null; + ? caseData.getDocumentSkeletonArgument() : Collections.emptyList(); case CLAIMANT2 -> caseData.getDocumentSkeletonArgumentApp2() != null - ? caseData.getDocumentSkeletonArgumentApp2() : null; + ? caseData.getDocumentSkeletonArgumentApp2() : Collections.emptyList(); case DEFENDANT1 -> caseData.getDocumentSkeletonArgumentRes() != null - ? caseData.getDocumentSkeletonArgumentRes() : null; + ? caseData.getDocumentSkeletonArgumentRes() : Collections.emptyList(); case DEFENDANT2 -> caseData.getDocumentSkeletonArgumentRes2() != null - ? caseData.getDocumentSkeletonArgumentRes2() : null; + ? caseData.getDocumentSkeletonArgumentRes2() : Collections.emptyList(); }; } default: return null; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/helpers/bundle/BundleRequestMapper.java b/src/main/java/uk/gov/hmcts/reform/civil/helpers/bundle/BundleRequestMapper.java index feaa58aec78..8267d327903 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/helpers/bundle/BundleRequestMapper.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/helpers/bundle/BundleRequestMapper.java @@ -27,17 +27,24 @@ import uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType; import uk.gov.hmcts.reform.civil.utils.ElementUtils; -import java.time.LocalDate; import java.util.Arrays; import java.util.Collections; +import java.util.Collection; import java.util.ArrayList; import java.util.HashMap; import java.util.Comparator; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.TreeMap; + +import java.time.LocalDate; + import java.util.stream.Collectors; import java.util.stream.IntStream; +import static uk.gov.hmcts.reform.civil.enums.CaseCategory.SPEC_CLAIM; import static uk.gov.hmcts.reform.civil.helpers.bundle.BundleFileNameHelper.getEvidenceUploadDocsByPartyAndDocType; import static uk.gov.hmcts.reform.civil.helpers.bundle.BundleFileNameHelper.getExpertDocsByPartyAndDocType; import static uk.gov.hmcts.reform.civil.helpers.bundle.BundleFileNameHelper.getWitnessDocsByPartyAndDocType; @@ -71,7 +78,7 @@ public BundleCreateRequest mapCaseDataToBundleCreateRequest(CaseData caseData, private String generateFileName(CaseData caseData) { String applicantName = caseData.getApplicant1().isIndividual() ? caseData.getApplicant1().getIndividualLastName() : caseData.getApplicant1().getPartyName(); - String respondentName = caseData.getApplicant1().isIndividual() + String respondentName = caseData.getRespondent1().isIndividual() ? caseData.getRespondent1().getIndividualLastName() : caseData.getRespondent1().getPartyName(); return applicantName + " v " + respondentName + "-" + DateFormatHelper.formatLocalDate(caseData.getHearingDate(), "ddMMyyyy"); @@ -103,7 +110,6 @@ private BundlingCaseData mapCaseData(CaseData caseData, String bundleConfigFileN .defendant2CostsBudgets(mapCostBudgetDocs(caseData, PartyType.DEFENDANT2)) .applicant1(caseData.getApplicant1()) .respondent1(caseData.getRespondent1()) - .courtLocation(caseData.getHearingLocation().getValue().getLabel()) .hearingDate(null != caseData.getHearingDate() ? DateFormatHelper.formatLocalDate(caseData.getHearingDate(), "dd-MM-yyyy") : null) .ccdCaseReference(caseData.getCcdCaseReference()) @@ -112,16 +118,42 @@ private BundlingCaseData mapCaseData(CaseData caseData, String bundleConfigFileN return bundlingCaseData; } + private List mapParticularsOfClaimDocs(CaseData caseData) { + List bundlingRequestDocuments = new ArrayList<>(); + if (Objects.nonNull(caseData.getServedDocumentFiles()) + && Objects.nonNull((caseData.getServedDocumentFiles().getParticularsOfClaimDocument()))) { + caseData.getServedDocumentFiles() + .getParticularsOfClaimDocument() + .forEach(poc -> bundlingRequestDocuments.add( + buildBundlingRequestDoc(getParticularsOfClaimName(caseData), + poc.getValue(), ""))); + } + return bundlingRequestDocuments; + } + + private String getParticularsOfClaimName(CaseData caseData) { + LocalDate pocDate; + if (SPEC_CLAIM.equals(caseData.getCaseAccessCategory())) { + pocDate = caseData.getIssueDate(); + } else if (Objects.nonNull(caseData.getClaimDetailsNotificationDate())) { + pocDate = caseData.getClaimDetailsNotificationDate().toLocalDate(); + } else { + pocDate = caseData.getSubmittedDate().toLocalDate(); + } + return generateDocName(BundleFileNameList.PARTICULARS_OF_CLAIM.getDisplayName(), + null, null, pocDate); + } + private List> mapJointStatementOfExperts(CaseData caseData) { List bundlingRequestDocuments = new ArrayList<>(); Arrays.stream(PartyType.values()).toList().forEach(partyType -> { - List allJointExpertsNames = getAllExpertsNames(partyType, EvidenceUploadFiles.JOINT_STATEMENT, + Set allJointExpertsNames = getAllExpertsNames(partyType, EvidenceUploadFiles.JOINT_STATEMENT, caseData); bundlingRequestDocuments.addAll(getAllExpertReports(partyType, EvidenceUploadFiles.JOINT_STATEMENT, caseData, BundleFileNameList.JOINT_STATEMENTS_OF_EXPERTS, allJointExpertsNames )); - bundlingRequestDocuments.addAll(getAllExpertReports(partyType, EvidenceUploadFiles.QUESTIONS_FOR_EXPERTS, caseData, - BundleFileNameList.QUESTIONS_TO, allJointExpertsNames)); + bundlingRequestDocuments.addAll(getAllOtherPartyQuestions(partyType, caseData, + allJointExpertsNames)); bundlingRequestDocuments.addAll(getAllExpertReports(partyType, EvidenceUploadFiles.ANSWERS_FOR_EXPERTS, caseData, BundleFileNameList.REPLIES_FROM, allJointExpertsNames)); }); @@ -163,27 +195,127 @@ private List> mapDisclosedDocs(CaseData caseDat private List> mapExpertEvidenceDocs(CaseData caseData, PartyType partyType) { List bundlingRequestDocuments = new ArrayList<>(); - List allExpertsNames = getAllExpertsNames(partyType, EvidenceUploadFiles.EXPERT_REPORT, caseData); + Set allExpertsNames = getAllExpertsNames(partyType, EvidenceUploadFiles.EXPERT_REPORT, caseData); + Set allJointExpertsNames = getAllExpertsNames(partyType, EvidenceUploadFiles.JOINT_STATEMENT, + caseData); bundlingRequestDocuments.addAll(getAllExpertReports(partyType, EvidenceUploadFiles.EXPERT_REPORT, caseData, BundleFileNameList.EXPERT_EVIDENCE, allExpertsNames)); - bundlingRequestDocuments.addAll(getAllExpertReports(partyType, EvidenceUploadFiles.QUESTIONS_FOR_EXPERTS, - caseData, BundleFileNameList.QUESTIONS_TO, allExpertsNames)); + + bundlingRequestDocuments.addAll(getAllOtherPartyQuestions(partyType, + caseData, allExpertsNames)); bundlingRequestDocuments.addAll(getAllExpertReports(partyType, EvidenceUploadFiles.ANSWERS_FOR_EXPERTS, caseData, BundleFileNameList.REPLIES_FROM, allExpertsNames)); - List allJointExpertsNames = getAllExpertsNames(partyType, EvidenceUploadFiles.JOINT_STATEMENT, - caseData); - bundlingRequestDocuments.addAll(getAllRemainingExpertReports(partyType, - EvidenceUploadFiles.QUESTIONS_FOR_EXPERTS, caseData, - BundleFileNameList.QUESTIONS_TO, allExpertsNames, allJointExpertsNames)); + bundlingRequestDocuments.addAll(getAllRemainingExpertQuestions(partyType, + EvidenceUploadFiles.QUESTIONS_FOR_EXPERTS, caseData)); bundlingRequestDocuments.addAll(getAllRemainingExpertReports(partyType, EvidenceUploadFiles.ANSWERS_FOR_EXPERTS, caseData, BundleFileNameList.REPLIES_FROM, allExpertsNames, allJointExpertsNames)); return ElementUtils.wrapElements(bundlingRequestDocuments); } + private List getAllRemainingExpertQuestions(PartyType partyType, + EvidenceUploadFiles questionsForExperts, CaseData caseData) { + List bundlingRequestDocuments = new ArrayList<>(); + List> listOfDocsOtherPartyQues = getExpertDocsByPartyAndDocType(partyType, + questionsForExperts, caseData); + Set allExpertFromOtherParty1 = getAllExpertFromOtherParty(partyType, EvidenceUploadFiles.EXPERT_REPORT, + caseData, true); + Set allExpertFromOtherParty2 = getAllExpertFromOtherParty(partyType, EvidenceUploadFiles.EXPERT_REPORT, + caseData, false); + Set allJointExpertsFromOtherParty1 = getAllExpertFromOtherParty(partyType, EvidenceUploadFiles.JOINT_STATEMENT, + caseData, true); + Set allJointExpertsFromOtherParty2 = getAllExpertFromOtherParty(partyType, EvidenceUploadFiles.JOINT_STATEMENT, + caseData, false); + Party otherParty1; + Party otherParty2; + if (partyType.equals(PartyType.CLAIMANT1) || partyType.equals(PartyType.CLAIMANT2)) { + otherParty1 = getPartyByPartyType(PartyType.DEFENDANT1, caseData); + otherParty2 = getPartyByPartyType(PartyType.DEFENDANT2, caseData); + + } else { + otherParty1 = getPartyByPartyType(PartyType.CLAIMANT1, caseData); + otherParty2 = getPartyByPartyType(PartyType.CLAIMANT2, caseData); + } + List> tempList = new ArrayList<>(); + listOfDocsOtherPartyQues.forEach(expertElement -> { + if (!((matchParty(expertElement.getValue().getExpertOptionOtherParty(), otherParty1) + && matchType(expertElement.getValue().getExpertOptionName(), allExpertFromOtherParty1, false)) + || (matchParty(expertElement.getValue().getExpertOptionOtherParty(), otherParty2) + && matchType(expertElement.getValue().getExpertOptionName(), allExpertFromOtherParty2, false)) + || (matchParty(expertElement.getValue().getExpertOptionOtherParty(), otherParty1) + && matchType(expertElement.getValue().getExpertOptionName(), allJointExpertsFromOtherParty1, false)) + || (matchParty(expertElement.getValue().getExpertOptionOtherParty(), otherParty2) + && matchType(expertElement.getValue().getExpertOptionName(), allJointExpertsFromOtherParty2, false)))) { + tempList.add(expertElement); + } + }); + bundlingRequestDocuments.addAll(covertExpertEvidenceTypeToBundleRequestDocs( + tempList, BundleFileNameList.QUESTIONS_TO.getDisplayName(), + EvidenceUploadFiles.QUESTIONS_FOR_EXPERTS.name())); + + return bundlingRequestDocuments; + } + + private Set getAllExpertFromOtherParty(PartyType partyType, EvidenceUploadFiles expertReport, + CaseData caseData, boolean isDefendant1) { + if (partyType.equals(PartyType.CLAIMANT1) || partyType.equals(PartyType.CLAIMANT2)) { + return getAllExpertsNames(isDefendant1 ? PartyType.DEFENDANT1 : PartyType.DEFENDANT2, + expertReport, caseData); + } else { + return getAllExpertsNames(isDefendant1 ? PartyType.CLAIMANT1 : PartyType.CLAIMANT2, + expertReport, caseData); + } + } + + private List getAllOtherPartyQuestions(PartyType partyType, + CaseData caseData, + Set allExpertsNames) { + List bundlingRequestDocuments = new ArrayList<>(); + List> questionsFromOtherPartyDocs = getAllDocsFromOtherParty(partyType, caseData, + EvidenceUploadFiles.QUESTIONS_FOR_EXPERTS + ); + if (!questionsFromOtherPartyDocs.isEmpty()) { + List> tempList = questionsFromOtherPartyDocs.stream().filter(expertElement -> matchType( + expertElement.getValue().getExpertOptionName(), allExpertsNames, false + )) + .filter(expertElement -> matchParty( + expertElement.getValue().getExpertOptionOtherParty(), + getPartyByPartyType(partyType, caseData) + )).collect(Collectors.toList()); + if (!tempList.isEmpty()) { + Map>> expertReportMap = groupExpertStatementsByName(tempList); + expertReportMap.forEach((expertName, expertEvidenceList) -> bundlingRequestDocuments.addAll(covertExpertEvidenceTypeToBundleRequestDocs( + expertEvidenceList, BundleFileNameList.QUESTIONS_TO.getDisplayName(), EvidenceUploadFiles.QUESTIONS_FOR_EXPERTS.name()))); + } + } + return bundlingRequestDocuments; + } + + private boolean matchParty(String expertOptionOtherParty, Party party) { + if (party != null && party.getPartyName() != null && expertOptionOtherParty.equalsIgnoreCase(party.getPartyName())) { + return true; + } + return party != null && party.isIndividual() && party.getIndividualFirstName() != null && expertOptionOtherParty.equalsIgnoreCase( + party.getIndividualFirstName()); + } + + private List> getAllDocsFromOtherParty(PartyType partyType, CaseData caseData, + EvidenceUploadFiles evidenceUploadFileType) { + List> list = new ArrayList<>(); + if (partyType.equals(PartyType.CLAIMANT1) || partyType.equals(PartyType.CLAIMANT2)) { + list.addAll(getExpertDocsByPartyAndDocType(PartyType.DEFENDANT1, + evidenceUploadFileType, caseData)); + list.addAll(getExpertDocsByPartyAndDocType(PartyType.DEFENDANT2, evidenceUploadFileType, caseData)); + } else { + list.addAll(getExpertDocsByPartyAndDocType(PartyType.CLAIMANT1, evidenceUploadFileType, caseData)); + list.addAll(getExpertDocsByPartyAndDocType(PartyType.CLAIMANT2, evidenceUploadFileType, caseData)); + } + return list; + } + private List getAllRemainingExpertReports(PartyType partyType, EvidenceUploadFiles evidenceUploadFiles, CaseData caseData, - BundleFileNameList bundleFileNameList, List allExpertsNames, List allJointExpertsNames) { + BundleFileNameList bundleFileNameList, Set allExpertsNames, Set allJointExpertsNames) { List bundlingRequestDocuments = new ArrayList<>(); Map>> expertReportMap = groupExpertStatementsByName(getExpertDocsByPartyAndDocType(partyType, evidenceUploadFiles, caseData)); @@ -203,20 +335,20 @@ private List getAllRemainingExpertReports(PartyType par return bundlingRequestDocuments; } - private List getAllExpertsNames(PartyType partyType, EvidenceUploadFiles evidenceUploadFileType, + private Set getAllExpertsNames(PartyType partyType, EvidenceUploadFiles evidenceUploadFileType, CaseData caseData) { - List> expertsList = getExpertDocsByPartyAndDocType(partyType, evidenceUploadFileType, caseData); + List> expertsList = getExpertDocsByPartyAndDocType(partyType, + evidenceUploadFileType, caseData); if (expertsList != null) { - return expertsList.stream().map(expertElement -> expertElement.getValue().getExpertOptionName()) - .collect(Collectors.toList()); - } else { - return Collections.emptyList(); + return expertsList.stream().map(expertElement -> expertElement.getValue().getExpertOptionName().trim().toLowerCase()) + .collect(Collectors.toSet()); } + return Collections.emptySet(); } private List getAllExpertReports(PartyType partyType, EvidenceUploadFiles evidenceUploadFiles, CaseData caseData, BundleFileNameList bundleFileNameList, - List allExpertsNames) { + Set allExpertsNames) { List bundlingRequestDocuments = new ArrayList<>(); Map>> expertReportMap = groupExpertStatementsByName(getExpertDocsByPartyAndDocType(partyType, evidenceUploadFiles, caseData)); @@ -236,11 +368,10 @@ private List getAllExpertReports(PartyType partyType, E private Map>> groupExpertStatementsByName( List> documentExpertReport) { - Map>> expertStatementMap = new HashMap>>(); + Map>> expertStatementMap = new TreeMap<>(); if (documentExpertReport != null) { expertStatementMap = documentExpertReport.stream().collect(Collectors - .groupingBy(uploadEvidenceWitnessElement -> uploadEvidenceWitnessElement + .groupingBy(uploadEvidenceExpertElement -> uploadEvidenceExpertElement .getValue().getExpertOptionName().trim().toLowerCase())); } return expertStatementMap; @@ -261,6 +392,10 @@ private List> mapWitnessStatements(CaseData cas bundlingRequestDocuments.addAll(covertWitnessEvidenceToBundleRequestDocs(getWitnessDocsByPartyAndDocType(partyType, EvidenceUploadFiles.WITNESS_SUMMARY, caseData), BundleFileNameList.WITNESS_SUMMARY.getDisplayName(), EvidenceUploadFiles.WITNESS_SUMMARY.name(), partyType, false)); + bundlingRequestDocuments.addAll(covertEvidenceUploadTypeToBundleRequestDocs(getEvidenceUploadDocsByPartyAndDocType(partyType, + EvidenceUploadFiles.DOCUMENTS_REFERRED, caseData), + BundleFileNameList.DOC_REFERRED_TO.getDisplayName(), + EvidenceUploadFiles.DOCUMENTS_REFERRED.name(), partyType)); bundlingRequestDocuments.addAll(covertWitnessEvidenceToBundleRequestDocs(getWitnessDocsByPartyAndDocType(partyType, EvidenceUploadFiles.NOTICE_OF_INTENTION, caseData), BundleFileNameList.HEARSAY_NOTICE.getDisplayName(), EvidenceUploadFiles.NOTICE_OF_INTENTION.name(), partyType, false)); @@ -346,7 +481,7 @@ private void sortEvidenceUploadByDate(List> private void sortExpertListByDate(List> expertEvidence, boolean sortByCreatedDate) { expertEvidence.sort(Comparator.comparing( - uploadEvidenceWitnessElement -> uploadEvidenceWitnessElement.getValue().getExpertOptionUploadDate(), + uploadEvidenceExpertElement -> uploadEvidenceExpertElement.getValue().getExpertOptionUploadDate(), Comparator.reverseOrder() )); } @@ -396,20 +531,20 @@ private List> mapOrdersDocument(CaseData caseDa bundlingRequestDocuments.addAll(mapSystemGeneratedCaseDocument(caseData.getDirectionOrderDocStaff(), BundleFileNameList.ORDER.getDisplayName())); } - if (caseData.getFinalOrderDocument() != null) { - bundlingRequestDocuments.add(buildBundlingRequestDoc(caseData.getFinalOrderDocument().getDocumentFileName(), caseData.getFinalOrderDocument(), "")); - } + return ElementUtils.wrapElements(bundlingRequestDocuments); } private List> mapStatementOfcaseDocs(CaseData caseData) { List bundlingRequestDocuments = new ArrayList<>(); - log.info("System generated docs : " + caseData.getSystemGeneratedCaseDocuments()); bundlingRequestDocuments.addAll(mapSystemGeneratedCaseDocument(caseData.getSystemGeneratedCaseDocuments().stream() .filter(caseDocumentElement -> caseDocumentElement.getValue().getDocumentType() - .equals(DocumentType.SEALED_CLAIM)).collect( - Collectors.toList()), + .equals(DocumentType.SEALED_CLAIM) + && null != caseDocumentElement.getValue().getDocumentLink().getCategoryID() + && caseDocumentElement.getValue().getDocumentLink().getCategoryID().equals("detailsOfClaim")) + .collect(Collectors.toList()), BundleFileNameList.CLAIM_FORM.getDisplayName())); + bundlingRequestDocuments.addAll(mapParticularsOfClaimDocs(caseData)); List> clAndDfDocList = caseData.getDefendantResponseDocuments(); clAndDfDocList.addAll(caseData.getClaimantResponseDocuments()); List> sortedDefendantDefenceAndClaimantReply = @@ -529,11 +664,11 @@ public List> filterDocumentaryEvidenceForTri )).collect(Collectors.toList()); } - private boolean matchType(String typeOfDocument, List displayNames, boolean doesNotMatchType) { + private boolean matchType(String name, Collection displayNames, boolean doesNotMatchType) { if (doesNotMatchType) { - return displayNames.stream().noneMatch(s -> s.equalsIgnoreCase(typeOfDocument.trim())); + return displayNames.stream().noneMatch(s -> s.equalsIgnoreCase(name.trim())); } else { - return displayNames.stream().anyMatch(s -> s.equalsIgnoreCase(typeOfDocument.trim())); + return displayNames.stream().anyMatch(s -> s.equalsIgnoreCase(name.trim())); } } @@ -578,14 +713,18 @@ private List covertEvidenceUploadTypeToBundleRequestDoc PartyType party) { List bundlingRequestDocuments = new ArrayList<>(); if (evidenceUploadDocList != null) { - if (documentType.equals(EvidenceUploadFiles.CASE_SUMMARY.name()) || documentType.equals(EvidenceUploadFiles.SKELETON_ARGUMENT.name())) { + if (documentType.equals(EvidenceUploadFiles.CASE_SUMMARY.name()) + || documentType.equals(EvidenceUploadFiles.SKELETON_ARGUMENT.name()) + || documentType.equals(EvidenceUploadFiles.COSTS.name())) { sortEvidenceUploadByDate(evidenceUploadDocList, true); } else { sortEvidenceUploadByDate(evidenceUploadDocList, false); } evidenceUploadDocList.forEach(uploadEvidenceDocumentTypeElement -> { - String docName = getFileNameBaseOnType(fileNamePrefix, uploadEvidenceDocumentTypeElement, documentType, party); + String docName = getFileNameBaseOnType(fileNamePrefix, uploadEvidenceDocumentTypeElement, + documentType, party, + String.valueOf(evidenceUploadDocList.indexOf(uploadEvidenceDocumentTypeElement) + 1)); bundlingRequestDocuments.add(buildBundlingRequestDoc(docName, uploadEvidenceDocumentTypeElement.getValue().getDocumentUpload(), documentType)); }); } @@ -593,7 +732,7 @@ private List covertEvidenceUploadTypeToBundleRequestDoc } private String getFileNameBaseOnType(String fileNamePrefix, Element uploadEvidence, - String documentType, PartyType party) { + String documentType, PartyType party, String index) { if (fileNamePrefix.equals(DOC_FILE_NAME)) { return uploadEvidence.getValue().getDocumentUpload().getDocumentFileName() .substring(0, uploadEvidence.getValue().getDocumentUpload().getDocumentFileName().lastIndexOf(".")); @@ -610,10 +749,19 @@ private String getFileNameBaseOnType(String fileNamePrefix, Element 30) { + return true; + } + return false; + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/Bundle.java b/src/main/java/uk/gov/hmcts/reform/civil/model/Bundle.java index 32e17980b6c..7aff2555707 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/Bundle.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/Bundle.java @@ -29,7 +29,7 @@ public class Bundle implements MappableObject { private YesOrNo hasCoversheets; private YesOrNo hasTableOfContents; - private String filename; + private String fileName; //Added for case progression trial bundling private Optional createdOn; @@ -72,7 +72,7 @@ public Bundle( Optional stitchedDocument, YesOrNo hasCoversheets, YesOrNo hasTableOfContents, - String filename + String fileName ) { this.id = id; this.title = title; @@ -83,7 +83,7 @@ public Bundle( this.stitchedDocument = stitchedDocument; this.hasCoversheets = hasCoversheets; this.hasTableOfContents = hasTableOfContents; - this.filename = filename; + this.fileName = fileName; } @@ -123,8 +123,8 @@ public YesOrNo getHasTableOfContents() { return hasTableOfContents; } - public String getFilename() { - return filename; + public String getFileName() { + return fileName; } public Optional getCreatedOn() { diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/CCJPaymentDetails.java b/src/main/java/uk/gov/hmcts/reform/civil/model/CCJPaymentDetails.java index 529d66ec762..3820e1befd6 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/CCJPaymentDetails.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/CCJPaymentDetails.java @@ -33,4 +33,7 @@ public class CCJPaymentDetails { private BigDecimal ccjJudgmentFixedCostAmount; private YesOrNo ccjJudgmentFixedCostOption; private String ccjJudgmentStatement; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private BigDecimal ccjJudgmentLipInterest; + } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/CaseData.java b/src/main/java/uk/gov/hmcts/reform/civil/model/CaseData.java index 99734b0293c..953b02321d3 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/CaseData.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/CaseData.java @@ -40,6 +40,7 @@ import uk.gov.hmcts.reform.civil.model.breathing.BreathingSpaceInfo; import uk.gov.hmcts.reform.civil.model.caseprogression.FreeFormOrderValues; import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; +import uk.gov.hmcts.reform.civil.model.citizenui.HelpWithFees; import uk.gov.hmcts.reform.civil.model.citizenui.RespondentLiPResponse; import uk.gov.hmcts.reform.civil.model.citizenui.ManageDocument; import uk.gov.hmcts.reform.civil.model.common.DynamicList; @@ -81,10 +82,16 @@ import uk.gov.hmcts.reform.civil.model.interestcalc.InterestClaimOptions; import uk.gov.hmcts.reform.civil.model.interestcalc.InterestClaimUntilType; import uk.gov.hmcts.reform.civil.model.interestcalc.SameRateInterestSelection; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentInstalmentDetails; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentRecordedReason; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentStatusDetails; +import uk.gov.hmcts.reform.civil.model.judgmentonline.PaymentPlanSelection; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentPaidInFull; import uk.gov.hmcts.reform.civil.model.sdo.DisposalHearingFinalDisposalHearingTimeDJ; import uk.gov.hmcts.reform.civil.model.sdo.DisposalHearingHearingNotesDJ; import uk.gov.hmcts.reform.civil.model.sdo.DisposalHearingOrderMadeWithoutHearingDJ; import uk.gov.hmcts.reform.civil.model.sdo.OtherDetails; +import uk.gov.hmcts.reform.civil.model.transferonlinecase.TransferCaseDetails; import uk.gov.hmcts.reform.civil.service.DeadlinesCalculator; import uk.gov.hmcts.reform.civil.utils.MonetaryConversions; @@ -101,6 +108,7 @@ import java.util.stream.Stream; import static java.util.Objects.nonNull; +import static java.util.Optional.ofNullable; import static uk.gov.hmcts.reform.civil.enums.AllocatedTrack.FAST_CLAIM; import static uk.gov.hmcts.reform.civil.enums.AllocatedTrack.SMALL_CLAIM; import static uk.gov.hmcts.reform.civil.enums.BusinessProcessStatus.FINISHED; @@ -520,6 +528,7 @@ public boolean hasNoOngoingBusinessProcess() { private List> trialHearingAddNewDirectionsDJ; private HearingMethodTelephoneHearingDJ disposalHearingMethodTelephoneHearingDJ; private HearingMethodVideoConferenceDJ disposalHearingMethodVideoConferenceHearingDJ; + private String featureToggleWA; private String caseManagementOrderSelection; private Document orderSDODocumentDJ; @@ -563,9 +572,12 @@ public boolean hasNoOngoingBusinessProcess() { //case progression private final List> documentAndName; + private final List> documentAndNameToAdd; private final List> documentAndNote; + private final List> documentAndNoteToAdd; private final CaseNoteType caseNoteType; - private final String caseNoteTypeNoteTA; + private final String caseNoteTA; + private final List> caseNotesTA; private final LocalDateTime noteAdditionDateTime; private final String caseTypeFlag; private final String witnessStatementFlag; @@ -595,8 +607,10 @@ public boolean hasNoOngoingBusinessProcess() { private final FreeFormOrderValues orderOnCourtInitiative; private final FreeFormOrderValues orderWithoutNotice; private final OrderOnCourtsList orderOnCourtsList; + private final String freeFormHearingNotes; + + private CaseDocument finalOrderDocument; - private Document finalOrderDocument; @Builder.Default private final List> finalOrderDocumentCollection = new ArrayList<>(); @@ -605,6 +619,22 @@ public boolean hasNoOngoingBusinessProcess() { private final String sdtRequestIdFromSdt; private final List> sdtRequestId; + //Judgments Online + private JudgmentRecordedReason joJudgmentRecordReason; + private JudgmentStatusDetails joJudgmentStatusDetails; + private LocalDate joOrderMadeDate; + private String joAmountOrdered; + private String joAmountCostOrdered; + private YesOrNo joIsRegisteredWithRTL; + private PaymentPlanSelection joPaymentPlanSelection; + private JudgmentInstalmentDetails joJudgmentInstalmentDetails; + private LocalDate joPaymentToBeMadeByDate; + private YesOrNo joIsLiveJudgmentExists; + private LocalDate joSetAsideDate; + private JudgmentPaidInFull joJudgmentPaidInFull; + + private final TransferCaseDetails transferCaseDetails; + /** * There are several fields that can hold the I2P of applicant1 depending * on multiparty scenario, which complicates all conditions depending on it. @@ -823,24 +853,36 @@ public boolean isRespondent1NotRepresented() { return NO.equals(getRespondent1Represented()); } + @JsonIgnore + public boolean isApplicant1NotRepresented() { + return NO.equals(getApplicant1Represented()); + } + @JsonIgnore public boolean isLRvLipOneVOne() { return isRespondent1NotRepresented() + && !isApplicant1NotRepresented() + && isOneVOne(this); + } + + @JsonIgnore + public boolean isLipvLipOneVOne() { + return isRespondent1NotRepresented() + && isApplicant1NotRepresented() && isOneVOne(this); } @JsonIgnore public boolean isJudgementDateNotPermitted() { - return nonNull(getRespondent1ResponseDate()) - && getRespondent1ResponseDate() - .toLocalDate().plusDays(5).atTime(DeadlinesCalculator.END_OF_BUSINESS_DAY).isAfter(LocalDateTime.now()); + return nonNull(getRespondToClaimAdmitPartLRspec().getWhenWillThisAmountBePaid()) + && getRespondToClaimAdmitPartLRspec().getWhenWillThisAmountBePaid() + .atTime(DeadlinesCalculator.END_OF_BUSINESS_DAY).isAfter(LocalDateTime.now()); } @JsonIgnore - public String setUpJudgementFormattedPermittedDate() { + public String setUpJudgementFormattedPermittedDate(LocalDate extendedRespondent1ResponseDate) { if (isJudgementDateNotPermitted()) { - return formatLocalDateTime(getRespondent1ResponseDate() - .toLocalDate().plusDays(5).atTime(DeadlinesCalculator.END_OF_BUSINESS_DAY), DATE_TIME_AT); + return formatLocalDateTime(extendedRespondent1ResponseDate.atTime(DeadlinesCalculator.END_OF_BUSINESS_DAY), DATE_TIME_AT); } return null; } @@ -982,13 +1024,19 @@ public List> getRecurringIncomeForRespondent1() { @JsonIgnore public List> getRecurringExpensesForRespondent1() { if (isFullAdmitClaimSpec()) { - return Optional.ofNullable(getRespondent1DQ()).map(Respondent1DQ::getRespondent1DQRecurringExpensesFA).orElse( - null); + return Optional.ofNullable(getRespondent1DQ()).map(Respondent1DQ::getRespondent1DQRecurringExpensesFA) + .orElse( + null); } return Optional.ofNullable(getRespondent1DQ()).map(Respondent1DQ::getRespondent1DQRecurringExpenses).orElse( null); } + @JsonIgnore + public List> getManageDocumentsList() { + return Optional.ofNullable(getManageDocuments()).orElse(new ArrayList<>()); + } + @JsonIgnore public boolean getApplicant1ResponseDeadlinePassed() { return getApplicant1ResponseDeadline() != null @@ -1000,4 +1048,52 @@ && getApplicant1ResponseDeadline().isBefore(LocalDateTime.now()) public String getApplicant1Email() { return getApplicant1().getPartyEmail() != null ? getApplicant1().getPartyEmail() : getClaimantUserDetails().getEmail(); } + + @JsonIgnore + public String getHelpWithFeesReferenceNumber() { + return Optional.ofNullable(getCaseDataLiP()) + .map(CaseDataLiP::getHelpWithFees) + .map(HelpWithFees::getHelpWithFeesReferenceNumber).orElse(null); + } + + @JsonIgnore + public Address getRespondent1CorrespondenceAddress() { + return Optional.ofNullable(getCaseDataLiP()) + .map(CaseDataLiP::getRespondent1LiPResponse) + .map(RespondentLiPResponse::getRespondent1LiPCorrespondenceAddress) + .orElse(null); + } + + @JsonIgnore + public String getCurrentCamundaBusinessProcessName() { + return ofNullable(getBusinessProcess()) + .map(BusinessProcess::getCamundaEvent) + .orElse(null); + } + + @JsonIgnore + public boolean isTranslatedDocumentUploaded() { + if (getSystemGeneratedCaseDocuments() != null) { + return getSystemGeneratedCaseDocuments().stream() + .filter(systemGeneratedCaseDocument -> systemGeneratedCaseDocument.getValue() + .getDocumentType().equals(DocumentType.DEFENCE_TRANSLATED_DOCUMENT)).findAny().isPresent(); + } + return false; + } + + @JsonIgnore + public boolean isRespondentSolicitorRegistered() { + return YesOrNo.YES.equals(getRespondent1OrgRegistered()); + } + + @JsonIgnore + public String getRespondent1Email() { + if (isRespondent1NotRepresented()) { + return getRespondent1().getPartyEmail(); + } + if (isRespondentSolicitorRegistered()) { + return getRespondentSolicitor1EmailAddress(); + } + return null; + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/CaseDataParent.java b/src/main/java/uk/gov/hmcts/reform/civil/model/CaseDataParent.java index 6db3eb1fbbe..5db7728550f 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/CaseDataParent.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/CaseDataParent.java @@ -31,6 +31,7 @@ import uk.gov.hmcts.reform.civil.enums.dj.HearingMethodVideoConferenceDJ; import uk.gov.hmcts.reform.civil.enums.dq.Language; import uk.gov.hmcts.reform.civil.enums.finalorders.AssistedCostTypesList; +import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersJudgePapers; import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrderToggle; import uk.gov.hmcts.reform.civil.enums.finalorders.HearingLengthFinalOrderList; import uk.gov.hmcts.reform.civil.enums.finalorders.OrderMadeOnTypes; @@ -140,11 +141,14 @@ import uk.gov.hmcts.reform.civil.model.sdo.TrialHearingHearingNotesDJ; import uk.gov.hmcts.reform.civil.model.sdo.TrialHearingTimeDJ; import uk.gov.hmcts.reform.civil.model.sdo.TrialOrderMadeWithoutHearingDJ; +import uk.gov.hmcts.reform.civil.model.transferonlinecase.NotSuitableSdoOptions; +import uk.gov.hmcts.reform.civil.model.transferonlinecase.TocTransferCaseReason; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; +import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; @@ -307,6 +311,8 @@ public class CaseDataParent implements MappableObject { private CaseDocument sdoOrderDocument; + private final YesOrNo eaCourtLocation; + // sdo ui flags private final YesOrNo setSmallClaimsFlag; private final YesOrNo setFastTrackFlag; @@ -437,6 +443,7 @@ public boolean isApplicantNotRepresented() { private final CertificateOfService cosNotifyClaimDefendant1; private final CertificateOfService cosNotifyClaimDefendant2; + private final String notificationText; private final List disclosureSelectionEvidence; private final List disclosureSelectionEvidenceRes; private final List witnessSelectionEvidence; @@ -527,9 +534,13 @@ public boolean isApplicantNotRepresented() { private final List> applicantWitnesses; private final List> respondent1Witnesses; private final List> respondent2Witnesses; - private final List> applicantSolOrgIndividuals; - private final List> respondent1SolOrgIndividuals; - private final List> applicant1SolOrgIndividuals; + private final List> applicant1LRIndividuals; + private final List> respondent1LRIndividuals; + private final List> respondent2LRIndividuals; + private final List> applicant1OrgIndividuals; + private final List> applicant2OrgIndividuals; + private final List> respondent1OrgIndividuals; + private final List> respondent2OrgIndividuals; private List disposalHearingDisclosureOfDocumentsDJToggle; private List disposalHearingWitnessOfFactDJToggle; @@ -615,6 +626,7 @@ public boolean isApplicantNotRepresented() { private YesOrNo finalOrderMadeSelection; private OrderMade finalOrderDateHeardComplex; + private List finalOrderJudgePapers; private List finalOrderJudgeHeardFrom; private FinalOrderRepresentation finalOrderRepresentation; private List finalOrderRecitals; @@ -698,12 +710,36 @@ public boolean isApplicantNotRepresented() { private List> applicant2UnavailableDatesForTab; private List> respondent1UnavailableDatesForTab; private List> respondent2UnavailableDatesForTab; + private String pcqId; + + // TOC + private String reasonForTransfer; + private DynamicList transferCourtLocationList; + private NotSuitableSdoOptions notSuitableSdoOptions; + private TocTransferCaseReason tocTransferCaseReason; @JsonUnwrapped private final UpdateDetailsForm updateDetailsForm; private FastTrackAllocation fastTrackAllocation; + /** + * used to temporary hold addresses. + */ + private final Address tempCorrespondenceAddress1; + /** + * used with tempCorrespondenceAddress1. + */ + private final YesOrNo tempCorrespondenceAddress1Required; + /** + * used to temporary hold addresses. + */ + private final Address tempCorrespondenceAddress2; + /** + * used with tempCorrespondenceAddress2. + */ + private final YesOrNo tempCorrespondenceAddress2Required; + @JsonIgnore public boolean isResponseAcceptedByClaimant() { return applicant1AcceptAdmitAmountPaidSpec == YesOrNo.YES @@ -749,8 +785,10 @@ public boolean hasClaimantAgreedToFreeMediation() { } @JsonIgnore - public Optional getTranslatedDocument() { - return Optional.ofNullable(getCaseDataLiP()).map(CaseDataLiP::getTranslatedDocument); + public List> getTranslatedDocuments() { + return Optional.ofNullable(getCaseDataLiP()) + .map(CaseDataLiP::getTranslatedDocuments) + .orElse(Collections.emptyList()); } @JsonIgnore @@ -759,9 +797,4 @@ public boolean hasClaimantNotAgreedToFreeMediation() { .map(CaseDataLiP::getApplicant1ClaimMediationSpecRequiredLip) .filter(ClaimantMediationLip::hasClaimantNotAgreedToFreeMediation).isPresent(); } - - @JsonIgnore - public boolean isTranslatedDocumentUploaded() { - return getCaseDataLiP() != null && getCaseDataLiP().getTranslatedDocument() != null; - } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/CourtLocation.java b/src/main/java/uk/gov/hmcts/reform/civil/model/CourtLocation.java index ba9d45f53d9..1037a0b4e5a 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/CourtLocation.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/CourtLocation.java @@ -14,13 +14,16 @@ public class CourtLocation { private final String applicantPreferredCourt; private final DynamicList applicantPreferredCourtLocationList; private final CaseLocationCivil caseLocation; + private final String reasonForHearingAtSpecificCourt; @JsonCreator CourtLocation(@JsonProperty("applicantPreferredCourt") String applicantPreferredCourt, @JsonProperty("applicantPreferredCourtLocationList") DynamicList applicantPreferredCourtLocationList, - @JsonProperty("caseLocation") CaseLocationCivil caseLocation) { + @JsonProperty("caseLocation") CaseLocationCivil caseLocation, + @JsonProperty("reasonForHearingAtSpecificCourt") String reasonForHearingAtSpecificCourt) { this.applicantPreferredCourt = applicantPreferredCourt; this.applicantPreferredCourtLocationList = applicantPreferredCourtLocationList; this.caseLocation = caseLocation; + this.reasonForHearingAtSpecificCourt = reasonForHearingAtSpecificCourt; } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/PartnerAndDependentsLRspec.java b/src/main/java/uk/gov/hmcts/reform/civil/model/PartnerAndDependentsLRspec.java index 3a2f81843ce..896d2b7009f 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/PartnerAndDependentsLRspec.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/PartnerAndDependentsLRspec.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.reform.civil.model; +import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Builder; import lombok.Data; import uk.gov.hmcts.reform.civil.enums.YesOrNo; @@ -16,4 +17,9 @@ public class PartnerAndDependentsLRspec { private final YesOrNo supportedAnyoneFinancialRequired; private final String supportPeopleNumber; private final String supportPeopleDetails; + + @JsonIgnore + public boolean hasPartner() { + return YesOrNo.YES == liveWithPartnerRequired; + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/Party.java b/src/main/java/uk/gov/hmcts/reform/civil/model/Party.java index 7b1bb165d06..32382122fad 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/Party.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/Party.java @@ -14,6 +14,7 @@ import javax.validation.constraints.PastOrPresent; import java.time.LocalDate; import java.util.List; +import java.util.Optional; import static uk.gov.hmcts.reform.civil.model.Party.Type.INDIVIDUAL; import static uk.gov.hmcts.reform.civil.model.Party.Type.SOLE_TRADER; @@ -101,4 +102,14 @@ public boolean isCompany() { public boolean isOrganisation() { return ORGANISATION.equals(getType()); } + + @JsonIgnore + public boolean isCompanyOROrganisation() { + return this.isCompany() || this.isOrganisation(); + } + + @JsonIgnore + public LocalDate getDateOfBirth() { + return Optional.ofNullable(individualDateOfBirth).orElse(soleTraderDateOfBirth); + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/RespondToClaim.java b/src/main/java/uk/gov/hmcts/reform/civil/model/RespondToClaim.java index bed5151df2b..deaecdf25c5 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/RespondToClaim.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/RespondToClaim.java @@ -1,6 +1,7 @@ package uk.gov.hmcts.reform.civil.model; import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Builder; import lombok.Data; import uk.gov.hmcts.reform.civil.validation.groups.PaymentDateGroup; @@ -23,4 +24,11 @@ public class RespondToClaim { private final LocalDate whenWasThisAmountPaid; private final PaymentMethod howWasThisAmountPaid; private final String howWasThisAmountPaidOther; + + @JsonIgnore + public String getExplanationOnHowTheAmountWasPaid() { + return getHowWasThisAmountPaid() == PaymentMethod.OTHER + ? getHowWasThisAmountPaidOther() + : getHowWasThisAmountPaid().getHumanFriendly(); + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/UpdateDetailsForm.java b/src/main/java/uk/gov/hmcts/reform/civil/model/UpdateDetailsForm.java index 82f48651bb7..33b489f1fec 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/UpdateDetailsForm.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/UpdateDetailsForm.java @@ -1,6 +1,5 @@ package uk.gov.hmcts.reform.civil.model; -import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,17 +10,18 @@ import java.util.List; @Data -@Builder +@Builder(toBuilder = true) @NoArgsConstructor @AllArgsConstructor public class UpdateDetailsForm { - @JsonProperty("partyChosen") private DynamicList partyChosen; - - @JsonProperty("additionalUnavailableDates") - private List> additionalUnavailableDates; - - @JsonProperty("hidePartyChoice") + private String partyChosenId; + private String partyChosenType; private YesOrNo hidePartyChoice; + private List> additionalUnavailableDates; + private List> updateExpertsDetailsForm; + private List> updateWitnessesDetailsForm; + private YesOrNo manageContactDetailsEventUsed; } + diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/UpdatePartyDetailsForm.java b/src/main/java/uk/gov/hmcts/reform/civil/model/UpdatePartyDetailsForm.java new file mode 100644 index 00000000000..5955d276a92 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/UpdatePartyDetailsForm.java @@ -0,0 +1,16 @@ +package uk.gov.hmcts.reform.civil.model; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder(toBuilder = true) +public class UpdatePartyDetailsForm { + + private String firstName; + private String lastName; + private String phoneNumber; + private String emailAddress; + private String partyId; + private String fieldOfExpertise; +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/account/AccountSimple.java b/src/main/java/uk/gov/hmcts/reform/civil/model/account/AccountSimple.java index fc57ab9c138..8c2908f3cfe 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/account/AccountSimple.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/account/AccountSimple.java @@ -1,18 +1,26 @@ package uk.gov.hmcts.reform.civil.model.account; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.AllArgsConstructor; import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.SuperBuilder; import uk.gov.hmcts.reform.civil.enums.YesOrNo; import java.math.BigDecimal; import javax.validation.constraints.NotNull; @Data +@NoArgsConstructor +@AllArgsConstructor +@SuperBuilder public class AccountSimple { /** * balance in pounds. */ @NotNull + @JsonFormat(shape = JsonFormat.Shape.STRING) private BigDecimal balance; /** * true if joint account, false if not, null if unknown. diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/allowance/DisabilityAllowance.java b/src/main/java/uk/gov/hmcts/reform/civil/model/allowance/DisabilityAllowance.java new file mode 100644 index 00000000000..a3222ed60a4 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/allowance/DisabilityAllowance.java @@ -0,0 +1,41 @@ +package uk.gov.hmcts.reform.civil.model.allowance; + +import lombok.Getter; + +import java.util.Arrays; +import java.util.function.Predicate; + +@Getter +public enum DisabilityAllowance { + + SINGLE(139.75, DisabilityParam::disabledSingle), + COUPLE(199.12, DisabilityParam::disabledCouple), + SEVERE_DISABILITY_SINGLE( + 268.01, + DisabilityParam::disabledSeverelySingle + ), + SEVERE_DISABILITY_COUPLE( + 536.03, + DisabilityParam::disabledSeverelyCouple + ), + DISABLED_DEPENDANT(260.26, DisabilityParam::disabledDependant), + CARER(149.93, DisabilityParam::isCarer), + NO_DISABILITY(0.0, DisabilityParam::notDisabled); + + private double allowance; + private final Predicate disabilityMatcher; + + DisabilityAllowance(double allowance, Predicate disabilityMatcher) { + this.allowance = allowance; + this.disabilityMatcher = disabilityMatcher; + } + + public static double getDisabilityAllowance(DisabilityParam disabilityParam) { + if (disabilityParam == null) { + return NO_DISABILITY.getAllowance(); + } + return Arrays.stream(DisabilityAllowance.values()) + .filter(disabilityAllowance -> disabilityAllowance.disabilityMatcher.test(disabilityParam)) + .mapToDouble(DisabilityAllowance::getAllowance).sum(); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/allowance/DisabilityParam.java b/src/main/java/uk/gov/hmcts/reform/civil/model/allowance/DisabilityParam.java new file mode 100644 index 00000000000..af0873ad0f6 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/allowance/DisabilityParam.java @@ -0,0 +1,37 @@ +package uk.gov.hmcts.reform.civil.model.allowance; + +import lombok.Builder; + +@Builder +public record DisabilityParam(boolean disabled, boolean hasPartner, boolean severelyDisabled, boolean dependant, + boolean carer) { + + public boolean disabledSingle() { + return disabled && !hasPartner && !severelyDisabled; + } + + public boolean disabledCouple() { + return disabled && hasPartner && !severelyDisabled; + } + + public boolean disabledSeverelySingle() { + return !hasPartner && severelyDisabled; + } + + public boolean disabledSeverelyCouple() { + return hasPartner && severelyDisabled; + } + + public boolean disabledDependant() { + return dependant; + } + + public boolean notDisabled() { + return !disabled && !severelyDisabled && !dependant && !carer; + } + + public boolean isCarer() { + return carer; + } + +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/allowance/PensionerAllowance.java b/src/main/java/uk/gov/hmcts/reform/civil/model/allowance/PensionerAllowance.java new file mode 100644 index 00000000000..2c1863ea11e --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/allowance/PensionerAllowance.java @@ -0,0 +1,26 @@ +package uk.gov.hmcts.reform.civil.model.allowance; + +import lombok.Getter; + +@Getter +public enum PensionerAllowance { + + SINGLE(335.83), + COUPLE(502.66); + + private double allowance; + + PensionerAllowance(double allowance) { + this.allowance = allowance; + } + + public static double getPensionerAllowance(boolean pensioner, boolean partnerPensioner) { + if ((pensioner && !partnerPensioner) || (!pensioner && partnerPensioner)) { + return SINGLE.allowance; + } + if (pensioner) { + return COUPLE.allowance; + } + return 0.0; + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/allowance/PersonalAllowance.java b/src/main/java/uk/gov/hmcts/reform/civil/model/allowance/PersonalAllowance.java new file mode 100644 index 00000000000..cfb335811d1 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/allowance/PersonalAllowance.java @@ -0,0 +1,41 @@ +package uk.gov.hmcts.reform.civil.model.allowance; + +import lombok.Getter; + +@Getter +public enum PersonalAllowance { + + SINGLE_UNDER_25(250.90), + SINGLE_OVER_25(316.76), + COUPLES_UNDER_18(379.16), + COUPLES_UNDER_18_UNDER_25(250.90), + COUPLES_UNDER_18_OVER_25(316.76), + COUPLES_OVER_18(497.68); + + private double allowance; + + PersonalAllowance(double allowance) { + this.allowance = allowance; + } + + public static PersonalAllowance getPersonalAllowance(int age, boolean hasPartner, boolean partnerOver18) { + boolean under25 = 25 > age; + boolean over25 = 25 <= age; + if (hasPartner && over25 && partnerOver18) { + return COUPLES_OVER_18; + } + if (hasPartner && over25 && !partnerOver18) { + return COUPLES_UNDER_18_OVER_25; + } + if (hasPartner && under25 && !partnerOver18) { + return COUPLES_UNDER_18_UNDER_25; + } + if (!hasPartner && under25) { + return SINGLE_UNDER_25; + } + if (!hasPartner && over25) { + return SINGLE_OVER_25; + } + return COUPLES_UNDER_18; + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/bundle/BundlingCaseData.java b/src/main/java/uk/gov/hmcts/reform/civil/model/bundle/BundlingCaseData.java index f48b855eb55..f37439ded9c 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/bundle/BundlingCaseData.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/bundle/BundlingCaseData.java @@ -22,6 +22,8 @@ public class BundlingCaseData { private final List> trialDocuments; @JsonProperty("statementsOfCaseDocuments") private final List> statementsOfCaseDocuments; + @JsonProperty("particularsOfClaim") + private final List> particularsOfClaim; @JsonProperty("ordersDocuments") private final List> ordersDocuments; @JsonProperty("claimant1WitnessStatements") @@ -60,8 +62,6 @@ public class BundlingCaseData { private final List> defendant2CostsBudgets; @JsonProperty("systemGeneratedCaseDocuments") private final List> systemGeneratedCaseDocuments; - @JsonProperty("courtLocation") - private final String courtLocation; @JsonProperty("applicant1") private final Party applicant1; @JsonProperty("hasApplicant2") diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/caseprogression/UploadEvidenceDocumentType.java b/src/main/java/uk/gov/hmcts/reform/civil/model/caseprogression/UploadEvidenceDocumentType.java index 35391068829..3d02a3d2e44 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/caseprogression/UploadEvidenceDocumentType.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/caseprogression/UploadEvidenceDocumentType.java @@ -8,6 +8,7 @@ import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.ZoneId; @Data @Builder(toBuilder = true) @@ -19,6 +20,6 @@ public class UploadEvidenceDocumentType { private LocalDate documentIssuedDate; private Document documentUpload; @Builder.Default - private LocalDateTime createdDatetime = LocalDateTime.now(); + private LocalDateTime createdDatetime = LocalDateTime.now(ZoneId.of("Europe/London")); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/caseprogression/UploadEvidenceExpert.java b/src/main/java/uk/gov/hmcts/reform/civil/model/caseprogression/UploadEvidenceExpert.java index b079f50e1e7..ead048028b5 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/caseprogression/UploadEvidenceExpert.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/caseprogression/UploadEvidenceExpert.java @@ -8,6 +8,7 @@ import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.ZoneId; @Data @Builder(toBuilder = true) @@ -24,5 +25,5 @@ public class UploadEvidenceExpert { private LocalDate expertOptionUploadDate; private Document expertDocument; @Builder.Default - private LocalDateTime createdDatetime = LocalDateTime.now(); + private LocalDateTime createdDatetime = LocalDateTime.now(ZoneId.of("Europe/London")); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/caseprogression/UploadEvidenceWitness.java b/src/main/java/uk/gov/hmcts/reform/civil/model/caseprogression/UploadEvidenceWitness.java index a8e0b54df4d..fcbc4bd4f51 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/caseprogression/UploadEvidenceWitness.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/caseprogression/UploadEvidenceWitness.java @@ -8,6 +8,7 @@ import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.ZoneId; @Data @Builder(toBuilder = true) @@ -19,5 +20,5 @@ public class UploadEvidenceWitness { private LocalDate witnessOptionUploadDate; private Document witnessOptionDocument; @Builder.Default - private LocalDateTime createdDatetime = LocalDateTime.now(); + private LocalDateTime createdDatetime = LocalDateTime.now(ZoneId.of("Europe/London")); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/AdditionalLipPartyDetails.java b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/AdditionalLipPartyDetails.java new file mode 100644 index 00000000000..96b5781f0cd --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/AdditionalLipPartyDetails.java @@ -0,0 +1,17 @@ +package uk.gov.hmcts.reform.civil.model.citizenui; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import uk.gov.hmcts.reform.civil.model.Address; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class AdditionalLipPartyDetails { + + private Address correspondenceAddress; + private String contactPerson; +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/CaseDataLiP.java b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/CaseDataLiP.java index e07709adab7..b66b6b1ffbc 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/CaseDataLiP.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/CaseDataLiP.java @@ -6,7 +6,9 @@ import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import uk.gov.hmcts.reform.civil.model.common.Element; +import java.util.List; import java.util.Optional; @Data @@ -19,11 +21,17 @@ public class CaseDataLiP { private RespondentLiPResponse respondent1LiPResponse; @JsonProperty("applicant1LiPResponse") private ClaimantLiPResponse applicant1LiPResponse; - private TranslatedDocument translatedDocument; + private List> translatedDocuments; @JsonProperty("respondent1LiPFinancialDetails") private FinancialDetailsLiP respondent1LiPFinancialDetails; @JsonProperty("applicant1ClaimMediationSpecRequiredLip") private ClaimantMediationLip applicant1ClaimMediationSpecRequiredLip; + @JsonProperty("helpWithFees") + private HelpWithFees helpWithFees; + @JsonProperty("respondent1AdditionalLipPartyDetails") + private AdditionalLipPartyDetails respondent1AdditionalLipPartyDetails; + @JsonProperty("applicant1AdditionalLipPartyDetails") + private AdditionalLipPartyDetails applicant1AdditionalLipPartyDetails; @JsonIgnore public boolean hasClaimantAgreedToFreeMediation() { diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/CcdDashboardClaimMatcher.java b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/CcdDashboardClaimMatcher.java index ea118401122..fe45e29d735 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/CcdDashboardClaimMatcher.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/CcdDashboardClaimMatcher.java @@ -9,6 +9,7 @@ import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.sdo.FastTrackHearingTime; import uk.gov.hmcts.reform.civil.model.sdo.SmallClaimsHearing; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import java.time.LocalDate; import java.time.LocalTime; @@ -21,10 +22,11 @@ public class CcdDashboardClaimMatcher implements Claim { private static final LocalTime FOUR_PM = LocalTime.of(16, 1, 0); private CaseData caseData; + private FeatureToggleService featureToggleService; @Override public boolean hasResponsePending() { - return caseData.getRespondent1ResponseDate() == null; + return caseData.getRespondent1ResponseDate() == null && !isPaperResponse(); } @Override @@ -75,7 +77,8 @@ public boolean hasResponseDeadlineBeenExtended() { @Override public boolean isEligibleForCCJ() { return caseData.getRespondent1ResponseDeadline() != null - && caseData.getRespondent1ResponseDeadline().isBefore(LocalDate.now().atTime(FOUR_PM)); + && caseData.getRespondent1ResponseDeadline().isBefore(LocalDate.now().atTime(FOUR_PM)) + && caseData.getPaymentTypeSelection() == null; } @Override @@ -117,7 +120,12 @@ public boolean isProceedOffline() { @Override public boolean isPaperResponse() { - return false; + if (!featureToggleService.isLipVLipEnabled()) { + return false; + } + + return Objects.nonNull(caseData.getTakenOfflineDate()) && Objects.nonNull(caseData.getCcdState()) + && caseData.getCcdState().equals(CaseState.PROCEEDS_IN_HERITAGE_SYSTEM); } @Override @@ -208,7 +216,7 @@ private boolean isBeforeFastTrackHearing() { @Override public boolean isMoreDetailsRequired() { - return hasSdoBeenDrawn() && isBeforeHearing(); + return hasSdoBeenDrawn() && isBeforeHearing() && featureToggleService.isCaseProgressionEnabled(); } @Override @@ -275,8 +283,15 @@ public boolean isPartialAdmissionRejected() { @Override public boolean isSDOOrderCreated() { - return hasSdoBeenDrawn() && noHearingScheduled() && caseData.getHearingDate() == null + return caseData.getHearingDate() == null && CaseState.CASE_PROGRESSION.equals(caseData.getCcdState()); } + @Override + public boolean isClaimantDefaultJudgement() { + return caseData.getRespondent1ResponseDeadline() != null + && caseData.getRespondent1ResponseDeadline().isBefore(LocalDate.now().atTime(FOUR_PM)) + && caseData.getPaymentTypeSelection() != null; + } + } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/Claim.java b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/Claim.java index 3a0a07b0c42..f8a6c0c3202 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/Claim.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/Claim.java @@ -80,4 +80,6 @@ public interface Claim { boolean isSDOOrderCreated(); + boolean isClaimantDefaultJudgement(); + } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/DashboardClaimStatus.java b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/DashboardClaimStatus.java index 4e16833975d..83716bcd9a8 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/DashboardClaimStatus.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/DashboardClaimStatus.java @@ -33,6 +33,9 @@ public enum DashboardClaimStatus { CLAIM_ENDED( Claim::hasClaimEnded ), + RESPONSE_BY_POST( + Claim::isPaperResponse + ), WAITING_COURT_REVIEW( Claim::isCourtReviewing ), @@ -64,6 +67,9 @@ public enum DashboardClaimStatus { REQUESTED_COUNTRY_COURT_JUDGEMENT( Claim::claimantRequestedCountyCourtJudgement ), + DEFAULT_JUDGEMENT( + Claim::isClaimantDefaultJudgement + ), RESPONSE_OVERDUE( Claim::hasResponsePendingOverdue ), @@ -91,9 +97,6 @@ public enum DashboardClaimStatus { PROCEED_OFFLINE( Claim::isProceedOffline ), - RESPONSE_BY_POST( - Claim::isPaperResponse - ), CHANGE_BY_DEFENDANT( Claim::hasChangeRequestFromDefendant ), diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/DocumentTypeMapper.java b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/DocumentTypeMapper.java new file mode 100644 index 00000000000..b83682daab2 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/DocumentTypeMapper.java @@ -0,0 +1,18 @@ +package uk.gov.hmcts.reform.civil.model.citizenui; + +import uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType; + +public final class DocumentTypeMapper { + + private DocumentTypeMapper() { + } + + public static ManageDocumentType mapDocumentTypeToManageDocumentType(DocumentType documentType) { + switch (documentType) { + case MEDIATION_AGREEMENT: + return ManageDocumentType.MEDIATION_AGREEMENT; + default: + return null; + } + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/HelpWithFees.java b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/HelpWithFees.java new file mode 100644 index 00000000000..d5b6809ae9e --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/HelpWithFees.java @@ -0,0 +1,17 @@ +package uk.gov.hmcts.reform.civil.model.citizenui; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class HelpWithFees { + + private YesOrNo helpWithFee; + private String helpWithFeesReferenceNumber; +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/ManageDocumentType.java b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/ManageDocumentType.java index 5c9d3bff56f..7ad1db47a80 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/ManageDocumentType.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/ManageDocumentType.java @@ -4,5 +4,6 @@ public enum ManageDocumentType { N9A_PAPER_ADMISSION_FULL_OR_PART, N9B_PAPER_DEFENCE_OR_COUNTERCLAIM, N9_REQUEST_MORE_TIME, - OTHER + OTHER, + MEDIATION_AGREEMENT } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/RespondentLiPResponse.java b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/RespondentLiPResponse.java index 4eb9ba8a266..0c92b3d64f9 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/RespondentLiPResponse.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/RespondentLiPResponse.java @@ -20,5 +20,4 @@ public class RespondentLiPResponse { private DQExtraDetailsLip respondent1DQExtraDetails; private HearingSupportLip respondent1DQHearingSupportLip; private String respondent1ResponseLanguage; - private String helpWithFeesReferenceNumberLip; } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/dto/ExtendedDeadlineDto.java b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/dto/ExtendedDeadlineDto.java new file mode 100644 index 00000000000..58c4a1182de --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/dto/ExtendedDeadlineDto.java @@ -0,0 +1,18 @@ +package uk.gov.hmcts.reform.civil.model.citizenui.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ExtendedDeadlineDto { + + private LocalDate responseDate; + private Integer plusDays; +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/dto/RepaymentDecisionType.java b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/dto/RepaymentDecisionType.java new file mode 100644 index 00000000000..30354909e22 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/citizenui/dto/RepaymentDecisionType.java @@ -0,0 +1,13 @@ +package uk.gov.hmcts.reform.civil.model.citizenui.dto; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +public enum RepaymentDecisionType { + IN_FAVOUR_OF_CLAIMANT, + IN_FAVOUR_OF_DEFENDANT; + + @JsonIgnore + public boolean isInFavourOfDefendant() { + return this == IN_FAVOUR_OF_DEFENDANT; + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/common/DynamicList.java b/src/main/java/uk/gov/hmcts/reform/civil/model/common/DynamicList.java index 1fe3e01a3f6..075db0e94a5 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/common/DynamicList.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/common/DynamicList.java @@ -16,7 +16,7 @@ */ @Data @Jacksonized -@Builder +@Builder(toBuilder = true) public class DynamicList { /** @@ -39,18 +39,20 @@ public static DynamicList fromList(List list) { } /** - * Sometimes a dynamic list can be prepopulated with a value. + * A dynamic list can be pre-populated with a code and value. * * @param list the original list of items + * @param toCode (optional) how to populate the DynamicListElement code, defaults to random UUID * @param toLabel how to create the label * @param value (optional) value to be selected * @param type of element * @return dynamic list, possibly with value set */ - public static DynamicList fromList(List list, Function toLabel, T value, boolean sort) { + public static DynamicList fromList(List list, Function toCode, Function toLabel, T value, boolean sort) { List items = list.stream() - .map(toLabel) - .map(DynamicListElement::dynamicElement) + .map(item -> toCode != null + ? DynamicListElement.dynamicElementFromCode(toCode.apply(item), toLabel.apply(item)) + : DynamicListElement.dynamicElement(toLabel.apply(item))) .collect(toList()); int index = value != null ? list.indexOf(value) : -1; @@ -68,6 +70,19 @@ public static DynamicList fromList(List list, Function toLabel return DynamicList.builder().listItems(items).value(chosen).build(); } + /** + * Sometimes a dynamic list can be pre-populated with a value. + * + * @param list the original list of items + * @param toLabel how to create the label + * @param value (optional) value to be selected + * @param type of element + * @return dynamic list, possibly with value set + */ + public static DynamicList fromList(List list, Function toLabel, T value, boolean sort) { + return fromList(list, null, toLabel, value, sort); + } + public static DynamicList fromDynamicListElementList(List list) { return DynamicList.builder().listItems(list).value(DynamicListElement.EMPTY).build(); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/casepogression/JudgeFinalOrderForm.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/casepogression/JudgeFinalOrderForm.java index 5b12973a95e..4bc540ec2ea 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/casepogression/JudgeFinalOrderForm.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/casepogression/JudgeFinalOrderForm.java @@ -28,39 +28,33 @@ public class JudgeFinalOrderForm implements MappableObject { private final String withoutNoticeSelectionText; private final LocalDate withoutNoticeSelectionDate; private final YesOrNo finalOrderMadeSelection; - private final LocalDate finalOrderHeardDate; - private final String finalOrderRepresented; - private final boolean claimantAttended; - private final boolean defendantAttended; - private final String judgeHeardFromClaimantTextIfAttended; - private final String judgeHeardFromDefendantTextIfAttended; - private final String judgeHeardClaimantNotAttendedText; - private final String judgeHeardDefendantNotAttendedText; private final String otherRepresentedText; - private final boolean judgeConsideredPapers; + private final String judgeConsideredPapers; private final boolean recordedToggle; private final String recordedText; private final String orderedText; private final String costSelection; - private final String costReservedText; - private final LocalDate paidByDate; - private final YesOrNo costProtection; - private final String costAmount; - private final String bespokeText; + private final String costsReservedText; + private final String bespokeCostText; private final boolean furtherHearingToggle; + private final boolean furtherHearingToToggle; private final LocalDate furtherHearingFromDate; private final LocalDate furtherHearingToDate; private final String furtherHearingLength; - private final String furtherHearingLocation; + private LocalDate datesToAvoid; + private final String furtherHearingLocationDefault; + private final Boolean showFurtherHearingLocationAlt; + private final String furtherHearingLocationAlt; private final String furtherHearingMethod; - private final boolean appealToggle; - private final String appealFor; - private final boolean appealGranted; - private final String appealReason; - private final String orderWithoutNotice; - private final LocalDate orderInitiativeOrWithoutNoticeDate; - private final YesOrNo isReason; - private final String reasonText; + private final String hearingNotes; + private final String appealGranted; + private final String claimantOrDefendantAppeal; + private final String tableAorB; + private final LocalDate appealDate; + private final String showInitiativeOrWithoutNotice; + private final LocalDate initiativeDate; + private final LocalDate withoutNoticeDate; + private final String reasonsText; private final String judgeNameTitle; private final String courtLocation; private final String courtName; @@ -68,4 +62,19 @@ public class JudgeFinalOrderForm implements MappableObject { private final String claimant2Name; private final String defendant1Name; private final String defendant2Name; + private final String claimantNum; + private final String defendantNum; + private final String orderMadeDate; + private final String claimantAttendsOrRepresented; + private final String claimantTwoAttendsOrRepresented; + private final String defendantAttendsOrRepresented; + private final String defendantTwoAttendsOrRepresented; + private final String summarilyAssessed; + private final LocalDate summarilyAssessedDate; + private final String detailedAssessment; + private final String interimPayment; + private final LocalDate interimPaymentDate; + private final String qcosProtection; + private final String costsProtection; + private final Boolean finalOrderJudgeHeardFrom; } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/AccountSimpleTemplateData.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/AccountSimpleTemplateData.java index 764d54c0c00..779cfbf2c32 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/AccountSimpleTemplateData.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/AccountSimpleTemplateData.java @@ -1,11 +1,13 @@ package uk.gov.hmcts.reform.civil.model.docmosis.common; import lombok.AllArgsConstructor; -import lombok.Builder; import lombok.Getter; +import lombok.experimental.SuperBuilder; import uk.gov.hmcts.reform.civil.model.account.AccountSimple; -@Builder +import java.math.RoundingMode; + +@SuperBuilder @AllArgsConstructor @Getter public class AccountSimpleTemplateData extends AccountSimple { @@ -15,7 +17,7 @@ public class AccountSimpleTemplateData extends AccountSimple { public AccountSimpleTemplateData(AccountSimple data, int index) { setAccountType(data.getAccountType()); setJointAccount(data.getJointAccount()); - setBalance(data.getBalance()); + setBalance(data.getBalance().setScale(2, RoundingMode.CEILING)); this.index = index; } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/DebtTemplateData.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/DebtTemplateData.java index 8d4123ef8e1..539721893bb 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/DebtTemplateData.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/DebtTemplateData.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.reform.civil.model.docmosis.common; +import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Builder; import lombok.Data; @@ -15,15 +16,17 @@ public class DebtTemplateData { private final String debtOwedTo; + @JsonFormat(shape = JsonFormat.Shape.STRING) private final BigDecimal poundsOwed; + @JsonFormat(shape = JsonFormat.Shape.STRING) private final BigDecimal paidPerMonth; @JsonIgnore public static DebtTemplateData loanDebtFrom(final LoanCardDebtLRspec debt) { return DebtTemplateData.builder() .debtOwedTo(debt.getLoanCardDebtDetail()) - .paidPerMonth(MonetaryConversions.penniesToPounds(debt.getMonthlyPayment())) - .poundsOwed(MonetaryConversions.penniesToPounds(debt.getTotalOwed())) + .paidPerMonth((MonetaryConversions.penniesToPounds(debt.getMonthlyPayment())).setScale(2, RoundingMode.CEILING)) + .poundsOwed((MonetaryConversions.penniesToPounds(debt.getTotalOwed())).setScale(2, RoundingMode.CEILING)) .build(); } @@ -33,18 +36,22 @@ public static DebtTemplateData generalDebtFrom(final DebtLRspec debtLRspec) { .debtOwedTo(debtLRspec.getDebtType().getLabel()); switch (debtLRspec.getPaymentFrequency()) { case ONCE_THREE_WEEKS: - builder.paidPerMonth(MonetaryConversions.penniesToPounds(debtLRspec.getPaymentAmount() + builder.paidPerMonth((MonetaryConversions.penniesToPounds(debtLRspec.getPaymentAmount() .multiply(BigDecimal.valueOf(4)) - .divide(BigDecimal.valueOf(3), RoundingMode.CEILING))); + .divide(BigDecimal.valueOf(3), RoundingMode.CEILING))) + .setScale(2, RoundingMode.CEILING)); break; case ONCE_TWO_WEEKS: - builder.paidPerMonth(MonetaryConversions.penniesToPounds(debtLRspec.getPaymentAmount().multiply(BigDecimal.valueOf(2)))); + builder.paidPerMonth((MonetaryConversions.penniesToPounds(debtLRspec.getPaymentAmount().multiply(BigDecimal.valueOf(2)))) + .setScale(2, RoundingMode.CEILING)); break; case ONCE_ONE_WEEK: - builder.paidPerMonth(MonetaryConversions.penniesToPounds(debtLRspec.getPaymentAmount().multiply(BigDecimal.valueOf(4)))); + builder.paidPerMonth((MonetaryConversions.penniesToPounds(debtLRspec.getPaymentAmount().multiply(BigDecimal.valueOf(4)))) + .setScale(2, RoundingMode.CEILING)); break; default: - builder.paidPerMonth(MonetaryConversions.penniesToPounds(debtLRspec.getPaymentAmount())); + builder.paidPerMonth((MonetaryConversions.penniesToPounds(debtLRspec.getPaymentAmount())) + .setScale(2, RoundingMode.CEILING)); break; } return builder.build(); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/EventTemplateData.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/EventTemplateData.java index ecdf9e730c3..f7eb4640fc0 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/EventTemplateData.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/EventTemplateData.java @@ -1,10 +1,17 @@ package uk.gov.hmcts.reform.civil.model.docmosis.common; import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Builder; import lombok.Getter; +import uk.gov.hmcts.reform.civil.model.TimelineOfEvents; import java.time.LocalDate; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; @Getter @Builder @@ -13,4 +20,15 @@ public class EventTemplateData { @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") private LocalDate date; private String explanation; + + @JsonIgnore + public static List toEventTemplateDataList(List timelineOfEvents) { + return Optional.ofNullable(timelineOfEvents).map(Collection::stream) + .orElseGet(Stream::empty) + .map(event -> + EventTemplateData.builder() + .date(event.getValue().getTimelineDate()) + .explanation(event.getValue().getTimelineDescription()) + .build()).collect(Collectors.toList()); + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/EvidenceTemplateData.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/EvidenceTemplateData.java index 5ba60570c6e..9bed100ca02 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/EvidenceTemplateData.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/EvidenceTemplateData.java @@ -6,7 +6,10 @@ import lombok.Getter; import uk.gov.hmcts.reform.civil.model.Evidence; +import java.util.Collection; +import java.util.List; import java.util.Optional; +import java.util.stream.Stream; @Getter @Builder @@ -22,6 +25,14 @@ public static EvidenceTemplateData toEvidenceTemplateData(Evidence evidence) { .build(); } + @JsonIgnore + public static List toEvidenceTemplateDataList(List evidenceList) { + return Optional.ofNullable(evidenceList).map(Collection::stream) + .orElseGet(Stream::empty) + .map(evidence -> EvidenceTemplateData.toEvidenceTemplateData(evidence)) + .toList(); + } + @JsonProperty("displayTypeValue") public String getDisplayTypeValue() { return Optional.ofNullable(type).map(type -> getDisplayValueFromEvidenceType(type)).orElse(""); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/Party.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/Party.java index ab1d81bbc03..b142e43c1e9 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/Party.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/Party.java @@ -22,4 +22,14 @@ public class Party { private final String litigationFriendPhoneNumber; private final String litigationFriendEmailAddress; private final String legalRepHeading; + + public static Party toLipParty(uk.gov.hmcts.reform.civil.model.Party party) { + return Party.builder() + .name(party.getPartyName()) + .emailAddress(party.getPartyEmail()) + .type(party.getType().getDisplayValue()) + .phoneNumber(party.getPartyPhone()) + .primaryAddress(party.getPrimaryAddress()) + .build(); + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/ReasonMoneyTemplateData.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/ReasonMoneyTemplateData.java index 68ab66218ff..9dff0a37efe 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/ReasonMoneyTemplateData.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/common/ReasonMoneyTemplateData.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.reform.civil.model.docmosis.common; +import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Builder; import lombok.Data; @@ -10,6 +11,7 @@ import uk.gov.hmcts.reform.civil.utils.MonetaryConversions; import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.Map; import static java.util.Map.entry; @@ -72,6 +74,8 @@ public class ReasonMoneyTemplateData { ); private String type; + + @JsonFormat(shape = JsonFormat.Shape.STRING) private BigDecimal amountPounds; @JsonIgnore @@ -80,7 +84,7 @@ public static ReasonMoneyTemplateData toReasonMoneyTemplateData(RecurringIncomeL .type(item.getType() == IncomeTypeLRspec.OTHER ? "Other: " + item.getTypeOtherDetails() : INCOME_TYPE_LIP_RESPONSE.get(item.getType())) - .amountPounds(MonetaryConversions.penniesToPounds(item.getAmount())) + .amountPounds((MonetaryConversions.penniesToPounds(item.getAmount())).setScale(2, RoundingMode.CEILING)) .build(); } @@ -90,7 +94,7 @@ public static ReasonMoneyTemplateData toReasonMoneyTemplateData(RecurringExpense .type(item.getType() == ExpenseTypeLRspec.OTHER ? "Other: " + item.getTypeOtherDetails() : EXPENSE_TYPE_LIP_RESPONSE.get(item.getType())) - .amountPounds(MonetaryConversions.penniesToPounds(item.getAmount())) + .amountPounds((MonetaryConversions.penniesToPounds(item.getAmount())).setScale(2, RoundingMode.CEILING)) .build(); } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/dj/DefaultJudgmentSDOOrderForm.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/dj/DefaultJudgmentSDOOrderForm.java index a117f8d87eb..3172d11f184 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/dj/DefaultJudgmentSDOOrderForm.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/dj/DefaultJudgmentSDOOrderForm.java @@ -77,6 +77,7 @@ public class DefaultJudgmentSDOOrderForm implements MappableObject { private final TrialHousingDisrepair trialHousingDisrepair; private final List> trialHearingAddNewDirectionsDJ; private final LocationRefData hearingLocation; + private final LocationRefData caseManagementLocation; //additional data for hearings private final boolean disposalHearingDisclosureOfDocumentsDJAddSection; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/dq/DirectionsQuestionnaireForm.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/dq/DirectionsQuestionnaireForm.java index ad9729d1116..586966fd40d 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/dq/DirectionsQuestionnaireForm.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/dq/DirectionsQuestionnaireForm.java @@ -29,7 +29,7 @@ import java.util.List; @Getter -@Builder +@Builder(toBuilder = true) @AllArgsConstructor @EqualsAndHashCode @ToString @@ -66,8 +66,10 @@ public class DirectionsQuestionnaireForm implements MappableObject { private final VulnerabilityQuestions vulnerabilityQuestions; private final String statementOfTruthText; private final Address respondent1LiPCorrespondenceAddress; + private final Address applicant1LiPCorrespondenceAddress; private final LipExperts lipExperts; private final LipExtraDQ lipExtraDQ; private final List hearingLipSupportRequirements; + private final String lipStatementOfTruthName; } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/dq/HearingLipSupportRequirements.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/dq/HearingLipSupportRequirements.java index d3ae6517b96..db0b261e85c 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/dq/HearingLipSupportRequirements.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/dq/HearingLipSupportRequirements.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Builder; import lombok.Data; +import uk.gov.hmcts.reform.civil.model.citizenui.HearingSupportLip; import uk.gov.hmcts.reform.civil.model.dq.RequirementsLip; import java.util.Collection; @@ -32,4 +33,13 @@ public static HearingLipSupportRequirements toHearingSupportRequirements(Require : HearingLipSupportRequirements.builder().build(); } + + @JsonIgnore + public static List toHearingSupportRequirementsList(Optional hearingSupportLip) { + return hearingSupportLip.map(HearingSupportLip::getUnwrappedRequirementsLip) + .map(Collection::stream) + .map(items -> items.map(item -> toHearingSupportRequirements(item)) + .toList()) + .orElse(Collections.emptyList()); + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/hearing/HearingForm.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/hearing/HearingForm.java index d6f5897da1c..3a1fa19368c 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/hearing/HearingForm.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/hearing/HearingForm.java @@ -37,6 +37,7 @@ public class HearingForm implements MappableObject { private final String defendant2Reference; private final boolean claimant2exists; private final boolean defendant2exists; + private final String listingOrRelisting; private final String claimReferenceNumber; private final CorrectEmail emailAddress; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sdo/SdoDocumentFormDisposal.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sdo/SdoDocumentFormDisposal.java index e16e8812d54..f309d8ed97e 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sdo/SdoDocumentFormDisposal.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sdo/SdoDocumentFormDisposal.java @@ -69,6 +69,7 @@ public class SdoDocumentFormDisposal implements MappableObject { private final String disposalHearingMethodTelephoneHearing; private final String disposalHearingMethodVideoConferenceHearing; private final LocationRefData hearingLocation; + private final LocationRefData caseManagementLocation; private final DisposalHearingBundle disposalHearingBundle; private final String disposalHearingBundleTypeText; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sdo/SdoDocumentFormFast.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sdo/SdoDocumentFormFast.java index 7aee5880ebf..343dc4380ec 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sdo/SdoDocumentFormFast.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sdo/SdoDocumentFormFast.java @@ -82,6 +82,7 @@ public class SdoDocumentFormFast implements MappableObject { private final String fastTrackMethodTelephoneHearing; private final String fastTrackMethodVideoConferenceHearing; private final LocationRefData hearingLocation; + private final LocationRefData caseManagementLocation; private final FastTrackBuildingDispute fastTrackBuildingDispute; private final FastTrackClinicalNegligence fastTrackClinicalNegligence; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sdo/SdoDocumentFormSmall.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sdo/SdoDocumentFormSmall.java index 553e427b912..80f9937e0fa 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sdo/SdoDocumentFormSmall.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sdo/SdoDocumentFormSmall.java @@ -67,6 +67,7 @@ public class SdoDocumentFormSmall implements MappableObject { private final SmallClaimsDocuments smallClaimsDocuments; private final SmallClaimsWitnessStatement smallClaimsWitnessStatement; private final LocationRefData hearingLocation; + private final LocationRefData caseManagementLocation; private final SmallClaimsCreditHire smallClaimsCreditHire; private final SmallClaimsRoadTrafficAccident smallClaimsRoadTrafficAccident; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sealedclaim/ResponseRepaymentDetailsForm.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sealedclaim/ResponseRepaymentDetailsForm.java new file mode 100644 index 00000000000..ae474fb8326 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sealedclaim/ResponseRepaymentDetailsForm.java @@ -0,0 +1,155 @@ +package uk.gov.hmcts.reform.civil.model.docmosis.sealedclaim; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec; +import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.RepaymentPlanLRspec; +import uk.gov.hmcts.reform.civil.model.RespondToClaim; +import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; +import uk.gov.hmcts.reform.civil.model.docmosis.common.EventTemplateData; +import uk.gov.hmcts.reform.civil.model.docmosis.common.EvidenceTemplateData; +import uk.gov.hmcts.reform.civil.model.docmosis.common.RepaymentPlanTemplateData; +import uk.gov.hmcts.reform.civil.utils.MonetaryConversions; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + +import static uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec.COUNTER_CLAIM; + +@Getter +@Builder(toBuilder = true) +@AllArgsConstructor +@EqualsAndHashCode +public class ResponseRepaymentDetailsForm { + + private final String amountToPay; + private final String howMuchWasPaid; + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") + @JsonSerialize(using = LocalDateSerializer.class) + private final LocalDate paymentDate; + private final String paymentHow; + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") + @JsonSerialize(using = LocalDateSerializer.class) + private final LocalDate payBy; + private final String whyNotPayImmediately; + private final RepaymentPlanTemplateData repaymentPlan; + private final RespondentResponseTypeSpec responseType; + private final String freeTextWhyReject; + private final String whyReject; + private final List timelineEventList; + private final String timelineComments; + private final List evidenceList; + private final String evidenceComments; + private final boolean mediation; + private final RespondentResponsePartAdmissionPaymentTimeLRspec howToPay; + + public String getResponseTypeDisplay() { + return Optional.ofNullable(responseType).map(RespondentResponseTypeSpec::getDisplayedValue).orElse(""); + } + + public static ResponseRepaymentDetailsForm toSealedClaimResponseCommonContent(CaseData caseData) { + ResponseRepaymentDetailsForm.ResponseRepaymentDetailsFormBuilder builder = ResponseRepaymentDetailsForm.builder(); + + if (caseData.getRespondent1ClaimResponseTypeForSpec() != null) { + builder.howToPay(caseData.getDefenceAdmitPartPaymentTimeRouteRequired()); + switch (caseData.getRespondent1ClaimResponseTypeForSpec()) { + case FULL_ADMISSION -> addRepaymentMethod(caseData, builder, caseData.getTotalClaimAmount()); + case PART_ADMISSION -> partAdmissionData(caseData, builder); + case FULL_DEFENCE -> fullDefenceData(caseData, builder); + case COUNTER_CLAIM -> builder.whyReject(COUNTER_CLAIM.name()); + default -> builder.whyReject(null); + } + } + + return builder + .whyNotPayImmediately(caseData.getResponseToClaimAdmitPartWhyNotPayLRspec()) + .responseType(caseData.getRespondent1ClaimResponseTypeForSpec()) + .mediation(caseData.getResponseClaimMediationSpecRequired() == YesOrNo.YES) + .build(); + } + + private static void addRepaymentMethod(CaseData caseData, ResponseRepaymentDetailsFormBuilder builder, BigDecimal totalAmount) { + if (caseData.isPayImmediately()) { + addPayByDatePayImmediately(builder, totalAmount, caseData.getRespondToClaimAdmitPartLRspec().getWhenWillThisAmountBePaid()); + } else if (caseData.isPayByInstallment()) { + addRepaymentPlan(caseData, builder, totalAmount); + } else if (caseData.isPayBySetDate()) { + addPayBySetDate(caseData, builder, totalAmount); + } + } + + private static void addPayBySetDate(CaseData caseData, ResponseRepaymentDetailsForm.ResponseRepaymentDetailsFormBuilder builder, BigDecimal totalClaimAmount) { + builder.payBy(caseData.getRespondToClaimAdmitPartLRspec().getWhenWillThisAmountBePaid()) + .amountToPay(totalClaimAmount + "") + .whyNotPayImmediately(caseData.getResponseToClaimAdmitPartWhyNotPayLRspec()); + } + + private static void addPayByDatePayImmediately(ResponseRepaymentDetailsFormBuilder builder, BigDecimal totalClaimAmount, LocalDate responseDate) { + builder.payBy(responseDate).amountToPay(totalClaimAmount + ""); + } + + private static void addRepaymentPlan(CaseData caseData, ResponseRepaymentDetailsForm.ResponseRepaymentDetailsFormBuilder builder, BigDecimal totalClaimAmount) { + RepaymentPlanLRspec repaymentPlan = caseData.getRespondent1RepaymentPlan(); + if (repaymentPlan != null) { + builder.repaymentPlan(RepaymentPlanTemplateData.builder() + .paymentFrequencyDisplay(repaymentPlan.getPaymentFrequencyDisplay()) + .firstRepaymentDate(repaymentPlan.getFirstRepaymentDate()) + .paymentAmount(MonetaryConversions.penniesToPounds(repaymentPlan.getPaymentAmount())) + .build()) + .payBy(repaymentPlan.finalPaymentBy(totalClaimAmount)) + .whyNotPayImmediately(caseData.getResponseToClaimAdmitPartWhyNotPayLRspec()); + } + } + + private static void alreadyPaid(CaseData caseData, ResponseRepaymentDetailsForm.ResponseRepaymentDetailsFormBuilder builder) { + RespondToClaim respondToClaim = caseData.getResponseToClaim(); + String howMuchWasPaidAsString = MonetaryConversions.penniesToPounds(respondToClaim.getHowMuchWasPaid()) + ""; + builder.whyReject("ALREADY_PAID") + .howMuchWasPaid(howMuchWasPaidAsString) + .paymentDate(respondToClaim.getWhenWasThisAmountPaid()) + .paymentHow(respondToClaim.getExplanationOnHowTheAmountWasPaid()); + } + + private static void addDetailsOnWhyClaimIsRejected(CaseData caseData, ResponseRepaymentDetailsForm.ResponseRepaymentDetailsFormBuilder builder) { + Optional caseDataLiPOptional = Optional.ofNullable(caseData.getCaseDataLiP()); + builder.freeTextWhyReject(caseData.getDetailsOfWhyDoesYouDisputeTheClaim()) + .timelineComments(caseDataLiPOptional.map(CaseDataLiP::getTimeLineComment).orElse( + "")) + .timelineEventList(EventTemplateData.toEventTemplateDataList(caseData.getSpecResponseTimelineOfEvents())) + .evidenceComments(caseDataLiPOptional.map(CaseDataLiP::getEvidenceComment).orElse( + "")) + .evidenceList(EvidenceTemplateData.toEvidenceTemplateDataList(caseData.getSpecResponselistYourEvidenceList())); + } + + private static void fullDefenceData(CaseData caseData, ResponseRepaymentDetailsForm.ResponseRepaymentDetailsFormBuilder builder) { + addDetailsOnWhyClaimIsRejected(caseData, builder); + if (caseData.hasDefendantPayedTheAmountClaimed()) { + alreadyPaid(caseData, builder); + } else if (caseData.isClaimBeingDisputed()) { + builder.whyReject("DISPUTE"); + } + } + + private static void partAdmissionData(CaseData caseData, ResponseRepaymentDetailsFormBuilder builder) { + addDetailsOnWhyClaimIsRejected(caseData, builder); + if (caseData.getSpecDefenceAdmittedRequired() == YesOrNo.YES) { + alreadyPaid(caseData, builder); + } else { + addRepaymentMethod( + caseData, + builder, + MonetaryConversions.penniesToPounds(caseData.getRespondToAdmittedClaimOwingAmount()) + ); + } + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sealedclaim/SealedClaimLipResponseForm.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sealedclaim/SealedClaimLipResponseForm.java index 3dddb485b64..91c0bfdda51 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sealedclaim/SealedClaimLipResponseForm.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sealedclaim/SealedClaimLipResponseForm.java @@ -8,33 +8,24 @@ import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; -import uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec; -import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec; -import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.ChildrenByAgeGroupLRspec; import uk.gov.hmcts.reform.civil.model.EmployerDetailsLRspec; import uk.gov.hmcts.reform.civil.model.PartnerAndDependentsLRspec; -import uk.gov.hmcts.reform.civil.model.PaymentMethod; -import uk.gov.hmcts.reform.civil.model.RespondToClaim; import uk.gov.hmcts.reform.civil.model.Respondent1CourtOrderDetails; import uk.gov.hmcts.reform.civil.model.Respondent1DebtLRspec; import uk.gov.hmcts.reform.civil.model.Respondent1EmployerDetailsLRspec; import uk.gov.hmcts.reform.civil.model.Respondent1SelfEmploymentLRspec; -import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; import uk.gov.hmcts.reform.civil.model.common.MappableObject; import uk.gov.hmcts.reform.civil.model.docmosis.LipFormParty; import uk.gov.hmcts.reform.civil.model.docmosis.common.AccommodationTemplate; import uk.gov.hmcts.reform.civil.model.docmosis.common.AccountSimpleTemplateData; import uk.gov.hmcts.reform.civil.model.docmosis.common.DebtTemplateData; -import uk.gov.hmcts.reform.civil.model.docmosis.common.EventTemplateData; -import uk.gov.hmcts.reform.civil.model.docmosis.common.EvidenceTemplateData; import uk.gov.hmcts.reform.civil.model.docmosis.common.ReasonMoneyTemplateData; -import uk.gov.hmcts.reform.civil.model.docmosis.common.RepaymentPlanTemplateData; import uk.gov.hmcts.reform.civil.utils.ElementUtils; import uk.gov.hmcts.reform.civil.utils.MonetaryConversions; -import java.math.BigDecimal; +import java.math.RoundingMode; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collection; @@ -45,10 +36,8 @@ import java.util.stream.IntStream; import java.util.stream.Stream; -import static uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec.COUNTER_CLAIM; - @Getter -@Builder +@Builder(toBuilder = true) @AllArgsConstructor @EqualsAndHashCode public class SealedClaimLipResponseForm implements MappableObject { @@ -59,29 +48,9 @@ public class SealedClaimLipResponseForm implements MappableObject { @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") @JsonSerialize(using = LocalDateSerializer.class) private final LocalDate generationDate; - private final String amountToPay; - private final String howMuchWasPaid; - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") - @JsonSerialize(using = LocalDateSerializer.class) - private final LocalDate paymentDate; - private final String paymentHow; - private final RespondentResponsePartAdmissionPaymentTimeLRspec howToPay; - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") - @JsonSerialize(using = LocalDateSerializer.class) - private final LocalDate payBy; - private final String whyNotPayImmediately; - private final RepaymentPlanTemplateData repaymentPlan; - private final RespondentResponseTypeSpec responseType; - private final String whyReject; - private final String freeTextWhyReject; private final LipFormParty claimant1; private final LipFormParty defendant1; private final LipFormParty defendant2; - private final List timelineEventList; - private final String timelineComments; - private final List evidenceList; - private final String evidenceComments; - private final boolean mediation; private final AccommodationTemplate whereTheyLive; private final PartnerAndDependentsLRspec partnerAndDependent; private final List employerDetails; @@ -91,10 +60,8 @@ public class SealedClaimLipResponseForm implements MappableObject { private final List debtList; private final List incomeList; private final List expenseList; - - public String getResponseTypeDisplay() { - return responseType.getDisplayedValue(); - } + //repayment details for repayment plan that are common between LR and LiP + private final ResponseRepaymentDetailsForm commonDetails; public boolean isCurrentlyWorking() { return (employerDetails != null && !employerDetails.isEmpty()) @@ -110,7 +77,6 @@ public int getNumberOfChildren() { public static SealedClaimLipResponseForm toTemplate(final CaseData caseData) { SealedClaimLipResponseForm.SealedClaimLipResponseFormBuilder builder = SealedClaimLipResponseForm.builder() .generationDate(LocalDate.now()) - .responseType(caseData.getRespondent1ClaimResponseTypeForSpec()) .claimReferenceNumber(caseData.getLegacyCaseReference()) .claimant1(LipFormParty.toLipDefenceParty(caseData.getApplicant1())) .defendant1(LipFormParty.toLipDefenceParty( @@ -118,26 +84,14 @@ public static SealedClaimLipResponseForm toTemplate(final CaseData caseData) { caseData.getRespondent1CorrespondanceAddress() )) .defendant2(LipFormParty.toLipDefenceParty(caseData.getRespondent2())) - .mediation(caseData.getResponseClaimMediationSpecRequired() == YesOrNo.YES) - .whyNotPayImmediately(caseData.getResponseToClaimAdmitPartWhyNotPayLRspec()) .partnerAndDependent(caseData.getRespondent1PartnerAndDependent()) - .debtList(mapToDebtList(caseData.getSpecDefendant1Debts())); + .debtList(mapToDebtList(caseData.getSpecDefendant1Debts())) + .commonDetails(ResponseRepaymentDetailsForm.toSealedClaimResponseCommonContent(caseData)); addSolicitorDetails(caseData, builder); addEmployeeDetails(caseData, builder); addFinancialDetails(caseData, builder); addSelfEmploymentDetails(caseData, builder); addCourtOrderDetails(caseData, builder); - - if (caseData.getRespondent1ClaimResponseTypeForSpec() != null) { - builder.howToPay(caseData.getDefenceAdmitPartPaymentTimeRouteRequired()); - switch (caseData.getRespondent1ClaimResponseTypeForSpec()) { - case FULL_ADMISSION -> addRepaymentMethod(caseData, builder, caseData.getTotalClaimAmount()); - case PART_ADMISSION -> partAdmissionData(caseData, builder); - case FULL_DEFENCE -> fullDefenceData(caseData, builder); - case COUNTER_CLAIM -> builder.whyReject(COUNTER_CLAIM.name()); - default -> builder.whyReject(null); - } - } return builder.build(); } @@ -157,110 +111,22 @@ private static void addEmployeeDetails(final CaseData caseData, SealedClaimLipRe } - private static void addPayBySetDate(CaseData caseData, SealedClaimLipResponseFormBuilder builder, BigDecimal totalClaimAmount) { - builder.payBy(caseData.getRespondToClaimAdmitPartLRspec().getWhenWillThisAmountBePaid()) - .amountToPay(totalClaimAmount + "") - .whyNotPayImmediately(caseData.getResponseToClaimAdmitPartWhyNotPayLRspec()); - } - - private static void addPayByDatePayImmediately(SealedClaimLipResponseFormBuilder builder, BigDecimal totalClaimAmount) { - builder.payBy(LocalDate.now() - .plusDays(RespondentResponsePartAdmissionPaymentTimeLRspec.DAYS_TO_PAY_IMMEDIATELY)) - .amountToPay(totalClaimAmount + ""); - } - - private static void addRepaymentPlan(CaseData caseData, SealedClaimLipResponseFormBuilder builder, BigDecimal totalClaimAmount) { - if (caseData.getRespondent1RepaymentPlan() != null) { - builder.repaymentPlan(RepaymentPlanTemplateData.builder() - .paymentFrequencyDisplay(caseData.getRespondent1RepaymentPlan().getPaymentFrequencyDisplay()) - .firstRepaymentDate(caseData.getRespondent1RepaymentPlan().getFirstRepaymentDate()) - .paymentAmount(MonetaryConversions.penniesToPounds(caseData.getRespondent1RepaymentPlan().getPaymentAmount())) - .build()) - .payBy(caseData.getRespondent1RepaymentPlan() - .finalPaymentBy(totalClaimAmount)) - .whyNotPayImmediately(caseData.getResponseToClaimAdmitPartWhyNotPayLRspec()); - } - } - - private static void alreadyPaid(CaseData caseData, SealedClaimLipResponseFormBuilder builder) { - RespondToClaim respondToClaim = caseData.getResponseToClaim(); - builder.whyReject("ALREADY_PAID") - .howMuchWasPaid(MonetaryConversions.penniesToPounds(respondToClaim.getHowMuchWasPaid()) + "") - .paymentDate(respondToClaim.getWhenWasThisAmountPaid()) - .paymentHow(respondToClaim.getHowWasThisAmountPaid() == PaymentMethod.OTHER - ? respondToClaim.getHowWasThisAmountPaidOther() - : respondToClaim.getHowWasThisAmountPaid() - .getHumanFriendly()); - } - - private static void addDetailsOnWhyClaimIsRejected(CaseData caseData, SealedClaimLipResponseFormBuilder builder) { - builder.freeTextWhyReject(caseData.getDetailsOfWhyDoesYouDisputeTheClaim()) - .timelineComments(Optional.ofNullable(caseData.getCaseDataLiP()).map(CaseDataLiP::getTimeLineComment).orElse( - "")) - .timelineEventList(Optional.ofNullable(caseData.getSpecResponseTimelineOfEvents()).map(Collection::stream) - .orElseGet(Stream::empty) - .map(event -> - EventTemplateData.builder() - .date(event.getValue().getTimelineDate()) - .explanation(event.getValue().getTimelineDescription()) - .build()).collect(Collectors.toList())) - .evidenceComments(Optional.ofNullable(caseData.getCaseDataLiP()).map(CaseDataLiP::getEvidenceComment).orElse( - "")) - .evidenceList(Optional.ofNullable(caseData.getSpecResponselistYourEvidenceList()).map(Collection::stream) - .orElseGet(Stream::empty) - .map(evidence -> EvidenceTemplateData.toEvidenceTemplateData(evidence)) - .toList()); - } - - private static void fullDefenceData(CaseData caseData, SealedClaimLipResponseForm.SealedClaimLipResponseFormBuilder builder) { - addDetailsOnWhyClaimIsRejected(caseData, builder); - if (caseData.hasDefendantPayedTheAmountClaimed()) { - alreadyPaid(caseData, builder); - } else if (caseData.isClaimBeingDisputed()) { - builder.whyReject("DISPUTE"); - } - } - - @JsonIgnore - private static void partAdmissionData(CaseData caseData, SealedClaimLipResponseForm.SealedClaimLipResponseFormBuilder builder) { - addDetailsOnWhyClaimIsRejected(caseData, builder); - if (caseData.getSpecDefenceAdmittedRequired() == YesOrNo.YES) { - alreadyPaid(caseData, builder); - } else { - addRepaymentMethod( - caseData, - builder, - MonetaryConversions.penniesToPounds(caseData.getRespondToAdmittedClaimOwingAmount()) - ); - } - } - private static void addSelfEmploymentDetails(CaseData caseData, SealedClaimLipResponseForm.SealedClaimLipResponseFormBuilder builder) { Optional.ofNullable(caseData.getSpecDefendant1SelfEmploymentDetails()) .ifPresent(selfEmployDetails -> builder.selfEmployment(Respondent1SelfEmploymentLRspec.builder() .amountOwed(selfEmployDetails.getAmountOwed() != null - ? MonetaryConversions.penniesToPounds( - selfEmployDetails.getAmountOwed()) + ? (MonetaryConversions.penniesToPounds( + selfEmployDetails.getAmountOwed())).setScale(2, RoundingMode.CEILING) : null) - .annualTurnover(MonetaryConversions.penniesToPounds( - selfEmployDetails.getAnnualTurnover())) + .annualTurnover((MonetaryConversions.penniesToPounds( + selfEmployDetails.getAnnualTurnover())).setScale(2, RoundingMode.CEILING)) .jobTitle(selfEmployDetails.getJobTitle()) .reason(selfEmployDetails.getReason()) .build()) ); } - private static void addRepaymentMethod(CaseData caseData, SealedClaimLipResponseFormBuilder builder, BigDecimal totalAmount) { - if (caseData.isPayImmediately()) { - addPayByDatePayImmediately(builder, totalAmount); - } else if (caseData.isPayByInstallment()) { - addRepaymentPlan(caseData, builder, totalAmount); - } else if (caseData.isPayBySetDate()) { - addPayBySetDate(caseData, builder, totalAmount); - } - } - @JsonIgnore private static List mapToDebtList(Respondent1DebtLRspec debtLRspec) { return Optional.ofNullable(debtLRspec).map(debt -> createDebtList(debt)).orElse(Collections.emptyList()); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sealedclaim/SealedClaimResponseFormForSpec.java b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sealedclaim/SealedClaimResponseFormForSpec.java index 9a99eac06dd..dcfda51f46a 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sealedclaim/SealedClaimResponseFormForSpec.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/docmosis/sealedclaim/SealedClaimResponseFormForSpec.java @@ -42,4 +42,6 @@ public class SealedClaimResponseFormForSpec implements MappableObject { private final String paymentMethod; private final String hearingCourtLocation; private final StatementOfTruth statementOfTruth; + //repayment details for repayment plan that are common between LR and LiP + private final ResponseRepaymentDetailsForm commonDetails; } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/documents/DocumentAndNote.java b/src/main/java/uk/gov/hmcts/reform/civil/model/documents/DocumentAndNote.java index 33cb4c343cf..fee4c6e850a 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/documents/DocumentAndNote.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/documents/DocumentAndNote.java @@ -7,6 +7,7 @@ import uk.gov.hmcts.reform.civil.documentmanagement.model.Document; import java.time.LocalDateTime; +import java.time.ZoneId; @Data @Builder(toBuilder = true) @@ -18,6 +19,6 @@ public class DocumentAndNote { private Document document; private String documentNote; @Builder.Default - private LocalDateTime createdDateTime = LocalDateTime.now(); + private LocalDateTime createdDateTime = LocalDateTime.now(ZoneId.of("Europe/London")); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/documents/DocumentWithName.java b/src/main/java/uk/gov/hmcts/reform/civil/model/documents/DocumentWithName.java index 3538f61d331..9aabf622994 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/documents/DocumentWithName.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/documents/DocumentWithName.java @@ -7,6 +7,7 @@ import uk.gov.hmcts.reform.civil.documentmanagement.model.Document; import java.time.LocalDateTime; +import java.time.ZoneId; @Data @Builder(toBuilder = true) @@ -17,5 +18,5 @@ public class DocumentWithName { private Document document; private String documentName; @Builder.Default - private LocalDateTime createdDateTime = LocalDateTime.now(); + private LocalDateTime createdDateTime = LocalDateTime.now(ZoneId.of("Europe/London")); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Applicant1DQ.java b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Applicant1DQ.java index 8f83c1cf8f5..6c168e24c1e 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Applicant1DQ.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Applicant1DQ.java @@ -38,6 +38,13 @@ public class Applicant1DQ implements DQ { private FutureApplications applicant1DQFutureApplications; private WelshLanguageRequirements applicant1DQLanguageLRspec; + private RemoteHearing remoteHearing; + + @JsonProperty("applicant1DQRemoteHearing") + public RemoteHearing getRemoteHearing() { + return remoteHearing; + } + @Override @JsonProperty("applicant1DQFileDirectionsQuestionnaire") public FileDirectionsQuestionnaire getFileDirectionQuestionnaire() { diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Applicant2DQ.java b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Applicant2DQ.java index 0d2725c5ce6..ade4eb1624b 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Applicant2DQ.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Applicant2DQ.java @@ -36,6 +36,13 @@ public class Applicant2DQ implements DQ { private StatementOfTruth applicant2DQStatementOfTruth; private VulnerabilityQuestions applicant2DQVulnerabilityQuestions; + private RemoteHearing remoteHearing; + + @JsonProperty("applicant2DQRemoteHearing") + public RemoteHearing getRemoteHearing() { + return remoteHearing; + } + @Override @JsonProperty("applicant2DQFileDirectionsQuestionnaire") public FileDirectionsQuestionnaire getFileDirectionQuestionnaire() { diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/DQ.java b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/DQ.java index ec307cf08c3..ce8b2d3b9ac 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/DQ.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/DQ.java @@ -67,6 +67,8 @@ default SmallClaimHearing getSmallClaimHearing(SmallClaimHearing smallClaimHeari FurtherInformation getFurtherInformation(); + RemoteHearing getRemoteHearing(); + WelshLanguageRequirements getWelshLanguageRequirements(); RemoteHearingLRspec getRemoteHearingLRspec(); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Expert.java b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Expert.java index b2460f9c437..3dd7e0951d1 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Expert.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Expert.java @@ -11,6 +11,7 @@ @Builder(toBuilder = true) public class Expert { + private final String partyID; private final String name; private final String firstName; private final String lastName; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/ExpertDetails.java b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/ExpertDetails.java index 6f01984ce90..61f9f1bc60d 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/ExpertDetails.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/ExpertDetails.java @@ -7,9 +7,10 @@ import java.math.BigDecimal; @Data -@Builder +@Builder(toBuilder = true) public class ExpertDetails { + private final String partyID; private final String expertName; private final String firstName; private final String lastName; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/RemoteHearing.java b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/RemoteHearing.java new file mode 100644 index 00000000000..05bb53133be --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/RemoteHearing.java @@ -0,0 +1,15 @@ +package uk.gov.hmcts.reform.civil.model.dq; + +import lombok.Builder; +import lombok.Data; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; + +@Data +@Builder(toBuilder = true) + +public class RemoteHearing { + + @Deprecated(forRemoval = true) + private final YesOrNo remoteHearingRequested; + private final String reasonForRemoteHearing; +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Respondent1DQ.java b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Respondent1DQ.java index 1051eebf933..198c2f682e3 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Respondent1DQ.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Respondent1DQ.java @@ -36,6 +36,7 @@ public class Respondent1DQ implements DQ { private Hearing respondent1DQHearingFastClaim; private Document respondent1DQDraftDirections; private RequestedCourt respondent1DQRequestedCourt; + private RemoteHearing respondent1DQRemoteHearing; private RemoteHearingLRspec respondent1DQRemoteHearingLRspec; private HearingSupport respondent1DQHearingSupport; private FurtherInformation respondent1DQFurtherInformation; @@ -211,4 +212,10 @@ public WelshLanguageRequirements getWelshLanguageRequirementsLRspec() { public VulnerabilityQuestions getVulnerabilityQuestions() { return respondent1DQVulnerabilityQuestions; } + + @Override + @JsonProperty("respondent1DQRemoteHearing") + public RemoteHearing getRemoteHearing() { + return respondent1DQRemoteHearing; + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Respondent2DQ.java b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Respondent2DQ.java index 3fadd378414..fcc36003bd7 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Respondent2DQ.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Respondent2DQ.java @@ -33,6 +33,8 @@ public class Respondent2DQ implements DQ { private SmallClaimHearing respondent2DQHearingSmallClaim; private Document respondent2DQDraftDirections; private RequestedCourt respondent2DQRequestedCourt; + + private RemoteHearing respondent2DQRemoteHearing; private RemoteHearingLRspec respondent2DQRemoteHearingLRspec; private HearingSupport respondent2DQHearingSupport; private YesOrNo respondent2DQCarerAllowanceCredit; @@ -174,4 +176,10 @@ public VulnerabilityQuestions getVulnerabilityQuestions() { public WelshLanguageRequirements getWelshLanguageRequirementsLRspec() { return respondent2DQLanguageLRspec; } + + @Override + @JsonProperty("respondent2DQRemoteHearing") + public RemoteHearing getRemoteHearing() { + return respondent2DQRemoteHearing; + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Witness.java b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Witness.java index c359608e116..e3ab4102dc0 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Witness.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/dq/Witness.java @@ -9,6 +9,7 @@ @Builder (toBuilder = true) public class Witness { + private final String partyID; @Deprecated private final String name; private final String firstName; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/AppealGrantedRefused.java b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/AppealGrantedRefused.java index 36c81ea4f27..ed46f5ab5ca 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/AppealGrantedRefused.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/AppealGrantedRefused.java @@ -4,6 +4,7 @@ import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; +import uk.gov.hmcts.reform.civil.enums.finalorders.ApplicationAppealList; @Data @Builder(toBuilder = true) @@ -13,4 +14,6 @@ public class AppealGrantedRefused { private AppealChoiceSecondDropdown appealChoiceSecondDropdownA; private AppealChoiceSecondDropdown appealChoiceSecondDropdownB; + private ApplicationAppealList circuitOrHighCourtList; + private ApplicationAppealList circuitOrHighCourtListRefuse; } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/AssistedOrderCostDetails.java b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/AssistedOrderCostDetails.java index 33faee68da8..f155ce3dd26 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/AssistedOrderCostDetails.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/AssistedOrderCostDetails.java @@ -1,12 +1,15 @@ package uk.gov.hmcts.reform.civil.model.finalorders; +import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.enums.finalorders.CostEnums; +import java.math.BigDecimal; import java.time.LocalDate; @Data @@ -21,4 +24,13 @@ public class AssistedOrderCostDetails { @JsonProperty("makeAnOrderForCostsQOCSYesOrNo") private YesOrNo makeAnOrderForCostsYesOrNo; private String besPokeCostDetailsText; + private CostEnums makeAnOrderForCostsList; + private CostEnums assistedOrderClaimantDefendantFirstDropdown; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private BigDecimal assistedOrderCostsFirstDropdownAmount; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private BigDecimal assistedOrderAssessmentThirdDropdownAmount; + private CostEnums assistedOrderAssessmentSecondDropdownList1; + private CostEnums assistedOrderAssessmentSecondDropdownList2; + } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/ClaimantAndDefendantHeard.java b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/ClaimantAndDefendantHeard.java index 664a65d3282..1aa8e57cd03 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/ClaimantAndDefendantHeard.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/ClaimantAndDefendantHeard.java @@ -14,9 +14,13 @@ public class ClaimantAndDefendantHeard { private FinalOrdersClaimantRepresentationList typeRepresentationClaimantList; + private FinalOrdersClaimantRepresentationList typeRepresentationClaimantListTwo; private TrialNoticeProcedure trialProcedureClaimantComplex; private FinalOrdersDefendantRepresentationList typeRepresentationDefendantList; + private FinalOrdersDefendantRepresentationList typeRepresentationDefendantTwoList; private TrialNoticeProcedure trialProcedureComplex; + private TrialNoticeProcedure trialProcedureDefTwoComplex; + private TrialNoticeProcedure trialProcedClaimTwoComplex; private String detailsRepresentationText; private String typeRepresentationClaimantOneDynamic; private String typeRepresentationClaimantTwoDynamic; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/DatesFinalOrders.java b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/DatesFinalOrders.java index 3821ee9efab..d308d99dcd2 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/DatesFinalOrders.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/DatesFinalOrders.java @@ -17,5 +17,6 @@ public class DatesFinalOrders { private LocalDate dateRangeFrom; private LocalDate dateRangeTo; private LocalDate datesToAvoidDates; + private String bespokeRangeTextArea; } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/FinalOrderAppeal.java b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/FinalOrderAppeal.java index 79283e45adf..fa76be671e0 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/FinalOrderAppeal.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/FinalOrderAppeal.java @@ -16,5 +16,6 @@ public class FinalOrderAppeal { private AppealList list; private String otherText; private ApplicationAppealList applicationList; - private AppealGrantedRefused appealGrantedRefusedDropdown; + private AppealGrantedRefused appealGrantedDropdown; + private AppealGrantedRefused appealRefusedDropdown; } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/FinalOrderRepresentation.java b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/FinalOrderRepresentation.java index 33ea7592ddc..01eec5cf72a 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/FinalOrderRepresentation.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/FinalOrderRepresentation.java @@ -5,9 +5,6 @@ import lombok.Data; import lombok.NoArgsConstructor; import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrderRepresentationList; -import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersJudgePapers; - -import java.util.List; @Data @Builder(toBuilder = true) @@ -18,5 +15,4 @@ public class FinalOrderRepresentation { private FinalOrderRepresentationList typeRepresentationList; private ClaimantAndDefendantHeard typeRepresentationComplex; private ClaimantAndDefendantHeard typeRepresentationOtherComplex; - private List typeRepresentationJudgePapersList; } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/OrderMade.java b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/OrderMade.java index 82242b8f932..60f157331e8 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/OrderMade.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/OrderMade.java @@ -13,6 +13,7 @@ public class OrderMade { private DatesFinalOrders singleDateSelection; private DatesFinalOrders dateRangeSelection; + private DatesFinalOrders bespokeRangeSelection; } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/TrialNoticeProcedure.java b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/TrialNoticeProcedure.java index d8d556af2a0..5f10b9d9647 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/TrialNoticeProcedure.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/finalorders/TrialNoticeProcedure.java @@ -13,5 +13,7 @@ public class TrialNoticeProcedure { private FinalOrdersClaimantDefendantNotAttending list; + private FinalOrdersClaimantDefendantNotAttending listClaimTwo; private FinalOrdersClaimantDefendantNotAttending listDef; + private FinalOrdersClaimantDefendantNotAttending listDefTwo; } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/genapplication/CaseLocationCivil.java b/src/main/java/uk/gov/hmcts/reform/civil/model/genapplication/CaseLocationCivil.java index edc224ba820..20bc4d13f5a 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/model/genapplication/CaseLocationCivil.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/genapplication/CaseLocationCivil.java @@ -14,4 +14,6 @@ public class CaseLocationCivil { private String region; private String siteName; private String baseLocation; + private String address; + private String postcode; } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentInstalmentDetails.java b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentInstalmentDetails.java new file mode 100644 index 00000000000..5ee21faea66 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentInstalmentDetails.java @@ -0,0 +1,19 @@ +package uk.gov.hmcts.reform.civil.model.judgmentonline; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; + +@Data +@Builder(toBuilder = true) +@NoArgsConstructor +@AllArgsConstructor +public class JudgmentInstalmentDetails { + + private String instalmentAmount; + private PaymentFrequency paymentFrequency; + private LocalDate firstInstalmentDate; +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentPaidInFull.java b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentPaidInFull.java new file mode 100644 index 00000000000..5e98a2cd895 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentPaidInFull.java @@ -0,0 +1,19 @@ +package uk.gov.hmcts.reform.civil.model.judgmentonline; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; +import java.util.List; + +@Data +@Builder(toBuilder = true) +@NoArgsConstructor +@AllArgsConstructor +public class JudgmentPaidInFull { + + private LocalDate dateOfFullPaymentMade; + private List confirmFullPaymentMade; +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentRTLStatus.java b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentRTLStatus.java new file mode 100644 index 00000000000..bc28c7672ab --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentRTLStatus.java @@ -0,0 +1,18 @@ +package uk.gov.hmcts.reform.civil.model.judgmentonline; + +public enum JudgmentRTLStatus { + REGISTRATION("R"), + CANCELLATION("C"), + SATISFACTION("S"), + MODIFIED("M"); + + private String rtlState; + + JudgmentRTLStatus(String rtlState) { + this.rtlState = rtlState; + } + + public String getRtlState() { + return rtlState; + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentRecordedReason.java b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentRecordedReason.java new file mode 100644 index 00000000000..f6ab0d8d390 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentRecordedReason.java @@ -0,0 +1,6 @@ +package uk.gov.hmcts.reform.civil.model.judgmentonline; + +public enum JudgmentRecordedReason { + DETERMINATION_OF_MEANS, + JUDGE_ORDER +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentStatusDetails.java b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentStatusDetails.java new file mode 100644 index 00000000000..95ff71895ff --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentStatusDetails.java @@ -0,0 +1,19 @@ +package uk.gov.hmcts.reform.civil.model.judgmentonline; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Builder(toBuilder = true) +@NoArgsConstructor +@AllArgsConstructor +public class JudgmentStatusDetails { + + private JudgmentStatusType judgmentStatusTypes; + private LocalDateTime lastUpdatedDate; + private String joRtlState; +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentStatusType.java b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentStatusType.java new file mode 100644 index 00000000000..1bd0d66a2c1 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/JudgmentStatusType.java @@ -0,0 +1,10 @@ +package uk.gov.hmcts.reform.civil.model.judgmentonline; + +public enum JudgmentStatusType { + REQUESTED, + ISSUED, + MODIFIED, + SET_ASIDE, + CANCELLED, + SATISFIED +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/PaymentFrequency.java b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/PaymentFrequency.java new file mode 100644 index 00000000000..880e9cf0398 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/PaymentFrequency.java @@ -0,0 +1,7 @@ +package uk.gov.hmcts.reform.civil.model.judgmentonline; + +public enum PaymentFrequency { + MONTHLY, + EVERY_TWO_WEEKS, + WEEKLY; +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/PaymentPlanSelection.java b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/PaymentPlanSelection.java new file mode 100644 index 00000000000..a2bedebfba3 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/judgmentonline/PaymentPlanSelection.java @@ -0,0 +1,7 @@ +package uk.gov.hmcts.reform.civil.model.judgmentonline; + +public enum PaymentPlanSelection { + PAY_IN_INSTALMENTS, + PAY_BY_DATE, + PAY_IMMEDIATELY +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/repaymentplan/ClaimantProposedPlan.java b/src/main/java/uk/gov/hmcts/reform/civil/model/repaymentplan/ClaimantProposedPlan.java new file mode 100644 index 00000000000..c325b34b416 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/repaymentplan/ClaimantProposedPlan.java @@ -0,0 +1,56 @@ +package uk.gov.hmcts.reform.civil.model.repaymentplan; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Builder; +import lombok.Data; +import uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec; +import uk.gov.hmcts.reform.civil.model.RepaymentPlanLRspec; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.Optional; + +import static uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec.BY_SET_DATE; +import static uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec.IMMEDIATELY; +import static uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec.SUGGESTION_OF_REPAYMENT_PLAN; +import static uk.gov.hmcts.reform.civil.utils.MonetaryConversions.penniesToPounds; +import static uk.gov.hmcts.reform.civil.utils.PaymentFrequencyCalculator.calculatePaymentPerMonth; + +@Data +@Builder +public class ClaimantProposedPlan { + + private RepaymentPlanLRspec repaymentPlanLRspec; + private RespondentResponsePartAdmissionPaymentTimeLRspec proposedRepaymentType; + private LocalDate repaymentByDate; + + @JsonIgnore + public LocalDate getRepaymentDate(BigDecimal totalClaimAmount) { + return Optional.ofNullable(repaymentPlanLRspec).map(repaymentPlan -> repaymentPlan.finalPaymentBy(totalClaimAmount)) + .orElse(repaymentByDate); + } + + @JsonIgnore + public double getCalculatedPaymentPerMonthFromRepaymentPlan() { + return calculatePaymentPerMonth( + penniesToPounds(repaymentPlanLRspec.getPaymentAmount()).doubleValue(), + repaymentPlanLRspec.getRepaymentFrequency() + ); + } + + @JsonIgnore + public boolean hasProposedPayImmediately() { + return IMMEDIATELY == proposedRepaymentType; + } + + @JsonIgnore + public boolean hasProposedPayBySetDate() { + return BY_SET_DATE == proposedRepaymentType; + } + + @JsonIgnore + public boolean hasProposedPayByInstallments() { + return SUGGESTION_OF_REPAYMENT_PLAN == proposedRepaymentType; + } + +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/transferonlinecase/NotSuitableSdoOptions.java b/src/main/java/uk/gov/hmcts/reform/civil/model/transferonlinecase/NotSuitableSdoOptions.java new file mode 100644 index 00000000000..6b61911868d --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/transferonlinecase/NotSuitableSdoOptions.java @@ -0,0 +1,9 @@ +package uk.gov.hmcts.reform.civil.model.transferonlinecase; + +import lombok.Getter; + +@Getter +public enum NotSuitableSdoOptions { + CHANGE_LOCATION, + OTHER_REASONS +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/transferonlinecase/TocTransferCaseReason.java b/src/main/java/uk/gov/hmcts/reform/civil/model/transferonlinecase/TocTransferCaseReason.java new file mode 100644 index 00000000000..df2805c0e69 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/transferonlinecase/TocTransferCaseReason.java @@ -0,0 +1,15 @@ +package uk.gov.hmcts.reform.civil.model.transferonlinecase; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder(toBuilder = true) +@NoArgsConstructor +@AllArgsConstructor +public class TocTransferCaseReason { + + private String reasonForCaseTransferJudgeTxt; +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/model/transferonlinecase/TransferCaseDetails.java b/src/main/java/uk/gov/hmcts/reform/civil/model/transferonlinecase/TransferCaseDetails.java new file mode 100644 index 00000000000..09a3a38aa03 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/model/transferonlinecase/TransferCaseDetails.java @@ -0,0 +1,15 @@ +package uk.gov.hmcts.reform.civil.model.transferonlinecase; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder(toBuilder = true) +@NoArgsConstructor +@AllArgsConstructor +public class TransferCaseDetails { + + private String reasonForTransferCaseTxt; +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadApplicantNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadApplicantNotificationHandler.java index 5a5c2c8e67d..06d1bcbee18 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadApplicantNotificationHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadApplicantNotificationHandler.java @@ -11,6 +11,8 @@ import java.util.Map; +import static java.util.Objects.nonNull; + @Service @RequiredArgsConstructor public class EvidenceUploadApplicantNotificationHandler implements NotificationData { @@ -24,12 +26,14 @@ public void notifyApplicantEvidenceUpload(CaseData caseData) throws Notification boolean isApplicantLip = isApplicantLip(caseData); //Send email to Applicant - notificationService.sendMail( - getEmail(caseData, isApplicantLip), - getTemplate(caseData, isApplicantLip), - addProperties(caseData), - getReference(caseData) - ); + if (nonNull(caseData.getNotificationText()) && !caseData.getNotificationText().equals("NULLED")) { + notificationService.sendMail( + getEmail(caseData, isApplicantLip), + getTemplate(caseData, isApplicantLip), + addProperties(caseData), + getReference(caseData) + ); + } } private static String getReference(CaseData caseData) { @@ -53,7 +57,8 @@ private boolean isApplicantLip(CaseData caseData) { @Override public Map addProperties(CaseData caseData) { return Map.of( - CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference() + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + UPLOADED_DOCUMENTS, caseData.getNotificationText() ); } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadRespondentNotificationHandler.java b/src/main/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadRespondentNotificationHandler.java index eb6758fa47c..a8a7dc43178 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadRespondentNotificationHandler.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadRespondentNotificationHandler.java @@ -11,6 +11,7 @@ import java.util.Map; +import static java.util.Objects.nonNull; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; @Service @@ -41,7 +42,7 @@ public void notifyRespondentEvidenceUpload(CaseData caseData, boolean isForRespo isRespondentLip = true; } - if (null != email) { + if (null != email && nonNull(caseData.getNotificationText()) && !caseData.getNotificationText().equals("NULLED")) { notificationService.sendMail( email, getTemplate(isRespondentLip), @@ -62,7 +63,8 @@ public String getTemplate(boolean isRespondentLip) { @Override public Map addProperties(CaseData caseData) { return Map.of( - CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference() - ); + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + UPLOADED_DOCUMENTS, caseData.getNotificationText() + ); } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/CaseNoteService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/CaseNoteService.java index f98a37f68e4..4c6f63654eb 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/CaseNoteService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/CaseNoteService.java @@ -7,7 +7,6 @@ import uk.gov.hmcts.reform.idam.client.IdamClient; import uk.gov.hmcts.reform.idam.client.models.UserDetails; -import java.time.LocalDateTime; import java.util.List; import static com.google.common.collect.Lists.newArrayList; @@ -19,21 +18,29 @@ public class CaseNoteService { private final IdamClient idamClient; + private final Time time; public CaseNote buildCaseNote(String authorisation, String note) { UserDetails userDetails = idamClient.getUserDetails(authorisation); return CaseNote.builder() .createdBy(userDetails.getFullName()) - .createdOn(LocalDateTime.now()) + .createdOn(time.now()) .note(note) .build(); } - public List> addNoteToList(CaseNote caseNote, List> caseNotes) { + public List> addNoteToListStart(CaseNote caseNote, List> caseNotes) { List> updatedCaseNotes = ofNullable(caseNotes).orElse(newArrayList()); updatedCaseNotes.add(0, element(caseNote)); return updatedCaseNotes; } + + public List> addNoteToListEnd(CaseNote caseNote, List> caseNotes) { + List> updatedCaseNotes = ofNullable(caseNotes).orElse(newArrayList()); + updatedCaseNotes.add(element(caseNote)); + + return updatedCaseNotes; + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/FeatureToggleService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/FeatureToggleService.java index bb9cea58385..f4aa4bc5382 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/FeatureToggleService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/FeatureToggleService.java @@ -71,4 +71,21 @@ public boolean isUpdateContactDetailsEnabled() { public boolean isLipVLipEnabled() { return featureToggleApi.isFeatureEnabled("cuiReleaseTwoEnabled"); } + + public boolean isLocationWhiteListedForCaseProgression(String locationEpimms) { + return featureToggleApi.isFeatureEnabledForLocation("case-progression-location-whitelist", locationEpimms, + true); + } + + public boolean isTransferOnlineCaseEnabled() { + return featureToggleApi.isFeatureEnabled("isTransferOnlineCaseEnabled"); + } + + public boolean isCaseProgressionEnabled() { + return featureToggleApi.isFeatureEnabled("cui-case-progression"); + } + + public boolean isEarlyAdoptersEnabled() { + return featureToggleApi.isFeatureEnabled("early-adopters"); + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/GenAppStateHelperService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/GenAppStateHelperService.java index 2569a7ad87b..f0d0abaf206 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/GenAppStateHelperService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/GenAppStateHelperService.java @@ -14,6 +14,7 @@ import uk.gov.hmcts.reform.civil.model.genapplication.GADetailsRespondentSol; import uk.gov.hmcts.reform.civil.model.genapplication.GeneralApplication; import uk.gov.hmcts.reform.civil.model.genapplication.GeneralApplicationsDetails; +import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; import java.util.ArrayList; import java.util.HashMap; @@ -31,6 +32,7 @@ public class GenAppStateHelperService { private final CoreCaseDataService coreCaseDataService; private final CaseDetailsConverter caseDetailsConverter; + private final InitiateGeneralApplicationService genAppService; private final ObjectMapper objectMapper; @@ -69,16 +71,19 @@ public boolean triggerEvent(CaseData caseData, CaseEvent event) { return true; } - public CaseData updateApplicationLocationDetailsInClaim(CaseData caseData) { + public CaseData updateApplicationLocationDetailsInClaim(CaseData caseData, String authToken) { if (!Collections.isEmpty(caseData.getGeneralApplications())) { List genApps = new ArrayList<>(); CaseData finalCaseData = caseData; + LocationRefData locationDetails = genAppService.getWorkAllocationLocationDetails(finalCaseData.getCaseManagementLocation().getBaseLocation(), authToken); caseData.getGeneralApplications().forEach(generalApplicationElement -> { GeneralApplication generalApplication = generalApplicationElement.getValue(); generalApplication.getCaseManagementLocation().setBaseLocation(finalCaseData.getCaseManagementLocation().getBaseLocation()); generalApplication.getCaseManagementLocation().setRegion(finalCaseData.getCaseManagementLocation().getRegion()); - generalApplication.getCaseManagementLocation().setSiteName(finalCaseData.getLocationName()); + generalApplication.getCaseManagementLocation().setSiteName(locationDetails.getSiteName()); + generalApplication.getCaseManagementLocation().setAddress(locationDetails.getCourtAddress()); + generalApplication.getCaseManagementLocation().setPostcode(locationDetails.getPostcode()); Map genAppMap = generalApplication.toMap(objectMapper); genAppMap.put("isCcmccLocation", YesOrNo.NO); generalApplication = objectMapper.convertValue(genAppMap, GeneralApplication.class); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/GeneralAppFeesService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/GeneralAppFeesService.java index ec252f3c5eb..889de7d1e51 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/GeneralAppFeesService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/GeneralAppFeesService.java @@ -52,7 +52,7 @@ public class GeneralAppFeesService { protected static final List ADJOURN_TYPES = List.of(GeneralApplicationTypes.ADJOURN_HEARING); protected static final List SD_CONSENT_TYPES - = List.of(GeneralApplicationTypes.SETTLE_OR_DISCONTINUE_CONSENT); + = List.of(GeneralApplicationTypes.SETTLE_BY_CONSENT); public Fee getFeeForGA(CaseData caseData) { Fee result = Fee.builder().calculatedAmountInPence(BigDecimal.valueOf(Integer.MAX_VALUE)).build(); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/InitiateGeneralApplicationService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/InitiateGeneralApplicationService.java index cd60c0cb9a8..f70a80f9ad5 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/InitiateGeneralApplicationService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/InitiateGeneralApplicationService.java @@ -4,10 +4,6 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; import org.springframework.stereotype.Service; -import uk.gov.hmcts.reform.authorisation.generators.AuthTokenGenerator; -import uk.gov.hmcts.reform.ccd.client.CaseAccessDataStoreApi; -import uk.gov.hmcts.reform.ccd.model.CaseAssignedUserRolesResource; -import uk.gov.hmcts.reform.civil.config.CrossAccessUserConfiguration; import uk.gov.hmcts.reform.civil.documentmanagement.model.Document; import uk.gov.hmcts.reform.civil.enums.CaseCategory; import uk.gov.hmcts.reform.civil.enums.CaseState; @@ -32,9 +28,9 @@ import uk.gov.hmcts.reform.civil.model.genapplication.GAUnavailabilityDates; import uk.gov.hmcts.reform.civil.model.genapplication.GAUrgencyRequirement; import uk.gov.hmcts.reform.civil.model.genapplication.GeneralApplication; -import uk.gov.hmcts.reform.civil.prd.client.OrganisationApi; import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; +import uk.gov.hmcts.reform.civil.utils.UserRoleCaching; import uk.gov.hmcts.reform.idam.client.models.UserDetails; import java.time.LocalDate; @@ -62,6 +58,8 @@ import static uk.gov.hmcts.reform.civil.model.Party.Type.INDIVIDUAL; import static uk.gov.hmcts.reform.civil.model.Party.Type.SOLE_TRADER; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.element; +import static uk.gov.hmcts.reform.civil.utils.UserRoleUtils.isRespondentSolicitorOne; +import static uk.gov.hmcts.reform.civil.utils.UserRoleUtils.isRespondentSolicitorTwo; @Service @RequiredArgsConstructor @@ -71,14 +69,8 @@ public class InitiateGeneralApplicationService { private final InitiateGeneralApplicationServiceHelper helper; private final GeneralAppsDeadlinesCalculator deadlinesCalculator; - private final CaseAccessDataStoreApi caseAccessDataStoreApi; - private final UserService userService; - private final CrossAccessUserConfiguration crossAccessUserConfiguration; - - private final OrganisationApi organisationApi; - private final AuthTokenGenerator authTokenGenerator; + private final UserRoleCaching userRoleCaching; private final LocationRefDataService locationRefDataService; - private final FeatureToggleService featureToggleService; private static final int NUMBER_OF_DEADLINE_DAYS = 5; public static final String GA_DOC_CATEGORY_ID = "applications"; @@ -95,7 +87,7 @@ public class InitiateGeneralApplicationService { + "you must provide at least one valid Date from"; public static final String INVALID_UNAVAILABILITY_RANGE = "Unavailability Date From cannot be after " + "Unavailability Date to. Please enter valid range."; - public static final String INVALID_SETTLE_OR_DISCONTINUE_CONSENT = "Settle or Discontinue by consent " + + public static final String INVALID_SETTLE_BY_CONSENT = "Settle by consent " + "must have been agreed with the respondent " + "before raising the application"; @@ -115,6 +107,8 @@ public CaseData buildCaseData(CaseData.CaseDataBuilder dataBuilder, CaseData cas .generalAppPBADetails(GAPbaDetails.builder().build()) .generalAppDetailsOfOrder(EMPTY) .generalAppReasonsOfOrder(EMPTY) + .generalAppParentClaimantIsApplicant(null) + .generalAppVaryJudgementType(null) .generalAppN245FormUpload(Document.builder().build()) .generalAppHearingDate(GAHearingDateGAspec.builder().build()) .generalAppInformOtherParty(GAInformOtherParty.builder().build()) @@ -185,6 +179,13 @@ private GeneralApplication buildApplication(CaseData.CaseDataBuilder dataBuilder Pair caseLocation = getWorkAllocationLocation(caseData, authToken); //Setting Work Allocation location and location name + if (Objects.isNull(caseLocation.getLeft().getSiteName()) + && Objects.nonNull(caseLocation.getLeft().getBaseLocation())) { + LocationRefData locationDetails = getWorkAllocationLocationDetails(caseLocation.getLeft().getBaseLocation(), authToken); + caseLocation.getLeft().setSiteName(locationDetails.getSiteName()); + caseLocation.getLeft().setAddress(locationDetails.getCourtAddress()); + caseLocation.getLeft().setPostcode(locationDetails.getPostcode()); + } applicationBuilder.caseManagementLocation(caseLocation.getLeft()); applicationBuilder.isCcmccLocation(caseLocation.getRight() ? YES : NO); applicationBuilder.locationName(hasSDOBeenMade(caseData.getCcdState()) @@ -301,35 +302,16 @@ private void validateUnavailableDates(List errors, } } - public boolean respondentAssigned(CaseData caseData) { + public boolean respondentAssigned(CaseData caseData, String authToken) { String caseId = caseData.getCcdCaseReference().toString(); - CaseAssignedUserRolesResource userRoles = getUserRolesOnCase(caseId); + List userRoles = userRoleCaching.getUserRoles(authToken, caseId); List respondentCaseRoles = getRespondentCaseRoles(caseData); - - for (String respondentCaseRole : respondentCaseRoles) { - if (userRoles.getCaseAssignedUserRoles() == null - || userRoles.getCaseAssignedUserRoles().stream() - .noneMatch(a -> a.getCaseRole() != null && respondentCaseRole.equals(a.getCaseRole()))) { - return false; - } - } - return true; + return !(userRoles.isEmpty() || !isRespondentSolicitorOne(respondentCaseRoles) + || (respondentCaseRoles.size() > 1 && !isRespondentSolicitorTwo(respondentCaseRoles))); } - public boolean isGAApplicantSameAsParentCaseClaimant(CaseData caseData, UserDetails userDetails) { - return helper.isGAApplicantSameAsParentCaseClaimant(caseData, userDetails); - } - - private CaseAssignedUserRolesResource getUserRolesOnCase(String caseId) { - String accessToken = userService.getAccessToken( - crossAccessUserConfiguration.getUserName(), - crossAccessUserConfiguration.getPassword() - ); - return caseAccessDataStoreApi.getUserRoles( - accessToken, - authTokenGenerator.generate(), - List.of(caseId) - ); + public boolean isGAApplicantSameAsParentCaseClaimant(CaseData caseData, String authToken) { + return helper.isGAApplicantSameAsParentCaseClaimant(caseData, authToken); } private List getRespondentCaseRoles(CaseData caseData) { @@ -368,6 +350,8 @@ public Pair getWorkAllocationLocation(CaseData caseD .region(ccmccLocation.getRegionId()) .baseLocation(ccmccLocation.getEpimmsId()) .siteName(ccmccLocation.getSiteName()) + .address(ccmccLocation.getCourtAddress()) + .postcode(ccmccLocation.getPostcode()) .build(); return Pair.of(courtLocation, true); } @@ -394,6 +378,15 @@ private CaseLocationCivil getClaimant1PreferredLocation(CaseData caseData) { .build(); } + public LocationRefData getWorkAllocationLocationDetails(String baseLocation, String authToken) { + List locationDetails = locationRefDataService.getCourtLocationsByEpimmsId(authToken, baseLocation); + if (locationDetails != null && !locationDetails.isEmpty()) { + return locationDetails.get(0); + } else { + return LocationRefData.builder().build(); + } + } + private boolean isDefendant1RespondedFirst(CaseData caseData) { return caseData.getRespondent2ResponseDate() == null || (caseData.getRespondent1ResponseDate() != null diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/InitiateGeneralApplicationServiceHelper.java b/src/main/java/uk/gov/hmcts/reform/civil/service/InitiateGeneralApplicationServiceHelper.java index a0071a7879b..d6d35fe839d 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/InitiateGeneralApplicationServiceHelper.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/InitiateGeneralApplicationServiceHelper.java @@ -13,6 +13,8 @@ import uk.gov.hmcts.reform.civil.model.common.Element; import uk.gov.hmcts.reform.civil.model.genapplication.GASolicitorDetailsGAspec; import uk.gov.hmcts.reform.civil.model.genapplication.GeneralApplication; +import uk.gov.hmcts.reform.civil.utils.UserRoleCaching; +import uk.gov.hmcts.reform.civil.utils.UserRoleUtils; import uk.gov.hmcts.reform.idam.client.models.UserDetails; import java.util.ArrayList; @@ -33,6 +35,7 @@ public class InitiateGeneralApplicationServiceHelper { private final CaseAccessDataStoreApi caseAccessDataStoreApi; + private final UserRoleCaching userRoleCaching; private final AuthTokenGenerator authTokenGenerator; private final UserService userService; private final CrossAccessUserConfiguration crossAccessUserConfiguration; @@ -228,24 +231,20 @@ public String getApplicantPartyName(CaseAssignedUserRolesResource userRoles, Use return EMPTY; } - public boolean isGAApplicantSameAsParentCaseClaimant(CaseData caseData, UserDetails userDetails) { + public boolean isGAApplicantSameAsParentCaseClaimant(CaseData caseData, String authToken) { String parentCaseId = caseData.getCcdCaseReference().toString(); + List userRolesCaching = userRoleCaching.getUserRoles(authToken, parentCaseId); - CaseAssignedUserRolesResource userRoles = getUserRoles(parentCaseId); - - List applicantSolicitor = getApplicantSolicitor(userRoles, userDetails); + boolean isApplicantSolicitor = UserRoleUtils.isApplicantSolicitor(userRolesCaching); String applicant1OrgCaseRole = caseData.getApplicant1OrganisationPolicy().getOrgPolicyCaseAssignedRole(); - if (!CollectionUtils.isEmpty(applicantSolicitor) && applicantSolicitor.size() == 1) { - - CaseAssignedUserRole applnSol = applicantSolicitor.get(0); + if (!CollectionUtils.isEmpty(userRolesCaching) && userRolesCaching.size() == 1 && isApplicantSolicitor) { - if (applnSol.getCaseRole() != null) { + String applnSol = userRolesCaching.get(0); - if (applnSol.getCaseRole().equals(applicant1OrgCaseRole)) { - return true; - } + if (applnSol != null && applnSol.equals(applicant1OrgCaseRole)) { + return true; } } @@ -257,13 +256,6 @@ public CaseAssignedUserRolesResource getUserRoles(String parentCaseId) { getCaaAccessToken(), authTokenGenerator.generate(), List.of(parentCaseId)); } - public List getApplicantSolicitor(CaseAssignedUserRolesResource userRoles, - UserDetails userDetails) { - return userRoles.getCaseAssignedUserRoles().stream() - .filter(CA -> CA.getUserId().equals(userDetails.getId())) - .collect(Collectors.toList()); - } - public String getCaaAccessToken() { return userService.getAccessToken( crossAccessUserConfiguration.getUserName(), diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/JudgementService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/JudgementService.java index f585e3836a7..3917b350b4d 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/JudgementService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/JudgementService.java @@ -31,8 +31,11 @@ public CCJPaymentDetails buildJudgmentAmountSummaryDetails(CaseData caseData) { .ccjJudgmentAmountInterestToDate(ccjJudgmentInterest(caseData)) .ccjPaymentPaidSomeAmountInPounds(ccjJudgmentPaidAmount(caseData)) .ccjJudgmentFixedCostAmount(ccjJudgmentFixedCost(caseData)) - .ccjJudgmentFixedCostOption(caseData.getCcjPaymentDetails().getCcjJudgmentFixedCostOption()) + .ccjJudgmentFixedCostOption(caseData.getCcjPaymentDetails() + .getCcjJudgmentFixedCostOption()) .ccjJudgmentStatement(ccjJudgmentStatement(caseData)) + .ccjPaymentPaidSomeOption(caseData.getCcjPaymentDetails().getCcjPaymentPaidSomeOption()) + .ccjJudgmentLipInterest(caseData.getCcjPaymentDetails().getCcjJudgmentLipInterest()) .build(); } @@ -53,7 +56,8 @@ private BigDecimal ccjJudgmentClaimAmount(CaseData caseData) { } private BigDecimal ccjJudgmentClaimFee(CaseData caseData) { - return MonetaryConversions.penniesToPounds(caseData.getClaimFee().getCalculatedAmountInPence()); + return caseData.isLipvLipOneVOne() ? caseData.getCcjPaymentDetails().getCcjJudgmentAmountClaimFee() : + MonetaryConversions.penniesToPounds(caseData.getClaimFee().getCalculatedAmountInPence()); } private BigDecimal ccjJudgmentPaidAmount(CaseData caseData) { @@ -66,13 +70,14 @@ private BigDecimal ccjJudgmentFixedCost(CaseData caseData) { } private BigDecimal ccjJudgmentInterest(CaseData caseData) { - return caseData.getTotalInterest(); + return caseData.isLipvLipOneVOne() ? caseData.getCcjPaymentDetails().getCcjJudgmentLipInterest() : + caseData.getTotalInterest(); } private BigDecimal ccjJudgementSubTotal(CaseData caseData) { return ccjJudgmentClaimAmount(caseData) .add(ccjJudgmentClaimFee(caseData)) - .add(caseData.getTotalInterest()) + .add(ccjJudgmentInterest(caseData)) .add(ccjJudgmentFixedCost(caseData)); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/OrganisationDetailsService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/OrganisationDetailsService.java index 43ce135e229..03b9e801d48 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/OrganisationDetailsService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/OrganisationDetailsService.java @@ -18,4 +18,13 @@ public String getApplicantLegalOrganizationName(CaseData caseData) { return organisation.map(Organisation::getName).orElse(caseData.getApplicantSolicitor1ClaimStatementOfTruth().getName()); } + public String getRespondentLegalOrganizationName(CaseData caseData) { + Optional organisation = organisationService.findOrganisationById( + caseData.getRespondent1OrganisationId()); + String respondentLegalOrganizationName = null; + if (organisation.isPresent()) { + respondentLegalOrganizationName = organisation.get().getName(); + } + return respondentLegalOrganizationName; + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/SendSDOBulkPrintService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/SendSDOBulkPrintService.java index 0d5a8052915..01bb544ac5e 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/SendSDOBulkPrintService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/SendSDOBulkPrintService.java @@ -23,7 +23,7 @@ public class SendSDOBulkPrintService { private final DocumentDownloadService documentDownloadService; private static final String SDO_ORDER_PACK_LETTER_TYPE = "sdo-order-pack"; - public void sendSDOToDefendantLIP(CaseData caseData) { + public void sendSDOToDefendantLIP(String authorisation, CaseData caseData) { if (caseData.getSystemGeneratedCaseDocuments() != null && !caseData.getSystemGeneratedCaseDocuments().isEmpty()) { Optional> caseDocument = caseData.getSDODocument(); @@ -32,7 +32,7 @@ public void sendSDOToDefendantLIP(CaseData caseData) { String documentId = documentUrl.substring(documentUrl.lastIndexOf("/") + 1); byte[] letterContent; try { - letterContent = documentDownloadService.downloadDocument(documentId).file().getInputStream().readAllBytes(); + letterContent = documentDownloadService.downloadDocument(authorisation, documentId).file().getInputStream().readAllBytes(); } catch (IOException e) { log.error("Failed getting letter content for SDO "); throw new DocumentDownloadException(caseDocument.get().getValue().getDocumentName(), e); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/SystemGeneratedDocumentService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/SystemGeneratedDocumentService.java index b5e8945298b..9b9a958aa32 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/SystemGeneratedDocumentService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/SystemGeneratedDocumentService.java @@ -5,12 +5,12 @@ import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; -import uk.gov.hmcts.reform.civil.documentmanagement.model.Document; -import uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.citizenui.TranslatedDocument; import uk.gov.hmcts.reform.civil.model.common.Element; import java.util.List; +import java.util.Objects; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.element; @@ -18,17 +18,23 @@ @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS) public class SystemGeneratedDocumentService { - public List> getSystemGeneratedDocumentsWithAddedDocument(Document document, DocumentType documentType, CallbackParams callbackParams) { - CaseData caseData = callbackParams.getCaseData(); + public List> getSystemGeneratedDocumentsWithAddedDocument(CaseDocument caseDocument, CaseData caseData) { List> systemGeneratedDocuments = caseData.getSystemGeneratedCaseDocuments(); - CaseDocument caseDocument = CaseDocument.toCaseDocument(document, documentType); systemGeneratedDocuments.add(element(caseDocument)); return systemGeneratedDocuments; } - public List> getSystemGeneratedDocumentsWithAddedDocument(CaseDocument caseDocument, CaseData caseData) { + public List> getSystemGeneratedDocumentsWithAddedDocument(List> translatedDocuments, CallbackParams callbackParams) { + + CaseData caseData = callbackParams.getCaseData(); List> systemGeneratedDocuments = caseData.getSystemGeneratedCaseDocuments(); - systemGeneratedDocuments.add(element(caseDocument)); + if (Objects.nonNull(translatedDocuments)) { + for (Element translateDocument : translatedDocuments) { + CaseDocument caseDocument = CaseDocument.toCaseDocument(translateDocument.getValue().getFile(), translateDocument.getValue().getCorrespondingDocumentType()); + systemGeneratedDocuments.add(element(caseDocument)); + } + } return systemGeneratedDocuments; } + } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/UpdateCaseManagementDetailsService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/UpdateCaseManagementDetailsService.java new file mode 100644 index 00000000000..b37adcba484 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/UpdateCaseManagementDetailsService.java @@ -0,0 +1,118 @@ +package uk.gov.hmcts.reform.civil.service.citizen; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; +import uk.gov.hmcts.reform.civil.helpers.LocationHelper; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.CaseManagementCategory; +import uk.gov.hmcts.reform.civil.model.CaseManagementCategoryElement; +import uk.gov.hmcts.reform.civil.model.common.Element; +import uk.gov.hmcts.reform.civil.model.dq.RequestedCourt; +import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; +import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; +import uk.gov.hmcts.reform.civil.utils.CourtLocationUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static uk.gov.hmcts.reform.civil.callback.CallbackParams.Params.BEARER_TOKEN; +import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.getMultiPartyScenario; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.element; + +@Slf4j +@Service +@RequiredArgsConstructor +public class UpdateCaseManagementDetailsService { + + private final LocationHelper locationHelper; + private final LocationRefDataService locationRefDataService; + private final CourtLocationUtils courtLocationUtils; + + public void updateCaseManagementDetails(CaseData.CaseDataBuilder builder, CallbackParams callbackParams) { + CaseData caseData = callbackParams.getCaseData(); + final List availableLocations = fetchLocationData(callbackParams); + + updateApplicant1RequestedCourtDetails(caseData, builder, availableLocations); + updateRespondent1RequestedCourtDetails(caseData, builder, availableLocations); + + caseData = builder.build(); + locationHelper.getCaseManagementLocation(caseData) + .ifPresent(requestedCourt -> locationHelper.updateCaseManagementLocation( + builder, + requestedCourt, + () -> locationRefDataService.getCourtLocationsForDefaultJudgments(callbackParams.getParams().get( + CallbackParams.Params.BEARER_TOKEN).toString()) + )); + + builder.caseNameHmctsInternal(caseParticipants(caseData).toString()); + + CaseManagementCategoryElement civil = + CaseManagementCategoryElement.builder().code("Civil").label("Civil").build(); + List> itemList = new ArrayList<>(); + itemList.add(element(civil)); + builder.caseManagementCategory( + CaseManagementCategory.builder().value(civil).list_items(itemList).build()); + + } + + private void updateApplicant1RequestedCourtDetails(CaseData caseData, CaseData.CaseDataBuilder builder, List availableLocations) { + Optional.ofNullable(caseData.getApplicant1DQ()) + .ifPresent(dq -> Optional.ofNullable(dq.getApplicant1DQRequestedCourt()) + .ifPresent(requestedCourt -> builder.applicant1DQ( + dq.toBuilder().applicant1DQRequestedCourt(correctCaseLocation(requestedCourt, availableLocations)) + .build()))); + } + + private void updateRespondent1RequestedCourtDetails(CaseData caseData, CaseData.CaseDataBuilder builder, List availableLocations) { + Optional.ofNullable(caseData.getRespondent1DQ()) + .ifPresent(dq -> Optional.ofNullable(dq.getRespondent1DQRequestedCourt()) + .ifPresent(requestedCourt -> builder.respondent1DQ( + dq.toBuilder().respondent1DQRequestedCourt(correctCaseLocation(requestedCourt, availableLocations)) + .build()))); + } + + private RequestedCourt correctCaseLocation(RequestedCourt requestedCourt, List locations) { + String locationLabel = requestedCourt.getCaseLocation().getBaseLocation(); + LocationRefData preferredLocation = locations.stream() + .filter(locationRefData -> courtLocationUtils.checkLocation(locationRefData, locationLabel)) + .findFirst().orElseThrow(RuntimeException::new); + return requestedCourt.toBuilder() + .responseCourtCode(preferredLocation.getCourtLocationCode()) + .caseLocation(LocationHelper.buildCaseLocation(preferredLocation)) + .build(); + } + + private List fetchLocationData(CallbackParams callbackParams) { + String authToken = callbackParams.getParams().get(BEARER_TOKEN).toString(); + return locationRefDataService.getCourtLocationsForDefaultJudgments(authToken); + } + + private StringBuilder caseParticipants(CaseData caseData) { + StringBuilder participantString = new StringBuilder(); + MultiPartyScenario multiPartyScenario = getMultiPartyScenario(caseData); + if (multiPartyScenario.equals(MultiPartyScenario.ONE_V_TWO_ONE_LEGAL_REP) + || multiPartyScenario.equals(MultiPartyScenario.ONE_V_TWO_TWO_LEGAL_REP)) { + participantString.append(caseData.getApplicant1().getPartyName()) + .append(" v ").append(caseData.getRespondent1().getPartyName()) + .append(" and ").append(caseData.getRespondent2().getPartyName()); + + } else if (multiPartyScenario.equals(MultiPartyScenario.TWO_V_ONE)) { + participantString.append(caseData.getApplicant1().getPartyName()) + .append(" and ").append(caseData.getApplicant2().getPartyName()) + .append(" v ") + .append(caseData.getRespondent1().getPartyName()); + + } else { + participantString.append(caseData.getApplicant1().getPartyName()) + .append(" v ") + .append(caseData.getRespondent1().getPartyName()); + } + return participantString; + + } + +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/AllowanceCalculator.java b/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/AllowanceCalculator.java new file mode 100644 index 00000000000..399d1816a0b --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/AllowanceCalculator.java @@ -0,0 +1,113 @@ +package uk.gov.hmcts.reform.civil.service.citizen.repaymentplan; + +import org.springframework.stereotype.Component; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.ChildrenByAgeGroupLRspec; +import uk.gov.hmcts.reform.civil.model.PartnerAndDependentsLRspec; +import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.model.UnemployedComplexTypeLRspec; +import uk.gov.hmcts.reform.civil.model.allowance.DisabilityAllowance; +import uk.gov.hmcts.reform.civil.model.allowance.DisabilityParam; +import uk.gov.hmcts.reform.civil.model.allowance.PensionerAllowance; +import uk.gov.hmcts.reform.civil.model.allowance.PersonalAllowance; +import uk.gov.hmcts.reform.civil.model.citizenui.FinancialDetailsLiP; +import uk.gov.hmcts.reform.civil.model.dq.Respondent1DQ; + +import java.time.LocalDate; +import java.time.Period; +import java.util.Optional; + +@Component +public class AllowanceCalculator { + + public static final double DEPENDANT_MONTHLY_ALLOWANCE = 289.90; + public static final String RETIRED = "RETIRED"; + + public double calculateAllowance(CaseData caseData) { + Optional partnerAndDependantInformation = Optional.ofNullable(caseData.getRespondent1PartnerAndDependent()); + Optional defendantFinancialDetailsLiP = Optional.ofNullable(caseData.getCaseDataLiP().getRespondent1LiPFinancialDetails()); + double personalAllowance = calculatePersonalAllowance( + partnerAndDependantInformation, + caseData.getRespondent1() + ); + double dependantsAllowance = calculateDependantsAllowance(partnerAndDependantInformation); + double disabilityAllowance = calculateDisabilityAllowance( + partnerAndDependantInformation, + caseData.getDisabilityPremiumPayments(), + caseData.getSevereDisabilityPremiumPayments(), + caseData.getRespondent1DQ(), + defendantFinancialDetailsLiP + ); + double pensionerAllowance = calculatePensionerAllowance( + defendantFinancialDetailsLiP, + caseData.getRespondToClaimAdmitPartUnemployedLRspec() + ); + return personalAllowance + dependantsAllowance + disabilityAllowance + pensionerAllowance; + } + + private double calculatePersonalAllowance(Optional partnerAndDependantInformation, Party defendant) { + int defendantAge = calculateDefendantAge(defendant); + boolean hasPartner = getHasPartner(partnerAndDependantInformation); + boolean partnerOver18 = YesOrNo.YES == partnerAndDependantInformation.map(PartnerAndDependentsLRspec::getPartnerAgedOver).orElse( + null); + return PersonalAllowance.getPersonalAllowance(defendantAge, hasPartner, partnerOver18).getAllowance(); + } + + private boolean getHasPartner(Optional partnerAndDependantInformation) { + return partnerAndDependantInformation.map(PartnerAndDependentsLRspec::hasPartner).orElse(false); + } + + private double calculateDependantsAllowance(Optional partnerAndDependantInformation) { + int numberOfSupportedPeople = partnerAndDependantInformation.map(PartnerAndDependentsLRspec::getSupportPeopleNumber) + .map(Integer::parseInt).orElse(0); + int numberOfChildren = partnerAndDependantInformation.map(PartnerAndDependentsLRspec::getHowManyChildrenByAgeGroup) + .map(ChildrenByAgeGroupLRspec::getTotalChildren).orElse(0); + return DEPENDANT_MONTHLY_ALLOWANCE * (numberOfSupportedPeople + numberOfChildren); + } + + private double calculateDisabilityAllowance(Optional partnerAndDependantInformation, + YesOrNo disabilityPremiumPayments, + YesOrNo severeDisability, + Respondent1DQ respondent1DQ, + Optional financialDetailsLiP) { + boolean disabled = YesOrNo.YES == disabilityPremiumPayments; + boolean severelyDisabled = YesOrNo.YES == severeDisability + || YesOrNo.YES == financialDetailsLiP.map(FinancialDetailsLiP::getPartnerSevereDisabilityLiP).orElse(YesOrNo.NO); + boolean hasPartner = getHasPartner(partnerAndDependantInformation); + boolean dependantDisabled = YesOrNo.YES == partnerAndDependantInformation.map(PartnerAndDependentsLRspec::getReceiveDisabilityPayments).orElse( + YesOrNo.NO); + YesOrNo carerOption = getCarerOption(respondent1DQ); + boolean carer = YesOrNo.YES == carerOption; + return DisabilityAllowance + .getDisabilityAllowance(new DisabilityParam( + disabled, + hasPartner, + severelyDisabled, + dependantDisabled, + carer + )); + + } + + private YesOrNo getCarerOption(Respondent1DQ respondent1DQ) { + if (respondent1DQ == null) { + return YesOrNo.NO; + } + return Optional.ofNullable(respondent1DQ.getRespondent1DQCarerAllowanceCreditFullAdmission()) + .orElse(respondent1DQ.getRespondent1DQCarerAllowanceCredit()); + } + + private double calculatePensionerAllowance(Optional financialDetailsLiP, UnemployedComplexTypeLRspec unemployedType) { + boolean partnerPensioner = YesOrNo.YES == financialDetailsLiP.map(FinancialDetailsLiP::getPartnerPensionLiP).orElse(YesOrNo.NO); + boolean defendantPensioner = RETIRED.equals(Optional.ofNullable(unemployedType) + .map(UnemployedComplexTypeLRspec::getUnemployedComplexTypeRequired).orElse("")); + return PensionerAllowance.getPensionerAllowance(defendantPensioner, partnerPensioner); + } + + private int calculateDefendantAge(Party defendant) { + LocalDate dateOfBirth = defendant.getDateOfBirth(); + LocalDate now = LocalDate.now(); + return dateOfBirth != null ? Period.between(now, dateOfBirth).getYears() : 0; + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/ExpenditureCalculator.java b/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/ExpenditureCalculator.java new file mode 100644 index 00000000000..be8d185fe39 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/ExpenditureCalculator.java @@ -0,0 +1,78 @@ +package uk.gov.hmcts.reform.civil.service.citizen.repaymentplan; + +import org.springframework.stereotype.Component; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.model.DebtLRspec; +import uk.gov.hmcts.reform.civil.model.LoanCardDebtLRspec; +import uk.gov.hmcts.reform.civil.model.Respondent1CourtOrderDetails; +import uk.gov.hmcts.reform.civil.model.Respondent1DebtLRspec; +import uk.gov.hmcts.reform.civil.model.common.Element; +import uk.gov.hmcts.reform.civil.model.dq.RecurringExpenseLRspec; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.List; +import java.util.stream.Collectors; + +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.unwrapElementsNullSafe; +import static uk.gov.hmcts.reform.civil.utils.MonetaryConversions.penniesToPounds; +import static uk.gov.hmcts.reform.civil.utils.PaymentFrequencyCalculator.calculatePaymentPerMonth; + +@Component +public class ExpenditureCalculator { + + public double calculateTotalExpenditure(List> recurringExpenseElementList, + Respondent1DebtLRspec respondent1DebtLRspec, + List> courtOrderDetailsElementList) { + double calculatedResult = calculateTotalMonthlyExpenses(recurringExpenseElementList) + + calculateTotalMonthlyDebt(respondent1DebtLRspec) + + calculateCourtOrders(courtOrderDetailsElementList); + return BigDecimal.valueOf(calculatedResult).setScale(2, RoundingMode.HALF_UP).doubleValue(); + } + + private double calculateTotalMonthlyExpenses(List> recurringExpenseElementList) { + List expenses = unwrapElementsNullSafe(recurringExpenseElementList); + return expenses.stream() + .mapToDouble(expense -> calculatePaymentPerMonth( + penniesToPounds(expense.getAmount()).doubleValue(), + expense.getFrequency() + )) + .sum(); + } + + private double calculateCourtOrders(List> courtOrderDetailsElementList) { + List courtOrderDetails = unwrapElementsNullSafe(courtOrderDetailsElementList); + return !courtOrderDetails.isEmpty() ? courtOrderDetails.stream().map(item -> penniesToPounds(item.getMonthlyInstalmentAmount())) + .collect(Collectors.summingDouble(BigDecimal::doubleValue)) : 0.0; + } + + private double calculateTotalMonthlyDebt(Respondent1DebtLRspec respondent1DebtLRspec) { + if (respondent1DebtLRspec == null) { + return 0.0; + } + if (YesOrNo.YES == respondent1DebtLRspec.getHasLoanCardDebt()) { + return calculateCreditCardDebts(respondent1DebtLRspec.getLoanCardDebtDetails()) + + calculateDebts(respondent1DebtLRspec.getDebtDetails()); + } + return calculateDebts(respondent1DebtLRspec.getDebtDetails()); + } + + private double calculateCreditCardDebts(List> loanCardDebtDetails) { + List cardDebtList = unwrapElementsNullSafe(loanCardDebtDetails); + return cardDebtList.stream() + .map(LoanCardDebtLRspec::getMonthlyPayment) + .map(debt -> penniesToPounds(debt)) + .collect(Collectors.summingDouble(BigDecimal::doubleValue)); + } + + private double calculateDebts(List> debtDetails) { + List debts = unwrapElementsNullSafe(debtDetails); + return debts.stream() + .mapToDouble(debt -> calculatePaymentPerMonth( + penniesToPounds(debt.getPaymentAmount()).doubleValue(), + debt.getPaymentFrequency() + )) + .sum(); + } + +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/IncomeCalculator.java b/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/IncomeCalculator.java new file mode 100644 index 00000000000..3f6719dee02 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/IncomeCalculator.java @@ -0,0 +1,55 @@ +package uk.gov.hmcts.reform.civil.service.citizen.repaymentplan; + +import org.springframework.stereotype.Component; +import uk.gov.hmcts.reform.civil.model.Respondent1SelfEmploymentLRspec; +import uk.gov.hmcts.reform.civil.model.account.AccountSimple; +import uk.gov.hmcts.reform.civil.model.common.Element; +import uk.gov.hmcts.reform.civil.model.dq.RecurringIncomeLRspec; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.unwrapElementsNullSafe; +import static uk.gov.hmcts.reform.civil.utils.MonetaryConversions.penniesToPounds; +import static uk.gov.hmcts.reform.civil.utils.PaymentFrequencyCalculator.calculatePaymentPerMonth; + +@Component +public class IncomeCalculator { + + public double calculateTotalMonthlyIncome(List> bankAccountElements, + List> recurringIncomeElements, + Respondent1SelfEmploymentLRspec specDefendant1SelfEmploymentDetails) { + double result = calculateRegularIncome(recurringIncomeElements) + + calculateTotalSavings(bankAccountElements) + + calculateMonthlyIncomeFromAnnualTurnover(specDefendant1SelfEmploymentDetails); + return BigDecimal.valueOf(result).setScale(2, RoundingMode.HALF_UP).doubleValue(); + } + + private double calculateTotalSavings(List> bankAccountElements) { + List bankAccounts = unwrapElementsNullSafe(bankAccountElements); + return bankAccounts.stream().filter(item -> item.getBalance().compareTo(BigDecimal.ZERO) > 0) + .map(AccountSimple::getBalance).collect(Collectors.summingDouble(BigDecimal::doubleValue)); + } + + private double calculateRegularIncome(List> recurringIncomeElements) { + List recurringIncomes = unwrapElementsNullSafe(recurringIncomeElements); + return recurringIncomes.stream().filter(income -> income.getAmount().compareTo(BigDecimal.ZERO) > 0) + .mapToDouble(this::calculateIncomePerMonth).sum(); + } + + private double calculateMonthlyIncomeFromAnnualTurnover(Respondent1SelfEmploymentLRspec specDefendant1SelfEmploymentDetails) { + return Optional.ofNullable(specDefendant1SelfEmploymentDetails) + .map(selfEmploymentDetails -> BigDecimal.valueOf(penniesToPounds(selfEmploymentDetails.getAnnualTurnover()).doubleValue() / 12) + .setScale(2, RoundingMode.HALF_UP) + .doubleValue()) + .orElse(0.0); + } + + private double calculateIncomePerMonth(RecurringIncomeLRspec income) { + double incomeAmount = penniesToPounds(income.getAmount()).doubleValue(); + return calculatePaymentPerMonth(incomeAmount, income.getFrequency()); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/RepaymentPlanDecisionCalculator.java b/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/RepaymentPlanDecisionCalculator.java new file mode 100644 index 00000000000..d6bb205bbc9 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/RepaymentPlanDecisionCalculator.java @@ -0,0 +1,96 @@ +package uk.gov.hmcts.reform.civil.service.citizen.repaymentplan; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.RepaymentPlanLRspec; +import uk.gov.hmcts.reform.civil.model.citizenui.dto.RepaymentDecisionType; +import uk.gov.hmcts.reform.civil.model.repaymentplan.ClaimantProposedPlan; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.Optional; + +import static uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec.BY_SET_DATE; + +@Service +@RequiredArgsConstructor +public class RepaymentPlanDecisionCalculator { + + private final IncomeCalculator incomeCalculator; + private final ExpenditureCalculator expenditureCalculator; + private final AllowanceCalculator allowanceCalculator; + + public RepaymentDecisionType calculateRepaymentDecision(CaseData caseData, ClaimantProposedPlan claimantProposedPlan) { + double disposableIncome = calculateDisposableIncome(caseData); + BigDecimal claimTotalAmount = Optional.ofNullable(caseData.getRespondToAdmittedClaimOwingAmountPounds()).orElse( + caseData.getTotalClaimAmount()); + + if (claimantProposedPlan.hasProposedPayImmediately()) { + return calculateDecisionBasedOnAmountAndDisposableIncome(claimTotalAmount.doubleValue(), disposableIncome); + } + if (claimantProposedPlan.hasProposedPayBySetDate()) { + RepaymentDecisionType repaymentDecisionType = calculateDecisionBasedOnAmountAndDisposableIncome( + claimTotalAmount.doubleValue(), + disposableIncome + ); + if (repaymentDecisionType.isInFavourOfDefendant()) { + LocalDate proposedDefendantRepaymentDate = getProposedDefendantRepaymentDate( + caseData, + claimTotalAmount + ); + return calculateDecisionBasedOnProposedDate( + proposedDefendantRepaymentDate, + claimantProposedPlan.getRepaymentByDate() + ); + } + return repaymentDecisionType; + } + if (claimantProposedPlan.hasProposedPayByInstallments()) { + return calculateDecisionBasedOnAmountAndDisposableIncome( + claimantProposedPlan.getCalculatedPaymentPerMonthFromRepaymentPlan(), + disposableIncome + ); + } + return RepaymentDecisionType.IN_FAVOUR_OF_DEFENDANT; + } + + private LocalDate getProposedDefendantRepaymentDate(CaseData caseData, BigDecimal claimTotalAmount) { + RespondentResponsePartAdmissionPaymentTimeLRspec respondentResponseType = caseData.getDefenceAdmitPartPaymentTimeRouteRequired(); + RepaymentPlanLRspec defendantRepaymentPlan = caseData.getRespondent1RepaymentPlan(); + return respondentResponseType == BY_SET_DATE + ? caseData.getRespondToClaimAdmitPartLRspec().getWhenWillThisAmountBePaid() : defendantRepaymentPlan.finalPaymentBy( + claimTotalAmount); + } + + private RepaymentDecisionType calculateDecisionBasedOnAmountAndDisposableIncome(double totalAmount, double disposableIncome) { + if (totalAmount > disposableIncome) { + return RepaymentDecisionType.IN_FAVOUR_OF_DEFENDANT; + } + return RepaymentDecisionType.IN_FAVOUR_OF_CLAIMANT; + } + + private RepaymentDecisionType calculateDecisionBasedOnProposedDate(LocalDate defendantProposedDate, LocalDate claimantProposedDate) { + if (claimantProposedDate.isAfter(defendantProposedDate)) { + return RepaymentDecisionType.IN_FAVOUR_OF_CLAIMANT; + } + return RepaymentDecisionType.IN_FAVOUR_OF_DEFENDANT; + } + + private double calculateDisposableIncome(CaseData caseData) { + double calculatedIncome = incomeCalculator.calculateTotalMonthlyIncome( + caseData.getRespondent1DQ().getRespondent1BankAccountList(), + caseData.getRecurringIncomeForRespondent1(), + caseData.getSpecDefendant1SelfEmploymentDetails() + ); + double calculatedExpenditure = expenditureCalculator.calculateTotalExpenditure( + caseData.getRecurringExpensesForRespondent1(), + caseData.getSpecDefendant1Debts(), + caseData.getRespondent1CourtOrderDetails() + ); + double calculatedAllowance = allowanceCalculator.calculateAllowance(caseData); + return calculatedIncome - calculatedExpenditure - calculatedAllowance; + } + +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/RepaymentPlanDecisionService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/RepaymentPlanDecisionService.java new file mode 100644 index 00000000000..e279e33b039 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/RepaymentPlanDecisionService.java @@ -0,0 +1,22 @@ +package uk.gov.hmcts.reform.civil.service.citizen.repaymentplan; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.ccd.client.model.CaseDetails; +import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.citizenui.dto.RepaymentDecisionType; +import uk.gov.hmcts.reform.civil.model.repaymentplan.ClaimantProposedPlan; + +@Service +@RequiredArgsConstructor +public class RepaymentPlanDecisionService { + + private final CaseDetailsConverter caseDetailsConverter; + private final RepaymentPlanDecisionCalculator repaymentPlanDecisionCalculator; + + public RepaymentDecisionType getCalculatedDecision(final CaseDetails caseDetails, final ClaimantProposedPlan claimantProposedPlan) { + CaseData caseData = caseDetailsConverter.toCaseData(caseDetails); + return repaymentPlanDecisionCalculator.calculateRepaymentDecision(caseData, claimantProposedPlan); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/citizenui/DashboardClaimInfoService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/citizenui/DashboardClaimInfoService.java index 9c27668ad36..058ab6c0eb8 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/citizenui/DashboardClaimInfoService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/citizenui/DashboardClaimInfoService.java @@ -12,6 +12,7 @@ import uk.gov.hmcts.reform.civil.model.citizenui.DashboardClaimStatusFactory; import uk.gov.hmcts.reform.civil.model.citizenui.DashboardResponse; import uk.gov.hmcts.reform.civil.service.CoreCaseDataService; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.claimstore.ClaimStoreService; import java.time.LocalDateTime; @@ -20,6 +21,7 @@ import java.util.Comparator; import java.util.List; import java.util.Objects; +import java.util.Optional; import java.util.stream.Collectors; import static java.util.Objects.nonNull; @@ -29,17 +31,13 @@ @RequiredArgsConstructor public class DashboardClaimInfoService { + private static final int CASES_PER_PAGE = 10; + + private final CaseDetailsConverter caseDetailsConverter; private final ClaimStoreService claimStoreService; private final CoreCaseDataService coreCaseDataService; - private final CaseDetailsConverter caseDetailsConverter; private final DashboardClaimStatusFactory dashboardClaimStatusFactory; - private static final int CASES_PER_PAGE = 10; - - private List getClaimsForClaimant(String authorisation, String claimantId) { - log.info("-----------calling ocmc claimant claims-------------"); - List ocmcClaims = claimStoreService.getClaimsForClaimant(authorisation, claimantId); - return ocmcClaims; - } + private final FeatureToggleService featureToggleService; public List getOcmcDefendantClaims(String authorisation, String defendantId) { log.info("-----------calling ocmc getOCMCDefendantClaims()-------------"); @@ -63,22 +61,35 @@ public DashboardResponse getDashboardDefendantResponse(String authorisation, Str public DashboardResponse getDashboardClaimantResponse(String authorisation, String claimantId, int currentPage) { List ocmcClaims = getClaimsForClaimant(authorisation, claimantId); + int startIndex = (currentPage - 1) * CASES_PER_PAGE; - var ccdData = coreCaseDataService.getCCDClaimsForLipClaimant(authorisation, startIndex); - int totalPages = getTotalPagesToBeListed(ccdData.getTotal() + ocmcClaims.size()); + SearchResult ccdData = null; + + if (featureToggleService.isLipVLipEnabled()) { + ccdData = coreCaseDataService.getCCDClaimsForLipClaimant(authorisation, startIndex); + } + + int totalPages = getTotalPagesToBeListed(getCcdClaimsCount(ccdData) + ocmcClaims.size()); List currentPageItems = currentPage <= totalPages ? getDashboardItemsForCurrentPage(ocmcClaims, currentPage, ccdData) : Collections.emptyList(); return DashboardResponse.builder().totalPages(totalPages).claims(currentPageItems).build(); } + private List getClaimsForClaimant(String authorisation, String claimantId) { + log.info("-----------calling ocmc claimant claims-------------"); + List ocmcClaims = claimStoreService.getClaimsForClaimant(authorisation, claimantId); + return ocmcClaims; + } + private List getDashboardItemsForCurrentPage(List ocmcClaims, int currentPage, SearchResult ccdClaims) { int startIndex = (currentPage - 1) * CASES_PER_PAGE; int endIndex = startIndex + CASES_PER_PAGE; - int ccdClaimsCount = ccdClaims.getTotal(); + int ccdClaimsCount = getCcdClaimsCount(ccdClaims); + List dashBoardClaimInfo = new ArrayList<>(); if (startIndex >= ccdClaimsCount) { int ocmcStartIndex = startIndex - ccdClaimsCount; @@ -102,8 +113,12 @@ private List sortOcmcCases(List ocmcCase .sorted(Comparator.comparing(DashboardClaimInfo::getCreatedDate).reversed()) .collect(Collectors.toList()); } - + private List translateSearchResultToDashboardItems(SearchResult claims) { + if (claims == null) { + return Collections.emptyList(); + } + return claims.getCases().stream().map(caseDetails -> translateCaseDataToDashboardClaimInfo(caseDetails)) .collect(Collectors.toList()); } @@ -118,7 +133,7 @@ private DashboardClaimInfo translateCaseDataToDashboardClaimInfo(CaseDetails cas .claimAmount(nonNull(caseData.getTotalClaimAmount()) ? caseData.getTotalClaimAmount() : null) .admittedAmount(caseData.getPartAdmitPaidValuePounds()) .responseDeadlineTime(caseData.getRespondent1ResponseDeadline()) - .status(dashboardClaimStatusFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher(caseData))) + .status(dashboardClaimStatusFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher(caseData, featureToggleService))) .build(); if (caseData.getRespondent1ResponseDeadline() != null) { item.setResponseDeadline(caseData.getRespondent1ResponseDeadline().toLocalDate()); @@ -150,4 +165,9 @@ private int getTotalPagesToBeListed(int totalClaims) { } return totalPages; } + + private int getCcdClaimsCount(final SearchResult ccdClaims) { + + return Optional.ofNullable(ccdClaims).map(SearchResult::getTotal).orElse(0); + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/citizenui/ResponseOneVOneShowTagService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/citizenui/ResponseOneVOneShowTagService.java new file mode 100644 index 00000000000..f639722d4b1 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/citizenui/ResponseOneVOneShowTagService.java @@ -0,0 +1,55 @@ +package uk.gov.hmcts.reform.civil.service.citizenui; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.civil.handler.callback.user.spec.show.ResponseOneVOneShowTag; +import uk.gov.hmcts.reform.civil.model.CaseData; + +import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.ONE_V_ONE; +import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.getMultiPartyScenario; +import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; + +@Service +@RequiredArgsConstructor +public class ResponseOneVOneShowTagService { + + public ResponseOneVOneShowTag setUpOneVOneFlow(CaseData caseData) { + if (ONE_V_ONE.equals(getMultiPartyScenario(caseData))) { + if (caseData.getRespondent1ClaimResponseTypeForSpec() == null) { + return null; + } + return switch (caseData.getRespondent1ClaimResponseTypeForSpec()) { + case FULL_DEFENCE -> ResponseOneVOneShowTag.ONE_V_ONE_FULL_DEFENCE; + case FULL_ADMISSION -> setUpOneVOneFlowForFullAdmit(caseData); + case PART_ADMISSION -> setUpOneVOneFlowForPartAdmit(caseData); + case COUNTER_CLAIM -> ResponseOneVOneShowTag.ONE_V_ONE_COUNTER_CLAIM; + default -> null; + }; + } + return null; + } + + private ResponseOneVOneShowTag setUpOneVOneFlowForPartAdmit(CaseData caseData) { + if (YES.equals(caseData.getSpecDefenceAdmittedRequired())) { + return ResponseOneVOneShowTag.ONE_V_ONE_PART_ADMIT_HAS_PAID; + } + return switch (caseData.getDefenceAdmitPartPaymentTimeRouteRequired()) { + case IMMEDIATELY -> ResponseOneVOneShowTag.ONE_V_ONE_PART_ADMIT_PAY_IMMEDIATELY; + case BY_SET_DATE -> ResponseOneVOneShowTag.ONE_V_ONE_PART_ADMIT_PAY_BY_SET_DATE; + case SUGGESTION_OF_REPAYMENT_PLAN -> ResponseOneVOneShowTag.ONE_V_ONE_PART_ADMIT_PAY_INSTALMENT; + default -> ResponseOneVOneShowTag.ONE_V_ONE_PART_ADMIT; + }; + } + + private ResponseOneVOneShowTag setUpOneVOneFlowForFullAdmit(CaseData caseData) { + if (YES.equals(caseData.getSpecDefenceFullAdmittedRequired())) { + return ResponseOneVOneShowTag.ONE_V_ONE_FULL_ADMIT_HAS_PAID; + } + return switch (caseData.getDefenceAdmitPartPaymentTimeRouteRequired()) { + case IMMEDIATELY -> ResponseOneVOneShowTag.ONE_V_ONE_FULL_ADMIT_PAY_IMMEDIATELY; + case BY_SET_DATE -> ResponseOneVOneShowTag.ONE_V_ONE_FULL_ADMIT_PAY_BY_SET_DATE; + case SUGGESTION_OF_REPAYMENT_PLAN -> ResponseOneVOneShowTag.ONE_V_ONE_FULL_ADMIT_PAY_INSTALMENT; + default -> ResponseOneVOneShowTag.ONE_V_ONE_FULL_ADMIT; + }; + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/citizenui/responsedeadline/DeadlineExtensionCalculatorService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/citizenui/responsedeadline/DeadlineExtensionCalculatorService.java index 0e6e5479803..71bf64f61c1 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/citizenui/responsedeadline/DeadlineExtensionCalculatorService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/citizenui/responsedeadline/DeadlineExtensionCalculatorService.java @@ -6,16 +6,28 @@ import java.time.LocalDate; +import static java.util.Objects.requireNonNull; + @Service @RequiredArgsConstructor public class DeadlineExtensionCalculatorService { private final WorkingDayIndicator workingDayIndicator; + int workingDaysCounter; - public LocalDate calculateExtendedDeadline(LocalDate dateProposed) { - return workingDayIndicator.isWorkingDay(dateProposed) - ? dateProposed - : workingDayIndicator.getNextWorkingDay(dateProposed); + public LocalDate calculateExtendedDeadline(LocalDate responseDate, int plusDays) { + workingDaysCounter = 0; + requireNonNull(responseDate); + if (plusDays == 0) { + return workingDayIndicator.getNextWorkingDay(responseDate); + } + return calculateWorkingDays(responseDate.plusDays(1), plusDays); } + public LocalDate calculateWorkingDays(LocalDate responseDate, int plusDays) { + if (workingDayIndicator.isWorkingDay(responseDate)) { + workingDaysCounter++; + } + return workingDaysCounter == plusDays ? responseDate : calculateWorkingDays(responseDate.plusDays(1), plusDays); + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/DocmosisTemplates.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/DocmosisTemplates.java index eb788d293f4..70238616c12 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/DocmosisTemplates.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/DocmosisTemplates.java @@ -20,20 +20,21 @@ public enum DocmosisTemplates { N121("CV-UNS-DEC-ENG-01280.docx", "default_judgment_form_%s.pdf"), DEFENDANT_RESPONSE_SPEC_SEALED_1v1("CV-SPC-HRN-ENG-01361.docx", "%s_response_sealed_form.pdf"), DEFENDANT_RESPONSE_SPEC_SEALED_1v2("CV-SPC-HRN-ENG-01360.docx", "%s_response_sealed_form.pdf"), + DEFENDANT_RESPONSE_SPEC_SEALED_1V1_INSTALLMENTS("CV-SPC-HRN-ENG-01362.docx", "%s_response_sealed_form.pdf"), LIP_CLAIM_FORM("CV-UNS-CLM-ENG-01096.docx", "litigant_in_person_claim_form_%s.pdf"), - SDO_DISPOSAL("CV-UNS-STD-ENG-01324.docx", "disposal_hearing_sdo_%s.pdf"), - DJ_SDO_DISPOSAL("CV-UNS-DEC-ENG-01323.docx", "Order_disposal_%s.pdf"), - DJ_SDO_TRIAL("CV-UNS-DEC-ENG-01322.docx", "Order_trial_%s.pdf"), - SDO_SMALL("CV-UNS-STD-ENG-01362.docx", "small_claims_sdo_%s.pdf"), - SDO_FAST("CV-UNS-STD-ENG-01326.docx", "fast_track_sdo_%s.pdf"), - SDO_FAST_FAST_TRACK_INT("CV-UNS-STD-ENG-01308.docx", "fast_track_sdo_%s.pdf"), - DEFENDANT_RESPONSE_LIP_SPEC("CV-SPC-CLM-ENG-01064-LIP.docx", "response_sealed_form_%s.pdf"), + SDO_DISPOSAL("CV-UNS-STD-ENG-01381.docx", "disposal_hearing_sdo_%s.pdf"), + DJ_SDO_DISPOSAL("CV-UNS-DEC-ENG-01329.docx", "Order_disposal_%s.pdf"), + DJ_SDO_TRIAL("CV-UNS-DEC-ENG-01376.docx", "Order_trial_%s.pdf"), + SDO_SMALL("CV-UNS-STD-ENG-01382.docx", "small_claims_sdo_%s.pdf"), + SDO_FAST("CV-UNS-STD-ENG-01380.docx", "fast_track_sdo_%s.pdf"), + SDO_FAST_FAST_TRACK_INT("CV-UNS-STD-ENG-01378.docx", "fast_track_sdo_%s.pdf"), + DEFENDANT_RESPONSE_LIP_SPEC("CV-SPC-CLM-ENG-01065-LIP.docx", "response_sealed_form_%s.pdf"), HEARING_SMALL_CLAIMS("CV-UNS-HNO-ENG-01197.docx", "hearing_small_claim_%s.pdf"), HEARING_FAST_TRACK("CV-UNS-HNO-ENG-01198.docx", "hearing_fast_track_%s.pdf"), HEARING_APPLICATION("CV-UNS-HNO-ENG-01199.docx", "hearing_application_%s.pdf"), HEARING_OTHER("CV-UNS-HNO-ENG-01196.docx", "hearing_other_claim_%s.pdf"), PIN_IN_THE_POST_LETTER("CV-CMC-LET-ENG-PIP0001.docx", "PIP_letter.pdf"), - SDO_HNL_DISPOSAL("CV-UNS-STD-ENG-01305.docx", "disposal_hearing_sdo_%s.pdf"), + SDO_HNL_DISPOSAL("CV-UNS-STD-ENG-01377.docx", "disposal_hearing_sdo_%s.pdf"), DJ_SDO_HNL_DISPOSAL("CV-UNS-DEC-ENG-01229.docx", "Order_disposal_%s.pdf"), DEFENDANT_RESPONSE_SPEC("CV-SPC-HRN-ENG-01357.docx", "%s_directions_questionnaire_form_%s.pdf"), DEFENDANT_RESPONSE_SPEC_FAST_TRACK_INT("CV-SPC-HRN-ENG-01358.docx", "%s_directions_questionnaire_form_%s.pdf"), @@ -48,7 +49,8 @@ public enum DocmosisTemplates { DQ_RESPONSE_2V1("CV-UNS-HRN-ENG-01344.docx", "%s_directions_questionnaire_form_%s.pdf"), DQ_RESPONSE_2V1_FAST_TRACK_INT("CV-UNS-HRN-ENG-01348.docx", "%s_directions_questionnaire_form_%s.pdf"), DQ_LR_V_LIP_RESPONSE("CV-SPC-HRN-ENG-LIP-01282.docx", "%s_directions_questionnaire_form_%s.pdf"), - TRIAL_READY("CV-UNS-HRN-ENG-01247.docx", "%s_%s_Trial_Arrangements.pdf"), + DQ_LIP_RESPONSE("CV-SPC-HRN-ENG-LIP-01283.docx", "%s_directions_questionnaire_form_%s.pdf"), + TRIAL_READY("CV-UNS-HRN-ENG-01247-10180.docx", "%s_%s_Trial_Arrangements.pdf"), HEARING_NOTICE_HMC("CV-UNS-HNO-ENG-01200.docx", "hearing_notice_%s.pdf"), // judge final Order FREE_FORM_ORDER_PDF("CV-UNS-DEC-ENG-01099.docx", "Order_%s.pdf"), diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/RepresentativeService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/RepresentativeService.java index 49dd35d3aa1..fd9384a9982 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/RepresentativeService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/RepresentativeService.java @@ -1,6 +1,7 @@ package uk.gov.hmcts.reform.civil.service.docmosis; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.ccd.model.OrganisationPolicy; import uk.gov.hmcts.reform.civil.service.FeatureToggleService; @@ -14,6 +15,7 @@ import static uk.gov.hmcts.reform.civil.enums.CaseCategory.SPEC_CLAIM; import static uk.gov.hmcts.reform.civil.model.docmosis.sealedclaim.Representative.fromOrganisation; +@Slf4j @Service @RequiredArgsConstructor public class RepresentativeService { @@ -21,15 +23,21 @@ public class RepresentativeService { private final OrganisationService organisationService; private final FeatureToggleService featureToggleService; - private boolean doesOrganisationPolicyExist(OrganisationPolicy organisationPolicy) { - return organisationPolicy != null - && organisationPolicy.getOrganisation() != null - && organisationPolicy.getOrganisation().getOrganisationID() != null; + private boolean doesOrganisationPolicyExist(OrganisationPolicy organisationPolicy, String organisationIDCopy) { + return (organisationPolicy != null && organisationPolicy.getOrganisation() != null + && organisationPolicy.getOrganisation().getOrganisationID() != null) + || organisationIDCopy != null; } public Representative getRespondent1Representative(CaseData caseData) { - if (doesOrganisationPolicyExist(caseData.getRespondent1OrganisationPolicy())) { - var organisationId = caseData.getRespondent1OrganisationPolicy().getOrganisation().getOrganisationID(); + if (doesOrganisationPolicyExist(caseData.getRespondent1OrganisationPolicy(), caseData.getRespondent1OrganisationIDCopy())) { + var organisationId = caseData.getRespondent1OrganisationIDCopy(); + + if (organisationId == null || organisationId.isEmpty()) { + organisationId = caseData.getRespondent1OrganisationPolicy().getOrganisation().getOrganisationID(); + } + + log.info("organisation1ID: " + organisationId); var representative = fromOrganisation(organisationService.findOrganisationById(organisationId) .orElseThrow(RuntimeException::new)); @@ -54,8 +62,14 @@ public Representative getRespondent1Representative(CaseData caseData) { } public Representative getRespondent2Representative(CaseData caseData) { - if (doesOrganisationPolicyExist(caseData.getRespondent2OrganisationPolicy())) { - var organisationId = caseData.getRespondent2OrganisationPolicy().getOrganisation().getOrganisationID(); + if (doesOrganisationPolicyExist(caseData.getRespondent2OrganisationPolicy(), caseData.getRespondent2OrganisationIDCopy())) { + var organisationId = caseData.getRespondent2OrganisationIDCopy(); + + if (organisationId == null || organisationId.isEmpty()) { + organisationId = caseData.getRespondent2OrganisationPolicy().getOrganisation().getOrganisationID(); + } + + log.info("organisation2ID: " + organisationId); var representative = fromOrganisation(organisationService.findOrganisationById(organisationId) .orElseThrow(RuntimeException::new)); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/caseprogression/JudgeFinalOrderGenerator.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/caseprogression/JudgeFinalOrderGenerator.java index dcb3a68ce48..d39136c1ce4 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/caseprogression/JudgeFinalOrderGenerator.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/caseprogression/JudgeFinalOrderGenerator.java @@ -1,18 +1,18 @@ package uk.gov.hmcts.reform.civil.service.docmosis.caseprogression; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.civil.documentmanagement.DocumentManagementService; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType; import uk.gov.hmcts.reform.civil.documentmanagement.model.PDF; -import uk.gov.hmcts.reform.civil.enums.CaseState; import uk.gov.hmcts.reform.civil.enums.finalorders.ApplicationAppealList; +import uk.gov.hmcts.reform.civil.enums.finalorders.CostEnums; import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrderToggle; import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersClaimantDefendantNotAttending; import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersClaimantRepresentationList; import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersDefendantRepresentationList; -import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersJudgePapers; import uk.gov.hmcts.reform.civil.enums.finalorders.OrderMadeOnTypes; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.docmosis.DocmosisDocument; @@ -23,20 +23,28 @@ import uk.gov.hmcts.reform.civil.service.docmosis.DocumentGeneratorService; import uk.gov.hmcts.reform.civil.service.docmosis.DocumentHearingLocationHelper; import uk.gov.hmcts.reform.civil.service.docmosis.TemplateDataGenerator; +import uk.gov.hmcts.reform.civil.utils.MonetaryConversions; import uk.gov.hmcts.reform.idam.client.IdamClient; import uk.gov.hmcts.reform.idam.client.models.UserDetails; import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.Locale; +import java.util.Objects; +import static java.lang.String.format; import static java.util.Objects.nonNull; -import static uk.gov.hmcts.reform.civil.enums.CaseState.JUDICIAL_REFERRAL; +import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; import static uk.gov.hmcts.reform.civil.enums.caseprogression.FinalOrderSelection.FREE_FORM_ORDER; import static uk.gov.hmcts.reform.civil.enums.finalorders.AppealList.OTHER; -import static uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersClaimantRepresentationList.CLAIMANT_NOT_ATTENDING; -import static uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersDefendantRepresentationList.DEFENDANT_NOT_ATTENDING; +import static uk.gov.hmcts.reform.civil.enums.finalorders.ApplicationAppealList.CIRCUIT_COURT; +import static uk.gov.hmcts.reform.civil.enums.finalorders.ApplicationAppealList.GRANTED; +import static uk.gov.hmcts.reform.civil.enums.finalorders.ApplicationAppealList.REFUSED; +import static uk.gov.hmcts.reform.civil.helpers.DateFormatHelper.formatLocalDate; import static uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates.ASSISTED_ORDER_PDF; import static uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates.FREE_FORM_ORDER_PDF; +@Slf4j @Service @RequiredArgsConstructor public class JudgeFinalOrderGenerator implements TemplateDataGenerator { @@ -47,6 +55,13 @@ public class JudgeFinalOrderGenerator implements TemplateDataGenerator finalOrdersJudgePapers.equals( - FinalOrdersJudgePapers.CONSIDERED)) : false) - .recordedToggle(nonNull(caseData.getFinalOrderRecitals()) - ? - caseData.getFinalOrderRecitals().stream().anyMatch(finalOrderToggle -> finalOrderToggle.equals( - FinalOrderToggle.SHOW)) : false) - .recordedText(nonNull(caseData.getFinalOrderRecitalsRecorded()) - ? caseData.getFinalOrderRecitalsRecorded().getText() : "") + .orderMadeDate(orderMadeDateBuilder(caseData)) + .courtLocation(LocationRefDataService.getDisplayEntry(locationRefData)) + .judgeNameTitle(userDetails.getFullName()) + .recordedToggle(nonNull(caseData.getFinalOrderRecitals())) + .recordedText(nonNull(caseData.getFinalOrderRecitalsRecorded()) ? caseData.getFinalOrderRecitalsRecorded().getText() : "") .orderedText(caseData.getFinalOrderOrderedThatText()) - .costSelection(caseData.getAssistedOrderCostList().name()) - .costReservedText(nonNull(caseData.getAssistedOrderCostsReserved()) - ? - caseData.getAssistedOrderCostsReserved().getDetailsRepresentationText() : "") - .bespokeText(nonNull(caseData.getAssistedOrderCostsBespoke()) - ? caseData.getAssistedOrderCostsBespoke().getBesPokeCostDetailsText() : "") - .furtherHearingToggle(nonNull(caseData.getFinalOrderFurtherHearingToggle()) - ? - caseData.getFinalOrderFurtherHearingToggle().stream().anyMatch(finalOrderToggle -> finalOrderToggle.name().equals( - FinalOrderToggle.SHOW.name())) : false) + .finalOrderJudgeHeardFrom(nonNull(caseData.getFinalOrderJudgeHeardFrom())) + .claimantAttendsOrRepresented(claimantAttendsOrRepresentedTextBuilder(caseData, false)) + .claimantTwoAttendsOrRepresented(nonNull(caseData.getApplicant2()) ? claimantAttendsOrRepresentedTextBuilder(caseData, true) : null) + .defendantAttendsOrRepresented(defendantAttendsOrRepresentedTextBuilder(caseData, false)) + .defendantTwoAttendsOrRepresented(nonNull(caseData.getRespondent2()) ? defendantAttendsOrRepresentedTextBuilder(caseData, true) : null) + .otherRepresentedText(getOtherRepresentedText(caseData)) + .judgeConsideredPapers(isJudgeConsideredPapers(caseData)) + .furtherHearingToggle(nonNull(caseData.getFinalOrderFurtherHearingToggle())) + .furtherHearingToToggle(nonNull(getFurtherHearingDate(caseData, false))) .furtherHearingFromDate(getFurtherHearingDate(caseData, true)) - .furtherHearingLength(getFurtherHearingLength(caseData)) .furtherHearingToDate(getFurtherHearingDate(caseData, false)) - .furtherHearingLocation(nonNull(caseData.getFinalOrderFurtherHearingComplex()) && nonNull(caseData.getFinalOrderFurtherHearingComplex().getAlternativeHearingList()) - ? - caseData.getFinalOrderFurtherHearingComplex().getAlternativeHearingList().getValue().getLabel() : "") - .furtherHearingMethod(nonNull(caseData.getFinalOrderFurtherHearingComplex()) && nonNull(caseData.getFinalOrderFurtherHearingComplex().getHearingMethodList()) - ? caseData.getFinalOrderFurtherHearingComplex().getHearingMethodList().name() : "") - .appealToggle(nonNull(caseData.getFinalOrderAppealToggle()) - ? - caseData.getFinalOrderAppealToggle().stream().anyMatch(finalOrderToggle -> finalOrderToggle.equals( - FinalOrderToggle.SHOW)) : false) - .appealFor(getAppealFor(caseData)) - .appealGranted(nonNull(caseData.getFinalOrderAppealComplex()) && nonNull(caseData.getFinalOrderAppealComplex().getApplicationList()) - ? - caseData.getFinalOrderAppealComplex().getApplicationList().name().equals(ApplicationAppealList.GRANTED.name()) : false) - .orderWithoutNotice(caseData.getOrderMadeOnDetailsList().name()) - .orderInitiativeOrWithoutNoticeDate(getOrderInitiativeOrWithoutNoticeDate(caseData)) - .isReason(caseData.getFinalOrderGiveReasonsYesNo()) - .reasonText(nonNull(caseData.getFinalOrderGiveReasonsComplex()) - ? caseData.getFinalOrderGiveReasonsComplex().getReasonsText() : ""); + .furtherHearingLength(getFurtherHearingLength(caseData)) + .datesToAvoid(getDatesToAvoid(caseData)) + .showFurtherHearingLocationAlt(isDefaultCourt(caseData)) + .furtherHearingLocationDefault(LocationRefDataService.getDisplayEntry(locationRefData)) + .furtherHearingLocationAlt(getFurtherHearingLocationAlt(caseData)) + .furtherHearingMethod(getFurtherHearingMethod(caseData)) + .hearingNotes(getHearingNotes(caseData)) + .costSelection(caseData.getAssistedOrderCostList().name()) + .costsReservedText(nonNull(caseData.getAssistedOrderCostsReserved()) ? caseData.getAssistedOrderCostsReserved().getDetailsRepresentationText() : null) + .bespokeCostText(nonNull(caseData.getAssistedOrderCostsBespoke()) ? caseData.getAssistedOrderCostsBespoke().getBesPokeCostDetailsText() : null) + .summarilyAssessed(getSummarilyAssessed(caseData)) + .summarilyAssessedDate(getSummarilyAssessedDate(caseData)) + .detailedAssessment(getDetailedAssessment(caseData)) + .interimPayment(getInterimPayment(caseData)) + .interimPaymentDate(getInterimPaymentDate(caseData)) + .qcosProtection(getQcosProtection(caseData)) + .costsProtection(caseData.getPublicFundingCostsProtection().equals(YES) ? "true" : null) + //appeal section + .claimantOrDefendantAppeal(getAppealFor(caseData)) + .appealGranted(isAppealGranted(caseData)) + .tableAorB(circuitOrHighCourt(caseData)) + .appealDate(getAppealDate(caseData)) + // InitiativeOrWithoutNotice section + .showInitiativeOrWithoutNotice(getInitiativeOrWithoutNotice(caseData)) + .initiativeDate(getInitiativeDate(caseData)) + .withoutNoticeDate(getWithoutNoticeDate(caseData)) + .reasonsText(getReasonsText(caseData)); return assistedFormOrderBuilder.build(); } - private LocalDate getOrderInitiativeOrWithoutNoticeDate(CaseData caseData) { - if (caseData.getOrderMadeOnDetailsList() != null) { - if (caseData.getOrderMadeOnDetailsList().name().equals(OrderMadeOnTypes.COURTS_INITIATIVE.name())) { - return caseData.getOrderMadeOnDetailsOrderCourt().getOwnInitiativeDate(); - } else if (caseData.getOrderMadeOnDetailsList().name().equals(OrderMadeOnTypes.WITHOUT_NOTICE.name())) { - return caseData.getOrderMadeOnDetailsOrderWithoutNotice().getWithOutNoticeDate(); + private String getOtherRepresentedText(CaseData caseData) { + return nonNull(caseData.getFinalOrderRepresentation()) + && nonNull(caseData.getFinalOrderRepresentation().getTypeRepresentationOtherComplex()) + ? caseData.getFinalOrderRepresentation().getTypeRepresentationOtherComplex().getDetailsRepresentationText() : ""; + } + + private String isJudgeConsideredPapers(CaseData caseData) { + return nonNull(caseData.getFinalOrderJudgePapers()) ? "true" : null; + } + + private LocalDate getDatesToAvoid(CaseData caseData) { + return nonNull(caseData.getFinalOrderFurtherHearingToggle()) + && nonNull(caseData.getFinalOrderFurtherHearingComplex().getDatesToAvoidDateDropdown()) + ? caseData.getFinalOrderFurtherHearingComplex().getDatesToAvoidDateDropdown().getDatesToAvoidDates() : null; + } + + private String getFurtherHearingLocationAlt(CaseData caseData) { + return nonNull(caseData.getFinalOrderFurtherHearingToggle()) + && nonNull(caseData.getFinalOrderFurtherHearingComplex().getAlternativeHearingList()) + ? caseData.getFinalOrderFurtherHearingComplex().getAlternativeHearingList().getValue().getLabel() : null; + } + + private String getFurtherHearingMethod(CaseData caseData) { + return nonNull(caseData.getFinalOrderFurtherHearingComplex()) && nonNull(caseData.getFinalOrderFurtherHearingComplex().getHearingMethodList()) + ? caseData.getFinalOrderFurtherHearingComplex().getHearingMethodList().name() : ""; + } + + private String getHearingNotes(CaseData caseData) { + return nonNull(caseData.getFinalOrderFurtherHearingToggle()) + && nonNull(caseData.getFinalOrderFurtherHearingComplex().getHearingNotesText()) + ? caseData.getFinalOrderFurtherHearingComplex().getHearingNotesText() : null; + } + + private String getSummarilyAssessed(CaseData caseData) { + return nonNull(caseData.getAssistedOrderMakeAnOrderForCosts()) + && nonNull(caseData.getAssistedOrderMakeAnOrderForCosts().getMakeAnOrderForCostsList()) + && caseData.getAssistedOrderMakeAnOrderForCosts().getAssistedOrderClaimantDefendantFirstDropdown().equals( + CostEnums.COSTS) + ? populateSummarilyAssessedText(caseData) : null; + } + + private LocalDate getSummarilyAssessedDate(CaseData caseData) { + return nonNull(caseData.getAssistedOrderMakeAnOrderForCosts()) + && nonNull(caseData.getAssistedOrderMakeAnOrderForCosts().getMakeAnOrderForCostsList()) + && caseData.getAssistedOrderMakeAnOrderForCosts().getAssistedOrderClaimantDefendantFirstDropdown().equals( + CostEnums.COSTS) + ? caseData.getAssistedOrderMakeAnOrderForCosts().getAssistedOrderCostsFirstDropdownDate() : null; + } + + private String getDetailedAssessment(CaseData caseData) { + return nonNull(caseData.getAssistedOrderMakeAnOrderForCosts()) + && nonNull(caseData.getAssistedOrderMakeAnOrderForCosts().getMakeAnOrderForCostsList()) + && caseData.getAssistedOrderMakeAnOrderForCosts().getAssistedOrderClaimantDefendantFirstDropdown().equals( + CostEnums.SUBJECT_DETAILED_ASSESSMENT) + ? populateDetailedAssessmentText(caseData) : null; + } + + private String getInterimPayment(CaseData caseData) { + return nonNull(caseData.getAssistedOrderMakeAnOrderForCosts()) + && nonNull(caseData.getAssistedOrderMakeAnOrderForCosts().getMakeAnOrderForCostsList()) + && caseData.getAssistedOrderMakeAnOrderForCosts().getAssistedOrderClaimantDefendantFirstDropdown().equals( + CostEnums.SUBJECT_DETAILED_ASSESSMENT) + && caseData.getAssistedOrderMakeAnOrderForCosts().getAssistedOrderAssessmentSecondDropdownList2().equals( + CostEnums.YES) + ? populateInterimPaymentText(caseData) : null; + } + + private LocalDate getInterimPaymentDate(CaseData caseData) { + return nonNull(caseData.getAssistedOrderMakeAnOrderForCosts()) + && nonNull(caseData.getAssistedOrderMakeAnOrderForCosts().getMakeAnOrderForCostsList()) + && caseData.getAssistedOrderMakeAnOrderForCosts().getAssistedOrderClaimantDefendantFirstDropdown().equals( + CostEnums.SUBJECT_DETAILED_ASSESSMENT) + ? caseData.getAssistedOrderMakeAnOrderForCosts().getAssistedOrderAssessmentThirdDropdownDate() : null; + } + + private String getQcosProtection(CaseData caseData) { + return nonNull(caseData.getAssistedOrderMakeAnOrderForCosts()) + && nonNull(caseData.getAssistedOrderMakeAnOrderForCosts().getMakeAnOrderForCostsYesOrNo()) + && caseData.getAssistedOrderMakeAnOrderForCosts().getMakeAnOrderForCostsYesOrNo().equals( + YES) ? "true" : null; + } + + private String getReasonsText(CaseData caseData) { + return nonNull(caseData.getFinalOrderGiveReasonsComplex()) + ? caseData.getFinalOrderGiveReasonsComplex().getReasonsText() : null; + } + + private LocalDate getWithoutNoticeDate(CaseData caseData) { + return caseData.getOrderMadeOnDetailsList().equals(OrderMadeOnTypes.WITHOUT_NOTICE) + ? caseData.getOrderMadeOnDetailsOrderWithoutNotice().getWithOutNoticeDate() : null; + } + + private LocalDate getInitiativeDate(CaseData caseData) { + return caseData.getOrderMadeOnDetailsList().equals(OrderMadeOnTypes.COURTS_INITIATIVE) + ? caseData.getOrderMadeOnDetailsOrderCourt().getOwnInitiativeDate() : null; + } + + private String isAppealGranted(CaseData caseData) { + return nonNull(caseData.getFinalOrderAppealComplex()) + && caseData.getFinalOrderAppealComplex().getApplicationList().name().equals(ApplicationAppealList.GRANTED.name()) + ? "true" : null; + } + + public String getInitiativeOrWithoutNotice(CaseData caseData) { + if (caseData.getOrderMadeOnDetailsList().equals(OrderMadeOnTypes.COURTS_INITIATIVE)) { + return caseData.getOrderMadeOnDetailsOrderCourt().getOwnInitiativeText(); + } + if (caseData.getOrderMadeOnDetailsList().equals(OrderMadeOnTypes.WITHOUT_NOTICE)) { + return caseData.getOrderMadeOnDetailsOrderWithoutNotice().getWithOutNoticeText(); + } + return null; + } + + public LocalDate getAppealDate(CaseData caseData) { + if (caseData.getFinalOrderAppealComplex() != null + && caseData.getFinalOrderAppealComplex().getApplicationList() == GRANTED) { + if (caseData.getFinalOrderAppealComplex().getAppealGrantedDropdown().getCircuitOrHighCourtList().equals( + CIRCUIT_COURT)) { + return caseData.getFinalOrderAppealComplex().getAppealGrantedDropdown().getAppealChoiceSecondDropdownA().getAppealGrantedRefusedDate(); + } else { + return caseData.getFinalOrderAppealComplex().getAppealGrantedDropdown().getAppealChoiceSecondDropdownB().getAppealGrantedRefusedDate(); + } + } + if (caseData.getFinalOrderAppealComplex() != null + && caseData.getFinalOrderAppealComplex().getApplicationList() == REFUSED) { + if (caseData.getFinalOrderAppealComplex().getAppealRefusedDropdown().getCircuitOrHighCourtListRefuse().equals(CIRCUIT_COURT)) { + return caseData.getFinalOrderAppealComplex().getAppealRefusedDropdown().getAppealChoiceSecondDropdownA().getAppealGrantedRefusedDate(); } else { - return null; + return caseData.getFinalOrderAppealComplex().getAppealRefusedDropdown().getAppealChoiceSecondDropdownB().getAppealGrantedRefusedDate(); } + } + return null; + } + + public String circuitOrHighCourt(CaseData caseData) { + if (caseData.getFinalOrderAppealComplex() != null + && caseData.getFinalOrderAppealComplex().getApplicationList() == GRANTED + && caseData.getFinalOrderAppealComplex().getAppealGrantedDropdown().getCircuitOrHighCourtList().equals(CIRCUIT_COURT)) { + return "a"; + } + if (caseData.getFinalOrderAppealComplex() != null + && caseData.getFinalOrderAppealComplex().getApplicationList() == REFUSED + && caseData.getFinalOrderAppealComplex().getAppealRefusedDropdown().getCircuitOrHighCourtListRefuse().equals(CIRCUIT_COURT)) { + return "a"; + } else { + return "b"; + } + } + + public String populateInterimPaymentText(CaseData caseData) { + return format( + "An interim payment of £%s on account of costs shall be paid by 4pm on ", + MonetaryConversions.penniesToPounds(caseData.getAssistedOrderMakeAnOrderForCosts().getAssistedOrderAssessmentThirdDropdownAmount())); + } + + public String populateSummarilyAssessedText(CaseData caseData) { + if (caseData.getAssistedOrderMakeAnOrderForCosts().getMakeAnOrderForCostsList().equals(CostEnums.CLAIMANT)) { + return format( + "The claimant shall pay the defendant's costs (both fixed and summarily assessed as appropriate) " + + "in the sum of £%s. Such sum shall be paid by 4pm on", + MonetaryConversions.penniesToPounds(caseData.getAssistedOrderMakeAnOrderForCosts().getAssistedOrderCostsFirstDropdownAmount())); + } else { + return format( + "The defendant shall pay the claimant's costs (both fixed and summarily assessed as appropriate) " + + "in the sum of £%s. Such sum shall be paid by 4pm on", + MonetaryConversions.penniesToPounds(caseData.getAssistedOrderMakeAnOrderForCosts().getAssistedOrderCostsFirstDropdownAmount())); + } + } + + public String populateDetailedAssessmentText(CaseData caseData) { + String standardOrIndemnity; + if (caseData.getAssistedOrderMakeAnOrderForCosts().getAssistedOrderAssessmentSecondDropdownList1().equals( + CostEnums.INDEMNITY_BASIS)) { + standardOrIndemnity = "on the indemnity basis if not agreed"; } else { - return null; + standardOrIndemnity = "on the standard basis if not agreed"; + } + + if (caseData.getAssistedOrderMakeAnOrderForCosts().getMakeAnOrderForCostsList().equals(CostEnums.CLAIMANT)) { + return format( + "The claimant shall pay the defendant's costs to be subject to a detailed assessment %s", + standardOrIndemnity + ); } + return format( + "The defendant shall pay the claimant's costs to be subject to a detailed assessment %s", + standardOrIndemnity + ); + } + + public Boolean isDefaultCourt(CaseData caseData) { + if (caseData.getFinalOrderFurtherHearingToggle() != null + && caseData.getFinalOrderFurtherHearingComplex() != null + && caseData.getFinalOrderFurtherHearingComplex().getHearingLocationList() != null) { + return caseData.getFinalOrderFurtherHearingComplex() + .getHearingLocationList().getValue().getCode().equals("LOCATION_LIST"); + } + return false; } public String getAppealFor(CaseData caseData) { @@ -201,7 +394,7 @@ public String getAppealFor(CaseData caseData) { if (caseData.getFinalOrderAppealComplex().getList().name().equals(OTHER.name())) { return caseData.getFinalOrderAppealComplex().getOtherText(); } else { - return caseData.getFinalOrderAppealComplex().getList().name().toLowerCase(); + return caseData.getFinalOrderAppealComplex().getList().name().toLowerCase() + "'s"; } } return ""; @@ -210,7 +403,7 @@ public String getAppealFor(CaseData caseData) { public LocalDate getFurtherHearingDate(CaseData caseData, boolean isFromDate) { if (caseData.getFinalOrderFurtherHearingToggle() != null && caseData.getFinalOrderFurtherHearingToggle().stream().anyMatch(finalOrderToggle -> finalOrderToggle.equals( - FinalOrderToggle.SHOW)) && caseData.getFinalOrderFurtherHearingComplex() != null) { + FinalOrderToggle.SHOW)) && caseData.getFinalOrderFurtherHearingComplex() != null) { if (isFromDate) { return caseData.getFinalOrderFurtherHearingComplex().getListFromDate(); } else { @@ -220,161 +413,194 @@ public LocalDate getFurtherHearingDate(CaseData caseData, boolean isFromDate) { return null; } - public boolean getIfAttended(CaseData caseData, boolean isDefendant) { - if (caseData.getFinalOrderRepresentation() != null && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex() != null) { - if (isDefendant) { - return (!(caseData.getFinalOrderRepresentation().getTypeRepresentationComplex() - .getTypeRepresentationDefendantList() - .equals(DEFENDANT_NOT_ATTENDING))); - } else { - return (!(caseData.getFinalOrderRepresentation().getTypeRepresentationComplex() - .getTypeRepresentationClaimantList() - .equals(CLAIMANT_NOT_ATTENDING))); - } - } - return false; - } - public String getFurtherHearingLength(CaseData caseData) { - if (caseData.getFinalOrderFurtherHearingComplex() != null) { - if (caseData.getFinalOrderFurtherHearingComplex().getLengthList() != null) { - switch (caseData.getFinalOrderFurtherHearingComplex().getLengthList()) { - case MINUTES_15: - return "15 minutes"; - case MINUTES_30: - return "30 minutes"; - case HOUR_1: - return "1 hour"; - case HOUR_1_5: - return "1.5 hours"; - case HOUR_2: - return "2 hours"; - default: - return ""; - } - } else if (caseData.getFinalOrderFurtherHearingComplex().getLengthListOther() != null) { - StringBuilder otherLength = new StringBuilder(); - if (caseData.getFinalOrderFurtherHearingComplex().getLengthListOther().getLengthListOtherDays() != null) { - otherLength.append(caseData.getFinalOrderFurtherHearingComplex().getLengthListOther().getLengthListOtherDays() + " days "); - } - if (caseData.getFinalOrderFurtherHearingComplex().getLengthListOther().getLengthListOtherHours() != null) { - otherLength.append(caseData.getFinalOrderFurtherHearingComplex().getLengthListOther().getLengthListOtherHours() + - " hours "); - } - if (caseData.getFinalOrderFurtherHearingComplex().getLengthListOther().getLengthListOtherMinutes() != null) { - otherLength.append(caseData.getFinalOrderFurtherHearingComplex().getLengthListOther().getLengthListOtherMinutes() + " minutes"); - } - return otherLength.toString(); + if (caseData.getFinalOrderFurtherHearingComplex() != null && caseData.getFinalOrderFurtherHearingComplex().getLengthList() != null) { + switch (caseData.getFinalOrderFurtherHearingComplex().getLengthList()) { + case MINUTES_15: + return "15 minutes"; + case MINUTES_30: + return "30 minutes"; + case HOUR_1: + return "1 hour"; + case HOUR_1_5: + return "1.5 hours"; + case HOUR_2: + return "2 hours"; + case OTHER: + return getOtherLength(caseData); + default: + return ""; } } return ""; } - private String getNotAttendedText(CaseData caseData, String party) { - if (caseData.getFinalOrderRepresentation() == null) { - return ""; - } - if (party.equals("DEFENDANT")) { - return getDefendantNotAttendedText(caseData); - } else { - return getClaimantNotAttendedText(caseData); + private String getOtherLength(CaseData caseData) { + StringBuilder otherLength = new StringBuilder(); + if (Objects.nonNull(caseData.getFinalOrderFurtherHearingComplex().getLengthListOther())) { + String otherDay = caseData.getFinalOrderFurtherHearingComplex().getLengthListOther().getLengthListOtherDays(); + String otherHour = caseData.getFinalOrderFurtherHearingComplex().getLengthListOther().getLengthListOtherHours(); + String otherMinute = caseData.getFinalOrderFurtherHearingComplex().getLengthListOther().getLengthListOtherMinutes(); + otherLength.append(Objects.nonNull(otherDay) ? (otherDay + " days ") : "") + .append(Objects.nonNull(otherHour) ? (otherHour + " hours ") : "") + .append(Objects.nonNull(otherMinute) ? (otherMinute + " minutes") : ""); } + return otherLength.toString(); } - public String getClaimantNotAttendedText(CaseData caseData) { - if (caseData.getFinalOrderRepresentation().getTypeRepresentationComplex() != null - && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureClaimantComplex() != null - && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureClaimantComplex().getList() != null) { - FinalOrdersClaimantDefendantNotAttending notAttendingType = - caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureClaimantComplex().getList(); - switch (notAttendingType) { - case NOT_SATISFIED_NOTICE_OF_TRIAL: - return "The claimant did not attend the trial, " + - "but the Judge was not satisfied that they had received notice of the hearing and it was not reasonable to proceed in their absence"; - case SATISFIED_NOTICE_OF_TRIAL: - return "The claimant did not attend the trial and whilst the Judge was satisfied that they had " + - "received notice of the trial it was not reasonable to proceed in their absence"; - case SATISFIED_REASONABLE_TO_PROCEED: - return "The claimant did not attend the trial, but the Judge was satisfied that they had received" + - " notice" + - " of the trial and it was reasonable to proceed in their absence"; - default: - return ""; + public String orderMadeDateBuilder(CaseData caseData) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy", Locale.ENGLISH); + if (caseData.getFinalOrderDateHeardComplex() != null) { + if (caseData.getFinalOrderDateHeardComplex().getSingleDateSelection() != null) { + LocalDate date1 = caseData.getFinalOrderDateHeardComplex().getSingleDateSelection().getSingleDate(); + return format("on %s", date1.format(formatter)); + + } + if (caseData.getFinalOrderDateHeardComplex().getDateRangeSelection() != null) { + LocalDate date1 = caseData.getFinalOrderDateHeardComplex().getDateRangeSelection().getDateRangeFrom(); + LocalDate date2 = caseData.getFinalOrderDateHeardComplex().getDateRangeSelection().getDateRangeTo(); + return format("between %s and %s", date1.format(formatter), date2.format(formatter)); + } + if (caseData.getFinalOrderDateHeardComplex().getBespokeRangeSelection() != null) { + return format( + "on %s", + caseData.getFinalOrderDateHeardComplex().getBespokeRangeSelection().getBespokeRangeTextArea() + ); } } - return ""; + return null; } - public String getDefendantNotAttendedText(CaseData caseData) { - if (caseData.getFinalOrderRepresentation().getTypeRepresentationComplex() != null - && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureComplex() != null - && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureComplex().getListDef() != null) { - FinalOrdersClaimantDefendantNotAttending notAttendingType = - caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureComplex().getListDef(); - switch (notAttendingType) { - case NOT_SATISFIED_NOTICE_OF_TRIAL: - return "The defendant did not attend the trial," + - " but the Judge was not satisfied that they had received notice of the hearing and it was not reasonable to proceed in their absence"; - case SATISFIED_NOTICE_OF_TRIAL: - return "The defendant did not attend the trial and whilst the Judge was satisfied " + - "that they had received notice of the trial it was not reasonable to proceed in their absence"; - case SATISFIED_REASONABLE_TO_PROCEED: - return "The defendant did not attend the trial," + - " but the Judge was satisfied that they had received notice of the trial and it was reasonable to proceed in their absence"; - default: - return ""; + public String claimantAttendsOrRepresentedTextBuilder(CaseData caseData, Boolean isClaimant2) { + String name; + if (isClaimant2 != null && !isClaimant2) { + name = caseData.getApplicant1().getPartyName(); + if (caseData.getFinalOrderRepresentation() != null && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex() != null + && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationClaimantList() != null) { + FinalOrdersClaimantRepresentationList type = + caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationClaimantList(); + return switch (type) { + case COUNSEL_FOR_CLAIMANT -> format("Counsel for %s, the claimant.", name); + case SOLICITOR_FOR_CLAIMANT -> format("Solicitor for %s, the claimant.", name); + case COST_DRAFTSMAN_FOR_THE_CLAIMANT -> format("Costs draftsman for %s, the claimant.", name); + case THE_CLAIMANT_IN_PERSON -> format("%s, the claimant, in person.", name); + case LAY_REPRESENTATIVE_FOR_THE_CLAIMANT -> format("A lay representative for %s, the claimant.", name); + case CLAIMANT_NOT_ATTENDING -> claimantNotAttendingText(caseData, isClaimant2, name); + }; + } + } else { + name = caseData.getApplicant2().getPartyName(); + if (caseData.getFinalOrderRepresentation() != null && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex() != null + && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationClaimantListTwo() != null) { + FinalOrdersClaimantRepresentationList type = + caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationClaimantListTwo(); + return switch (type) { + case COUNSEL_FOR_CLAIMANT -> format("Counsel for %s, the claimant.", name); + case SOLICITOR_FOR_CLAIMANT -> format("Solicitor for %s, the claimant.", name); + case COST_DRAFTSMAN_FOR_THE_CLAIMANT -> format("Costs draftsman for %s, the claimant.", name); + case THE_CLAIMANT_IN_PERSON -> format("%s, the claimant, in person.", name); + case LAY_REPRESENTATIVE_FOR_THE_CLAIMANT -> format("A lay representative for %s, the claimant.", name); + case CLAIMANT_NOT_ATTENDING -> claimantNotAttendingText(caseData, isClaimant2, name); + }; } } return ""; } - public String getRepresentedClaimant(CaseData caseData) { - if (caseData.getFinalOrderRepresentation() != null && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex() != null - && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationClaimantList() != null) { - FinalOrdersClaimantRepresentationList type = - caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationClaimantList(); - switch (type) { - case COUNSEL_FOR_CLAIMANT: - return "counsel for claimant"; - case SOLICITOR_FOR_CLAIMANT: - return "solicitor for claimant"; - case COST_DRAFTSMAN_FOR_THE_CLAIMANT: - return "costs draftsman for the claimant"; - case THE_CLAIMANT_IN_PERSON: - return "the claimant in person"; - case LAY_REPRESENTATIVE_FOR_THE_CLAIMANT: - return "lay representative for the claimant"; - default: return ""; + public String defendantAttendsOrRepresentedTextBuilder(CaseData caseData, Boolean isDefendant2) { + String name; + if (isDefendant2 != null && !isDefendant2) { + name = caseData.getRespondent1().getPartyName(); + if (caseData.getFinalOrderRepresentation() != null && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex() != null + && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationDefendantList() != null) { + FinalOrdersDefendantRepresentationList type = + caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationDefendantList(); + return switch (type) { + case COUNSEL_FOR_DEFENDANT -> format("Counsel for %s, the defendant.", name); + case SOLICITOR_FOR_DEFENDANT -> format("Solicitor for %s, the defendant.", name); + case COST_DRAFTSMAN_FOR_THE_DEFENDANT -> format("Costs draftsman for %s, the defendant.", name); + case THE_DEFENDANT_IN_PERSON -> format("%s, the defendant, in person.", name); + case LAY_REPRESENTATIVE_FOR_THE_DEFENDANT -> format("A lay representative for %s, the defendant.", name + ); + case DEFENDANT_NOT_ATTENDING -> defendantNotAttendingText(caseData, isDefendant2, name); + }; + } + } else { + name = caseData.getRespondent2().getPartyName(); + if (caseData.getFinalOrderRepresentation() != null && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex() != null + && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationDefendantTwoList() != null) { + FinalOrdersDefendantRepresentationList type = + caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationDefendantTwoList(); + return switch (type) { + case COUNSEL_FOR_DEFENDANT -> format("Counsel for %s, the defendant.", name); + case SOLICITOR_FOR_DEFENDANT -> format("Solicitor for %s, the defendant.", name); + case COST_DRAFTSMAN_FOR_THE_DEFENDANT -> format("Costs draftsman for %s, the defendant.", name); + case THE_DEFENDANT_IN_PERSON -> format("%s, the defendant, in person.", name); + case LAY_REPRESENTATIVE_FOR_THE_DEFENDANT -> format("A lay representative for %s, the defendant.", name); + case DEFENDANT_NOT_ATTENDING -> defendantNotAttendingText(caseData, isDefendant2, name); + }; } } return ""; } - public String getRepresentedDefendant(CaseData caseData) { - if (caseData.getFinalOrderRepresentation() != null && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex() != null - && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationDefendantList() != null) { - FinalOrdersDefendantRepresentationList type = - caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTypeRepresentationDefendantList(); - switch (type) { - case COUNSEL_FOR_DEFENDANT: - return "counsel for defendant"; - case SOLICITOR_FOR_DEFENDANT: - return "solicitor for defendant"; - case COST_DRAFTSMAN_FOR_THE_DEFENDANT: - return "costs draftsman for the defendant"; - case THE_DEFENDANT_IN_PERSON: - return "the defendant in person"; - case LAY_REPRESENTATIVE_FOR_THE_DEFENDANT: - return "lay representative for the defendant"; - default: return ""; - } + public String claimantNotAttendingText(CaseData caseData, Boolean isClaimant2, String name) { + if (isClaimant2 != null && !isClaimant2 && (caseData.getFinalOrderRepresentation().getTypeRepresentationComplex() != null + && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureClaimantComplex() != null + && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureClaimantComplex().getList() != null)) { + FinalOrdersClaimantDefendantNotAttending notAttendingType = + caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureClaimantComplex().getList(); + return switch (notAttendingType) { + case SATISFIED_REASONABLE_TO_PROCEED -> format( + "%s, the claimant, did not attend the trial. The Judge was satisfied that they had %s", name, NOTICE_RECIEVED_CAN_PROCEED); + case SATISFIED_NOTICE_OF_TRIAL -> format( + "%s, the claimant, did not attend the trial and, whilst the Judge was satisfied that they had %s", name, NOTICE_RECIEVED_CANNOT_PROCEED); + case NOT_SATISFIED_NOTICE_OF_TRIAL -> format( + "%s, the claimant, did not attend the trial. %s", name, NOTICE_NOT_RECIEVED_CANNOT_PROCEED); + }; + } else if (caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedClaimTwoComplex() != null + && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedClaimTwoComplex().getListClaimTwo() != null) { + FinalOrdersClaimantDefendantNotAttending notAttendingType = + caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedClaimTwoComplex().getListClaimTwo(); + return switch (notAttendingType) { + case SATISFIED_REASONABLE_TO_PROCEED -> format( + "%s, the claimant, did not attend the trial. The Judge was satisfied that they had %s", name, NOTICE_RECIEVED_CAN_PROCEED); + case SATISFIED_NOTICE_OF_TRIAL -> format( + "%s, the claimant, did not attend the trial and, whilst the Judge was satisfied that they had %s", name, NOTICE_RECIEVED_CANNOT_PROCEED); + case NOT_SATISFIED_NOTICE_OF_TRIAL -> format("%s, the claimant, did not attend the trial. %s", name, NOTICE_NOT_RECIEVED_CANNOT_PROCEED + ); + }; } return ""; } - private boolean hasSDOBeenMade(CaseState state) { + public String defendantNotAttendingText(CaseData caseData, Boolean isDefendant2, String name) { + if (isDefendant2 != null && !isDefendant2 && (caseData.getFinalOrderRepresentation().getTypeRepresentationComplex() != null + && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureComplex() != null + && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureComplex().getListDef() != null)) { + FinalOrdersClaimantDefendantNotAttending notAttendingType = + caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureComplex().getListDef(); + return switch (notAttendingType) { + case SATISFIED_REASONABLE_TO_PROCEED -> format("%s, the defendant, did not attend the trial. " + + "The Judge was satisfied that they had %s", name, NOTICE_RECIEVED_CAN_PROCEED); + case SATISFIED_NOTICE_OF_TRIAL -> format("%s, the defendant, did not attend the trial and, whilst the " + + "Judge was satisfied that they had %s", name, NOTICE_RECIEVED_CANNOT_PROCEED); + case NOT_SATISFIED_NOTICE_OF_TRIAL -> format("%s, the defendant, did not attend the trial. %s", name, NOTICE_NOT_RECIEVED_CANNOT_PROCEED); + }; - return !JUDICIAL_REFERRAL.equals(state); + } else if (caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureDefTwoComplex() != null + && caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureDefTwoComplex().getListDefTwo() != null) { + FinalOrdersClaimantDefendantNotAttending notAttendingType = + caseData.getFinalOrderRepresentation().getTypeRepresentationComplex().getTrialProcedureDefTwoComplex().getListDefTwo(); + return switch (notAttendingType) { + case SATISFIED_REASONABLE_TO_PROCEED -> format("%s, the defendant, did not attend the trial." + + " The Judge was satisfied that they had %s", name, NOTICE_RECIEVED_CAN_PROCEED); + case SATISFIED_NOTICE_OF_TRIAL -> format("%s, the defendant, did not attend the trial and, " + + "whilst the Judge was satisfied that they had %s", name, NOTICE_RECIEVED_CANNOT_PROCEED); + case NOT_SATISFIED_NOTICE_OF_TRIAL -> format("%s, the defendant, did not attend the trial. %s", name, NOTICE_NOT_RECIEVED_CANNOT_PROCEED); + }; + } + return ""; } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dj/DefaultJudgmentOrderFormGenerator.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dj/DefaultJudgmentOrderFormGenerator.java index f37a2c1eebc..1d6f4200f15 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dj/DefaultJudgmentOrderFormGenerator.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dj/DefaultJudgmentOrderFormGenerator.java @@ -133,7 +133,8 @@ private DefaultJudgmentSDOOrderForm getDefaultJudgmentFormHearing(CaseData caseD .disposalHearingCostsAddSection(getToggleValue(caseData.getDisposalHearingCostsDJToggle())) .applicant(checkApplicantPartyName(caseData) ? caseData.getApplicant1().getPartyName().toUpperCase() : null) - .respondent(checkDefendantRequested(caseData).toUpperCase()); + .respondent(checkDefendantRequested(caseData).toUpperCase()) + .caseManagementLocation(locationHelper.getHearingLocation(null, caseData, authorisation)); djOrderFormBuilder .disposalHearingOrderMadeWithoutHearingDJ(caseData.getDisposalHearingOrderMadeWithoutHearingDJ()) @@ -146,8 +147,7 @@ private DefaultJudgmentSDOOrderForm getDefaultJudgmentFormHearing(CaseData caseD } private DefaultJudgmentSDOOrderForm getDefaultJudgmentFormTrial(CaseData caseData, String authorisation) { - String trialHearingLocation = checkDisposalHearingMethod(caseData.getTrialHearingMethodDJ()) - ? getDynamicListValueLabel(caseData.getTrialHearingMethodInPersonDJ()) : null; + String trialHearingLocation = getDynamicListValueLabel(caseData.getTrialHearingMethodInPersonDJ()); UserDetails userDetails = idamClient.getUserDetails(authorisation); boolean isJudge = false; @@ -207,6 +207,7 @@ private DefaultJudgmentSDOOrderForm getDefaultJudgmentFormTrial(CaseData caseDat && caseData.getTrialHearingTimeDJ().getDateToToggle() != null) .trialOrderMadeWithoutHearingDJ(caseData.getTrialOrderMadeWithoutHearingDJ()) .trialHearingTimeEstimateDJ(getHearingTimeEstimateLabel(caseData.getTrialHearingTimeDJ())) + .caseManagementLocation(locationHelper.getHearingLocation(null, caseData, authorisation)) .hearingLocation(locationHelper.getHearingLocation( trialHearingLocation, caseData, diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipClaimantFormMapper.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipClaimantFormMapper.java new file mode 100644 index 00000000000..55a29e02f51 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipClaimantFormMapper.java @@ -0,0 +1,43 @@ +package uk.gov.hmcts.reform.civil.service.docmosis.dq; + +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; +import uk.gov.hmcts.reform.civil.model.citizenui.ClaimantLiPResponse; +import uk.gov.hmcts.reform.civil.model.citizenui.DQExtraDetailsLip; +import uk.gov.hmcts.reform.civil.model.citizenui.ExpertLiP; +import uk.gov.hmcts.reform.civil.model.citizenui.HearingSupportLip; +import uk.gov.hmcts.reform.civil.model.docmosis.dq.HearingLipSupportRequirements; + +import java.util.List; +import java.util.Optional; + +import static uk.gov.hmcts.reform.civil.model.docmosis.dq.HearingLipSupportRequirements.toHearingSupportRequirementsList; + +public class DQLipClaimantFormMapper extends DQLipFormMapper { + + @Override + protected List toHearingSupportRequirements(Optional caseDataLiPOptional) { + Optional hearingLipSupportRequirements = caseDataLiPOptional + .map(CaseDataLiP::getApplicant1LiPResponse) + .map(ClaimantLiPResponse::getApplicant1DQHearingSupportLip); + return toHearingSupportRequirementsList(hearingLipSupportRequirements); + } + + @Override + protected DQExtraDetailsLip getDQExtraDetails(Optional caseDataLiPOptional) { + return caseDataLiPOptional + .map(CaseDataLiP::getApplicant1LiPResponse) + .map(ClaimantLiPResponse::getApplicant1DQExtraDetails) + .orElse(null); + } + + @Override + protected Optional getExpertLip(DQExtraDetailsLip dqExtraDetailsLip) { + return Optional.ofNullable(dqExtraDetailsLip).map(DQExtraDetailsLip::getApplicant1DQLiPExpert); + } + + @Override + protected String getStatementOfTruthName(CaseData caseData) { + return caseData.getApplicant1().getPartyName(); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipDefendantFormMapper.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipDefendantFormMapper.java new file mode 100644 index 00000000000..87bf708c7a2 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipDefendantFormMapper.java @@ -0,0 +1,41 @@ +package uk.gov.hmcts.reform.civil.service.docmosis.dq; + +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; +import uk.gov.hmcts.reform.civil.model.citizenui.DQExtraDetailsLip; +import uk.gov.hmcts.reform.civil.model.citizenui.ExpertLiP; +import uk.gov.hmcts.reform.civil.model.citizenui.HearingSupportLip; +import uk.gov.hmcts.reform.civil.model.citizenui.RespondentLiPResponse; +import uk.gov.hmcts.reform.civil.model.docmosis.dq.HearingLipSupportRequirements; + +import java.util.List; +import java.util.Optional; + +import static uk.gov.hmcts.reform.civil.model.docmosis.dq.HearingLipSupportRequirements.toHearingSupportRequirementsList; + +public class DQLipDefendantFormMapper extends DQLipFormMapper { + + @Override + protected List toHearingSupportRequirements(Optional caseDataLiPOptional) { + Optional hearingLipSupportRequirements = caseDataLiPOptional + .map(CaseDataLiP::getRespondent1LiPResponse) + .map(RespondentLiPResponse::getRespondent1DQHearingSupportLip); + return toHearingSupportRequirementsList(hearingLipSupportRequirements); + } + + @Override + protected DQExtraDetailsLip getDQExtraDetails(Optional caseDataLiPOptional) { + return caseDataLiPOptional.map(CaseDataLiP::getRespondent1LiPResponse) + .map(RespondentLiPResponse::getRespondent1DQExtraDetails).orElse(null); + } + + @Override + protected Optional getExpertLip(DQExtraDetailsLip dqExtraDetailsLip) { + return Optional.ofNullable(dqExtraDetailsLip).map(DQExtraDetailsLip::getRespondent1DQLiPExpert); + } + + @Override + protected String getStatementOfTruthName(CaseData caseData) { + return caseData.getRespondent1().getPartyName(); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipFormMapper.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipFormMapper.java new file mode 100644 index 00000000000..cdfbbec2aa3 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipFormMapper.java @@ -0,0 +1,63 @@ +package uk.gov.hmcts.reform.civil.service.docmosis.dq; + +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; +import uk.gov.hmcts.reform.civil.model.citizenui.DQExtraDetailsLip; +import uk.gov.hmcts.reform.civil.model.citizenui.ExpertLiP; +import uk.gov.hmcts.reform.civil.model.docmosis.dq.DirectionsQuestionnaireForm; +import uk.gov.hmcts.reform.civil.model.docmosis.dq.HearingLipSupportRequirements; +import uk.gov.hmcts.reform.civil.model.docmosis.dq.LipExperts; +import uk.gov.hmcts.reform.civil.model.docmosis.dq.LipExtraDQ; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static uk.gov.hmcts.reform.civil.model.docmosis.dq.ExpertReportTemplate.toExpertReportTemplate; + +public abstract class DQLipFormMapper { + + protected abstract List toHearingSupportRequirements(Optional caseDataLiPOptional); + + protected abstract DQExtraDetailsLip getDQExtraDetails(Optional caseDataLiPOptional); + + protected abstract Optional getExpertLip(DQExtraDetailsLip dqExtraDetailsLip); + + protected abstract String getStatementOfTruthName(CaseData caseData); + + public DirectionsQuestionnaireForm addLipDQs(DirectionsQuestionnaireForm form, Optional caseDataLiPOptional) { + var builder = form.toBuilder(); + builder.hearingLipSupportRequirements(toHearingSupportRequirements(caseDataLiPOptional)); + var dqExtraDetails = getDQExtraDetails(caseDataLiPOptional); + var expertLip = getExpertLip(dqExtraDetails); + if (dqExtraDetails != null) { + builder.lipExtraDQ(LipExtraDQ.builder().triedToSettle(dqExtraDetails.getTriedToSettle()) + .requestExtra4weeks(dqExtraDetails.getRequestExtra4weeks()) + .considerClaimantDocuments(dqExtraDetails.getConsiderClaimantDocuments()) + .considerClaimantDocumentsDetails(dqExtraDetails.getConsiderClaimantDocumentsDetails()) + .determinationWithoutHearingRequired(dqExtraDetails.getDeterminationWithoutHearingRequired()) + .determinationWithoutHearingReason(dqExtraDetails.getDeterminationWithoutHearingReason()) + .giveEvidenceYourSelf(dqExtraDetails.getGiveEvidenceYourSelf()) + .whyPhoneOrVideoHearing(dqExtraDetails.getWhyPhoneOrVideoHearing()) + .wantPhoneOrVideoHearing(dqExtraDetails.getWantPhoneOrVideoHearing()) + .build()) + .lipExperts(LipExperts.builder() + .details(expertLip.map(ExpertLiP::getUnwrappedDetails).map(Collection::stream) + .map(stream -> stream.map(item -> toExpertReportTemplate(item)).toList()) + .orElse(Collections.emptyList())) + .caseNeedsAnExpert(expertLip + .map(ExpertLiP::getCaseNeedsAnExpert).orElse(null)) + .expertCanStillExamineDetails(expertLip + .map(ExpertLiP::getExpertCanStillExamineDetails) + .orElse(null)) + .expertReportRequired(expertLip + .map(ExpertLiP::getExpertReportRequired) + .orElse(null)) + + .build()); + + } + return builder.build(); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipFormMapperFactory.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipFormMapperFactory.java new file mode 100644 index 00000000000..20b1bf4a2c6 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipFormMapperFactory.java @@ -0,0 +1,19 @@ +package uk.gov.hmcts.reform.civil.service.docmosis.dq; + +import uk.gov.hmcts.reform.civil.model.CaseData; + +public class DQLipFormMapperFactory { + + public static String CLAIMANT_LIP_RESPONSE_PROCESS = "CLAIMANT_RESPONSE_CUI"; + + public DQLipFormMapper getDQLipFormMapper(CaseData caseData) { + if (isClaimantLipResponse(caseData)) { + return new DQLipClaimantFormMapper(); + } + return new DQLipDefendantFormMapper(); + } + + private boolean isClaimantLipResponse(CaseData caseData) { + return CLAIMANT_LIP_RESPONSE_PROCESS.equals(caseData.getCurrentCamundaBusinessProcessName()); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionQuestionnaireLipGeneratorFactory.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionQuestionnaireLipGeneratorFactory.java new file mode 100644 index 00000000000..cd3d8844e8f --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionQuestionnaireLipGeneratorFactory.java @@ -0,0 +1,21 @@ +package uk.gov.hmcts.reform.civil.service.docmosis.dq; + +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; + +@Component +@RequiredArgsConstructor +public class DirectionQuestionnaireLipGeneratorFactory { + + private final FeatureToggleService featureToggleService; + private final DirectionsQuestionnaireLipGenerator directionsQuestionnaireLipGenerator; + private final DirectionQuestionnaireLipResponseGenerator directionQuestionnaireLipResponseGenerator; + + public DirectionsQuestionnaireGenerator getDirectionQuestionnaire() { + if (featureToggleService.isLipVLipEnabled()) { + return directionQuestionnaireLipResponseGenerator; + } + return directionsQuestionnaireLipGenerator; + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionQuestionnaireLipResponseGenerator.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionQuestionnaireLipResponseGenerator.java new file mode 100644 index 00000000000..5df9aefae14 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionQuestionnaireLipResponseGenerator.java @@ -0,0 +1,72 @@ +package uk.gov.hmcts.reform.civil.service.docmosis.dq; + +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.civil.documentmanagement.DocumentManagementService; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.docmosis.common.Party; +import uk.gov.hmcts.reform.civil.model.docmosis.dq.DirectionsQuestionnaireForm; +import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; +import uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates; +import uk.gov.hmcts.reform.civil.service.docmosis.DocumentGeneratorService; +import uk.gov.hmcts.reform.civil.service.docmosis.RepresentativeService; +import uk.gov.hmcts.reform.civil.service.flowstate.StateFlowEngine; + +import java.util.List; +import java.util.Optional; + +import static uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates.DQ_LIP_RESPONSE; + +@Service +public class DirectionQuestionnaireLipResponseGenerator extends DirectionsQuestionnaireGenerator { + + private static final DQLipFormMapperFactory MAPPER_FACTORY = new DQLipFormMapperFactory(); + + public DirectionQuestionnaireLipResponseGenerator(DocumentManagementService documentManagementService, + DocumentGeneratorService documentGeneratorService, + StateFlowEngine stateFlowEngine, + RepresentativeService representativeService, + FeatureToggleService featureToggleService, + LocationRefDataService locationRefDataService) { + super( + documentManagementService, + documentGeneratorService, + stateFlowEngine, + representativeService, + featureToggleService, + locationRefDataService + ); + } + + @Override + public DirectionsQuestionnaireForm getTemplateData(CaseData caseData, String authorisation) { + DirectionsQuestionnaireForm.DirectionsQuestionnaireFormBuilder builder = getDirectionsQuestionnaireFormBuilder( + caseData, + authorisation + ); + DQLipFormMapper mapper = MAPPER_FACTORY.getDQLipFormMapper(caseData); + builder.lipStatementOfTruthName(mapper.getStatementOfTruthName(caseData)) + .applicant(Party.toLipParty(caseData.getApplicant1())) + .respondent1LiPCorrespondenceAddress(caseData.getRespondent1CorrespondenceAddress()); + return mapper.addLipDQs(builder.build(), Optional.ofNullable(caseData.getCaseDataLiP())); + } + + @Override + protected DocmosisTemplates getTemplateId(CaseData caseData) { + if ((caseData.isRespondent1NotRepresented() || caseData.isApplicantNotRepresented()) + && getFeatureToggleService().isLipVLipEnabled()) { + return DQ_LIP_RESPONSE; + } + return super.getTemplateId(caseData); + } + + @Override + protected List getApplicants(CaseData caseData) { + return List.of(Party.toLipParty(caseData.getApplicant1())); + } + + @Override + protected List getRespondents(CaseData caseData, String defendantIdentifier) { + return List.of(Party.toLipParty(caseData.getRespondent1())); + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionsQuestionnaireGenerator.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionsQuestionnaireGenerator.java index 13ece23ef77..ea108e89eb0 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionsQuestionnaireGenerator.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionsQuestionnaireGenerator.java @@ -322,7 +322,7 @@ protected DirectionsQuestionnaireForm.DirectionsQuestionnaireFormBuilder getDire return builder; } - private List getApplicants(CaseData caseData) { + protected List getApplicants(CaseData caseData) { var legalRepHeading = caseData.getCaseAccessCategory().equals(SPEC_CLAIM) ? "Name" : "Organisation name"; var applicant = caseData.getApplicant1(); var applicant2 = caseData.getApplicant2(); @@ -558,12 +558,12 @@ private DisclosureReport getDisclosureReport(DQ dq) { } public static boolean isClaimantResponse(CaseData caseData) { - return "CLAIMANT_RESPONSE".equals(ofNullable(caseData.getBusinessProcess()) - .map(BusinessProcess::getCamundaEvent) - .orElse(null)) - || "CLAIMANT_RESPONSE_SPEC".equals(ofNullable(caseData.getBusinessProcess()) - .map(BusinessProcess::getCamundaEvent) - .orElse(null)); + var businessProcess = ofNullable(caseData.getBusinessProcess()) + .map(BusinessProcess::getCamundaEvent) + .orElse(null); + return "CLAIMANT_RESPONSE".equals(businessProcess) + || "CLAIMANT_RESPONSE_SPEC".equals(businessProcess) + || "CLAIMANT_RESPONSE_CUI".equals(businessProcess); } private boolean isClaimantMultipartyProceed(CaseData caseData) { diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionsQuestionnaireLipGenerator.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionsQuestionnaireLipGenerator.java index 6302384565f..598d19f4bf5 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionsQuestionnaireLipGenerator.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionsQuestionnaireLipGenerator.java @@ -59,10 +59,7 @@ public DirectionsQuestionnaireForm getTemplateData(CaseData caseData, String aut caseData, authorisation ); - builder.respondent1LiPCorrespondenceAddress(Optional.ofNullable(caseData.getCaseDataLiP()) - .map(CaseDataLiP::getRespondent1LiPResponse) - .map(RespondentLiPResponse::getRespondent1LiPCorrespondenceAddress) - .orElse(null)) + builder.respondent1LiPCorrespondenceAddress(caseData.getRespondent1CorrespondenceAddress()) .hearingLipSupportRequirements(Optional.ofNullable( caseData.getCaseDataLiP()) .map( diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingFormGenerator.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingFormGenerator.java index e9f4cdd73cc..ea16e212bc2 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingFormGenerator.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingFormGenerator.java @@ -2,6 +2,8 @@ import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; + +import uk.gov.hmcts.reform.civil.enums.DocCategory; import uk.gov.hmcts.reform.civil.helpers.DateFormatHelper; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.docmosis.DocmosisDocument; @@ -13,6 +15,7 @@ import uk.gov.hmcts.reform.civil.service.docmosis.DocumentGeneratorService; import uk.gov.hmcts.reform.civil.service.docmosis.TemplateDataGenerator; import uk.gov.hmcts.reform.civil.documentmanagement.DocumentManagementService; +import uk.gov.hmcts.reform.civil.utils.AssignCategoryId; import uk.gov.hmcts.reform.civil.utils.HearingUtils; import java.time.LocalDate; @@ -35,6 +38,7 @@ public class HearingFormGenerator implements TemplateDataGenerator private final DocumentManagementService documentManagementService; private final DocumentGeneratorService documentGeneratorService; + private final AssignCategoryId assignCategoryId; public List generate(CaseData caseData, String authorisation) { @@ -43,14 +47,16 @@ public List generate(CaseData caseData, String authorisation) { DocmosisTemplates template = getTemplate(caseData); DocmosisDocument document = documentGeneratorService.generateDocmosisDocument(templateData, template); - caseDocuments.add(documentManagementService.uploadDocument( - authorisation, - new PDF( - getFileName(caseData, template), - document.getBytes(), - DocumentType.HEARING_FORM - ) - )); + CaseDocument caseDocument = documentManagementService.uploadDocument( + authorisation, + new PDF( + getFileName(caseData, template), + document.getBytes(), + DocumentType.HEARING_FORM + ) + ); + assignCategoryId.assignCategoryIdToCaseDocument(caseDocument, DocCategory.HEARING_NOTICES.getValue()); + caseDocuments.add(caseDocument); return caseDocuments; } @@ -58,6 +64,7 @@ public List generate(CaseData caseData, String authorisation) { public HearingForm getTemplateData(CaseData caseData) { return HearingForm.builder() + .listingOrRelisting(caseData.getListingOrRelisting().toString()) .court(caseData.getHearingLocation().getValue().getLabel()) .caseNumber(caseData.getLegacyCaseReference()) .creationDate(getDateFormatted(LocalDate.now())) diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingNoticeHmcGenerator.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingNoticeHmcGenerator.java index 8d3646a2e13..9cbf7fc5e24 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingNoticeHmcGenerator.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingNoticeHmcGenerator.java @@ -7,6 +7,7 @@ import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType; import uk.gov.hmcts.reform.civil.documentmanagement.model.PDF; +import uk.gov.hmcts.reform.civil.enums.DocCategory; import uk.gov.hmcts.reform.civil.enums.PaymentStatus; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.docmosis.DocmosisDocument; @@ -17,6 +18,7 @@ import uk.gov.hmcts.reform.civil.service.docmosis.DocumentGeneratorService; import uk.gov.hmcts.reform.civil.service.docmosis.TemplateDataGenerator; import uk.gov.hmcts.reform.civil.service.hearings.HearingFeesService; +import uk.gov.hmcts.reform.civil.utils.AssignCategoryId; import uk.gov.hmcts.reform.civil.utils.HearingFeeUtils; import uk.gov.hmcts.reform.civil.utils.HearingUtils; import uk.gov.hmcts.reform.civil.utils.HmcDataUtils; @@ -39,6 +41,7 @@ public class HearingNoticeHmcGenerator implements TemplateDataGenerator generate(CaseData caseData, HearingGetResponse hearing, String authorisation) { @@ -52,7 +55,9 @@ public List generate(CaseData caseData, HearingGetResponse hearing document.getBytes(), DocumentType.HEARING_FORM ); - caseDocuments.add(documentManagementService.uploadDocument(authorisation, pdf)); + CaseDocument caseDocument = documentManagementService.uploadDocument(authorisation, pdf); + assignCategoryId.assignCategoryIdToCaseDocument(caseDocument, DocCategory.HEARING_NOTICES.getValue()); + caseDocuments.add(caseDocument); return caseDocuments; } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sdo/SdoGeneratorService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sdo/SdoGeneratorService.java index 5518be04434..dec7b81724d 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sdo/SdoGeneratorService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sdo/SdoGeneratorService.java @@ -6,9 +6,7 @@ import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType; import uk.gov.hmcts.reform.civil.documentmanagement.model.PDF; -import uk.gov.hmcts.reform.civil.enums.sdo.DisposalHearingMethod; -import uk.gov.hmcts.reform.civil.enums.sdo.FastTrackMethod; -import uk.gov.hmcts.reform.civil.enums.sdo.SmallClaimsMethod; +import uk.gov.hmcts.reform.civil.enums.sdo.DisposalHearingFinalDisposalHearingTimeEstimate; import uk.gov.hmcts.reform.civil.helpers.sdo.SdoHelper; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.common.DynamicList; @@ -18,6 +16,7 @@ import uk.gov.hmcts.reform.civil.model.docmosis.sdo.SdoDocumentFormDisposal; import uk.gov.hmcts.reform.civil.model.docmosis.sdo.SdoDocumentFormFast; import uk.gov.hmcts.reform.civil.model.docmosis.sdo.SdoDocumentFormSmall; +import uk.gov.hmcts.reform.civil.model.sdo.DisposalHearingHearingTime; import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates; import uk.gov.hmcts.reform.civil.service.docmosis.DocumentGeneratorService; @@ -163,26 +162,22 @@ private SdoDocumentFormDisposal getTemplateDataDisposal(CaseData caseData, Strin sdoDocumentBuilder .disposalOrderWithoutHearing(caseData.getDisposalOrderWithoutHearing()) - .disposalHearingTime(caseData.getDisposalHearingHearingTime()) - .disposalHearingTimeEstimate(SdoHelper.getDisposalHearingTimeLabel(caseData)); + .disposalHearingTime(caseData.getDisposalHearingHearingTime()); + Optional.ofNullable(caseData.getDisposalHearingHearingTime()) + .map(DisposalHearingHearingTime::getTime) + .map(DisposalHearingFinalDisposalHearingTimeEstimate::getLabel) + .ifPresent(sdoDocumentBuilder::disposalHearingTimeEstimate); - if (caseData.getDisposalHearingMethod() == DisposalHearingMethod.disposalHearingMethodInPerson) { - sdoDocumentBuilder.hearingLocation( - locationHelper.getHearingLocation( - Optional.ofNullable(caseData.getDisposalHearingMethodInPerson()) - .map(DynamicList::getValue) - .map(DynamicListElement::getLabel) - .orElse(null), - caseData, - authorisation - )); - } else { - sdoDocumentBuilder.hearingLocation(locationHelper.getHearingLocation( - null, + sdoDocumentBuilder.hearingLocation( + locationHelper.getHearingLocation( + Optional.ofNullable(caseData.getDisposalHearingMethodInPerson()) + .map(DynamicList::getValue) + .map(DynamicListElement::getLabel) + .orElse(null), caseData, authorisation - )); - } + )) + .caseManagementLocation(locationHelper.getHearingLocation(null, caseData, authorisation)); return sdoDocumentBuilder.build(); } @@ -291,23 +286,16 @@ private SdoDocumentFormFast getTemplateDataFast(CaseData caseData, String judgeN .fastTrackHearingTime(caseData.getFastTrackHearingTime()) .fastTrackHearingTimeEstimate(SdoHelper.getFastClaimsHearingTimeLabel(caseData)); - if (caseData.getFastTrackMethod() == FastTrackMethod.fastTrackMethodInPerson) { - sdoDocumentFormBuilder - .hearingLocation(locationHelper.getHearingLocation( - Optional.ofNullable(caseData.getFastTrackMethodInPerson()) - .map(DynamicList::getValue) - .map(DynamicListElement::getLabel) - .orElse(null), - caseData, - authorisation - )); - } else { - sdoDocumentFormBuilder.hearingLocation(locationHelper.getHearingLocation( - null, + sdoDocumentFormBuilder + .hearingLocation(locationHelper.getHearingLocation( + Optional.ofNullable(caseData.getFastTrackMethodInPerson()) + .map(DynamicList::getValue) + .map(DynamicListElement::getLabel) + .orElse(null), caseData, authorisation - )); - } + )) + .caseManagementLocation(locationHelper.getHearingLocation(null, caseData, authorisation)); return sdoDocumentFormBuilder.build(); } @@ -378,8 +366,7 @@ private SdoDocumentFormSmall getTemplateDataSmall(CaseData caseData, String judg SdoHelper.hasSmallClaimsVariable(caseData, "smallClaimsNumberOfWitnessesToggle") ); - if (caseData.getSmallClaimsMethod() == SmallClaimsMethod.smallClaimsMethodInPerson) { - sdoDocumentFormBuilder.hearingLocation( + sdoDocumentFormBuilder.hearingLocation( locationHelper.getHearingLocation( Optional.ofNullable(caseData.getSmallClaimsMethodInPerson()) .map(DynamicList::getValue) @@ -387,16 +374,12 @@ private SdoDocumentFormSmall getTemplateDataSmall(CaseData caseData, String judg .orElse(null), caseData, authorisation - )); - } else { - sdoDocumentFormBuilder.hearingLocation(locationHelper.getHearingLocation( - null, - caseData, - authorisation - )); - } + )) + .caseManagementLocation( + locationHelper.getHearingLocation(null, caseData, authorisation)); return sdoDocumentFormBuilder .build(); } + } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimFormGenerator.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimFormGenerator.java index 42f4bbadd62..08f7b40e3df 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimFormGenerator.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimFormGenerator.java @@ -4,15 +4,14 @@ import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.civil.documentmanagement.DocumentManagementService; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; +import uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType; +import uk.gov.hmcts.reform.civil.documentmanagement.model.PDF; import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; import uk.gov.hmcts.reform.civil.model.CaseData; -import uk.gov.hmcts.reform.civil.model.LitigationFriend; import uk.gov.hmcts.reform.civil.model.SolicitorReferences; import uk.gov.hmcts.reform.civil.model.docmosis.DocmosisDocument; import uk.gov.hmcts.reform.civil.model.docmosis.common.Party; import uk.gov.hmcts.reform.civil.model.docmosis.sealedclaim.SealedClaimForm; -import uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType; -import uk.gov.hmcts.reform.civil.documentmanagement.model.PDF; import uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates; import uk.gov.hmcts.reform.civil.service.docmosis.DocumentGeneratorService; import uk.gov.hmcts.reform.civil.service.docmosis.RepresentativeService; @@ -147,32 +146,31 @@ private List getRespondents(CaseData caseData, MultiPartyScenario multiPa private List getApplicants(CaseData caseData, MultiPartyScenario multiPartyScenario) { var applicant = caseData.getApplicant1(); var applicantRepresentative = representativeService.getApplicantRepresentative(caseData); + var litigationFriend1 = caseData.getApplicant1LitigationFriend(); var applicantParties = new ArrayList<>(List.of( Party.builder() .type(applicant.getType().getDisplayValue()) .soleTraderTradingAs(DocmosisTemplateDataUtils.fetchSoleTraderCompany(applicant)) .name(applicant.getPartyName()) .primaryAddress(applicant.getPrimaryAddress()) - .litigationFriendName( - ofNullable(caseData.getApplicant1LitigationFriend()) - .map(LitigationFriend::getFullName) - .orElse("")) + .litigationFriendName(litigationFriend1 != null ? litigationFriend1.getFirstName() + " " + + litigationFriend1.getLastName() : "") .representative(applicantRepresentative) .build())); if (multiPartyScenario == TWO_V_ONE) { var applicant2 = caseData.getApplicant2(); - applicantParties.add(Party.builder() - .type(applicant2.getType().getDisplayValue()) - .soleTraderTradingAs(DocmosisTemplateDataUtils.fetchSoleTraderCompany(applicant2)) - .name(applicant2.getPartyName()) - .primaryAddress(applicant2.getPrimaryAddress()) - .litigationFriendName( - ofNullable(caseData.getApplicant2LitigationFriend()) - .map(LitigationFriend::getFullName) - .orElse("")) - .representative(applicantRepresentative) - .build()); + var litigationFriend2 = caseData.getApplicant2LitigationFriend(); + applicantParties.add( + Party.builder() + .type(applicant2.getType().getDisplayValue()) + .soleTraderTradingAs(DocmosisTemplateDataUtils.fetchSoleTraderCompany(applicant2)) + .name(applicant2.getPartyName()) + .primaryAddress(applicant2.getPrimaryAddress()) + .litigationFriendName(litigationFriend2 != null ? litigationFriend2.getFirstName() + " " + + litigationFriend2.getLastName() : "") + .representative(applicantRepresentative) + .build()); } return applicantParties; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimLipResponseFormGenerator.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimLipResponseFormGenerator.java index 754d9ef596a..bc971235285 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimLipResponseFormGenerator.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimLipResponseFormGenerator.java @@ -1,7 +1,6 @@ package uk.gov.hmcts.reform.civil.service.docmosis.sealedclaim; import lombok.RequiredArgsConstructor; - import org.springframework.stereotype.Service; import uk.gov.hmcts.reform.civil.documentmanagement.DocumentManagementService; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimResponseFormGeneratorForSpec.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimResponseFormGeneratorForSpec.java index 31dffdf75ff..53b2b4f08fd 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimResponseFormGeneratorForSpec.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimResponseFormGeneratorForSpec.java @@ -15,12 +15,14 @@ import uk.gov.hmcts.reform.civil.model.docmosis.DocmosisDocument; import uk.gov.hmcts.reform.civil.model.docmosis.common.SpecifiedParty; import uk.gov.hmcts.reform.civil.model.docmosis.sealedclaim.Representative; +import uk.gov.hmcts.reform.civil.model.docmosis.sealedclaim.ResponseRepaymentDetailsForm; import uk.gov.hmcts.reform.civil.model.docmosis.sealedclaim.SealedClaimResponseFormForSpec; import uk.gov.hmcts.reform.civil.model.docmosis.sealedclaim.TimelineEventDetailsDocmosis; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType; import uk.gov.hmcts.reform.civil.documentmanagement.model.PDF; import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates; import uk.gov.hmcts.reform.civil.service.docmosis.DocumentGeneratorService; import uk.gov.hmcts.reform.civil.service.docmosis.RepresentativeService; @@ -37,6 +39,10 @@ import java.util.Optional; import java.util.stream.Stream; +import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.isOneVOne; +import static uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates.DEFENDANT_RESPONSE_SPEC_SEALED_1V1_INSTALLMENTS; +import static uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates.DEFENDANT_RESPONSE_SPEC_SEALED_1v1; +import static uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates.DEFENDANT_RESPONSE_SPEC_SEALED_1v2; import static uk.gov.hmcts.reform.civil.service.robotics.utils.RoboticsDataUtil.CIVIL_COURT_TYPE_ID; @Service @@ -47,6 +53,7 @@ public class SealedClaimResponseFormGeneratorForSpec implements TemplateDataGene private final DocumentGeneratorService documentGeneratorService; private final DocumentManagementService documentManagementService; private final LocationRefDataService locationRefDataService; + private final FeatureToggleService featureToggleService; @Override public SealedClaimResponseFormForSpec getTemplateData(CaseData caseData, String authorisation) { @@ -77,7 +84,7 @@ public SealedClaimResponseFormForSpec getTemplateData(CaseData caseData, String .whyDisputeTheClaim(caseData.getDetailsOfWhyDoesYouDisputeTheClaim()) .hearingCourtLocation(hearingCourtLocation) .statementOfTruth(statementOfTruth); - + addRepaymentPlanDetails(builder, caseData); if (MultiPartyScenario.getMultiPartyScenario(caseData) == MultiPartyScenario.ONE_V_TWO_TWO_LEGAL_REP) { builder.respondent1(getDefendant1v2ds(caseData)); } else { @@ -134,6 +141,12 @@ public SealedClaimResponseFormForSpec getTemplateData(CaseData caseData, String return builder.build(); } + private void addRepaymentPlanDetails(SealedClaimResponseFormForSpec.SealedClaimResponseFormForSpecBuilder builder, CaseData caseData) { + if (featureToggleService.isPinInPostEnabled() && isOneVOne(caseData)) { + builder.commonDetails(ResponseRepaymentDetailsForm.toSealedClaimResponseCommonContent(caseData)); + } + } + /** * We pass through this method twice, once for each defendant. Each time * we have to set the defendant who just answered. @@ -203,14 +216,7 @@ private List getTimeLine(CaseData caseData) { public CaseDocument generate(CaseData caseData, String authorization) { SealedClaimResponseFormForSpec templateData = getTemplateData(caseData, authorization); - - DocmosisTemplates docmosisTemplate; - if (caseData.getRespondent2() != null && YesOrNo.YES.equals(caseData.getRespondentResponseIsSame())) { - docmosisTemplate = DocmosisTemplates.DEFENDANT_RESPONSE_SPEC_SEALED_1v2; - } else { - docmosisTemplate = DocmosisTemplates.DEFENDANT_RESPONSE_SPEC_SEALED_1v1; - } - + DocmosisTemplates docmosisTemplate = getTemplate(caseData); DocmosisDocument docmosisDocument = documentGeneratorService.generateDocmosisDocument( templateData, docmosisTemplate @@ -222,4 +228,18 @@ public CaseDocument generate(CaseData caseData, String authorization) { new PDF(fileName, docmosisDocument.getBytes(), DocumentType.SEALED_CLAIM) ); } + + private DocmosisTemplates getTemplate(CaseData caseData) { + if (caseData.getRespondent2() != null && YesOrNo.YES.equals(caseData.getRespondentResponseIsSame())) { + return DEFENDANT_RESPONSE_SPEC_SEALED_1v2; + } + return getDocmosisTemplateForSingleParty(); + } + + private DocmosisTemplates getDocmosisTemplateForSingleParty() { + if (featureToggleService.isPinInPostEnabled()) { + return DEFENDANT_RESPONSE_SPEC_SEALED_1V1_INSTALLMENTS; + } + return DEFENDANT_RESPONSE_SPEC_SEALED_1v1; + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/trialready/TrialReadyFormGenerator.java b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/trialready/TrialReadyFormGenerator.java index d6ea12ae165..6061c9334db 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/trialready/TrialReadyFormGenerator.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/docmosis/trialready/TrialReadyFormGenerator.java @@ -7,6 +7,7 @@ import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType; import uk.gov.hmcts.reform.civil.documentmanagement.model.PDF; +import uk.gov.hmcts.reform.civil.enums.CaseRole; import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.Party; @@ -35,12 +36,12 @@ public class TrialReadyFormGenerator { private static final String TASK_ID_APPLICANT = "GenerateTrialReadyFormApplicant"; private static final String TASK_ID_RESPONDENT1 = "GenerateTrialReadyFormRespondent1"; - public CaseDocument generate(CaseData caseData, String authorisation, String camundaActivity) { + public CaseDocument generate(CaseData caseData, String authorisation, String camundaActivity, CaseRole userRole) { TrialReadyForm templateData = getTemplateData(caseData, camundaActivity); DocmosisTemplates template = TRIAL_READY; DocmosisDocument document = documentGeneratorService.generateDocmosisDocument(templateData, template); - return documentManagementService.uploadDocument( + CaseDocument trialReadyDocument = documentManagementService.uploadDocument( authorisation, new PDF( getFileName(caseData, template, camundaActivity), @@ -48,6 +49,8 @@ public CaseDocument generate(CaseData caseData, String authorisation, String cam DocumentType.TRIAL_READY_DOCUMENT ) ); + + return trialReadyDocument.toBuilder().ownedBy(userRole).build(); } private TrialReadyForm getTemplateData(CaseData caseData, String camundaActivity) { @@ -93,16 +96,12 @@ private String getUserLastName(CaseData caseData, String camundaActivity) { } private String getTypeUserLastName(Party party) { - switch (party.getType()) { - case INDIVIDUAL: - return party.getIndividualLastName(); - case COMPANY: - return party.getCompanyName(); - case SOLE_TRADER: - return party.getSoleTraderLastName(); - default: - return party.getOrganisationName(); - } + return switch (party.getType()) { + case INDIVIDUAL -> party.getIndividualLastName(); + case COMPANY -> party.getCompanyName(); + case SOLE_TRADER -> party.getSoleTraderLastName(); + default -> party.getOrganisationName(); + }; } private TrialReadyForm.TrialReadyFormBuilder completeTrialReadyFormWithOptionalFields( diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/documentmanagement/ClaimFormService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/documentmanagement/ClaimFormService.java index 0f52b06b455..e97800b1625 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/documentmanagement/ClaimFormService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/documentmanagement/ClaimFormService.java @@ -20,15 +20,15 @@ public class ClaimFormService { private final DocumentDownloadService documentDownloadService; + @Autowired + private final SealedClaimFormGeneratorForSpec sealedClaimFormGeneratorForSpec; + public CaseDocument uploadSealedDocument( String authorisation, CaseData caseData) { return sealedClaimFormGeneratorForSpec.generate(caseData, authorisation); } - @Autowired - private final SealedClaimFormGeneratorForSpec sealedClaimFormGeneratorForSpec; - - public DownloadedDocumentResponse downloadDocumentById(String caseDocumentId) { - return documentDownloadService.downloadDocument(caseDocumentId); + public DownloadedDocumentResponse downloadDocumentById(String authorisation, String caseDocumentId) { + return documentDownloadService.downloadDocument(authorisation, caseDocumentId); } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/documentmanagement/DocumentDownloadService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/documentmanagement/DocumentDownloadService.java index 7e2ebf82b71..e2c99f66f69 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/documentmanagement/DocumentDownloadService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/documentmanagement/DocumentDownloadService.java @@ -2,23 +2,17 @@ import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; -import uk.gov.hmcts.reform.civil.config.SystemUpdateUserConfiguration; import uk.gov.hmcts.reform.civil.documentmanagement.DocumentManagementService; import uk.gov.hmcts.reform.civil.documentmanagement.model.DownloadedDocumentResponse; -import uk.gov.hmcts.reform.civil.service.UserService; @Service @RequiredArgsConstructor public class DocumentDownloadService { - private final UserService userService; - private final SystemUpdateUserConfiguration userConfig; private final DocumentManagementService documentManagementService; - public DownloadedDocumentResponse downloadDocument(String documentId) { - String authorisation = userService.getAccessToken(userConfig.getUserName(), userConfig.getPassword()); + public DownloadedDocumentResponse downloadDocument(String authorisation, String documentId) { String documentPath = String.format("documents/%s", documentId); - return documentManagementService.downloadDocumentWithMetaData(authorisation, documentPath); } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowPredicate.java b/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowPredicate.java index 6e5fe26e9e1..f0bfc9f7825 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowPredicate.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowPredicate.java @@ -18,6 +18,7 @@ import java.util.function.Predicate; import static uk.gov.hmcts.reform.civil.enums.CaseCategory.SPEC_CLAIM; +import static uk.gov.hmcts.reform.civil.enums.CaseCategory.UNSPEC_CLAIM; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.ONE_V_ONE; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.ONE_V_TWO_TWO_LEGAL_REP; import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.getMultiPartyScenario; @@ -371,7 +372,8 @@ private static boolean getPredicateForAwaitingResponsesNonFullDefenceReceived(Ca public static final Predicate takenOfflineSDONotDrawn = caseData -> caseData.getReasonNotSuitableSDO() != null && StringUtils.isNotBlank(caseData.getReasonNotSuitableSDO().getInput()) - && caseData.getTakenOfflineDate() != null; + && caseData.getTakenOfflineDate() != null + && caseData.getTakenOfflineByStaffDate() == null; public static final Predicate takenOfflineSDONotDrawnAfterNotificationAcknowledgedTimeExtension = FlowPredicate::getPredicateTakenOfflineSDONotDrawnAfterNotificationAckTimeExt; @@ -459,14 +461,60 @@ private static boolean getPredicateTakenOfflineSDONotDrawnAfterClaimDetailsNotif caseData.getTakenOfflineDate() != null; public static final Predicate takenOfflineAfterSDO = caseData -> - caseData.getReasonNotSuitableSDO() == null && caseData.getTakenOfflineDate() != null; + caseData.getDrawDirectionsOrderRequired() != null + && caseData.getReasonNotSuitableSDO() == null + && caseData.getTakenOfflineDate() != null + && caseData.getTakenOfflineByStaffDate() == null; public static final Predicate takenOfflineByStaff = caseData -> caseData.getTakenOfflineByStaffDate() != null; + public static final Predicate takenOfflineByStaffAfterClaimantResponseBeforeSDO = caseData -> + caseData.getTakenOfflineByStaffDate() != null + && caseData.getApplicant1ResponseDate() != null + && caseData.getDrawDirectionsOrderRequired() == null + && caseData.getReasonNotSuitableSDO() == null; + + public static final Predicate takenOfflineByStaffAfterSDO = caseData -> + caseData.getTakenOfflineByStaffDate() != null + && caseData.getDrawDirectionsOrderRequired() != null + && caseData.getReasonNotSuitableSDO() == null; + + public static final Predicate takenOfflineAfterNotSuitableForSdo = caseData -> + caseData.getTakenOfflineByStaffDate() != null + && caseData.getDrawDirectionsOrderRequired() == null + && caseData.getReasonNotSuitableSDO() != null + && StringUtils.isNotBlank(caseData.getReasonNotSuitableSDO().getInput()); + + public static final Predicate takenOfflineByStaffAfterDefendantResponse = caseData -> + getPredicateTakenOfflineByStaffAfterDefendantResponseBeforeClaimantResponse(caseData); + public static final Predicate takenOfflineByStaffAfterClaimIssue = caseData -> getPredicateTakenOfflineByStaffAfterClaimIssue(caseData); + public static final Predicate takenOfflineByStaffBeforeClaimIssued = caseData -> + getPredicateTakenOfflineByStaffBeforeClaimIssue(caseData); + + public static final boolean getPredicateTakenOfflineByStaffAfterDefendantResponseBeforeClaimantResponse(CaseData caseData) { + boolean basePredicate = caseData.getTakenOfflineByStaffDate() != null + && caseData.getApplicant1ResponseDate() == null; + + if (UNSPEC_CLAIM.equals(caseData.getCaseAccessCategory()) + && YES.equals(caseData.getAddApplicant2())) { + return basePredicate && caseData.getApplicant2ResponseDate() == null; + } + + return basePredicate; + } + + public static final boolean getPredicateTakenOfflineByStaffBeforeClaimIssue(CaseData caseData) { + // In case of SPEC and UNSPEC claim ClaimNotificationDeadline will be set when the case is issued + return caseData.getTakenOfflineByStaffDate() != null + && caseData.getClaimNotificationDeadline() == null + && caseData.getClaimNotificationDate() == null + && caseData.getSubmittedDate() != null; + } + public static final boolean getPredicateTakenOfflineByStaffAfterClaimIssue(CaseData caseData) { // In case of SPEC claim ClaimNotificationDate will be set even when the case is issued // In case of UNSPEC ClaimNotificationDate will be set only after notification step @@ -972,6 +1020,13 @@ private static boolean getPredicateForMultipartyCase(CaseData caseData) { && caseData.getListingOrRelisting().equals(LISTING) && caseData.getCaseDismissedHearingFeeDueDate() == null && caseData.getTakenOfflineDate() == null; - + public static final Predicate isPayImmediately = CaseData::isPayImmediately; + + public static final Predicate casemanMarksMediationUnsuccessful = caseData -> + Objects.nonNull(caseData.getMediation().getUnsuccessfulMediationReason()); + + public static final Predicate takenOfflineByStaffBeforeMediationUnsuccessful = caseData -> + caseData.getTakenOfflineByStaffDate() != null + && Objects.isNull(caseData.getMediation().getUnsuccessfulMediationReason()); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowState.java b/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowState.java index ff8f094a232..dd643f7bc6e 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowState.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowState.java @@ -81,7 +81,10 @@ enum Main implements FlowState { TAKEN_OFFLINE_SDO_NOT_DRAWN, RESPONDENT_RESPONSE_LANGUAGE_IS_BILINGUAL, IN_MEDIATION, - IN_HEARING_READINESS; + IN_HEARING_READINESS, + MEDIATION_UNSUCCESSFUL_PROCEED, + All_FINAL_ORDERS_ISSUED, + PREPARE_FOR_HEARING_CONDUCT_HEARING; public static final String FLOW_NAME = "MAIN"; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowStateAllowedEventService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowStateAllowedEventService.java index 27f14abb1ea..85c31fb7330 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowStateAllowedEventService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowStateAllowedEventService.java @@ -5,7 +5,6 @@ import uk.gov.hmcts.reform.ccd.client.model.CaseDetails; import uk.gov.hmcts.reform.civil.callback.CaseEvent; import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; -import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.stateflow.StateFlow; @@ -15,6 +14,9 @@ import static java.util.Collections.emptyList; import static java.util.Map.entry; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.LIFT_BREATHING_SPACE_LIP; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.asyncStitchingComplete; +import static uk.gov.hmcts.reform.civil.enums.CaseCategory.SPEC_CLAIM; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.ACKNOWLEDGEMENT_OF_SERVICE; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.ACKNOWLEDGE_CLAIM; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.ADD_CASE_NOTE; @@ -26,62 +28,68 @@ import static uk.gov.hmcts.reform.civil.callback.CaseEvent.APPLICATION_OFFLINE_UPDATE_CLAIM; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.APPLY_NOC_DECISION; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.BUNDLE_CREATION_NOTIFICATION; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CLAIMANT_RESPONSE_CUI; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CREATE_CLAIM_SPEC_AFTER_PAYMENT; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CREATE_CLAIM_AFTER_PAYMENT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CASE_PROCEEDS_IN_CASEMAN; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CHANGE_SOLICITOR_EMAIL; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CLAIMANT_RESPONSE; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CLAIMANT_RESPONSE_CUI; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CLAIMANT_RESPONSE_SPEC; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CREATE_CLAIM; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CREATE_CLAIM_AFTER_PAYMENT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CREATE_CLAIM_SPEC; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CREATE_CLAIM_SPEC_AFTER_PAYMENT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CREATE_LIP_CLAIM; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CREATE_SDO; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.DEFAULT_JUDGEMENT; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.MANAGE_CONTACT_INFORMATION; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOTIFY_HEARING_PARTIES; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.REQUEST_JUDGEMENT_ADMISSION_SPEC; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.DEFAULT_JUDGEMENT_SPEC; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.DEFENDANT_RESPONSE; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.DEFENDANT_RESPONSE_CUI; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.DEFENDANT_RESPONSE_SPEC; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.DISCONTINUE_CLAIM; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.DISMISS_CLAIM; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.ENTER_BREATHING_SPACE_SPEC; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.ENTER_BREATHING_SPACE_LIP; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.ENTER_BREATHING_SPACE_SPEC; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.EVIDENCE_UPLOAD_APPLICANT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.EVIDENCE_UPLOAD_JUDGE; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.EVIDENCE_UPLOAD_RESPONDENT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.EXTEND_RESPONSE_DEADLINE; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.HEARING_FEE_UNPAID; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.GENERATE_DIRECTIONS_ORDER; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.HEARING_FEE_PAID; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.HEARING_FEE_UNPAID; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.HEARING_SCHEDULED; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.INFORM_AGREED_EXTENSION_DATE; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.INFORM_AGREED_EXTENSION_DATE_SPEC; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.INITIATE_GENERAL_APPLICATION; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.JUDGMENT_PAID_IN_FULL; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.LIFT_BREATHING_SPACE_SPEC; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.LIP_CLAIM_SETTLED; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.MANAGE_CONTACT_INFORMATION; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.MEDIATION_SUCCESSFUL; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.MEDIATION_UNSUCCESSFUL; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.RESET_PIN; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.TRIAL_READINESS; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.UPLOAD_TRANSLATED_DOCUMENT; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.migrateCase; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.MOVE_TO_DECISION_OUTCOME; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOC_REQUEST; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOTIFY_DEFENDANT_CUI_FOR_DEADLINE_EXTENSION; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOTIFY_CLAIMANT_CUI_FOR_DEADLINE_EXTENSION; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOTIFY_DEFENDANT_CUI_FOR_DEADLINE_EXTENSION; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOTIFY_DEFENDANT_OF_CLAIM; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOTIFY_DEFENDANT_OF_CLAIM_DETAILS; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOTIFY_HEARING_PARTIES; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NotSuitable_SDO; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.RECORD_JUDGMENT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.REFER_TO_JUDGE; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.REQUEST_JUDGEMENT_ADMISSION_SPEC; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.RESET_PIN; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.RESUBMIT_CLAIM; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.SERVICE_REQUEST_RECEIVED; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.SET_ASIDE_JUDGMENT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.STANDARD_DIRECTION_ORDER_DJ; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.TAKE_CASE_OFFLINE; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.TRIAL_READY_NOTIFICATION; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.TRANSFER_ONLINE_CASE; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.TRIAL_READINESS; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.TRIAL_READY_CHECK; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.GENERATE_DIRECTIONS_ORDER; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.TRIAL_READY_NOTIFICATION; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.UPLOAD_TRANSLATED_DOCUMENT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.WITHDRAW_CLAIM; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.asyncStitchingComplete; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.migrateCase; import static uk.gov.hmcts.reform.civil.enums.CaseCategory.SPEC_CLAIM; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.AWAITING_RESPONSES_FULL_DEFENCE_RECEIVED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.AWAITING_RESPONSES_NOT_FULL_DEFENCE_RECEIVED; @@ -105,6 +113,7 @@ import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.FULL_DEFENCE_PROCEED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.IN_HEARING_READINESS; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.IN_MEDIATION; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.MEDIATION_UNSUCCESSFUL_PROCEED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.NOTIFICATION_ACKNOWLEDGED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.NOTIFICATION_ACKNOWLEDGED_TIME_EXTENSION; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PART_ADMISSION; @@ -114,17 +123,18 @@ import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PAST_CLAIM_DISMISSED_DEADLINE_AWAITING_CAMUNDA; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PAST_CLAIM_NOTIFICATION_DEADLINE_AWAITING_CAMUNDA; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PENDING_CLAIM_ISSUED_UNREPRESENTED_DEFENDANT; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PREPARE_FOR_HEARING_CONDUCT_HEARING; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.RESPONDENT_RESPONSE_LANGUAGE_IS_BILINGUAL; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.SPEC_DRAFT; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.TAKEN_OFFLINE_AFTER_CLAIM_DETAILS_NOTIFIED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.TAKEN_OFFLINE_AFTER_CLAIM_NOTIFIED; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.TAKEN_OFFLINE_AFTER_SDO; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.TAKEN_OFFLINE_BY_STAFF; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.TAKEN_OFFLINE_PAST_APPLICANT_RESPONSE_DEADLINE; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.TAKEN_OFFLINE_SDO_NOT_DRAWN; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.TAKEN_OFFLINE_UNREGISTERED_DEFENDANT; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.TAKEN_OFFLINE_UNREPRESENTED_DEFENDANT; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.TAKEN_OFFLINE_UNREPRESENTED_UNREGISTERED_DEFENDANT; -import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.TAKEN_OFFLINE_AFTER_SDO; @Service @RequiredArgsConstructor @@ -132,7 +142,6 @@ public class FlowStateAllowedEventService { private final StateFlowEngine stateFlowEngine; private final CaseDetailsConverter caseDetailsConverter; - private final FeatureToggleService toggleService; private static final Map> ALLOWED_EVENTS_ON_FLOW_STATE = Map.ofEntries( entry( @@ -272,7 +281,9 @@ public class FlowStateAllowedEventService { EVIDENCE_UPLOAD_RESPONDENT, GENERATE_DIRECTIONS_ORDER, TRIAL_READINESS, - BUNDLE_CREATION_NOTIFICATION + BUNDLE_CREATION_NOTIFICATION, + TRANSFER_ONLINE_CASE, + asyncStitchingComplete ) ), @@ -427,7 +438,8 @@ public class FlowStateAllowedEventService { INITIATE_GENERAL_APPLICATION, CREATE_SDO, NotSuitable_SDO, - migrateCase + migrateCase, + CLAIMANT_RESPONSE_CUI ) ), @@ -445,7 +457,8 @@ public class FlowStateAllowedEventService { CREATE_SDO, NotSuitable_SDO, APPLICATION_OFFLINE_UPDATE_CLAIM, - migrateCase + migrateCase, + CLAIMANT_RESPONSE_CUI ) ), @@ -526,7 +539,12 @@ public class FlowStateAllowedEventService { EVIDENCE_UPLOAD_JUDGE, TRIAL_READINESS, BUNDLE_CREATION_NOTIFICATION, - ADD_UNAVAILABLE_DATES + ADD_UNAVAILABLE_DATES, + SET_ASIDE_JUDGMENT, + JUDGMENT_PAID_IN_FULL, + RECORD_JUDGMENT, + TRANSFER_ONLINE_CASE, + asyncStitchingComplete ) ), @@ -630,7 +648,8 @@ public class FlowStateAllowedEventService { List.of( DISMISS_CLAIM, migrateCase, - CREATE_SDO + CREATE_SDO, + NotSuitable_SDO ) ), entry( @@ -749,7 +768,8 @@ public class FlowStateAllowedEventService { GENERATE_DIRECTIONS_ORDER, TRIAL_READINESS, BUNDLE_CREATION_NOTIFICATION, - ADD_UNAVAILABLE_DATES + ADD_UNAVAILABLE_DATES, + asyncStitchingComplete ) ) ); @@ -793,6 +813,7 @@ public class FlowStateAllowedEventService { ENTER_BREATHING_SPACE_SPEC, ENTER_BREATHING_SPACE_LIP, LIFT_BREATHING_SPACE_SPEC, + LIFT_BREATHING_SPACE_LIP, RESUBMIT_CLAIM, WITHDRAW_CLAIM, DISCONTINUE_CLAIM, @@ -810,6 +831,7 @@ public class FlowStateAllowedEventService { ENTER_BREATHING_SPACE_SPEC, ENTER_BREATHING_SPACE_LIP, LIFT_BREATHING_SPACE_SPEC, + LIFT_BREATHING_SPACE_LIP, NOTIFY_DEFENDANT_OF_CLAIM, ADD_DEFENDANT_LITIGATION_FRIEND, CASE_PROCEEDS_IN_CASEMAN, @@ -843,7 +865,9 @@ public class FlowStateAllowedEventService { migrateCase, EVIDENCE_UPLOAD_RESPONDENT, BUNDLE_CREATION_NOTIFICATION, - CHANGE_SOLICITOR_EMAIL + CHANGE_SOLICITOR_EMAIL, + LIP_CLAIM_SETTLED, + asyncStitchingComplete ) ), entry( @@ -852,6 +876,7 @@ public class FlowStateAllowedEventService { ACKNOWLEDGEMENT_OF_SERVICE, ENTER_BREATHING_SPACE_SPEC, ENTER_BREATHING_SPACE_LIP, + LIFT_BREATHING_SPACE_LIP, LIFT_BREATHING_SPACE_SPEC, INFORM_AGREED_EXTENSION_DATE, INFORM_AGREED_EXTENSION_DATE_SPEC, @@ -880,7 +905,9 @@ public class FlowStateAllowedEventService { migrateCase, EVIDENCE_UPLOAD_RESPONDENT, BUNDLE_CREATION_NOTIFICATION, - CHANGE_SOLICITOR_EMAIL + CHANGE_SOLICITOR_EMAIL, + LIP_CLAIM_SETTLED, + asyncStitchingComplete ) ), entry( @@ -889,6 +916,7 @@ public class FlowStateAllowedEventService { DEFENDANT_RESPONSE, ENTER_BREATHING_SPACE_SPEC, ENTER_BREATHING_SPACE_LIP, + LIFT_BREATHING_SPACE_LIP, LIFT_BREATHING_SPACE_SPEC, ADD_DEFENDANT_LITIGATION_FRIEND, WITHDRAW_CLAIM, @@ -912,6 +940,7 @@ public class FlowStateAllowedEventService { DEFENDANT_RESPONSE, ENTER_BREATHING_SPACE_SPEC, ENTER_BREATHING_SPACE_LIP, + LIFT_BREATHING_SPACE_LIP, LIFT_BREATHING_SPACE_SPEC, ADD_DEFENDANT_LITIGATION_FRIEND, WITHDRAW_CLAIM, @@ -924,7 +953,8 @@ public class FlowStateAllowedEventService { CREATE_SDO, NotSuitable_SDO, migrateCase, - CHANGE_SOLICITOR_EMAIL + CHANGE_SOLICITOR_EMAIL, + LIP_CLAIM_SETTLED ) ), @@ -935,6 +965,7 @@ public class FlowStateAllowedEventService { CLAIMANT_RESPONSE_SPEC, ENTER_BREATHING_SPACE_SPEC, ENTER_BREATHING_SPACE_LIP, + LIFT_BREATHING_SPACE_LIP, LIFT_BREATHING_SPACE_SPEC, WITHDRAW_CLAIM, ADD_DEFENDANT_LITIGATION_FRIEND, @@ -948,7 +979,9 @@ public class FlowStateAllowedEventService { NotSuitable_SDO, migrateCase, DEFAULT_JUDGEMENT_SPEC, - CHANGE_SOLICITOR_EMAIL + CHANGE_SOLICITOR_EMAIL, + LIP_CLAIM_SETTLED, + CLAIMANT_RESPONSE_CUI ) ), @@ -958,6 +991,7 @@ public class FlowStateAllowedEventService { CLAIMANT_RESPONSE_SPEC, ENTER_BREATHING_SPACE_SPEC, ENTER_BREATHING_SPACE_LIP, + LIFT_BREATHING_SPACE_LIP, LIFT_BREATHING_SPACE_SPEC, WITHDRAW_CLAIM, ADD_DEFENDANT_LITIGATION_FRIEND, @@ -971,7 +1005,9 @@ public class FlowStateAllowedEventService { migrateCase, DEFAULT_JUDGEMENT_SPEC, REQUEST_JUDGEMENT_ADMISSION_SPEC, - CHANGE_SOLICITOR_EMAIL + CHANGE_SOLICITOR_EMAIL, + LIP_CLAIM_SETTLED, + CLAIMANT_RESPONSE_CUI ) ), @@ -982,6 +1018,7 @@ public class FlowStateAllowedEventService { CLAIMANT_RESPONSE_CUI, ENTER_BREATHING_SPACE_SPEC, ENTER_BREATHING_SPACE_LIP, + LIFT_BREATHING_SPACE_LIP, LIFT_BREATHING_SPACE_SPEC, WITHDRAW_CLAIM, ADD_DEFENDANT_LITIGATION_FRIEND, @@ -995,7 +1032,8 @@ public class FlowStateAllowedEventService { migrateCase, DEFAULT_JUDGEMENT_SPEC, CHANGE_SOLICITOR_EMAIL, - REQUEST_JUDGEMENT_ADMISSION_SPEC + REQUEST_JUDGEMENT_ADMISSION_SPEC, + LIP_CLAIM_SETTLED ) ), @@ -1012,6 +1050,7 @@ public class FlowStateAllowedEventService { List.of( ENTER_BREATHING_SPACE_SPEC, ENTER_BREATHING_SPACE_LIP, + LIFT_BREATHING_SPACE_LIP, LIFT_BREATHING_SPACE_SPEC, WITHDRAW_CLAIM, ADD_DEFENDANT_LITIGATION_FRIEND, @@ -1022,7 +1061,8 @@ public class FlowStateAllowedEventService { CREATE_SDO, NotSuitable_SDO, migrateCase, - CHANGE_SOLICITOR_EMAIL + CHANGE_SOLICITOR_EMAIL, + LIP_CLAIM_SETTLED ) ), @@ -1032,6 +1072,7 @@ public class FlowStateAllowedEventService { ADD_DEFENDANT_LITIGATION_FRIEND, ENTER_BREATHING_SPACE_SPEC, ENTER_BREATHING_SPACE_LIP, + LIFT_BREATHING_SPACE_LIP, LIFT_BREATHING_SPACE_SPEC, WITHDRAW_CLAIM, DISCONTINUE_CLAIM, @@ -1058,7 +1099,13 @@ public class FlowStateAllowedEventService { BUNDLE_CREATION_NOTIFICATION, ADD_CASE_NOTE, CHANGE_SOLICITOR_EMAIL, - ADD_UNAVAILABLE_DATES + ADD_UNAVAILABLE_DATES, + SET_ASIDE_JUDGMENT, + JUDGMENT_PAID_IN_FULL, + RECORD_JUDGMENT, + LIP_CLAIM_SETTLED, + TRANSFER_ONLINE_CASE, + asyncStitchingComplete ) ), @@ -1068,6 +1115,7 @@ public class FlowStateAllowedEventService { ADD_DEFENDANT_LITIGATION_FRIEND, ENTER_BREATHING_SPACE_SPEC, ENTER_BREATHING_SPACE_LIP, + LIFT_BREATHING_SPACE_LIP, LIFT_BREATHING_SPACE_SPEC, WITHDRAW_CLAIM, DISCONTINUE_CLAIM, @@ -1078,7 +1126,8 @@ public class FlowStateAllowedEventService { NotSuitable_SDO, REFER_TO_JUDGE, migrateCase, - CHANGE_SOLICITOR_EMAIL + CHANGE_SOLICITOR_EMAIL, + LIP_CLAIM_SETTLED ) ), entry( @@ -1133,6 +1182,7 @@ public class FlowStateAllowedEventService { ACKNOWLEDGE_CLAIM, ENTER_BREATHING_SPACE_SPEC, ENTER_BREATHING_SPACE_LIP, + LIFT_BREATHING_SPACE_LIP, LIFT_BREATHING_SPACE_SPEC, INFORM_AGREED_EXTENSION_DATE, ADD_DEFENDANT_LITIGATION_FRIEND, @@ -1165,7 +1215,8 @@ public class FlowStateAllowedEventService { MEDIATION_UNSUCCESSFUL, CREATE_SDO, CHANGE_SOLICITOR_EMAIL, - ADD_UNAVAILABLE_DATES + ADD_UNAVAILABLE_DATES, + LIP_CLAIM_SETTLED ) ), entry( @@ -1174,6 +1225,7 @@ public class FlowStateAllowedEventService { ADD_DEFENDANT_LITIGATION_FRIEND, ENTER_BREATHING_SPACE_SPEC, ENTER_BREATHING_SPACE_LIP, + LIFT_BREATHING_SPACE_LIP, LIFT_BREATHING_SPACE_SPEC, WITHDRAW_CLAIM, DISCONTINUE_CLAIM, @@ -1199,23 +1251,167 @@ public class FlowStateAllowedEventService { TRIAL_READINESS, BUNDLE_CREATION_NOTIFICATION, CHANGE_SOLICITOR_EMAIL, - ADD_UNAVAILABLE_DATES + ADD_UNAVAILABLE_DATES, + LIP_CLAIM_SETTLED, + asyncStitchingComplete ) ), entry( PART_ADMIT_NOT_SETTLED_NO_MEDIATION.fullName(), List.of( + ADD_DEFENDANT_LITIGATION_FRIEND, + ENTER_BREATHING_SPACE_SPEC, + ENTER_BREATHING_SPACE_LIP, + LIFT_BREATHING_SPACE_LIP, + LIFT_BREATHING_SPACE_SPEC, + WITHDRAW_CLAIM, + DISCONTINUE_CLAIM, + CASE_PROCEEDS_IN_CASEMAN, + AMEND_PARTY_DETAILS, + INITIATE_GENERAL_APPLICATION, CREATE_SDO, - CHANGE_SOLICITOR_EMAIL + NotSuitable_SDO, + HEARING_SCHEDULED, + TRIAL_READY_CHECK, + TRIAL_READY_NOTIFICATION, + MOVE_TO_DECISION_OUTCOME, + HEARING_FEE_UNPAID, + HEARING_FEE_PAID, + REFER_TO_JUDGE, + migrateCase, + TAKE_CASE_OFFLINE, + GENERATE_DIRECTIONS_ORDER, + TRIAL_READINESS, + EVIDENCE_UPLOAD_APPLICANT, + EVIDENCE_UPLOAD_RESPONDENT, + EVIDENCE_UPLOAD_JUDGE, + TRIAL_READINESS, + BUNDLE_CREATION_NOTIFICATION, + ADD_CASE_NOTE, + CHANGE_SOLICITOR_EMAIL, + ADD_UNAVAILABLE_DATES, + LIP_CLAIM_SETTLED, + asyncStitchingComplete ) ), entry( RESPONDENT_RESPONSE_LANGUAGE_IS_BILINGUAL.fullName(), List.of( CHANGE_SOLICITOR_EMAIL, - EXTEND_RESPONSE_DEADLINE + EXTEND_RESPONSE_DEADLINE, + LIP_CLAIM_SETTLED ) + ), + entry( + MEDIATION_UNSUCCESSFUL_PROCEED.fullName(), + List.of( + ADD_DEFENDANT_LITIGATION_FRIEND, + ENTER_BREATHING_SPACE_SPEC, + LIFT_BREATHING_SPACE_SPEC, + WITHDRAW_CLAIM, + DISCONTINUE_CLAIM, + CASE_PROCEEDS_IN_CASEMAN, + AMEND_PARTY_DETAILS, + INITIATE_GENERAL_APPLICATION, + CREATE_SDO, + NotSuitable_SDO, + HEARING_SCHEDULED, + TRIAL_READY_CHECK, + TRIAL_READY_NOTIFICATION, + MOVE_TO_DECISION_OUTCOME, + HEARING_FEE_UNPAID, + HEARING_FEE_PAID, + REFER_TO_JUDGE, + migrateCase, + TAKE_CASE_OFFLINE, + GENERATE_DIRECTIONS_ORDER, + TRIAL_READINESS, + EVIDENCE_UPLOAD_APPLICANT, + EVIDENCE_UPLOAD_RESPONDENT, + EVIDENCE_UPLOAD_JUDGE, + TRIAL_READINESS, + BUNDLE_CREATION_NOTIFICATION, + CHANGE_SOLICITOR_EMAIL, + ADD_UNAVAILABLE_DATES, + asyncStitchingComplete + ) + ), + entry( + PREPARE_FOR_HEARING_CONDUCT_HEARING.fullName(), + List.of( + asyncStitchingComplete + ) + ), + entry( + TAKEN_OFFLINE_BY_STAFF.fullName(), + List.of( + ADD_CASE_NOTE, + APPLICATION_OFFLINE_UPDATE_CLAIM, + migrateCase + ) + ), + entry( + TAKEN_OFFLINE_UNREGISTERED_DEFENDANT.fullName(), + List.of( + ADD_CASE_NOTE, + APPLICATION_OFFLINE_UPDATE_CLAIM, + migrateCase + ) + ), + entry( + TAKEN_OFFLINE_UNREPRESENTED_DEFENDANT.fullName(), + List.of( + ADD_CASE_NOTE, + APPLICATION_OFFLINE_UPDATE_CLAIM, + migrateCase + ) + ), + entry( + TAKEN_OFFLINE_UNREPRESENTED_UNREGISTERED_DEFENDANT.fullName(), + List.of( + ADD_CASE_NOTE, + APPLICATION_OFFLINE_UPDATE_CLAIM, + migrateCase + ) + ), + entry( + TAKEN_OFFLINE_PAST_APPLICANT_RESPONSE_DEADLINE.fullName(), + List.of( + ADD_CASE_NOTE, + APPLICATION_OFFLINE_UPDATE_CLAIM, + migrateCase + ) + ), + entry( + TAKEN_OFFLINE_AFTER_CLAIM_DETAILS_NOTIFIED.fullName(), + List.of( + ADD_CASE_NOTE, + APPLICATION_OFFLINE_UPDATE_CLAIM, + migrateCase + ) + ), + entry( + TAKEN_OFFLINE_AFTER_CLAIM_NOTIFIED.fullName(), + List.of( + ADD_CASE_NOTE, + APPLICATION_OFFLINE_UPDATE_CLAIM, + migrateCase + ) + ), + entry( + TAKEN_OFFLINE_SDO_NOT_DRAWN.fullName(), + List.of( + ADD_CASE_NOTE, + migrateCase + ) + ), + entry( + TAKEN_OFFLINE_AFTER_SDO.fullName(), + List.of( + ADD_CASE_NOTE, + AMEND_PARTY_DETAILS + ) ) ); @@ -1253,6 +1449,10 @@ public boolean isAllowed(CaseDetails caseDetails, CaseEvent caseEvent) { return true; } + if (caseEvent.equals(CASE_PROCEEDS_IN_CASEMAN)) { + return true; + } + CaseData caseData = caseDetailsConverter.toCaseData(caseDetails); if (SPEC_CLAIM.equals(caseData.getCaseAccessCategory()) || CREATE_CLAIM_SPEC.equals(caseEvent) || CREATE_LIP_CLAIM.equals(caseEvent)) { diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/StateFlowEngine.java b/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/StateFlowEngine.java index 5d237f893c3..39f82bb7088 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/StateFlowEngine.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/flowstate/StateFlowEngine.java @@ -3,13 +3,13 @@ import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; import uk.gov.hmcts.reform.ccd.client.model.CaseDetails; -import uk.gov.hmcts.reform.civil.handler.callback.user.RespondToDefenceCallbackHandler; import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.stateflow.StateFlow; import uk.gov.hmcts.reform.civil.stateflow.StateFlowBuilder; import uk.gov.hmcts.reform.civil.stateflow.model.State; +import uk.gov.hmcts.reform.civil.utils.JudicialReferralUtils; import java.util.Map; @@ -18,8 +18,8 @@ import static uk.gov.hmcts.reform.civil.service.flowstate.FlowFlag.BULK_CLAIM_ENABLED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowFlag.GENERAL_APPLICATION_ENABLED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowLipPredicate.agreedToMediation; -import static uk.gov.hmcts.reform.civil.service.flowstate.FlowLipPredicate.declinedMediation; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowLipPredicate.ccjRequestJudgmentByAdmission; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowLipPredicate.declinedMediation; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowLipPredicate.isLipCase; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowLipPredicate.isTranslatedDocumentUploaded; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowLipPredicate.partAdmitPayImmediately; @@ -39,9 +39,10 @@ import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.caseDismissedAfterDetailNotified; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.caseDismissedAfterDetailNotifiedExtension; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.caseDismissedPastHearingFeeDue; -import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.claimDismissalOutOfTime; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.casemanMarksMediationUnsuccessful; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.certificateOfServiceEnabled; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.claimDetailsNotified; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.claimDismissalOutOfTime; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.claimDismissedByCamunda; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.claimIssued; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.claimNotified; @@ -71,8 +72,8 @@ import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.fullDefenceSpec; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.isClaimantNotSettlePartAdmitClaim; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.isInHearingReadiness; -import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.isRespondentResponseLangIsBilingual; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.isPayImmediately; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.isRespondentResponseLangIsBilingual; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.multipartyCase; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.noticeOfChangeEnabled; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.notificationAcknowledged; @@ -94,14 +95,20 @@ import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.specClaim; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineAfterClaimDetailsNotified; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineAfterClaimNotified; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineAfterNotSuitableForSdo; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineAfterSDO; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaff; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterClaimDetailsNotified; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterClaimDetailsNotifiedExtension; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterClaimIssue; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterClaimNotified; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterClaimantResponseBeforeSDO; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterDefendantResponse; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterNotificationAcknowledged; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterNotificationAcknowledgedTimeExtension; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterSDO; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffBeforeClaimIssued; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffBeforeMediationUnsuccessful; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineBySystem; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineSDONotDrawn; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineSDONotDrawnAfterClaimDetailsNotified; @@ -130,24 +137,25 @@ import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.FLOW_NAME; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.FULL_ADMISSION; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.FULL_ADMIT_AGREE_REPAYMENT; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.FULL_ADMIT_JUDGMENT_ADMISSION; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.FULL_ADMIT_NOT_PROCEED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.FULL_ADMIT_PAY_IMMEDIATELY; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.FULL_ADMIT_PROCEED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.FULL_ADMIT_REJECT_REPAYMENT; -import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.FULL_ADMIT_JUDGMENT_ADMISSION; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.FULL_DEFENCE; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.FULL_DEFENCE_NOT_PROCEED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.FULL_DEFENCE_PROCEED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.IN_HEARING_READINESS; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.IN_MEDIATION; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.MEDIATION_UNSUCCESSFUL_PROCEED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.NOTIFICATION_ACKNOWLEDGED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.NOTIFICATION_ACKNOWLEDGED_TIME_EXTENSION; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PART_ADMISSION; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PART_ADMIT_AGREE_REPAYMENT; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PART_ADMIT_AGREE_SETTLE; -import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PART_ADMIT_PAY_IMMEDIATELY; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PART_ADMIT_NOT_PROCEED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PART_ADMIT_NOT_SETTLED_NO_MEDIATION; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PART_ADMIT_PAY_IMMEDIATELY; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PART_ADMIT_PROCEED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PART_ADMIT_REJECT_REPAYMENT; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PAST_APPLICANT_RESPONSE_DEADLINE_AWAITING_CAMUNDA; @@ -279,6 +287,7 @@ public StateFlow build(FlowState.Main initialState) { ))) .state(CLAIM_SUBMITTED) .transitionTo(CLAIM_ISSUED_PAYMENT_SUCCESSFUL).onlyIf(paymentSuccessful) + .transitionTo(TAKEN_OFFLINE_BY_STAFF).onlyIf(takenOfflineByStaffBeforeClaimIssued) .transitionTo(CLAIM_ISSUED_PAYMENT_FAILED).onlyIf(paymentFailed) .transitionTo(PENDING_CLAIM_ISSUED_UNREPRESENTED_DEFENDANT_ONE_V_ONE_SPEC).onlyIf(isLipCase) .set(flags -> { @@ -498,23 +507,23 @@ public StateFlow build(FlowState.Main initialState) { .onlyIf(fullDefenceProceed.and(allAgreedToLrMediationSpec).and(agreedToMediation.negate()).and(declinedMediation.negate())) .set((c, flags) -> { flags.put(FlowFlag.AGREED_TO_MEDIATION.name(), true); - flags.put(FlowFlag.SDO_ENABLED.name(), RespondToDefenceCallbackHandler.shouldMoveToJudicialReferral(c)); + flags.put(FlowFlag.SDO_ENABLED.name(), JudicialReferralUtils.shouldMoveToJudicialReferral(c)); }) .transitionTo(FULL_DEFENCE_PROCEED) .onlyIf(fullDefenceProceed.and(allAgreedToLrMediationSpec.negate().and(agreedToMediation.negate())) .or(declinedMediation).and(applicantOutOfTime.negate()).and(demageMultiClaim)) .set((c, flags) -> { flags.put(FlowFlag.IS_MULTI_TRACK.name(), true); - flags.put(FlowFlag.SDO_ENABLED.name(), RespondToDefenceCallbackHandler.shouldMoveToJudicialReferral(c)); + flags.put(FlowFlag.SDO_ENABLED.name(), JudicialReferralUtils.shouldMoveToJudicialReferral(c)); }) .transitionTo(FULL_DEFENCE_PROCEED) .onlyIf(fullDefenceProceed.and(allAgreedToLrMediationSpec.negate().and(agreedToMediation.negate())) .or(declinedMediation).and(applicantOutOfTime.negate()).and(demageMultiClaim.negate())) .setDynamic(Map.of(FlowFlag.SDO_ENABLED.name(), - RespondToDefenceCallbackHandler::shouldMoveToJudicialReferral)) + JudicialReferralUtils::shouldMoveToJudicialReferral)) .transitionTo(FULL_DEFENCE_NOT_PROCEED).onlyIf(fullDefenceNotProceed) - .transitionTo(TAKEN_OFFLINE_BY_STAFF).onlyIf(takenOfflineByStaff) - .transitionTo(PAST_APPLICANT_RESPONSE_DEADLINE_AWAITING_CAMUNDA) + .transitionTo(TAKEN_OFFLINE_BY_STAFF).onlyIf(takenOfflineByStaffAfterDefendantResponse) + .transitionTo(PAST_APPLICANT_RESPONSE_DEADLINE_AWAITING_CAMUNDA) .onlyIf(applicantOutOfTime) .state(PAST_CLAIM_NOTIFICATION_DEADLINE_AWAITING_CAMUNDA) .transitionTo(CLAIM_DISMISSED_PAST_CLAIM_NOTIFICATION_DEADLINE).onlyIf(claimDismissedByCamunda) @@ -545,7 +554,7 @@ public StateFlow build(FlowState.Main initialState) { .transitionTo(PART_ADMIT_NOT_SETTLED_NO_MEDIATION) .onlyIf(isClaimantNotSettlePartAdmitClaim.and(not(agreedToMediation))) .setDynamic(Map.of(FlowFlag.SDO_ENABLED.name(), - RespondToDefenceCallbackHandler::shouldMoveToJudicialReferral)) + JudicialReferralUtils::shouldMoveToJudicialReferral)) .transitionTo(PART_ADMIT_PROCEED).onlyIf(fullDefenceProceed) .transitionTo(PART_ADMIT_NOT_PROCEED).onlyIf(fullDefenceNotProceed) .transitionTo(PART_ADMIT_PAY_IMMEDIATELY).onlyIf(partAdmitPayImmediately) @@ -564,7 +573,9 @@ public StateFlow build(FlowState.Main initialState) { .state(FULL_DEFENCE_PROCEED) .transitionTo(IN_HEARING_READINESS).onlyIf(isInHearingReadiness) .transitionTo(CLAIM_DISMISSED_HEARING_FEE_DUE_DEADLINE).onlyIf(caseDismissedPastHearingFeeDue) - .transitionTo(TAKEN_OFFLINE_BY_STAFF).onlyIf(takenOfflineByStaff) + .transitionTo(TAKEN_OFFLINE_BY_STAFF).onlyIf(takenOfflineByStaffAfterClaimantResponseBeforeSDO + .or(takenOfflineByStaffAfterSDO) + .or(takenOfflineAfterNotSuitableForSdo)) .transitionTo(TAKEN_OFFLINE_AFTER_SDO).onlyIf(takenOfflineAfterSDO) .transitionTo(TAKEN_OFFLINE_SDO_NOT_DRAWN).onlyIf(takenOfflineSDONotDrawn) .state(FULL_DEFENCE_NOT_PROCEED) @@ -586,6 +597,7 @@ public StateFlow build(FlowState.Main initialState) { .state(PART_ADMIT_PROCEED) .state(PART_ADMIT_NOT_PROCEED) .state(PART_ADMIT_NOT_SETTLED_NO_MEDIATION) + .transitionTo(IN_HEARING_READINESS).onlyIf(isInHearingReadiness) .transitionTo(CLAIM_DISMISSED_HEARING_FEE_DUE_DEADLINE).onlyIf(caseDismissedPastHearingFeeDue) .transitionTo(TAKEN_OFFLINE_BY_STAFF).onlyIf(takenOfflineByStaff) .transitionTo(TAKEN_OFFLINE_AFTER_SDO).onlyIf(takenOfflineAfterSDO) @@ -598,6 +610,14 @@ public StateFlow build(FlowState.Main initialState) { .state(PART_ADMIT_PAY_IMMEDIATELY) .state(CLAIM_DISMISSED_HEARING_FEE_DUE_DEADLINE) .state(IN_MEDIATION) + .transitionTo(MEDIATION_UNSUCCESSFUL_PROCEED).onlyIf(casemanMarksMediationUnsuccessful) + .transitionTo(TAKEN_OFFLINE_BY_STAFF).onlyIf(takenOfflineByStaffBeforeMediationUnsuccessful) + .state(MEDIATION_UNSUCCESSFUL_PROCEED) + .transitionTo(IN_HEARING_READINESS).onlyIf(isInHearingReadiness) + .transitionTo(CLAIM_DISMISSED_HEARING_FEE_DUE_DEADLINE).onlyIf(caseDismissedPastHearingFeeDue) + .transitionTo(TAKEN_OFFLINE_BY_STAFF).onlyIf(takenOfflineByStaff) + .transitionTo(TAKEN_OFFLINE_AFTER_SDO).onlyIf(takenOfflineAfterSDO) + .transitionTo(TAKEN_OFFLINE_SDO_NOT_DRAWN).onlyIf(takenOfflineSDONotDrawn) .state(IN_HEARING_READINESS) .state(FULL_ADMIT_JUDGMENT_ADMISSION) .build(); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/hearings/HearingValuesService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/hearings/HearingValuesService.java index b518d73aaf4..3fc48b61a9f 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/hearings/HearingValuesService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/hearings/HearingValuesService.java @@ -8,15 +8,16 @@ import uk.gov.hmcts.reform.civil.config.ManageCaseBaseUrlConfiguration; import uk.gov.hmcts.reform.civil.config.PaymentsConfiguration; import uk.gov.hmcts.reform.civil.exceptions.CaseNotFoundException; -import uk.gov.hmcts.reform.civil.exceptions.PartyIdsUpdatedException; +import uk.gov.hmcts.reform.civil.exceptions.MissingFieldsUpdatedException; import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.hearingvalues.ServiceHearingValuesModel; import uk.gov.hmcts.reform.civil.service.CategoryService; import uk.gov.hmcts.reform.civil.service.CoreCaseDataService; import uk.gov.hmcts.reform.civil.service.OrganisationService; +import uk.gov.hmcts.reform.civil.utils.CaseFlagsInitialiser; -import static uk.gov.hmcts.reform.civil.callback.CaseEvent.UPDATE_PARTY_IDS; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.UPDATE_MISSING_FIELDS; import static uk.gov.hmcts.reform.civil.helpers.hearingsmappings.CaseFlagsMapper.getCaseFlags; import static uk.gov.hmcts.reform.civil.helpers.hearingsmappings.CaseFlagsToHearingValueMapper.hasCaseInterpreterRequiredFlag; import static uk.gov.hmcts.reform.civil.helpers.hearingsmappings.HearingDetailsMapper.getDuration; @@ -49,7 +50,15 @@ import static uk.gov.hmcts.reform.civil.helpers.hearingsmappings.ServiceHearingsCaseLevelMapper.getPublicCaseName; import static uk.gov.hmcts.reform.civil.helpers.hearingsmappings.VocabularyMapper.getVocabulary; import static uk.gov.hmcts.reform.civil.utils.HmctsServiceIDUtils.getHmctsServiceID; +import static uk.gov.hmcts.reform.civil.utils.PartyUtils.populateDQPartyIds; import static uk.gov.hmcts.reform.civil.utils.PartyUtils.populateWithPartyIds; +import static uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils.copyDatesIntoListingTabFields; +import static uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils.rollUpUnavailabilityDatesForRespondent; +import static uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils.shouldUpdateApplicant1UnavailableDates; +import static uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils.shouldUpdateApplicant2UnavailableDates; +import static uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils.shouldUpdateRespondent1UnavailableDates; +import static uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils.shouldUpdateRespondent2UnavailableDates; +import static uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils.updateMissingUnavailableDatesForApplicants; @Slf4j @Service @@ -64,10 +73,11 @@ public class HearingValuesService { private final CaseDetailsConverter caseDetailsConverter; private final OrganisationService organisationService; private final ObjectMapper mapper; + private final CaseFlagsInitialiser caseFlagInitialiser; public ServiceHearingValuesModel getValues(Long caseId, String hearingId, String authToken) throws Exception { CaseData caseData = retrieveCaseData(caseId); - populateMissingPartyIds(caseId, caseData); + populateMissingFields(caseId, caseData); String baseUrl = manageCaseBaseUrlConfiguration.getManageCaseBaseUrl(); String hmctsServiceID = getHmctsServiceID(caseData, paymentsConfiguration); @@ -117,35 +127,87 @@ private CaseData retrieveCaseData(long caseId) { } } + private void populateMissingFields(Long caseId, CaseData caseData) throws Exception { + CaseData.CaseDataBuilder builder = caseData.toBuilder(); + boolean partyIdsUpdated = populateMissingPartyIds(builder, caseData); + boolean unavailableDatesUpdated = populateMissingUnavailableDatesFields(builder); + boolean caseFlagsUpdated = initialiseMissingCaseFlags(builder); + + if (partyIdsUpdated || unavailableDatesUpdated || caseFlagsUpdated) { + try { + caseDataService.triggerEvent( + caseId, UPDATE_MISSING_FIELDS, builder.build().toMap(mapper)); + } catch (FeignException e) { + log.error("Updating missing fields failed: {}", e); + throw e; + } + throw new MissingFieldsUpdatedException(); + } + } + /** * Tactical solution to updated partyIds if they do not already exist. * The partyIds within applicant1 field is checked as that is the very first party field * that gets populated during claim creation. If no partyIds exist it's safe to assume there * are missing partyIds to populate. * + * @param builder case data builder * @param caseData given case data. - * @throws PartyIdsUpdatedException If party ids have been updated, to force the consumer to request + * @throws MissingFieldsUpdatedException If party ids have been updated, to force the consumer to request * the hearing values endpoint again. * @throws FeignException If an error is returned from case data service when triggering the event. */ - private void populateMissingPartyIds(Long caseId, CaseData caseData) throws Exception { + private boolean populateMissingPartyIds(CaseData.CaseDataBuilder builder, CaseData caseData) { if (caseData.getApplicant1().getPartyID() == null) { - var builder = caseData.toBuilder(); // Even if party ids creation is released and cases are // in an inconsistent state where app/res fields have no party ids // and litfriends, witnesses and experts do it's still safe to call populateWithPartyFlags // as it was created to not overwrite partyId fields if they exist. populateWithPartyIds(builder); + populateDQPartyIds(builder); + return true; + } + return false; + } - try { - caseDataService.triggerEvent( - caseId, UPDATE_PARTY_IDS, builder.build().toMap(mapper)); - } catch (FeignException e) { - log.error("Updating case data with party ids failed: {}", e); - throw e; - } + /** + * Tactical solution to update unavailable dates with date and event added. + * First the unavailable dates fields are checked if date added exists before + * overwriting with the event and date added fields + * + * @throws MissingFieldsUpdatedException If unavailable dates have been updated, to force the consumer to request + * the hearing values endpoint again. + * @throws FeignException If an error is returned from case data service when triggering the event. + */ + private boolean populateMissingUnavailableDatesFields(CaseData.CaseDataBuilder builder) { + CaseData caseData = builder.build(); + if (shouldUpdateApplicant1UnavailableDates(caseData) + || shouldUpdateApplicant2UnavailableDates(caseData) + || shouldUpdateRespondent1UnavailableDates(caseData) + || shouldUpdateRespondent2UnavailableDates(caseData)) { + updateMissingUnavailableDatesForApplicants(caseData, builder, true); + rollUpUnavailabilityDatesForRespondent(builder, true); + copyDatesIntoListingTabFields(builder.build(), builder); + return true; + } + return false; + } - throw new PartyIdsUpdatedException(); + /** + * Tactical solution to initialise case flags. + * First the applicant is checked for the flags field as it's the first one + * to get initialised on claim creation + * + * @throws MissingFieldsUpdatedException If case flags have been re-initialised, to force the consumer to request + * the hearing values endpoint again. + * @throws FeignException If an error is returned from case data service when triggering the event. + */ + private boolean initialiseMissingCaseFlags(CaseData.CaseDataBuilder builder) { + CaseData caseData = builder.build(); + if (caseData.getApplicant1().getFlags() == null) { + caseFlagInitialiser.initialiseMissingCaseFlags(builder); + return true; } + return false; } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/mediation/MediationCSVService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/mediation/MediationCSVService.java index b204bee884a..020ed9074e2 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/mediation/MediationCSVService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/mediation/MediationCSVService.java @@ -11,6 +11,8 @@ public abstract class MediationCSVService { private static final String CASE_TYPE = "1"; private static final String CHECK_LIST = "4"; private static final String PARTY_STATUS = "5"; + private static final String CLAIMANT = "1"; + private static final String RESPONDENT = "2"; public String generateCSVContent(CaseData caseData) { MediationParams mediationParams = getMediationParams(caseData); @@ -26,7 +28,7 @@ private String getCSVContent(MediationParams params) { String totalClaimAmount = data.getTotalClaimAmount().toString(); String[] claimantData = { SITE_ID, data.getLegacyCaseReference(), CASE_TYPE, totalClaimAmount, - data.getApplicant1().getType().toString(), getCsvCompanyName(data.getApplicant1()), + CLAIMANT, getCsvCompanyName(data.getApplicant1()), applicantContactDetails.getApplicantContactName(params), applicantContactDetails.getApplicantContactNumber(params), CHECK_LIST, PARTY_STATUS, applicantContactDetails.getApplicantContactEmail(params), isPilot(data.getTotalClaimAmount()) @@ -34,7 +36,7 @@ private String getCSVContent(MediationParams params) { String[] respondentData = { SITE_ID, data.getLegacyCaseReference(), CASE_TYPE, totalClaimAmount, - data.getRespondent1().getType().toString(), getCsvCompanyName(data.getRespondent1()), + RESPONDENT, getCsvCompanyName(data.getRespondent1()), defendantContactDetails.getDefendantContactName(params), defendantContactDetails.getDefendantContactNumber(params), CHECK_LIST, PARTY_STATUS, defendantContactDetails.getDefendantContactEmail(params), isPilot(data.getTotalClaimAmount()) diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/RoboticsNotificationService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/RoboticsNotificationService.java index cee35c21cf1..9eb0e618f21 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/RoboticsNotificationService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/RoboticsNotificationService.java @@ -14,6 +14,7 @@ import uk.gov.hmcts.reform.civil.model.robotics.RoboticsCaseDataSpec; import uk.gov.hmcts.reform.civil.sendgrid.EmailData; import uk.gov.hmcts.reform.civil.sendgrid.SendGridClient; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.robotics.dto.RoboticsCaseDataDTO; import uk.gov.hmcts.reform.civil.service.robotics.exception.RoboticsDataException; import uk.gov.hmcts.reform.civil.service.robotics.mapper.RoboticsDataMapper; @@ -45,6 +46,7 @@ public class RoboticsNotificationService { private final RoboticsEmailConfiguration roboticsEmailConfiguration; private final RoboticsDataMapper roboticsDataMapper; private final RoboticsDataMapperForSpec roboticsDataMapperForSpec; + private final FeatureToggleService toggleService; public void notifyRobotics(@NotNull CaseData caseData, boolean isMultiParty, String authToken) { requireNonNull(caseData); @@ -150,22 +152,42 @@ private String getSubject(CaseData caseData, String triggerEvent, boolean isMult private String getSubjectForSpec(CaseData caseData, String triggerEvent, boolean isMultiParty) { String subject; if (caseData.isRespondent1NotRepresented()) { - if (nonNull(caseData.getPaymentTypeSelection())) { - subject = String.format( - "LR v LiP Default Judgement Case Data for %s", - caseData.getLegacyCaseReference() - ); - } else if (caseData.isCcjRequestJudgmentByAdmission()) { - subject = String.format( - "LR v LiP Judgement by Admission Case Data for %s", - caseData.getLegacyCaseReference() - ); + if (caseData.isLipvLipOneVOne() && toggleService.isLipVLipEnabled()) { + if (nonNull(caseData.getPaymentTypeSelection())) { + subject = String.format( + "LiP v LiP Default Judgement Case Data for %s", + caseData.getLegacyCaseReference() + ); + } else if (caseData.isCcjRequestJudgmentByAdmission()) { + subject = String.format( + "LiP v LiP Judgement by Admission Case Data for %s", + caseData.getLegacyCaseReference() + ); + } else { + subject = String.format( + "LiP v LiP Case Data for %s", + caseData.getLegacyCaseReference() + ); + } } else { - subject = String.format( - "LR v LiP Case Data for %s", - caseData.getLegacyCaseReference() - ); + if (nonNull(caseData.getPaymentTypeSelection())) { + subject = String.format( + "LR v LiP Default Judgement Case Data for %s", + caseData.getLegacyCaseReference() + ); + } else if (caseData.isCcjRequestJudgmentByAdmission()) { + subject = String.format( + "LR v LiP Judgement by Admission Case Data for %s", + caseData.getLegacyCaseReference() + ); + } else { + subject = String.format( + "LR v LiP Case Data for %s", + caseData.getLegacyCaseReference() + ); + } } + } else if (isMultiParty) { subject = String.format("Multiparty LR v LR Case Data for %s - %s - %s", caseData.getLegacyCaseReference(), diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/EventHistoryMapper.java b/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/EventHistoryMapper.java index 6ff3372409e..f393162c526 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/EventHistoryMapper.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/EventHistoryMapper.java @@ -3,6 +3,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.Nullable; import org.springframework.stereotype.Component; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.enums.AllocatedTrack; @@ -14,13 +15,13 @@ import uk.gov.hmcts.reform.civil.enums.RespondentResponseType; import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec; import uk.gov.hmcts.reform.civil.enums.YesOrNo; -import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.ClaimProceedsInCaseman; import uk.gov.hmcts.reform.civil.model.ClaimProceedsInCasemanLR; import uk.gov.hmcts.reform.civil.model.ClaimantResponseDetails; import uk.gov.hmcts.reform.civil.model.Party; import uk.gov.hmcts.reform.civil.model.PartyData; +import uk.gov.hmcts.reform.civil.model.RepaymentPlanLRspec; import uk.gov.hmcts.reform.civil.model.RespondToClaim; import uk.gov.hmcts.reform.civil.model.breathing.BreathingSpaceType; import uk.gov.hmcts.reform.civil.model.dq.DQ; @@ -32,6 +33,7 @@ import uk.gov.hmcts.reform.civil.model.robotics.EventDetails; import uk.gov.hmcts.reform.civil.model.robotics.EventHistory; import uk.gov.hmcts.reform.civil.model.robotics.EventType; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.Time; import uk.gov.hmcts.reform.civil.service.flowstate.FlowState; import uk.gov.hmcts.reform.civil.service.flowstate.StateFlowEngine; @@ -41,11 +43,13 @@ import uk.gov.hmcts.reform.civil.utils.PartyUtils; import java.math.BigDecimal; +import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -368,6 +372,22 @@ private BigDecimal getInstallmentAmount(String amount) { return MonetaryConversions.penniesToPounds(regularRepaymentAmountPennies); } + @Nullable + private BigDecimal getInstallmentAmount(boolean isResponsePayByInstallment, Optional repaymentPlan) { + return isResponsePayByInstallment + ? MonetaryConversions.penniesToPounds( + repaymentPlan.map(RepaymentPlanLRspec::getPaymentAmount).map(amount -> amount.setScale(2)).orElse(BigDecimal.ZERO)) + : null; + } + + @Nullable + private LocalDate getFirstInstallmentDate(boolean isResponsePayByInstallment, Optional repaymentPlan) { + return isResponsePayByInstallment + ? repaymentPlan.map(RepaymentPlanLRspec::getFirstRepaymentDate) + .orElse(null) + : null; + } + private void buildBreathingSpaceEvent(EventHistory.EventHistoryBuilder builder, CaseData caseData, EventType eventType, String bsStatus) { String eventDetails = null; @@ -480,10 +500,14 @@ private void buildCcjEvent(EventHistory.EventHistoryBuilder builder, CaseData ca } private void buildJudgmentByAdmissionEventDetails(EventHistory.EventHistoryBuilder builder, CaseData caseData) { - EventDetails judgmentByAdmissionEvent; - judgmentByAdmissionEvent = EventDetails.builder() + boolean isResponsePayByInstallment = caseData.isPayByInstallment(); + Optional repaymentPlan = Optional.ofNullable(caseData.getRespondent1RepaymentPlan()); + EventDetails judgmentByAdmissionEvent = EventDetails.builder() .amountOfJudgment(caseData.getCcjPaymentDetails().getCcjJudgmentAmountClaimAmount() - .add(caseData.getTotalInterest()).setScale(2)) + .add(caseData.isLipvLipOneVOne() && featureToggleService.isLipVLipEnabled() + ? caseData.getCcjPaymentDetails().getCcjJudgmentLipInterest() : + caseData.getTotalInterest()) + .setScale(2)) .amountOfCosts(caseData.getCcjPaymentDetails().getCcjJudgmentFixedCostAmount() .add(caseData.getCcjPaymentDetails().getCcjJudgmentAmountClaimFee()).setScale(2)) .amountPaidBeforeJudgment(caseData.getCcjPaymentDetails().getCcjPaymentPaidSomeAmountInPounds().setScale(2)) @@ -491,16 +515,11 @@ private void buildJudgmentByAdmissionEventDetails(EventHistory.EventHistoryBuild .paymentInFullDate(caseData.isPayBySetDate() ? caseData.getRespondToClaimAdmitPartLRspec().getWhenWillThisAmountBePaid().atStartOfDay() : null) - .installmentAmount(caseData.isPayByInstallment() - ? MonetaryConversions.penniesToPounds( - caseData.getRespondent1RepaymentPlan().getPaymentAmount()).setScale(2) - : null) - .installmentPeriod(caseData.isPayByInstallment() - ? getInstallmentPeriodForRequestJudgmentByAdmission(caseData) + .installmentAmount(getInstallmentAmount(isResponsePayByInstallment, repaymentPlan)) + .installmentPeriod(isResponsePayByInstallment + ? getInstallmentPeriodForRequestJudgmentByAdmission(repaymentPlan) : null) - .firstInstallmentDate(caseData.isPayByInstallment() - ? caseData.getRespondent1RepaymentPlan().getFirstRepaymentDate() - : null) + .firstInstallmentDate(getFirstInstallmentDate(isResponsePayByInstallment, repaymentPlan)) .dateOfJudgment(setApplicant1ResponseDate(caseData)) .jointJudgment(false) .judgmentToBeRegistered(true) @@ -616,69 +635,6 @@ private void buildRespondentResponseEvent(EventHistory.EventHistoryBuilder build case FULL_ADMISSION: buildReceiptOfAdmission(builder, caseData, respondentResponseDate, respondentID); break; - /*case STATES_PAID: - builder.statesPaid( - Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(STATES_PAID.getCode()) - .dateReceived(respondentResponseDate) - .litigiousPartyID(respondentID) - .build()); - break; - case BREATHING_SPACE_ENTERED: - builder.breathingSpaceEntered( - Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(BREATHING_SPACE_ENTERED.getCode()) - .dateReceived(respondentResponseDate) - .litigiousPartyID(respondentID) - .build()); - break; - case BREATHING_SPACE_LIFTED: - builder.breathingSpaceEntered( - Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(BREATHING_SPACE_LIFTED.getCode()) - .dateReceived(respondentResponseDate) - .litigiousPartyID(respondentID) - .build()); - break; - case MENTAL_HEALTH_BREATHING_SPACE_ENTERED: - builder.breathingSpaceMentalHealthEntered( - Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(MENTAL_HEALTH_BREATHING_SPACE_ENTERED.getCode()) - .dateReceived(respondentResponseDate) - .litigiousPartyID(respondentID) - .build()); - break; - case MENTAL_HEALTH_BREATHING_SPACE_LIFTED: - builder.breathingSpaceMentalHealthLifted( - Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(MENTAL_HEALTH_BREATHING_SPACE_LIFTED.getCode()) - .dateReceived(respondentResponseDate) - .litigiousPartyID(respondentID) - .build()); - break;*/ - /*case INTENTION_TO_PROCEED: - builder.receiptOfAdmission( - Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(INTENTION_TO_PROCEED.getCode()) - .dateReceived(respondentResponseDate) - .litigiousPartyID(respondentID) - .build()); - break; - case INTENTION_TO_PROCEED_STATES_PAID: - builder.receiptOfAdmission( - Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(INTENTION_TO_PROCEED_STATES_PAID.getCode()) - .dateReceived(respondentResponseDate) - .litigiousPartyID(respondentID) - .build()); - break;*/ default: break; } @@ -1110,15 +1066,15 @@ private void buildTakenOfflineMultitrackUnspec(EventHistory.EventHistoryBuilder if (AllocatedTrack.MULTI_CLAIM.equals(caseData.getAllocatedTrack())) { String miscText = "RPA Reason:Multitrack Unspec going offline."; builder.miscellaneous( - Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(MISCELLANEOUS.getCode()) - .dateReceived(caseData.getApplicant1ResponseDate()) - .eventDetailsText(miscText) - .eventDetails(EventDetails.builder() - .miscText(miscText) - .build()) - .build()); + Event.builder() + .eventSequence(prepareEventSequence(builder.build())) + .eventCode(MISCELLANEOUS.getCode()) + .dateReceived(caseData.getApplicant1ResponseDate()) + .eventDetailsText(miscText) + .eventDetails(EventDetails.builder() + .miscText(miscText) + .build()) + .build()); } } @@ -1880,6 +1836,21 @@ private void buildAcknowledgementOfServiceSpec(EventHistory.EventHistoryBuilder .build())); } + private void buildRespondentResponseText(EventHistory.EventHistoryBuilder builder, CaseData caseData, String miscText, LocalDateTime respondentResponseDate) { + if (!SPEC_CLAIM.equals(caseData.getCaseAccessCategory())) { + builder.miscellaneous(Event.builder() + .eventSequence(prepareEventSequence(builder.build())) + .eventCode(MISCELLANEOUS.getCode()) + .dateReceived(respondentResponseDate) + .eventDetailsText(miscText) + .eventDetails(EventDetails.builder() + .miscText(miscText) + .build()) + .build()); + } + + } + private void buildRespondentFullAdmission(EventHistory.EventHistoryBuilder builder, CaseData caseData) { String miscText; if (defendant1ResponseExists.test(caseData)) { @@ -1890,15 +1861,8 @@ private void buildRespondentFullAdmission(EventHistory.EventHistoryBuilder build .dateReceived(caseData.getRespondent1ResponseDate()) .litigiousPartyID(RESPONDENT_ID) .build() - ).miscellaneous(Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(MISCELLANEOUS.getCode()) - .dateReceived(caseData.getRespondent1ResponseDate()) - .eventDetailsText(miscText) - .eventDetails(EventDetails.builder() - .miscText(miscText) - .build()) - .build()); + ); + buildRespondentResponseText(builder, caseData, miscText, caseData.getRespondent1ResponseDate()); if (defendant1v2SameSolicitorSameResponse.test(caseData)) { LocalDateTime respondent2ResponseDate = null != caseData.getRespondent2ResponseDate() @@ -1910,15 +1874,8 @@ private void buildRespondentFullAdmission(EventHistory.EventHistoryBuilder build .dateReceived(respondent2ResponseDate) .litigiousPartyID(RESPONDENT2_ID) .build() - ).miscellaneous(Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(MISCELLANEOUS.getCode()) - .dateReceived(respondent2ResponseDate) - .eventDetailsText(miscText) - .eventDetails(EventDetails.builder() - .miscText(miscText) - .build()) - .build()); + ); + buildRespondentResponseText(builder, caseData, miscText, respondent2ResponseDate); } } if (defendant2ResponseExists.test(caseData)) { @@ -1929,15 +1886,8 @@ private void buildRespondentFullAdmission(EventHistory.EventHistoryBuilder build .dateReceived(caseData.getRespondent2ResponseDate()) .litigiousPartyID(RESPONDENT2_ID) .build() - ).miscellaneous(Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(MISCELLANEOUS.getCode()) - .dateReceived(caseData.getRespondent2ResponseDate()) - .eventDetailsText(miscText) - .eventDetails(EventDetails.builder() - .miscText(miscText) - .build()) - .build()); + ); + buildRespondentResponseText(builder, caseData, miscText, caseData.getRespondent2ResponseDate()); } } @@ -1946,26 +1896,33 @@ private void buildRespondentPartAdmission(EventHistory.EventHistoryBuilder build List directionsQuestionnaireFiledEvents = new ArrayList<>(); boolean isRespondent1; if (defendant1ResponseExists.test(caseData)) { - Party respondent1 = caseData.getRespondent1(); + final Party respondent1 = caseData.getRespondent1(); miscText = prepareRespondentResponseText(caseData, caseData.getRespondent1(), true); Respondent1DQ respondent1DQ = caseData.getRespondent1DQ(); LocalDateTime respondent1ResponseDate = caseData.getRespondent1ResponseDate(); - builder.receiptOfPartAdmission( - Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(RECEIPT_OF_PART_ADMISSION.getCode()) - .dateReceived(caseData.getRespondent1ResponseDate()) - .litigiousPartyID(RESPONDENT_ID) - .build() - ).miscellaneous(Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(MISCELLANEOUS.getCode()) - .dateReceived(caseData.getRespondent1ResponseDate()) - .eventDetailsText(miscText) - .eventDetails(EventDetails.builder() - .miscText(miscText) - .build()) - .build()); + + if (SPEC_CLAIM.equals(caseData.getCaseAccessCategory()) + && Objects.nonNull(caseData.getSpecDefenceAdmittedRequired()) + && caseData.getSpecDefenceAdmittedRequired().equals(YES)) { + builder.statesPaid(buildDefenceFiledEvent( + builder, + respondent1ResponseDate, + RESPONDENT_ID, + true + )); + } else { + builder.receiptOfPartAdmission( + Event.builder() + .eventSequence(prepareEventSequence(builder.build())) + .eventCode(RECEIPT_OF_PART_ADMISSION.getCode()) + .dateReceived(caseData.getRespondent1ResponseDate()) + .litigiousPartyID(RESPONDENT_ID) + .build() + ); + } + + buildRespondentResponseText(builder, caseData, miscText, respondent1ResponseDate); + directionsQuestionnaireFiledEvents.add( buildDirectionsQuestionnaireFiledEvent(builder, caseData, respondent1ResponseDate, @@ -1975,8 +1932,8 @@ private void buildRespondentPartAdmission(EventHistory.EventHistoryBuilder build true )); if (defendant1v2SameSolicitorSameResponse.test(caseData)) { - Party respondent2 = caseData.getRespondent2(); - Respondent1DQ respondent2DQ = caseData.getRespondent1DQ(); + final Party respondent2 = caseData.getRespondent2(); + final Respondent1DQ respondent2DQ = caseData.getRespondent1DQ(); LocalDateTime respondent2ResponseDate = null != caseData.getRespondent2ResponseDate() ? caseData.getRespondent2ResponseDate() : caseData.getRespondent1ResponseDate(); miscText = prepareRespondentResponseText(caseData, caseData.getRespondent2(), false); @@ -1987,15 +1944,8 @@ private void buildRespondentPartAdmission(EventHistory.EventHistoryBuilder build .dateReceived(respondent2ResponseDate) .litigiousPartyID(RESPONDENT2_ID) .build() - ).miscellaneous(Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(MISCELLANEOUS.getCode()) - .dateReceived(respondent2ResponseDate) - .eventDetailsText(miscText) - .eventDetails(EventDetails.builder() - .miscText(miscText) - .build()) - .build()); + ); + buildRespondentResponseText(builder, caseData, miscText, respondent2ResponseDate); directionsQuestionnaireFiledEvents.add( buildDirectionsQuestionnaireFiledEvent(builder, caseData, respondent2ResponseDate, @@ -2018,15 +1968,10 @@ private void buildRespondentPartAdmission(EventHistory.EventHistoryBuilder build .dateReceived(caseData.getRespondent2ResponseDate()) .litigiousPartyID(RESPONDENT2_ID) .build() - ).miscellaneous(Event.builder() - .eventSequence(prepareEventSequence(builder.build())) - .eventCode(MISCELLANEOUS.getCode()) - .dateReceived(caseData.getRespondent2ResponseDate()) - .eventDetailsText(miscText) - .eventDetails(EventDetails.builder() - .miscText(miscText) - .build()) - .build()); + ); + + buildRespondentResponseText(builder, caseData, miscText, respondent2ResponseDate); + directionsQuestionnaireFiledEvents.add( buildDirectionsQuestionnaireFiledEvent(builder, caseData, respondent2ResponseDate, @@ -2231,17 +2176,19 @@ private String getInstallmentPeriod(CaseData data) { return "FUL"; } - private String getInstallmentPeriodForRequestJudgmentByAdmission(CaseData caseData) { - switch (caseData.getRespondent1RepaymentPlan().getRepaymentFrequency()) { - case ONCE_ONE_WEEK: - return "WK"; - case ONCE_TWO_WEEKS: - return "FOR"; - case ONCE_ONE_MONTH: - return "MTH"; - default: - return null; - } + private String getInstallmentPeriodForRequestJudgmentByAdmission(Optional repaymentPlanLRspec) { + return repaymentPlanLRspec.map(RepaymentPlanLRspec::getRepaymentFrequency).map(repaymentFrequency -> { + switch (repaymentFrequency) { + case ONCE_ONE_WEEK: + return "WK"; + case ONCE_TWO_WEEKS: + return "FOR"; + case ONCE_ONE_MONTH: + return "MTH"; + default: + return null; + } + }).orElse(null); } private BigDecimal getCostOfJudgment(CaseData data) { @@ -2292,7 +2239,7 @@ private void buildSpecAdmitRejectRepayment(EventHistory.EventHistoryBuilder buil } private void buildClaimInMediation(EventHistory.EventHistoryBuilder builder, - CaseData caseData) { + CaseData caseData) { if (caseData.hasDefendantAgreedToFreeMediation() && caseData.hasClaimantAgreedToFreeMediation()) { @@ -2365,7 +2312,7 @@ private void buildLrVLipFullDefenceEvent(EventHistory.EventHistoryBuilder builde private LocalDateTime setApplicant1ResponseDate(CaseData caseData) { LocalDateTime applicant1ResponseDate = caseData.getApplicant1ResponseDate(); - if (applicant1ResponseDate == null) { + if (applicant1ResponseDate == null || applicant1ResponseDate.isBefore(LocalDateTime.now())) { applicant1ResponseDate = LocalDateTime.now(); } return applicant1ResponseDate; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/RoboticsDataMapper.java b/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/RoboticsDataMapper.java index 35a06bd365d..40e0726dfc4 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/RoboticsDataMapper.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/RoboticsDataMapper.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.reform.civil.service.robotics.mapper; +import feign.FeignException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -151,8 +152,13 @@ private Solicitor buildRespondentSolicitor(CaseData caseData, String id) { ); if (organisationId != null) { - organisationService.findOrganisationById(organisationId) - .ifPresent(buildOrganisation(solicitorBuilder, caseData.getRespondentSolicitor1ServiceAddress())); + try { + organisationService.findOrganisationById(organisationId) + .ifPresent(buildOrganisation(solicitorBuilder, caseData.getRespondentSolicitor1ServiceAddress())); + } catch (FeignException e) { + log.error("Error recovering org id " + organisationId + + " for case id " + caseData.getLegacyCaseReference(), e); + } } organisationDetails.ifPresent(buildOrganisationDetails(solicitorBuilder)); @@ -221,9 +227,16 @@ private Solicitor buildApplicantSolicitor(CaseData caseData, String id) { .orElse(null) ); - organisationId - .flatMap(organisationService::findOrganisationById) - .ifPresent(buildOrganisation(solicitorBuilder, caseData.getApplicantSolicitor1ServiceAddress())); + try { + organisationId + .flatMap(organisationService::findOrganisationById) + .ifPresent(buildOrganisation(solicitorBuilder, caseData.getApplicantSolicitor1ServiceAddress())); + } catch (FeignException e) { + /* CIV-10011 organisationId is not null (if it were, the call to findOrganisationById would not have + been done, so the FeignException would not have been thrown */ + log.error("Error recovering org id " + organisationId.orElse(null) + + " for case id " + caseData.getLegacyCaseReference(), e); + } return solicitorBuilder.build(); } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/RoboticsDataMapperForSpec.java b/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/RoboticsDataMapperForSpec.java index e97f1c852fb..f3354fc706a 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/RoboticsDataMapperForSpec.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/RoboticsDataMapperForSpec.java @@ -107,7 +107,8 @@ private CaseHeader buildCaseHeader(CaseData caseData) { private List buildSolicitors(CaseData caseData) { List solicitorsList = new ArrayList<>(); - solicitorsList.add(buildApplicantSolicitor(caseData)); + ofNullable(buildApplicantSolicitor(caseData)) + .ifPresent(solicitorsList::add); ofNullable(buildRespondentSolicitor(caseData)) .ifPresent(solicitorsList::add); @@ -227,6 +228,9 @@ private Consumer buildOrganisationDetails( } private Solicitor buildApplicantSolicitor(CaseData caseData) { + if (featureToggleService.isLipVLipEnabled() && caseData.isLipvLipOneVOne()) { + return null; + } Optional organisationId = getOrganisationId(caseData.getApplicant1OrganisationPolicy()); var providedServiceAddress = caseData.getSpecApplicantCorrespondenceAddressdetails(); Solicitor.SolicitorBuilder solicitorBuilder = Solicitor.builder() diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyCheckSearchService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyCheckSearchService.java index d23f38cf85b..b418a6a16fd 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyCheckSearchService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyCheckSearchService.java @@ -13,6 +13,7 @@ import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.matchQuery; import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; +import static uk.gov.hmcts.reform.civil.enums.CaseState.HEARING_READINESS; import static uk.gov.hmcts.reform.civil.enums.CaseState.PREPARE_FOR_HEARING_CONDUCT_HEARING; @Service @@ -30,7 +31,10 @@ public Query query(int startIndex) { .must(rangeQuery("data.hearingDate").lt(LocalDate.now() .atTime(LocalTime.MIN).plusWeeks(3) .toString())) - .must(beState(PREPARE_FOR_HEARING_CONDUCT_HEARING)) + .must(boolQuery() + .minimumShouldMatch(1) + .should(beState(PREPARE_FOR_HEARING_CONDUCT_HEARING)) + .should(beState(HEARING_READINESS))) .mustNot(matchQuery("data.allocatedTrack", "SMALL_CLAIM")) .mustNot(matchQuery("data.trialReadyChecked", "Yes"))), List.of("reference"), diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyNotificationSearchService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyNotificationSearchService.java index 878b2f73638..53a26cd55e1 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyNotificationSearchService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyNotificationSearchService.java @@ -15,6 +15,7 @@ import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.matchQuery; import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; +import static uk.gov.hmcts.reform.civil.enums.CaseState.HEARING_READINESS; import static uk.gov.hmcts.reform.civil.enums.CaseState.PREPARE_FOR_HEARING_CONDUCT_HEARING; @Service @@ -32,10 +33,13 @@ public Query query(int startIndex) { .must(rangeQuery("data.hearingDate").lt(LocalDate.now() .atTime(LocalTime.MIN) .plusWeeks(6).toString())) - .must(beState(PREPARE_FOR_HEARING_CONDUCT_HEARING))) + .must(boolQuery() + .minimumShouldMatch(1) + .should(beState(PREPARE_FOR_HEARING_CONDUCT_HEARING)) + .should(beState(HEARING_READINESS))) .mustNot(matchQuery("data.allocatedTrack", "SMALL_CLAIM")) .mustNot(matchQuery("data.listingOrRelisting", ListingOrRelisting.RELISTING)) - .mustNot(matchQuery("data.trialReadyNotified", YesOrNo.YES)), + .mustNot(matchQuery("data.trialReadyNotified", YesOrNo.YES))), List.of("reference"), startIndex ); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/service/stitching/CivilDocumentStitchingService.java b/src/main/java/uk/gov/hmcts/reform/civil/service/stitching/CivilDocumentStitchingService.java index 9f34abfe63a..1dd8250a528 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/service/stitching/CivilDocumentStitchingService.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/service/stitching/CivilDocumentStitchingService.java @@ -18,6 +18,7 @@ import uk.gov.hmcts.reform.civil.model.documents.DocumentMetaData; import java.time.LocalDateTime; +import java.time.ZoneId; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -37,7 +38,13 @@ public class CivilDocumentStitchingService implements DocumentStitcher { public CaseDocument bundle(List documents, String authorisation, String bundleTitle, String bundleFilename, CaseData caseData) { CaseDetails payload = createBundlePayload(documents, bundleTitle, bundleFilename, caseData); - log.info("Calling stitching api end point for {}", caseData.getLegacyCaseReference()); + log.info( + "Calling stitching api end point for {}, Bundle Title {}, File Name {}", + caseData.getLegacyCaseReference(), + bundleTitle, + bundleFilename + ); + CaseData caseDataFromBundlePayload = bundleRequestExecutor.post( BundleRequest.builder().caseDetails(payload).build(), stitchingConfiguration.getStitchingUrl(), @@ -63,11 +70,14 @@ private CaseDocument retrieveCaseDocument(Optional stitchedDocument) { Document document = stitchedDocument.get(); String documentUrl = document.getDocumentUrl(); String documentBinaryUrl = document.getDocumentBinaryUrl(); + return CaseDocument.builder() - .documentLink(Document.builder().documentUrl(documentUrl).documentBinaryUrl(documentBinaryUrl).documentFileName(document.getDocumentFileName()).build()) + .documentLink(Document.builder().documentUrl(documentUrl) + .documentBinaryUrl(documentBinaryUrl) + .documentFileName(document.getDocumentFileName()).build()) .documentName("Stitched document") .documentType(SEALED_CLAIM) - .createdDatetime(LocalDateTime.now()) + .createdDatetime(LocalDateTime.now(ZoneId.of("Europe/London"))) .createdBy(CREATED_BY) .build(); } @@ -80,7 +90,7 @@ private CaseDetails createBundlePayload(List documents, String List> idValueList = new ArrayList<>(); idValueList.add(new IdValue<>( "1", - Bundle.builder().id("1").description(bundleTitle).eligibleForStitching("yes").documents(bundleDocuments).filename(bundleFilename).build() + Bundle.builder().id("1").description(bundleTitle).eligibleForStitching("yes").documents(bundleDocuments).fileName(bundleFilename).build() )); CaseData.CaseDataBuilder caseDataBuilder = caseData.toBuilder(); @@ -112,4 +122,3 @@ private static List> prepareBundleDocuments(List> copyCaseDocumentListWithCategoryId( + List> source, String theID) { + if (!featureToggleService.isCaseFileViewEnabled()) { + return null; + } + return source.stream().map(caseDocument -> { + Document sourceDocument = caseDocument.getValue().getDocumentLink(); + Document document = Document.builder() + .categoryID(theID) + .documentFileName(sourceDocument.getDocumentFileName()) + .documentBinaryUrl(sourceDocument.getDocumentBinaryUrl()) + .documentHash(sourceDocument.getDocumentHash()) + .documentUrl(sourceDocument.getDocumentUrl()) + .build(); + return element(CaseDocument.builder() + .documentName(caseDocument.getValue().getDocumentName()) + .documentType(caseDocument.getValue().getDocumentType()) + .documentLink(document) + .documentSize(caseDocument.getValue().getDocumentSize()) + .createdBy(caseDocument.getValue().getCreatedBy()) + .createdDatetime(caseDocument.getValue().getCreatedDatetime()) + .build()); + }).toList(); + } + public void assignCategoryIdToDocument(Document documentUpload, String theID) { if (!featureToggleService.isCaseFileViewEnabled()) { return; diff --git a/src/main/java/uk/gov/hmcts/reform/civil/utils/CaseFlagUtils.java b/src/main/java/uk/gov/hmcts/reform/civil/utils/CaseFlagUtils.java index 569a9f22620..cfc0249f777 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/utils/CaseFlagUtils.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/utils/CaseFlagUtils.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.reform.civil.utils; +import uk.gov.hmcts.reform.ccd.model.OrganisationPolicy; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.PartyFlagStructure; import uk.gov.hmcts.reform.civil.model.caseflags.FlagDetail; @@ -22,18 +23,45 @@ import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.element; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.unwrapElements; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_LEGAL_REP_INDIVIDUALS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_ORG_INDIVIDUALS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_TWO_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_TWO_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_TWO_ORG_INDIVIDUALS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_LEGAL_REP_INDIVIDUALS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_ORG_INDIVIDUALS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_LEGAL_REP_INDIVIDUALS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_ORG_INDIVIDUALS_ID; +import static uk.gov.hmcts.reform.civil.utils.PartyUtils.appendWithNewPartyId; import uk.gov.hmcts.reform.civil.model.LitigationFriend; import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.prd.model.Organisation; +import uk.gov.hmcts.reform.civil.service.OrganisationService; public class CaseFlagUtils { - public static String RESPONDENT_SOLICITOR_ONE_WITNESS = "Respondent solicitor 1 witness"; - public static String RESPONDENT_SOLICITOR_ONE_EXPERT = "Respondent solicitor 1 expert"; - public static String RESPONDENT_SOLICITOR_TWO_WITNESS = "Respondent solicitor 2 witness"; - public static String RESPONDENT_SOLICITOR_TWO_EXPERT = "Respondent solicitor 2 expert"; - public static String APPLICANT_SOLICITOR_WITNESS = "Applicant solicitor witness"; - public static String APPLICANT_SOLICITOR_EXPERT = "Applicant solicitor expert"; + public static final String RESPONDENT_SOLICITOR_ONE_WITNESS = "Respondent solicitor 1 witness"; + public static final String RESPONDENT_SOLICITOR_ONE_EXPERT = "Respondent solicitor 1 expert"; + public static final String RESPONDENT_SOLICITOR_TWO_WITNESS = "Respondent solicitor 2 witness"; + public static final String RESPONDENT_SOLICITOR_TWO_EXPERT = "Respondent solicitor 2 expert"; + public static final String APPLICANT_SOLICITOR_WITNESS = "Applicant solicitor witness"; + public static final String APPLICANT_SOLICITOR_EXPERT = "Applicant solicitor expert"; + public static final String APPLICANT_ONE = "Applicant 1"; + public static final String APPLICANT_TWO = "Applicant 2"; + public static final String APPLICANT_ONE_LITIGATION_FRIEND = "Applicant 1 Litigation Friend"; + public static final String APPLICANT_TWO_LITIGATION_FRIEND = "Applicant 2 Litigation Friend"; + public static final String RESPONDENT_ONE = "Respondent 1"; + public static final String RESPONDENT_TWO = "Respondent 2"; + public static final String RESPONDENT_ONE_LITIGATION_FRIEND = "Respondent 1 Litigation Friend"; + public static final String RESPONDENT_TWO_LITIGATION_FRIEND = "Respondent 2 Litigation Friend"; private CaseFlagUtils() { //NO-OP @@ -47,10 +75,11 @@ public static Flags createFlags(String flagsPartyName, String roleOnCase) { .build(); } - private static PartyFlagStructure createPartiesCaseFlagsField(String firstName, String lastName, + private static PartyFlagStructure createPartiesCaseFlagsField(String partyId, String firstName, String lastName, String email, String phone, String roleOnCase) { - String partyName = String.format("%s %s", firstName, lastName); + String partyName = formattedPartyNameForFlags(firstName, lastName); return PartyFlagStructure.builder() + .partyID(partyId) .firstName(firstName) .lastName(lastName) .email(email) @@ -71,7 +100,7 @@ public static LitigationFriend updateLitFriend(String roleOnCase, LitigationFrie // ToDo: Remove the use of fullName after H&L changes are default ===================================== litFriendToUpdate.getFullName() != null ? litFriendToUpdate.getFullName() // ==================================================================================================== - : String.format("%s %s", litFriendToUpdate.getFirstName(), litFriendToUpdate.getLastName()), + : formattedPartyNameForFlags(litFriendToUpdate.getFirstName(), litFriendToUpdate.getLastName()), roleOnCase)).build() : null; } @@ -80,7 +109,7 @@ private static List> getTopLevelFieldForWitnessesWit String roleOnCase) { List> list = new ArrayList<>(); for (Witness witness : witnessList) { - PartyFlagStructure build = createPartiesCaseFlagsField(witness.getFirstName(), witness.getLastName(), + PartyFlagStructure build = createPartiesCaseFlagsField(witness.getPartyID(), witness.getFirstName(), witness.getLastName(), witness.getEmailAddress(), witness.getPhoneNumber(), roleOnCase); list.add(element(build)); @@ -93,7 +122,7 @@ private static List> getTopLevelFieldForExpertsWithF String roleOnCase) { List> list = new ArrayList<>(); for (Expert expert : expertList) { - PartyFlagStructure build = createPartiesCaseFlagsField(expert.getFirstName(), expert.getLastName(), + PartyFlagStructure build = createPartiesCaseFlagsField(expert.getPartyID(), expert.getFirstName(), expert.getLastName(), expert.getEmailAddress(), expert.getPhoneNumber(), roleOnCase); list.add(element(build)); @@ -170,6 +199,129 @@ public static void addApplicantExpertAndWitnessFlagsStructure(CaseData.CaseDataB } } + public static void createOrUpdateFlags(CaseData.CaseDataBuilder builder, CaseData caseData, OrganisationService organisationService) { + String partyChosen = caseData.getUpdateDetailsForm().getPartyChosenId(); + // claimant/defendant + updatePartyFlags(builder, caseData, partyChosen); + // litigation friend + updateLitigationFriendFlags(builder, caseData, partyChosen); + // attending for org/company + updateOrgIndividualsFlags(builder, caseData, partyChosen); + // attending for legal rep + updateLRIndividualsFlags(builder, caseData, partyChosen, organisationService); + } + + private static void updateLRIndividualsFlags(CaseData.CaseDataBuilder builder, CaseData caseData, String partyChosen, OrganisationService organisationService) { + if ((CLAIMANT_ONE_LEGAL_REP_INDIVIDUALS_ID).equals(partyChosen)) { + String legalRepFirmName = getLegalRepFirmName( + caseData.getApplicant1OrganisationPolicy(), + organisationService, + APPLICANT_ONE); + builder.applicant1LRIndividuals(updatePartyNameForPartyFlagStructures(caseData.getApplicant1LRIndividuals(), legalRepFirmName)); + } + if ((DEFENDANT_ONE_LEGAL_REP_INDIVIDUALS_ID).equals(partyChosen)) { + String legalRepFirmName = getLegalRepFirmName( + caseData.getRespondent1OrganisationPolicy(), + organisationService, + RESPONDENT_ONE); + builder.respondent1LRIndividuals(updatePartyNameForPartyFlagStructures(caseData.getRespondent1LRIndividuals(), legalRepFirmName)); + } + if ((DEFENDANT_TWO_LEGAL_REP_INDIVIDUALS_ID).equals(partyChosen)) { + String legalRepFirmName = getLegalRepFirmName( + caseData.getRespondent2OrganisationPolicy(), + organisationService, + RESPONDENT_TWO); + builder.respondent2LRIndividuals(updatePartyNameForPartyFlagStructures(caseData.getRespondent2LRIndividuals(), legalRepFirmName)); + } + } + + private static void updateOrgIndividualsFlags(CaseData.CaseDataBuilder builder, CaseData caseData, String partyChosen) { + if ((CLAIMANT_ONE_ORG_INDIVIDUALS_ID).equals(partyChosen)) { + builder.applicant1OrgIndividuals(updatePartyNameForPartyFlagStructures(caseData.getApplicant1OrgIndividuals(), caseData.getApplicant1().getPartyName())); + } + if ((CLAIMANT_TWO_ORG_INDIVIDUALS_ID).equals(partyChosen)) { + builder.applicant2OrgIndividuals(updatePartyNameForPartyFlagStructures(caseData.getApplicant2OrgIndividuals(), caseData.getApplicant2().getPartyName())); + } + if ((DEFENDANT_ONE_ORG_INDIVIDUALS_ID).equals(partyChosen)) { + builder.respondent1OrgIndividuals(updatePartyNameForPartyFlagStructures(caseData.getRespondent1OrgIndividuals(), caseData.getRespondent1().getPartyName())); + } + if ((DEFENDANT_TWO_ORG_INDIVIDUALS_ID).equals(partyChosen)) { + builder.respondent2OrgIndividuals(updatePartyNameForPartyFlagStructures(caseData.getRespondent2OrgIndividuals(), caseData.getRespondent2().getPartyName())); + } + } + + private static void updateLitigationFriendFlags(CaseData.CaseDataBuilder builder, CaseData caseData, String partyChosen) { + if ((CLAIMANT_ONE_LITIGATION_FRIEND_ID).equals(partyChosen)) { + builder.applicant1LitigationFriend(updatePartyNameForLitigationFriendFlags(caseData.getApplicant1LitigationFriend())); + } + if ((CLAIMANT_TWO_LITIGATION_FRIEND_ID).equals(partyChosen)) { + builder.applicant2LitigationFriend(updatePartyNameForLitigationFriendFlags(caseData.getApplicant2LitigationFriend())); + } + if ((DEFENDANT_ONE_LITIGATION_FRIEND_ID).equals(partyChosen)) { + builder.respondent1LitigationFriend(updatePartyNameForLitigationFriendFlags(caseData.getRespondent1LitigationFriend())); + } + if ((DEFENDANT_TWO_LITIGATION_FRIEND_ID).equals(partyChosen)) { + builder.respondent2LitigationFriend(updatePartyNameForLitigationFriendFlags(caseData.getRespondent2LitigationFriend())); + } + } + + private static void updatePartyFlags(CaseData.CaseDataBuilder builder, CaseData caseData, String partyChosen) { + if ((CLAIMANT_ONE_ID).equals(partyChosen)) { + builder.applicant1(updatePartyNameForFlags(caseData.getApplicant1())); + } + if ((CLAIMANT_TWO_ID).equals(partyChosen)) { + builder.applicant2(updatePartyNameForFlags(caseData.getApplicant2())); + } + if ((DEFENDANT_ONE_ID).equals(partyChosen)) { + builder.respondent1(updatePartyNameForFlags(caseData.getRespondent1())); + } + if ((DEFENDANT_TWO_ID).equals(partyChosen)) { + builder.respondent2(updatePartyNameForFlags(caseData.getRespondent2())); + } + } + + private static List> updatePartyNameForPartyFlagStructures(List> individuals, + String roleOnCase) { + if (individuals != null && !individuals.isEmpty()) { + List partyFlagStructures = unwrapElements(individuals); + List updatedList = new ArrayList<>(); + for (PartyFlagStructure partyFlagStructure : partyFlagStructures) { + String formattedPartyNameForFlags = formattedPartyNameForFlags(partyFlagStructure.getFirstName(), partyFlagStructure.getLastName()); + if (partyFlagStructure.getFlags() == null) { + // new party so initialise flags and party ID + updatedList.add( + appendWithNewPartyId(partyFlagStructure + .toBuilder() + .flags(createFlags(formattedPartyNameForFlags, roleOnCase)).build())); + } else { + // existing party with flags so just update the name + updatedList.add( + partyFlagStructure + .toBuilder() + .flags(partyFlagStructure.getFlags().toBuilder() + .partyName(formattedPartyNameForFlags) + .build()).build()); + } + } + return wrapElements(updatedList); + } + return null; + } + + private static Party updatePartyNameForFlags(Party party) { + return party.toBuilder().flags(party.getFlags().toBuilder() + .partyName(party.getPartyName()) + .build()).build(); + } + + private static LitigationFriend updatePartyNameForLitigationFriendFlags(LitigationFriend litigationFriend) { + return litigationFriend.toBuilder() + .flags(litigationFriend.getFlags().toBuilder() + .partyName(litigationFriend.getFullName() != null ? litigationFriend.getFullName() + : formattedPartyNameForFlags(litigationFriend.getFirstName(), litigationFriend.getLastName())) + .build()).build(); + } + public static List getAllCaseFlags(CaseData caseData) { var flagCollection = new ArrayList(); flagCollection.addAll(getFlagDetails(caseData.getCaseFlags())); @@ -221,4 +373,17 @@ public static List filter(List flagDetails, Predicate true)) .collect(Collectors.toList()); } + + private static String formattedPartyNameForFlags(String firstName, String lastName) { + return String.format("%s %s", firstName, lastName); + } + + private static String getLegalRepFirmName(OrganisationPolicy organisationPolicy, + OrganisationService organisationService, + String party) { + String organisationID = organisationPolicy.getOrganisation().getOrganisationID(); + return organisationService.findOrganisationById(organisationID) + .map(Organisation::getName) + .orElse(String.format("legal representative for %s", party.toLowerCase())); + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/utils/CaseFlagsInitialiser.java b/src/main/java/uk/gov/hmcts/reform/civil/utils/CaseFlagsInitialiser.java index af59095bcbf..708b197e462 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/utils/CaseFlagsInitialiser.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/utils/CaseFlagsInitialiser.java @@ -5,15 +5,27 @@ import uk.gov.hmcts.reform.civil.callback.CaseEvent; import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.service.OrganisationService; +import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.APPLICANT_ONE; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.APPLICANT_ONE_LITIGATION_FRIEND; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.APPLICANT_TWO; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.APPLICANT_TWO_LITIGATION_FRIEND; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.RESPONDENT_ONE; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.RESPONDENT_ONE_LITIGATION_FRIEND; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.RESPONDENT_TWO; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.RESPONDENT_TWO_LITIGATION_FRIEND; import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.addApplicantExpertAndWitnessFlagsStructure; import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.addRespondentDQPartiesFlagStructure; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.createOrUpdateFlags; @Component @AllArgsConstructor public class CaseFlagsInitialiser { private final FeatureToggleService featureToggleService; + private final OrganisationService organisationService; public void initialiseCaseFlags(CaseEvent caseEvent, CaseData.CaseDataBuilder dataBuilder) { if (!featureToggleService.isCaseFlagsEnabled()) { @@ -24,29 +36,11 @@ public void initialiseCaseFlags(CaseEvent caseEvent, CaseData.CaseDataBuilder da switch (caseEvent) { case CREATE_CLAIM: case CREATE_CLAIM_SPEC: { - dataBuilder - .applicant1(CaseFlagUtils.updateParty("Applicant 1", caseData.getApplicant1())) - .applicant2(CaseFlagUtils.updateParty("Applicant 2", caseData.getApplicant2())) - .respondent1(CaseFlagUtils.updateParty("Respondent 1", caseData.getRespondent1())) - .respondent2(CaseFlagUtils.updateParty("Respondent 2", caseData.getRespondent2())) - .applicant1LitigationFriend(CaseFlagUtils.updateLitFriend( - "Applicant 1 Litigation Friend", caseData.getApplicant1LitigationFriend())) - .applicant2LitigationFriend(CaseFlagUtils.updateLitFriend( - "Applicant 2 Litigation Friend", caseData.getApplicant2LitigationFriend())); + initialiseApplicantAndRespondentFlags(dataBuilder, caseData); break; } case ADD_DEFENDANT_LITIGATION_FRIEND: { - dataBuilder - .respondent1LitigationFriend( - CaseFlagUtils.updateLitFriend( - "Respondent 1 Litigation Friend", - caseData.getRespondent1LitigationFriend() - )) - .respondent2LitigationFriend( - CaseFlagUtils.updateLitFriend( - "Respondent 2 Litigation Friend", - caseData.getRespondent2LitigationFriend() - )); + initialiseRespondentLitigationFriendFlags(dataBuilder, caseData); break; } case DEFENDANT_RESPONSE_SPEC: @@ -59,7 +53,59 @@ public void initialiseCaseFlags(CaseEvent caseEvent, CaseData.CaseDataBuilder da addApplicantExpertAndWitnessFlagsStructure(dataBuilder, caseData); break; } + case MANAGE_CONTACT_INFORMATION: { + createOrUpdateFlags(dataBuilder, caseData, organisationService); + break; + } default: } } + + public void initialiseMissingCaseFlags(CaseData.CaseDataBuilder dataBuilder) { + CaseData caseData = dataBuilder.build(); + initialiseApplicantAndRespondentFlags(dataBuilder, caseData); + initialiseRespondentLitigationFriendFlags(dataBuilder, caseData); + if (shouldReinitialiseRespondentDQFlags(caseData)) { + addRespondentDQPartiesFlagStructure(dataBuilder, caseData); + } + if (shouldReinitialiseApplicantDQFlags(caseData)) { + addApplicantExpertAndWitnessFlagsStructure(dataBuilder, caseData); + } + } + + private void initialiseRespondentLitigationFriendFlags(CaseData.CaseDataBuilder dataBuilder, CaseData caseData) { + dataBuilder + .respondent1LitigationFriend( + CaseFlagUtils.updateLitFriend( + RESPONDENT_ONE_LITIGATION_FRIEND, + caseData.getRespondent1LitigationFriend() + )) + .respondent2LitigationFriend( + CaseFlagUtils.updateLitFriend( + RESPONDENT_TWO_LITIGATION_FRIEND, + caseData.getRespondent2LitigationFriend() + )); + } + + private void initialiseApplicantAndRespondentFlags(CaseData.CaseDataBuilder dataBuilder, CaseData caseData) { + dataBuilder + .applicant1(CaseFlagUtils.updateParty(APPLICANT_ONE, caseData.getApplicant1())) + .applicant2(CaseFlagUtils.updateParty(APPLICANT_TWO, caseData.getApplicant2())) + .respondent1(CaseFlagUtils.updateParty(RESPONDENT_ONE, caseData.getRespondent1())) + .respondent2(CaseFlagUtils.updateParty(RESPONDENT_TWO, caseData.getRespondent2())) + .applicant1LitigationFriend(CaseFlagUtils.updateLitFriend( + APPLICANT_ONE_LITIGATION_FRIEND, caseData.getApplicant1LitigationFriend())) + .applicant2LitigationFriend(CaseFlagUtils.updateLitFriend( + APPLICANT_TWO_LITIGATION_FRIEND, caseData.getApplicant2LitigationFriend())); + } + + private boolean shouldReinitialiseRespondentDQFlags(CaseData caseData) { + return caseData.getRespondent1Witnesses() == null || caseData.getRespondent1Experts() == null + || (YES.equals(caseData.getAddRespondent2()) + && (caseData.getRespondent2Experts() == null || caseData.getRespondent2Witnesses() == null)); + } + + private boolean shouldReinitialiseApplicantDQFlags(CaseData caseData) { + return caseData.getApplicantExperts() == null || caseData.getApplicantWitnesses() == null; + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/utils/CourtLocationUtils.java b/src/main/java/uk/gov/hmcts/reform/civil/utils/CourtLocationUtils.java index ac70c9b2442..d1fae17737c 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/utils/CourtLocationUtils.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/utils/CourtLocationUtils.java @@ -35,7 +35,7 @@ public LocationRefData findPreferredLocationData(final List loc return preferredLocation.orElse(null); } - private Boolean checkLocation(final LocationRefData location, String locationTempLabel) { + public Boolean checkLocation(final LocationRefData location, String locationTempLabel) { String locationLabel = location.getSiteName() + " - " + location.getCourtAddress() + " - " + location.getPostcode(); diff --git a/src/main/java/uk/gov/hmcts/reform/civil/utils/DocmosisTemplateDataUtils.java b/src/main/java/uk/gov/hmcts/reform/civil/utils/DocmosisTemplateDataUtils.java index bb535eaa203..bd9559f9772 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/utils/DocmosisTemplateDataUtils.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/utils/DocmosisTemplateDataUtils.java @@ -9,7 +9,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.Optional; import java.util.function.Function; import static java.lang.String.format; @@ -42,9 +41,11 @@ public static String fetchRespondentName(CaseData caseData) { respondentNameBuilder.append("1 "); respondentNameBuilder.append(caseData.getRespondent1().getPartyName()); soleTraderCompany(caseData.getRespondent1(), respondentNameBuilder); + litigationFriend(caseData.getRespondent1LitigationFriend(), respondentNameBuilder); respondentNameBuilder.append(" & 2 "); respondentNameBuilder.append(caseData.getRespondent2().getPartyName()); soleTraderCompany(caseData.getRespondent2(), respondentNameBuilder); + litigationFriend(caseData.getRespondent2LitigationFriend(), respondentNameBuilder); } else { respondentNameBuilder.append(caseData.getRespondent1().getPartyName()); soleTraderCompany(caseData.getRespondent1(), respondentNameBuilder); @@ -61,9 +62,11 @@ public static String fetchApplicantName(CaseData caseData) { applicantNameBuilder.append("1 "); applicantNameBuilder.append(caseData.getApplicant1().getPartyName()); soleTraderCompany(caseData.getApplicant1(), applicantNameBuilder); + litigationFriend(caseData.getApplicant1LitigationFriend(), applicantNameBuilder); applicantNameBuilder.append(" & 2 "); applicantNameBuilder.append(caseData.getApplicant2().getPartyName()); soleTraderCompany(caseData.getApplicant2(), applicantNameBuilder); + litigationFriend(caseData.getApplicant2LitigationFriend(), applicantNameBuilder); } else if (caseData.getApplicant1() != null) { applicantNameBuilder.append(caseData.getApplicant1().getPartyName()); soleTraderCompany(caseData.getApplicant1(), applicantNameBuilder); @@ -110,9 +113,10 @@ private static void soleTraderCompany(Party party, StringBuilder stringBuilder) } private static void litigationFriend(LitigationFriend litigationFriend, StringBuilder stringBuilder) { - Optional.ofNullable(litigationFriend) - .map(LitigationFriend::getFullName) - .ifPresent(fullName -> stringBuilder.append(format(" (proceeding by L/F %s)", fullName))); + if (litigationFriend != null) { + String fullName = litigationFriend.getFirstName() + " " + litigationFriend.getLastName(); + stringBuilder.append(format(" (proceeding by L/F %s)", fullName)); + } } public static SolicitorReferences fetchSolicitorReferencesMultiparty(CaseData caseData) { diff --git a/src/main/java/uk/gov/hmcts/reform/civil/utils/ElementUtils.java b/src/main/java/uk/gov/hmcts/reform/civil/utils/ElementUtils.java index 27b6406f0cb..35b83167282 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/utils/ElementUtils.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/utils/ElementUtils.java @@ -10,6 +10,7 @@ import java.util.Collections; import java.util.List; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import java.util.stream.Stream; @@ -45,6 +46,10 @@ public static List unwrapElements(List> elements) { .collect(toUnmodifiableList()); } + public static List unwrapElementsNullSafe(List> elements) { + return Optional.ofNullable(elements).map(ElementUtils::unwrapElements).orElse(Collections.emptyList()); + } + public static Element element(T element) { return Element.builder() .id(UUID.randomUUID()) diff --git a/src/main/java/uk/gov/hmcts/reform/civil/utils/HearingUtils.java b/src/main/java/uk/gov/hmcts/reform/civil/utils/HearingUtils.java index a9cb5203578..1782904a015 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/utils/HearingUtils.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/utils/HearingUtils.java @@ -51,7 +51,7 @@ public static String getHearingType(CaseData caseData) { case IN_PERSON: return caseData.getHearingLocation().getValue().getLabel(); case VIDEO: - return "videoconference"; + return "video conference"; case TELEPHONE: return "telephone"; default: diff --git a/src/main/java/uk/gov/hmcts/reform/civil/utils/JudicialReferralUtils.java b/src/main/java/uk/gov/hmcts/reform/civil/utils/JudicialReferralUtils.java new file mode 100644 index 00000000000..2df4c2c08f1 --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/utils/JudicialReferralUtils.java @@ -0,0 +1,58 @@ +package uk.gov.hmcts.reform.civil.utils; + +import uk.gov.hmcts.reform.civil.enums.AllocatedTrack; +import uk.gov.hmcts.reform.civil.enums.CaseCategory; +import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.model.CaseData; + +import static uk.gov.hmcts.reform.civil.enums.AllocatedTrack.getAllocatedTrack; +import static uk.gov.hmcts.reform.civil.enums.MultiPartyScenario.getMultiPartyScenario; +import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; + +public class JudicialReferralUtils { + + private JudicialReferralUtils() { + //NO-OP + } + + /** + * Computes whether the case data should move to judicial referral or not. + * + * @param caseData a case data such that defendants rejected the claim, and claimant(s) wants to proceed + * vs all the defendants + * @return true if and only if the case should move to judicial referral + */ + public static boolean shouldMoveToJudicialReferral(CaseData caseData) { + CaseCategory caseCategory = caseData.getCaseAccessCategory(); + + if (CaseCategory.SPEC_CLAIM.equals(caseCategory)) { + MultiPartyScenario multiPartyScenario = getMultiPartyScenario(caseData); + + return switch (multiPartyScenario) { + case ONE_V_ONE, ONE_V_TWO_ONE_LEGAL_REP, ONE_V_TWO_TWO_LEGAL_REP -> caseData.getApplicant1ProceedWithClaim() == YesOrNo.YES; + case TWO_V_ONE -> caseData.getApplicant1ProceedWithClaimSpec2v1() == YesOrNo.YES; + }; + } else { + AllocatedTrack allocatedTrack = + getAllocatedTrack( + CaseCategory.UNSPEC_CLAIM.equals(caseCategory) + ? caseData.getClaimValue().toPounds() + : caseData.getTotalClaimAmount(), + caseData.getClaimType() + ); + if (AllocatedTrack.MULTI_CLAIM.equals(allocatedTrack)) { + return false; + } + MultiPartyScenario multiPartyScenario = getMultiPartyScenario(caseData); + return switch (multiPartyScenario) { + case ONE_V_ONE -> caseData.getApplicant1ProceedWithClaim() == YesOrNo.YES; + case TWO_V_ONE -> caseData.getApplicant1ProceedWithClaimMultiParty2v1() == YES + && caseData.getApplicant2ProceedWithClaimMultiParty2v1() == YES; + case ONE_V_TWO_ONE_LEGAL_REP, ONE_V_TWO_TWO_LEGAL_REP -> + caseData.getApplicant1ProceedWithClaimAgainstRespondent1MultiParty1v2() == YES + && caseData.getApplicant1ProceedWithClaimAgainstRespondent2MultiParty1v2() == YES; + }; + } + } +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/utils/ManageContactInformationUtils.java b/src/main/java/uk/gov/hmcts/reform/civil/utils/ManageContactInformationUtils.java index 5967810fb19..83ff6136dd6 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/utils/ManageContactInformationUtils.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/utils/ManageContactInformationUtils.java @@ -2,16 +2,22 @@ import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.model.UpdatePartyDetailsForm; import uk.gov.hmcts.reform.civil.model.common.DynamicListElement; +import uk.gov.hmcts.reform.civil.model.common.Element; +import uk.gov.hmcts.reform.civil.model.dq.Expert; import uk.gov.hmcts.reform.civil.model.dq.Experts; +import uk.gov.hmcts.reform.civil.model.dq.Witness; import uk.gov.hmcts.reform.civil.model.dq.Witnesses; - +import java.time.LocalDate; +import java.util.ArrayList; import java.util.List; - import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; import static uk.gov.hmcts.reform.civil.model.Party.Type.COMPANY; import static uk.gov.hmcts.reform.civil.model.Party.Type.ORGANISATION; import static uk.gov.hmcts.reform.civil.model.common.DynamicListElement.dynamicElementFromCode; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.unwrapElements; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; public class ManageContactInformationUtils { @@ -34,30 +40,30 @@ private ManageContactInformationUtils() { private static final String ORG_INDIVIDUALS = "Individuals attending for the organisation"; private static final String LEGAL_REP_INDIVIDUALS = "Individuals attending for the legal representative"; - private static final String CLAIMANT_ONE_ID = "CLAIMANT_1"; - private static final String CLAIMANT_ONE_LITIGATION_FRIEND_ID = "CLAIMANT_1_LITIGATIONFRIEND"; - private static final String CLAIMANT_ONE_LEGAL_REP_INDIVIDUALS_ID = "CLAIMANT_1_INDIVIDUALSSOLICITORORG"; - private static final String CLAIMANT_ONE_ORG_INDIVIDUALS_ID = "CLAIMANT_1_INDIVIDUALSORG"; - private static final String CLAIMANT_ONE_WITNESSES_ID = "CLAIMANT_1_WITNESSES"; - private static final String CLAIMANT_ONE_EXPERTS_ID = "CLAIMANT_1_EXPERTS"; - - private static final String CLAIMANT_TWO_ID = "CLAIMANT_2"; - private static final String CLAIMANT_TWO_LITIGATION_FRIEND_ID = "CLAIMANT_2_LITIGATIONFRIEND"; - private static final String CLAIMANT_TWO_ORG_INDIVIDUALS_ID = "CLAIMANT_1_INDIVIDUALSORG"; - - private static final String DEFENDANT_ONE_ID = "DEFENDANT_1"; - private static final String DEFENDANT_ONE_LITIGATION_FRIEND_ID = "DEFENDANT_1_LITIGATIONFRIEND"; - private static final String DEFENDANT_ONE_LEGAL_REP_INDIVIDUALS_ID = "DEFENDANT_1_INDIVIDUALSSOLICITORORG"; - private static final String DEFENDANT_ONE_ORG_INDIVIDUALS_ID = "DEFENDANT_1_INDIVIDUALSORG"; - private static final String DEFENDANT_ONE_WITNESSES_ID = "DEFENDANT_1_WITNESSES"; - private static final String DEFENDANT_ONE_EXPERTS_ID = "DEFENDANT_1_EXPERTS"; - - private static final String DEFENDANT_TWO_ID = "DEFENDANT_2"; - private static final String DEFENDANT_TWO_LITIGATION_FRIEND_ID = "DEFENDANT_2_LITIGATIONFRIEND"; - private static final String DEFENDANT_TWO_LEGAL_REP_INDIVIDUALS_ID = "DEFENDANT_2_INDIVIDUALSSOLICITORORG"; - private static final String DEFENDANT_TWO_ORG_INDIVIDUALS_ID = "DEFENDANT_2_INDIVIDUALSORG"; - private static final String DEFENDANT_TWO_WITNESSES_ID = "DEFENDANT_2_WITNESSES"; - private static final String DEFENDANT_TWO_EXPERTS_ID = "DEFENDANT_2_EXPERTS"; + public static final String CLAIMANT_ONE_ID = "CLAIMANT_1"; + public static final String CLAIMANT_ONE_LITIGATION_FRIEND_ID = "CLAIMANT_1_LITIGATION_FRIEND"; + public static final String CLAIMANT_ONE_LEGAL_REP_INDIVIDUALS_ID = "CLAIMANT_1_LR_INDIVIDUALS"; + public static final String CLAIMANT_ONE_ORG_INDIVIDUALS_ID = "CLAIMANT_1_ORGANISATION_INDIVIDUALS"; + public static final String CLAIMANT_ONE_WITNESSES_ID = "CLAIMANT_1_WITNESSES"; + public static final String CLAIMANT_ONE_EXPERTS_ID = "CLAIMANT_1_EXPERTS"; + + public static final String CLAIMANT_TWO_ID = "CLAIMANT_2"; + public static final String CLAIMANT_TWO_LITIGATION_FRIEND_ID = "CLAIMANT_2_LITIGATION_FRIEND"; + public static final String CLAIMANT_TWO_ORG_INDIVIDUALS_ID = "CLAIMANT_2_ORGANISATION_INDIVIDUALS"; + + public static final String DEFENDANT_ONE_ID = "DEFENDANT_1"; + public static final String DEFENDANT_ONE_LITIGATION_FRIEND_ID = "DEFENDANT_1_LITIGATION_FRIEND"; + public static final String DEFENDANT_ONE_LEGAL_REP_INDIVIDUALS_ID = "DEFENDANT_1_LR_INDIVIDUALS"; + public static final String DEFENDANT_ONE_ORG_INDIVIDUALS_ID = "DEFENDANT_1_ORGANISATION_INDIVIDUALS"; + public static final String DEFENDANT_ONE_WITNESSES_ID = "DEFENDANT_1_WITNESSES"; + public static final String DEFENDANT_ONE_EXPERTS_ID = "DEFENDANT_1_EXPERTS"; + + public static final String DEFENDANT_TWO_ID = "DEFENDANT_2"; + public static final String DEFENDANT_TWO_LITIGATION_FRIEND_ID = "DEFENDANT_2_LITIGATION_FRIEND"; + public static final String DEFENDANT_TWO_LEGAL_REP_INDIVIDUALS_ID = "DEFENDANT_2_LR_INDIVIDUALS"; + public static final String DEFENDANT_TWO_ORG_INDIVIDUALS_ID = "DEFENDANT_2_ORGANISATION_INDIVIDUALS"; + public static final String DEFENDANT_TWO_WITNESSES_ID = "DEFENDANT_2_WITNESSES"; + public static final String DEFENDANT_TWO_EXPERTS_ID = "DEFENDANT_2_EXPERTS"; public static void addApplicant1Options(List list, CaseData caseData, boolean isAdmin) { addApplicant1PartyOptions(list, caseData); @@ -95,6 +101,178 @@ public static void addDefendant2Options(List list, CaseData addDefendant2ExpertsAndWitnesses(list, caseData, isAdmin); } + public static String appendUserAndType(String partyChosen, CaseData caseData, boolean isAdmin) { + String user = isAdmin ? "ADMIN" : "LR"; + + switch (partyChosen) { + case (CLAIMANT_ONE_ID): { + return formatId(partyChosen, user, caseData.getApplicant1()); + } + case(CLAIMANT_TWO_ID): { + return formatId(partyChosen, user, caseData.getApplicant2()); + } + case (DEFENDANT_ONE_ID): { + return formatId(partyChosen, user, caseData.getRespondent1()); + } + case(DEFENDANT_TWO_ID): { + return formatId(partyChosen, user, caseData.getRespondent2()); + } + case(CLAIMANT_ONE_LITIGATION_FRIEND_ID): + case(CLAIMANT_TWO_LITIGATION_FRIEND_ID): + case(DEFENDANT_ONE_LITIGATION_FRIEND_ID): + case(DEFENDANT_TWO_LITIGATION_FRIEND_ID): { + return formatId(partyChosen, user); + } + default: { + throw new IllegalArgumentException("Manage Contact Information party chosen ID does not exist"); + } + } + } + + public static List> mapExpertsToUpdatePartyDetailsForm(List> experts) { + List> newExperts = new ArrayList<>(); + + if (experts != null) { + for (Element party : experts) { + Expert expert = party.getValue(); + newExperts.addAll(wrapElements(UpdatePartyDetailsForm.builder() + .firstName(expert.getFirstName()) + .lastName(expert.getLastName()) + .emailAddress(expert.getEmailAddress()) + .phoneNumber(expert.getPhoneNumber()) + .fieldOfExpertise(expert.getFieldOfExpertise()) + .partyId(expert.getPartyID()) //this will need to be added in new ticket + .build())); + } + } + return newExperts; + } + + public static List> mapUpdatePartyDetailsFormToDQExperts(List> existingDQExperts, List> formExperts) { + List> newExperts = new ArrayList<>(); + List experts = unwrapElements(existingDQExperts); + + if (formExperts != null) { + for (Element form : formExperts) { + UpdatePartyDetailsForm formExpert = form.getValue(); + + Expert dqExpert = experts.stream() + .filter(e -> e.getPartyID().equals(formExpert.getPartyId())) + .findFirst() + .orElse(null); + + if (dqExpert != null && dqExpert.getPartyID() != null) { + // if id already exists in dq + newExperts.addAll(wrapElements(dqExpert.toBuilder() + .firstName(formExpert.getFirstName()) + .lastName(formExpert.getLastName()) + .emailAddress(formExpert.getEmailAddress()) + .phoneNumber(formExpert.getPhoneNumber()) + .fieldOfExpertise(formExpert.getFieldOfExpertise()) + .build())); + } else { + // if id doesn't exist in dq means it is a newly added expert + newExperts.addAll(wrapElements(Expert.builder() + .firstName(formExpert.getFirstName()) + .lastName(formExpert.getLastName()) + .emailAddress(formExpert.getEmailAddress()) + .phoneNumber(formExpert.getPhoneNumber()) + .fieldOfExpertise(formExpert.getFieldOfExpertise()) + .dateAdded(LocalDate.now()) + .eventAdded("Manage Contact Information Event") + .partyID(null) //CIV-10382 + .build())); + // Replace above to this in CIV-10382 + // newExperts.addAll(wrapElements(appendWithNewPartyIds(Expert.builder() + // .firstName(formExpert.getFirstName()) + // .lastName(formExpert.getLastName()) + // .emailAddress(formExpert.getEmailAddress()) + // .phoneNumber(formExpert.getPhoneNumber()) + // .fieldOfExpertise(formExpert.getFieldOfExpertise()) + // .dateAdded(LocalDate.now()) + // .eventAdded("Manage Contact Information Event") + // .build()))); + } + } + } + + return newExperts; + } + + public static List> mapWitnessesToUpdatePartyDetailsForm(List> witnesses) { + List> newWitnesses = new ArrayList<>(); + + if (witnesses != null) { + for (Element party : witnesses) { + Witness witness = party.getValue(); + newWitnesses.addAll(wrapElements(UpdatePartyDetailsForm.builder() + .firstName(witness.getFirstName()) + .lastName(witness.getLastName()) + .emailAddress(witness.getEmailAddress()) + .phoneNumber(witness.getPhoneNumber()) + .partyId(witness.getPartyID()) + .build())); + } + } + return newWitnesses; + } + + public static List> mapUpdatePartyDetailsFormToDQWitnesses(List> existingDQWitnesses, List> formWitnesses) { + List> newWitnesses = new ArrayList<>(); + List witnesses = unwrapElements(existingDQWitnesses); + + if (formWitnesses != null) { + for (Element form : formWitnesses) { + UpdatePartyDetailsForm formWitness = form.getValue(); + + Witness dqWitness = witnesses.stream() + .filter(w -> w.getPartyID().equals(formWitness.getPartyId())) + .findFirst() + .orElse(null); + + // if id already exists in dq + if (dqWitness != null && dqWitness.getPartyID() != null) { + newWitnesses.addAll(wrapElements(dqWitness.toBuilder() + .firstName(formWitness.getFirstName()) + .lastName(formWitness.getLastName()) + .emailAddress(formWitness.getEmailAddress()) + .phoneNumber(formWitness.getPhoneNumber()) + .build())); + } else { + // if id doesn't exist in dq means it is a newly added witness + newWitnesses.addAll(wrapElements(Witness.builder() + .firstName(formWitness.getFirstName()) + .lastName(formWitness.getLastName()) + .emailAddress(formWitness.getEmailAddress()) + .phoneNumber(formWitness.getPhoneNumber()) + .dateAdded(LocalDate.now()) + .eventAdded("Manage Contact Information Event") + .partyID(null) //CIV-10382 + .build())); + // Replace above to this in CIV-10382 + // newWitnesses.addAll(wrapElements(appendWithNewPartyIds(Witness.builder() + // .firstName(formWitness.getFirstName()) + // .lastName(formWitness.getLastName()) + // .emailAddress(formWitness.getEmailAddress()) + // .phoneNumber(formWitness.getPhoneNumber()) + // .dateAdded(LocalDate.now()) + // .eventAdded("Manage Contact Information Event") + // .build()))); + } + } + } + + return newWitnesses; + } + + private static String formatId(String partyChosen, String isAdmin, Party party) { + return String.format("%s_%s_%s", partyChosen, isAdmin, party.getType().toString()); + } + + private static String formatId(String partyChosen, String isAdmin) { + return String.format("%s_%s", partyChosen, isAdmin); + } + private static void addApplicant1PartyOptions(List list, CaseData caseData) { // applicant 1 party name list.add(dynamicElementFromCode(CLAIMANT_ONE_ID, diff --git a/src/main/java/uk/gov/hmcts/reform/civil/utils/PartyUtils.java b/src/main/java/uk/gov/hmcts/reform/civil/utils/PartyUtils.java index bfe9ffc4812..2da2a2861dd 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/utils/PartyUtils.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/utils/PartyUtils.java @@ -11,6 +11,15 @@ import uk.gov.hmcts.reform.civil.model.PartyFlagStructure; import uk.gov.hmcts.reform.civil.model.SolicitorReferences; import uk.gov.hmcts.reform.civil.model.common.Element; +import uk.gov.hmcts.reform.civil.model.dq.Applicant1DQ; +import uk.gov.hmcts.reform.civil.model.dq.Applicant2DQ; +import uk.gov.hmcts.reform.civil.model.dq.Expert; +import uk.gov.hmcts.reform.civil.model.dq.ExpertDetails; +import uk.gov.hmcts.reform.civil.model.dq.Experts; +import uk.gov.hmcts.reform.civil.model.dq.Respondent1DQ; +import uk.gov.hmcts.reform.civil.model.dq.Respondent2DQ; +import uk.gov.hmcts.reform.civil.model.dq.Witness; +import uk.gov.hmcts.reform.civil.model.dq.Witnesses; import java.time.LocalDate; import java.util.List; @@ -27,6 +36,8 @@ import static uk.gov.hmcts.reform.civil.enums.PartyRole.RESPONDENT_TWO; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.unwrapElements; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; public class PartyUtils { @@ -78,7 +89,7 @@ public static String getLitigiousPartyName(Party party, LitigationFriend litigat return party.getOrganisationName(); case INDIVIDUAL: return ofNullable(litigationFriend) - .map(lf -> getIndividualName(party) + " L/F " + lf.getFullName()) + .map(lf -> getIndividualName(party) + " L/F " + lf.getFirstName() + " " + lf.getLastName()) .orElse(getIndividualName(party)); case SOLE_TRADER: return ofNullable(party.getSoleTraderTradingAs()) @@ -366,6 +377,81 @@ public static List> appendWithNewPartyIds(List appendWithNewPartyIds(expert)).collect(Collectors.toList()))).build(); + } + + public static Witness appendWithNewPartyIds(Witness witness) { + return witness != null && witness.getPartyID() == null ? witness.toBuilder().partyID(createPartyId()).build() : witness; + } + + public static Witnesses appendWithNewPartyIds(Witnesses witnesses) { + if (witnesses == null || witnesses.getDetails() == null) { + return witnesses; + } + + return witnesses.toBuilder().details( + wrapElements(unwrapElements( + witnesses.getDetails()).stream().map( + witness -> appendWithNewPartyIds(witness)).collect(Collectors.toList()))).build(); + } + + public static Applicant1DQ appendWithNewPartyIds(Applicant1DQ applicant1DQ) { + return applicant1DQ != null ? applicant1DQ.toBuilder() + .applicant1DQExperts(appendWithNewPartyIds(applicant1DQ.getApplicant1DQExperts())) + .applicant1RespondToClaimExperts(appendWithNewPartyIds(applicant1DQ.getApplicant1RespondToClaimExperts())) + .applicant1DQWitnesses(appendWithNewPartyIds(applicant1DQ.getApplicant1DQWitnesses())) + .build() : null; + } + + public static Applicant2DQ appendWithNewPartyIds(Applicant2DQ applicant2DQ) { + return applicant2DQ != null ? applicant2DQ.toBuilder() + .applicant2DQExperts(appendWithNewPartyIds(applicant2DQ.getApplicant2DQExperts())) + .applicant2RespondToClaimExperts(appendWithNewPartyIds(applicant2DQ.getApplicant2RespondToClaimExperts())) + .applicant2DQWitnesses(appendWithNewPartyIds(applicant2DQ.getApplicant2DQWitnesses())) + .build() : null; + } + + public static Respondent1DQ appendWithNewPartyIds(Respondent1DQ respondent1DQ) { + return respondent1DQ != null ? respondent1DQ.toBuilder() + .respondent1DQExperts(appendWithNewPartyIds(respondent1DQ.getRespondent1DQExperts())) + .respondToClaimExperts(appendWithNewPartyIds(respondent1DQ.getRespondToClaimExperts())) + .respondent1DQWitnesses(appendWithNewPartyIds(respondent1DQ.getRespondent1DQWitnesses())) + .build() : null; + } + + public static Respondent2DQ appendWithNewPartyIds(Respondent2DQ respondent2DQ) { + return respondent2DQ != null ? respondent2DQ.toBuilder() + .respondent2DQExperts(appendWithNewPartyIds(respondent2DQ.getRespondent2DQExperts())) + .respondToClaimExperts2(appendWithNewPartyIds(respondent2DQ.getRespondToClaimExperts2())) + .respondent2DQWitnesses(appendWithNewPartyIds(respondent2DQ.getRespondent2DQWitnesses())) + .build() : null; + } + + public static void populateDQPartyIds(CaseData.CaseDataBuilder builder) { + CaseData caseData = builder.build(); + builder + .applicant1DQ(appendWithNewPartyIds(caseData.getApplicant1DQ())) + .applicant2DQ(appendWithNewPartyIds(caseData.getApplicant2DQ())) + .respondent1DQ(appendWithNewPartyIds(caseData.getRespondent1DQ())) + .respondent2DQ(appendWithNewPartyIds(caseData.getRespondent2DQ())); + } + @SuppressWarnings("unchecked") public static void populateWithPartyIds(CaseData.CaseDataBuilder builder) { CaseData caseData = builder.build(); @@ -377,12 +463,6 @@ public static void populateWithPartyIds(CaseData.CaseDataBuilder builder) { .applicant1LitigationFriend(appendWithNewPartyId(caseData.getApplicant1LitigationFriend())) .applicant2LitigationFriend(appendWithNewPartyId(caseData.getApplicant2LitigationFriend())) .respondent1LitigationFriend(appendWithNewPartyId(caseData.getRespondent1LitigationFriend())) - .respondent2LitigationFriend(appendWithNewPartyId(caseData.getRespondent2LitigationFriend())) - .applicantExperts(appendWithNewPartyIds(caseData.getApplicantExperts())) - .respondent1Experts(appendWithNewPartyIds(caseData.getRespondent1Experts())) - .respondent2Experts(appendWithNewPartyIds(caseData.getRespondent2Experts())) - .applicantWitnesses(appendWithNewPartyIds(caseData.getApplicantWitnesses())) - .respondent1Witnesses(appendWithNewPartyIds(caseData.getRespondent1Witnesses())) - .respondent2Witnesses(appendWithNewPartyIds(caseData.getRespondent2Witnesses())); + .respondent2LitigationFriend(appendWithNewPartyId(caseData.getRespondent2LitigationFriend())); } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/utils/PaymentFrequencyCalculator.java b/src/main/java/uk/gov/hmcts/reform/civil/utils/PaymentFrequencyCalculator.java new file mode 100644 index 00000000000..7900125b23a --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/utils/PaymentFrequencyCalculator.java @@ -0,0 +1,47 @@ +package uk.gov.hmcts.reform.civil.utils; + +import uk.gov.hmcts.reform.civil.enums.PaymentFrequencyLRspec; + +public class PaymentFrequencyCalculator { + + private static final int NUMBER_OF_WORKING_WEEKS_IN_A_YEAR = 52; + private static final int NUMBER_OF_MONTHS_IN_A_YEAR = 12; + + private PaymentFrequencyCalculator() { + + } + + public static double calculatePaymentPerMonth(double amount, PaymentFrequencyLRspec paymentFrequencyLRspec) { + switch (paymentFrequencyLRspec) { + case ONCE_FOUR_WEEKS -> { + return calculateWeeklyPaymentIntoMonthly(4, amount); + } + case ONCE_THREE_WEEKS -> { + return calculateWeeklyPaymentIntoMonthly(3, amount); + } + case ONCE_TWO_WEEKS -> { + return calculateWeeklyPaymentIntoMonthly(2, amount); + } + case ONCE_ONE_WEEK -> { + return calculateWeeklyPaymentIntoMonthly(amount); + } + default -> { + return amount; + } + } + } + + public static double calculateWeeklyPaymentIntoMonthly(int weeks, double amount) { + double amountPerWeek = calculatePaymentPerWeek(weeks, amount); + return calculateWeeklyPaymentIntoMonthly(amountPerWeek); + } + + public static double calculateWeeklyPaymentIntoMonthly(double amount) { + return Math.round(amount * NUMBER_OF_WORKING_WEEKS_IN_A_YEAR / NUMBER_OF_MONTHS_IN_A_YEAR); + } + + private static double calculatePaymentPerWeek(int weeks, double amount) { + return amount / weeks; + } + +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/utils/UnavailabilityDatesUtils.java b/src/main/java/uk/gov/hmcts/reform/civil/utils/UnavailabilityDatesUtils.java index fb06f4e944a..81a5e845f2e 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/utils/UnavailabilityDatesUtils.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/utils/UnavailabilityDatesUtils.java @@ -76,7 +76,7 @@ public static void rollUpUnavailabilityDatesForRespondent(CaseData.CaseDataBuild .getUnavailableDates(); List> updatedUnavailableDates = addEventAndDate( - caseData.getRespondent1ResponseDate().toLocalDate(), + caseData.getRespondent2ResponseDate().toLocalDate(), DEFENDANT_RESPONSE_EVENT, respondent2DQUnavailableDates ); @@ -344,4 +344,35 @@ private static void copyDatesIntoListingTabFieldsForRespondent2(CaseData caseDat .respondent2(caseData.getRespondent2().toBuilder().unavailableDates(dates).build()) .respondent2UnavailableDatesForTab(dates); } + + public static void updateMissingUnavailableDatesForApplicants(CaseData caseData, CaseData.CaseDataBuilder builder, + boolean updateDetailsEnabled) { + if (isClaimantIntentionEvent(caseData)) { + rollUpUnavailabilityDatesForApplicant(builder, updateDetailsEnabled); + } else { + rollUpUnavailabilityDatesForApplicantDJ(builder, updateDetailsEnabled); + } + } + + public static boolean shouldUpdateApplicant1UnavailableDates(CaseData caseData) { + return caseData.getApplicant1().getUnavailableDates() != null + && caseData.getApplicant1().getUnavailableDates().get(0).getValue().getDateAdded() == null; + } + + public static boolean shouldUpdateApplicant2UnavailableDates(CaseData caseData) { + return caseData.getApplicant2() != null + && caseData.getApplicant2().getUnavailableDates() != null + && caseData.getApplicant2().getUnavailableDates().get(0).getValue().getDateAdded() == null; + } + + public static boolean shouldUpdateRespondent1UnavailableDates(CaseData caseData) { + return caseData.getRespondent1().getUnavailableDates() != null + && caseData.getRespondent1().getUnavailableDates().get(0).getValue().getDateAdded() == null; + } + + public static boolean shouldUpdateRespondent2UnavailableDates(CaseData caseData) { + return caseData.getRespondent2() != null + && caseData.getRespondent2().getUnavailableDates() != null + && caseData.getRespondent2().getUnavailableDates().get(0).getValue().getDateAdded() == null; + } } diff --git a/src/main/java/uk/gov/hmcts/reform/civil/utils/UserRoleCaching.java b/src/main/java/uk/gov/hmcts/reform/civil/utils/UserRoleCaching.java new file mode 100644 index 00000000000..3f5a4898b5c --- /dev/null +++ b/src/main/java/uk/gov/hmcts/reform/civil/utils/UserRoleCaching.java @@ -0,0 +1,25 @@ +package uk.gov.hmcts.reform.civil.utils; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.civil.service.CoreCaseUserService; +import uk.gov.hmcts.reform.civil.service.UserService; +import uk.gov.hmcts.reform.idam.client.models.UserInfo; + +import java.util.List; + +@Service +@RequiredArgsConstructor +@Slf4j +public class UserRoleCaching { + + private final UserService userService; + private final CoreCaseUserService coreCaseUserService; + + public List getUserRoles(String bearerToken, String ccdCaseRef) { + UserInfo userInfo = userService.getUserInfo(bearerToken); + return coreCaseUserService.getUserCaseRoles(ccdCaseRef, userInfo.getUid()); + } + +} diff --git a/src/main/java/uk/gov/hmcts/reform/civil/utils/UserRoleUtils.java b/src/main/java/uk/gov/hmcts/reform/civil/utils/UserRoleUtils.java index 1dd5fa1e4fc..4d5d21219aa 100644 --- a/src/main/java/uk/gov/hmcts/reform/civil/utils/UserRoleUtils.java +++ b/src/main/java/uk/gov/hmcts/reform/civil/utils/UserRoleUtils.java @@ -1,10 +1,11 @@ package uk.gov.hmcts.reform.civil.utils; import uk.gov.hmcts.reform.civil.enums.CaseRole; - import java.util.List; import static uk.gov.hmcts.reform.civil.enums.CaseRole.APPLICANTSOLICITORONE; +import static uk.gov.hmcts.reform.civil.enums.CaseRole.CLAIMANT; +import static uk.gov.hmcts.reform.civil.enums.CaseRole.DEFENDANT; import static uk.gov.hmcts.reform.civil.enums.CaseRole.RESPONDENTSOLICITORONE; import static uk.gov.hmcts.reform.civil.enums.CaseRole.RESPONDENTSOLICITORTWO; @@ -26,7 +27,16 @@ public static boolean isRespondentSolicitorTwo(List roles) { return hasRole(roles, RESPONDENTSOLICITORTWO); } + public static boolean isLIPClaimant(List roles) { + return hasRole(roles, CLAIMANT); + } + + public static boolean isLIPDefendant(List roles) { + return hasRole(roles, DEFENDANT); + } + private static boolean hasRole(List roles, CaseRole role) { return roles.stream().anyMatch(role.getFormattedName()::contains); } + } diff --git a/src/main/java/uk/gov/hmcts/reform/cmc/model/CmcClaim.java b/src/main/java/uk/gov/hmcts/reform/cmc/model/CmcClaim.java index 0d054f748f0..e3b80c94597 100644 --- a/src/main/java/uk/gov/hmcts/reform/cmc/model/CmcClaim.java +++ b/src/main/java/uk/gov/hmcts/reform/cmc/model/CmcClaim.java @@ -394,4 +394,9 @@ public boolean isPartialAdmissionRejected() { && Objects.nonNull(claimantResponse) && claimantResponse.getType().equals(ClaimantResponseType.REJECTION); } + + @Override + public boolean isClaimantDefaultJudgement() { + return false; + } } diff --git a/src/main/java/uk/gov/hmcts/reform/fees/client/FeesClient.java b/src/main/java/uk/gov/hmcts/reform/fees/client/FeesClient.java index 36e094d7b91..16e29cf716e 100644 --- a/src/main/java/uk/gov/hmcts/reform/fees/client/FeesClient.java +++ b/src/main/java/uk/gov/hmcts/reform/fees/client/FeesClient.java @@ -4,6 +4,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Service; +import uk.gov.hmcts.reform.civil.enums.AllocatedTrack; import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.fees.client.model.Fee2Dto; import uk.gov.hmcts.reform.fees.client.model.FeeLookupResponseDto; @@ -15,10 +16,17 @@ public class FeesClient { + public static final String EVENT_ISSUE = "issue"; + public static final String EVENT_HEARING = "hearing"; + public static final String FAST_TRACK_HEARING = "FastTrackHrg"; + public static final String HEARING_SMALL_CLAIMS = "HearingSmallClaims"; + public static final String MONEY_CLAIM = "MoneyClaim"; + private final FeesApi feesApi; private final String service; private final String jurisdiction1; private final String jurisdiction2; + private final String jurisdictionFastTrackClaim; private final FeatureToggleService featureToggleService; @Autowired @@ -27,22 +35,42 @@ public FeesClient( FeatureToggleService featureToggleService, @Value("${fees.api.service:}") String service, @Value("${fees.api.jurisdiction1:}") String jurisdiction1, - @Value("${fees.api.jurisdiction2:}") String jurisdiction2 + @Value("${fees.api.jurisdiction2:}") String jurisdiction2, + @Value("${fees.api.jurisdiction-fast-track-claim:}") String jurisdictionFastTrackClaim ) { this.feesApi = feesApi; this.service = service; this.jurisdiction1 = jurisdiction1; this.jurisdiction2 = jurisdiction2; + this.jurisdictionFastTrackClaim = jurisdictionFastTrackClaim; this.featureToggleService = featureToggleService; } public FeeLookupResponseDto lookupFee(String channel, String event, BigDecimal amount) { - String keyword = event.equalsIgnoreCase("issue") - ? "MoneyClaim" - : "HearingSmallClaims"; - if (featureToggleService.isFeatureEnabled("fee-keywords-enable")) { - return this.feesApi.lookupFee(service, jurisdiction1, jurisdiction2, channel, event, keyword, amount); + String keyword; + String jurisdiction2; + + if (featureToggleService.isLipVLipEnabled() && isFastTrackClaimAndHearingEvent(amount, event)) { + keyword = FAST_TRACK_HEARING; + jurisdiction2 = this.jurisdictionFastTrackClaim; + } else { + keyword = EVENT_ISSUE.equalsIgnoreCase(event) + ? MONEY_CLAIM + : HEARING_SMALL_CLAIMS; + jurisdiction2 = this.jurisdiction2; + } + + return this.feesApi.lookupFee( + service, + jurisdiction1, + jurisdiction2, + channel, + event, + keyword, + amount + ); + } else { return this.feesApi.lookupFeeWithoutKeyword(service, jurisdiction1, jurisdiction2, channel, event, amount); } @@ -51,4 +79,19 @@ public FeeLookupResponseDto lookupFee(String channel, String event, BigDecimal a public Fee2Dto[] findRangeGroup(String channel, String event) { return this.feesApi.findRangeGroup(service, jurisdiction1, jurisdiction2, channel, event); } + + /** + * Returns true if given amount fall under fast track claim and event is hearing. + * + * @param amount - Claim amount + * @param event - Claim event + * @return boolean + */ + private boolean isFastTrackClaimAndHearingEvent(BigDecimal amount, String event) { + + return EVENT_HEARING.equalsIgnoreCase(event) && AllocatedTrack.FAST_CLAIM == AllocatedTrack.getAllocatedTrack( + amount, + null + ); + } } diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 69e4a9cc4c0..187c0e2b2f9 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -70,6 +70,8 @@ serviceRequestClaimIssued: site_id: AAA7 service: CIVIL +wa: + feature-toggle: ${WA_TOGGLE:Prod} send-letter: url: ${SEND_LETTER_URL:http://localhost:8765} @@ -79,6 +81,7 @@ fees: service: civil money claims jurisdiction1: civil jurisdiction2: county court + jurisdiction-fast-track-claim: civil channel: default event: issue hearingEvent: hearing @@ -212,9 +215,12 @@ notifications: claimantSolicitorDefendantResponseForSpec: "28ea1d53-93b1-4e48-a7e5-7a876f910f86" claimantSolicitorImmediatelyDefendantResponseForSpec: "263d7737-933d-4d0b-9f08-23847613f6a4" respondentSolicitorDefendantResponseForSpec: "9527f77e-b346-4527-b93c-c2affd39fa51" + respondentSolicitorDefResponseSpecWithClaimantAction: "efbd38e8-3fe7-4db6-ad55-b751b96477b1" respondentDefendantResponseForSpec: "94c71894-9590-4995-aae0-edea94fc4594" sdoOrdered: "90667080-6b20-48f2-b9ea-349fa8ec78e4" sdoOrderedSpec: "1c1a200c-b3c1-45eb-9768-aeea56857420" + sdoOrderedEA: "837d3f5e-e1f8-4d6b-b053-719392fe556c" + sdoOrderedSpecEA: "7224780e-416c-4c0b-a718-056cd93abe06" sdoOrderedSpecBilingual: "0ae860e7-80b5-46f8-95b7-8f19d6f974cf" claimantSolicitorConfirmsNotToProceedSpec: "156b71f5-30ac-4398-aad2-72dfd424c6f2" claimantSolicitorConfirmsNotToProceedSpecLip: "25988b85-dafc-40be-970f-45fbb7d0f860" @@ -223,6 +229,8 @@ notifications: respondentSolicitorNotifyNotToProceedSpec: "4dc0b5bb-674f-401e-8a39-05686dc0302e" claimantSolicitorConfirmsToProceedSpec: "99786d26-ab90-43c7-aa20-9d450d8ce4eb" respondentSolicitorNotifyToProceedSpec: "ea6cb18e-ebba-4759-8df3-426e00f2f09c" + claimantSolicitorConfirmsToProceedSpecWithAction: "d454e5a9-8c56-4a1d-acce-53a1686376bc" + respondentSolicitorNotifyToProceedSpecWithAction: "c1bb435e-0300-4e51-89ec-56dd7f77ef27" applicantSolicitor1DefaultJudgmentReceived: "14a43ad4-e337-490a-bf8b-1288520dc9eb" claimantSolicitorCounterClaimForSpec: "256b6cf4-6201-48f0-bf1e-88a187712196" respondentSolicitorCounterClaimForSpec: "6cb3b3d5-f1aa-4236-ad03-685605a9235e" @@ -238,6 +246,7 @@ notifications: respondentDeadlineExtension: "13514e8a-8621-4d3a-a317-8fd0ba7a184f" respondentDeadlineExtensionWelsh: "5fb6d574-e1b8-42bc-9d97-fcd8042f36d3" claimantDeadlineExtension: "74e33576-487f-4c63-bdef-fe12c4279faa" + claimantLipDeadlineExtension: "77cc47b1-4a9a-4baf-9313-98542698d32a" respondentChangeOfAddressNotificationTemplate: "174a9566-6ce2-4df5-9ffd-265bbd4787cc" respondentLipFullAdmitOrPartAdmitTemplate: "d41a95de-ab84-4442-b6d1-33db03b5e1b0" respondentLipFullDefenceWithMediationTemplate: "2177f3b0-3833-4788-bd7f-a473e32950af" @@ -265,7 +274,8 @@ notifications: bundleCreationTemplate: "0280b3c7-ad4e-4c43-8974-72b5a5501b02" generateOrderNotificationTemplate: "78532d45-aadf-4223-89fd-4932b4cbe411" - notifyClaimantLrTemplate: "2d86f90b-95e8-4592-af88-06ae7936cc57" + notifyClaimantLrTemplate: "adcf4c5f-2b9c-482d-8311-a4b8ffe7ef45" + notifyDefendantLrTemplate: "2d86f90b-95e8-4592-af88-06ae7936cc57" notifyDefendantLipTemplate: "d40a8b04-b226-4232-a881-f7249a61d038" notifyDefendantLipWelshTemplate : "d63b744a-97c8-42bd-95a2-3d86dd703c3d" @@ -274,8 +284,11 @@ notifications: notifyRespondentLiPMediationAgreementTemplateWelsh: "07a98d47-91a3-4806-a6e2-9e75366556af" notifyRespondentLRMediationAgreementTemplate: "998d0355-7aa8-4bd3-87b2-537eb31c9db5" respondentLipPartAdmitSettleClaimTemplate: "81745979-5330-4771-816c-aa78085e741a" + respondentLrPartAdmitSettleClaimTemplate: "6a1f4ef9-5334-4f2c-9e43-b292753929fb" respondent1DefaultJudgmentRequestedTemplate: "d4cf381f-a2b3-4a81-a442-eb2aa5deb210" respondent1LipClaimUpdatedTemplate: "9c44f3fb-a340-49e5-bf64-32a3187d7dcd" + claimantLipClaimUpdatedTemplate: "0abdcb29-edd3-418a-aeab-a102da4ad441" + applicantLiPDefaultJudgmentRequested: "668d4703-e97f-4e2f-8d07-1a697aac6d0b" hearingFeeUnpaidNoc: "cb4e6c4f-bb4a-4b1b-a7ed-dad68af4f0a1" @@ -296,9 +309,16 @@ notifications: hearingNotificationLipDefendantTemplate: "9239a55e-fd08-4f03-9ba5-7d90ac35af41" + notifyLiPClaimantClaimSubmittedAndPayClaimFeeTemplate: "3d302844-ecdc-47e6-8aed-971c3f42a059" notifyLiPClaimantDefendantResponded: "4b1325dd-51ed-4dc2-bcc6-d9afb01a3f29" notifyLiPClaimantDefendantChangedContactDetails: "72a14146-c897-4fc6-be4f-474266da7398" + notifyApplicant1EnteredBreathingSpaceLip: "7e34af74-ec20-476b-aea5-6a6508d3acaf" + notifyEnteredBreathingSpaceForDefendantLip: "e551a04f-9da1-4654-a7be-2040e02925aa" + + notifyLiPApplicantBreathingSpaceLifted: "b6dbc714-210e-475d-a1db-bf5ea28de98b" + notifyLiPRespondentBreathingSpaceLifted: "4ca3017b-b2fa-4ac0-a867-9bfada50a80c" + sendgrid: api-key: ${SENDGRID_API_KEY:false} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/advice/ResourceExceptionHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/advice/ResourceExceptionHandlerTest.java index ef55860be22..08d2a6fe890 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/advice/ResourceExceptionHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/advice/ResourceExceptionHandlerTest.java @@ -145,6 +145,21 @@ public void testFeignExceptionGatewayTimeoutException() { ); } + @Test + public void testClientAbortException() { + testTemplate( + "ClosedChannelException", + str -> new FeignException.InternalServerError( + "ClosedChannelException", + Mockito.mock(feign.Request.class), + new byte[]{}, + Collections.emptyMap() + ), + handler::handleClientAbortException, + HttpStatus.REQUEST_TIMEOUT + ); + } + @Test public void testHandleNotificationClientException() { testTemplate( diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/ClaimIssueCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/ClaimIssueCallbackHandlerTest.java index 89894b4a836..b5d2910c1fa 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/ClaimIssueCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/ClaimIssueCallbackHandlerTest.java @@ -10,6 +10,7 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit.jupiter.SpringExtension; import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.model.OrganisationPolicy; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; import uk.gov.hmcts.reform.civil.model.CaseData; @@ -56,6 +57,8 @@ void setup() { @Test void shouldAddClaimNotificationDeadline_whenClaimIsIssued() { CaseData caseData = CaseDataBuilder.builder().atStatePendingClaimIssued() + .build().toBuilder() + .respondent1OrganisationIDCopy("") .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); @@ -67,7 +70,7 @@ void shouldAddClaimNotificationDeadline_whenClaimIsIssued() { } @Test - void shouldClearOrganisationId_whenClaimIsIssued() { + void shouldNotThrowException_whenIdCopyIsDefined() { CaseData caseData = CaseDataBuilder.builder().atStatePendingClaimIssued() .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); @@ -75,29 +78,28 @@ void shouldClearOrganisationId_whenClaimIsIssued() { var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); - assertThat(updatedData.getRespondent1OrganisationPolicy().getOrganisation().getOrganisationID()) - .isEqualTo(null); - assertThat(updatedData.getRespondent1OrganisationIDCopy()).isEqualTo("QWERTY R"); - assertThat(updatedData.getRespondent2OrganisationIDCopy()).isEqualTo("QWERTY R2"); - + assertThat(updatedData.getClaimNotificationDeadline()).isEqualTo(deadline); + assertThat(updatedData.getNextDeadline()).isEqualTo(deadline.toLocalDate()); } @Test - void shouldClearOrganisationIdTwoDefendants_whenClaimIsIssued() { + void shouldNotThrowException_whenIdCopyIsNotDefined() { CaseData caseData = CaseDataBuilder.builder().atStatePendingClaimIssued() - .multiPartyClaimTwoDefendantSolicitors() + .build().toBuilder() + .respondent1OrganisationIDCopy("") + .build(); + caseData = caseData.toBuilder() + .respondent1OrganisationPolicy( + OrganisationPolicy.builder().build() + ) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); - assertThat(updatedData.getRespondent1OrganisationPolicy().getOrganisation().getOrganisationID()) - .isEqualTo(null); - assertThat(updatedData.getRespondent2OrganisationPolicy().getOrganisation().getOrganisationID()) - .isEqualTo(null); - assertThat(updatedData.getRespondent1OrganisationIDCopy()).isEqualTo("QWERTY R"); - assertThat(updatedData.getRespondent2OrganisationIDCopy()).isEqualTo("QWERTY R2"); + assertThat(updatedData.getClaimNotificationDeadline()).isEqualTo(deadline); + assertThat(updatedData.getNextDeadline()).isEqualTo(deadline.toLocalDate()); } @Test diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/RespondentResponseDeadlineCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/RespondentResponseDeadlineCallbackHandlerTest.java new file mode 100644 index 00000000000..6f8d1a7a5af --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/RespondentResponseDeadlineCallbackHandlerTest.java @@ -0,0 +1,59 @@ +package uk.gov.hmcts.reform.civil.handler.callback.camunda.caseevents; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; +import uk.gov.hmcts.reform.civil.service.DeadlinesCalculator; + +import java.time.LocalDateTime; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = { + RespondentResponseDeadlineCallbackHandler.class, + DeadlinesCalculator.class, + JacksonAutoConfiguration.class +}) +public class RespondentResponseDeadlineCallbackHandlerTest extends BaseCallbackHandlerTest { + + @Autowired + private RespondentResponseDeadlineCallbackHandler handler; + + @Autowired + private final ObjectMapper mapper = new ObjectMapper(); + + @MockBean + private DeadlinesCalculator deadlinesCalculator; + + @Test + void shouldUpdateRespondent1ResponseDeadlineTo28days_whenClaimIssud() { + + LocalDateTime localDateTime = LocalDateTime.of(2023, 10, 30, 12, 0, 0); + when(deadlinesCalculator.plus28DaysAt4pmDeadline(any())).thenReturn(localDateTime); + + CaseData caseData = CaseDataBuilder.builder().build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + // When + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + + // Then + assertThat(updatedData.getRespondent1ResponseDeadline()).isEqualTo(localDateTime); + + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/SendSDOToLiPDefendantCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/SendSDOToLiPDefendantCallbackHandlerTest.java index 395e562d5ec..fc7e8601643 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/SendSDOToLiPDefendantCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/SendSDOToLiPDefendantCallbackHandlerTest.java @@ -14,8 +14,10 @@ import uk.gov.hmcts.reform.civil.sampledata.CallbackParamsBuilder; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.service.SendSDOBulkPrintService; +import uk.gov.hmcts.reform.civil.service.documentmanagement.DocumentDownloadService; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.SEND_SDO_ORDER_TO_LIP_DEFENDANT; @@ -32,6 +34,8 @@ public class SendSDOToLiPDefendantCallbackHandlerTest extends BaseCallbackHandle private SendSDOToLiPDefendantCallbackHandler handler; @MockBean private SendSDOBulkPrintService sendSDOBulkPrintService; + @MockBean + private DocumentDownloadService documentDownloadService; public static final String TASK_ID = "SendSDOToDefendantLIP"; @@ -59,6 +63,6 @@ void shouldDownloadDocumentAndPrintLetterSuccessfully() { // then assertThat(response.getErrors()).isNull(); - verify(sendSDOBulkPrintService).sendSDOToDefendantLIP(caseData); + verify(sendSDOBulkPrintService).sendSDOToDefendantLIP(any(), any()); } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/TriggerGenAppLocationUpdateCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/TriggerGenAppLocationUpdateCallbackHandlerTest.java index e82e3a302b3..53cd99df257 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/TriggerGenAppLocationUpdateCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/caseevents/TriggerGenAppLocationUpdateCallbackHandlerTest.java @@ -46,6 +46,8 @@ class TriggerGenAppLocationUpdateCallbackHandlerTest extends BaseCallbackHandler @MockBean private GenAppStateHelperService helperService; + private static final String authToken = "Bearer TestAuthToken"; + @Test void handleEventsReturnsTheExpectedCallbackEvent() { assertThat(handler.handledEvents()).contains(TRIGGER_UPDATE_GA_LOCATION); @@ -60,12 +62,12 @@ void shouldTriggerGeneralApplicationEvent_whenCaseHasGeneralApplication() { true, true, getOriginalStatusOfGeneralApplication() ); - when(helperService.updateApplicationLocationDetailsInClaim(caseData)).thenReturn(caseData); + when(helperService.updateApplicationLocationDetailsInClaim(any(), any())).thenReturn(caseData); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); assertThat(response.getErrors()).isNull(); - verify(helperService, times(1)).updateApplicationLocationDetailsInClaim(caseData); + verify(helperService, times(1)).updateApplicationLocationDetailsInClaim(any(), any()); verify(helperService, times(1)).triggerEvent(caseData, TRIGGER_LOCATION_UPDATE); verify(helperService, times(1)).triggerEvent(caseData, TRIGGER_LOCATION_UPDATE); verifyNoMoreInteractions(helperService); @@ -93,7 +95,7 @@ void triggerGeneralApplicationEventThrowsException_HandleFailure() { ); String expectedErrorMessage = "Could not trigger event to update location on application under case: " + caseData.getCcdCaseReference(); - when(helperService.updateApplicationLocationDetailsInClaim(caseData)).thenReturn(caseData); + when(helperService.updateApplicationLocationDetailsInClaim(any(), any())).thenReturn(caseData); when(helperService.triggerEvent(any(CaseData.class), eq(TRIGGER_LOCATION_UPDATE))) .thenThrow(new RuntimeException()); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateAcknowledgementOfClaimCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateAcknowledgementOfClaimCallbackHandlerTest.java index 4b5dfe39d41..b2ad22bd785 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateAcknowledgementOfClaimCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateAcknowledgementOfClaimCallbackHandlerTest.java @@ -109,6 +109,7 @@ void shouldAssignCategoryId_whenInvokedAnd1v2DifferentSol() { CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); // Then assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo("defendant2DefenseDirectionsQuestionnaire"); + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo("DQRespondentTwo"); } @Test @@ -126,6 +127,7 @@ void shouldAssignClaimantCategoryId_whenInvokedAnd1v2DifferentSolButWrongFlag() CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); // Then assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo("defendant1DefenseDirectionsQuestionnaire"); + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo("DQRespondent"); } @Test @@ -143,6 +145,7 @@ void shouldAssignCategoryId_whenInvokedAnd1v1Or1v2SameSol() { CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); // Then assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo("defendant1DefenseDirectionsQuestionnaire"); + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo("DQRespondent"); } @Test diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateClaimFormForSpecHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateClaimFormForSpecHandlerTest.java index c19bc333f6b..36217026471 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateClaimFormForSpecHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateClaimFormForSpecHandlerTest.java @@ -443,12 +443,15 @@ void shouldStitchClaimFormWithLipForm_whenOneVsTwo_andBothDefendantsAreLitigantI } @Test - void shouldNotGenerateClaimForm_whenLipvLipFlagIsOn() { + void shouldNotGenerateClaimForm_whenLipvLipFlagIsOnAndApplicantIsLip() { given(toggleService.isLipVLipEnabled()).willReturn(true); CaseData caseData = CaseDataBuilder.builder() .atStatePendingClaimIssuedUnrepresentedDefendant().build().toBuilder() .specRespondent1Represented(NO) + .build() + .toBuilder() + .applicant1Represented(NO) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionQuestionnaireLipCallBackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionQuestionnaireLipCallBackHandlerTest.java index 87acff350e8..c15b9669c47 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionQuestionnaireLipCallBackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionQuestionnaireLipCallBackHandlerTest.java @@ -1,6 +1,7 @@ package uk.gov.hmcts.reform.civil.handler.callback.camunda.docmosis; import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; @@ -14,6 +15,7 @@ import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.service.SystemGeneratedDocumentService; +import uk.gov.hmcts.reform.civil.service.docmosis.dq.DirectionQuestionnaireLipGeneratorFactory; import uk.gov.hmcts.reform.civil.service.docmosis.dq.DirectionsQuestionnaireLipGenerator; import java.time.LocalDateTime; @@ -38,6 +40,8 @@ class GenerateDirectionQuestionnaireLipCallBackHandlerTest extends BaseCallbackH @Autowired private GenerateDirectionQuestionnaireLipCallBackHandler handler; @MockBean + private DirectionQuestionnaireLipGeneratorFactory directionQuestionnaireLipGeneratorFactory; + @MockBean private DirectionsQuestionnaireLipGenerator directionsQuestionnaireLipGenerator; @MockBean private SystemGeneratedDocumentService systemGeneratedDocumentService; @@ -56,6 +60,12 @@ class GenerateDirectionQuestionnaireLipCallBackHandlerTest extends BaseCallbackH .build(); private static final String BEARER_TOKEN = "BEARER_TOKEN"; + @BeforeEach + void setUp() { + given(directionQuestionnaireLipGeneratorFactory.getDirectionQuestionnaire()).willReturn( + directionsQuestionnaireLipGenerator); + } + @Test void shouldGenerateForm_whenAboutToSubmitCalled() { given(directionsQuestionnaireLipGenerator.generate(any(CaseData.class), anyString())).willReturn(FORM); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionsQuestionnaireCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionsQuestionnaireCallbackHandlerTest.java index b9096b96899..a32833d9f46 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionsQuestionnaireCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateDirectionsQuestionnaireCallbackHandlerTest.java @@ -307,7 +307,7 @@ void shouldAddDocumentToSystemGeneratedDocuments_when1v2DiffSolBothRespondents() CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); - assertThat(updatedData.getSystemGeneratedCaseDocuments().size()).isEqualTo(2); + assertThat(updatedData.getSystemGeneratedCaseDocuments()).hasSize(2); } @Test @@ -337,6 +337,8 @@ void shouldAssignDefendantCategoryId_whenInvokedUnspecified() { // Then assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo( "defendant1DefenseDirectionsQuestionnaire"); + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo( + "DQRespondent"); } @Test @@ -354,6 +356,8 @@ void shouldAssignClaimantCategoryId_whenInvokedAndClaimantUnspecified() { assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo( "directionsQuestionnaire"); + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo( + "DQApplicant"); } @Test @@ -383,6 +387,8 @@ void shouldAssignDefendantCategoryId_when1v1or1v2SameSolicitorUnspecified() { // Then assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo( "defendant1DefenseDirectionsQuestionnaire"); + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo( + "DQRespondent"); } @Test @@ -400,6 +406,8 @@ void shouldAssignDefendantCategoryId_whenInvokedAnd1v2DiffSolicitorUnspecified() // Then assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo( "defendant2DefenseDirectionsQuestionnaire"); + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo( + "DQRespondentTwo"); } @Test @@ -417,6 +425,8 @@ void shouldAssignClaimantCategoryId_whenFlagNotUserRespondent2Unspecified() { // Then assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo( "directionsQuestionnaire"); + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo( + "DQApplicant"); } @Test @@ -434,6 +444,8 @@ void shouldAssignClaimantCategoryId_whenInvokedAndClaimantSpecified() { // Then assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo( "directionsQuestionnaire"); + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo( + "DQApplicant"); } @Test @@ -464,6 +476,8 @@ void shouldAssignDefendantCategoryId_whenInvokedSpecified() { // Then assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo( "defendant1DefenseDirectionsQuestionnaire"); + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo( + "DQRespondent"); } @Test @@ -487,6 +501,8 @@ void shouldAssignDefendantCategoryId_1v2SameSolicitorNotSameResponseSpecified() // Then assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo( "defendant1DefenseDirectionsQuestionnaire"); + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo( + "DQRespondent"); } @Test diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateResponseSealedSpecTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateResponseSealedSpecTest.java index 9c3d9141af1..2e64560c3b6 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateResponseSealedSpecTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateResponseSealedSpecTest.java @@ -148,6 +148,7 @@ void shouldGenerateClaimForm_whenNotV1VersionAndIsPinInPostDisabled() { ReflectionTestUtils.setField(handler, "stitchEnabled", true); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); when(toggleService.isPinInPostEnabled()).thenReturn(false); + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); // When: handler is called var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -156,7 +157,7 @@ void shouldGenerateClaimForm_whenNotV1VersionAndIsPinInPostDisabled() { // Then: updatedData should contain stitched doc assertThat(updatedData.getSystemGeneratedCaseDocuments().stream() .filter(caseDocumentElement -> caseDocumentElement.getValue() - .getDocumentName().equals(STITCHED_DOC.getDocumentName())).count()).isEqualTo(1); + .getDocumentName().equals(STITCHED_DOC.getDocumentName())).count()).isEqualTo(2); verify(sealedClaimResponseFormGeneratorForSpec).generate(any(CaseData.class), eq(BEARER_TOKEN)); } @@ -167,6 +168,7 @@ void shouldGenerateClaimForm_V1VersionAndIsPinInPostEnabled() { ReflectionTestUtils.setField(handler, "stitchEnabled", true); CallbackParams params = callbackParamsOf(CallbackVersion.V_1, caseData, ABOUT_TO_SUBMIT); when(toggleService.isPinInPostEnabled()).thenReturn(true); + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); // When: handler is called var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -175,7 +177,7 @@ void shouldGenerateClaimForm_V1VersionAndIsPinInPostEnabled() { // Then: updatedData should contain stitched doc assertThat(updatedData.getSystemGeneratedCaseDocuments().stream() .filter(caseDocumentElement -> caseDocumentElement.getValue() - .getDocumentName().equals(STITCHED_DOC.getDocumentName())).count()).isEqualTo(1); + .getDocumentName().equals(STITCHED_DOC.getDocumentName())).count()).isEqualTo(2); verify(sealedClaimResponseFormGeneratorForSpec).generate(any(CaseData.class), eq(BEARER_TOKEN)); } @@ -186,6 +188,7 @@ void shouldGenerateClaimForm_V1VersionAndIsPinInPostDisabled() { ReflectionTestUtils.setField(handler, "stitchEnabled", true); CallbackParams params = callbackParamsOf(CallbackVersion.V_1, caseData, ABOUT_TO_SUBMIT); when(toggleService.isPinInPostEnabled()).thenReturn(false); + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); // When: handler is called var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -194,7 +197,7 @@ void shouldGenerateClaimForm_V1VersionAndIsPinInPostDisabled() { // Then: updatedData should contain stitched doc assertThat(updatedData.getSystemGeneratedCaseDocuments().stream() .filter(caseDocumentElement -> caseDocumentElement.getValue() - .getDocumentName().equals(STITCHED_DOC.getDocumentName())).count()).isEqualTo(1); + .getDocumentName().equals(STITCHED_DOC.getDocumentName())).count()).isEqualTo(2); verify(sealedClaimResponseFormGeneratorForSpec).generate(any(CaseData.class), eq(BEARER_TOKEN)); } @@ -204,6 +207,7 @@ void shouldGenerateClaimForm_V1VersionAndIsPinInPostEnabledStitchingDisabled() { ReflectionTestUtils.setField(handler, "stitchEnabled", false); CallbackParams params = callbackParamsOf(CallbackVersion.V_1, caseData, ABOUT_TO_SUBMIT); when(toggleService.isPinInPostEnabled()).thenReturn(true); + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); // When: handler is called var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -212,7 +216,7 @@ void shouldGenerateClaimForm_V1VersionAndIsPinInPostEnabledStitchingDisabled() { // Then: updatedData should contain sealed form not stitched doc assertThat(updatedData.getSystemGeneratedCaseDocuments().stream() .filter(caseDocumentElement -> caseDocumentElement.getValue() - .getDocumentName().equals(SEALED_FORM.getDocumentName())).count()).isEqualTo(2); + .getDocumentName().equals(SEALED_FORM.getDocumentName())).count()).isEqualTo(3); verify(sealedClaimResponseFormGeneratorForSpec).generate(any(CaseData.class), eq(BEARER_TOKEN)); } @@ -222,6 +226,7 @@ void shouldGenerateClaimForm_whenNotV1VersionAndIsPinInPostDisabledStichingDisab ReflectionTestUtils.setField(handler, "stitchEnabled", false); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); when(toggleService.isPinInPostEnabled()).thenReturn(false); + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); // When: handler is called var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -230,7 +235,7 @@ void shouldGenerateClaimForm_whenNotV1VersionAndIsPinInPostDisabledStichingDisab // Then: updatedData should contain sealed form not stitched doc assertThat(updatedData.getSystemGeneratedCaseDocuments().stream() .filter(caseDocumentElement -> caseDocumentElement.getValue() - .getDocumentName().equals(SEALED_FORM.getDocumentName())).count()).isEqualTo(2); + .getDocumentName().equals(SEALED_FORM.getDocumentName())).count()).isEqualTo(3); verify(sealedClaimResponseFormGeneratorForSpec).generate(any(CaseData.class), eq(BEARER_TOKEN)); } @@ -241,6 +246,7 @@ void shouldGenerateClaimForm_V1VersionAndIsPinInPostDisabledAndStitchDisabled() ReflectionTestUtils.setField(handler, "stitchEnabled", false); CallbackParams params = callbackParamsOf(CallbackVersion.V_1, caseData, ABOUT_TO_SUBMIT); when(toggleService.isPinInPostEnabled()).thenReturn(false); + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); // When: handler is called var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -249,7 +255,7 @@ void shouldGenerateClaimForm_V1VersionAndIsPinInPostDisabledAndStitchDisabled() // Then: updatedData should contain sealed form not stitched doc assertThat(updatedData.getSystemGeneratedCaseDocuments().stream() .filter(caseDocumentElement -> caseDocumentElement.getValue() - .getDocumentName().equals(SEALED_FORM.getDocumentName())).count()).isEqualTo(2); + .getDocumentName().equals(SEALED_FORM.getDocumentName())).count()).isEqualTo(3); verify(sealedClaimResponseFormGeneratorForSpec).generate(any(CaseData.class), eq(BEARER_TOKEN)); } @@ -264,6 +270,7 @@ void shouldGenerateClaimForm_WhenSpecResponseTimelineDocAndRespondent1SpecDefenc ReflectionTestUtils.setField(handler, "stitchEnabled", true); CallbackParams params = callbackParamsOf(CallbackVersion.V_1, caseData, ABOUT_TO_SUBMIT); when(toggleService.isPinInPostEnabled()).thenReturn(false); + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); // When: handler is called var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -272,7 +279,7 @@ void shouldGenerateClaimForm_WhenSpecResponseTimelineDocAndRespondent1SpecDefenc // Then: updatedData should contain stitched doc assertThat(updatedData.getSystemGeneratedCaseDocuments().stream() .filter(caseDocumentElement -> caseDocumentElement.getValue() - .getDocumentName().equals(STITCHED_DOC.getDocumentName())).count()).isEqualTo(1); + .getDocumentName().equals(STITCHED_DOC.getDocumentName())).count()).isEqualTo(2); verify(sealedClaimResponseFormGeneratorForSpec).generate(any(CaseData.class), eq(BEARER_TOKEN)); } @@ -295,6 +302,7 @@ void shouldAssignCategoryId_whenInvoked() { CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); // Then assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo("defendant1DefenseDirectionsQuestionnaire"); + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo("DQRespondent"); } @@ -317,7 +325,7 @@ void shouldAssignCategoryId_whenInvokedStitchedEnabled() { CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); // Then assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo("defendant1DefenseDirectionsQuestionnaire"); - + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo("DQRespondent"); } @Test @@ -340,7 +348,7 @@ void shouldAssignCategoryId_whenInvokedAndRespondent2() { CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); // Then assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo("defendant2DefenseDirectionsQuestionnaire"); - + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo("DQRespondentTwo"); } @Test @@ -363,7 +371,7 @@ void shouldAssignCategoryId_whenInvokedAndRespondent2StitchedEnabled() { CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); // Then assertThat(updatedData.getSystemGeneratedCaseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo("defendant2DefenseDirectionsQuestionnaire"); - + assertThat(updatedData.getSystemGeneratedCaseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo("DQRespondentTwo"); } @Test diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateTrialReadyFormHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateTrialReadyFormHandlerTest.java index 10dce0f8980..02edab5333d 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateTrialReadyFormHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/docmosis/GenerateTrialReadyFormHandlerTest.java @@ -13,6 +13,7 @@ import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.documentmanagement.model.Document; +import uk.gov.hmcts.reform.civil.enums.CaseRole; import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; import uk.gov.hmcts.reform.civil.model.CaseData; @@ -45,7 +46,7 @@ ValidationAutoConfiguration.class, CaseDetailsConverter.class, }) -public class GenerateTrialReadyFormHandlerTest extends BaseCallbackHandlerTest { +class GenerateTrialReadyFormHandlerTest extends BaseCallbackHandlerTest { @Autowired private final ObjectMapper mapper = new ObjectMapper(); @@ -55,7 +56,7 @@ public class GenerateTrialReadyFormHandlerTest extends BaseCallbackHandlerTest { private TrialReadyFormGenerator trialReadyFormGenerator; @Test - public void shouldGenerateForm_when1v1() { + void shouldGenerateForm_when1v1() { // Given CaseDocument document = CaseDocument.builder() .createdBy("John") @@ -70,7 +71,8 @@ public void shouldGenerateForm_when1v1() { .build()) .build(); - when(trialReadyFormGenerator.generate(any(CaseData.class), anyString(), anyString())).thenReturn(document); + when(trialReadyFormGenerator.generate(any(CaseData.class), anyString(), anyString(), any(CaseRole.class))) + .thenReturn(document); CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); params.getRequest().setEventId(GENERATE_TRIAL_READY_FORM_APPLICANT.name()); @@ -78,15 +80,16 @@ public void shouldGenerateForm_when1v1() { var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); // Then verify(trialReadyFormGenerator).generate( - any(CaseData.class), eq("BEARER_TOKEN"), eq("GenerateTrialReadyFormApplicant")); + any(CaseData.class), eq("BEARER_TOKEN"), eq("GenerateTrialReadyFormApplicant"), + eq(CaseRole.CLAIMANT)); CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); - assertThat(updatedData.getTrialReadyDocuments().size()).isEqualTo(1); + assertThat(updatedData.getTrialReadyDocuments()).hasSize(1); } @Test - public void shouldGenerateForm_when1v1AndRespondent1() { + void shouldGenerateForm_when1v1AndRespondent1() { // Given CaseDocument document = CaseDocument.builder() .createdBy("John") @@ -101,7 +104,8 @@ public void shouldGenerateForm_when1v1AndRespondent1() { .build()) .build(); - when(trialReadyFormGenerator.generate(any(CaseData.class), anyString(), anyString())).thenReturn(document); + when(trialReadyFormGenerator.generate(any(CaseData.class), anyString(), anyString(), any(CaseRole.class))) + .thenReturn(document); CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); params.getRequest().setEventId(GENERATE_TRIAL_READY_FORM_RESPONDENT1.name()); @@ -109,15 +113,16 @@ public void shouldGenerateForm_when1v1AndRespondent1() { var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); // Then verify(trialReadyFormGenerator).generate( - any(CaseData.class), eq("BEARER_TOKEN"), eq("GenerateTrialReadyFormRespondent1")); + any(CaseData.class), eq("BEARER_TOKEN"), eq("GenerateTrialReadyFormRespondent1"), + eq(CaseRole.DEFENDANT)); CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); - assertThat(updatedData.getTrialReadyDocuments().size()).isEqualTo(1); + assertThat(updatedData.getTrialReadyDocuments()).hasSize(1); } @Test - public void shouldGenerateForm_when1v2AndOneSeveralPartiesGeneratesDocument() { + void shouldGenerateForm_when1v2AndOneSeveralPartiesGeneratesDocument() { // Given CaseDocument document = CaseDocument.builder() .createdBy("John") @@ -133,7 +138,9 @@ public void shouldGenerateForm_when1v2AndOneSeveralPartiesGeneratesDocument() { .build(); List> systemGeneratedCaseDocuments = new ArrayList<>(); systemGeneratedCaseDocuments.add(element(document)); - when(trialReadyFormGenerator.generate(any(CaseData.class), anyString(), anyString())).thenReturn(document); + + when(trialReadyFormGenerator.generate(any(CaseData.class), anyString(), anyString(), any(CaseRole.class))) + .thenReturn(document); CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .trialReadyDocuments(systemGeneratedCaseDocuments).build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); @@ -142,10 +149,11 @@ public void shouldGenerateForm_when1v2AndOneSeveralPartiesGeneratesDocument() { var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); // Then verify(trialReadyFormGenerator).generate( - any(CaseData.class), eq("BEARER_TOKEN"), eq("GenerateTrialReadyFormRespondent2")); + any(CaseData.class), eq("BEARER_TOKEN"), eq("GenerateTrialReadyFormRespondent2"), + eq(CaseRole.RESPONDENTSOLICITORTWO)); CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); - assertThat(updatedData.getTrialReadyDocuments().size()).isEqualTo(2); + assertThat(updatedData.getTrialReadyDocuments()).hasSize(2); } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/noticeofchange/UpdateCaseDetailsAfterNoCHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/noticeofchange/UpdateCaseDetailsAfterNoCHandlerTest.java index 17708a6f4d3..a0fc90c4c81 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/noticeofchange/UpdateCaseDetailsAfterNoCHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/noticeofchange/UpdateCaseDetailsAfterNoCHandlerTest.java @@ -154,6 +154,7 @@ void shouldUpdateSolicitorDetails_afterNoCSubmittedByRespondentSolicitor1v1() { assertThat(updatedCaseData.getUnassignedCaseListDisplayOrganisationReferences()).isEmpty(); assertThat(updatedCaseData.getRespondentSolicitor1EmailAddress()) .isEqualTo("requester@example.com"); + assertThat(updatedCaseData.getDefendant1LIPAtClaimIssued()).isEqualTo(NO); } @Test @@ -182,6 +183,7 @@ void shouldUpdateSolicitorDetails_afterNoCSubmittedByRespondentSolicitor1v1LiP() assertThat(updatedCaseData.getRespondent1OrgRegistered()).isEqualTo(YES); assertThat(updatedCaseData.getRespondentSolicitor1EmailAddress()) .isEqualTo("requester@example.com"); + assertThat(updatedCaseData.getDefendant1LIPAtClaimIssued()).isEqualTo(NO); } @Test @@ -218,6 +220,7 @@ void shouldUpdateSolicitorDetails_afterNoCSubmittedByRespondentSolicitor2In1v2Di assertThat(updatedCaseData.getUnassignedCaseListDisplayOrganisationReferences()).isEmpty(); assertThat(updatedCaseData.getRespondentSolicitor2EmailAddress()) .isEqualTo("requester@example.com"); + assertThat(updatedCaseData.getDefendant2LIPAtClaimIssued()).isEqualTo(NO); } @Test @@ -248,6 +251,7 @@ void shouldUpdateSolicitorDetails_afterNoCSubmittedByRespondentSolicitor2In1v2Di assertThat(updatedCaseData.getRespondentSolicitor2EmailAddress()) .isEqualTo("requester@example.com"); assertThat(getMultiPartyScenario(updatedCaseData)).isEqualTo(ONE_V_TWO_ONE_LEGAL_REP); + assertThat(updatedCaseData.getDefendant2LIPAtClaimIssued()).isEqualTo(NO); } @Test @@ -278,6 +282,7 @@ void shouldUpdateSolicitorDetails_afterNoCSubmittedByRespondentSolicitor2In1v2Sa assertThat(updatedCaseData.getRespondentSolicitor2EmailAddress()) .isEqualTo("requester@example.com"); assertThat(getMultiPartyScenario(updatedCaseData)).isEqualTo(ONE_V_TWO_TWO_LEGAL_REP); + assertThat(updatedCaseData.getDefendant2LIPAtClaimIssued()).isEqualTo(NO); } @Test @@ -308,6 +313,7 @@ void shouldUpdateSolicitorDetails_afterNoCSubmittedByRespondentSolicitor2LiP() { assertThat(getMultiPartyScenario(updatedCaseData)).isEqualTo(ONE_V_TWO_TWO_LEGAL_REP); assertThat(updatedCaseData.getRespondentSolicitor2EmailAddress()) .isEqualTo("requester@example.com"); + assertThat(updatedCaseData.getDefendant2LIPAtClaimIssued()).isEqualTo(NO); } @Test @@ -339,6 +345,7 @@ void shouldUpdateSolicitorDetails_afterNoCSubmittedByRespondentSolicitor2BothRes assertThat(getMultiPartyScenario(updatedCaseData)).isEqualTo(ONE_V_TWO_TWO_LEGAL_REP); assertThat(updatedCaseData.getRespondentSolicitor2EmailAddress()) .isEqualTo("requester@example.com"); + assertThat(updatedCaseData.getDefendant2LIPAtClaimIssued()).isEqualTo(NO); } @Test diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AcknowledgeClaimApplicantNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AcknowledgeClaimApplicantNotificationHandlerTest.java index 3bc6f72a827..d32dd7e979f 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AcknowledgeClaimApplicantNotificationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/AcknowledgeClaimApplicantNotificationHandlerTest.java @@ -10,6 +10,7 @@ import org.springframework.boot.test.mock.mockito.MockBean; import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest; import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.model.IdamUserDetails; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; import uk.gov.hmcts.reform.civil.enums.YesOrNo; @@ -25,6 +26,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; @@ -85,6 +87,51 @@ void shouldNotifyApplicantSolicitor_whenInvoked() { ); } + @Test + void shouldNotNotifyApplicantSolicitor_whenRecipeintIsNull() { + CaseData caseData = CaseDataBuilder.builder() + .atStateNotificationAcknowledged() + .applicantSolicitor1UserDetails(IdamUserDetails.builder().email(null).build()) + .build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( + CallbackRequest.builder().eventId("NOTIFY_APPLICANT_SOLICITOR1_FOR_CLAIM_ACKNOWLEDGEMENT").build()) + .build(); + + handler.handle(params); + + assertThatNoException(); + } + + @Test + void shouldNotNotifyRespondentSolicitor_whenRecipeint1IsNull() { + CaseData caseData = CaseDataBuilder.builder() + .atStateNotificationAcknowledged() + .respondentSolicitor1EmailAddress(null) + .build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( + CallbackRequest.builder().eventId("NOTIFY_APPLICANT_SOLICITOR1_FOR_CLAIM_ACKNOWLEDGEMENT").build()) + .build(); + + handler.handle(params); + + assertThatNoException(); + } + + @Test + void shouldNotNotifyRespondentSolicitor_whenRecipeint2IsNull() { + CaseData caseData = CaseDataBuilder.builder() + .atStateNotificationAcknowledged() + .respondentSolicitor2EmailAddress(null) + .build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( + CallbackRequest.builder().eventId("NOTIFY_APPLICANT_SOLICITOR1_FOR_CLAIM_ACKNOWLEDGEMENT").build()) + .build(); + + handler.handle(params); + + assertThatNoException(); + } + @Test void shouldNotifyRespondentSolicitor_whenInvokedWithCcEvent() { CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build(); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/BreathingSpaceEnteredLIPNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/BreathingSpaceEnteredLIPNotificationHandlerTest.java new file mode 100644 index 00000000000..39af45c255f --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/BreathingSpaceEnteredLIPNotificationHandlerTest.java @@ -0,0 +1,113 @@ +package uk.gov.hmcts.reform.civil.handler.callback.camunda.notification; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CallbackType; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; + +import java.util.Map; + +import static org.mockito.ArgumentMatchers.eq; + +@ExtendWith(SpringExtension.class) +public class BreathingSpaceEnteredLIPNotificationHandlerTest { + + @InjectMocks + private BreathingSpaceEnteredLIPNotificationHandler handler; + @Mock + private NotificationService notificationService; + @Mock + private NotificationsProperties notificationsProperties; + + private static String templateId = "templateId"; + + @Test + public void notifyApplicant1BreathingSpace() { + + Mockito.when(notificationsProperties.getNotifyApplicant1EnteredBreathingSpaceLip()) + .thenReturn(templateId); + CaseData caseData = createCaseData(); + CallbackParams params = createCallbackParams( + CaseEvent.NOTIFY_LIP_APPLICANT1_BREATHING_SPACE_ENTER, + caseData + ); + + handler.handle(params); + + Mockito.verify(notificationService).sendMail( + eq("applicant1@gmail.com"), + eq(templateId), + eq(createExpectedTemplateProperties()), + eq("notify-breathing-space-lip-legacy ref") + ); + } + + @Test + public void notifyRespondentBreathingSpace() { + + Mockito.when(notificationsProperties.getNotifyEnteredBreathingSpaceForDefendantLip()) + .thenReturn(templateId); + CaseData caseData = createCaseData(); + CallbackParams params = createCallbackParams( + CaseEvent.NOTIFY_LIP_RESPONDENT_BREATHING_SPACE_ENTER, + caseData + ); + + handler.handle(params); + + Mockito.verify(notificationService).sendMail( + eq("respondent@gmail.com"), + eq(templateId), + eq(createExpectedTemplateProperties()), + eq("notify-breathing-space-lip-legacy ref") + ); + } + + private CaseData createCaseData() { + return CaseData.builder() + .legacyCaseReference("legacy ref") + .applicant1(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("mr") + .individualFirstName("applicant1") + .individualLastName("lip") + .partyEmail("applicant1@gmail.com") + .build()) + .respondent1(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("mr") + .individualFirstName("respondent") + .individualLastName("lip") + .partyEmail("respondent@gmail.com") + .build()) + .build(); + } + + private CallbackParams createCallbackParams(CaseEvent caseEvent, CaseData caseData) { + return CallbackParams.builder() + .type(CallbackType.ABOUT_TO_SUBMIT) + .caseData(caseData) + .request(CallbackRequest.builder() + .eventId(caseEvent.name()) + .build()) + .build(); + } + + private Map createExpectedTemplateProperties() { + return Map.of( + "defendantName", "mr respondent lip", + "claimReferenceNumber", "legacy ref", + "claimantName", "mr applicant1 lip" + ); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/BreathingSpaceLiftedLIPNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/BreathingSpaceLiftedLIPNotificationHandlerTest.java new file mode 100644 index 00000000000..f1ccb6ae767 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/BreathingSpaceLiftedLIPNotificationHandlerTest.java @@ -0,0 +1,141 @@ +package uk.gov.hmcts.reform.civil.handler.callback.camunda.notification; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; +import uk.gov.hmcts.reform.civil.sampledata.CallbackParamsBuilder; +import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; +import uk.gov.hmcts.reform.civil.sampledata.PartyBuilder; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.BreathingSpaceLiftedLIPNotificationHandler.TASK_ID_APPLICANT; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.BreathingSpaceLiftedLIPNotificationHandler.TASK_ID_RESPONDENT; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.CLAIMANT_NAME; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.CLAIM_REFERENCE_NUMBER; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.RESPONDENT_NAME; +import static uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilderSpec.LEGACY_CASE_REFERENCE; + +@SpringBootTest(classes = { + BreathingSpaceLiftedLIPNotificationHandler.class, + JacksonAutoConfiguration.class, +}) +class BreathingSpaceLiftedLIPNotificationHandlerTest extends BaseCallbackHandlerTest { + + @MockBean + private NotificationService notificationService; + @MockBean + private NotificationsProperties notificationsProperties; + @Autowired + private BreathingSpaceLiftedLIPNotificationHandler handler; + + @Nested + class AboutToSubmitCallback { + + private static final String APPLICANT_EMAIL_TEMPLATE = "template-id-applicant"; + private static final String RESPONDENT_EMAIL_TEMPLATE = "template-id-respondent"; + private static final String CLAIMANT_EMAIL_ID = "claimant@email.com"; + private static final String RESPONDENT_EMAIL_ID = "respondent@email.com"; + private static final String REFERENCE_NUMBER = "notify-breathing-space-lifted-000DC001"; + private static final String CLAIMANT = "Mr. John Rambo"; + private static final String DEFENDANT = "Mr. Sole Trader"; + + @BeforeEach + void setup() { + when(notificationsProperties.getNotifyLiPApplicantBreathingSpaceLifted()).thenReturn(APPLICANT_EMAIL_TEMPLATE); + when(notificationsProperties.getNotifyLiPRespondentBreathingSpaceLifted()).thenReturn(RESPONDENT_EMAIL_TEMPLATE); + } + + @Test + void shouldNotifyApplicant_BreathingSpaceLifted() { + // Given + CaseData caseData = CaseDataBuilder.builder().atStateClaimSubmitted().build().toBuilder() + .applicant1(PartyBuilder.builder().individual().build().toBuilder() + .partyEmail(CLAIMANT_EMAIL_ID) + .build()) + .respondent1(PartyBuilder.builder().soleTrader().build().toBuilder() + .build()) + .build(); + + CallbackParams params = CallbackParams.builder().type(ABOUT_TO_SUBMIT) + .caseData(caseData) + .request(CallbackRequest.builder().eventId(CaseEvent.NOTIFY_LIP_APPLICANT_BREATHING_SPACE_LIFTED.name()).build()) + .build(); + + // When + handler.handle(params); + + // Then + verify(notificationService, times(1)).sendMail( + CLAIMANT_EMAIL_ID, + APPLICANT_EMAIL_TEMPLATE, + getNotificationDataMap(caseData), + REFERENCE_NUMBER + ); + } + + @Test + void shouldNotifyRespondent_BreathingSpaceLifted() { + // Given + CaseData caseData = CaseDataBuilder.builder().atStateClaimSubmitted().build().toBuilder() + .applicant1(PartyBuilder.builder().individual().build().toBuilder() + .partyEmail(CLAIMANT_EMAIL_ID) + .build()) + .respondent1(PartyBuilder.builder().soleTrader().build().toBuilder() + .partyEmail(RESPONDENT_EMAIL_ID) + .build()) + .build(); + + CallbackParams params = CallbackParams.builder().type(ABOUT_TO_SUBMIT) + .caseData(caseData) + .request(CallbackRequest.builder().eventId(CaseEvent.NOTIFY_LIP_RESPONDENT_BREATHING_SPACE_LIFTED.name()).build()) + .build(); + + // When + handler.handle(params); + + // Then + verify(notificationService, times(1)).sendMail( + RESPONDENT_EMAIL_ID, + RESPONDENT_EMAIL_TEMPLATE, + getNotificationDataMap(caseData), + REFERENCE_NUMBER + ); + } + + private Map getNotificationDataMap(CaseData caseData) { + return Map.of( + CLAIM_REFERENCE_NUMBER, LEGACY_CASE_REFERENCE, + CLAIMANT_NAME, CLAIMANT, + RESPONDENT_NAME, DEFENDANT + ); + } + + } + + @Test + void shouldReturnCorrectCamundaActivityId_whenInvoked() { + assertThat(handler.camundaActivityId(CallbackParamsBuilder.builder().request(CallbackRequest.builder().eventId( + CaseEvent.NOTIFY_LIP_RESPONDENT_BREATHING_SPACE_LIFTED.name()).build()).build())).isEqualTo(TASK_ID_RESPONDENT); + + assertThat(handler.camundaActivityId(CallbackParamsBuilder.builder().request(CallbackRequest.builder().eventId( + CaseEvent.NOTIFY_LIP_APPLICANT_BREATHING_SPACE_LIFTED.name()).build()).build())).isEqualTo(TASK_ID_APPLICANT); + } + +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseAgreedSettledPartAdmitDefendantLipNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseAgreedSettledPartAdmitDefendantLipNotificationHandlerTest.java index 442970d3d21..d83714e012d 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseAgreedSettledPartAdmitDefendantLipNotificationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseAgreedSettledPartAdmitDefendantLipNotificationHandlerTest.java @@ -11,6 +11,7 @@ import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.enums.CaseCategory; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; @@ -20,6 +21,7 @@ import uk.gov.hmcts.reform.civil.sampledata.CallbackParamsBuilder; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.sampledata.PartyBuilder; +import uk.gov.hmcts.reform.civil.service.OrganisationDetailsService; import java.util.Map; @@ -30,6 +32,7 @@ import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.RESPONDENT_NAME; import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.CLAIM_REFERENCE_NUMBER; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.CLAIM_LEGAL_ORG_NAME_SPEC; import static uk.gov.hmcts.reform.civil.utils.PartyUtils.getPartyNameBasedOnType; @SpringBootTest(classes = { @@ -40,17 +43,22 @@ public class ClaimantResponseAgreedSettledPartAdmitDefendantLipNotificationHandl public static final String targetEmail = "sole.trader@email.com"; public static final String template = "spec-lip-template-id"; + public static final String templateEmail_lr = "respondent1email@hmcts.net"; + public static final String template_id_lr = "spec-lr-template-id"; public static final String bilingualTemplate = "spec-lip-template-bilingual-id"; public static final String englishLangResponse = "ENGLISH"; public static final String bothLangResponse = "BOTH"; public static final String reference = "claimant-part-admit-settle-respondent-notification-000DC001"; public static final String EVENT_ID = "NOTIFY_LIP_DEFENDANT_PART_ADMIT_CLAIM_SETTLED"; + private static final String ORGANISATION_NAME = "Defendant solicitor org"; @MockBean private NotificationService notificationService; @MockBean private NotificationsProperties notificationsProperties; + @MockBean + private OrganisationDetailsService organisationDetailsService; @Autowired private ClaimantResponseAgreedSettledPartAdmitDefendantLipNotificationHandler handler; @@ -61,6 +69,8 @@ class AboutToSubmitCallback { void setup() { when(notificationsProperties.getRespondentLipPartAdmitSettleClaimTemplate()).thenReturn(template); when(notificationsProperties.getRespondentLipPartAdmitSettleClaimBilingualTemplate()).thenReturn(bilingualTemplate); + when(notificationsProperties.getRespondentLrPartAdmitSettleClaimTemplate()).thenReturn(template_id_lr); + when(organisationDetailsService.getRespondentLegalOrganizationName(any())).thenReturn(ORGANISATION_NAME); } @Test @@ -88,6 +98,7 @@ void shouldNotifyRespondent_whenInvoked_spec_lip() { void shouldNotNotify_whenInvoked_spec_lip_withLr() { CaseData caseData = CaseDataBuilder.builder() .atStateClaimDetailsNotified() + .respondent1OrgRegistered(null) .caseAccessCategory(CaseCategory.SPEC_CLAIM) .build(); @@ -161,12 +172,41 @@ void shouldNotNotify_whenInvoked_spec_lip_english() { ); } + @Test + void shouldNotifyRespondent_whenInvoked_spec_lr() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimDetailsNotified() + .respondentSolicitor1EmailAddress("respondent1email@hmcts.net") + .respondent1OrgRegistered(YesOrNo.YES) + .build(); + + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( + CallbackRequest.builder().eventId(EVENT_ID) + .build()).build(); + + handler.handle(params); + + verify(notificationService).sendMail( + templateEmail_lr, + template_id_lr, + getNotificationDataMap(caseData), + reference + ); + } + @NotNull private Map getNotificationDataMap(CaseData caseData) { - return Map.of( - RESPONDENT_NAME, getPartyNameBasedOnType(caseData.getRespondent1()), - CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference() - ); + if (caseData.isRespondent1NotRepresented()) { + return Map.of( + RESPONDENT_NAME, getPartyNameBasedOnType(caseData.getRespondent1()), + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference() + ); + } else { + return Map.of( + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + CLAIM_LEGAL_ORG_NAME_SPEC, organisationDetailsService.getRespondentLegalOrganizationName(caseData) + ); + } } } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedApplicantNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedApplicantNotificationHandlerTest.java new file mode 100644 index 00000000000..9f1af1849ee --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedApplicantNotificationHandlerTest.java @@ -0,0 +1,84 @@ +package uk.gov.hmcts.reform.civil.handler.callback.camunda.notification; + +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; +import uk.gov.hmcts.reform.civil.sampledata.CallbackParamsBuilder; +import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.ClaimantResponseConfirmsToProceedApplicantNotificationHandler.TASK_ID; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.APPLICANT_ONE_NAME; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.CLAIM_REFERENCE_NUMBER; +import static uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder.LEGACY_CASE_REFERENCE; + +@SpringBootTest(classes = { + ClaimantResponseConfirmsToProceedApplicantNotificationHandler.class, + JacksonAutoConfiguration.class +}) + +class ClaimantResponseConfirmsToProceedApplicantNotificationHandlerTest extends BaseCallbackHandlerTest { + + @MockBean + private NotificationService notificationService; + @MockBean + private NotificationsProperties notificationsProperties; + @Autowired + private ClaimantResponseConfirmsToProceedApplicantNotificationHandler handler; + + @Nested + class AboutToSubmitCallback { + + @BeforeEach + void setup() { + when(notificationsProperties.getClaimantLipClaimUpdatedTemplate()).thenReturn("template-id"); + } + + @Test + void shouldNotifyLipApplicant_whenInvoked() { + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( + CallbackRequest.builder().eventId("NOTIFY_LIP_APPLICANT_CLAIMANT_CONFIRM_TO_PROCEED") + .build()).build(); + + handler.handle(params); + + verify(notificationService).sendMail( + "rambo@email.com", + "template-id", + getNotificationDataMap(caseData), + "claimant-confirms-to-proceed-applicant-notification-000DC001" + ); + } + + @Test + void shouldReturnCorrectCamundaActivityId_whenInvoked() { + assertThat(handler.camundaActivityId(CallbackParamsBuilder.builder().request(CallbackRequest.builder().eventId( + "NOTIFY_LIP_APPLICANT_CLAIMANT_CONFIRM_TO_PROCEED").build()).build())).isEqualTo(TASK_ID); + } + + @NotNull + private Map getNotificationDataMap(CaseData caseData) { + return Map.of( + CLAIM_REFERENCE_NUMBER, LEGACY_CASE_REFERENCE, + APPLICANT_ONE_NAME, "Mr. John Rambo" + ); + } + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedLiPRespondentNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedLiPRespondentNotificationHandlerTest.java new file mode 100644 index 00000000000..fdf30eb236a --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedLiPRespondentNotificationHandlerTest.java @@ -0,0 +1,90 @@ +package uk.gov.hmcts.reform.civil.handler.callback.camunda.notification; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; +import uk.gov.hmcts.reform.civil.sampledata.CallbackParamsBuilder; +import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.ClaimantResponseConfirmsToProceedLiPRespondentNotificationHandler.TASK_ID; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.CLAIM_REFERENCE_NUMBER; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.RESPONDENT_NAME; +import static uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder.LEGACY_CASE_REFERENCE; + +@SpringBootTest(classes = { + ClaimantResponseConfirmsToProceedLiPRespondentNotificationHandler.class, + JacksonAutoConfiguration.class +}) +public class ClaimantResponseConfirmsToProceedLiPRespondentNotificationHandlerTest extends BaseCallbackHandlerTest { + + @MockBean + private NotificationService notificationService; + @MockBean + private NotificationsProperties notificationsProperties; + @Autowired + private ClaimantResponseConfirmsToProceedLiPRespondentNotificationHandler handler; + + @Nested + class AboutToSubmitCallback { + + private static final String RESPONDENT_EMAIL_TEMPLATE = "template-id-respondent"; + private static final String RESPONDENT_EMAIL_ID = "sole.trader@email.com"; + private static final String REFERENCE_NUMBER = "claimant-confirms-to-proceed-respondent-notification-000DC001"; + private static final String DEFENDANT = "Mr. Sole Trader"; + + @BeforeEach + void setup() { + when(notificationsProperties.getRespondent1LipClaimUpdatedTemplate()).thenReturn( + RESPONDENT_EMAIL_TEMPLATE); + } + + @Test + void shouldNotifyLipRespondent_whenInvoked() { + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( + CallbackRequest.builder().eventId(CaseEvent.NOTIFY_LIP_RESPONDENT_CLAIMANT_CONFIRM_TO_PROCEED.name()) + .build()).build(); + + handler.handle(params); + + verify(notificationService).sendMail( + RESPONDENT_EMAIL_ID, + RESPONDENT_EMAIL_TEMPLATE, + getNotificationDataMap(caseData), + REFERENCE_NUMBER + ); + } + + private Map getNotificationDataMap(CaseData caseData) { + return Map.of( + CLAIM_REFERENCE_NUMBER, LEGACY_CASE_REFERENCE, + RESPONDENT_NAME, DEFENDANT + ); + } + + @Test + void shouldReturnCorrectCamundaActivityId_whenInvoked() { + assertThat(handler.camundaActivityId(CallbackParamsBuilder.builder().request(CallbackRequest.builder().eventId( + CaseEvent.NOTIFY_LIP_RESPONDENT_CLAIMANT_CONFIRM_TO_PROCEED.name()).build()).build())).isEqualTo(TASK_ID); + } + + } + +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedRespondentNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedRespondentNotificationHandlerTest.java index c9cf92fd0e1..9f67e39cac1 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedRespondentNotificationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseConfirmsToProceedRespondentNotificationHandlerTest.java @@ -12,17 +12,17 @@ import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CaseEvent; import uk.gov.hmcts.reform.civil.enums.CaseCategory; -import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; +import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec; import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; -import uk.gov.hmcts.reform.civil.sampledata.PartyBuilder; -import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; +import uk.gov.hmcts.reform.civil.prd.model.Organisation; import uk.gov.hmcts.reform.civil.sampledata.CallbackParamsBuilder; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; -import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.sampledata.PartyBuilder; import uk.gov.hmcts.reform.civil.service.OrganisationService; -import uk.gov.hmcts.reform.civil.prd.model.Organisation; import java.util.Map; import java.util.Optional; @@ -60,8 +60,6 @@ class ClaimantResponseConfirmsToProceedRespondentNotificationHandlerTest extends private NotificationsProperties notificationsProperties; @Autowired private ClaimantResponseConfirmsToProceedRespondentNotificationHandler handler; - @MockBean - private FeatureToggleService featureToggleService; @Nested class AboutToSubmitCallback { @@ -72,6 +70,8 @@ void setup() { when(notificationsProperties.getClaimantSolicitorConfirmsNotToProceed()).thenReturn("template-id"); when(notificationsProperties.getRespondentSolicitorNotifyToProceedSpec()).thenReturn("spec-template-id"); when(notificationsProperties.getClaimantSolicitorConfirmsToProceedSpec()).thenReturn("spec-template-id"); + when(notificationsProperties.getRespondentSolicitorNotifyToProceedSpecWithAction()).thenReturn("spec-template-no-mediation"); + when(notificationsProperties.getClaimantSolicitorConfirmsToProceedSpecWithAction()).thenReturn("spec-template-no-mediation"); when(notificationsProperties.getRespondent1LipClaimUpdatedTemplate()).thenReturn("spec-template-id"); } @@ -113,6 +113,30 @@ void shouldNotifyRespondentSolicitor_whenInvoked_spec() { ); } + @Test + void shouldNotifyRespondentSolicitor_whenSpecRejectAllNoMediation() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimDetailsNotified() + .setClaimTypeToSpecClaim() + .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_DEFENCE) + .build().toBuilder() + .responseClaimMediationSpecRequired(YesOrNo.NO) + .build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( + CallbackRequest.builder().eventId("NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIMANT_CONFIRMS_TO_PROCEED") + .build()).build(); + + handler.handle(params); + + verify(notificationService).sendMail( + "respondentsolicitor@example.com", + "spec-template-no-mediation", + getNotificationDataMapSpec(caseData, + CaseEvent.NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIMANT_CONFIRMS_TO_PROCEED), + "claimant-confirms-to-proceed-respondent-notification-000DC001" + ); + } + @Test void shouldNotifyRespondentSolicitor2_whenInvoked_spec() { CaseData caseData = CaseDataBuilder.builder() @@ -155,6 +179,30 @@ void shouldNotifyApplicantSolicitor_whenInvoked_spec() { ); } + @Test + void shouldNotifyApplicantSolicitor_whenSpecRejectAllNoMediation() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimDetailsNotified() + .setClaimTypeToSpecClaim() + .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_DEFENCE) + .build().toBuilder() + .responseClaimMediationSpecRequired(YesOrNo.NO) + .build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( + CallbackRequest.builder().eventId("NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIMANT_CONFIRMS_TO_PROCEED_CC") + .build()).build(); + + handler.handle(params); + + verify(notificationService).sendMail( + "applicantsolicitor@example.com", + "spec-template-no-mediation", + getNotificationDataMapSpec(caseData, + CaseEvent.NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIMANT_CONFIRMS_TO_PROCEED_CC), + "claimant-confirms-to-proceed-respondent-notification-000DC001" + ); + } + @Test void shouldNotifyRespondentSolicitor2withNoIntentionToProceed_whenInvoked() { CaseData caseData = CaseDataBuilder.builder() @@ -316,11 +364,11 @@ void shouldReturnCorrectCamundaActivityId_whenInvoked() { "NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIMANT_CONFIRMS_TO_PROCEED").build()).build())).isEqualTo(TASK_ID); assertThat(handler.camundaActivityId(CallbackParamsBuilder.builder().request(CallbackRequest.builder().eventId( - "NOTIFY_RESPONDENT_SOLICITOR2_FOR_CLAIMANT_CONFIRMS_TO_PROCEED").build()) + "NOTIFY_RESPONDENT_SOLICITOR2_FOR_CLAIMANT_CONFIRMS_TO_PROCEED").build()) .build())).isEqualTo(Task_ID_RESPONDENT_SOL2); assertThat(handler.camundaActivityId(CallbackParamsBuilder.builder().request(CallbackRequest.builder().eventId( "NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIMANT_CONFIRMS_TO_PROCEED_CC").build()).build())).isEqualTo( - TASK_ID_CC); + TASK_ID_CC); } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseNotAgreedRepaymentDefendantLipNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseNotAgreedRepaymentDefendantLipNotificationHandlerTest.java index 483d23eb3f0..7226dd7e545 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseNotAgreedRepaymentDefendantLipNotificationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ClaimantResponseNotAgreedRepaymentDefendantLipNotificationHandlerTest.java @@ -17,6 +17,7 @@ import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.service.OrganisationDetailsService; import uk.gov.hmcts.reform.civil.sampledata.CallbackParamsBuilder; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.notify.NotificationService; @@ -24,10 +25,12 @@ import java.util.Map; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.ClaimantResponseConfirmsNotToProceedRespondentNotificationHandler.CLAIM_REFERENCE_NUMBER; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.CLAIM_LEGAL_ORG_NAME_SPEC; import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.DEFENDANT_NAME; import static uk.gov.hmcts.reform.civil.utils.PartyUtils.getPartyNameBasedOnType; @@ -41,8 +44,11 @@ class ClaimantResponseNotAgreedRepaymentDefendantLipNotificationHandlerTest exte private NotificationService notificationService; @MockBean private NotificationsProperties notificationsProperties; + @MockBean + private OrganisationDetailsService organisationDetailsService; @Autowired private ClaimantResponseNotAgreedRepaymentDefendantLipNotificationHandler handler; + private static final String ORGANISATION_NAME = "Defendant solicitor org"; @Nested class AboutToSubmitCallback { @@ -51,6 +57,8 @@ class AboutToSubmitCallback { void setup() { when(notificationsProperties.getNotifyDefendantLipTemplate()).thenReturn("template-id"); when(notificationsProperties.getNotifyDefendantLipWelshTemplate()).thenReturn("template-welsh-id"); + when(notificationsProperties.getNotifyDefendantLrTemplate()).thenReturn("template-id-lr"); + when(organisationDetailsService.getRespondentLegalOrganizationName(any())).thenReturn(ORGANISATION_NAME); } @Test @@ -62,6 +70,7 @@ void shouldNotifyRespondentParty_whenInvoked() { CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified() .respondent1(respondent1) .respondent1OrgRegistered(null) + .respondent1Represented(null) .specRespondent1Represented(YesOrNo.NO) .build(); CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( @@ -89,6 +98,7 @@ void shouldNotifyRespondentPartyInWelsh_whenInvoked() { .atStateClaimDetailsNotified() .respondent1(respondent1) .respondent1OrgRegistered(null) + .respondent1Represented(null) .specRespondent1Represented(YesOrNo.NO) .caseDataLip(CaseDataLiP.builder().respondent1LiPResponse(RespondentLiPResponse.builder().respondent1ResponseLanguage( "BOTH").build()).build()) @@ -108,12 +118,39 @@ void shouldNotifyRespondentPartyInWelsh_whenInvoked() { ); } + @Test + void shouldNotifyRespondentLrParty_whenInvoked() { + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified() + .respondentSolicitor1EmailAddress("respondent1email@hmcts.net") + .respondent1OrgRegistered(YesOrNo.YES) + .build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( + CallbackRequest.builder().eventId("NOTIFY_LIP_DEFENDANT_REJECT_REPAYMENT") + .build()).build(); + + handler.handle(params); + + verify(notificationService).sendMail( + "respondent1email@hmcts.net", + "template-id-lr", + getNotificationDataMapSpec(caseData), + "claimant-reject-repayment-respondent-notification-000DC001" + ); + } + @NotNull public Map getNotificationDataMapSpec(CaseData caseData) { - return Map.of( - CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), - DEFENDANT_NAME, getPartyNameBasedOnType(caseData.getRespondent1()) - ); + if (caseData.isRespondent1NotRepresented()) { + return Map.of( + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + DEFENDANT_NAME, getPartyNameBasedOnType(caseData.getRespondent1()) + ); + } else { + return Map.of( + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + CLAIM_LEGAL_ORG_NAME_SPEC, organisationDetailsService.getRespondentLegalOrganizationName(caseData) + ); + } } } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateClaimRespondentNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateClaimRespondentNotificationHandlerTest.java index 80ae6965c89..91f50469330 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateClaimRespondentNotificationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateClaimRespondentNotificationHandlerTest.java @@ -9,6 +9,7 @@ import org.springframework.boot.test.mock.mockito.MockBean; import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest; import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.model.IdamUserDetails; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; import uk.gov.hmcts.reform.civil.service.FeatureToggleService; @@ -20,6 +21,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; @@ -91,6 +93,46 @@ void shouldNotifyApplicantSolicitor_whenInvokedWithCcEvent() { ); } + @Test + void shouldNotNotify_whenApplicantEmailIsNull() { + CaseData caseData = CaseDataBuilder.builder() + .atStateRespondentFullDefence() + .applicantSolicitor1UserDetails(IdamUserDetails.builder().email(null).build()) + .build(); + + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( + CallbackRequest.builder().eventId("NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIM_ISSUE_CC").build()).build(); + + handler.handle(params); + assertThatNoException(); + } + + @Test + void shouldNotNotify_whenRespondent1RecipientIsNull() { + CaseData caseData = CaseDataBuilder.builder() + .atStateRespondentFullDefence() + .respondentSolicitor1EmailAddress(null) + .build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( + CallbackRequest.builder().eventId("NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIM_ISSUE").build()).build(); + + handler.handle(params); + assertThatNoException(); + } + + @Test + void shouldNotNotify_whenRespondent2RecipientIsNull() { + CaseData caseData = CaseDataBuilder.builder() + .atStateRespondentFullDefence() + .respondentSolicitor2EmailAddress(null) + .build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( + CallbackRequest.builder().eventId("NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIM_ISSUE").build()).build(); + + handler.handle(params); + assertThatNoException(); + } + private Map getNotificationDataMap(CaseData caseData) { return Map.of( CLAIM_REFERENCE_NUMBER, LEGACY_CASE_REFERENCE, diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDOApplicantsNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDOApplicantsNotificationHandlerTest.java index c1f5b880a9c..c5bb04f3f96 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDOApplicantsNotificationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDOApplicantsNotificationHandlerTest.java @@ -16,6 +16,7 @@ import uk.gov.hmcts.reform.civil.sampledata.CallbackParamsBuilder; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.OrganisationService; import uk.gov.hmcts.reform.civil.prd.model.Organisation; @@ -45,6 +46,8 @@ public class CreateSDOApplicantsNotificationHandlerTest extends BaseCallbackHand private NotificationsProperties notificationsProperties; @MockBean private OrganisationService organisationService; + @MockBean + private FeatureToggleService featureToggleService; @Autowired private CreateSDOApplicantsNotificationHandler handler; @@ -82,6 +85,58 @@ private Map getNotificationDataMap(CaseData caseData) { } } + @Nested + class AboutToSubmitCallbackEA { + + @BeforeEach + void setup() { + when(notificationsProperties.getSdoOrderedEA()).thenReturn("template-id-EA"); + when(notificationsProperties.getSdoOrderedSpecEA()).thenReturn("template-id-spec-EA"); + when(featureToggleService.isEarlyAdoptersEnabled()).thenReturn(true); + when(organisationService.findOrganisationById(anyString())) + .thenReturn(Optional.of(Organisation.builder().name("Signer Name").build())); + } + + @Test + void shouldNotifyApplicantSolicitor_whenInvoked() { + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).build(); + + handler.handle(params); + + verify(notificationService).sendMail( + "applicantsolicitor@example.com", + "template-id-EA", + getNotificationDataMap(caseData), + "create-sdo-applicants-notification-000DC001" + ); + } + + @Test + void shouldNotifyApplicantSolicitorSpec_whenInvoked() { + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified() + .setClaimTypeToSpecClaim().build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).build(); + + handler.handle(params); + + verify(notificationService).sendMail( + "applicantsolicitor@example.com", + "template-id-spec-EA", + getNotificationDataMap(caseData), + "create-sdo-applicants-notification-000DC001" + ); + } + + @NotNull + private Map getNotificationDataMap(CaseData caseData) { + return Map.of( + CLAIM_REFERENCE_NUMBER, LEGACY_CASE_REFERENCE, + CLAIM_LEGAL_ORG_NAME_SPEC, "Signer Name" + ); + } + } + @Test void shouldReturnCorrectCamundaActivityId_whenInvoked() { assertThat(handler.camundaActivityId(CallbackParamsBuilder.builder().request(CallbackRequest.builder().eventId( diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent1NotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent1NotificationHandlerTest.java index 4bd78cd08a7..1c2fdca3e69 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent1NotificationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent1NotificationHandlerTest.java @@ -24,6 +24,7 @@ import uk.gov.hmcts.reform.civil.sampledata.CallbackParamsBuilder; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.sampledata.PartyBuilder; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.OrganisationService; import java.util.Map; @@ -54,12 +55,15 @@ public class CreateSDORespondent1NotificationHandlerTest extends BaseCallbackHan private NotificationsProperties notificationsProperties; @MockBean private OrganisationService organisationService; + @MockBean + private FeatureToggleService featureToggleService; @Autowired private CreateSDORespondent1NotificationHandler handler; private static final String DEFENDANT_EMAIL = "respondent@example.com"; private static final String LEGACY_REFERENCE = "create-sdo-respondent-1-notification-000DC001"; private static final String DEFENDANT_NAME = "respondent"; private static final String TEMPLATE_ID = "template-id"; + private static final String TEMPLATE_ID_EA = "template-id-EA"; private static final String ORG_NAME = "Signer Name"; @Nested @@ -68,8 +72,10 @@ class AboutToSubmitCallback { @BeforeEach void setup() { when(notificationsProperties.getSdoOrdered()).thenReturn(TEMPLATE_ID); + when(notificationsProperties.getSdoOrderedEA()).thenReturn(TEMPLATE_ID_EA); when(notificationsProperties.getSdoOrderedSpecBilingual()).thenReturn(TEMPLATE_ID); when(notificationsProperties.getSdoOrderedSpec()).thenReturn(TEMPLATE_ID); + when(notificationsProperties.getSdoOrderedSpecEA()).thenReturn(TEMPLATE_ID_EA); when(organisationService.findOrganisationById(anyString())) .thenReturn(Optional.of(Organisation.builder().name(ORG_NAME).build())); } @@ -95,6 +101,28 @@ void shouldNotifyRespondentSolicitor_whenInvoked() { ); } + @Test + void shouldNotifyRespondentSolicitor_whenInvokedEA() { + when(featureToggleService.isEarlyAdoptersEnabled()).thenReturn(true); + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build(); + CallbackParams params = CallbackParams.builder() + .caseData(caseData) + .type(ABOUT_TO_SUBMIT) + .request(CallbackRequest.builder() + .eventId(CaseEvent.NOTIFY_RESPONDENT_SOLICITOR1_SDO_TRIGGERED.name()) + .build()) + .build(); + + handler.handle(params); + + verify(notificationService).sendMail( + caseData.getRespondentSolicitor1EmailAddress(), + TEMPLATE_ID_EA, + getNotificationDataMap(caseData), + LEGACY_REFERENCE + ); + } + @Test void shouldNotifyRespondentLiP_whenInvoked() { CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build() @@ -120,6 +148,32 @@ void shouldNotifyRespondentLiP_whenInvoked() { ); } + @Test + void shouldNotifyRespondentLiP_whenInvokedEA() { + when(featureToggleService.isEarlyAdoptersEnabled()).thenReturn(true); + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build() + .toBuilder() + .respondent1Represented(YesOrNo.NO) + .caseAccessCategory(CaseCategory.SPEC_CLAIM) + .build(); + CallbackParams params = CallbackParams.builder() + .caseData(caseData) + .type(ABOUT_TO_SUBMIT) + .request(CallbackRequest.builder() + .eventId(CaseEvent.NOTIFY_RESPONDENT_SOLICITOR1_SDO_TRIGGERED.name()) + .build()) + .build(); + + handler.handle(params); + + verify(notificationService).sendMail( + caseData.getRespondent1().getPartyEmail(), + TEMPLATE_ID_EA, + getNotificationDataLipMap1(caseData), + LEGACY_REFERENCE + ); + } + @Test void shouldNotifyRespondentLiPWithBilingual_whenDefendantResponseIsBilingual() { Party party = PartyBuilder.builder() diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent2NotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent2NotificationHandlerTest.java index ff70f29e664..b8eea5b2ebf 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent2NotificationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/CreateSDORespondent2NotificationHandlerTest.java @@ -20,6 +20,7 @@ import uk.gov.hmcts.reform.civil.prd.model.Organisation; import uk.gov.hmcts.reform.civil.sampledata.CallbackParamsBuilder; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.OrganisationService; import java.util.Map; @@ -48,6 +49,8 @@ public class CreateSDORespondent2NotificationHandlerTest extends BaseCallbackHan private NotificationsProperties notificationsProperties; @MockBean private OrganisationService organisationService; + @MockBean + private FeatureToggleService featureToggleService; @Autowired private CreateSDORespondent2NotificationHandler handler; @@ -57,6 +60,7 @@ class AboutToSubmitCallback { @BeforeEach void setup() { when(notificationsProperties.getSdoOrdered()).thenReturn("template-id"); + when(notificationsProperties.getSdoOrderedEA()).thenReturn("template-id-ea"); when(organisationService.findOrganisationById(anyString())) .thenReturn(Optional.of(Organisation.builder().name("Signer Name").build())); } @@ -90,6 +94,36 @@ void shouldNotifyRespondentSolicitor_whenInvoked() { ); } + @Test + void shouldNotifyRespondentSolicitor_whenInvokedEA() { + when(featureToggleService.isEarlyAdoptersEnabled()).thenReturn(true); + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build() + .toBuilder() + .respondent2(Party.builder() + .type(Party.Type.COMPANY) + .companyName("Company 1") + .partyEmail("company@email.com") + .build()) + .respondent2Represented(YesOrNo.YES) + .build(); + CallbackParams params = CallbackParams.builder() + .caseData(caseData) + .type(ABOUT_TO_SUBMIT) + .request(CallbackRequest.builder() + .eventId(CaseEvent.NOTIFY_RESPONDENT_SOLICITOR2_SDO_TRIGGERED.name()) + .build()) + .build(); + + handler.handle(params); + + verify(notificationService).sendMail( + "respondentsolicitor2@example.com", + "template-id-ea", + getNotificationDataMap(caseData), + "create-sdo-respondent-2-notification-000DC001" + ); + } + @Test void shouldNotifyRespondentLiP_whenInvoked() { CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build() diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DJApplicantReceivedNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DJApplicantReceivedNotificationHandlerTest.java index 52e3fc5e75c..21968b80ada 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DJApplicantReceivedNotificationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DJApplicantReceivedNotificationHandlerTest.java @@ -10,6 +10,7 @@ import org.springframework.boot.test.mock.mockito.MockBean; import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest; import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.model.IdamUserDetails; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.model.CaseData; @@ -19,6 +20,7 @@ import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.sampledata.PartyBuilder; import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.OrganisationService; import uk.gov.hmcts.reform.civil.prd.model.Organisation; @@ -32,6 +34,7 @@ import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.DJApplicantReceivedNotificationHandler.TASK_ID; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.APPLICANT_ONE_NAME; import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.CLAIM_NUMBER; import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.DEFENDANT_NAME; import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.LEGAL_ORG_APPLICANT1; @@ -53,6 +56,8 @@ public class DJApplicantReceivedNotificationHandlerTest { private OrganisationService organisationService; @Autowired private DJApplicantReceivedNotificationHandler handler; + @MockBean + private FeatureToggleService featureToggleService; @Nested class AboutToSubmitCallback { @@ -63,8 +68,12 @@ void setup() { .thenReturn("test-template-received-id"); when(notificationsProperties.getApplicantSolicitor1DefaultJudgmentRequested()) .thenReturn("test-template-requested-id"); + when(notificationsProperties.getApplicantLiPDefaultJudgmentRequested()) + .thenReturn("test-template-requested-lip-id"); when(organisationService.findOrganisationById(anyString())) .thenReturn(Optional.of(Organisation.builder().name("Test Org Name").build())); + when(featureToggleService.isLipVLipEnabled()) + .thenReturn(false); } @Test @@ -134,6 +143,32 @@ void shouldNotifyApplicantSolicitor_whenInvokedAnd1v1AndBothNotSelected() { ); } + @Test + void shouldNotifyApplicantSolicitor_whenInvokedAndLiPvsLiPEnabled() { + when(featureToggleService.isLipVLipEnabled()) + .thenReturn(true); + //send Received email + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .respondent1Represented(YesOrNo.NO) + .applicant1Represented(YesOrNo.NO) + .addRespondent2(YesOrNo.NO) + .claimantUserDetails(IdamUserDetails.builder() + .id("f5e5cc53-e065-43dd-8cec-2ad005a6b9a9") + .email("test@gmail.com") + .build()) + .build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).build(); + + handler.handle(params); + + verify(notificationService).sendMail( + "rambo@email.com", + "test-template-requested-lip-id", + getLipvLiPData(caseData), + "default-judgment-applicant-received-notification-000DC001" + ); + } + @NotNull private Map getNotificationDataMap(CaseData caseData) { return Map.of( @@ -152,6 +187,16 @@ private Map getNotificationDataMapForRequested(CaseData caseData ); } + @NotNull + public Map getLipvLiPData(CaseData caseData) { + return Map.of( + APPLICANT_ONE_NAME, getPartyNameBasedOnType(caseData.getApplicant1()), + CLAIM_NUMBER, LEGACY_CASE_REFERENCE, + DEFENDANT_NAME, getPartyNameBasedOnType(caseData.getRespondent1()) + ); + + } + } @Test diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantClaimDetailsNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantClaimDetailsNotificationHandlerTest.java index f4b753b30dc..f86caa31001 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantClaimDetailsNotificationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantClaimDetailsNotificationHandlerTest.java @@ -9,6 +9,8 @@ import org.springframework.boot.test.mock.mockito.MockBean; import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest; import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.config.ToggleConfiguration; +import uk.gov.hmcts.reform.civil.model.IdamUserDetails; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; import uk.gov.hmcts.reform.civil.model.CaseData; @@ -21,7 +23,9 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; @@ -59,6 +63,9 @@ class DefendantClaimDetailsNotificationHandlerTest extends BaseCallbackHandlerTe @MockBean private DeadlinesCalculator deadlinesCalculator; + @MockBean + private ToggleConfiguration toggleConfiguration; + @Nested class AboutToSubmitCallback { private LocalDateTime responseDeadline; @@ -69,6 +76,7 @@ void setup() { when(notificationsProperties.getRespondentSolicitorClaimDetailsEmailTemplate()) .thenReturn(templateId); when(deadlinesCalculator.plus14DaysDeadline(any())).thenReturn(responseDeadline); + given(toggleConfiguration.getFeatureToggle()).willReturn("WA 4"); } @Test @@ -182,6 +190,57 @@ void shouldNotifyRespondentSolicitor_whenInvokedWithMultipartyEnabled() { ); } + @Test + void shouldNotNotifyRespondentSolicitor_when1v2SSRecipient1IsNull() { + CaseData caseData = CaseDataBuilder.builder() + .atStateRespondentFullDefenceAfterNotificationAcknowledgement() + .respondentSolicitor1EmailAddress(null) + .build(); + CallbackParams params = CallbackParamsBuilder.builder() + .of(ABOUT_TO_SUBMIT, caseData) + .request(CallbackRequest.builder() + .eventId(NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIM_DETAILS.name()) + .build()) + .build(); + + handler.handle(params); + assertThatNoException(); + } + + @Test + void shouldNotNotifyApplicantSolicitor_ApplicantRecipient1IsNull() { + CaseData caseData = CaseDataBuilder.builder() + .atStateRespondentFullDefenceAfterNotificationAcknowledgement() + .applicantSolicitor1UserDetails(IdamUserDetails.builder().email(null).build()) + .build(); + CallbackParams params = CallbackParamsBuilder.builder() + .of(ABOUT_TO_SUBMIT, caseData) + .request(CallbackRequest.builder() + .eventId(NOTIFY_RESPONDENT_SOLICITOR1_FOR_CLAIM_DETAILS_CC.name()) + .build()) + .build(); + + handler.handle(params); + assertThatNoException(); + } + + @Test + void shouldNotNotifyRespondentSolicitor_1v2DSRecipient1IsNull() { + CaseData caseData = CaseDataBuilder.builder() + .atStateRespondentFullDefenceAfterNotificationAcknowledgement() + .respondentSolicitor2EmailAddress(null) + .build(); + CallbackParams params = CallbackParamsBuilder.builder() + .of(ABOUT_TO_SUBMIT, caseData) + .request(CallbackRequest.builder() + .eventId(NOTIFY_RESPONDENT_SOLICITOR2_FOR_CLAIM_DETAILS.name()) + .build()) + .build(); + + handler.handle(params); + assertThatNoException(); + } + } @Test diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantResponseApplicantNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantResponseApplicantNotificationHandlerTest.java index b0f44a92d31..b9c5d6e3dee 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantResponseApplicantNotificationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/DefendantResponseApplicantNotificationHandlerTest.java @@ -85,7 +85,7 @@ void setup() { when(organisationService.findOrganisationById(anyString())) .thenReturn(Optional.of(Organisation.builder().name("Signer Name").build())); when(notificationsProperties.getClaimantSolicitorImmediatelyDefendantResponseForSpec()).thenReturn("templateImm-id"); - + when(notificationsProperties.getRespondentSolicitorDefResponseSpecWithClaimantAction()).thenReturn("spec-respondent-template-id-action"); } @Nested @@ -168,17 +168,17 @@ void shouldNotifyApplicantSolicitorSpec_whenInvoked() { LocalDate whenWillPay = LocalDate.now().plusMonths(1); CaseData caseData = CaseDataBuilder.builder() - .atStateNotificationAcknowledged() - .build().toBuilder() - .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.PART_ADMISSION) + .atStateNotificationAcknowledged() + .build().toBuilder() + .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.PART_ADMISSION) .respondent2ClaimResponseTypeForSpec(RespondentResponseTypeSpec.PART_ADMISSION) .defenceAdmitPartPaymentTimeRouteRequired(RespondentResponsePartAdmissionPaymentTimeLRspec.BY_SET_DATE) - .respondToClaimAdmitPartLRspec( - RespondToClaimAdmitPartLRspec.builder() + .respondToClaimAdmitPartLRspec( + RespondToClaimAdmitPartLRspec.builder() .whenWillThisAmountBePaid(whenWillPay) .build() - ) - .build(); + ) + .build(); caseData = caseData.toBuilder().caseAccessCategory(SPEC_CLAIM).build(); CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( CallbackRequest.builder().eventId("NOTIFY_APPLICANT_SOLICITOR1_FOR_DEFENDANT_RESPONSE").build()) @@ -341,6 +341,29 @@ void shouldNotifyRespondentSolicitorSpecDef1_whenInvokedWithCcEvent() { handler.handle(params); + verify(notificationService).sendMail( + "respondentsolicitor@example.com", + "spec-respondent-template-id", + getNotificationDataMapPartAdmissionSpec(caseData), + "defendant-response-applicant-notification-000DC001" + ); + } + + @Test + void sendNotificationToSolicitorSpec_shouldNotifyRespondentSolicitorSpecDef1v1() { + CaseData caseData = CaseDataBuilder.builder() + .atStateNotificationAcknowledged().build(); + caseData = caseData.toBuilder().caseAccessCategory(SPEC_CLAIM) + .respondent1DQ(Respondent1DQ.builder().build()) + .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_DEFENCE) + .build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( + CallbackRequest.builder().eventId("NOTIFY_APPLICANT_SOLICITOR1_FOR_DEFENDANT_RESPONSE_CC") + .build()) + .build(); + + handler.handle(params); + verify(notificationService).sendMail( "respondentsolicitor@example.com", "spec-respondent-template-id", @@ -349,6 +372,30 @@ void shouldNotifyRespondentSolicitorSpecDef1_whenInvokedWithCcEvent() { ); } + @Test + void sendNotificationToSolicitorSpecPart_shouldNotifyRespondentSolicitorSpecDef1v1() { + CaseData caseData = CaseDataBuilder.builder() + .atStateNotificationAcknowledged().build(); + caseData = caseData.toBuilder().caseAccessCategory(SPEC_CLAIM) + .respondent1DQ(Respondent1DQ.builder().build()) + .defenceAdmitPartPaymentTimeRouteRequired(RespondentResponsePartAdmissionPaymentTimeLRspec.IMMEDIATELY) + .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.PART_ADMISSION) + .build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).request( + CallbackRequest.builder().eventId("NOTIFY_APPLICANT_SOLICITOR1_FOR_DEFENDANT_RESPONSE_CC") + .build()) + .build(); + + handler.handle(params); + + verify(notificationService).sendMail( + "respondentsolicitor@example.com", + "spec-respondent-template-id-action", + getNotificationDataMapSpec(caseData), + "defendant-response-applicant-notification-000DC001" + ); + } + @Test void shouldNotifyRespondentSolicitorSpecDef1SecondScenerio_whenInvokedWithCcEvent() { CaseData caseData = CaseDataBuilder.builder() @@ -546,6 +593,15 @@ private Map getNotificationDataMapImmediatelySpec(CaseData caseD ); } + + private Map getNotificationDataMapPartAdmissionSpec(CaseData caseData) { + return Map.of( + "defendantName", "Mr. Sole Trader", + CLAIM_LEGAL_ORG_NAME_SPEC, "Signer Name", + CLAIM_REFERENCE_NUMBER, LEGACY_CASE_REFERENCE + ); + } + } @Test diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotificationClaimantOfHearingHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotificationClaimantOfHearingHandlerTest.java index c53ea10e96f..d2484a2c490 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotificationClaimantOfHearingHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotificationClaimantOfHearingHandlerTest.java @@ -154,13 +154,17 @@ void shouldNotifyApplicantSolicitor_whenInvokedWithFeeAnd1v1WithNoFee() { .applicantSolicitor1UserDetails(IdamUserDetails.builder().email("applicantemail@hmcts.net").build()) .respondentSolicitor1EmailAddress("respondent1email@hmcts.net") .hearingReferenceNumber("000HN001") - .hearingFee(Fee.builder().calculatedAmountInPence(BigDecimal.valueOf(0)).build()) + .hearingFee(Fee.builder().calculatedAmountInPence(BigDecimal.valueOf(30000)).build()) + .hearingFeePaymentDetails(PaymentDetails.builder() + .status(SUCCESS) + .build()) .hearingDueDate(null) .hearingTimeHourMinute("1530") .addApplicant2(YesOrNo.NO) .addRespondent2(YesOrNo.NO) .solicitorReferences(null) .build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData) .request(CallbackRequest.builder().eventId("NOTIFY_CLAIMANT_HEARING").build()).build(); // When @@ -224,6 +228,8 @@ void shouldNotifyApplicantSolicitor_whenInvokedWithFeeAnd1v1WithNoSolicitorRefer .respondentSolicitor1EmailAddress("respondent1email@hmcts.net") .hearingReferenceNumber("000HN001") .hearingTimeHourMinute("1530") + .hearingFee(Fee.builder().calculatedAmountInPence(BigDecimal.valueOf(30000)).build()) + .hearingDueDate(LocalDate.of(2022, 10, 6)) .addApplicant2(YesOrNo.NO) .addRespondent2(YesOrNo.NO) .solicitorReferences(SolicitorReferences.builder().build()) @@ -235,8 +241,8 @@ void shouldNotifyApplicantSolicitor_whenInvokedWithFeeAnd1v1WithNoSolicitorRefer // Then verify(notificationService).sendMail( "applicantemail@hmcts.net", - "test-template-no-fee-claimant-id", - getNotificationNoFeeDatePMDataMap(caseData), + "test-template-fee-claimant-id", + getNotificationFeeDatePMDataMap(caseData), "notification-of-hearing-000HN001" ); } @@ -306,7 +312,11 @@ void shouldNotifyApplicantSolicitor_whenInvokedNoFeeAnd1v1() { .respondentSolicitor1EmailAddress("respondent1email@hmcts.net") .hearingReferenceNumber("000HN001") .hearingTimeHourMinute("0830") + .hearingFee(Fee.builder().calculatedAmountInPence(BigDecimal.valueOf(30000)).build()) .hearingDueDate(LocalDate.of(2022, 11, 23)) + .hearingFeePaymentDetails(PaymentDetails.builder() + .status(SUCCESS) + .build()) .addApplicant2(YesOrNo.NO) .addRespondent2(YesOrNo.NO) .build(); @@ -333,7 +343,11 @@ void shouldNotifyApplicantSolicitor_whenInvokedNoFeeAnd1v2() { .respondentSolicitor2EmailAddress("respondent2email@hmcts.net") .hearingReferenceNumber("000HN001") .hearingTimeHourMinute("0830") + .hearingFee(Fee.builder().calculatedAmountInPence(BigDecimal.valueOf(30000)).build()) .hearingDueDate(LocalDate.of(2022, 11, 23)) + .hearingFeePaymentDetails(PaymentDetails.builder() + .status(SUCCESS) + .build()) .addApplicant2(YesOrNo.NO) .addRespondent2(YesOrNo.YES) .respondent2(Party.builder().type(Party.Type.COMPANY).companyName("Party2").build()) @@ -360,7 +374,11 @@ void shouldNotifyApplicantSolicitor_whenInvokedNoFeeAnd2v1() { .respondentSolicitor1EmailAddress("respondent1email@hmcts.net") .hearingReferenceNumber("000HN001") .hearingTimeHourMinute("0830") + .hearingFee(Fee.builder().calculatedAmountInPence(BigDecimal.valueOf(30000)).build()) .hearingDueDate(LocalDate.of(2022, 11, 23)) + .hearingFeePaymentDetails(PaymentDetails.builder() + .status(SUCCESS) + .build()) .addApplicant2(YesOrNo.YES) .addRespondent2(YesOrNo.NO) .build(); @@ -424,8 +442,7 @@ private Map getNotificationFeeDataMapHMC(CaseData caseData) { private Map getNotificationNoFeeDataMap(CaseData caseData) { return Map.of( CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), - "claimantReferenceNumber", "12345", "hearingFee", "£0.00", - "hearingDate", "07-10-2022", "hearingTime", "08:30am", "hearingDueDate", "23-11-2022" + "claimantReferenceNumber", "12345", "hearingDate", "07-10-2022", "hearingTime", "08:30am" ); } @@ -437,12 +454,20 @@ private Map getNotificationNoFeeDataMapHMC(CaseData caseData) { ); } + @NotNull + private Map getNotificationFeeDatePMDataMap(CaseData caseData) { + return Map.of( + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + "claimantReferenceNumber", "", "hearingFee", "£300.00", + "hearingDate", "07-10-2022", "hearingTime", "03:30pm", "hearingDueDate", "06-10-2022" + ); + } + @NotNull private Map getNotificationNoFeeDatePMDataMap(CaseData caseData) { return Map.of( CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), - "claimantReferenceNumber", "", "hearingFee", "£0.00", - "hearingDate", "07-10-2022", "hearingTime", "03:30pm", "hearingDueDate", "" + "claimantReferenceNumber", "", "hearingDate", "07-10-2022", "hearingTime", "03:30pm" ); } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotifyClaimantClaimSubmittedTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotifyClaimantClaimSubmittedTest.java new file mode 100644 index 00000000000..e7eacfc0f36 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotifyClaimantClaimSubmittedTest.java @@ -0,0 +1,137 @@ +package uk.gov.hmcts.reform.civil.handler.callback.camunda.notification; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; +import uk.gov.hmcts.reform.civil.model.citizenui.HelpWithFees; +import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; +import uk.gov.hmcts.reform.civil.sampledata.CallbackParamsBuilder; +import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; +import uk.gov.hmcts.reform.civil.sampledata.PartyBuilder; + +import java.util.Map; + +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.CLAIMANT_NAME; + +@SpringBootTest(classes = { + NotifyClaimantClaimSubmitted.class, + JacksonAutoConfiguration.class +}) +public class NotifyClaimantClaimSubmittedTest extends BaseCallbackHandlerTest { + + @MockBean + private NotificationService notificationService; + @MockBean + private NotificationsProperties notificationsProperties; + @Autowired + private NotifyClaimantClaimSubmitted handler; + + @Nested + class AboutToSubmitCallback { + + private static final String EMAIL_TEMPLATE = "test-notification-id"; + private static final String CLAIMANT_EMAIL_ID = "testorg@email.com"; + private static final String REFERENCE_NUMBER = "claim-submitted-notification-000DC001"; + private static final String CLAIMANT = "Mr. John Rambo"; + + @BeforeEach + void setup() { + when(notificationsProperties.getNotifyLiPClaimantClaimSubmittedAndPayClaimFeeTemplate()).thenReturn( + EMAIL_TEMPLATE); + } + + @Test + void shouldNotifyApplicant1_ClaimIsSubmittedButNotIssued() { + // Given + CaseData caseData = CaseDataBuilder.builder().atStateClaimSubmitted().build().toBuilder() + .applicant1(PartyBuilder.builder().individual().build().toBuilder() + .partyEmail(CLAIMANT_EMAIL_ID) + .build()) + .respondent1(PartyBuilder.builder().soleTrader().build().toBuilder() + .build()) + .build(); + + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).build(); + + // When + handler.handle(params); + + // Then + verify(notificationService, times(1)).sendMail( + CLAIMANT_EMAIL_ID, + EMAIL_TEMPLATE, + getNotificationDataMap(caseData), + REFERENCE_NUMBER + ); + } + + @Test + void shouldNotSendEmail_whenEventIsCalledAndDefendantHasNoEmail() { + //Given + CaseData caseData = CaseDataBuilder.builder().atStateClaimSubmitted().build().toBuilder() + .applicant1(PartyBuilder.builder().individual().build().toBuilder() + .build()) + .respondent1(PartyBuilder.builder().soleTrader().build().toBuilder() + .build()) + .build(); + + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).build(); + + // When + handler.handle(params); + + // Then + verify(notificationService, times(0)).sendMail( + CLAIMANT_EMAIL_ID, + EMAIL_TEMPLATE, + getNotificationDataMap(caseData), + REFERENCE_NUMBER + ); + } + + @Test + void shouldNotSendEmail_whenHFWReferanceNumberPresent() { + //Given + CaseData caseData = CaseDataBuilder.builder().atStateClaimSubmitted().build().toBuilder() + .applicant1(PartyBuilder.builder().individual().build().toBuilder() + .build()) + .respondent1(PartyBuilder.builder().soleTrader().build().toBuilder() + .build()) + .caseDataLiP(CaseDataLiP.builder().helpWithFees(HelpWithFees.builder().helpWithFeesReferenceNumber("1111").build()).build()) + .build(); + + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).build(); + + // When + handler.handle(params); + + // Then + verify(notificationService, times(0)).sendMail( + CLAIMANT_EMAIL_ID, + EMAIL_TEMPLATE, + getNotificationDataMap(caseData), + REFERENCE_NUMBER + ); + } + + private Map getNotificationDataMap(CaseData caseData) { + return Map.of( + CLAIMANT_NAME, CLAIMANT + ); + } + + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotifyLIPDefendantClaimantSettleTheClaimTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotifyLIPDefendantClaimantSettleTheClaimTest.java new file mode 100644 index 00000000000..6558c5612ce --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/NotifyLIPDefendantClaimantSettleTheClaimTest.java @@ -0,0 +1,91 @@ +package uk.gov.hmcts.reform.civil.handler.callback.camunda.notification; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; +import uk.gov.hmcts.reform.civil.sampledata.CallbackParamsBuilder; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.NOTIFY_DEFENDANT_CLAIMANT_SETTLE_THE_CLAIM; + +@SpringBootTest(classes = { + NotifyLIPDefendantClaimantSettleTheClaim.class, + JacksonAutoConfiguration.class, +}) +public class NotifyLIPDefendantClaimantSettleTheClaimTest extends BaseCallbackHandlerTest { + + @Autowired + private NotifyLIPDefendantClaimantSettleTheClaim notificationHandler; + @MockBean + private NotificationService notificationService; + @MockBean + NotificationsProperties notificationsProperties; + @Captor + private ArgumentCaptor targetEmail; + @Captor + private ArgumentCaptor emailTemplate; + @Captor + private ArgumentCaptor> notificationDataMap; + @Captor + private ArgumentCaptor reference; + + @Nested + class AboutToSubmitCallback { + + private static final String DEFENDANT_EMAIL_ADDRESS = "defendantmail@hmcts.net"; + private static final String DEFENDANT_PARTY_NAME = "ABC ABC"; + private static final String REFERENCE_NUMBER = "8372942374"; + private static final String EMAIL_TEMPLATE = "test-notification-id"; + private static final String CLAIMANT_ORG_NAME = "Org Name"; + + @BeforeEach + void setUp() { + given(notificationsProperties.getNotifyDefendantLIPClaimantSettleTheClaimTemplate()).willReturn(EMAIL_TEMPLATE); + } + + @Test + void shouldSendNotificationToDefendantLip_whenEventIsCalledAndDefendantHasEmail() { + //Given + CaseData caseData = CaseData.builder() + .respondent1(Party.builder().type(Party.Type.COMPANY).companyName(DEFENDANT_PARTY_NAME).partyEmail( + DEFENDANT_EMAIL_ADDRESS).build()) + .applicant1(Party.builder().type(Party.Type.COMPANY).companyName(CLAIMANT_ORG_NAME).build()) + .legacyCaseReference(REFERENCE_NUMBER) + .addApplicant2(YesOrNo.NO) + .addRespondent2(YesOrNo.NO) + .build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData) + .request(CallbackRequest.builder().eventId(NOTIFY_DEFENDANT_CLAIMANT_SETTLE_THE_CLAIM.name()).build()).build(); + //When + notificationHandler.handle(params); + //Then + verify(notificationService, times(1)).sendMail(targetEmail.capture(), + emailTemplate.capture(), + notificationDataMap.capture(), reference.capture() + ); + assertThat(targetEmail.getAllValues().get(0)).isEqualTo(DEFENDANT_EMAIL_ADDRESS); + assertThat(emailTemplate.getAllValues().get(0)).isEqualTo(EMAIL_TEMPLATE); + } + + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ResponseDeadlineExtensionClaimantNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ResponseDeadlineExtensionClaimantNotificationHandlerTest.java index 01d3ad788fa..62a6ff2fee7 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ResponseDeadlineExtensionClaimantNotificationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/camunda/notification/ResponseDeadlineExtensionClaimantNotificationHandlerTest.java @@ -10,6 +10,8 @@ import org.springframework.boot.test.mock.mockito.MockBean; import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest; import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.config.PinInPostConfiguration; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.notify.NotificationsProperties; import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec; import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; @@ -17,10 +19,12 @@ import uk.gov.hmcts.reform.civil.sampledata.CallbackParamsBuilder; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.notify.NotificationService; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.OrganisationService; import uk.gov.hmcts.reform.civil.prd.model.Organisation; import java.time.LocalDate; +import java.time.LocalDateTime; import java.util.Map; import java.util.Optional; @@ -30,11 +34,15 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; -import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.ResponseDeadlineExtensionClaimantNotificationHandler.TASK_ID; import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.RESPONDENT_NAME; import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.CLAIM_LEGAL_ORG_NAME_SPEC; import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.CLAIM_REFERENCE_NUMBER; import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.AGREED_EXTENSION_DATE; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.CLAIMANT_NAME; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.DEFENDANT_NAME; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.RESPONSE_DEADLINE; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.FRONTEND_URL; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.ResponseDeadlineExtensionClaimantNotificationHandler.TASK_ID; import static uk.gov.hmcts.reform.civil.helpers.DateFormatHelper.DATE; import static uk.gov.hmcts.reform.civil.helpers.DateFormatHelper.formatLocalDate; @@ -50,7 +58,10 @@ class ResponseDeadlineExtensionClaimantNotificationHandlerTest extends BaseCallb private NotificationsProperties notificationsProperties; @MockBean private OrganisationService organisationService; - + @MockBean + private FeatureToggleService toggleService; + @MockBean + private PinInPostConfiguration pipInPostConfiguration; @Autowired private ResponseDeadlineExtensionClaimantNotificationHandler handler; @@ -59,6 +70,8 @@ class AboutToSubmitCallback { private final String emailTemplate = "emailTemplate2"; private final String claimantEmail = "applicantsolicitor@example.com"; + private final String claimantLipEmail = "rambo@email.com"; + private final String emailLipTemplate = "emailTemplateLip"; private final String legacyReference = "000DC001"; @BeforeEach @@ -66,6 +79,10 @@ void setUp() { when(organisationService.findOrganisationById(anyString())) .thenReturn(Optional.of(Organisation.builder().name("Signer Name").build())); given(notificationsProperties.getClaimantDeadlineExtension()).willReturn(emailTemplate); + given(notificationsProperties.getClaimantLipDeadlineExtension()).willReturn(emailLipTemplate); + when(toggleService.isLipVLipEnabled()).thenReturn(false); + when(pipInPostConfiguration.getCuiFrontEndUrl()).thenReturn("url"); + } @Test @@ -104,5 +121,38 @@ AGREED_EXTENSION_DATE, formatLocalDate(caseData.getRespondentSolicitor1AgreedDea ); } + @Test + void shouldSendEmailToClaimantLip() { + when(toggleService.isLipVLipEnabled()).thenReturn(true); + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified() + .build().toBuilder() + .respondent1Represented(YesOrNo.NO) + .specRespondent1Represented(YesOrNo.NO) + .applicant1Represented(YesOrNo.NO) + .respondent1ResponseDeadline(LocalDateTime.now()) + .build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_SUBMIT, caseData).build(); + + handler.handle(params); + + verify(notificationService).sendMail( + claimantLipEmail, + emailLipTemplate, + getNotificationDataMapForLip(caseData), + "claimant-deadline-extension-notification-" + legacyReference + ); + } + + @NotNull + private Map getNotificationDataMapForLip(CaseData caseData) { + return Map.of( + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + CLAIMANT_NAME, "Mr. John Rambo", + DEFENDANT_NAME, "Mr. Sole Trader", + FRONTEND_URL, "url", + RESPONSE_DEADLINE, formatLocalDate( + caseData.getRespondent1ResponseDeadline().toLocalDate(), DATE) + ); + } } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/AcknowledgeOfServiceCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/AcknowledgeOfServiceCallbackHandlerTest.java index fd63d074f3c..dd3ad237cd7 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/AcknowledgeOfServiceCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/AcknowledgeOfServiceCallbackHandlerTest.java @@ -239,6 +239,46 @@ void aboutToSubmit_NewResponseDeadline() { .getData().get("respondent1ResponseDeadline").toString()) .isEqualTo(newDeadline); } + + @Test + void aboutToSubmit_NewResponseDeadline1v2() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimDetailsNotified() + .multiPartyClaimTwoDefendantSolicitors() + .respondent1Copy(Party.builder().partyName("Party 2").primaryAddress( + Address + .builder() + .addressLine1("Triple street") + .postCode("Postcode") + .build()) + .build()) + .respondent2Copy(Party.builder().partyName("Respondent 2").primaryAddress( + Address + .builder() + .addressLine1("Triple street") + .postCode("Postcode") + .build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, CallbackType.ABOUT_TO_SUBMIT); + CallbackRequest request = CallbackRequest.builder() + .build(); + params = params.toBuilder().request(request).build(); + + Mockito.when(deadlinesCalculator.plus14DaysAt4pmDeadline(caseData.getRespondent1ResponseDeadline())) + .thenReturn(caseData.getRespondent1ResponseDeadline() + .plusDays(14) + .withHour(16) + .withMinute(0) + .withSecond(1)); + + String newDeadline = LocalDateTime.now().plusDays(28).withHour(16).withMinute(0).withSecond(1).truncatedTo(ChronoUnit.SECONDS).toString(); + + CallbackResponse response = handler.handle(params); + assertThat(((AboutToStartOrSubmitCallbackResponse) response) + .getData().get("respondent1ResponseDeadline").toString()) + .isEqualTo(newDeadline); + } } @Nested diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/AddCaseNoteCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/AddCaseNoteCallbackHandlerTest.java index 97cd47172d9..d5bfcfcbd81 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/AddCaseNoteCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/AddCaseNoteCallbackHandlerTest.java @@ -90,12 +90,12 @@ void shouldAddCaseNoteToList_whenInvoked() { when(caseNoteService.buildCaseNote(params.getParams().get(BEARER_TOKEN).toString(), "Example case note")) .thenReturn(expectedCaseNote); - when(caseNoteService.addNoteToList(expectedCaseNote, caseData.getCaseNotes())).thenReturn(updatedCaseNotes); + when(caseNoteService.addNoteToListStart(expectedCaseNote, caseData.getCaseNotes())).thenReturn(updatedCaseNotes); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); verify(caseNoteService).buildCaseNote(params.getParams().get(BEARER_TOKEN).toString(), "Example case note"); - verify(caseNoteService).addNoteToList(expectedCaseNote, caseData.getCaseNotes()); + verify(caseNoteService).addNoteToListStart(expectedCaseNote, caseData.getCaseNotes()); assertThat(response.getData()) .doesNotHaveToString("caseNote"); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/ClaimantResponseCuiCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/ClaimantResponseCuiCallbackHandlerTest.java index 4d41d5a5dcd..8c889304389 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/ClaimantResponseCuiCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/ClaimantResponseCuiCallbackHandlerTest.java @@ -1,41 +1,79 @@ package uk.gov.hmcts.reform.civil.handler.callback.user; import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit.jupiter.SpringExtension; import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.enums.CaseState; import uk.gov.hmcts.reform.civil.enums.MediationDecision; import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.helpers.LocationHelper; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.Party; import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; import uk.gov.hmcts.reform.civil.model.citizenui.ClaimantMediationLip; +import uk.gov.hmcts.reform.civil.model.defaultjudgment.CaseLocationCivil; +import uk.gov.hmcts.reform.civil.model.dq.Applicant1DQ; +import uk.gov.hmcts.reform.civil.model.dq.RequestedCourt; +import uk.gov.hmcts.reform.civil.model.dq.Respondent1DQ; +import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; +import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; +import uk.gov.hmcts.reform.civil.service.citizen.UpdateCaseManagementDetailsService; +import uk.gov.hmcts.reform.civil.service.citizenui.ResponseOneVOneShowTagService; +import uk.gov.hmcts.reform.civil.utils.CourtLocationUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CLAIMANT_RESPONSE_CUI; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; +import static uk.gov.hmcts.reform.civil.model.Party.Type.COMPANY; +import static uk.gov.hmcts.reform.civil.model.Party.Type.ORGANISATION; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = { ClaimantResponseCuiCallbackHandler.class, - JacksonAutoConfiguration.class + JacksonAutoConfiguration.class, + ResponseOneVOneShowTagService.class, + JacksonAutoConfiguration.class, + CourtLocationUtils.class, + LocationRefDataService.class, + LocationHelper.class, + UpdateCaseManagementDetailsService.class }) class ClaimantResponseCuiCallbackHandlerTest extends BaseCallbackHandlerTest { + @Autowired + private CourtLocationUtils courtLocationUtility; + @MockBean + private LocationHelper locationHelper; + @MockBean + private LocationRefDataService locationRefDataService; @Autowired private ClaimantResponseCuiCallbackHandler handler; + private static final String courtLocation = "Site 1 - Adr 1 - AAA 111"; @Autowired private final ObjectMapper mapper = new ObjectMapper(); + @MockBean + private ResponseOneVOneShowTagService responseOneVOneShowTagService; + @Nested class AboutToStartCallback { @@ -53,9 +91,21 @@ void shouldReturnNoError_WhenAboutToStartIsInvoked() { @Nested class AboutToSubmitCallback { + @BeforeEach + void before() { + LocationRefData locationRefData = LocationRefData.builder().siteName("Site 1").courtAddress("Adr 1").postcode("AAA 111") + .courtName("Court Name").region("Region").regionId("1").courtVenueId("1") + .courtTypeId("10").courtLocationCode("court1") + .epimmsId("111").build(); + given(locationRefDataService.getCourtLocationsForDefaultJudgments(any())) + .willReturn(getSampleCourLocationsRefObject()); + given(locationHelper.updateCaseManagementLocation(any(), any(), any())).willReturn(Optional.ofNullable(locationRefData)); + } + @Test void shouldUpdateBusinessProcess() { CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued1v1LiP() .caseDataLip( CaseDataLiP.builder() .applicant1ClaimMediationSpecRequiredLip( @@ -80,10 +130,28 @@ void shouldUpdateBusinessProcess() { @Test void shouldOnlyUpdateClaimStatus_whenPartAdmitNotSettled_NoMediation() { + Applicant1DQ applicant1DQ = + Applicant1DQ.builder().applicant1DQRequestedCourt(RequestedCourt.builder() + .responseCourtCode("court1") + .caseLocation(CaseLocationCivil.builder() + .region(courtLocation) + .baseLocation(courtLocation) + .build()) + .build()).build(); + Respondent1DQ respondent1DQ = + Respondent1DQ.builder().respondent1DQRequestedCourt(RequestedCourt.builder() + .responseCourtCode("court2") + .caseLocation(CaseLocationCivil.builder() + .region(courtLocation) + .baseLocation(courtLocation) + .build()) + .build()).build(); CaseData caseData = CaseDataBuilder.builder() .atStateClaimIssued() .applicant1PartAdmitConfirmAmountPaidSpec(NO) .applicant1PartAdmitIntentionToSettleClaimSpec(NO) + .applicant1DQ(applicant1DQ) + .respondent1DQ(respondent1DQ) .applicant1AcceptAdmitAmountPaidSpec(NO) .caseDataLip(CaseDataLiP.builder().applicant1ClaimMediationSpecRequiredLip(ClaimantMediationLip.builder().hasAgreedFreeMediation( MediationDecision.No).build()) @@ -102,6 +170,80 @@ void shouldOnlyUpdateClaimStatus_whenPartAdmitNotSettled_NoMediation() { .extracting("status") .isEqualTo("READY"); + assertThat(response.getState()).isEqualTo(CaseState.JUDICIAL_REFERRAL.name()); + CaseData data = mapper.convertValue(response.getData(), CaseData.class); + assertThat(data.getApplicant1DQ().getApplicant1DQRequestedCourt().getResponseCourtCode()).isEqualTo("court1"); + assertThat(data.getCaseNameHmctsInternal()).isEqualTo(data.getApplicant1().getPartyName() + " v " + data.getRespondent1().getPartyName()); + } + + @Test + void shouldChangeCaseState_whenApplicantRejectClaimSettlementAndAgreeToMediation() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued() + .applicant1PartAdmitConfirmAmountPaidSpec(NO) + .caseDataLip(CaseDataLiP.builder().applicant1ClaimMediationSpecRequiredLip(ClaimantMediationLip.builder().hasAgreedFreeMediation( + MediationDecision.Yes).build()) + .build()) + .build(); + + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getState()).isEqualTo(CaseState.IN_MEDIATION.name()); + } + + protected List getSampleCourLocationsRefObject() { + return new ArrayList<>(List.of( + LocationRefData.builder() + .epimmsId("111").siteName("Site 1").courtAddress("Adr 1").postcode("AAA 111") + .courtLocationCode("court1").build(), + LocationRefData.builder() + .epimmsId("222").siteName("Site 2").courtAddress("Adr 2").postcode("BBB 222") + .courtLocationCode("court2").build(), + LocationRefData.builder() + .epimmsId("333").siteName("Site 3").courtAddress("Adr 3").postcode("CCC 333") + .courtLocationCode("court3").build() + )); + } + + @Test + void shouldChangeCaseState_whenApplicantRejectRepaymentPlanAndIsCompany_toAllFinalOrdersIssued() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued() + .applicant1AcceptPartAdmitPaymentPlanSpec(NO) + .respondent1(Party.builder() + .type(COMPANY) + .companyName("Test Inc") + .build()) + .build(); + + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getState()).isEqualTo(CaseState.PROCEEDS_IN_HERITAGE_SYSTEM.name()); + } + + @Test + void shouldChangeCaseState_whenApplicantRejectRepaymentPlanAndIsOrganisation_toAllFinalOrdersIssued() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued() + .applicant1AcceptPartAdmitPaymentPlanSpec(NO) + .respondent1(Party.builder() + .type(ORGANISATION) + .companyName("Test Inc") + .build()) + .build(); + + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getState()).isEqualTo(CaseState.PROCEEDS_IN_HERITAGE_SYSTEM.name()); } } + + @Test + void handleEventsReturnsTheExpectedCallbackEvents() { + assertThat(handler.handledEvents()).containsOnly(CLAIMANT_RESPONSE_CUI); + } + } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimCallbackHandlerTest.java index 0b94819df8e..71b10419903 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimCallbackHandlerTest.java @@ -21,6 +21,7 @@ import uk.gov.hmcts.reform.civil.config.ClaimUrlsConfiguration; import uk.gov.hmcts.reform.civil.config.ExitSurveyConfiguration; import uk.gov.hmcts.reform.civil.config.MockDatabaseConfiguration; +import uk.gov.hmcts.reform.civil.config.ToggleConfiguration; import uk.gov.hmcts.reform.civil.documentmanagement.model.Document; import uk.gov.hmcts.reform.civil.enums.CaseCategory; import uk.gov.hmcts.reform.civil.enums.YesOrNo; @@ -116,7 +117,8 @@ ValidationAutoConfiguration.class, ValidateEmailService.class, OrganisationService.class, - AssignCategoryId.class}, + AssignCategoryId.class, + ToggleConfiguration.class}, properties = {"reference.database.enabled=false"}) class CreateClaimCallbackHandlerTest extends BaseCallbackHandlerTest { @@ -171,6 +173,9 @@ class CreateClaimCallbackHandlerTest extends BaseCallbackHandlerTest { @Value("${civil.response-pack-url}") private String responsePackLink; + @MockBean + private ToggleConfiguration toggleConfiguration; + @Test void handleEventsReturnsTheExpectedCallbackEvent() { assertThat(handler.handledEvents()).contains(CREATE_CLAIM); @@ -374,6 +379,7 @@ class MidEventFeeCallback { @BeforeEach void setup() { given(feesService.getFeeDataByClaimValue(any())).willReturn(feeData); + given(toggleConfiguration.getFeatureToggle()).willReturn("WA 4"); } @Test @@ -458,6 +464,11 @@ class MidEventStartClaimCallback { private static final String PAGE_ID = "start-claim"; + @BeforeEach + void setup() { + given(toggleConfiguration.getFeatureToggle()).willReturn("WA 4"); + } + @Test void shouldAddClaimStartedFlagToData_whenInvoked() { CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build(); @@ -1137,9 +1148,9 @@ void shouldCopyRespondent1OrgPolicyReferenceForSameRegisteredSolicitorScenario_w assertThat(respondent2OrgPolicy).extracting("OrgPolicyReference").isEqualTo("org1PolicyReference"); assertThat(respondent2OrgPolicy) - .extracting("Organisation").extracting("OrganisationID") - .isEqualTo("org1"); + .extracting("Organisation").extracting("OrganisationID").isNull(); assertThat(respondentSolicitor2EmailAddress).isEqualTo("respondentsolicitor@example.com"); + assertThat(response.getData()).extracting("respondent2OrganisationIDCopy").isEqualTo("org1"); } @Test @@ -1520,9 +1531,13 @@ void shouldUpdateCaseListAndUnassignedListData() { .build()) .respondent1OrganisationPolicy(OrganisationPolicy.builder() .orgPolicyReference("DEFENDANTREF1") + .organisation(uk.gov.hmcts.reform.ccd.model.Organisation.builder() + .organisationID("QWERTY R").build()) .build()) .respondent2OrganisationPolicy(OrganisationPolicy.builder() .orgPolicyReference("DEFENDANTREF2") + .organisation(uk.gov.hmcts.reform.ccd.model.Organisation.builder() + .organisationID("QWERTY R2").build()) .build()) .build(); @@ -1536,6 +1551,59 @@ void shouldUpdateCaseListAndUnassignedListData() { .containsEntry("caseListDisplayDefendantSolicitorReferences", "6789, 01234"); } + @Test + void shouldUpdateRespondent1Organisation1IDCopySameSol() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued1v2AndSameRepresentative() + .respondent1OrganisationPolicy(OrganisationPolicy.builder() + .orgPolicyReference("DEFENDANTREF1") + .organisation(uk.gov.hmcts.reform.ccd.model.Organisation.builder() + .organisationID("QWERTY R").build()) + .build()) + .build(); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle( + callbackParamsOf(caseData, ABOUT_TO_SUBMIT)); + + assertThat(response.getData()) + .extracting("respondent1OrganisationIDCopy") + .isEqualTo("QWERTY R"); + assertThat(response.getData()) + .extracting("respondent2OrganisationIDCopy") + .isEqualTo("QWERTY R"); + } + + @Test + void shouldUpdateRespondent1And2Organisation1IDCopy() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimDraft() + .multiPartyClaimTwoDefendantSolicitors() + .applicant1OrganisationPolicy(OrganisationPolicy.builder() + .orgPolicyReference("CLAIMANTREF1") + .build()) + .respondent1OrganisationPolicy(OrganisationPolicy.builder() + .orgPolicyReference("DEFENDANTREF1") + .organisation(uk.gov.hmcts.reform.ccd.model.Organisation.builder() + .organisationID("QWERTY R").build()) + .build()) + .respondent2OrganisationPolicy(OrganisationPolicy.builder() + .orgPolicyReference("DEFENDANTREF2") + .organisation(uk.gov.hmcts.reform.ccd.model.Organisation.builder() + .organisationID("QWERTY R2").build()) + .build()) + .build(); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle( + callbackParamsOf(caseData, ABOUT_TO_SUBMIT)); + + assertThat(response.getData()) + .extracting("respondent1OrganisationIDCopy") + .isEqualTo("QWERTY R"); + assertThat(response.getData()) + .extracting("respondent2OrganisationIDCopy") + .isEqualTo("QWERTY R2"); + } + @Test void shouldReturnExpectedErrorMessagesInResponse_whenInvokedWithNullCourtLocation() { CaseData data = caseData.toBuilder() @@ -1591,7 +1659,7 @@ void oneVOne() { @Test void unrepresentedDefendants() { CaseData caseData = CaseDataBuilder.builder() - .atStateClaimDraft() + .atStateClaimSubmittedNoRespondentRepresented() .respondent1OrganisationPolicy(null) .respondent2OrganisationPolicy(null) .build(); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimSpecCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimSpecCallbackHandlerTest.java index 8c9f03e7dc7..c3b3ccad55a 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimSpecCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateClaimSpecCallbackHandlerTest.java @@ -21,6 +21,7 @@ import uk.gov.hmcts.reform.civil.config.ClaimUrlsConfiguration; import uk.gov.hmcts.reform.civil.config.ExitSurveyConfiguration; import uk.gov.hmcts.reform.civil.config.MockDatabaseConfiguration; +import uk.gov.hmcts.reform.civil.config.ToggleConfiguration; import uk.gov.hmcts.reform.civil.enums.CaseCategory; import uk.gov.hmcts.reform.civil.enums.CaseRole; import uk.gov.hmcts.reform.civil.enums.YesOrNo; @@ -201,6 +202,9 @@ class CreateClaimSpecCallbackHandlerTest extends BaseCallbackHandlerTest { @MockBean private FeatureToggleService toggleService; + @MockBean + private ToggleConfiguration toggleConfiguration; + @Nested class AboutToStartCallback { @@ -1637,7 +1641,7 @@ void setup() { .willReturn(UserDetails.builder().email(EMAIL).id(userId).build()); given(time.now()).willReturn(submittedDate); - + given(toggleConfiguration.getFeatureToggle()).willReturn("WA 4"); given(defendantPinToPostLRspecService.buildDefendantPinToPost()) .willReturn(DefendantPinToPostLRspec.builder() .accessCode( diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateSDOCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateSDOCallbackHandlerTest.java index b07bf5b4f50..505d72475f1 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateSDOCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/CreateSDOCallbackHandlerTest.java @@ -1,9 +1,12 @@ package uk.gov.hmcts.reform.civil.handler.callback.user; import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.SneakyThrows; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -65,8 +68,11 @@ import java.util.stream.Collectors; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; @@ -75,6 +81,8 @@ import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CREATE_SDO; import static uk.gov.hmcts.reform.civil.enums.CaseCategory.SPEC_CLAIM; +import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; +import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; import static uk.gov.hmcts.reform.civil.handler.callback.user.CreateSDOCallbackHandler.CONFIRMATION_HEADER; import static uk.gov.hmcts.reform.civil.handler.callback.user.CreateSDOCallbackHandler.CONFIRMATION_SUMMARY_1v1; import static uk.gov.hmcts.reform.civil.handler.callback.user.CreateSDOCallbackHandler.CONFIRMATION_SUMMARY_1v2; @@ -141,6 +149,49 @@ void setup() { .thenReturn(LocalDate.now().plusDays(7)); } + @Test + void shouldPopulateLocationListsWithPreselectedCourt() { + Category category = Category.builder().categoryKey("HearingChannel").key("INTER").valueEn("In Person").activeFlag("Y").build(); + CategorySearchResult categorySearchResult = CategorySearchResult.builder().categories(List.of(category)).build(); + String preSelectedCourt = "214320"; + List locations = List.of( + LocationRefData.builder().epimmsId("00001").courtLocationCode("00001") + .siteName("court 1").courtAddress("1 address").postcode("Y01 7RB").build(), + LocationRefData.builder().epimmsId(preSelectedCourt).courtLocationCode(preSelectedCourt) + .siteName("court 2").courtAddress("2 address").postcode("Y02 7RB").build(), + LocationRefData.builder().epimmsId("00003").courtLocationCode("00003") + .siteName("court 3").courtAddress("3 address").postcode("Y03 7RB").build() + ); + when(locationRefDataService.getCourtLocationsForDefaultJudgments(anyString())).thenReturn(locations); + when(categoryService.findCategoryByCategoryIdAndServiceId(any(), any(), any())).thenReturn(Optional.of(categorySearchResult)); + + CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft() + .atStateClaimIssuedDisposalHearingSDOInPersonHearing().build(); + + CallbackParams params = callbackParamsOf(CallbackVersion.V_1, caseData, ABOUT_TO_START); + CaseDocument order = CaseDocument.builder().documentLink( + Document.builder().documentUrl("url").build()) + .build(); + when(sdoGeneratorService.generate(any(), any())).thenReturn(order); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + CaseData responseCaseData = objectMapper.convertValue(response.getData(), CaseData.class); + + DynamicList expected = DynamicList.builder() + .listItems(List.of( + DynamicListElement.builder().code("00001").label("court 1 - 1 address - Y01 7RB").build(), + DynamicListElement.builder().code(preSelectedCourt).label("court 2 - 2 address - Y02 7RB").build(), + DynamicListElement.builder().code("00003").label("court 3 - 3 address - Y03 7RB").build() + ) + ) + .value(DynamicListElement.builder().code(preSelectedCourt).label("court 2 - 2 address - Y02 7RB").build()) + .build(); + + assertThat(responseCaseData.getDisposalHearingMethodInPerson()).isEqualTo(expected); + assertThat(responseCaseData.getFastTrackMethodInPerson()).isEqualTo(expected); + assertThat(responseCaseData.getSmallClaimsMethodInPerson()).isEqualTo(expected); + } + @Test void shouldGenerateDynamicListsCorrectly() { Category category = Category.builder().categoryKey("HearingChannel").key("INTER").valueEn("In Person").activeFlag("Y").build(); @@ -193,7 +244,16 @@ class AboutToSubmitCallback { @BeforeEach void setup() { - caseData = CaseDataBuilder.builder().atStateClaimDraft().build(); + List items = List.of("label 1", "label 2", "label 3"); + DynamicList options = DynamicList.fromList(items, Object::toString, items.get(0), false); + caseData = CaseDataBuilder.builder().atStateClaimDraft() + .caseManagementLocation(CaseLocationCivil.builder().baseLocation("00000").build()) + .build().toBuilder() + .disposalHearingMethodInPerson(options) + .fastTrackMethodInPerson(options) + .smallClaimsMethodInPerson(options) + .setFastTrackFlag(YES) + .build(); params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); userId = UUID.randomUUID().toString(); @@ -201,11 +261,22 @@ void setup() { .willReturn(UserDetails.builder().email(EMAIL).id(userId).build()); given(time.now()).willReturn(submittedDate); + + given(featureToggleService.isLocationWhiteListedForCaseProgression(anyString())).willReturn(true); + + given(featureToggleService.isEarlyAdoptersEnabled()).willReturn(true); } @Test void shouldUpdateBusinessProcess_whenInvoked() { - var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle( + params.toBuilder() + .caseData(params.getCaseData().toBuilder() + .claimsTrack(ClaimsTrack.smallClaimsTrack) + .drawDirectionsOrderRequired(NO) + .build()) + .build() + ); assertThat(response.getData()) .extracting("businessProcess") @@ -233,13 +304,21 @@ void setup() { } @Test - void shouldUpdateCaseLocation_whenDisposal() { + void shouldNotUpdateCaseLocation_whenDisposal() { List items = List.of("label 1", "label 2", "label 3"); DynamicList options = DynamicList.fromList(items, Object::toString, items.get(0), false); + CaseLocationCivil previousManagementLocation = CaseLocationCivil.builder() + .region("previous region") + .baseLocation("previous base location") + .build(); CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build().toBuilder() + .caseManagementLocation(CaseLocationCivil.builder().baseLocation("00000").build()) .disposalHearingMethod(DisposalHearingMethod.disposalHearingMethodInPerson) .disposalHearingMethodInPerson(options) + .fastTrackMethodInPerson(options) + .smallClaimsMethodInPerson(options) .disposalHearingMethodToggle(Collections.singletonList(OrderDetailsPagesSectionsToggle.SHOW)) + .caseManagementLocation(previousManagementLocation) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); LocationRefData matching = LocationRefData.builder() @@ -256,20 +335,23 @@ void shouldUpdateCaseLocation_whenDisposal() { assertThat(response.getData()) .extracting("caseManagementLocation") .extracting("region", "baseLocation") - .containsOnly(matching.getRegionId(), matching.getEpimmsId()); - assertThat(response.getData()) - .extracting("locationName") - .isEqualTo(matching.getSiteName()); + .containsOnly(previousManagementLocation.getRegion(), previousManagementLocation.getBaseLocation()); } @Test - void shouldUpdateCaseLocation_whenFastTrack() { + void shouldNotUpdateCaseLocation_whenFastTrack() { List items = List.of("label 1", "label 2", "label 3"); DynamicList options = DynamicList.fromList(items, Object::toString, items.get(0), false); + CaseLocationCivil previousManagementLocation = CaseLocationCivil.builder() + .region("previous region") + .baseLocation("previous base location") + .build(); CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build().toBuilder() + .caseManagementLocation(CaseLocationCivil.builder().baseLocation("00000").build()) .fastTrackMethod(FastTrackMethod.fastTrackMethodInPerson) .fastTrackMethodInPerson(options) .claimsTrack(ClaimsTrack.fastTrack) + .caseManagementLocation(previousManagementLocation) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); LocationRefData matching = LocationRefData.builder() @@ -286,20 +368,25 @@ void shouldUpdateCaseLocation_whenFastTrack() { assertThat(response.getData()) .extracting("caseManagementLocation") .extracting("region", "baseLocation") - .containsOnly(matching.getRegionId(), matching.getEpimmsId()); - assertThat(response.getData()) - .extracting("locationName") - .isEqualTo(matching.getSiteName()); + .containsOnly(previousManagementLocation.getRegion(), previousManagementLocation.getBaseLocation()); } @Test - void shouldUpdateCaseLocation_whenSmallClaims() { + void shouldNotUpdateCaseLocation_whenSmallClaims() { List items = List.of("label 1", "label 2", "label 3"); DynamicList options = DynamicList.fromList(items, Object::toString, items.get(0), false); + CaseLocationCivil previousManagementLocation = CaseLocationCivil.builder() + .region("previous region") + .baseLocation("previous base location") + .build(); CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build().toBuilder() + .caseManagementLocation(CaseLocationCivil.builder().baseLocation("00000").build()) .smallClaimsMethod(SmallClaimsMethod.smallClaimsMethodInPerson) + .disposalHearingMethodInPerson(options) + .fastTrackMethodInPerson(options) .smallClaimsMethodInPerson(options) .claimsTrack(ClaimsTrack.smallClaimsTrack) + .caseManagementLocation(previousManagementLocation) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); LocationRefData matching = LocationRefData.builder() @@ -316,21 +403,24 @@ void shouldUpdateCaseLocation_whenSmallClaims() { assertThat(response.getData()) .extracting("caseManagementLocation") .extracting("region", "baseLocation") - .containsOnly(matching.getRegionId(), matching.getEpimmsId()); - assertThat(response.getData()) - .extracting("locationName") - .isEqualTo(matching.getSiteName()); + .containsOnly(previousManagementLocation.getRegion(), previousManagementLocation.getBaseLocation()); } @Test - void shouldUpdateCaseLocation_whenFastTrackAndOrderRequired() { + void shouldNotUpdateCaseLocation_whenFastTrackAndOrderRequired() { List items = List.of("label 1", "label 2", "label 3"); DynamicList options = DynamicList.fromList(items, Object::toString, items.get(0), false); + CaseLocationCivil previousManagementLocation = CaseLocationCivil.builder() + .region("previous region") + .baseLocation("previous base location") + .build(); CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build().toBuilder() + .caseManagementLocation(CaseLocationCivil.builder().baseLocation("00000").build()) .fastTrackMethod(FastTrackMethod.fastTrackMethodInPerson) .fastTrackMethodInPerson(options) .drawDirectionsOrderRequired(YesOrNo.YES) .drawDirectionsOrderSmallClaims(YesOrNo.NO) + .caseManagementLocation(previousManagementLocation) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); LocationRefData matching = LocationRefData.builder() @@ -346,18 +436,26 @@ void shouldUpdateCaseLocation_whenFastTrackAndOrderRequired() { assertThat(response.getData()) .extracting("caseManagementLocation") .extracting("region", "baseLocation") - .containsOnly(matching.getRegionId(), matching.getEpimmsId()); + .containsOnly(previousManagementLocation.getRegion(), previousManagementLocation.getBaseLocation()); } @Test - void shouldUpdateCaseLocation_whenSmallClaimsAndOrderRequired() { + void shouldNotUpdateCaseLocation_whenSmallClaimsAndOrderRequired() { List items = List.of("label 1", "label 2", "label 3"); - DynamicList options = DynamicList.fromList(items, Object::toString, items.get(0), false); + DynamicList options = DynamicList.fromList(items, Object::toString, Object::toString, items.get(0), false); + CaseLocationCivil previousManagementLocation = CaseLocationCivil.builder() + .region("previous region") + .baseLocation("previous base location") + .build(); CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build().toBuilder() + .caseManagementLocation(CaseLocationCivil.builder().baseLocation("00000").build()) .smallClaimsMethod(SmallClaimsMethod.smallClaimsMethodInPerson) + .fastTrackMethodInPerson(options) + .disposalHearingMethodInPerson(options) .smallClaimsMethodInPerson(options) .drawDirectionsOrderRequired(YesOrNo.YES) .drawDirectionsOrderSmallClaims(YesOrNo.YES) + .caseManagementLocation(previousManagementLocation) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); LocationRefData matching = LocationRefData.builder() @@ -373,12 +471,19 @@ void shouldUpdateCaseLocation_whenSmallClaimsAndOrderRequired() { assertThat(response.getData()) .extracting("caseManagementLocation") .extracting("region", "baseLocation") - .containsOnly(matching.getRegionId(), matching.getEpimmsId()); + .containsOnly(previousManagementLocation.getRegion(), previousManagementLocation.getBaseLocation()); } @Test void shouldReturnNullDocument_whenInvokedAboutToSubmit() { + List items = List.of("label 1", "label 2", "label 3"); + DynamicList options = DynamicList.fromList(items, Object::toString, Object::toString, items.get(0), false); CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build().toBuilder() + .caseManagementLocation(CaseLocationCivil.builder().baseLocation("00000").build()) + .build().toBuilder() + .fastTrackMethodInPerson(options) + .disposalHearingMethodInPerson(options) + .smallClaimsMethodInPerson(options) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); @@ -388,6 +493,212 @@ void shouldReturnNullDocument_whenInvokedAboutToSubmit() { } } + @ParameterizedTest + @CsvSource({"true", "false"}) + void shouldSetEarlyAdoptersFlag_whenDisposal(Boolean isLocationWhiteListed) { + DynamicList options = DynamicList.builder() + .listItems(List.of( + DynamicListElement.builder().code("00001").label("court 1 - 1 address - Y01 7RB").build(), + DynamicListElement.builder().code("00002").label("court 2 - 2 address - Y02 7RB").build(), + DynamicListElement.builder().code("00003").label("court 3 - 3 address - Y03 7RB").build() + ) + ) + .build(); + + DynamicListElement selectedCourt = DynamicListElement.builder() + .code("00002").label("court 2 - 2 address - Y02 7RB").build(); + + CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build().toBuilder() + .caseManagementLocation(CaseLocationCivil.builder().baseLocation("00000").build()) + .disposalHearingMethod(DisposalHearingMethod.disposalHearingMethodInPerson) + .disposalHearingMethodInPerson(options.toBuilder().value(selectedCourt).build()) + .fastTrackMethodInPerson(options) + .smallClaimsMethodInPerson(options) + .disposalHearingMethodInPerson(options.toBuilder().value(selectedCourt).build()) + .disposalHearingMethodToggle(Collections.singletonList(OrderDetailsPagesSectionsToggle.SHOW)) + .orderType(OrderType.DISPOSAL) + .build(); + + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + when(featureToggleService.isEarlyAdoptersEnabled()).thenReturn(true); + when(featureToggleService.isLocationWhiteListedForCaseProgression(eq(selectedCourt.getCode()))).thenReturn( + isLocationWhiteListed); + when(locationRefDataService.getLocationMatchingLabel(selectedCourt.getCode(), params.getParams().get( + CallbackParams.Params.BEARER_TOKEN).toString())) + .thenReturn(Optional.of(LocationRefData.builder() + .regionId("region id") + .epimmsId("epimms id") + .siteName("site name") + .build())); + + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + CaseData responseCaseData = objectMapper.convertValue(response.getData(), CaseData.class); + + assertThat(responseCaseData.getEaCourtLocation()).isEqualTo(isLocationWhiteListed ? YES : NO); + } + + @ParameterizedTest + @CsvSource({"true", "false"}) + void shouldSetEarlyAdoptersFlag_whenSmallClaims(Boolean isLocationWhiteListed) { + DynamicList options = DynamicList.builder() + .listItems(List.of( + DynamicListElement.builder().code("00001").label("court 1 - 1 address - Y01 7RB").build(), + DynamicListElement.builder().code("00002").label("court 2 - 2 address - Y02 7RB").build(), + DynamicListElement.builder().code("00003").label("court 3 - 3 address - Y03 7RB").build() + ) + ) + .build(); + + DynamicListElement selectedCourt = DynamicListElement.builder() + .code("00002").label("court 2 - 2 address - Y02 7RB").build(); + + CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build().toBuilder() + .caseManagementLocation(CaseLocationCivil.builder().baseLocation("00000").build()) + .smallClaimsMethod(SmallClaimsMethod.smallClaimsMethodInPerson) + .disposalHearingMethodInPerson(options) + .fastTrackMethodInPerson(options) + .smallClaimsMethodInPerson(options.toBuilder().value(selectedCourt).build()) + .claimsTrack(ClaimsTrack.smallClaimsTrack) + .setSmallClaimsFlag(YES) + .drawDirectionsOrderRequired(NO) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + when(featureToggleService.isEarlyAdoptersEnabled()).thenReturn(true); + when(featureToggleService.isLocationWhiteListedForCaseProgression(eq(selectedCourt.getCode()))).thenReturn( + isLocationWhiteListed); + when(locationRefDataService.getLocationMatchingLabel("label 1", params.getParams().get( + CallbackParams.Params.BEARER_TOKEN).toString())).thenReturn( + Optional.of(LocationRefData.builder() + .regionId("region id") + .epimmsId("epimms id") + .siteName("location name") + .build())); + + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + CaseData responseCaseData = objectMapper.convertValue(response.getData(), CaseData.class); + + assertThat(responseCaseData.getEaCourtLocation()).isEqualTo(isLocationWhiteListed ? YES : NO); + } + + @ParameterizedTest + @CsvSource({"true", "false"}) + void shouldSetEarlyAdoptersFlag_whenFastTrack(Boolean isLocationWhiteListed) { + DynamicList options = DynamicList.builder() + .listItems(List.of( + DynamicListElement.builder().code("00001").label("court 1 - 1 address - Y01 7RB").build(), + DynamicListElement.builder().code("00002").label("court 2 - 2 address - Y02 7RB").build(), + DynamicListElement.builder().code("00003").label("court 3 - 3 address - Y03 7RB").build() + ) + ) + .build(); + + DynamicListElement selectedCourt = DynamicListElement.builder() + .code("00002").label("court 2 - 2 address - Y02 7RB").build(); + + CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build().toBuilder() + .caseManagementLocation(CaseLocationCivil.builder().baseLocation("00000").build()) + .fastTrackMethod(FastTrackMethod.fastTrackMethodInPerson) + .smallClaimsMethodInPerson(options) + .fastTrackMethodInPerson(options.toBuilder().value(selectedCourt).build()) + .disposalHearingMethodInPerson(options) + .claimsTrack(ClaimsTrack.fastTrack) + .setFastTrackFlag(YES) + .drawDirectionsOrderRequired(NO) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + when(featureToggleService.isEarlyAdoptersEnabled()).thenReturn(true); + when(featureToggleService.isLocationWhiteListedForCaseProgression(eq(selectedCourt.getCode()))).thenReturn( + isLocationWhiteListed); + when(locationRefDataService.getLocationMatchingLabel("label 1", params.getParams().get( + CallbackParams.Params.BEARER_TOKEN).toString())).thenReturn( + Optional.of(LocationRefData.builder() + .regionId("region id") + .epimmsId("epimms id") + .siteName("location name") + .build())); + + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + CaseData responseCaseData = objectMapper.convertValue(response.getData(), CaseData.class); + + assertThat(responseCaseData.getEaCourtLocation()).isEqualTo(isLocationWhiteListed ? YES : NO); + } + + @Test + @SneakyThrows + void shouldThrowIllegalArgumentException_whenClaimTrackCannotDefined() { + DynamicList options = DynamicList.builder() + .listItems(List.of( + DynamicListElement.builder().code("00001").label("court 1 - 1 address - Y01 7RB").build(), + DynamicListElement.builder().code("00002").label("court 2 - 2 address - Y02 7RB").build(), + DynamicListElement.builder().code("00003").label("court 3 - 3 address - Y03 7RB").build() + ) + ) + .build(); + + CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build().toBuilder() + .caseManagementLocation(CaseLocationCivil.builder().baseLocation("00000").build()) + .fastTrackMethod(FastTrackMethod.fastTrackMethodInPerson) + .smallClaimsMethodInPerson(options) + .fastTrackMethodInPerson(options) + .disposalHearingMethodInPerson(options) + .claimsTrack(ClaimsTrack.fastTrack) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + when(featureToggleService.isEarlyAdoptersEnabled()).thenReturn(true); + when(locationRefDataService.getLocationMatchingLabel("label 1", params.getParams().get( + CallbackParams.Params.BEARER_TOKEN).toString())).thenReturn( + Optional.of(LocationRefData.builder() + .regionId("region id") + .epimmsId("epimms id") + .siteName("location name") + .build())); + + assertThrows(IllegalArgumentException.class, () -> handler.handle(params), + "Epimms Id is not provided" + ); + } + + @ParameterizedTest + @CsvSource({"true", "false"}) + void shouldNotSetEarlyAdoptersFlag_whenEarlyAdoptersToggleIsOff(Boolean isLocationWhiteListed) { + DynamicList options = DynamicList.builder() + .listItems(List.of( + DynamicListElement.builder().code("00001").label("court 1 - 1 address - Y01 7RB").build(), + DynamicListElement.builder().code("00002").label("court 2 - 2 address - Y02 7RB").build(), + DynamicListElement.builder().code("00003").label("court 3 - 3 address - Y03 7RB").build() + ) + ) + .build(); + + DynamicListElement selectedCourt = DynamicListElement.builder() + .code("00002").label("court 2 - 2 address - Y02 7RB").build(); + + CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build().toBuilder() + .caseManagementLocation(CaseLocationCivil.builder().baseLocation("00000").build()) + .fastTrackMethod(FastTrackMethod.fastTrackMethodInPerson) + .fastTrackMethodInPerson(options.toBuilder().value(selectedCourt).build()) + .smallClaimsMethodInPerson(options) + .disposalHearingMethodInPerson(options) + .claimsTrack(ClaimsTrack.fastTrack) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + when(featureToggleService.isEarlyAdoptersEnabled()).thenReturn(false); + when(featureToggleService.isLocationWhiteListedForCaseProgression(eq(selectedCourt.getCode()))).thenReturn( + isLocationWhiteListed); + when(locationRefDataService.getLocationMatchingLabel("label 1", params.getParams().get( + CallbackParams.Params.BEARER_TOKEN).toString())).thenReturn( + Optional.of(LocationRefData.builder() + .regionId("region id") + .epimmsId("epimms id") + .siteName("location name") + .build())); + + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + CaseData responseCaseData = objectMapper.convertValue(response.getData(), CaseData.class); + + assertThat(responseCaseData.getEaCourtLocation()).isNull(); + } + @Nested class MidEventDisposalHearingLocationRefDataCallback extends LocationRefSampleDataBuilder { @@ -1464,4 +1775,76 @@ void shouldReturnExpectedSubmittedCallbackResponse_2v1() { void handleEventsReturnsTheExpectedCallbackEvent() { assertThat(handler.handledEvents()).contains(CREATE_SDO); } + + @Nested + class MidEventNegativeNumberOfWitness { + private static final String PAGE_ID = "validateInputValue"; + + @Test + void shouldThrowErrorWhenEnteringNegativeNumberOfWitnessSmallClaim() { + + CaseData caseData = CaseDataBuilder.builder() + .atSmallClaimsWitnessStatementWithNegativeInputs() + .build() + .toBuilder() + .claimsTrack(ClaimsTrack.smallClaimsTrack) + .build(); + + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors().get(0)).isEqualTo("The number entered cannot be less than zero"); + } + + @Test + void shouldThrowErrorWhenEnteringNegativeNumberOfWitnessFastTrack() { + + CaseData caseData = CaseDataBuilder.builder() + .atFastTrackWitnessOfFactWithNegativeInputs() + .build() + .toBuilder() + .claimsTrack(ClaimsTrack.fastTrack) + .build(); + + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors().get(0)).isEqualTo("The number entered cannot be less than zero"); + } + + @Test + void shouldNotThrowErrorWhenEnteringPositiveNumberOfWitnessSmallClaim() { + + CaseData caseData = CaseDataBuilder.builder() + .atSmallClaimsWitnessStatementWithPositiveInputs() + .build() + .toBuilder() + .claimsTrack(ClaimsTrack.smallClaimsTrack) + .build(); + + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response).isNotNull(); + assertThat(response.getErrors()).isNull(); + } + + @Test + void shouldNotThrowErrorWhenEnteringPositiveNumberOfWitnessFastTrack() { + + CaseData caseData = CaseDataBuilder.builder() + .atFastTrackWitnessOfFactWithPositiveInputs() + .build() + .toBuilder() + .claimsTrack(ClaimsTrack.fastTrack) + .build(); + + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response).isNotNull(); + assertThat(response.getErrors()).isNull(); + + } + } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/DefaultJudgementSpecHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/DefaultJudgementSpecHandlerTest.java index 9c7d7531104..cabfd02fd7f 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/DefaultJudgementSpecHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/DefaultJudgementSpecHandlerTest.java @@ -924,7 +924,7 @@ class SubmittedCallback { void shouldReturnExpectedSubmittedCallbackResponse_whenInvoked1v1() { String body = "
    Download default judgment " - + "%n%n The defendant will be served the Default Judgment."; + + "%n%n The defendant will be served with the Default Judgment."; CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .respondent1ResponseDeadline(LocalDateTime.now().minusDays(15)) .build(); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadApplicantHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadApplicantHandlerTest.java index 5bc8f129491..3704297d425 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadApplicantHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadApplicantHandlerTest.java @@ -96,7 +96,32 @@ class EvidenceUploadApplicantHandlerTest extends BaseCallbackHandlerTest { private final UploadEvidenceExpert uploadEvidenceDate = new UploadEvidenceExpert(); private final UploadEvidenceWitness uploadEvidenceDate2 = new UploadEvidenceWitness(); private final UploadEvidenceDocumentType uploadEvidenceDate3 = new UploadEvidenceDocumentType(); - + private static final String NotificationWhenBothClaimant = "\n" + + "Both claimants - Disclosure list\n" + + "Both claimants - Documents for disclosure\n" + + "Both claimants - Documents referred to in the statement\n" + + "Both claimants - Expert's report\n" + + "Both claimants - Joint Statement of Experts / Single Joint Expert Report\n" + + "Both claimants - Questions for other party's expert or joint experts\n" + + "Both claimants - Answer to questions asked\n" + + "Both claimants - Case Summary\n" + + "Both claimants - Skeleton argument\n" + + "Both claimants - Authorities\n" + + "Both claimants - Costs\n" + + "Both claimants - Documentary evidence for trial"; + private static final String NotificationWhenClaimantTwo = "\n" + + "Claimant 2 - Disclosure list\n" + + "Claimant 2 - Documents for disclosure\n" + + "Claimant 2 - Documents referred to in the statement\n" + + "Claimant 2 - Expert's report\n" + + "Claimant 2 - Joint Statement of Experts / Single Joint Expert Report\n" + + "Claimant 2 - Questions for other party's expert or joint experts\n" + + "Claimant 2 - Answer to questions asked\n" + + "Claimant 2 - Case Summary\n" + + "Claimant 2 - Skeleton argument\n" + + "Claimant 2 - Authorities\n" + + "Claimant 2 - Costs\n" + + "Claimant 2 - Documentary evidence for trial"; private static final String PAGE_ID = "validateValuesApplicant"; @BeforeEach @@ -108,6 +133,7 @@ void setup() { void givenAboutToStart_assignCaseProgAllocatedTrackUnSpec() { // Given CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .notificationText(null) .claimType(ClaimType.CLINICAL_NEGLIGENCE) .claimValue(ClaimValue.builder() .statementOfValueInPennies(BigDecimal.valueOf(5000)) @@ -121,12 +147,14 @@ void givenAboutToStart_assignCaseProgAllocatedTrackUnSpec() { .handle(params); // Then assertThat(response.getData()).extracting("caseProgAllocatedTrack").isEqualTo("SMALL_CLAIM"); + assertThat(response.getData()).extracting("notificationText").isNull(); } @Test void givenAboutToStart_assignCaseProgAllocatedTrackSpec() { // Given CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .notificationText(null) .claimType(null) .totalClaimAmount(BigDecimal.valueOf(12500)) .build(); @@ -138,6 +166,7 @@ void givenAboutToStart_assignCaseProgAllocatedTrackSpec() { .handle(params); // Then assertThat(response.getData()).extracting("caseProgAllocatedTrack").isEqualTo("FAST_CLAIM"); + assertThat(response.getData()).extracting("notificationText").isNull(); } @Test @@ -496,6 +525,7 @@ void shouldAssignCategoryID_whenDocumentExists() { "hash", null); var documentUpload = UploadEvidenceWitness.builder() .witnessOptionUploadDate(LocalDate.of(2023, 2, 10)) + .createdDatetime(LocalDateTime.of(2022, 05, 10, 12, 13, 12)) .witnessOptionDocument(testDocument).build(); List> documentList = new ArrayList<>(); documentList.add(Element.builder().value(documentUpload).build()); @@ -676,7 +706,6 @@ void shouldBreakWhenThereIsAnyCaseBundlesWithNullCreatedDate() { @CsvSource({"0", "2"}) void should_do_naming_convention(String selected) { LocalDateTime createdDate = LocalDateTime.of(2022, 05, 10, 12, 13, 12); - String witnessName = "AppWitness"; LocalDate witnessDate = LocalDate.of(2023, 2, 10); List options = List.of(EvidenceUploadHandlerBase.OPTION_APP1, @@ -810,14 +839,141 @@ void should_do_naming_convention(String selected) { assertThat(updatedData.getDocumentAuthoritiesApp2().get(0).getValue() .getDocumentUpload().getDocumentFileName()).isEqualTo(TEST_FILE_NAME); assertThat(updatedData.getDocumentAuthoritiesApp2().get(0).getValue() - .getDocumentUpload().getCategoryID()).isEqualTo(EvidenceUploadHandlerBase.APPLICANT_TWO_TRIAL_AUTHORITIES); + .getDocumentUpload().getCategoryID()).isEqualTo(EvidenceUploadHandlerBase.APPLICANT_TWO_PRECEDENT_H); assertThat(updatedData.getDocumentCostsApp2().get(0).getValue() .getDocumentUpload().getDocumentFileName()).isEqualTo(TEST_FILE_NAME); assertThat(updatedData.getDocumentCostsApp2().get(0).getValue() - .getDocumentUpload().getCategoryID()).isEqualTo(EvidenceUploadHandlerBase.APPLICANT_TWO_TRIAL_COSTS); + .getDocumentUpload().getCategoryID()).isEqualTo(EvidenceUploadHandlerBase.APPLICANT_TWO_SCHEDULE_OF_COSTS); + assertThat(updatedData.getNotificationText()).isEqualTo(NotificationWhenBothClaimant); } } + @Test + void should_do_naming_convention_app2() { + LocalDateTime createdDate = LocalDateTime.of(2022, 05, 10, 12, 13, 12); + List> witnessEvidenceDocs = new ArrayList<>(); + String witnessName = "appTwoWitness"; + List options = List.of(EvidenceUploadHandlerBase.OPTION_APP1, + EvidenceUploadHandlerBase.OPTION_APP2, + EvidenceUploadHandlerBase.OPTION_APP_BOTH); + LocalDate witnessDate = LocalDate.of(2023, 2, 10); + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .addApplicant2(YES) + .applicant1(PartyBuilder.builder().individual().build()) + .applicant2(PartyBuilder.builder().individual().build()) + .evidenceUploadOptions(DynamicList.fromList(options, Object::toString, options.get(1), false)) + .documentWitnessSummaryApp2(createWitnessDocs(witnessName, createdDate, witnessDate)) + .documentWitnessStatementApp2(createWitnessDocs(witnessName, createdDate, witnessDate)) + .documentHearsayNoticeApp2(createWitnessDocs(witnessName, createdDate, witnessDate)) + .documentExpertReportApp2(createExpertDocs("expertName", witnessDate, "expertise", null, null, null, null)) + .documentJointStatementApp2(createExpertDocs("expertsName", witnessDate, null, "expertises", null, null, null)) + .documentQuestionsApp2(createExpertDocs("expertName", witnessDate, null, null, "other", "question", null)) + .documentAnswersApp2(createExpertDocs("expertName", witnessDate, null, null, "other", null, "answer")) + .documentForDisclosureApp2(createEvidenceDocs("typeDisclosure", witnessDate)) + .documentReferredInStatementApp2(createEvidenceDocs("typeReferred", witnessDate)) + .documentEvidenceForTrialApp2(createEvidenceDocs("typeForTrial", witnessDate)) + .documentDisclosureListApp2(createEvidenceDocs(null, null)) + .documentCaseSummaryApp2(createEvidenceDocs(null, null)) + .documentSkeletonArgumentApp2(createEvidenceDocs(null, null)) + .documentAuthoritiesApp2(createEvidenceDocs(null, null)) + .documentCostsApp2(createEvidenceDocs(null, null)) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + given(userService.getUserInfo(anyString())).willReturn(UserInfo.builder().uid("uid").build()); + + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).willReturn(false); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).willReturn(false); + + // When handle is called + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + + // Then applicant docs should have name changed + assertThat(updatedData.getDocumentWitnessSummaryApp2().get(0).getValue() + .getWitnessOptionDocument().getDocumentFileName()).isEqualTo("Witness Summary of appTwoWitness.pdf"); + assertThat(updatedData.getDocumentWitnessStatementApp2().get(0).getValue() + .getWitnessOptionDocument().getDocumentFileName()).isEqualTo("Witness Statement of appTwoWitness 10-02-2023.pdf"); + assertThat(updatedData.getDocumentHearsayNoticeApp2().get(0).getValue() + .getWitnessOptionDocument().getDocumentFileName()).isEqualTo("Hearsay evidence appTwoWitness 10-02-2023.pdf"); + assertThat(updatedData.getDocumentExpertReportApp2().get(0).getValue() + .getExpertDocument().getDocumentFileName()).isEqualTo("Experts report expertName expertise 10-02-2023.pdf"); + assertThat(updatedData.getDocumentJointStatementApp2().get(0).getValue() + .getExpertDocument().getDocumentFileName()).isEqualTo("Joint report expertsName expertises 10-02-2023.pdf"); + assertThat(updatedData.getDocumentQuestionsApp2().get(0).getValue() + .getExpertDocument().getDocumentFileName()).isEqualTo("expertName other question.pdf"); + assertThat(updatedData.getDocumentAnswersApp2().get(0).getValue() + .getExpertDocument().getDocumentFileName()).isEqualTo("expertName other answer.pdf"); + assertThat(updatedData.getDocumentForDisclosureApp2().get(0).getValue() + .getDocumentUpload().getDocumentFileName()).isEqualTo("Document for disclosure typeDisclosure 10-02-2023.pdf"); + assertThat(updatedData.getDocumentReferredInStatementApp2().get(0).getValue() + .getDocumentUpload().getDocumentFileName()).isEqualTo("Referred Document typeReferred 10-02-2023.pdf"); + assertThat(updatedData.getDocumentEvidenceForTrialApp2().get(0).getValue() + .getDocumentUpload().getDocumentFileName()).isEqualTo("Documentary Evidence typeForTrial 10-02-2023.pdf"); + assertThat(updatedData.getDocumentDisclosureListApp2().get(0).getValue() + .getDocumentUpload().getDocumentFileName()).isEqualTo(TEST_FILE_NAME); + assertThat(updatedData.getDocumentCaseSummaryApp2().get(0).getValue() + .getDocumentUpload().getDocumentFileName()).isEqualTo(TEST_FILE_NAME); + assertThat(updatedData.getDocumentSkeletonArgumentApp2().get(0).getValue() + .getDocumentUpload().getDocumentFileName()).isEqualTo(TEST_FILE_NAME); + assertThat(updatedData.getDocumentAuthoritiesApp2().get(0).getValue() + .getDocumentUpload().getDocumentFileName()).isEqualTo(TEST_FILE_NAME); + assertThat(updatedData.getDocumentCostsApp2().get(0).getValue() + .getDocumentUpload().getDocumentFileName()).isEqualTo(TEST_FILE_NAME); + assertThat(updatedData.getNotificationText()).isEqualTo(NotificationWhenClaimantTwo); + } + + @Test + void shouldNotAddSameNotificationIfAlreadyAdded_notificationText() { + // If we populate notification string with an entry, we do not want to duplicate that on further uploads of same type. + List options = List.of(EvidenceUploadHandlerBase.OPTION_APP1, + EvidenceUploadHandlerBase.OPTION_APP2, + EvidenceUploadHandlerBase.OPTION_APP_BOTH); + LocalDate witnessDate = LocalDate.of(2023, 2, 10); + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .notificationText("Documentation that has been uploaded: \n\n Claimant 1 - Joint Statement of Experts / Single Joint Expert Report \n") + .applicant1(PartyBuilder.builder().individual().build()) + .evidenceUploadOptions(DynamicList.fromList(options, Object::toString, options.get(0), false)) + .documentJointStatement(createExpertDocs("expertsName", witnessDate, null, "expertises", null, null, null)) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + given(userService.getUserInfo(anyString())).willReturn(UserInfo.builder().uid("uid").build()); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).willReturn(false); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).willReturn(false); + given(coreCaseDataService.getCase(anyLong())).willReturn(CaseDetails.builder().build()); + // When handle is called + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + // Then Notificcation should not have a duplicate entry + assertThat(updatedData.getNotificationText()) + .isEqualTo("Documentation that has been uploaded: \n\n Claimant 1 - Joint Statement of Experts / Single Joint Expert Report \n"); + } + + @Test + void shouldNotPopulateNotificationWithOldDocument_whenNewDocumentUploadAdded() { + // When evidence upload is retriggered we do not send a notification for old content i.e uploaded before midnight of current day + List options = List.of(EvidenceUploadHandlerBase.OPTION_APP1, + EvidenceUploadHandlerBase.OPTION_APP2, + EvidenceUploadHandlerBase.OPTION_APP_BOTH); + LocalDate witnessDate = LocalDate.of(2023, 2, 10); + String witnessName = "Witness"; + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .notificationText(null) + .evidenceUploadOptions(DynamicList.fromList(options, Object::toString, options.get(0), false)) + .documentWitnessStatement(createWitnessDocs(witnessName, LocalDateTime.now().minusDays(2), witnessDate)) + .documentWitnessSummary(createWitnessDocs(witnessName, LocalDateTime.now(), witnessDate)) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + given(userService.getUserInfo(anyString())).willReturn(UserInfo.builder().uid("uid").build()); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).willReturn(false); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).willReturn(false); + given(coreCaseDataService.getCase(anyLong())).willReturn(CaseDetails.builder().build()); + // When handle is called + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + // Then Notification should not have old entry (witness statement) + assertThat(updatedData.getNotificationText()).isEqualTo("\nClaimant 1 - Witness summary"); + } + private List> createEvidenceDocs(String type, LocalDate issuedDate) { Document document = Document.builder().documentBinaryUrl( TEST_URL) diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadJudgeHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadJudgeHandlerTest.java index 51ea12be8f7..d37c56db259 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadJudgeHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadJudgeHandlerTest.java @@ -1,11 +1,14 @@ package uk.gov.hmcts.reform.civil.handler.callback.user; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit.jupiter.SpringExtension; import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; import uk.gov.hmcts.reform.ccd.client.model.SubmittedCallbackResponse; @@ -14,28 +17,43 @@ import uk.gov.hmcts.reform.civil.enums.CaseNoteType; import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.CaseNote; import uk.gov.hmcts.reform.civil.model.common.Element; import uk.gov.hmcts.reform.civil.documentmanagement.model.Document; import uk.gov.hmcts.reform.civil.model.documents.DocumentAndNote; import uk.gov.hmcts.reform.civil.model.documents.DocumentWithName; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; +import uk.gov.hmcts.reform.civil.service.CaseNoteService; +import uk.gov.hmcts.reform.civil.service.Time; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; +import static uk.gov.hmcts.reform.civil.callback.CallbackParams.Params.BEARER_TOKEN; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = { EvidenceUploadJudgeHandler.class, - JacksonAutoConfiguration.class + JacksonAutoConfiguration.class, + CaseNoteService.class }) public class EvidenceUploadJudgeHandlerTest extends BaseCallbackHandlerTest { @Autowired private EvidenceUploadJudgeHandler handler; + @Autowired + private ObjectMapper objectMapper; + @MockBean + private CaseNoteService caseNoteService; + + @MockBean + private Time time; public static final String REFERENCE_NUMBER = "000DC001"; @@ -44,12 +62,16 @@ class AboutToStartCallback { @Test void aboutToStartCallback_placeholder() { - CaseData caseData = CaseDataBuilder.builder().build(); + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .caseNoteType(CaseNoteType.NOTE_ONLY) + .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_START); - AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + var response = (AboutToStartOrSubmitCallbackResponse) handler .handle(params); + assertThat(response.getData()).extracting("caseNoteType").isNull(); + } } @@ -59,26 +81,131 @@ class AboutToSubmitCallback { @Test void shouldPopulateNoteDateTime_whenNoteIsAddedToCase() { CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() - .caseNoteTypeNoteTA("test note") + .caseNoteType(CaseNoteType.NOTE_ONLY) + .caseNoteTA("test note") .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + CaseNote expectedCaseNote = createCaseNote(time.now(), "John Doe", "test note"); + List> updatedCaseNotes = wrapElements(expectedCaseNote); + + when(caseNoteService.buildCaseNote(params.getParams().get(BEARER_TOKEN).toString(), "test note")) + .thenReturn(expectedCaseNote); + when(caseNoteService.addNoteToListEnd(expectedCaseNote, caseData.getCaseNotes())).thenReturn(updatedCaseNotes); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); - assertThat(response.getData().get("noteAdditionDateTime")).isNotNull(); + assertThat(response.getData()).extracting("caseNotesTA") + .isEqualTo(objectMapper.convertValue(updatedCaseNotes, new TypeReference<>() {})); + assertThat(response.getData()).extracting("documentAndName").isNull(); + assertThat(response.getData()).extracting("documentAndNote").isNull(); + } + + @Test + void shouldCopyDocumentAndNameToAdd_whenDocumentWithNameIsNull() { + Document document = Document.builder().documentFileName("fileName").build(); + DocumentWithName testDocument = DocumentWithName.builder() + .documentName("testDocument") + .document(document) + .build(); + List> documentWithNameToAdd = wrapElements(testDocument); + + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .caseNoteType(CaseNoteType.DOCUMENT_ONLY) + .documentAndNameToAdd(documentWithNameToAdd) + .caseNoteTA(null) + .build(); + + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getData()).extracting("documentAndName") + .isEqualTo(objectMapper.convertValue(documentWithNameToAdd, new TypeReference<>() {})); + assertThat(response.getData()).extracting("caseNotesTA").isNull(); + assertThat(response.getData()).extracting("documentAndNote").isNull(); } @Test - void shouldNotPopulateNoteDateTime_whenNoteIsAddedToCase() { + void shouldAddDocument_whenDocumentWithNameIsNotNull() { + Document document = Document.builder().documentFileName("fileName").build(); + DocumentWithName testDocument = DocumentWithName.builder() + .documentName("testDocument") + .document(document) + .build(); + List> documentWithNameToAdd = wrapElements(testDocument); + List> documentWithNameStart = wrapElements(testDocument); + List> documentWithNameEnd = wrapElements(testDocument, testDocument); + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() - .caseNoteTypeNoteTA(null) + .caseNoteType(CaseNoteType.DOCUMENT_ONLY) + .documentAndNameToAdd(documentWithNameToAdd) + .documentAndName(documentWithNameStart) + .caseNoteTA(null) .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); - assertThat(response.getData().get("noteAdditionDateTime")).isNull(); + assertThat(response.getData()).extracting("documentAndName") + .isEqualTo(objectMapper.convertValue(documentWithNameEnd, new TypeReference<>() {})); + assertThat(response.getData()).extracting("caseNotesTA").isNull(); + assertThat(response.getData()).extracting("documentAndNote").isNull(); + + } + + @Test + void shouldAddNote_whenDocumentWithNoteIsNotNull() { + Document document = Document.builder().documentFileName("fileName").build(); + DocumentAndNote testDocument = DocumentAndNote.builder() + .documentName("testDocument") + .document(document) + .documentNote("Note") + .build(); + List> documentAndNoteToAdd = wrapElements(testDocument); + List> documentAndNoteStart = wrapElements(testDocument); + List> documentAndNoteEnd = wrapElements(testDocument, testDocument); + + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .caseNoteType(CaseNoteType.DOCUMENT_AND_NOTE) + .documentAndNoteToAdd(documentAndNoteToAdd) + .documentAndNote(documentAndNoteStart) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getData()).extracting("documentAndNote") + .isEqualTo(objectMapper.convertValue(documentAndNoteEnd, new TypeReference<>() {})); + assertThat(response.getData()).extracting("caseNotesTA").isNull(); + assertThat(response.getData()).extracting("documentAndName").isNull(); + + } + + @Test + void shouldCopyDocumentAndNoteToAdd_whenDocumentWithNoteIsNull() { + Document document = Document.builder().documentFileName("fileName").build(); + DocumentAndNote testDocument = DocumentAndNote.builder() + .documentName("testDocument") + .document(document) + .documentNote("Note") + .build(); + List> documentAndNoteToAdd = wrapElements(testDocument); + + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .caseNoteType(CaseNoteType.DOCUMENT_AND_NOTE) + .documentAndNoteToAdd(documentAndNoteToAdd) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getData()).extracting("documentAndNote") + .isEqualTo(objectMapper.convertValue(documentAndNoteToAdd, new TypeReference<>() {})); + assertThat(response.getData()).extracting("caseNotesTA").isNull(); + assertThat(response.getData()).extracting("documentAndName").isNull(); } } @@ -101,7 +228,7 @@ void shouldPopulateConfirmation_DocumentAndNote() { documentList.add(Element.builder().value(documentAndNote).build()); CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() - .documentAndNote(documentList) + .documentAndNoteToAdd(documentList) .caseNoteType(CaseNoteType.DOCUMENT_AND_NOTE) .build(); CallbackParams params = callbackParamsOf(caseData, CallbackType.SUBMITTED); @@ -130,7 +257,7 @@ void submittedCallback_documentOnly() { documentList.add(Element.builder().value(documentAndNote).build()); CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() - .documentAndName(documentList) + .documentAndNameToAdd(documentList) .caseNoteType(CaseNoteType.DOCUMENT_ONLY) .build(); CallbackParams params = callbackParamsOf(caseData, CallbackType.SUBMITTED); @@ -142,6 +269,30 @@ void submittedCallback_documentOnly() { .confirmationBody(String.format(body)) .build()); } + + @Test + void submittedCallback_noteOnly() { + String header = "# Case note added \n # " + REFERENCE_NUMBER; + + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .caseNoteType(CaseNoteType.NOTE_ONLY) + .build(); + CallbackParams params = callbackParamsOf(caseData, CallbackType.SUBMITTED); + + SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); + + assertThat(response).usingRecursiveComparison().isEqualTo(SubmittedCallbackResponse.builder() + .confirmationHeader(header) + .build()); + } + } + + private CaseNote createCaseNote(LocalDateTime timeStamp, String createdBy, String note) { + return CaseNote.builder() + .createdOn(timeStamp) + .createdBy(createdBy) + .note(note) + .build(); } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadRespondentHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadRespondentHandlerTest.java index 12ad66d8943..d5c32eeac09 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadRespondentHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/EvidenceUploadRespondentHandlerTest.java @@ -111,7 +111,32 @@ class EvidenceUploadRespondentHandlerTest extends BaseCallbackHandlerTest { private final UploadEvidenceExpert uploadEvidenceDate = new UploadEvidenceExpert(); private final UploadEvidenceWitness uploadEvidenceDate2 = new UploadEvidenceWitness(); private final UploadEvidenceDocumentType uploadEvidenceDate3 = new UploadEvidenceDocumentType(); - + private static final String NotificationWhenBothDefendant = "\n" + + "Both defendants - Disclosure list\n" + + "Both defendants - Documents for disclosure\n" + + "Both defendants - Documents referred to in the statement\n" + + "Both defendants - Expert's report\n" + + "Both defendants - Joint Statement of Experts / Single Joint Expert Report\n" + + "Both defendants - Questions for other party's expert or joint experts\n" + + "Both defendants - Answer to questions asked\n" + + "Both defendants - Case Summary\n" + + "Both defendants - Skeleton argument\n" + + "Both defendants - Authorities\n" + + "Both defendants - Costs\n" + + "Both defendants - Documentary evidence for trial"; + private static final String NotificationWhenDefendantTwo = "\n" + + "Defendant 2 - Disclosure list\n" + + "Defendant 2 - Documents for disclosure\n" + + "Defendant 2 - Documents referred to in the statement\n" + + "Defendant 2 - Expert's report\n" + + "Defendant 2 - Joint Statement of Experts / Single Joint Expert Report\n" + + "Defendant 2 - Questions for other party's expert or joint experts\n" + + "Defendant 2 - Answer to questions asked\n" + + "Defendant 2 - Case Summary\n" + + "Defendant 2 - Skeleton argument\n" + + "Defendant 2 - Authorities\n" + + "Defendant 2 - Costs\n" + + "Defendant 2 - Documentary evidence for trial"; private static final String PAGE_ID = "validateValuesRespondent"; @BeforeEach @@ -123,6 +148,7 @@ void setup() { void givenAboutToStart_assignCaseProgAllocatedTrackUnSpec() { // Given CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .notificationText("NULLED") .claimType(ClaimType.CLINICAL_NEGLIGENCE) .claimValue(ClaimValue.builder() .statementOfValueInPennies(BigDecimal.valueOf(5000)) @@ -136,12 +162,14 @@ void givenAboutToStart_assignCaseProgAllocatedTrackUnSpec() { .handle(params); // Then assertThat(response.getData()).extracting("caseProgAllocatedTrack").isEqualTo("SMALL_CLAIM"); + assertThat(response.getData()).extracting("notificationText").isNull(); } @Test void givenAboutToStart_assignCaseProgAllocatedTrackSpec() { // Given CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .notificationText(null) .claimType(null) .totalClaimAmount(BigDecimal.valueOf(12500)) .build(); @@ -153,12 +181,14 @@ void givenAboutToStart_assignCaseProgAllocatedTrackSpec() { .handle(params); // Then assertThat(response.getData()).extracting("caseProgAllocatedTrack").isEqualTo("FAST_CLAIM"); + assertThat(response.getData()).extracting("notificationText").isNull(); } @Test void givenAboutToStart_1v2SameSolicitor_shouldShowOptions() { // Given CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .notificationText("existing notification") .claimType(null) .totalClaimAmount(BigDecimal.valueOf(12500)) .addRespondent2(YES) @@ -172,6 +202,7 @@ void givenAboutToStart_1v2SameSolicitor_shouldShowOptions() { .handle(params); // Then assertThat(response.getData()).extracting("evidenceUploadOptions").isNotNull(); + assertThat(response.getData()).extracting("notificationText").isEqualTo("existing notification"); } @ParameterizedTest @@ -997,7 +1028,8 @@ void shouldAssignCategoryID_whenDocumentExistsTwoRespondentSpec() { "testBinUrl", "A Fancy Name", "hash", null); var documentUpload = UploadEvidenceDocumentType.builder() - .documentIssuedDate(LocalDate.of(2023, 2, 10)) + .documentIssuedDate(LocalDate.of(2022, 2, 10)) + .createdDatetime(LocalDateTime.of(2022, 05, 10, 12, 13, 12)) .documentUpload(testDocument).build(); List> documentList = new ArrayList<>(); documentList.add(Element.builder().value(documentUpload).build()); @@ -1023,7 +1055,8 @@ void shouldAssignCategoryID_whenDocumentExistsTwoRespondentUnSpec() { "testBinUrl", "A Fancy Name", "hash", null); var documentUpload = UploadEvidenceDocumentType.builder() - .documentIssuedDate(LocalDate.of(2023, 2, 10)) + .documentIssuedDate(LocalDate.of(2022, 2, 10)) + .createdDatetime(LocalDateTime.of(2022, 05, 10, 12, 13, 12)) .documentUpload(testDocument).build(); List> documentList = new ArrayList<>(); documentList.add(Element.builder().value(documentUpload).build()); @@ -1048,7 +1081,10 @@ void shouldAssignCategoryID_whenDocumentExistsOneRespondentSpec() { Document testDocument = new Document("testurl", "testBinUrl", "A Fancy Name", "hash", null); - var documentUpload = UploadEvidenceExpert.builder().expertDocument(testDocument).build(); + var documentUpload = UploadEvidenceExpert.builder() + .expertDocument(testDocument) + .createdDatetime(LocalDateTime.of(2022, 05, 10, 12, 13, 12)) + .build(); List> documentList = new ArrayList<>(); documentList.add(Element.builder().value(documentUpload).build()); // Given @@ -1073,7 +1109,10 @@ void shouldAssignCategoryID_whenDocumentExistsOneRespondentUnSpec() { Document testDocument = new Document("testurl", "testBinUrl", "A Fancy Name", "hash", null); - var documentUpload = UploadEvidenceExpert.builder().expertDocument(testDocument).build(); + var documentUpload = UploadEvidenceExpert.builder() + .expertDocument(testDocument) + .createdDatetime(LocalDateTime.of(2022, 05, 10, 12, 13, 12)) + .build(); List> documentList = new ArrayList<>(); documentList.add(Element.builder().value(documentUpload).build()); // Given @@ -1273,7 +1312,6 @@ void shouldBreakWhenThereIsAnyCaseBundlesWithNullCreatedDate() { @CsvSource({"0", "2"}) void should_do_naming_convention_resp1(String selected) { LocalDateTime createdDate = LocalDateTime.of(2022, 05, 10, 12, 13, 12); - List> witnessEvidenceDocs = new ArrayList<>(); String witnessName = "ResOneWitness"; List options = List.of(EvidenceUploadHandlerBase.OPTION_DEF1, @@ -1409,11 +1447,12 @@ void should_do_naming_convention_resp1(String selected) { assertThat(updatedData.getDocumentAuthoritiesRes2().get(0).getValue() .getDocumentUpload().getDocumentFileName()).isEqualTo(TEST_FILE_NAME); assertThat(updatedData.getDocumentAuthoritiesRes2().get(0).getValue() - .getDocumentUpload().getCategoryID()).isEqualTo(EvidenceUploadHandlerBase.RESPONDENT_TWO_TRIAL_AUTHORITIES); + .getDocumentUpload().getCategoryID()).isEqualTo(EvidenceUploadHandlerBase.RESPONDENT_TWO_PRECEDENT_H); assertThat(updatedData.getDocumentCostsRes2().get(0).getValue() .getDocumentUpload().getDocumentFileName()).isEqualTo(TEST_FILE_NAME); assertThat(updatedData.getDocumentCostsRes2().get(0).getValue() - .getDocumentUpload().getCategoryID()).isEqualTo(EvidenceUploadHandlerBase.RESPONDENT_TWO_TRIAL_COSTS); + .getDocumentUpload().getCategoryID()).isEqualTo(EvidenceUploadHandlerBase.RESPONDENT_TWO_SCHEDULE_OF_COSTS); + assertThat(updatedData.getNotificationText()).contains(NotificationWhenBothDefendant); } } @@ -1484,6 +1523,59 @@ void should_do_naming_convention_resp2() { .getDocumentUpload().getDocumentFileName()).isEqualTo(TEST_FILE_NAME); assertThat(updatedData.getDocumentCostsRes2().get(0).getValue() .getDocumentUpload().getDocumentFileName()).isEqualTo(TEST_FILE_NAME); + assertThat(updatedData.getNotificationText()).isEqualTo(NotificationWhenDefendantTwo); + } + + @Test + void shouldNotAddSameNotificationIfAlreadyAdded_notificationText() { + // If we populate notification string with an entry, we do not want to duplicate that on further uploads of same type. + List options = List.of(EvidenceUploadHandlerBase.OPTION_DEF1, + EvidenceUploadHandlerBase.OPTION_DEF2, + EvidenceUploadHandlerBase.OPTION_DEF_BOTH); + LocalDate witnessDate = LocalDate.of(2023, 2, 10); + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .notificationText("Documentation that has been uploaded: \n\n Defendant 1 - Joint Statement of Experts / Single Joint Expert Report \n") + .applicant1(PartyBuilder.builder().individual().build()) + .evidenceUploadOptions(DynamicList.fromList(options, Object::toString, options.get(0), false)) + .documentJointStatementRes(createExpertDocs("expertsName", witnessDate, null, "expertises", null, null, null)) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + given(userService.getUserInfo(anyString())).willReturn(UserInfo.builder().uid("uid").build()); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).willReturn(true); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).willReturn(false); + given(coreCaseDataService.getCase(anyLong())).willReturn(CaseDetails.builder().build()); + // When handle is called + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + // Then Notificcation should not have a duplicate entry + assertThat(updatedData.getNotificationText()) + .isEqualTo("Documentation that has been uploaded: \n\n Defendant 1 - Joint Statement of Experts / Single Joint Expert Report \n"); + } + + @Test + void shouldNotPopulateNotificationWithOldDocument_whenNewDocumentUploadAdded() { + // When evidence upload is retriggered we do not send a notification for old content i.e uploaded before midnight of current day + List options = List.of(EvidenceUploadHandlerBase.OPTION_DEF1, + EvidenceUploadHandlerBase.OPTION_DEF2, + EvidenceUploadHandlerBase.OPTION_DEF_BOTH); + LocalDate witnessDate = LocalDate.of(2023, 2, 10); + String witnessName = "Witness"; + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .notificationText(null) + .evidenceUploadOptions(DynamicList.fromList(options, Object::toString, options.get(0), false)) + .documentWitnessStatementRes(createWitnessDocs(witnessName, LocalDateTime.now().minusDays(2), witnessDate)) + .documentWitnessSummaryRes(createWitnessDocs(witnessName, LocalDateTime.now(), witnessDate)) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + given(userService.getUserInfo(anyString())).willReturn(UserInfo.builder().uid("uid").build()); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).willReturn(true); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).willReturn(false); + given(coreCaseDataService.getCase(anyLong())).willReturn(CaseDetails.builder().build()); + // When handle is called + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + // Then Notification should not have old entry (witness statement) + assertThat(updatedData.getNotificationText()).isEqualTo("\nDefendant 1 - Witness summary"); } @Test diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/GenerateDirectionOrderCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/GenerateDirectionOrderCallbackHandlerTest.java index d77d1c28c22..9891b5f8586 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/GenerateDirectionOrderCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/GenerateDirectionOrderCallbackHandlerTest.java @@ -18,16 +18,27 @@ import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.documentmanagement.model.Document; import uk.gov.hmcts.reform.civil.enums.caseprogression.FinalOrderSelection; +import uk.gov.hmcts.reform.civil.enums.caseprogression.OrderOnCourtsList; +import uk.gov.hmcts.reform.civil.enums.finalorders.AssistedCostTypesList; +import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrderRepresentationList; import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrderToggle; +import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersJudgePapers; +import uk.gov.hmcts.reform.civil.enums.finalorders.HearingLengthFinalOrderList; +import uk.gov.hmcts.reform.civil.enums.finalorders.OrderMadeOnTypes; import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.HearingNotes; import uk.gov.hmcts.reform.civil.model.common.Element; import uk.gov.hmcts.reform.civil.model.finalorders.AppealChoiceSecondDropdown; import uk.gov.hmcts.reform.civil.model.finalorders.AppealGrantedRefused; import uk.gov.hmcts.reform.civil.model.finalorders.AssistedOrderCostDetails; +import uk.gov.hmcts.reform.civil.model.finalorders.AssistedOrderReasons; +import uk.gov.hmcts.reform.civil.model.finalorders.ClaimantAndDefendantHeard; import uk.gov.hmcts.reform.civil.model.finalorders.DatesFinalOrders; import uk.gov.hmcts.reform.civil.model.finalorders.FinalOrderAppeal; import uk.gov.hmcts.reform.civil.model.finalorders.FinalOrderFurtherHearing; +import uk.gov.hmcts.reform.civil.model.finalorders.FinalOrderRecitalsRecorded; +import uk.gov.hmcts.reform.civil.model.finalorders.FinalOrderRepresentation; import uk.gov.hmcts.reform.civil.model.finalorders.OrderMade; import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; @@ -55,14 +66,15 @@ import static uk.gov.hmcts.reform.civil.callback.CaseEvent.GENERATE_DIRECTIONS_ORDER; import static uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType.JUDGE_FINAL_ORDER; import static uk.gov.hmcts.reform.civil.enums.CaseState.CASE_PROGRESSION; -import static uk.gov.hmcts.reform.civil.enums.CaseState.JUDICIAL_REFERRAL; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; +import static uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersClaimantRepresentationList.CLAIMANT_NOT_ATTENDING; +import static uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersDefendantRepresentationList.DEFENDANT_NOT_ATTENDING; + import static uk.gov.hmcts.reform.civil.handler.callback.user.GenerateDirectionOrderCallbackHandler.BODY_1v1; import static uk.gov.hmcts.reform.civil.handler.callback.user.GenerateDirectionOrderCallbackHandler.BODY_1v2; import static uk.gov.hmcts.reform.civil.handler.callback.user.GenerateDirectionOrderCallbackHandler.BODY_2v1; import static uk.gov.hmcts.reform.civil.handler.callback.user.GenerateDirectionOrderCallbackHandler.HEADER; - import static uk.gov.hmcts.reform.civil.utils.ElementUtils.element; @ExtendWith(SpringExtension.class) @@ -130,6 +142,61 @@ void shouldReturnNoError_WhenAboutToStartIsInvoked() { var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); assertThat(response.getErrors()).isNull(); } + + @Test + void shouldNullPreviousSubmittedEventSelections_whenInvokedFreeForm() { + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.FREE_FORM_ORDER) + .freeFormRecordedTextArea("text") + .freeFormOrderedTextArea("text") + .orderOnCourtsList(OrderOnCourtsList.ORDER_ON_COURT_INITIATIVE) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_START); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getData().get("finalOrderSelection")).isNull(); + assertThat(response.getData().get("freeFormRecordedTextArea")).isNull(); + assertThat(response.getData().get("freeFormOrderedTextArea")).isNull(); + assertThat(response.getData().get("orderOnCourtsList")).isNull(); + } + + @Test + void shouldNullPreviousSubmittedEventSelections_whenInvokedAssisted() { + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderMadeSelection(YES).finalOrderDateHeardComplex(OrderMade.builder().build()) + .finalOrderJudgePapers(List.of(FinalOrdersJudgePapers.CONSIDERED)) + .finalOrderJudgeHeardFrom(List.of(FinalOrderToggle.SHOW)).finalOrderRepresentation(FinalOrderRepresentation.builder().build()) + .finalOrderRecitals(List.of(FinalOrderToggle.SHOW)).finalOrderRecitalsRecorded(FinalOrderRecitalsRecorded.builder().text("text").build()) + .finalOrderOrderedThatText("text") + .finalOrderFurtherHearingToggle(List.of(FinalOrderToggle.SHOW)).finalOrderFurtherHearingComplex(FinalOrderFurtherHearing.builder().build()) + .assistedOrderCostList(AssistedCostTypesList.MAKE_AN_ORDER_FOR_DETAILED_COSTS).assistedOrderCostsReserved(AssistedOrderCostDetails.builder().build()) + .assistedOrderMakeAnOrderForCosts(AssistedOrderCostDetails.builder().build()).assistedOrderCostsBespoke(AssistedOrderCostDetails.builder().build()) + .finalOrderAppealToggle(List.of(FinalOrderToggle.SHOW)).finalOrderAppealComplex(FinalOrderAppeal.builder().build()) + .orderMadeOnDetailsList(OrderMadeOnTypes.WITHOUT_NOTICE) + .finalOrderGiveReasonsComplex(AssistedOrderReasons.builder().reasonsText("text").build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_START); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getData().get("finalOrderSelection")).isNull(); + assertThat(response.getData().get("finalOrderMadeSelection")).isNull(); + assertThat(response.getData().get("finalOrderDateHeardComplex")).isNull(); + assertThat(response.getData().get("finalOrderJudgePapers")).isNull(); + assertThat(response.getData().get("finalOrderJudgeHeardFrom")).isNull(); + assertThat(response.getData().get("finalOrderRepresentation")).isNull(); + assertThat(response.getData().get("finalOrderRecitals")).isNull(); + assertThat(response.getData().get("finalOrderRecitalsRecorded")).isNull(); + assertThat(response.getData().get("finalOrderOrderedThatText")).isNull(); + assertThat(response.getData().get("finalOrderFurtherHearingToggle")).isNull(); + assertThat(response.getData().get("finalOrderFurtherHearingComplex")).isNull(); + assertThat(response.getData().get("assistedOrderCostList")).isNull(); + assertThat(response.getData().get("assistedOrderCostsReserved")).isNull(); + assertThat(response.getData().get("assistedOrderMakeAnOrderForCosts")).isNull(); + assertThat(response.getData().get("assistedOrderCostsBespoke")).isNull(); + assertThat(response.getData().get("finalOrderAppealToggle")).isNull(); + assertThat(response.getData().get("finalOrderAppealComplex")).isNull(); + assertThat(response.getData().get("orderMadeOnDetailsList")).isNull(); + assertThat(response.getData().get("finalOrderGiveReasonsComplex")).isNull(); + } } @Nested @@ -149,11 +216,11 @@ void shouldPopulateFreeFormOrderValues_onMidEventCallback() { "onInitiativeSelectionTextArea") .isEqualTo(ON_INITIATIVE_SELECTION_TEXT); assertThat(response.getData()).extracting("orderOnCourtInitiative").extracting("onInitiativeSelectionDate") - .isEqualTo(LocalDate.now().toString()); + .isEqualTo(LocalDate.now().plusDays(7).toString()); assertThat(response.getData()).extracting("orderWithoutNotice").extracting("withoutNoticeSelectionTextArea") .isEqualTo(WITHOUT_NOTICE_SELECTION_TEXT); assertThat(response.getData()).extracting("orderWithoutNotice").extracting("withoutNoticeSelectionDate") - .isEqualTo(LocalDate.now().toString()); + .isEqualTo(LocalDate.now().plusDays(7).toString()); } @@ -192,13 +259,13 @@ void shouldPopulateFields_whenIsCalledAfterSdo() { .isEqualTo("Mr. John Rambo"); assertThat(response.getData()).extracting("orderMadeOnDetailsOrderCourt") .extracting("ownInitiativeDate") - .isEqualTo(LocalDate.now().toString()); + .isEqualTo(LocalDate.now().plusDays(7).toString()); assertThat(response.getData()).extracting("orderMadeOnDetailsOrderWithoutNotice") .extracting("withOutNoticeText") .isEqualTo(WITHOUT_NOTICE_SELECTION_TEXT); assertThat(response.getData()).extracting("orderMadeOnDetailsOrderWithoutNotice") .extracting("withOutNoticeDate") - .isEqualTo(LocalDate.now().toString()); + .isEqualTo(LocalDate.now().plusDays(7).toString()); assertThat(response.getData()).extracting("assistedOrderMakeAnOrderForCosts") .extracting("assistedOrderCostsFirstDropdownDate") .isEqualTo(advancedDate); @@ -208,15 +275,37 @@ void shouldPopulateFields_whenIsCalledAfterSdo() { assertThat(response.getData()).extracting("assistedOrderMakeAnOrderForCosts") .extracting("makeAnOrderForCostsQOCSYesOrNo") .isEqualTo("No"); + assertThat(response.getData()).extracting("assistedOrderMakeAnOrderForCosts") + .extracting("makeAnOrderForCostsList") + .isEqualTo("CLAIMANT"); + assertThat(response.getData()).extracting("assistedOrderMakeAnOrderForCosts") + .extracting("assistedOrderClaimantDefendantFirstDropdown") + .isEqualTo("SUBJECT_DETAILED_ASSESSMENT"); + assertThat(response.getData()).extracting("assistedOrderMakeAnOrderForCosts") + .extracting("assistedOrderAssessmentSecondDropdownList1") + .isEqualTo("STANDARD_BASIS"); + assertThat(response.getData()).extracting("assistedOrderMakeAnOrderForCosts") + .extracting("assistedOrderAssessmentSecondDropdownList2") + .isEqualTo("NO"); assertThat(response.getData()).extracting("publicFundingCostsProtection") .isEqualTo("No"); assertThat(response.getData()).extracting("finalOrderAppealComplex") - .extracting("appealGrantedRefusedDropdown") + .extracting("appealGrantedDropdown") + .extracting("appealChoiceSecondDropdownA") + .extracting("appealGrantedRefusedDate") + .isEqualTo(LocalDate.now().plusDays(21).toString()); + assertThat(response.getData()).extracting("finalOrderAppealComplex") + .extracting("appealGrantedDropdown") + .extracting("appealChoiceSecondDropdownB") + .extracting("appealGrantedRefusedDate") + .isEqualTo(LocalDate.now().plusDays(21).toString()); + assertThat(response.getData()).extracting("finalOrderAppealComplex") + .extracting("appealRefusedDropdown") .extracting("appealChoiceSecondDropdownA") .extracting("appealGrantedRefusedDate") .isEqualTo(LocalDate.now().plusDays(21).toString()); assertThat(response.getData()).extracting("finalOrderAppealComplex") - .extracting("appealGrantedRefusedDropdown") + .extracting("appealRefusedDropdown") .extracting("appealChoiceSecondDropdownB") .extracting("appealGrantedRefusedDate") .isEqualTo(LocalDate.now().plusDays(21).toString()); @@ -256,72 +345,6 @@ void shouldPopulateFields_whenIsCalledAfterSdoDiffSol() { .isEqualTo("Mr. John Rambo"); } - - @Test - void shouldPopulateFields_whenIsCalledBeforeSdo() { - // Given - CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() - .addApplicant2(YES) - .applicant2(PartyBuilder.builder().individual().build()) - .ccdState(JUDICIAL_REFERRAL) - .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER).build(); - List locations = new ArrayList<>(); - locations.add(LocationRefData.builder().courtName("Court Name").region("Region").build()); - when(locationRefDataService.getCourtLocationsForDefaultJudgments(any())).thenReturn(locations); - CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); - String advancedDate = LocalDate.now().plusDays(14).toString(); - when(locationRefDataService.getCcmccLocation(any())).thenReturn(locationRefDataBeforeSdo); - // When - var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); - // Then - assertThat(response.getData()).extracting("orderMadeOnDetailsOrderCourt") - .extracting("ownInitiativeText") - .isEqualTo(ON_INITIATIVE_SELECTION_TEXT); - assertThat(response.getData()).extracting("finalOrderRepresentation") - .extracting("typeRepresentationComplex") - .extracting("typeRepresentationClaimantOneDynamic") - .isEqualTo("Mr. John Rambo"); - assertThat(response.getData()).extracting("finalOrderRepresentation") - .extracting("typeRepresentationComplex") - .extracting("typeRepresentationDefendantOneDynamic") - .isEqualTo("Mr. Sole Trader"); - assertThat(response.getData()).extracting("finalOrderRepresentation") - .extracting("typeRepresentationComplex") - .extracting("typeRepresentationClaimantTwoDynamic") - .isEqualTo("Mr. John Rambo"); - assertThat(response.getData()).extracting("orderMadeOnDetailsOrderCourt") - .extracting("ownInitiativeDate") - .isEqualTo(LocalDate.now().toString()); - assertThat(response.getData()).extracting("orderMadeOnDetailsOrderWithoutNotice") - .extracting("withOutNoticeText") - .isEqualTo(WITHOUT_NOTICE_SELECTION_TEXT); - assertThat(response.getData()).extracting("orderMadeOnDetailsOrderWithoutNotice") - .extracting("withOutNoticeDate") - .isEqualTo(LocalDate.now().toString()); - assertThat(response.getData()).extracting("assistedOrderMakeAnOrderForCosts") - .extracting("assistedOrderCostsFirstDropdownDate") - .isEqualTo(advancedDate); - assertThat(response.getData()).extracting("assistedOrderMakeAnOrderForCosts") - .extracting("assistedOrderAssessmentThirdDropdownDate") - .isEqualTo(advancedDate); - assertThat(response.getData()).extracting("assistedOrderMakeAnOrderForCosts") - .extracting("makeAnOrderForCostsQOCSYesOrNo") - .isEqualTo("No"); - assertThat(response.getData()).extracting("publicFundingCostsProtection") - .isEqualTo("No"); - assertThat(response.getData()).extracting("finalOrderAppealComplex") - .extracting("appealGrantedRefusedDropdown") - .extracting("appealChoiceSecondDropdownA") - .extracting("appealGrantedRefusedDate") - .isEqualTo(LocalDate.now().plusDays(21).toString()); - assertThat(response.getData()).extracting("finalOrderAppealComplex") - .extracting("appealGrantedRefusedDropdown") - .extracting("appealChoiceSecondDropdownB") - .extracting("appealGrantedRefusedDate") - .isEqualTo(LocalDate.now().plusDays(21).toString()); - assertThat(response.getData()).extracting("finalOrderFurtherHearingComplex") - .extracting("hearingLocationList").asString().contains("SiteName before Sdo"); - } } @Nested @@ -410,6 +433,14 @@ static Stream validAssistedOrderDates() { .datesToAvoidDates(LocalDate.now().plusDays(2)) .build()).build()).build() ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing.builder() + .dateToDate(LocalDate.now().minusDays(4)) + .listFromDate(LocalDate.now().minusDays(5)) + .build()).build() + ), Arguments.of( CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) @@ -439,7 +470,7 @@ static Stream validAssistedOrderDates() { CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) .finalOrderAppealComplex(FinalOrderAppeal.builder() - .appealGrantedRefusedDropdown(AppealGrantedRefused.builder() + .appealGrantedDropdown(AppealGrantedRefused.builder() .appealChoiceSecondDropdownA(AppealChoiceSecondDropdown.builder() .appealGrantedRefusedDate(LocalDate.now().plusDays(21)) .build()).build()).build()).build() @@ -448,10 +479,28 @@ static Stream validAssistedOrderDates() { CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) .finalOrderAppealComplex(FinalOrderAppeal.builder() - .appealGrantedRefusedDropdown(AppealGrantedRefused.builder() + .appealGrantedDropdown(AppealGrantedRefused.builder() .appealChoiceSecondDropdownB(AppealChoiceSecondDropdown.builder() .appealGrantedRefusedDate(LocalDate.now().plusDays(21)) .build()).build()).build()).build() + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderAppealComplex(FinalOrderAppeal.builder() + .appealRefusedDropdown(AppealGrantedRefused.builder() + .appealChoiceSecondDropdownA(AppealChoiceSecondDropdown.builder() + .appealGrantedRefusedDate(LocalDate.now().plusDays(21)) + .build()).build()).build()).build() + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderAppealComplex(FinalOrderAppeal.builder() + .appealRefusedDropdown(AppealGrantedRefused.builder() + .appealChoiceSecondDropdownB(AppealChoiceSecondDropdown.builder() + .appealGrantedRefusedDate(LocalDate.now().plusDays(21)) + .build()).build()).build()).build() ) ); } @@ -503,7 +552,16 @@ static Stream invalidAssistedOrderDates() { "The date in Further hearing may not be before the established date" ), Arguments.of( - CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing.builder() + .dateToDate(LocalDate.now().minusDays(5)) + .listFromDate(LocalDate.now().minusDays(4)) + .build()).build(), + "The date range in Further hearing may not have a 'from date', that is after the 'date to'" + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) .assistedOrderMakeAnOrderForCosts(AssistedOrderCostDetails.builder() .assistedOrderCostsFirstDropdownDate(LocalDate.now().minusDays(2)) @@ -524,7 +582,7 @@ static Stream invalidAssistedOrderDates() { CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) .finalOrderAppealComplex(FinalOrderAppeal.builder() - .appealGrantedRefusedDropdown(AppealGrantedRefused.builder() + .appealGrantedDropdown(AppealGrantedRefused.builder() .appealChoiceSecondDropdownA(AppealChoiceSecondDropdown.builder() .appealGrantedRefusedDate(LocalDate.now().minusDays(1)) .build()).build()).build()).build(), @@ -534,11 +592,187 @@ static Stream invalidAssistedOrderDates() { CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) .finalOrderAppealComplex(FinalOrderAppeal.builder() - .appealGrantedRefusedDropdown(AppealGrantedRefused.builder() + .appealGrantedDropdown(AppealGrantedRefused.builder() .appealChoiceSecondDropdownB(AppealChoiceSecondDropdown.builder() .appealGrantedRefusedDate(LocalDate.now().minusDays(1)) .build()).build()).build()).build(), "The date in Appeal notice date may not be before the established date" + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderAppealComplex(FinalOrderAppeal.builder() + .appealRefusedDropdown(AppealGrantedRefused.builder() + .appealChoiceSecondDropdownA(AppealChoiceSecondDropdown.builder() + .appealGrantedRefusedDate(LocalDate.now().minusDays(1)) + .build()).build()).build()).build(), + "The date in Appeal notice date may not be before the established date" + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderAppealComplex(FinalOrderAppeal.builder() + .appealRefusedDropdown(AppealGrantedRefused.builder() + .appealChoiceSecondDropdownB(AppealChoiceSecondDropdown.builder() + .appealGrantedRefusedDate(LocalDate.now().minusDays(1)) + .build()).build()).build()).build(), + "The date in Appeal notice date may not be before the established date" + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderFurtherHearingToggle(List.of(FinalOrderToggle.SHOW)) + .finalOrderFurtherHearingComplex( + FinalOrderFurtherHearing.builder().lengthList(HearingLengthFinalOrderList.OTHER) + .build()).build(), + "Further hearing, Length of new hearing, Other is empty" + ) + ); + } + + @ParameterizedTest + @MethodSource("validJudgeHeardFrom") + void validateJudgeHeardFromSection_shouldReturnNoError(CaseData caseData) { + // When + when(judgeFinalOrderGenerator.generate(any(), any())).thenReturn(finalOrder); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(callbackParamsOf(caseData, MID, PAGE_ID)); + // Then + assertThat(response.getErrors()).isEmpty(); + } + + static Stream validJudgeHeardFrom() { + List toggle = new ArrayList<>(); + toggle.add(FinalOrderToggle.SHOW); + return Stream.of( + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderJudgeHeardFrom(toggle) + .finalOrderRepresentation(FinalOrderRepresentation.builder() + .typeRepresentationList(FinalOrderRepresentationList.CLAIMANT_AND_DEFENDANT) + .typeRepresentationComplex(ClaimantAndDefendantHeard.builder() + .typeRepresentationDefendantOneDynamic("defendant one") + .typeRepresentationClaimantOneDynamic("claimant one") + .typeRepresentationClaimantList(CLAIMANT_NOT_ATTENDING) + .typeRepresentationDefendantList(DEFENDANT_NOT_ATTENDING) + .build()).build()).build() + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .addRespondent2(YES) + .respondent2(PartyBuilder.builder().individual().build()) + .respondent2SameLegalRepresentative(NO) + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderJudgeHeardFrom(toggle) + .finalOrderRepresentation(FinalOrderRepresentation.builder() + .typeRepresentationList(FinalOrderRepresentationList.CLAIMANT_AND_DEFENDANT) + .typeRepresentationComplex(ClaimantAndDefendantHeard.builder() + .typeRepresentationDefendantOneDynamic("defendant one") + .typeRepresentationDefendantTwoDynamic("defendant two") + .typeRepresentationClaimantOneDynamic("claimant one") + .typeRepresentationClaimantList(CLAIMANT_NOT_ATTENDING) + .typeRepresentationDefendantList(DEFENDANT_NOT_ATTENDING) + .typeRepresentationDefendantTwoList(DEFENDANT_NOT_ATTENDING) + .build()).build()).build() + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .addApplicant2(YES) + .applicant2(PartyBuilder.builder().individual().build()) + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderJudgeHeardFrom(toggle) + .finalOrderRepresentation(FinalOrderRepresentation.builder() + .typeRepresentationList(FinalOrderRepresentationList.CLAIMANT_AND_DEFENDANT) + .typeRepresentationComplex(ClaimantAndDefendantHeard.builder() + .typeRepresentationDefendantOneDynamic("defendant one") + .typeRepresentationClaimantOneDynamic("claimant one") + .typeRepresentationClaimantTwoDynamic("claimant one") + .typeRepresentationClaimantList(CLAIMANT_NOT_ATTENDING) + .typeRepresentationDefendantList(DEFENDANT_NOT_ATTENDING) + .typeRepresentationClaimantListTwo(CLAIMANT_NOT_ATTENDING) + .build()).build()).build() + ) + ); + } + + @ParameterizedTest + @MethodSource("invalidJudgeHeardFrom") + void validateJudgeHeardFromSection_shouldReturnErrors(CaseData caseData, String expectedErrorMessage) { + // When + when(judgeFinalOrderGenerator.generate(any(), any())).thenReturn(finalOrder); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(callbackParamsOf(caseData, MID, PAGE_ID)); + // Then + assertThat(response.getErrors().get(0)).isEqualTo(expectedErrorMessage);; + } + + static Stream invalidJudgeHeardFrom() { + List toggle = new ArrayList<>(); + toggle.add(FinalOrderToggle.SHOW); + return Stream.of( + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderJudgeHeardFrom(toggle) + .finalOrderRepresentation(FinalOrderRepresentation.builder() + .typeRepresentationList(FinalOrderRepresentationList.CLAIMANT_AND_DEFENDANT) + .typeRepresentationComplex(ClaimantAndDefendantHeard.builder() + .typeRepresentationDefendantOneDynamic("defendant one") + .typeRepresentationClaimantOneDynamic("claimant one") + .typeRepresentationClaimantList(null) + .typeRepresentationDefendantList(DEFENDANT_NOT_ATTENDING) + .build()).build()).build(), + "Judge Heard from: 'Claimant(s) and defendant(s)' section for claimant, requires a selection to be made" + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderJudgeHeardFrom(toggle) + .finalOrderRepresentation(FinalOrderRepresentation.builder() + .typeRepresentationList(FinalOrderRepresentationList.CLAIMANT_AND_DEFENDANT) + .typeRepresentationComplex(ClaimantAndDefendantHeard.builder() + .typeRepresentationDefendantOneDynamic("defendant one") + .typeRepresentationClaimantOneDynamic("claimant one") + .typeRepresentationClaimantList(CLAIMANT_NOT_ATTENDING) + .typeRepresentationDefendantList(null) + .build()).build()).build(), + "Judge Heard from: 'Claimant(s) and defendant(s)' section for defendant, requires a selection to be made" + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .addRespondent2(YES) + .respondent2(PartyBuilder.builder().individual().build()) + .respondent2SameLegalRepresentative(NO) + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderJudgeHeardFrom(toggle) + .finalOrderRepresentation(FinalOrderRepresentation.builder() + .typeRepresentationList(FinalOrderRepresentationList.CLAIMANT_AND_DEFENDANT) + .typeRepresentationComplex(ClaimantAndDefendantHeard.builder() + .typeRepresentationDefendantOneDynamic("defendant one") + .typeRepresentationDefendantTwoDynamic("defendant two") + .typeRepresentationClaimantOneDynamic("claimant one") + .typeRepresentationClaimantList(CLAIMANT_NOT_ATTENDING) + .typeRepresentationDefendantList(DEFENDANT_NOT_ATTENDING) + .typeRepresentationDefendantTwoList(null) + .build()).build()).build(), + "Judge Heard from: 'Claimant(s) and defendant(s)' section for second defendant, requires a selection to be made" + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .addApplicant2(YES) + .applicant2(PartyBuilder.builder().individual().build()) + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderJudgeHeardFrom(toggle) + .finalOrderRepresentation(FinalOrderRepresentation.builder() + .typeRepresentationList(FinalOrderRepresentationList.CLAIMANT_AND_DEFENDANT) + .typeRepresentationComplex(ClaimantAndDefendantHeard.builder() + .typeRepresentationDefendantOneDynamic("defendant one") + .typeRepresentationClaimantOneDynamic("claimant one") + .typeRepresentationClaimantTwoDynamic("claimant one") + .typeRepresentationClaimantList(CLAIMANT_NOT_ATTENDING) + .typeRepresentationClaimantListTwo(null) + .typeRepresentationDefendantList(DEFENDANT_NOT_ATTENDING) + .build()).build()).build(), + "Judge Heard from: 'Claimant(s) and defendant(s)' section for second claimant, requires a selection to be made" ) ); } @@ -555,16 +789,16 @@ void shouldAddDocumentToCollection_onAboutToSubmit() { CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) .finalOrderDocumentCollection(finalCaseDocuments) + .finalOrderDocument(finalOrder) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); // When - when(judgeFinalOrderGenerator.generate(any(), any())).thenReturn(finalOrder); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); // Then assertThat(response.getData()).extracting("finalOrderDocumentCollection").isNotNull(); assertThat(updatedData.getFinalOrderDocumentCollection().get(0) - .getValue().getDocumentLink().getCategoryID().equals("finalOrders")); + .getValue().getDocumentLink().getCategoryID()).isEqualTo("finalOrders"); } @Test @@ -575,10 +809,10 @@ void shouldChangeStateToFinalOrder_onAboutToSubmitAndFreeFormOrder() { CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderSelection(FinalOrderSelection.FREE_FORM_ORDER) .finalOrderDocumentCollection(finalCaseDocuments) + .finalOrderDocument(finalOrder) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); // When - when(judgeFinalOrderGenerator.generate(any(), any())).thenReturn(finalOrder); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); // Then assertThat(response.getState()).isEqualTo("All_FINAL_ORDERS_ISSUED"); @@ -593,10 +827,10 @@ void shouldChangeStateToFinalOrder_onAboutToSubmitAndAssistedOrderAndNoFurtherHe .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) .finalOrderFurtherHearingToggle(null) .finalOrderDocumentCollection(finalCaseDocuments) + .finalOrderDocument(finalOrder) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); // When - when(judgeFinalOrderGenerator.generate(any(), any())).thenReturn(finalOrder); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); // Then assertThat(response.getState()).isEqualTo("All_FINAL_ORDERS_ISSUED"); @@ -613,14 +847,86 @@ void shouldChangeStateToCaseProgression_onAboutToSubmitAndAssistedOrderWithFurth .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) .finalOrderFurtherHearingToggle(toggle) .finalOrderDocumentCollection(finalCaseDocuments) + .finalOrderDocument(finalOrder) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); // When - when(judgeFinalOrderGenerator.generate(any(), any())).thenReturn(finalOrder); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); // Then assertThat(response.getState()).isEqualTo("CASE_PROGRESSION"); } + + @Test + void shouldRePopulateHearingNotes_whenAssistedHearingNotesExist() { + // Given + List toggle = new ArrayList<>(); + toggle.add(FinalOrderToggle.SHOW); + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderFurtherHearingToggle(toggle) + .finalOrderDocument(finalOrder) + .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing.builder() + .hearingNotesText("test text hearing notes assisted order").build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + // When + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + // Then + assertThat(response.getData()).extracting("hearingNotes").extracting("notes").isEqualTo("test text hearing notes assisted order"); + } + + @Test + void shouldRePopulateHearingNotes_whenFreeFormHearingNotesExist() { + // Given + List toggle = new ArrayList<>(); + toggle.add(FinalOrderToggle.SHOW); + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.FREE_FORM_ORDER) + .freeFormHearingNotes("test text hearing notes free form order") + .finalOrderDocument(finalOrder) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + // When + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + // Then + assertThat(response.getData()).extracting("hearingNotes").extracting("notes").isEqualTo("test text hearing notes free form order"); + } + + @Test + void shouldNotRePopulateHearingNotes_whenAssistedHearingNotesDoNotExist() { + // Given + List toggle = new ArrayList<>(); + toggle.add(FinalOrderToggle.SHOW); + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) + .finalOrderFurtherHearingToggle(toggle) + .finalOrderDocument(finalOrder) + .hearingNotes(HearingNotes.builder().notes("preexisting hearing notes").build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + // When + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + // Then + assertThat(response.getData()).extracting("hearingNotes").extracting("notes").isEqualTo("preexisting hearing notes"); + } + + @Test + void shouldNotRePopulateHearingNotes_whenFreeFormHearingNotesDoNotExist() { + // Given + List toggle = new ArrayList<>(); + toggle.add(FinalOrderToggle.SHOW); + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderSelection(FinalOrderSelection.FREE_FORM_ORDER) + .finalOrderFurtherHearingToggle(toggle) + .hearingNotes(HearingNotes.builder().notes("preexisting hearing notes").build()) + .finalOrderDocument(finalOrder) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + // When + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + // Then + assertThat(response.getData()).extracting("hearingNotes").extracting("notes").isEqualTo("preexisting hearing notes"); + } } @Nested diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/HearingScheduledHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/HearingScheduledHandlerTest.java index 01edb1be745..0f8595eb50d 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/HearingScheduledHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/HearingScheduledHandlerTest.java @@ -24,6 +24,9 @@ import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.enums.AllocatedTrack; import uk.gov.hmcts.reform.civil.enums.CaseState; +import uk.gov.hmcts.reform.civil.enums.hearing.HearingChannel; +import uk.gov.hmcts.reform.civil.enums.hearing.HearingDuration; +import uk.gov.hmcts.reform.civil.enums.hearing.HearingNoticeList; import uk.gov.hmcts.reform.civil.enums.hearing.ListingOrRelisting; import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; @@ -40,6 +43,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; @@ -74,6 +78,34 @@ public void prepareTest() { given(feesService.getFeeForHearingFastTrackClaims(any())).willReturn(Fee.builder().build()); } + @Test + void shouldNullPreviousSubmittedEventSelections_whenInvoked() { + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .hearingNoticeList(HearingNoticeList.OTHER) + .hearingNoticeListOther("hearing notice list other") + .listingOrRelisting(ListingOrRelisting.LISTING) + .hearingLocation(DynamicList.builder().listItems(List.of( + DynamicListElement.builder().label("element 1").code("E0").build(), + DynamicListElement.builder().label("element 2").code("E1").build())).build()) + .channel(HearingChannel.IN_PERSON) + .hearingDate(LocalDate.now()) + .hearingTimeHourMinute("hearingTimeHourMinute") + .hearingDuration(HearingDuration.DAY_1) + .information("hearing info") + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_START); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getData().get("hearingNoticeList")).isNull(); + assertThat(response.getData().get("listingOrRelisting")).isNull(); + assertThat(response.getData().get("hearingLocation")).isNull(); + assertThat(response.getData().get("channel")).isNull(); + assertThat(response.getData().get("hearingDate")).isNull(); + assertThat(response.getData().get("hearingTimeHourMinute")).isNull(); + assertThat(response.getData().get("hearingDuration")).isNull(); + assertThat(response.getData().get("information")).isNull(); + assertThat(response.getData().get("hearingNoticeListOther")).isNull(); + } + @ParameterizedTest @ValueSource(strings = { "locationName" }) void shouldReturnLocationList_whenLocationsAreQueried(String pageId) { diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/InitiateGeneralApplicationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/InitiateGeneralApplicationHandlerTest.java index ecdde2ea2ad..0c1e5fa4b7f 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/InitiateGeneralApplicationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/InitiateGeneralApplicationHandlerTest.java @@ -33,6 +33,7 @@ import uk.gov.hmcts.reform.civil.service.InitiateGeneralApplicationServiceHelper; import uk.gov.hmcts.reform.civil.service.OrganisationService; import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; +import uk.gov.hmcts.reform.civil.utils.UserRoleCaching; import uk.gov.hmcts.reform.idam.client.IdamClient; import uk.gov.hmcts.reform.idam.client.models.UserDetails; import uk.gov.hmcts.reform.civil.prd.model.Organisation; @@ -60,13 +61,13 @@ import static uk.gov.hmcts.reform.civil.enums.dq.GAHearingSupportRequirements.OTHER_SUPPORT; import static uk.gov.hmcts.reform.civil.enums.dq.GAHearingType.IN_PERSON; import static uk.gov.hmcts.reform.civil.enums.dq.GeneralApplicationTypes.EXTEND_TIME; -import static uk.gov.hmcts.reform.civil.enums.dq.GeneralApplicationTypes.SETTLE_OR_DISCONTINUE_CONSENT; +import static uk.gov.hmcts.reform.civil.enums.dq.GeneralApplicationTypes.SETTLE_BY_CONSENT; import static uk.gov.hmcts.reform.civil.enums.dq.GeneralApplicationTypes.STAY_THE_CLAIM; import static uk.gov.hmcts.reform.civil.enums.dq.GeneralApplicationTypes.STRIKE_OUT; import static uk.gov.hmcts.reform.civil.enums.dq.GeneralApplicationTypes.SUMMARY_JUDGEMENT; import static uk.gov.hmcts.reform.civil.enums.dq.GeneralApplicationTypes.VARY_JUDGEMENT; import static uk.gov.hmcts.reform.civil.enums.dq.GeneralApplicationTypes.VARY_ORDER; -import static uk.gov.hmcts.reform.civil.service.InitiateGeneralApplicationService.INVALID_SETTLE_OR_DISCONTINUE_CONSENT; +import static uk.gov.hmcts.reform.civil.service.InitiateGeneralApplicationService.INVALID_SETTLE_BY_CONSENT; import static uk.gov.hmcts.reform.civil.service.InitiateGeneralApplicationService.INVALID_TRIAL_DATE_RANGE; import static uk.gov.hmcts.reform.civil.service.InitiateGeneralApplicationService.INVALID_UNAVAILABILITY_RANGE; import static uk.gov.hmcts.reform.civil.service.InitiateGeneralApplicationService.TRIAL_DATE_FROM_REQUIRED; @@ -108,6 +109,9 @@ class InitiateGeneralApplicationHandlerTest extends BaseCallbackHandlerTest { @MockBean protected LocationRefDataService locationRefDataService; + @MockBean + protected UserRoleCaching userRoleCaching; + public static final String APPLICANT_EMAIL_ID_CONSTANT = "testUser@gmail.com"; public static final String RESPONDENT_EMAIL_ID_CONSTANT = "respondent@gmail.com"; @@ -271,7 +275,7 @@ void shouldNotCauseAnyErrorsWhenGaTypeIsMultipleTypeWithVaryJudgement() { @Test void shouldNotCauseAnyErrorsWhenGaTypeIsMultipleTypeWithSettleOrDiscontinueConsent() { List types = List.of(STRIKE_OUT, SUMMARY_JUDGEMENT, - SETTLE_OR_DISCONTINUE_CONSENT); + SETTLE_BY_CONSENT); CaseData caseData = CaseDataBuilder .builder().generalAppType(GAApplicationType.builder().types(types).build()).build(); @@ -284,7 +288,7 @@ void shouldNotCauseAnyErrorsWhenGaTypeIsMultipleTypeWithSettleOrDiscontinueConse assertThat(responseCaseData.getGeneralAppVaryJudgementType()).isEqualTo(NO); assertThat(response.getErrors().size()).isEqualTo(1); assertThat(response.getErrors().get(0).equals("It is not possible to select an additional application type " + - "when applying to settle or discontinue by consent")); + "when applying to Settle by consent")); } } @@ -376,7 +380,7 @@ void shouldNotCauseAnyErrors_whenGaTypeIsNotSettleOrDiscontinueConsent() { @Test void shouldNotCauseAnyErrors_whenGaTypeIsNotSettleOrDiscontinueConsentYes() { - List types = List.of(SETTLE_OR_DISCONTINUE_CONSENT); + List types = List.of(SETTLE_BY_CONSENT); CaseData caseData = CaseDataBuilder .builder().generalAppType(GAApplicationType.builder().types(types).build()) .build().toBuilder() @@ -394,7 +398,7 @@ void shouldNotCauseAnyErrors_whenGaTypeIsNotSettleOrDiscontinueConsentYes() { @Test void shouldCauseError_whenGaTypeIsNotSettleOrDiscontinueConsentNo() { - List types = List.of(SETTLE_OR_DISCONTINUE_CONSENT); + List types = List.of(SETTLE_BY_CONSENT); CaseData caseData = CaseDataBuilder .builder().generalAppType(GAApplicationType.builder().types(types).build()) .build().toBuilder() @@ -407,7 +411,7 @@ void shouldCauseError_whenGaTypeIsNotSettleOrDiscontinueConsentNo() { var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); assertThat(response.getErrors()).isNotEmpty(); - assertThat(response.getErrors()).contains(INVALID_SETTLE_OR_DISCONTINUE_CONSENT); + assertThat(response.getErrors()).contains(INVALID_SETTLE_BY_CONSENT); } } @@ -980,7 +984,7 @@ void shouldNotReturnErrors_whenRespondentSolAssignedToCase() { given(locationRefDataService.getCourtLocationsForGeneralApplication(any())).willReturn(locations); CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build(); - given(initiateGeneralAppService.respondentAssigned(any())).willReturn(true); + given(initiateGeneralAppService.respondentAssigned(any(), any())).willReturn(true); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_START); @@ -1005,7 +1009,7 @@ void shouldReturnErrors_whenNoRespondentSolAssignedToCase() { .courtName("Court Name").region("Region").build()); given(locationRefDataService.getCourtLocationsForGeneralApplication(any())).willReturn(locations); CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build(); - given(initiateGeneralAppService.respondentAssigned(any())).willReturn(false); + given(initiateGeneralAppService.respondentAssigned(any(), any())).willReturn(false); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_START); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/InitiateGeneralApplicationServiceHelperTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/InitiateGeneralApplicationServiceHelperTest.java index 7a99513e52f..9f2c10dcfc0 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/InitiateGeneralApplicationServiceHelperTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/InitiateGeneralApplicationServiceHelperTest.java @@ -25,6 +25,7 @@ import uk.gov.hmcts.reform.civil.service.InitiateGeneralApplicationServiceHelper; import uk.gov.hmcts.reform.civil.service.UserService; import uk.gov.hmcts.reform.civil.utils.ElementUtils; +import uk.gov.hmcts.reform.civil.utils.UserRoleCaching; import uk.gov.hmcts.reform.idam.client.IdamClient; import uk.gov.hmcts.reform.idam.client.models.UserDetails; @@ -78,6 +79,9 @@ public class InitiateGeneralApplicationServiceHelperTest { @MockBean protected IdamClient idamClient; + @MockBean + protected UserRoleCaching userRoleCaching; + public UserDetails getUserDetails(String id, String email) { return UserDetails.builder().id(id) .email(email) diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/JudgmentPaidInFullCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/JudgmentPaidInFullCallbackHandlerTest.java new file mode 100644 index 00000000000..96a20dcd1a0 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/JudgmentPaidInFullCallbackHandlerTest.java @@ -0,0 +1,139 @@ +package uk.gov.hmcts.reform.civil.handler.callback.user; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.SubmittedCallbackResponse; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CallbackType; +import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentPaidInFull; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentStatusType; +import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; +import java.time.LocalDate; +import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.JUDGMENT_PAID_IN_FULL; + +@SpringBootTest(classes = { + JacksonAutoConfiguration.class, + JudgmentPaidInFullCallbackHandler.class +}) +class JudgmentPaidInFullCallbackHandlerTest extends BaseCallbackHandlerTest { + + @Autowired + private JudgmentPaidInFullCallbackHandler handler; + + @Autowired + private ObjectMapper objectMapper; + + @Test + void handleEventsReturnsTheExpectedCallbackEvents() { + assertThat(handler.handledEvents()).containsOnly(JUDGMENT_PAID_IN_FULL); + } + + @Nested + class AboutToSubmitCallback { + @Test + void shouldPopulateDate() { + //Given: Casedata is in All_FINAL_ORDERS_ISSUED State and Record Judgement is done + CaseData caseData = CaseDataBuilder.builder().buildJudgmentOnlineCaseWithMarkJudgementPaidAfter30Days(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + //When: handler is called with ABOUT_TO_SUBMIT event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + //Then: judgmentOnline fields should be set correctly + var judgmentPaid = JudgmentPaidInFull.builder() + .dateOfFullPaymentMade(LocalDate.of(2023, 9, 15)) + .confirmFullPaymentMade(List.of("CONFIRMED")) + .build(); + + assertThat(response.getData().get("joJudgmentPaidInFull")).extracting("dateOfFullPaymentMade").isEqualTo("2023-09-15"); + assertThat(response.getData().get("joJudgmentPaidInFull")).extracting("confirmFullPaymentMade").isEqualTo(List.of("CONFIRMED")); + } + + @Test + void shouldPopulateJudgementStatusAsSatisfied() { + //Given: Casedata is in All_FINAL_ORDERS_ISSUED State and Record Judgement is done + CaseData caseData = CaseDataBuilder.builder().buildJudgmentOnlineCaseWithMarkJudgementPaidAfter30Days(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + //When: handler is called with ABOUT_TO_SUBMIT event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + //Then: judgmentOnline fields should be set correctly + var judgmentPaid = JudgmentPaidInFull.builder() + .dateOfFullPaymentMade(LocalDate.of(2023, 9, 15)) + .confirmFullPaymentMade(List.of("CONFIRMED")) + .build(); + + assertThat(response.getData().get("joJudgmentPaidInFull")).extracting("dateOfFullPaymentMade").isEqualTo("2023-09-15"); + assertThat(response.getData().get("joJudgmentPaidInFull")).extracting("confirmFullPaymentMade").isEqualTo(List.of("CONFIRMED")); + assertThat(response.getData().get("joJudgmentStatusDetails")).extracting("judgmentStatusTypes").isEqualTo( + JudgmentStatusType.SATISFIED.name()); + assertThat(response.getData().get("joJudgmentStatusDetails")).extracting("joRtlState").isEqualTo("S"); + assertThat(response.getData().get("joIsLiveJudgmentExists")).isEqualTo("No"); + + } + + @Test + void shouldPopulateJudgementStatusAsCancelled() { + //Given: Casedata is in All_FINAL_ORDERS_ISSUED State and Record Judgement is done + CaseData caseData = CaseDataBuilder.builder().buildJudgmentOnlineCaseWithMarkJudgementPaidWithin30Days(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + //When: handler is called with ABOUT_TO_SUBMIT event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + //Then: judgmentOnline fields should be set correctly + var judgmentPaid = JudgmentPaidInFull.builder() + .dateOfFullPaymentMade(LocalDate.of(2023, 9, 15)) + .confirmFullPaymentMade(List.of("CONFIRMED")) + .build(); + + assertThat(response.getData().get("joJudgmentPaidInFull")).extracting("dateOfFullPaymentMade").isEqualTo("2023-09-15"); + assertThat(response.getData().get("joJudgmentPaidInFull")).extracting("confirmFullPaymentMade").isEqualTo(List.of("CONFIRMED")); + assertThat(response.getData().get("joJudgmentStatusDetails")).extracting("judgmentStatusTypes").isEqualTo( + JudgmentStatusType.CANCELLED.name()); + assertThat(response.getData().get("joJudgmentStatusDetails")).extracting("joRtlState").isEqualTo("C"); + assertThat(response.getData().get("joIsLiveJudgmentExists")).isEqualTo("No"); + } + } + + @Nested + class MidCallback { + @Test + void shouldValidatePaymentMadeDate() { + + CaseData caseData = CaseDataBuilder.builder().buildJudgmentOnlineCaseWithMarkJudgementPaidAfter30Days(); + caseData.getJoJudgmentPaidInFull().setDateOfFullPaymentMade(LocalDate.now().minusDays(2)); + + CallbackParams params = callbackParamsOf(caseData, MID, "validate-payment-date"); + //When: handler is called with MID event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors().contains("Date must be in past")); + } + } + + @Nested + class SubmittedCallback { + @Test + public void whenSubmitted_thenIncludeHeader() { + CaseData caseData = CaseDataBuilder.builder().buildJudgmentOnlineCaseWithMarkJudgementPaidAfter30Days(); + CallbackParams params = CallbackParams.builder() + .caseData(caseData) + .type(CallbackType.SUBMITTED) + .build(); + SubmittedCallbackResponse response = + (SubmittedCallbackResponse) handler.handle(params); + Assertions.assertTrue(response.getConfirmationHeader().contains("# Judgment marked as paid in full")); + Assertions.assertTrue(response.getConfirmationBody().contains("The judgment has been marked as paid in full")); + } + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/LIPClaimSettledCallBackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/LIPClaimSettledCallBackHandlerTest.java new file mode 100644 index 00000000000..4ea303a584a --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/LIPClaimSettledCallBackHandlerTest.java @@ -0,0 +1,73 @@ +package uk.gov.hmcts.reform.civil.handler.callback.user; + +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.LIP_CLAIM_SETTLED; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = { + LIPClaimSettledCallbackHandler.class, + JacksonAutoConfiguration.class, +}) +public class LIPClaimSettledCallBackHandlerTest extends BaseCallbackHandlerTest { + + @Autowired + private LIPClaimSettledCallbackHandler handler; + + @Nested + class AboutToStartCallback { + + @Test + void shouldReturnNoError_WhenAboutToStartIsInvoked() { + CaseData caseData = CaseDataBuilder.builder().atStateClaimIssued().build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_START); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getErrors()).isNull(); + } + } + + @Nested + class AboutToSubmitCallback { + + @Test + void shouldUpdateBusinessProcess() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued() + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getData()) + .extracting("businessProcess") + .extracting("camundaEvent") + .isEqualTo(LIP_CLAIM_SETTLED.name()); + assertThat(response.getData()) + .extracting("businessProcess") + .extracting("status") + .isEqualTo("READY"); + } + } + + @Test + void handleEventsReturnsTheExpectedCallbackEvent() { + assertThat(handler.handledEvents()).contains(LIP_CLAIM_SETTLED); + } + +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/LiftBreathingSpaceLipCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/LiftBreathingSpaceLipCallbackHandlerTest.java new file mode 100644 index 00000000000..e0952dd4833 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/LiftBreathingSpaceLipCallbackHandlerTest.java @@ -0,0 +1,57 @@ +package uk.gov.hmcts.reform.civil.handler.callback.user; + +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.LIFT_BREATHING_SPACE_LIP; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = { + LiftBreathingSpaceLipCallbackHandler.class, + JacksonAutoConfiguration.class, +}) +class LiftBreathingSpaceLipCallbackHandlerTest extends BaseCallbackHandlerTest { + + @Autowired + private LiftBreathingSpaceLipCallbackHandler handler; + + @Nested + class AboutToSubmitCallback { + + @Test + void shouldUpdateBusinessProcess() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued() + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getData()) + .extracting("businessProcess") + .extracting("camundaEvent") + .isEqualTo(LIFT_BREATHING_SPACE_LIP.name()); + assertThat(response.getData()) + .extracting("businessProcess") + .extracting("status") + .isEqualTo("READY"); + } + } + + @Test + void handleEventsReturnsTheExpectedCallbackEvent() { + assertThat(handler.handledEvents()).contains(LIFT_BREATHING_SPACE_LIP); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/ManageContactInformationCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/ManageContactInformationCallbackHandlerTest.java index 832084cce8f..8ff9b667be7 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/ManageContactInformationCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/ManageContactInformationCallbackHandlerTest.java @@ -4,40 +4,80 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.CaseDetails; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CallbackType; +import uk.gov.hmcts.reform.civil.enums.CaseCategory; import uk.gov.hmcts.reform.civil.enums.CaseState; import uk.gov.hmcts.reform.civil.enums.RespondentResponseType; import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; +import uk.gov.hmcts.reform.civil.model.Address; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.model.UpdateDetailsForm; +import uk.gov.hmcts.reform.civil.model.UpdatePartyDetailsForm; +import uk.gov.hmcts.reform.civil.model.common.DynamicList; +import uk.gov.hmcts.reform.civil.model.common.DynamicListElement; +import uk.gov.hmcts.reform.civil.model.common.Element; +import uk.gov.hmcts.reform.civil.model.dq.Applicant1DQ; +import uk.gov.hmcts.reform.civil.model.dq.Expert; +import uk.gov.hmcts.reform.civil.model.dq.Experts; +import uk.gov.hmcts.reform.civil.model.dq.Respondent1DQ; +import uk.gov.hmcts.reform.civil.model.dq.Respondent2DQ; +import uk.gov.hmcts.reform.civil.model.dq.Witness; +import uk.gov.hmcts.reform.civil.model.dq.Witnesses; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.service.CoreCaseUserService; +import uk.gov.hmcts.reform.civil.utils.CaseFlagsInitialiser; +import uk.gov.hmcts.reform.civil.validation.PostcodeValidator; import uk.gov.hmcts.reform.idam.client.models.UserInfo; - +import java.time.LocalDate; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; -import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; +import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; import static uk.gov.hmcts.reform.civil.model.Party.Type.COMPANY; +import static uk.gov.hmcts.reform.civil.model.Party.Type.INDIVIDUAL; import static uk.gov.hmcts.reform.civil.utils.DynamicListUtils.listFromDynamicList; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.unwrapElements; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_EXPERTS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_WITNESSES_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_TWO_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_TWO_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_EXPERTS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_WITNESSES_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_EXPERTS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_WITNESSES_ID; @SpringBootTest(classes = { ManageContactInformationCallbackHandler.class, JacksonAutoConfiguration.class, - CaseDetailsConverter.class + CaseDetailsConverter.class, + PostcodeValidator.class }) class ManageContactInformationCallbackHandlerTest extends BaseCallbackHandlerTest { @@ -47,9 +87,18 @@ class ManageContactInformationCallbackHandlerTest extends BaseCallbackHandlerTes @Autowired private ObjectMapper mapper; + @MockBean + private CaseFlagsInitialiser caseFlagInitialiser; + @MockBean private CoreCaseUserService coreCaseUserService; + @MockBean + private CaseDetailsConverter caseDetailsConverter; + + @MockBean + private PostcodeValidator postcodeValidator; + private static final UserInfo ADMIN_USER = UserInfo.builder() .roles(List.of("caseworker-civil-admin")) .uid("uid") @@ -664,31 +713,537 @@ void shouldReturnExpectedList_WhenInvokedFor1v2DifferentSolicitorAsRespondentSol @Nested class AboutToSubmit { + UpdatePartyDetailsForm party; + Expert dqExpert; + Expert expectedExpert1; + Witness dqWitness; + Witness expectedWitness1; + + @BeforeEach + void setup() { + party = UpdatePartyDetailsForm.builder().firstName("First").lastName("Name").build(); + dqExpert = Expert.builder().partyID("id").firstName("dq").lastName("dq").build(); + expectedExpert1 = dqExpert.builder().firstName("First").lastName("Name") + .eventAdded("Manage Contact Information Event").dateAdded(LocalDate.now()) + .partyID(null) //change this for CIV-10382 + .build(); + dqWitness = Witness.builder().firstName("dq").lastName("dq").partyID("id").build(); + expectedWitness1 = Witness.builder().firstName("First").lastName("Name") + .eventAdded("Manage Contact Information Event").dateAdded(LocalDate.now()) + .partyID(null).build(); // CIV-10382 + } @Test - void shouldReturnExpectedResponse_WhenAboutToSubmitIsInvoked() { - CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build(); + void shouldUpdateApplicantOneExperts() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(CLAIMANT_ONE_EXPERTS_ID) + .build()) + .build()) + .partyChosenId(CLAIMANT_ONE_EXPERTS_ID) + .updateExpertsDetailsForm(wrapElements(party)) + .build()) + .applicant1DQ(Applicant1DQ.builder() + .applicant1DQExperts(Experts.builder().details(wrapElements(dqExpert)).build()) + .build()) + .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler .handle(params); - assertEquals(AboutToStartOrSubmitCallbackResponse.builder().build(), response); + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(unwrapElements(updatedData.getApplicant1DQ().getApplicant1DQExperts().getDetails()).get(0)).isEqualTo(expectedExpert1); } - } - @Nested - class Submitted { + @Test + void shouldUpdateDefendantOneExperts() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(DEFENDANT_ONE_EXPERTS_ID) + .build()) + .build()) + .partyChosenId(DEFENDANT_ONE_EXPERTS_ID) + .updateExpertsDetailsForm(wrapElements(party)) + .build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQExperts(Experts.builder().details(wrapElements(dqExpert)).build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(unwrapElements(updatedData.getRespondent1DQ().getRespondent1DQExperts().getDetails()).get(0)).isEqualTo(expectedExpert1); + } + + @Test + void shouldUpdateDefendantTwoExperts() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(DEFENDANT_TWO_EXPERTS_ID) + .build()) + .build()) + .partyChosenId(DEFENDANT_TWO_EXPERTS_ID) + .updateExpertsDetailsForm(wrapElements(party)) + .build()) + .respondent2DQ(Respondent2DQ.builder() + .respondent2DQExperts(Experts.builder().details(wrapElements(dqExpert)).build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(unwrapElements(updatedData.getRespondent2DQ().getRespondent2DQExperts().getDetails()).get(0)).isEqualTo(expectedExpert1); + } + + @Test + void shouldUpdateApplicantOneWitnesses() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(CLAIMANT_ONE_WITNESSES_ID) + .build()) + .build()) + .partyChosenId(CLAIMANT_ONE_WITNESSES_ID) + .updateWitnessesDetailsForm(wrapElements(party)) + .build()) + .applicant1DQ(Applicant1DQ.builder() + .applicant1DQWitnesses(Witnesses.builder().details(wrapElements(dqWitness)).build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(unwrapElements(updatedData.getApplicant1DQ().getApplicant1DQWitnesses().getDetails()).get(0)).isEqualTo(expectedWitness1); + } + + @Test + void shouldUpdateDefendantOneWitnesses() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(DEFENDANT_ONE_WITNESSES_ID) + .build()) + .build()) + .partyChosenId(DEFENDANT_ONE_WITNESSES_ID) + .updateWitnessesDetailsForm(wrapElements(party)) + .build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQWitnesses(Witnesses.builder().details(wrapElements(dqWitness)).build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(unwrapElements(updatedData.getRespondent1DQ().getRespondent1DQWitnesses().getDetails()).get(0)).isEqualTo(expectedWitness1); + } @Test - void shouldReturnExpectedResponse_WhenSubmittedIsInvoked() { - CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build(); - CallbackParams params = callbackParamsOf(caseData, SUBMITTED); + void shouldUpdateDefendantTwoWitnesses() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(DEFENDANT_TWO_WITNESSES_ID) + .build()) + .build()) + .partyChosenId(DEFENDANT_TWO_WITNESSES_ID) + .updateWitnessesDetailsForm(wrapElements(party)) + .build()) + .respondent2DQ(Respondent2DQ.builder() + .respondent2DQWitnesses(Witnesses.builder().details(wrapElements(dqWitness)).build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler .handle(params); - assertEquals(AboutToStartOrSubmitCallbackResponse.builder().build(), response); + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(unwrapElements(updatedData.getRespondent2DQ().getRespondent2DQWitnesses().getDetails()).get(0)).isEqualTo(expectedWitness1); + } + + @Test + void addingExpertWhenNoneExisted() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(CLAIMANT_ONE_EXPERTS_ID) + .build()) + .build()) + .partyChosenId(CLAIMANT_ONE_EXPERTS_ID) + .updateExpertsDetailsForm(wrapElements(party)) + .build()) + .applicant1DQ(Applicant1DQ.builder() + .applicant1DQExperts(Experts.builder() + .expertRequired(NO) + .build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(unwrapElements(updatedData.getApplicant1DQ().getApplicant1DQExperts().getDetails()).get(0)).isEqualTo(expectedExpert1); + assertThat(updatedData.getApplicant1DQ().getApplicant1DQExperts().getExpertRequired()).isEqualTo(YES); + } + + @Test + void removingAllExperts() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(CLAIMANT_ONE_EXPERTS_ID) + .build()) + .build()) + .partyChosenId(CLAIMANT_ONE_EXPERTS_ID) + .updateExpertsDetailsForm(null) + .build()) + .applicant1DQ(Applicant1DQ.builder() + .applicant1DQExperts(Experts.builder() + .expertRequired(YES) + .details(wrapElements(dqExpert)).build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(unwrapElements(updatedData.getApplicant1DQ().getApplicant1DQExperts().getDetails())).isEmpty(); + assertThat(updatedData.getApplicant1DQ().getApplicant1DQExperts().getExpertRequired()).isEqualTo(NO); + } + + @Test + void addingWitnessWhenNoneExisted() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(DEFENDANT_ONE_WITNESSES_ID) + .build()) + .build()) + .partyChosenId(DEFENDANT_ONE_WITNESSES_ID) + .updateWitnessesDetailsForm(wrapElements(party)) + .build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQWitnesses(Witnesses.builder().witnessesToAppear(NO).build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(unwrapElements(updatedData.getRespondent1DQ().getRespondent1DQWitnesses().getDetails()).get(0)).isEqualTo(expectedWitness1); + assertThat(updatedData.getRespondent1DQ().getRespondent1DQWitnesses().getWitnessesToAppear()).isEqualTo(YES); + } + + @Test + void removingAllWitnesses() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(DEFENDANT_ONE_WITNESSES_ID) + .build()) + .build()) + .partyChosenId(DEFENDANT_ONE_WITNESSES_ID) + .updateWitnessesDetailsForm(null) + .build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQWitnesses(Witnesses.builder() + .details(wrapElements(dqWitness)) + .witnessesToAppear(YES).build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(unwrapElements(updatedData.getRespondent1DQ().getRespondent1DQWitnesses().getDetails())).isEmpty(); + assertThat(updatedData.getRespondent1DQ().getRespondent1DQWitnesses().getWitnessesToAppear()).isEqualTo(NO); + } + } + + @Nested + class MidShowWarning { + private static final String PAGE_ID = "show-warning"; + + @ParameterizedTest + @ValueSource(strings = {CLAIMANT_ONE_ID, CLAIMANT_TWO_ID, DEFENDANT_ONE_ID, DEFENDANT_TWO_ID}) + void shouldReturnWarning(String partyChosenId) { + String errorTitle = "Check the litigation friend's details"; + String errorMessage = "After making these changes, please ensure that the " + + "litigation friend's contact information is also up to date."; + + CaseData caseData = CaseDataBuilder.builder() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(partyChosenId) + .build()) + .build()) + .build()) + .addApplicant1LitigationFriend() + .addApplicant2LitigationFriend() + .addRespondent1LitigationFriend() + .addRespondent2LitigationFriend() + .build(); + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getWarnings()).contains(errorTitle); + assertThat(response.getWarnings()).contains(errorMessage); + } + + @ParameterizedTest + @ValueSource(strings = {CLAIMANT_ONE_ID, CLAIMANT_TWO_ID, DEFENDANT_ONE_ID, DEFENDANT_TWO_ID, DEFENDANT_ONE_LITIGATION_FRIEND_ID}) + void shouldNotReturnWarning(String partyChosenId) { + CaseData caseData = CaseDataBuilder.builder() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(partyChosenId) + .build()) + .build()) + .build()) + .build(); + + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getWarnings()).isEmpty(); + } + + @Test + void shouldReturnPostcodeError() { + given(postcodeValidator.validate(any())).willReturn(List.of("Please enter Postcode")); + + CaseData caseData = CaseDataBuilder.builder() + .caseAccessCategory(CaseCategory.SPEC_CLAIM) + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(CLAIMANT_ONE_ID) + .build()) + .build()) + .build()) + .applicant1(Party.builder() + .type(INDIVIDUAL) + .primaryAddress(Address.builder() + .postCode(null) + .build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getErrors()).isNotNull(); + assertEquals(1, response.getErrors().size()); + assertEquals("Please enter Postcode", response.getErrors().get(0)); + } + } + + @Nested + class MidShowPartyField { + private static final String PAGE_ID = "show-party-field"; + + @Test + void shouldPopulatePartyChosenId() { + CaseData caseData = CaseDataBuilder.builder() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code("CODE") + .build()) + .build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(updatedData.getUpdateDetailsForm().getPartyChosenId()).isEqualTo("CODE"); + assertThat(updatedData.getUpdateDetailsForm().getPartyChosenType()).isEqualTo(null); + assertThat(updatedData.getUpdateDetailsForm().getUpdateExpertsDetailsForm()).isEmpty(); + assertThat(updatedData.getUpdateDetailsForm().getUpdateWitnessesDetailsForm()).isEmpty(); + } + + @ParameterizedTest + @ValueSource(strings = {CLAIMANT_ONE_ID, CLAIMANT_TWO_ID, DEFENDANT_ONE_ID, DEFENDANT_TWO_ID}) + void shouldPopulatePartyType(String partyChosenId) { + when(userService.getUserInfo(anyString())).thenReturn(ADMIN_USER); + CaseData caseDataBefore = CaseDataBuilder.builder() + .applicant1(Party.builder().type(INDIVIDUAL).build()) + .applicant2(Party.builder().type(INDIVIDUAL).build()) + .respondent1(Party.builder().type(INDIVIDUAL).build()) + .respondent2(Party.builder().type(INDIVIDUAL).build()) + .buildClaimIssuedPaymentCaseData(); + given(caseDetailsConverter.toCaseData(any(CaseDetails.class))).willReturn(caseDataBefore); + + CaseData caseData = CaseDataBuilder.builder() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(partyChosenId) + .build()) + .build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(updatedData.getUpdateDetailsForm().getPartyChosenId()).isEqualTo(partyChosenId); + assertThat(updatedData.getUpdateDetailsForm().getPartyChosenType()).isEqualTo(partyChosenId + "_ADMIN_INDIVIDUAL"); + assertThat(updatedData.getUpdateDetailsForm().getUpdateExpertsDetailsForm()).isEmpty(); + assertThat(updatedData.getUpdateDetailsForm().getUpdateWitnessesDetailsForm()).isEmpty(); + } + + @ParameterizedTest + @ValueSource(strings = {CLAIMANT_ONE_LITIGATION_FRIEND_ID, CLAIMANT_TWO_LITIGATION_FRIEND_ID, DEFENDANT_ONE_LITIGATION_FRIEND_ID, DEFENDANT_TWO_LITIGATION_FRIEND_ID}) + void shouldPopulatePartyTypeForLitigationFriend(String partyChosenId) { + when(userService.getUserInfo(anyString())).thenReturn(LEGAL_REP_USER); + CaseData caseDataBefore = CaseDataBuilder.builder() + .applicant1(Party.builder().type(INDIVIDUAL).build()) + .applicant2(Party.builder().type(INDIVIDUAL).build()) + .respondent1(Party.builder().type(INDIVIDUAL).build()) + .respondent2(Party.builder().type(INDIVIDUAL).build()) + .buildClaimIssuedPaymentCaseData(); + given(caseDetailsConverter.toCaseData(any(CaseDetails.class))).willReturn(caseDataBefore); + + CaseData caseData = CaseDataBuilder.builder() + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(partyChosenId) + .build()) + .build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(updatedData.getUpdateDetailsForm().getPartyChosenId()).isEqualTo(partyChosenId); + assertThat(updatedData.getUpdateDetailsForm().getPartyChosenType()).isEqualTo(partyChosenId + "_LR"); + assertThat(updatedData.getUpdateDetailsForm().getUpdateExpertsDetailsForm()).isEmpty(); + assertThat(updatedData.getUpdateDetailsForm().getUpdateWitnessesDetailsForm()).isEmpty(); + } + + @ParameterizedTest + @ValueSource(strings = {CLAIMANT_ONE_EXPERTS_ID, DEFENDANT_ONE_EXPERTS_ID, DEFENDANT_TWO_EXPERTS_ID}) + void shouldPopulateExperts(String partyChosenId) { + when(userService.getUserInfo(anyString())).thenReturn(ADMIN_USER); + Expert expert = Expert.builder().firstName("First").lastName("Name").partyID("id").build(); + UpdatePartyDetailsForm party = UpdatePartyDetailsForm.builder().firstName("First").lastName("Name") + .partyId("id").build(); + List> form = wrapElements(party); + + CaseData caseData = CaseDataBuilder.builder() + .applicant1DQ(Applicant1DQ.builder() + .applicant1DQExperts(Experts.builder().details(wrapElements(expert)).build()) + .build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQExperts(Experts.builder().details(wrapElements(expert)).build()) + .build()) + .respondent2DQ(Respondent2DQ.builder() + .respondent2DQExperts(Experts.builder().details(wrapElements(expert)).build()) + .build()) + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(partyChosenId) + .build()) + .build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(updatedData.getUpdateDetailsForm().getPartyChosenId()).isEqualTo(partyChosenId); + assertThat(updatedData.getUpdateDetailsForm().getPartyChosenType()).isEqualTo(null); + assertThat(updatedData.getUpdateDetailsForm().getUpdateExpertsDetailsForm()).isEqualTo(form); + assertThat(updatedData.getUpdateDetailsForm().getUpdateWitnessesDetailsForm()).isEmpty(); + + } + + @ParameterizedTest + @ValueSource(strings = {CLAIMANT_ONE_WITNESSES_ID, DEFENDANT_ONE_WITNESSES_ID, DEFENDANT_TWO_WITNESSES_ID}) + void shouldPopulateWitnesses(String partyChosenId) { + Witness witness = Witness.builder().firstName("First").lastName("Name").partyID("id").build(); + UpdatePartyDetailsForm party = UpdatePartyDetailsForm.builder().firstName("First").lastName("Name") + .partyId("id").build(); + List> form = wrapElements(party); + + CaseData caseData = CaseDataBuilder.builder() + .applicant1DQ(Applicant1DQ.builder() + .applicant1DQWitnesses(Witnesses.builder().details(wrapElements(witness)).build()) + .build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQWitnesses(Witnesses.builder().details(wrapElements(witness)).build()) + .build()) + .respondent2DQ(Respondent2DQ.builder() + .respondent2DQWitnesses(Witnesses.builder().details(wrapElements(witness)).build()) + .build()) + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosen(DynamicList.builder() + .value(DynamicListElement.builder() + .code(partyChosenId) + .build()) + .build()) + .build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(updatedData.getUpdateDetailsForm().getPartyChosenId()).isEqualTo(partyChosenId); + assertThat(updatedData.getUpdateDetailsForm().getPartyChosenType()).isEqualTo(null); + assertThat(updatedData.getUpdateDetailsForm().getUpdateExpertsDetailsForm()).isEmpty(); + assertThat(updatedData.getUpdateDetailsForm().getUpdateWitnessesDetailsForm()).isEqualTo(form); + } } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/MediationSuccessfulCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/MediationSuccessfulCallbackHandlerTest.java index 887fb6fc8b0..aaf613e8501 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/MediationSuccessfulCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/MediationSuccessfulCallbackHandlerTest.java @@ -61,9 +61,9 @@ void shouldCallSubmitSuccessfulMediationUponAboutToSubmit() { assertThat(response.getData()).extracting("mediationSettlementAgreedAt").isNotNull(); assertThat(response.getData()).extracting("mediationAgreement").isNotNull(); + assertThat(response.getData()).extracting("manageDocuments").isNotNull(); assertThat(response.getState()) .isEqualTo(CaseState.CASE_STAYED.name()); - } } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/NotSuitableSDOCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/NotSuitableSDOCallbackHandlerTest.java index ac11aeb6d52..fd3783f4a81 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/NotSuitableSDOCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/NotSuitableSDOCallbackHandlerTest.java @@ -4,6 +4,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration; @@ -19,6 +21,7 @@ import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.Time; import uk.gov.hmcts.reform.idam.client.IdamClient; import uk.gov.hmcts.reform.idam.client.models.UserDetails; @@ -30,6 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; @@ -52,6 +56,9 @@ class NotSuitableSDOCallbackHandlerTest extends BaseCallbackHandlerTest { @MockBean private IdamClient idamClient; + @MockBean + private FeatureToggleService toggleService; + @Autowired private NotSuitableSDOCallbackHandler handler; @@ -99,7 +106,7 @@ class MidCallback { @Test void shouldValidateReasonLessThan150_whenInvoked() { - + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(false); final String PAGE_ID = "not-suitable-reason"; caseData = CaseDataBuilder.builder().atStateBeforeTakenOfflineSDONotDrawn().build(); @@ -112,8 +119,8 @@ void shouldValidateReasonLessThan150_whenInvoked() { } @Test - void shouldValidateReasonMoreThan150_whenInvoked() { - + void shouldValidateReasonMoreThan150_whenInvokedA() { + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(false); final String PAGE_ID = "not-suitable-reason"; final int lengthALlowed = 150; @@ -127,6 +134,68 @@ void shouldValidateReasonMoreThan150_whenInvoked() { + lengthALlowed + " characters."); } + + @Test + void shouldValidateReasonLessThan150_whenInvokedAndTOCEnabledOtherReasons() { + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(true); + final String PAGE_ID = "not-suitable-reason"; + + caseData = CaseDataBuilder.builder().atStateBeforeTakenOfflineSDONotDrawn().build(); + params = callbackParamsOf(caseData, MID, PAGE_ID); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getErrors()).isEmpty(); + + } + + @Test + void shouldValidateReasonMoreThan150_whenInvokedAndTOCEnabledOtherReasons() { + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(true); + final String PAGE_ID = "not-suitable-reason"; + final int lengthALlowed = 150; + + caseData = CaseDataBuilder.builder().atStateBeforeTakenOfflineSDONotDrawnOverLimit().build(); + params = callbackParamsOf(caseData, MID, PAGE_ID); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getErrors().get(0)).isEqualTo("Character Limit Reached: " + + "Reason for not drawing Standard Directions order cannot exceed " + + lengthALlowed + " characters."); + + } + + @Test + void shouldValidateTOCReasonLessThan150_whenInvokedAndTOCEnabledTransferCase() { + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(true); + final String PAGE_ID = "not-suitable-reason"; + + caseData = CaseDataBuilder.builder().atStateBeforeTransferCaseSDONotDrawn().build(); + params = callbackParamsOf(caseData, MID, PAGE_ID); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getErrors()).isEmpty(); + + } + + @Test + void shouldValidateTOCReasonMoreThan150_whenInvokedAndTOCEnabledTransferCase() { + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(true); + final String PAGE_ID = "not-suitable-reason"; + final int lengthALlowed = 150; + + caseData = CaseDataBuilder.builder().atStateBeforeTransferCaseSDONotDrawnOverLimit().build(); + params = callbackParamsOf(caseData, MID, PAGE_ID); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getErrors().get(0)).isEqualTo("Character Limit Reached: " + + "Reason for not drawing Standard Directions order cannot exceed " + + lengthALlowed + " characters."); + + } } @Nested @@ -148,6 +217,7 @@ void setup() { @Test void shouldUpdateBusinessProcess_whenInvoked() { + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(false); caseData = CaseDataBuilder.builder().atStateBeforeTakenOfflineSDONotDrawn().build(); params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -161,6 +231,7 @@ void shouldUpdateBusinessProcess_whenInvoked() { @Test void checkOtherDetailsUpdated() { + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(false); caseData = CaseDataBuilder.builder().atStateBeforeTakenOfflineSDONotDrawn().build(); params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -169,13 +240,67 @@ void checkOtherDetailsUpdated() { assertThat(response.getData()).extracting("otherDetails").extracting("reasonNotSuitableForSDO").isEqualTo("unforeseen complexities"); } + + @Test + void shouldUpdateBusinessProcess_whenInvokedAndTOCEnabledOtherReasons() { + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(true); + caseData = CaseDataBuilder.builder().atStateBeforeTakenOfflineSDONotDrawn().build(); + params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getData()) + .extracting("businessProcess") + .extracting("camundaEvent", "status") + .containsOnly(NotSuitable_SDO.name(), "READY"); + + } + + @Test + void checkOtherDetailsUpdated_whenTOCEnabledOtherReasons() { + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(true); + caseData = CaseDataBuilder.builder().atStateBeforeTakenOfflineSDONotDrawn().build(); + params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getData()).extracting("notSuitableSdoOptions").isEqualTo("OTHER_REASONS"); + assertThat(response.getData()).extracting("otherDetails").extracting("notSuitableForSDO").isEqualTo("Yes"); + assertThat(response.getData()).extracting("otherDetails").extracting("reasonNotSuitableForSDO").isEqualTo("unforeseen complexities"); + + } + + @Test + void shouldUpdateBusinessProcess_whenInvokedAndTOCEnabledTransferCase() { + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(true); + caseData = CaseDataBuilder.builder().atStateBeforeTransferCaseSDONotDrawn().build(); + params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getData()) + .extracting("businessProcess") + .isNull(); + + } + + @Test + void checkOtherDetailsUpdated_whenTOCEnabledTransferCase() { + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(true); + caseData = CaseDataBuilder.builder().atStateBeforeTransferCaseSDONotDrawn().build(); + params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getData()).extracting("notSuitableSdoOptions").isEqualTo("CHANGE_LOCATION"); + assertThat(response.getData()).extracting("otherDetails").extracting("notSuitableForSDO").isEqualTo("Yes"); + assertThat(response.getData()).extracting("transferCaseDetails").extracting("reasonForTransferCaseTxt").isEqualTo("unforeseen complexities"); + } } @Nested class SubmittedCallback { - @Test - void shouldReturnExpectedSubmittedCallbackResponse() { + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void shouldReturnExpectedSubmittedCallbackResponse(Boolean toggleState) { + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(toggleState); CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build(); CallbackParams params = callbackParamsOf(caseData, SUBMITTED); SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); @@ -192,10 +317,30 @@ void shouldReturnExpectedSubmittedCallbackResponse() { .confirmationBody(body) .build()); } + + @Test + void shouldReturnExpectedSubmittedCallbackResponse_whenTOCEnabledTransferCase() { + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(true); + CaseData caseData = CaseDataBuilder.builder().atStateBeforeTransferCaseSDONotDrawn().build(); + CallbackParams params = callbackParamsOf(caseData, SUBMITTED); + SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); + + String header = format("# Your request was successful%n## This claim will be transferred to a different location"); + String body = format("
    A notification will be sent to the listing officer to look at this case and " + + "process the transfer of case."); + + assertThat(response).usingRecursiveComparison().isEqualTo( + SubmittedCallbackResponse.builder() + .confirmationHeader(header) + .confirmationBody(body) + .build()); + } } - @Test - void handleEventsReturnsTheExpectedCallbackEvent() { + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void handleEventsReturnsTheExpectedCallbackEvent(Boolean toggleState) { + when(toggleService.isTransferOnlineCaseEnabled()).thenReturn(toggleState); assertThat(handler.handledEvents()).contains(NotSuitable_SDO); } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RecordJudgmentCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RecordJudgmentCallbackHandlerTest.java new file mode 100644 index 00000000000..ec6a4c9ef0d --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RecordJudgmentCallbackHandlerTest.java @@ -0,0 +1,218 @@ +package uk.gov.hmcts.reform.civil.handler.callback.user; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.SubmittedCallbackResponse; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CallbackType; +import uk.gov.hmcts.reform.civil.enums.CaseState; +import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentInstalmentDetails; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentRecordedReason; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentStatusType; +import uk.gov.hmcts.reform.civil.model.judgmentonline.PaymentPlanSelection; +import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; + +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.RECORD_JUDGMENT; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = { + RecordJudgmentCallbackHandler.class, + JacksonAutoConfiguration.class +}) +class RecordJudgmentCallbackHandlerTest extends BaseCallbackHandlerTest { + + @Autowired + private RecordJudgmentCallbackHandler handler; + + @Autowired + private ObjectMapper objectMapper; + + @Test + void handleEventsReturnsTheExpectedCallbackEvents() { + assertThat(handler.handledEvents()).containsOnly(RECORD_JUDGMENT); + } + + @Nested + class AboutToStartCallback { + + @Test + void shouldPopulateAllJoFieldsAsNull() { + //Given: Casedata in All_FINAL_ORDERS_ISSUED State + CaseData caseData = CaseDataBuilder.builder().atStateHearingDateScheduled().build().toBuilder() + .ccdState(CaseState.All_FINAL_ORDERS_ISSUED) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_START); + + //When: handler is called with ABOUT_TO_START event + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + //Then: all judgmentOnline fields should be null + assertThat(response.getData().get("joJudgmentStatusDetails")).isNull(); + assertThat(response.getData().get("joOrderMadeDate")).isNull(); + assertThat(response.getData().get("joPaymentPlanSelection")).isNull(); + assertThat(response.getData().get("joJudgmentInstalmentDetails")).isNull(); + assertThat(response.getData().get("joJudgmentRecordReason")).isNull(); + assertThat(response.getData().get("joAmountOrdered")).isNull(); + assertThat(response.getData().get("joAmountCostOrdered")).isNull(); + assertThat(response.getData().get("joIsRegisteredWithRTL")).isNull(); + assertThat(response.getData().get("joAmountOrdered")).isNull(); + assertThat(response.getData().get("joJudgmentPaidInFull")).isNull(); + + } + } + + @Nested + class AboutToSubmitCallback { + @Test + void shouldPopulateAllJudgmentFields_For_Pay_Instalment() { + //Given : Casedata in All_FINAL_ORDERS_ISSUED State + CaseData caseData = CaseDataBuilder.builder().buildJudmentOnlineCaseDataWithPaymentByInstalment(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + //When: handler is called with ABOUT_TO_SUBMIT event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + //Then: judgmentOnline fields should be set correctly + assertThat(response.getData().get("joJudgmentStatusDetails")).extracting("judgmentStatusTypes").isEqualTo( + JudgmentStatusType.ISSUED.name()); + assertThat(response.getData().get("joJudgmentStatusDetails")).extracting("joRtlState").isEqualTo("R"); + assertThat(response.getData().get("joJudgmentStatusDetails")).extracting("lastUpdatedDate").isNotNull(); + assertThat(response.getData()).containsEntry("joJudgmentRecordReason", + JudgmentRecordedReason.JUDGE_ORDER.name()); + assertThat(response.getData()).containsEntry("joPaymentPlanSelection", + PaymentPlanSelection.PAY_IN_INSTALMENTS.name()); + assertThat(response.getData().get("joJudgmentInstalmentDetails")).extracting("instalmentAmount").isEqualTo("120"); + assertThat(response.getData().get("joJudgmentInstalmentDetails")).extracting("paymentFrequency").isEqualTo("MONTHLY"); + assertThat(response.getData().get("joJudgmentInstalmentDetails")).extracting("firstInstalmentDate").isEqualTo("2022-12-12"); + assertThat(response.getData()).containsEntry("joIsRegisteredWithRTL", "Yes"); + assertThat(response.getData()).containsEntry("joAmountOrdered", "1200"); + assertThat(response.getData()).containsEntry("joAmountCostOrdered", "1100"); + assertThat(response.getData()).containsEntry("joOrderMadeDate", "2022-12-12"); + assertThat(response.getData().get("joJudgmentPaidInFull")).isNull(); + } + + @Test + void shouldPopulateAllJudgmentFields_For_Pay_Immediately() { + //Given : Casedata in All_FINAL_ORDERS_ISSUED State + CaseData caseData = CaseDataBuilder.builder().buildJudmentOnlineCaseDataWithPaymentImmediately(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + //When: handler is called with ABOUT_TO_SUBMIT event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + //Then: judgmentOnline fields should be set correctly + assertThat(response.getData().get("joJudgmentStatusDetails")).extracting("judgmentStatusTypes").isEqualTo( + JudgmentStatusType.ISSUED.name()); + assertThat(response.getData().get("joJudgmentStatusDetails")).extracting("joRtlState").isEqualTo("R"); + assertThat(response.getData().get("joJudgmentStatusDetails")).extracting("lastUpdatedDate").isNotNull(); + assertThat(response.getData()).containsEntry("joJudgmentRecordReason", + JudgmentRecordedReason.JUDGE_ORDER.name()); + assertThat(response.getData()).containsEntry("joPaymentPlanSelection", + PaymentPlanSelection.PAY_IMMEDIATELY.name()); + assertThat(response.getData()).containsEntry("joIsRegisteredWithRTL", "Yes"); + assertThat(response.getData()).containsEntry("joAmountOrdered", "1200"); + assertThat(response.getData()).containsEntry("joAmountCostOrdered", "1100"); + assertThat(response.getData()).containsEntry("joOrderMadeDate", "2022-12-12"); + assertThat(response.getData().get("joJudgmentPaidInFull")).isNull(); + } + + @Test + void shouldPopulateAllJudgmentFields_For_Pay_By_Date() { + //Given : Casedata in All_FINAL_ORDERS_ISSUED State + CaseData caseData = CaseDataBuilder.builder().buildJudmentOnlineCaseDataWithPaymentByDate(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + //When: handler is called with ABOUT_TO_SUBMIT event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + //Then: judgmentOnline fields should be set correctly + assertThat(response.getData().get("joJudgmentStatusDetails")).extracting("judgmentStatusTypes").isEqualTo( + JudgmentStatusType.ISSUED.name()); + assertThat(response.getData().get("joJudgmentStatusDetails")).extracting("joRtlState").isEqualTo("R"); + assertThat(response.getData().get("joJudgmentStatusDetails")).extracting("lastUpdatedDate").isNotNull(); + assertThat(response.getData()).containsEntry("joJudgmentRecordReason", + JudgmentRecordedReason.JUDGE_ORDER.name()); + assertThat(response.getData()).containsEntry("joPaymentPlanSelection", + PaymentPlanSelection.PAY_BY_DATE.name()); + assertThat(response.getData()).containsEntry("joIsRegisteredWithRTL", "Yes"); + assertThat(response.getData()).containsEntry("joAmountOrdered", "1200"); + assertThat(response.getData()).containsEntry("joAmountCostOrdered", "1100"); + assertThat(response.getData()).containsEntry("joOrderMadeDate", "2022-12-12"); + assertThat(response.getData()).containsEntry("joPaymentToBeMadeByDate", "2023-12-12"); + assertThat(response.getData().get("joJudgmentPaidInFull")).isNull(); + } + } + + @Nested + class MidCallback { + @Test + void shouldValidatePaymentInstalmentDate() { + + CaseData caseData = CaseDataBuilder.builder().buildJudmentOnlineCaseDataWithPaymentByInstalment(); + caseData.setJoJudgmentInstalmentDetails(JudgmentInstalmentDetails.builder().firstInstalmentDate(LocalDate.now().minusDays(2)).build()); + + CallbackParams params = callbackParamsOf(caseData, MID, "validateDates"); + //When: handler is called with MID event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors()).contains("Date of first instalment must be in the future"); + } + + @Test + void shouldValidatePaymentPaidByDate() { + + CaseData caseData = CaseDataBuilder.builder().buildJudmentOnlineCaseDataWithPaymentByDate(); + caseData.setJoPaymentToBeMadeByDate(LocalDate.now().minusDays(2)); + + CallbackParams params = callbackParamsOf(caseData, MID, "validateDates"); + //When: handler is called with MID event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors()).contains("Date the judgment will be paid by must be in the future"); + } + + @Test + void shouldValidateOrderDate() { + + CaseData caseData = CaseDataBuilder.builder().buildJudmentOnlineCaseDataWithPaymentByInstalment(); + caseData.setJoOrderMadeDate(LocalDate.now().plusDays(2)); + + CallbackParams params = callbackParamsOf(caseData, MID, "validateDates"); + //When: handler is called with MID event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors()).contains("Date judge made the order must be in the past"); + } + } + + @Nested + class SubmittedCallback { + @Test + public void whenSubmitted_thenIncludeHeader() { + CaseData caseData = CaseDataBuilder.builder().buildJudmentOnlineCaseDataWithPaymentByInstalment(); + CallbackParams params = CallbackParams.builder() + .caseData(caseData) + .type(CallbackType.SUBMITTED) + .build(); + SubmittedCallbackResponse response = + (SubmittedCallbackResponse) handler.handle(params); + Assertions.assertTrue(response.getConfirmationHeader().contains("# Judgment recorded")); + Assertions.assertTrue(response.getConfirmationBody().contains("The judgment has been recorded")); + } + } + +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RequestJudgementByAdmissionForSpecCuiCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RequestJudgementByAdmissionForSpecCuiCallbackHandlerTest.java index c614282cdf5..4587d7afc7a 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RequestJudgementByAdmissionForSpecCuiCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RequestJudgementByAdmissionForSpecCuiCallbackHandlerTest.java @@ -20,6 +20,7 @@ import uk.gov.hmcts.reform.civil.model.CCJPaymentDetails; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.Fee; +import uk.gov.hmcts.reform.civil.model.RespondToClaimAdmitPartLRspec; import uk.gov.hmcts.reform.civil.sampledata.CallbackParamsBuilder; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.service.FeatureToggleService; @@ -27,6 +28,7 @@ import uk.gov.hmcts.reform.civil.utils.MonetaryConversions; import java.math.BigDecimal; +import java.time.LocalDate; import java.time.LocalDateTime; import static java.lang.String.format; @@ -34,8 +36,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; -import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.REQUEST_JUDGEMENT_ADMISSION_SPEC; import static uk.gov.hmcts.reform.civil.enums.CaseState.AWAITING_APPLICANT_INTENTION; @@ -63,14 +65,19 @@ public class RequestJudgementByAdmissionForSpecCuiCallbackHandlerTest extends Ba @Autowired private JudgementService judgementService; + @MockBean + private CaseDetailsConverter caseDetailsConverter; + @Nested class AboutToStartCallback { @Test void shouldReturnError_WhenAboutToStartIsInvoked() { + LocalDate whenWillPay = LocalDate.now().plusDays(5); CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() .respondent1ResponseDate(LocalDateTime.now()) .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_ADMISSION) .ccdState(AWAITING_APPLICANT_INTENTION) + .respondToClaimAdmitPartLRspec(RespondToClaimAdmitPartLRspec.builder().whenWillThisAmountBePaid(whenWillPay).build()) .build(); CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_START, caseData).build(); AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler @@ -80,10 +87,12 @@ void shouldReturnError_WhenAboutToStartIsInvoked() { @Test void shouldNotReturnError_WhenAboutToStartIsInvokedOneDefendant() { + LocalDate whenWillPay = LocalDate.of(2023, 10, 11); CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() .respondent1ResponseDate(LocalDateTime.now().minusDays(15)) .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_ADMISSION) .ccdState(AWAITING_APPLICANT_INTENTION) + .respondToClaimAdmitPartLRspec(RespondToClaimAdmitPartLRspec.builder().whenWillThisAmountBePaid(whenWillPay).build()) .build(); CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_START, caseData).build(); AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler @@ -94,7 +103,6 @@ void shouldNotReturnError_WhenAboutToStartIsInvokedOneDefendant() { @Nested class MidEventCallbackSetUpCcjSummaryPage { - private static final String PAGE_ID = "set-up-ccj-amount-summary"; @Test @@ -301,7 +309,6 @@ class MidEventCallbackValidateAmountPaidFlag { @Test void shouldCheckValidateAmountPaid_withErrorMessage() { - CCJPaymentDetails ccjPaymentDetails = CCJPaymentDetails.builder() .ccjPaymentPaidSomeAmount(BigDecimal.valueOf(150000)) .build(); @@ -311,7 +318,6 @@ void shouldCheckValidateAmountPaid_withErrorMessage() { .totalClaimAmount(new BigDecimal(1000)) .build(); CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); - var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); assertThat(response.getErrors()).contains("The amount paid must be less than the full claim amount."); @@ -341,9 +347,12 @@ class AboutToSubmitCallbackTest { @Test void shouldSetUpBusinessProcessAndCaseState() { - CaseData caseData = CaseDataBuilder.builder().build(); + CaseData caseData = CaseDataBuilder.builder().respondent1Represented(YES) + .specRespondent1Represented(YES) + .applicant1Represented(YES).build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + when(caseDetailsConverter.toCaseData(params.getRequest().getCaseDetails())).thenReturn(caseData); AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler .handle(params); @@ -354,6 +363,46 @@ void shouldSetUpBusinessProcessAndCaseState() { .extracting("camundaEvent") .isEqualTo(REQUEST_JUDGEMENT_ADMISSION_SPEC.name()); } + + @Test + void shouldSetUpBusinessProcessAndCaseStateForLip() { + BigDecimal subToatal = BigDecimal.valueOf(1300); + BigDecimal stillOwed = new BigDecimal("1295.00"); + CCJPaymentDetails ccjPaymentDetails = CCJPaymentDetails.builder() + .ccjPaymentPaidSomeOption(YesOrNo.YES) + .ccjPaymentPaidSomeAmount(BigDecimal.valueOf(500.0)) + .ccjJudgmentLipInterest(BigDecimal.valueOf(300)) + .ccjJudgmentAmountClaimFee(BigDecimal.valueOf(0)) + .build(); + CaseData caseData = CaseData.builder() + .respondent1Represented(YesOrNo.NO) + .specRespondent1Represented(YesOrNo.NO) + .applicant1Represented(YesOrNo.NO) + .totalClaimAmount(BigDecimal.valueOf(1000)) + .ccjPaymentDetails(ccjPaymentDetails) + .build(); + + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + when(caseDetailsConverter.toCaseData(params.getRequest().getCaseDetails())).thenReturn(caseData); + when(featureToggleService.isLipVLipEnabled()).thenReturn(true); + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + CCJPaymentDetails ccjResponseForJudgement = + getCaseData(response).getCcjPaymentDetails(); + assertThat(response.getState()) + .isEqualTo(CaseState.PROCEEDS_IN_HERITAGE_SYSTEM.name()); + assertThat(response.getData()) + .extracting("businessProcess") + .extracting("camundaEvent") + .isEqualTo(REQUEST_JUDGEMENT_ADMISSION_SPEC.name()); + assertThat(ccjPaymentDetails.getCcjPaymentPaidSomeOption()).isEqualTo(ccjResponseForJudgement.getCcjPaymentPaidSomeOption()); + assertThat(MonetaryConversions.penniesToPounds(ccjPaymentDetails.getCcjPaymentPaidSomeAmount())).isEqualTo( + ccjResponseForJudgement.getCcjPaymentPaidSomeAmountInPounds()); + assertThat(caseData.getTotalClaimAmount()).isEqualTo(ccjResponseForJudgement.getCcjJudgmentAmountClaimAmount()); + assertThat(subToatal).isEqualTo(ccjResponseForJudgement.getCcjJudgmentSummarySubtotalAmount()); + assertThat(stillOwed).isEqualTo(ccjResponseForJudgement.getCcjJudgmentTotalStillOwed()); + + } } @Nested diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimCallbackHandlerTest.java index aa01f919fda..568f46fe7ce 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimCallbackHandlerTest.java @@ -1834,7 +1834,9 @@ void shouldAssignCategoryId_whenInvoked() { .extracting("defendantResponseDocuments") .asString() .contains("category_id=defendant1DefenseDirectionsQuestionnaire") - .contains("category_id=defendant2DefenseDirectionsQuestionnaire"); + .contains("category_id=defendant2DefenseDirectionsQuestionnaire") + .contains("category_id=DQRespondent") + .contains("category_id=DQRespondentTwo"); } @Test diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimSpecCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimSpecCallbackHandlerTest.java index d5d15102a07..73040deeb42 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimSpecCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToClaimSpecCallbackHandlerTest.java @@ -19,6 +19,7 @@ import uk.gov.hmcts.reform.ccd.client.model.CallbackRequest; import uk.gov.hmcts.reform.ccd.client.model.CallbackResponse; import uk.gov.hmcts.reform.ccd.client.model.SubmittedCallbackResponse; +import uk.gov.hmcts.reform.civil.callback.CallbackException; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CallbackType; import uk.gov.hmcts.reform.civil.constants.SpecJourneyConstantLRSpec; @@ -55,31 +56,35 @@ import uk.gov.hmcts.reform.civil.model.UnavailableDate; import uk.gov.hmcts.reform.civil.model.common.DynamicList; import uk.gov.hmcts.reform.civil.model.common.Element; -import uk.gov.hmcts.reform.civil.model.dq.RequestedCourt; import uk.gov.hmcts.reform.civil.model.dq.Respondent1DQ; import uk.gov.hmcts.reform.civil.model.dq.Respondent2DQ; -import uk.gov.hmcts.reform.civil.model.dq.SmallClaimHearing; import uk.gov.hmcts.reform.civil.model.dq.Witness; import uk.gov.hmcts.reform.civil.model.dq.Witnesses; +import uk.gov.hmcts.reform.civil.model.dq.RequestedCourt; +import uk.gov.hmcts.reform.civil.model.dq.Expert; +import uk.gov.hmcts.reform.civil.model.dq.Experts; +import uk.gov.hmcts.reform.civil.model.dq.ExpertDetails; +import uk.gov.hmcts.reform.civil.model.dq.SmallClaimHearing; import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; import uk.gov.hmcts.reform.civil.sampledata.AddressBuilder; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.sampledata.PartyBuilder; -import uk.gov.hmcts.reform.civil.service.CoreCaseUserService; import uk.gov.hmcts.reform.civil.service.DeadlinesCalculator; import uk.gov.hmcts.reform.civil.service.ExitSurveyContentService; import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.Time; import uk.gov.hmcts.reform.civil.service.UserService; +import uk.gov.hmcts.reform.civil.service.CoreCaseUserService; +import uk.gov.hmcts.reform.civil.service.citizenui.responsedeadline.DeadlineExtensionCalculatorService; import uk.gov.hmcts.reform.civil.service.flowstate.FlowFlag; import uk.gov.hmcts.reform.civil.service.flowstate.StateFlowEngine; import uk.gov.hmcts.reform.civil.stateflow.StateFlow; import uk.gov.hmcts.reform.civil.utils.AssignCategoryId; import uk.gov.hmcts.reform.civil.utils.CaseFlagsInitialiser; import uk.gov.hmcts.reform.civil.utils.CourtLocationUtils; -import uk.gov.hmcts.reform.civil.utils.ElementUtils; import uk.gov.hmcts.reform.civil.utils.MonetaryConversions; +import uk.gov.hmcts.reform.civil.utils.ElementUtils; import uk.gov.hmcts.reform.civil.validation.DateOfBirthValidator; import uk.gov.hmcts.reform.civil.validation.PaymentDateValidator; import uk.gov.hmcts.reform.civil.validation.PostcodeValidator; @@ -92,15 +97,17 @@ import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; -import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -118,10 +125,12 @@ import static uk.gov.hmcts.reform.civil.enums.CaseRole.RESPONDENTSOLICITORTWO; import static uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec.IMMEDIATELY; import static uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec.FULL_ADMISSION; +import static uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec.FULL_DEFENCE; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; import static uk.gov.hmcts.reform.civil.helpers.DateFormatHelper.DATE; import static uk.gov.hmcts.reform.civil.helpers.DateFormatHelper.formatLocalDateTime; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.unwrapElements; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; @ExtendWith(MockitoExtension.class) @@ -162,6 +171,8 @@ class RespondToClaimSpecCallbackHandlerTest extends BaseCallbackHandlerTest { private CourtLocationUtils courtLocationUtils; @Mock private CaseFlagsInitialiser caseFlagsInitialiser; + @Mock + private DeadlineExtensionCalculatorService deadlineExtensionCalculatorService; @Spy private List confirmationTextGenerators = List.of( @@ -194,15 +205,82 @@ public void setup() { ); } + @Test + void whenCallBackEventNotImplementedOrEventInvalid() { + // Given + String postCode = "postCode"; + CaseData caseData = CaseData.builder() + .build().toBuilder() + .respondentSolicitor1ServiceAddressRequired(NO) + .respondentSolicitor1ServiceAddress(Address.builder().postCode(postCode).build()) + .isRespondent1(YES) + .build(); + CallbackParams callbackParams = callbackParamsOf(caseData, CallbackType.MID, " ").toBuilder() + .request(CallbackRequest.builder().eventId(SpecJourneyConstantLRSpec.DEFENDANT_RESPONSE_SPEC) + .build()).build(); + + //When + CallbackException ex = assertThrows(CallbackException.class, () -> handler.handle(callbackParams), + + "A CallbackException was expected to be thrown but wasn't."); + // Then + assertThat(ex.getMessage()).contains("Callback for event"); + } + + @Test + void resetStatementOfTruth() { + CaseData caseData = CaseDataBuilder.builder().build(); + CallbackParams params = callbackParamsOf(caseData, CallbackType.MID, "statement-of-truth"); + CallbackRequest request = CallbackRequest.builder() + .eventId(SpecJourneyConstantLRSpec.DEFENDANT_RESPONSE_SPEC) + .build(); + params = params.toBuilder().request(request).build(); + + // When + CallbackResponse response = handler.handle(params); + + // Then + assertNotNull(response); + } + @Test void midSpecCorrespondenceAddress_checkAddressIfWasIncorrect() { // Given String postCode = "postCode"; CaseData caseData = CaseData.builder() - .specAoSApplicantCorrespondenceAddressRequired(YesOrNo.NO) - .specAoSApplicantCorrespondenceAddressdetails(Address.builder() - .postCode(postCode) - .build()) + .build().toBuilder() + .respondentSolicitor1ServiceAddressRequired(NO) + .respondentSolicitor1ServiceAddress(Address.builder().postCode(postCode).build()) + .isRespondent1(YES) + .build(); + CallbackParams params = callbackParamsOf(caseData, CallbackType.MID, "specCorrespondenceAddress"); + CallbackRequest request = CallbackRequest.builder() + .eventId(SpecJourneyConstantLRSpec.DEFENDANT_RESPONSE_SPEC) + .build(); + params = params.toBuilder().request(request).build(); + + List errors = Collections.singletonList("error 1"); + Mockito.when(postcodeValidator.validate(postCode)).thenReturn(errors); + + // When + CallbackResponse response = handler.handle(params); + + // Then + assertEquals(errors, ((AboutToStartOrSubmitCallbackResponse) response).getErrors()); + } + + @Test + void midSpecCorrespondenceAddress_checkAddressIfWasIncorrectForSol2() { + // Given + String postCode = "postCode"; + CaseData caseData = CaseData.builder() + .build().toBuilder() + .respondentSolicitor1ServiceAddressRequired(YES) + .respondentSolicitor1ServiceAddress(Address.builder().postCode(postCode).build()) + .isRespondent1(YES) + .isRespondent2(YES) + .respondentSolicitor2ServiceAddressRequired(NO) + .respondentSolicitor2ServiceAddress(Address.builder().postCode(postCode).build()) .build(); CallbackParams params = callbackParamsOf(caseData, CallbackType.MID, "specCorrespondenceAddress"); CallbackRequest request = CallbackRequest.builder() @@ -652,9 +730,6 @@ public void testValidateRespondentPaymentDate() { AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler .handle(params); - List expectedErrorArray = new ArrayList<>(); - expectedErrorArray.add("Date for when will the amount be paid must be today or in the future."); - // Then assertThat(response).isNotNull(); /* @@ -701,71 +776,6 @@ public void testValidateDefendant2RepaymentDate() { @Nested class AboutToSubmitTests { - @Test - void shouldAddPartyIdsToPartyFields_whenInvoked() { - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(mockedStateFlow.isFlagSet(any())).thenReturn(true); - when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); - when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(true); - when(deadlinesCalculator.calculateApplicantResponseDeadlineSpec(any(), any())) - .thenReturn(LocalDateTime.now()); - when(toggleService.isHmcEnabled()).thenReturn(true); - - CaseData caseData = CaseDataBuilder.builder().atStateApplicantRespondToDefenceAndProceed() - .respondent2DQ() - .respondent1Copy(PartyBuilder.builder().individual().build()) - .atSpecAoSApplicantCorrespondenceAddressRequired(YES) - .addRespondent2(YES) - .respondent2(PartyBuilder.builder().individual().build()) - .respondent2Copy(PartyBuilder.builder().individual().build()) - .atSpecAoSRespondent2HomeAddressRequired(NO) - .atSpecAoSRespondent2HomeAddressDetails(AddressBuilder.maximal().build()) - .build(); - - AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler - .handle(callbackParamsOf(caseData, ABOUT_TO_SUBMIT)); - - assertThat(response.getData()).extracting("applicant1").hasFieldOrProperty("partyID"); - assertThat(response.getData()).extracting("respondent1").hasFieldOrProperty("partyID"); - assertThat(response.getData()).extracting("respondent2").hasFieldOrProperty("partyID"); - } - - @Test - void shouldNotAddPartyIdsToPartyFields_whenInvokedWithHMCToggleOff() { - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(mockedStateFlow.isFlagSet(any())).thenReturn(true); - when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); - when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(true); - when(deadlinesCalculator.calculateApplicantResponseDeadlineSpec(any(), any())) - .thenReturn(LocalDateTime.now()); - when(toggleService.isHmcEnabled()).thenReturn(false); - - CaseData caseData = CaseDataBuilder.builder().atStateApplicantRespondToDefenceAndProceed() - .respondent2DQ() - .respondent1Copy(PartyBuilder.builder().individual().build()) - .atSpecAoSApplicantCorrespondenceAddressRequired(YES) - .addRespondent2(YES) - .respondent2(PartyBuilder.builder().individual().build()) - .respondent2Copy(PartyBuilder.builder().individual().build()) - .atSpecAoSRespondent2HomeAddressRequired(NO) - .atSpecAoSRespondent2HomeAddressDetails(AddressBuilder.maximal().build()) - .build(); - - AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler - .handle(callbackParamsOf(caseData, ABOUT_TO_SUBMIT)); - - var objectMapper = new ObjectMapper(); - objectMapper.findAndRegisterModules(); - objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); - - assertThat(response.getData()).extracting("applicant1") - .isEqualTo(objectMapper.convertValue(caseData.getApplicant1(), HashMap.class)); - assertThat(response.getData()).extracting("respondent1") - .isEqualTo(objectMapper.convertValue(caseData.getRespondent1(), HashMap.class)); - assertThat(response.getData()).extracting("respondent2") - .isEqualTo(objectMapper.convertValue(caseData.getRespondent2(), HashMap.class)); - } - @Test void updateRespondent1AddressWhenUpdated() { // Given @@ -776,9 +786,11 @@ void updateRespondent1AddressWhenUpdated() { Address changedAddress = AddressBuilder.maximal().build(); CaseData caseData = CaseDataBuilder.builder() + .respondent1(PartyBuilder.builder().individual().build()) .atStateApplicantRespondToDefenceAndProceed() - .atSpecAoSApplicantCorrespondenceAddressRequired(NO) - .atSpecAoSApplicantCorrespondenceAddressDetails(AddressBuilder.maximal().build()) + .build().toBuilder() + .tempCorrespondenceAddress1Required(NO) + .tempCorrespondenceAddress1(AddressBuilder.maximal().build()) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); @@ -809,17 +821,21 @@ void updateRespondent2AddressWhenUpdated() { when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(true); - Address changedAddress = AddressBuilder.maximal().build(); - + Address newAddress2 = AddressBuilder.defaults().build(); CaseData caseData = CaseDataBuilder.builder().atStateApplicantRespondToDefenceAndProceed() .respondent2DQ() .respondent1Copy(PartyBuilder.builder().individual().build()) - .atSpecAoSApplicantCorrespondenceAddressRequired(YES) .addRespondent2(YES) .respondent2(PartyBuilder.builder().individual().build()) .respondent2Copy(PartyBuilder.builder().individual().build()) - .atSpecAoSRespondent2HomeAddressRequired(NO) - .atSpecAoSRespondent2HomeAddressDetails(AddressBuilder.maximal().build()) + .build().toBuilder() + .tempCorrespondenceAddress1Required(YES) + .tempCorrespondenceAddress1(Address.builder().build()) + .build().toBuilder() + .tempCorrespondenceAddress2Required(NO) + .tempCorrespondenceAddress2(newAddress2) + .respondentSolicitor2ServiceAddressRequired(NO) + .respondentSolicitor2ServiceAddress(newAddress2) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); @@ -833,13 +849,13 @@ void updateRespondent2AddressWhenUpdated() { // Then assertThat(response.getData()) .extracting("respondent2").extracting("primaryAddress") - .extracting("AddressLine1").isEqualTo("address line 1"); + .extracting("AddressLine1").isEqualTo(newAddress2.getAddressLine1()); assertThat(response.getData()) .extracting("respondent2").extracting("primaryAddress") - .extracting("AddressLine2").isEqualTo("address line 2"); + .extracting("AddressLine2").isEqualTo(newAddress2.getAddressLine2()); assertThat(response.getData()) .extracting("respondent2").extracting("primaryAddress") - .extracting("AddressLine3").isEqualTo("address line 3"); + .extracting("AddressLine3").isEqualTo(newAddress2.getAddressLine3()); } @Test @@ -852,6 +868,7 @@ void defendantResponsePopulatesWitnessesData() { when(mockedStateFlow.isFlagSet(any())).thenReturn(true); when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(true); + when(toggleService.isHmcEnabled()).thenReturn(true); Witnesses res1witnesses = Witnesses.builder().details( wrapElements( @@ -882,18 +899,20 @@ void defendantResponsePopulatesWitnessesData() { CaseData caseData = CaseDataBuilder.builder().atStateApplicantRespondToDefenceAndProceed() .respondent2DQ() .respondent1Copy(PartyBuilder.builder().individual().build()) - .atSpecAoSApplicantCorrespondenceAddressRequired(YES) .addRespondent2(YES) .respondent2(PartyBuilder.builder().individual().build()) .respondent2Copy(PartyBuilder.builder().individual().build()) - .atSpecAoSRespondent2HomeAddressRequired(NO) - .atSpecAoSRespondent2HomeAddressDetails(AddressBuilder.maximal().build()) .build().toBuilder() .respondent1DQWitnessesSmallClaim(res1witnesses) .respondent2DQWitnessesSmallClaim(res2witnesses) .build().toBuilder() + .tempCorrespondenceAddress1Required(YES) + .tempCorrespondenceAddress1(Address.builder().build()) .respondent2ResponseDate(dateTime) - .respondent1ResponseDate(dateTime).build(); + .respondent1ResponseDate(dateTime).build().toBuilder() + .tempCorrespondenceAddress2Required(NO) + .tempCorrespondenceAddress2(AddressBuilder.maximal().build()) + .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); when(deadlinesCalculator.calculateApplicantResponseDeadlineSpec(any(), any())) @@ -908,14 +927,29 @@ void defendantResponsePopulatesWitnessesData() { objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // Then - assertThat(response.getData()) - .extracting("respondent1DQWitnesses") - .isEqualTo(objectMapper.convertValue(res1witnesses, new TypeReference<>() { - })); - assertThat(response.getData()) - .extracting("respondent2DQWitnesses") - .isEqualTo(objectMapper.convertValue(res2witnesses, new TypeReference<>() { - })); + + Witnesses actualRespondent1DQWitnesses = objectMapper.convertValue(response.getData().get("respondent1DQWitnesses"), new TypeReference<>() {}); + Witness actualRespondent1Witness = unwrapElements(actualRespondent1DQWitnesses.getDetails()).get(0); + assertThat(actualRespondent1Witness.getPartyID()).isNotNull(); + assertThat(actualRespondent1Witness.getFirstName()).isEqualTo("Witness"); + assertThat(actualRespondent1Witness.getLastName()).isEqualTo("One"); + assertThat(actualRespondent1Witness.getEmailAddress()).isEqualTo("test-witness-one@example.com"); + assertThat(actualRespondent1Witness.getPhoneNumber()).isEqualTo("07865456789"); + assertThat(actualRespondent1Witness.getReasonForWitness()).isEqualTo("great reasons"); + assertThat(actualRespondent1Witness.getEventAdded()).isEqualTo("Defendant Response Event"); + assertThat(actualRespondent1Witness.getDateAdded()).isEqualTo(date); + + Witnesses actualRespondent2DQWitnesses = objectMapper.convertValue(response.getData().get("respondent2DQWitnesses"), new TypeReference<>() {}); + Witness respondent2Witness = unwrapElements(actualRespondent2DQWitnesses.getDetails()).get(0); + assertThat(respondent2Witness.getPartyID()).isNotNull(); + assertThat(respondent2Witness.getFirstName()).isEqualTo("Witness"); + assertThat(respondent2Witness.getLastName()).isEqualTo("Two"); + assertThat(respondent2Witness.getEmailAddress()).isEqualTo("test-witness-two@example.com"); + assertThat(respondent2Witness.getPhoneNumber()).isEqualTo("07532628263"); + assertThat(respondent2Witness.getReasonForWitness()).isEqualTo("good reasons"); + assertThat(respondent2Witness.getEventAdded()).isEqualTo("Defendant Response Event"); + assertThat(respondent2Witness.getDateAdded()).isEqualTo(date); + } @Nested @@ -1005,6 +1039,10 @@ void oneVTwo_SecondDefendantRepliesSameLegalRep() { .type(Party.Type.COMPANY) .companyName("company") .build(); + Party defendant2 = Party.builder() + .type(Party.Type.COMPANY) + .companyName("company2") + .build(); CaseData caseData = CaseData.builder() .respondent2SameLegalRepresentative(YES) .caseAccessCategory(SPEC_CLAIM) @@ -1013,6 +1051,8 @@ void oneVTwo_SecondDefendantRepliesSameLegalRep() { .respondent2ClaimResponseTypeForSpec(FULL_ADMISSION) .respondent1(defendant1) .respondent1Copy(defendant1) + .respondent2(defendant2) + .respondent2Copy(defendant2) .respondent1DQ( Respondent1DQ.builder() .respondToCourtLocation( @@ -1058,10 +1098,10 @@ void oneVTwo_SecondDefendantRepliesSameLegalRep() { .thenReturn(true); UserInfo userInfo = UserInfo.builder().uid("798").build(); when(userService.getUserInfo(anyString())).thenReturn(userInfo); - + LocalDate whenWillPay = LocalDate.now().plusDays(5); + given(deadlineExtensionCalculatorService.calculateExtendedDeadline(any(), anyInt())).willReturn(whenWillPay); // When - AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler - .handle(params); + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); // Then AbstractObjectAssert sent2 = assertThat(response.getData()) @@ -1090,11 +1130,17 @@ void oneVTwo_SecondDefendantReplies() { .type(Party.Type.COMPANY) .companyName("company") .build(); + Party defendant2 = Party.builder() + .type(Party.Type.COMPANY) + .companyName("company 2") + .build(); CaseData caseData = CaseData.builder() .caseAccessCategory(SPEC_CLAIM) .ccdCaseReference(354L) .respondent1(defendant1) .respondent1Copy(defendant1) + .respondent2(defendant2) + .respondent2Copy(defendant2) .respondent1DQ( Respondent1DQ.builder() .respondToCourtLocation( @@ -1178,7 +1224,11 @@ void shouldNullDocuments_whenInvokedAndCaseFileEnabled() { .respondent1(PartyBuilder.builder().individual().build()) .respondent1Copy(PartyBuilder.builder().individual().build()) .respondent1DQ(Respondent1DQ.builder().build()) + .respondent2(PartyBuilder.builder().individual().build()) + .respondent2Copy(PartyBuilder.builder().individual().build()) .respondent2DQ(Respondent2DQ.builder().build()) + .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_DEFENCE) + .respondent2ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_DEFENCE) .ccdCaseReference(354L) .respondent1SpecDefenceResponseDocument(testDocument) .respondent2SpecDefenceResponseDocument(testDocument) @@ -1196,32 +1246,30 @@ void shouldNullDocuments_whenInvokedAndCaseFileEnabled() { } @Test - void shouldUpdateCorrespondence1_whenProvided() { + void shouldUpdateExpertEvents_whenInvokedAndUpdateContactDetailsEnabled_For2DivergeResponse() { // Given + LocalDateTime dateTime = LocalDateTime.of(2023, 6, 6, 6, 6, 6); when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); when(mockedStateFlow.isFlagSet(any())).thenReturn(true); when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); - when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).thenReturn(true); - when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(false); - when(toggleService.isCaseFileViewEnabled()).thenReturn(true); - var testDocument = ResponseDocument.builder() - .file(Document.builder().documentUrl("fake-url").documentFileName("file-name").documentBinaryUrl("binary-url").build()).build(); + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(true); + when(toggleService.isUpdateContactDetailsEnabled()).thenReturn(true); CaseData caseData = CaseData.builder() .respondent1(PartyBuilder.builder().individual().build()) .respondent1Copy(PartyBuilder.builder().individual().build()) - .respondent1DQ(Respondent1DQ.builder().build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQExperts(Experts.builder() + .details(wrapElements(Expert.builder().build())).build()) + .build()) + .respondent2(PartyBuilder.builder().individual().build()) + .respondent2Copy(PartyBuilder.builder().individual().build()) .respondent2DQ(Respondent2DQ.builder().build()) + .claimant1ClaimResponseTypeForSpec(FULL_DEFENCE) + .claimant2ClaimResponseTypeForSpec(FULL_ADMISSION) .ccdCaseReference(354L) - .respondent1SpecDefenceResponseDocument(testDocument) - .respondent2SpecDefenceResponseDocument(testDocument) - .isRespondent1(YesOrNo.YES) - .specAoSRespondentCorrespondenceAddressRequired(YesOrNo.NO) - .specAoSRespondentCorrespondenceAddressdetails( - Address.builder() - .postCode("new postcode") - .build() - ) + .respondent1ResponseDate(dateTime).build().toBuilder() + .respondent2SameLegalRepresentative(YES) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); @@ -1231,46 +1279,36 @@ void shouldUpdateCorrespondence1_whenProvided() { .handle(params); // Then - assertThat(response.getData().get("specRespondentCorrespondenceAddressdetails")) - .extracting("PostCode") - .isEqualTo("new postcode"); - assertThat(response.getData().get("specAoSRespondentCorrespondenceAddressdetails")) - .extracting("PostCode") - .isNull(); + assertThat(response.getData().get("respondent1DQExperts")).isNotNull(); + assertThat(response.getData().get("respondent2DQExperts")).isNull(); + } @Test - void shouldUpdateCorrespondence1_whenProvided1v2ss() { + void shouldUpdateExpertEvents_whenInvokedAndUpdateContactDetailsEnabled_CanAddApplicant2() { // Given + LocalDateTime dateTime = LocalDateTime.of(2023, 6, 6, 6, 6, 6); when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); when(mockedStateFlow.isFlagSet(any())).thenReturn(true); when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); - when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).thenReturn(true); - when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(false); - when(toggleService.isCaseFileViewEnabled()).thenReturn(true); - var testDocument = ResponseDocument.builder() - .file(Document.builder().documentUrl("fake-url").documentFileName("file-name").documentBinaryUrl("binary-url").build()).build(); + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(true); + when(toggleService.isUpdateContactDetailsEnabled()).thenReturn(true); CaseData caseData = CaseData.builder() .respondent1(PartyBuilder.builder().individual().build()) .respondent1Copy(PartyBuilder.builder().individual().build()) - .respondent1DQ(Respondent1DQ.builder().build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQExperts(Experts.builder() + .details(wrapElements(Expert.builder().build())).build()) + .build()) + .respondent2(PartyBuilder.builder().individual().build()) + .respondent2Copy(PartyBuilder.builder().individual().build()) .respondent2DQ(Respondent2DQ.builder().build()) + .claimant1ClaimResponseTypeForSpec(FULL_DEFENCE) + .claimant2ClaimResponseTypeForSpec(FULL_ADMISSION) .ccdCaseReference(354L) - .respondent1SpecDefenceResponseDocument(testDocument) - .respondent2SpecDefenceResponseDocument(testDocument) - .isRespondent1(YesOrNo.YES) - .specAoSRespondentCorrespondenceAddressRequired(YesOrNo.NO) - .specAoSRespondentCorrespondenceAddressdetails( - Address.builder() - .postCode("new postcode") - .build() - ) - .respondent2(Party.builder() - .type(Party.Type.COMPANY) - .companyName("Company 3") - .build()) - .respondent2SameLegalRepresentative(YES) + .respondent1ResponseDate(dateTime).build().toBuilder() + .addApplicant2(YES) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); @@ -1280,48 +1318,35 @@ void shouldUpdateCorrespondence1_whenProvided1v2ss() { .handle(params); // Then - assertThat(response.getData().get("specRespondentCorrespondenceAddressdetails")) - .extracting("PostCode") - .isEqualTo("new postcode"); - assertThat(response.getData().get("specAoSRespondentCorrespondenceAddressdetails")) - .extracting("PostCode") - .isNull(); - assertEquals( - response.getData().get("specRespondentCorrespondenceAddressdetails"), - response.getData().get("specRespondent2CorrespondenceAddressdetails") - ); - assertEquals( - response.getData().get("specRespondentCorrespondenceAddressRequired"), - response.getData().get("specRespondent2CorrespondenceAddressRequired") - ); + assertThat(response.getData().get("respondent1DQExperts")).isNotNull(); + assertThat(response.getData().get("respondent2DQExperts")).isNull(); + } @Test - void shouldUpdateCorrespondence2_whenProvided() { + void shouldUpdateExpertEvents_whenInvokedAndUpdateContactDetailsEnabled_FullAdmission() { // Given + LocalDateTime dateTime = LocalDateTime.of(2023, 6, 6, 6, 6, 6); when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); when(mockedStateFlow.isFlagSet(any())).thenReturn(true); when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(true); - when(toggleService.isCaseFileViewEnabled()).thenReturn(true); - var testDocument = ResponseDocument.builder() - .file(Document.builder().documentUrl("fake-url").documentFileName("file-name").documentBinaryUrl("binary-url").build()).build(); + when(toggleService.isUpdateContactDetailsEnabled()).thenReturn(true); CaseData caseData = CaseData.builder() .respondent1(PartyBuilder.builder().individual().build()) .respondent1Copy(PartyBuilder.builder().individual().build()) - .respondent1DQ(Respondent1DQ.builder().build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQExperts(Experts.builder() + .details(wrapElements(Expert.builder().build())).build()) + .build()) + .respondent2(PartyBuilder.builder().individual().build()) + .respondent2Copy(PartyBuilder.builder().individual().build()) .respondent2DQ(Respondent2DQ.builder().build()) + .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_ADMISSION) + .respondent2ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_ADMISSION) .ccdCaseReference(354L) - .respondent1SpecDefenceResponseDocument(testDocument) - .respondent2SpecDefenceResponseDocument(testDocument) - .isRespondent2(YesOrNo.YES) - .specAoSRespondent2CorrespondenceAddressRequired(YesOrNo.NO) - .specAoSRespondent2CorrespondenceAddressdetails( - Address.builder() - .postCode("new postcode") - .build() - ) + .respondent1ResponseDate(dateTime).build().toBuilder() .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); @@ -1331,76 +1356,564 @@ void shouldUpdateCorrespondence2_whenProvided() { .handle(params); // Then - assertThat(response.getData().get("specRespondent2CorrespondenceAddressdetails")) - .extracting("PostCode") - .isEqualTo("new postcode"); - assertThat(response.getData().get("specAoSRespondent2CorrespondenceAddressdetails")) - .extracting("PostCode") - .isNull(); + assertThat(response.getData().get("respondent1DQExperts")).isNotNull(); + assertThat(response.getData().get("respondent2DQExperts")).isNull(); + } @Test - void shouldPopulateRespondent2Flag_WhenInvoked() { + void shouldUpdateExpertEvents_whenInvokedAndUpdateContactDetailsEnabled() { // Given - when(toggleService.isCaseFileViewEnabled()).thenReturn(true); + LocalDateTime dateTime = LocalDateTime.of(2023, 6, 6, 6, 6, 6); when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + when(mockedStateFlow.isFlagSet(any())).thenReturn(true); when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); - given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).willReturn(true); - given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).willReturn(false); - CaseData caseData = CaseDataBuilder.builder() - .atStateClaimDetailsNotified() - .respondent2(PartyBuilder.builder().individual().build()) - .addRespondent2(YES) + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(true); + when(toggleService.isUpdateContactDetailsEnabled()).thenReturn(true); + + CaseData caseData = CaseData.builder() .respondent1(PartyBuilder.builder().individual().build()) .respondent1Copy(PartyBuilder.builder().individual().build()) - .respondent1DQ(Respondent1DQ.builder().build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQExperts(Experts.builder() + .details(wrapElements(Expert.builder().build())).build()) + .build()) + .respondent2(PartyBuilder.builder().individual().build()) + .respondent2Copy(PartyBuilder.builder().individual().build()) .respondent2DQ(Respondent2DQ.builder().build()) + .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_DEFENCE) + .respondent2ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_DEFENCE) + .ccdCaseReference(354L) + .respondent1ResponseDate(dateTime).build().toBuilder() .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + // When AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler .handle(params); - // Given - assertThat(response.getData().get("respondent2DocumentGeneration")).isEqualTo("userRespondent2"); + + // Then + assertThat(response.getData().get("respondent1DQExperts")).isNotNull(); + assertThat(response.getData().get("respondent2DQExperts")).isNull(); + } @Test - void shouldNotPopulateRespondent2Flag_WhenInvoked() { + void shouldUpdateExpertEvents_whenInvokedAndUpdateContactDetailsEnabled_V2DraftDirections() { // Given - when(toggleService.isCaseFileViewEnabled()).thenReturn(true); + LocalDateTime dateTime = LocalDateTime.of(2023, 6, 6, 6, 6, 6); when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + when(mockedStateFlow.isFlagSet(any())).thenReturn(true); when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); - given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).willReturn(false); - given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).willReturn(true); - CaseData caseData = CaseDataBuilder.builder() - .atStateClaimDetailsNotified() - .respondent2(PartyBuilder.builder().individual().build()) - .addRespondent2(YES) + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(true); + when(toggleService.isUpdateContactDetailsEnabled()).thenReturn(true); + + CaseData caseData = CaseData.builder() .respondent1(PartyBuilder.builder().individual().build()) .respondent1Copy(PartyBuilder.builder().individual().build()) - .respondent1DQ(Respondent1DQ.builder().build()) - .respondent2DQ(Respondent2DQ.builder().build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQExperts(Experts.builder() + .details(wrapElements(Expert.builder().build())).build()) + .build()) + .respondent2(PartyBuilder.builder().individual().build()) + .respondent2Copy(PartyBuilder.builder().individual().build()) + .respondent2DQ(Respondent2DQ.builder() + .respondent2DQDraftDirections(Document.builder().build()).build()) + .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_DEFENCE) + .respondent2ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_DEFENCE) + .ccdCaseReference(354L) + .respondent1ResponseDate(dateTime).build().toBuilder() .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + // When AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler .handle(params); - // Given - assertThat(response.getData().get("respondent2DocumentGeneration")).isNull(); - } - @Nested - class MidEventSetGenericResponseTypeFlagCallback { + // Then + assertThat(response.getData().get("respondent1DQExperts")).isNotNull(); + assertThat(response.getData().get("respondent2DQExperts")).isNull(); - private static final String PAGE_ID = "set-generic-response-type-flag"; + } - @Test - void shouldSetMultiPartyResponseTypeFlags_Counter_Admit_OR_Admit_Part_combination1() { - // Given - CaseData caseData = CaseDataBuilder.builder().atStateRespondent2v1BothNotFullDefence_PartAdmissionX2() - .build(); + @Test + void shouldUpdateWitnessEvents_whenInvokedAndUpdateContactDetailsEnabled() { + // Given + LocalDateTime dateTime = LocalDateTime.of(2023, 6, 6, 6, 6, 6); + when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + when(mockedStateFlow.isFlagSet(any())).thenReturn(true); + when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(true); + when(toggleService.isUpdateContactDetailsEnabled()).thenReturn(true); - CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + CaseData caseData = CaseData.builder() + .respondent1(PartyBuilder.builder().individual().build()) + .respondent1Copy(PartyBuilder.builder().individual().build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQWitnesses(Witnesses.builder() + .details(wrapElements(Witness.builder().build())).build()) + .build()) + + .respondent2(PartyBuilder.builder().individual().build()) + .respondent2Copy(PartyBuilder.builder().individual().build()) + .respondent2DQ(Respondent2DQ.builder().build()) + .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_DEFENCE) + .respondent2ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_DEFENCE) + .ccdCaseReference(354L) + .respondent1ResponseDate(dateTime).build().toBuilder() + .build(); + + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + // When + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + // Then + assertThat(response.getData().get("respondent1DQWitnesses")).isNotNull(); + assertThat(response.getData().get("respondent2DQWitnesses")).isNull(); + + } + + @Test + void shouldUpdateCorrespondence1_whenProvided() { + // Given + when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + when(mockedStateFlow.isFlagSet(any())).thenReturn(true); + when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).thenReturn(true); + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(false); + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); + var testDocument = ResponseDocument.builder() + .file(Document.builder().documentUrl("fake-url").documentFileName("file-name").documentBinaryUrl("binary-url").build()).build(); + + CaseData caseData = CaseData.builder() + .respondent1(PartyBuilder.builder().individual().build()) + .respondent1Copy(PartyBuilder.builder().individual().build()) + .respondent1DQ(Respondent1DQ.builder().build()) + .respondent2DQ(Respondent2DQ.builder().build()) + .ccdCaseReference(354L) + .respondent1SpecDefenceResponseDocument(testDocument) + .respondent2SpecDefenceResponseDocument(testDocument) + .isRespondent1(YesOrNo.YES) + .respondentSolicitor1ServiceAddressRequired(YesOrNo.NO) + .respondentSolicitor1ServiceAddress( + Address.builder() + .postCode("new postcode") + .build() + ) + .build(); + + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + // When + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + // Then + assertThat(response.getData().get("specRespondentCorrespondenceAddressdetails")) + .extracting("PostCode") + .isEqualTo("new postcode"); + assertThat(response.getData().get("respondentSolicitor1ServiceAddress")) + .extracting("PostCode") + .isNull(); + } + + @Test + void shouldUpdateCorrespondence1_whenProvided1v2ss() { + // Given + when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + when(mockedStateFlow.isFlagSet(any())).thenReturn(true); + when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).thenReturn(true); + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(false); + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); + var testDocument = ResponseDocument.builder() + .file(Document.builder().documentUrl("fake-url").documentFileName("file-name").documentBinaryUrl("binary-url").build()).build(); + + CaseData caseData = CaseData.builder() + .respondent1(PartyBuilder.builder().individual().build()) + .respondent1Copy(PartyBuilder.builder().individual().build()) + .respondent1DQ(Respondent1DQ.builder().build()) + .respondent2DQ(Respondent2DQ.builder().build()) + .ccdCaseReference(354L) + .respondent1SpecDefenceResponseDocument(testDocument) + .respondent2SpecDefenceResponseDocument(testDocument) + .isRespondent1(YesOrNo.YES) + .respondentSolicitor1ServiceAddressRequired(YesOrNo.NO) + .respondentSolicitor1ServiceAddress( + Address.builder() + .postCode("new postcode") + .build() + ) + .respondent2(Party.builder() + .type(Party.Type.COMPANY) + .companyName("Company 3") + .build()) + .respondent2SameLegalRepresentative(YES) + .build(); + + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + // When + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + // Then + assertThat(response.getData().get("specRespondentCorrespondenceAddressdetails")) + .extracting("PostCode") + .isEqualTo("new postcode"); + assertThat(response.getData().get("respondentSolicitor1ServiceAddress")) + .extracting("PostCode") + .isNull(); + assertEquals( + response.getData().get("specRespondentCorrespondenceAddressdetails"), + response.getData().get("specRespondent2CorrespondenceAddressdetails") + ); + assertEquals( + response.getData().get("specRespondentCorrespondenceAddressRequired"), + response.getData().get("specRespondent2CorrespondenceAddressRequired") + ); + } + + @Test + void shouldUpdateCorrespondence1_whenProvided1v2ss_withSameResponse() { + // Given + when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + when(mockedStateFlow.isFlagSet(any())).thenReturn(true); + when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).thenReturn(true); + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(false); + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); + var testDocument = ResponseDocument.builder() + .file(Document.builder().documentUrl("fake-url").documentFileName("file-name").documentBinaryUrl("binary-url").build()).build(); + + CaseData caseData = CaseData.builder() + .respondent1(PartyBuilder.builder().individual().build()) + .respondent1Copy(PartyBuilder.builder().individual().build()) + .respondent1DQ(Respondent1DQ.builder().build()) + .respondent2DQ(Respondent2DQ.builder().build()) + .ccdCaseReference(354L) + .respondent1SpecDefenceResponseDocument(testDocument) + .respondent2SpecDefenceResponseDocument(testDocument) + .isRespondent1(YesOrNo.YES) + .respondentResponseIsSame(YES) + .respondentSolicitor1ServiceAddressRequired(YesOrNo.NO) + .respondentSolicitor1ServiceAddress( + Address.builder() + .postCode("new postcode") + .build() + ) + .respondent2(Party.builder() + .type(Party.Type.COMPANY) + .companyName("Company 3") + .build()) + .respondent2SameLegalRepresentative(YES) + .build(); + + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + // When + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + // Then + assertThat(response.getData().get("specRespondentCorrespondenceAddressdetails")) + .extracting("PostCode") + .isEqualTo("new postcode"); + assertThat(response.getData().get("respondentSolicitor1ServiceAddress")) + .extracting("PostCode") + .isNull(); + assertEquals( + response.getData().get("specRespondentCorrespondenceAddressdetails"), + response.getData().get("specRespondent2CorrespondenceAddressdetails") + ); + assertEquals( + response.getData().get("specRespondentCorrespondenceAddressRequired"), + response.getData().get("specRespondent2CorrespondenceAddressRequired") + ); + } + + @Test + void shouldUpdateCorrespondence1_whenProvided1v2ss_withSameResponse_withv2copy() { + // Given + when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + when(mockedStateFlow.isFlagSet(any())).thenReturn(true); + when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).thenReturn(true); + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(false); + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); + var testDocument = ResponseDocument.builder() + .file(Document.builder().documentUrl("fake-url").documentFileName("file-name").documentBinaryUrl("binary-url").build()).build(); + + CaseData caseData = CaseData.builder() + .respondent1(PartyBuilder.builder().individual().build()) + .respondent1Copy(PartyBuilder.builder().individual().build()) + .respondent1DQ(Respondent1DQ.builder().build()) + .respondent2DQ(Respondent2DQ.builder().build()) + .ccdCaseReference(354L) + .respondent1SpecDefenceResponseDocument(testDocument) + .respondent2SpecDefenceResponseDocument(testDocument) + .isRespondent1(YesOrNo.YES) + .respondentResponseIsSame(YES) + .respondentSolicitor1ServiceAddressRequired(YesOrNo.NO) + .respondentSolicitor1ServiceAddress( + Address.builder() + .postCode("new postcode") + .build() + ) + .respondent2(Party.builder() + .type(Party.Type.COMPANY) + .companyName("Company 3") + .build()) + .respondent2Copy(PartyBuilder.builder().individual().build()) + .respondent2SameLegalRepresentative(YES) + .build(); + + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + // When + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + // Then + assertThat(response.getData().get("specRespondentCorrespondenceAddressdetails")) + .extracting("PostCode") + .isEqualTo("new postcode"); + assertThat(response.getData().get("respondentSolicitor1ServiceAddress")) + .extracting("PostCode") + .isNull(); + assertEquals( + response.getData().get("specRespondentCorrespondenceAddressdetails"), + response.getData().get("specRespondent2CorrespondenceAddressdetails") + ); + assertEquals( + response.getData().get("specRespondentCorrespondenceAddressRequired"), + response.getData().get("specRespondent2CorrespondenceAddressRequired") + ); + } + + @Test + void shouldUpdateCorrespondence1_whenProvided1v2ss_withSameResponse_withv2copyAndNoTempAdr() { + // Given + when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + when(mockedStateFlow.isFlagSet(any())).thenReturn(true); + when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).thenReturn(true); + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(false); + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); + var testDocument = ResponseDocument.builder() + .file(Document.builder().documentUrl("fake-url").documentFileName("file-name").documentBinaryUrl("binary-url").build()).build(); + + CaseData caseData = CaseData.builder() + .respondent1(PartyBuilder.builder().individual().build()) + .respondent1Copy(PartyBuilder.builder().individual().build()) + .respondent1DQ(Respondent1DQ.builder().build()) + .respondent2DQ(Respondent2DQ.builder().build()) + .ccdCaseReference(354L) + .respondent1SpecDefenceResponseDocument(testDocument) + .respondent2SpecDefenceResponseDocument(testDocument) + .isRespondent1(YesOrNo.YES) + .respondentResponseIsSame(YES) + .respondentSolicitor1ServiceAddressRequired(YesOrNo.NO) + .respondentSolicitor1ServiceAddress( + Address.builder() + .postCode("new postcode") + .build() + ) + .respondent2(Party.builder() + .type(Party.Type.COMPANY) + .companyName("Company 3") + .build()) + .respondent2Copy(PartyBuilder.builder().individual().build()) + .respondent2SameLegalRepresentative(YES) + .tempCorrespondenceAddress2Required(NO) + .build(); + + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + // When + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + // Then + assertThat(response.getData().get("specRespondentCorrespondenceAddressdetails")) + .extracting("PostCode") + .isEqualTo("new postcode"); + assertThat(response.getData().get("respondentSolicitor1ServiceAddress")) + .extracting("PostCode") + .isNull(); + assertEquals( + response.getData().get("specRespondentCorrespondenceAddressdetails"), + response.getData().get("specRespondent2CorrespondenceAddressdetails") + ); + assertEquals( + response.getData().get("specRespondentCorrespondenceAddressRequired"), + response.getData().get("specRespondent2CorrespondenceAddressRequired") + ); + } + + @Test + void shouldUpdateCorrespondence2_whenProvided() { + // Given + when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + when(mockedStateFlow.isFlagSet(any())).thenReturn(true); + when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); + when(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).thenReturn(true); + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); + var testDocument = ResponseDocument.builder() + .file(Document.builder().documentUrl("fake-url").documentFileName("file-name").documentBinaryUrl("binary-url").build()).build(); + + CaseData caseData = CaseData.builder() + .respondent1(PartyBuilder.builder().individual().build()) + .respondent1Copy(PartyBuilder.builder().individual().build()) + .respondent1DQ(Respondent1DQ.builder().build()) + .respondent2(PartyBuilder.builder().individual().build()) + .respondent2Copy(PartyBuilder.builder().individual().build()) + .respondent2DQ(Respondent2DQ.builder().build()) + .ccdCaseReference(354L) + .respondent1SpecDefenceResponseDocument(testDocument) + .respondent2SpecDefenceResponseDocument(testDocument) + .isRespondent2(YesOrNo.YES) + .respondentSolicitor2ServiceAddressRequired(YesOrNo.NO) + .respondentSolicitor2ServiceAddress( + Address.builder() + .postCode("new postcode") + .build() + ) + .build(); + + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + // When + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + // Then + assertThat(response.getData().get("specRespondent2CorrespondenceAddressdetails")) + .extracting("PostCode") + .isEqualTo("new postcode"); + assertThat(response.getData().get("respondentSolicitor2ServiceAddress")) + .extracting("PostCode") + .isNull(); + } + + @Test + void shouldPopulateRespondent2Flag_WhenInvoked() { + // Given + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); + when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).willReturn(true); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).willReturn(false); + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimDetailsNotified() + .respondent2(PartyBuilder.builder().individual().build()) + .addRespondent2(YES) + .respondent1(PartyBuilder.builder().individual().build()) + .respondent1Copy(PartyBuilder.builder().individual().build()) + .respondent1DQ(Respondent1DQ.builder().build()) + .respondent2DQ(Respondent2DQ.builder().build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + // When + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + // Given + assertThat(response.getData().get("respondent2DocumentGeneration")).isEqualTo("userRespondent2"); + } + + @Test + void shouldPopulateRespondent2Flag_WhenInvokedWithSmallClaimExperts_1DQ() { + // Given + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); + when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).willReturn(true); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).willReturn(false); + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimDetailsNotified() + .respondent2(PartyBuilder.builder().individual().build()) + .addRespondent2(YES) + .respondent1(PartyBuilder.builder().individual().build()) + .respondent1Copy(PartyBuilder.builder().individual().build()) + .respondent1DQ(Respondent1DQ.builder() + .respondToClaimExperts(ExpertDetails.builder().build()).build()) + .respondent2DQ(Respondent2DQ.builder().build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + // When + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + // Given + assertThat(response.getData().get("respondent2DocumentGeneration")).isEqualTo("userRespondent2"); + } + + @Test + void shouldPopulateRespondent2Flag_WhenInvokedWithSmallClaimExperts_2DQ() { + // Given + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); + when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).willReturn(true); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).willReturn(false); + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimDetailsNotified() + .respondent2(PartyBuilder.builder().individual().build()) + .addRespondent2(YES) + .respondent1(PartyBuilder.builder().individual().build()) + .respondent1Copy(PartyBuilder.builder().individual().build()) + .respondent2DQ(Respondent2DQ.builder() + .respondToClaimExperts2(ExpertDetails.builder().build()).build()) + .respondent1DQ(Respondent1DQ.builder().build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + // When + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + // Given + assertThat(response.getData().get("respondent2DocumentGeneration")).isEqualTo("userRespondent2"); + } + + @Test + void shouldNotPopulateRespondent2Flag_WhenInvoked() { + // Given + when(toggleService.isCaseFileViewEnabled()).thenReturn(true); + when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + when(stateFlowEngine.evaluate(any(CaseData.class))).thenReturn(mockedStateFlow); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORTWO))).willReturn(false); + given(coreCaseUserService.userHasCaseRole(any(), any(), eq(RESPONDENTSOLICITORONE))).willReturn(true); + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimDetailsNotified() + .respondent2(PartyBuilder.builder().individual().build()) + .addRespondent2(YES) + .respondent1(PartyBuilder.builder().individual().build()) + .respondent1Copy(PartyBuilder.builder().individual().build()) + .respondent1DQ(Respondent1DQ.builder().build()) + .respondent2DQ(Respondent2DQ.builder().build()) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + // When + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + // Given + assertThat(response.getData().get("respondent2DocumentGeneration")).isNull(); + } + + @Nested + class MidEventSetGenericResponseTypeFlagCallback { + + private static final String PAGE_ID = "set-generic-response-type-flag"; + + @Test + void shouldSetMultiPartyResponseTypeFlags_Counter_Admit_OR_Admit_Part_combination1() { + // Given + CaseData caseData = CaseDataBuilder.builder().atStateRespondent2v1BothNotFullDefence_PartAdmissionX2() + .build(); + + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); // When var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -1426,6 +1939,26 @@ void shouldSetMultiPartyResponseTypeFlags_Counter_Admit_OR_Admit_Part_combinatio .isEqualTo("COUNTER_ADMIT_OR_ADMIT_PART"); } + @Test + void shouldSetMultiPartyResponseTypeFlags_Counter_Admit_OR_Admit_Part_combination2_CanAddApplicant2() { + // Given + CaseData caseData = CaseDataBuilder.builder().atStateRespondent2v1BothNotFullDefence_CounterClaimX2() + .addApplicant2(YES) + .respondent1ClaimResponseTypeForSpec(FULL_ADMISSION) + .respondent1ClaimResponseTypeForSpec(FULL_ADMISSION) + .build(); + + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + + // When + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + // Then + assertThat(response.getData()).extracting("multiPartyResponseTypeFlags") + .isEqualTo("COUNTER_ADMIT_OR_ADMIT_PART"); + } + + /** * if solicitor says that each defendant gets their response but then chooses the same * option from full defence/part admit/full admit/counterclaim, then it is not different response. @@ -1516,7 +2049,6 @@ void shouldReturnError_whenWitnessRequiredAndNullDetails() { void shouldReturnNoError_whenWitnessRequiredAndDetailsProvided() { // Given List> testWitness = wrapElements(Witness.builder().name("test witness").build()); - Witnesses witnesses = Witnesses.builder().witnessesToAppear(YES).details(testWitness).build(); CaseData caseData = CaseDataBuilder.builder() .respondent1DQ(Respondent1DQ.builder().build()) .respondent1DQWitnessesRequiredSpec(YES) @@ -1605,9 +2137,6 @@ void specificSummary_whenPartialAdmitNotPay() { // When SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); - LocalDateTime responseDeadline = caseData.getApplicant1ResponseDeadline(); - String claimNumber = caseData.getLegacyCaseReference(); - // Then assertThat(response.getConfirmationBody()) .contains(caseData.getApplicant1().getPartyName()) @@ -2015,12 +2544,12 @@ void whenProvided_thenValidateCorrespondence1() { CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build() .toBuilder() .isRespondent1(YES) - .specAoSRespondentCorrespondenceAddressRequired(YesOrNo.NO) - .specAoSRespondentCorrespondenceAddressdetails(Address.builder() + .respondentSolicitor1ServiceAddressRequired(YesOrNo.NO) + .respondentSolicitor1ServiceAddress(Address.builder() .postCode("postal code") .build()) .build(); - CallbackParams params = callbackParamsOf(caseData, MID, "confirm-details"); + CallbackParams params = callbackParamsOf(caseData, MID, "specCorrespondenceAddress"); when(postcodeValidator.validate("postal code")).thenReturn(Collections.emptyList()); // When @@ -2037,12 +2566,12 @@ void whenProvided_thenValidateCorrespondence2() { CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build() .toBuilder() .isRespondent2(YES) - .specAoSRespondent2CorrespondenceAddressRequired(YesOrNo.NO) - .specAoSRespondent2CorrespondenceAddressdetails(Address.builder() + .respondentSolicitor2ServiceAddressRequired(YesOrNo.NO) + .respondentSolicitor2ServiceAddress(Address.builder() .postCode("postal code") .build()) .build(); - CallbackParams params = callbackParamsOf(caseData, MID, "confirm-details"); + CallbackParams params = callbackParamsOf(caseData, MID, "specCorrespondenceAddress"); when(postcodeValidator.validate("postal code")).thenReturn(Collections.emptyList()); // When @@ -2060,7 +2589,12 @@ class AboutToStart { @Test void shouldPopulateCourtLocations() { // Given - CaseData caseData = CaseData.builder().build(); + CaseData caseData = CaseData.builder() + .respondent1(Party.builder() + .partyName("name") + .type(Party.Type.INDIVIDUAL) + .build()) + .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_START); List locations = List.of(LocationRefData.builder() @@ -2267,6 +2801,50 @@ public void shouldThrowError_whenValidateRespondentExpertsMultipartyWithNoUnavai // Then assertThat(response.getErrors()).isNotEmpty(); } + + @Test + public void shouldThrowError_whenValidateRespondentExpertsMultipartyWithNoUnavailableDates_DisputesTheClaim() { + // Given + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified() + .responseClaimTrack(SpecJourneyConstantLRSpec.DISPUTES_THE_CLAIM) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQHearingSmallClaim(SmallClaimHearing.builder().unavailableDatesRequired( + YES).build()).build()) + .build(); + List errors = Collections.singletonList("error 1"); + Mockito.when(dateValidator.validateFastClaimHearing(any())).thenReturn(errors); + CallbackParams params = callbackParamsOf(caseData, MID, "validate-unavailable-dates"); + // When + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + // Then + assertThat(response.getErrors()).isNotEmpty(); + } + + @Test + public void shouldThrowError_whenValidateRespondentExpertsMultipartyWithNoUnavailableDates_V2() { + // Given + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified() + .responseClaimTrack(SpecJourneyConstantLRSpec.SMALL_CLAIM) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQHearingSmallClaim(SmallClaimHearing.builder().unavailableDatesRequired( + YES).build()).build()) + .respondent2DQ(Respondent2DQ.builder() + .respondent2DQHearingSmallClaim(SmallClaimHearing.builder().unavailableDatesRequired( + YES).build()).build()) + .isRespondent2(YES) + .build(); + List errors = Collections.singletonList("error 1"); + Mockito.when(dateValidator.validateSmallClaimsHearing(any())).thenReturn(errors); + CallbackParams params = callbackParamsOf(caseData, MID, "validate-unavailable-dates"); + // When + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); + + // Then + assertThat(response.getErrors()).isNotEmpty(); + } } @Test diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceCallbackHandlerTest.java index 5f3e2eed505..477f89efc1a 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceCallbackHandlerTest.java @@ -19,6 +19,8 @@ import uk.gov.hmcts.reform.ccd.client.model.SubmittedCallbackResponse; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.config.ExitSurveyConfiguration; +import uk.gov.hmcts.reform.civil.config.ToggleConfiguration; +import uk.gov.hmcts.reform.civil.documentmanagement.model.Document; import uk.gov.hmcts.reform.civil.enums.CaseState; import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.enums.dq.UnavailableDateType; @@ -69,12 +71,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.CLAIMANT_RESPONSE; +import static uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType.DEFENDANT_DEFENCE; import static uk.gov.hmcts.reform.civil.enums.BusinessProcessStatus.READY; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; @@ -121,6 +125,9 @@ class RespondToDefenceCallbackHandlerTest extends BaseCallbackHandlerTest { @MockBean private FeatureToggleService featureToggleService; + @MockBean + private ToggleConfiguration toggleConfiguration; + @Nested class AboutToStartCallback { @@ -206,18 +213,46 @@ class OneVTwo { @Test void shouldSetRespondentSharedClaimResponseDocumentSameSolicitorScenario_WhenAboutToStartIsInvoked() { - CaseData caseData = CaseDataBuilder.builder() - .atStateRespondentFullDefenceAfterNotifyClaimDetails() - .multiPartyClaimOneDefendantSolicitor() + CaseData caseData = CaseDataBuilder.builder().atStateRespondentFullDefenceAfterNotifyClaimDetails().build().toBuilder() + .respondent2(PartyBuilder.builder().individual().build()) + .addRespondent2(YES) + .respondent2(PartyBuilder.builder().individual().build()) + .respondent2SameLegalRepresentative(YES) + .defendantResponseDocuments(wrapElements(CaseDocument.builder() + .documentType(DEFENDANT_DEFENCE) + .documentLink(Document.builder() + .documentUrl("url") + .documentHash("hash") + .documentFileName("respondent defense") + .documentBinaryUrl("binUrl") + .build()).build())) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_START); AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler .handle(params); + assertThat(response.getErrors()).isNull(); + assertThat(response.getData()).extracting("respondentSharedClaimResponseDocument").isNotNull(); + } + + @Test + void shouldSetRespondent1ClaimResponseDocument_WhenAboutToStartIsInvoked() { + CaseData caseData = CaseDataBuilder.builder().atStateRespondentFullDefenceAfterNotifyClaimDetails().build().toBuilder() + .defendantResponseDocuments(wrapElements(CaseDocument.builder() + .documentType(DEFENDANT_DEFENCE) + .documentLink(Document.builder() + .documentUrl("url") + .documentHash("hash") + .documentFileName("respondent defense") + .documentBinaryUrl("binUrl") + .build()).build())) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_START); + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); assertThat(response.getErrors()).isNull(); - assertThat(response.getData().get("respondentSharedClaimResponseDocument")) - .isEqualTo(caseData.toMap(mapper).get("respondent1ClaimResponseDocument")); + assertThat(response.getData()).extracting("respondent1ClaimResponseDocument").isNotNull(); } @Test @@ -514,6 +549,7 @@ class AboutToSubmitCallback { @BeforeEach void setup() { when(time.now()).thenReturn(localDateTime); + given(toggleConfiguration.getFeatureToggle()).willReturn("WA 3.5"); } @ParameterizedTest @@ -642,6 +678,7 @@ void shouldNotAddPartyIdsToPartyFields_whenInvokedWithHMCToggleOff() { @Test void shouldAssembleClaimantResponseDocuments2v1ProceedBoth() { when(time.now()).thenReturn(LocalDateTime.of(2022, 2, 18, 12, 10, 55)); + when(featureToggleService.isCaseFileViewEnabled()).thenReturn(true); var caseData = CaseDataBuilder.builder().build().toBuilder() .respondent1(Party.builder().companyName("company").type(Party.Type.COMPANY).build()) .applicant1DefenceResponseDocument(ResponseDocument.builder() @@ -682,7 +719,7 @@ void shouldAssembleClaimantResponseDocuments2v1ProceedBoth() { @SuppressWarnings("unchecked") List docs = (ArrayList) response.getData().get("claimantResponseDocuments"); - assertEquals(4, docs.size()); + assertEquals(8, docs.size()); assertThat(response.getData()) .extracting("claimantResponseDocuments") @@ -703,6 +740,7 @@ void shouldAssembleClaimantResponseDocuments2v1ProceedBoth() { @Test void shouldAssembleClaimantResponseDocuments2v1ProceedOne() { when(time.now()).thenReturn(LocalDateTime.of(2022, 2, 18, 12, 10, 55)); + when(featureToggleService.isCaseFileViewEnabled()).thenReturn(true); var caseData = CaseDataBuilder.builder().build().toBuilder() .respondent1(Party.builder().companyName("company").type(Party.Type.COMPANY).build()) .applicant1DefenceResponseDocument(ResponseDocument.builder() @@ -743,7 +781,7 @@ void shouldAssembleClaimantResponseDocuments2v1ProceedOne() { @SuppressWarnings("unchecked") List docs = (ArrayList) response.getData().get("claimantResponseDocuments"); - assertEquals(4, docs.size()); + assertEquals(8, docs.size()); assertThat(response.getData()) .extracting("claimantResponseDocuments") @@ -764,6 +802,7 @@ void shouldAssembleClaimantResponseDocuments2v1ProceedOne() { @Test void shouldAssembleClaimantResponseDocuments2v1NotProceed() { when(time.now()).thenReturn(LocalDateTime.of(2022, 2, 18, 12, 10, 55)); + when(featureToggleService.isCaseFileViewEnabled()).thenReturn(true); var caseData = CaseDataBuilder.builder().build().toBuilder() .respondent1(Party.builder().companyName("company").type(Party.Type.COMPANY).build()) .applicant1DefenceResponseDocument(ResponseDocument.builder() @@ -804,7 +843,7 @@ void shouldAssembleClaimantResponseDocuments2v1NotProceed() { @SuppressWarnings("unchecked") List docs = (ArrayList) response.getData().get("claimantResponseDocuments"); - assertEquals(4, docs.size()); + assertEquals(8, docs.size()); assertThat(response.getData()) .extracting("claimantResponseDocuments") @@ -825,6 +864,7 @@ void shouldAssembleClaimantResponseDocuments2v1NotProceed() { @Test void shouldAssembleClaimantResponseDocuments1v1Proceed() { when(time.now()).thenReturn(LocalDateTime.of(2022, 2, 18, 12, 10, 55)); + when(featureToggleService.isCaseFileViewEnabled()).thenReturn(true); var caseData = CaseDataBuilder.builder().build().toBuilder() .respondent1(Party.builder().companyName("company").type(Party.Type.COMPANY).build()) .applicant1DefenceResponseDocument(ResponseDocument.builder() @@ -858,7 +898,7 @@ void shouldAssembleClaimantResponseDocuments1v1Proceed() { @SuppressWarnings("unchecked") List docs = (ArrayList) response.getData().get("claimantResponseDocuments"); - assertEquals(3, docs.size()); + assertEquals(6, docs.size()); assertThat(response.getData()) .extracting("claimantResponseDocuments") @@ -878,6 +918,7 @@ void shouldAssembleClaimantResponseDocuments1v1Proceed() { @Test void shouldAssembleClaimantResponseDocuments1v1NotProceed() { when(time.now()).thenReturn(LocalDateTime.of(2022, 2, 18, 12, 10, 55)); + when(featureToggleService.isCaseFileViewEnabled()).thenReturn(true); var caseData = CaseDataBuilder.builder().build().toBuilder() .respondent1(Party.builder().companyName("company").type(Party.Type.COMPANY).build()) .applicant1DefenceResponseDocument(ResponseDocument.builder() @@ -911,7 +952,7 @@ void shouldAssembleClaimantResponseDocuments1v1NotProceed() { @SuppressWarnings("unchecked") List docs = (ArrayList) response.getData().get("claimantResponseDocuments"); - assertEquals(3, docs.size()); + assertEquals(6, docs.size()); assertThat(response.getData()) .extracting("claimantResponseDocuments") @@ -931,6 +972,7 @@ void shouldAssembleClaimantResponseDocuments1v1NotProceed() { @Test void shouldAssembleClaimantResponseDocuments1v2ssProceedBoth() { when(time.now()).thenReturn(LocalDateTime.of(2022, 2, 18, 12, 10, 55)); + when(featureToggleService.isCaseFileViewEnabled()).thenReturn(true); var caseData = CaseDataBuilder.builder().build().toBuilder() .respondent1(Party.builder().companyName("company").type(Party.Type.COMPANY).build()) .applicant1DefenceResponseDocument(ResponseDocument.builder() @@ -969,7 +1011,7 @@ void shouldAssembleClaimantResponseDocuments1v2ssProceedBoth() { @SuppressWarnings("unchecked") List docs = (ArrayList) response.getData().get("claimantResponseDocuments"); - assertEquals(3, docs.size()); + assertEquals(6, docs.size()); assertThat(response.getData()) .extracting("claimantResponseDocuments") @@ -989,6 +1031,7 @@ void shouldAssembleClaimantResponseDocuments1v2ssProceedBoth() { @Test void shouldAssembleClaimantResponseDocuments1v2ssProceedOne() { when(time.now()).thenReturn(LocalDateTime.of(2022, 2, 18, 12, 10, 55)); + when(featureToggleService.isCaseFileViewEnabled()).thenReturn(true); var caseData = CaseDataBuilder.builder().build().toBuilder() .respondent1(Party.builder().companyName("company").type(Party.Type.COMPANY).build()) .applicant1DefenceResponseDocument(ResponseDocument.builder() @@ -1027,7 +1070,7 @@ void shouldAssembleClaimantResponseDocuments1v2ssProceedOne() { @SuppressWarnings("unchecked") List docs = (ArrayList) response.getData().get("claimantResponseDocuments"); - assertEquals(3, docs.size()); + assertEquals(6, docs.size()); assertThat(response.getData()) .extracting("claimantResponseDocuments") @@ -1047,6 +1090,7 @@ void shouldAssembleClaimantResponseDocuments1v2ssProceedOne() { @Test void shouldAssembleClaimantResponseDocuments1v2ssNotProceed() { when(time.now()).thenReturn(LocalDateTime.of(2022, 2, 18, 12, 10, 55)); + when(featureToggleService.isCaseFileViewEnabled()).thenReturn(true); var caseData = CaseDataBuilder.builder().build().toBuilder() .respondent1(Party.builder().companyName("company").type(Party.Type.COMPANY).build()) .applicant1DefenceResponseDocument(ResponseDocument.builder() @@ -1085,7 +1129,7 @@ void shouldAssembleClaimantResponseDocuments1v2ssNotProceed() { @SuppressWarnings("unchecked") List docs = (ArrayList) response.getData().get("claimantResponseDocuments"); - assertEquals(3, docs.size()); + assertEquals(6, docs.size()); assertThat(response.getData()) .extracting("claimantResponseDocuments") @@ -1141,6 +1185,11 @@ void shouldAssignCategoryId_whenInvoked() { assertThat(updatedData.getClaimantResponseDocuments().get(0).getValue().getDocumentLink().getCategoryID()).isEqualTo("directionsQuestionnaire"); assertThat(updatedData.getClaimantResponseDocuments().get(1).getValue().getDocumentLink().getCategoryID()).isEqualTo("directionsQuestionnaire"); assertThat(updatedData.getClaimantResponseDocuments().get(2).getValue().getDocumentLink().getCategoryID()).isEqualTo("directionsQuestionnaire"); + assertThat(updatedData.getClaimantResponseDocuments().get(3).getValue().getDocumentLink().getCategoryID()).isEqualTo("directionsQuestionnaire"); + assertThat(updatedData.getClaimantResponseDocuments().get(4).getValue().getDocumentLink().getCategoryID()).isEqualTo("DQApplicant"); + assertThat(updatedData.getClaimantResponseDocuments().get(5).getValue().getDocumentLink().getCategoryID()).isEqualTo("DQApplicant"); + assertThat(updatedData.getClaimantResponseDocuments().get(6).getValue().getDocumentLink().getCategoryID()).isEqualTo("DQApplicant"); + assertThat(updatedData.getClaimantResponseDocuments().get(7).getValue().getDocumentLink().getCategoryID()).isEqualTo("DQApplicant"); } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceSpecCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceSpecCallbackHandlerTest.java index 2d3412f0f83..9b5371b1f9f 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceSpecCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/RespondToDefenceSpecCallbackHandlerTest.java @@ -18,6 +18,7 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; import uk.gov.hmcts.reform.ccd.client.model.SubmittedCallbackResponse; +import uk.gov.hmcts.reform.civil.bankholidays.WorkingDayIndicator; import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.callback.CallbackVersion; import uk.gov.hmcts.reform.civil.config.ExitSurveyConfiguration; @@ -68,6 +69,8 @@ import uk.gov.hmcts.reform.civil.service.PaymentDateService; import uk.gov.hmcts.reform.civil.service.Time; import uk.gov.hmcts.reform.civil.service.citizenui.RespondentMediationService; +import uk.gov.hmcts.reform.civil.service.citizenui.ResponseOneVOneShowTagService; +import uk.gov.hmcts.reform.civil.service.citizenui.responsedeadline.DeadlineExtensionCalculatorService; import uk.gov.hmcts.reform.civil.service.flowstate.FlowState; import uk.gov.hmcts.reform.civil.utils.CaseFlagsInitialiser; import uk.gov.hmcts.reform.civil.utils.CourtLocationUtils; @@ -91,6 +94,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; @@ -128,7 +132,8 @@ LocationHelper.class, LocationRefDataService.class, JudgementService.class, - PaymentDateService.class + PaymentDateService.class, + ResponseOneVOneShowTagService.class }) class RespondToDefenceSpecCallbackHandlerTest extends BaseCallbackHandlerTest { @@ -144,6 +149,9 @@ class RespondToDefenceSpecCallbackHandlerTest extends BaseCallbackHandlerTest { @Autowired private PaymentDateService paymentDateService; + @Autowired + private ResponseOneVOneShowTagService responseOneVOneShowTagService; + @MockBean private UnavailableDateValidator unavailableDateValidator; @@ -165,6 +173,10 @@ class RespondToDefenceSpecCallbackHandlerTest extends BaseCallbackHandlerTest { private RespondentMediationService respondentMediationService; @MockBean private DeadlinesCalculator deadlinesCalculator; + @MockBean + private WorkingDayIndicator workingDayIndicator; + @MockBean + private DeadlineExtensionCalculatorService deadlineCalculatorService; @Nested class AboutToStart { @@ -288,6 +300,30 @@ void shouldPopulateRespondent1AndRespondent2Docs_whenInvokedAndSystemGeneratedCo assertThat(response.getData()).extracting("respondent1GeneratedResponseDocument").isNotNull(); assertThat(response.getData()).extracting("respondent2GeneratedResponseDocument").isNotNull(); } + + @Test + void shouldPopulateResponse_whenInvokedAndSystemGeneratedContainsResponseDoc() { + // Given + when(featureToggleService.isPinInPostEnabled()).thenReturn(true); + var testDocument1 = CaseDocument.builder() + .documentName("response_sealed_form.pdf") + .documentType(SEALED_CLAIM) + .documentLink(Document.builder() + .documentUrl("test-respondent1Doc-url") + .documentFileName("response_sealed_form.pdf") + .documentBinaryUrl("binary-url") + .build()).build(); + List> documentList = new ArrayList<>(); + documentList.add(element(testDocument1)); + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .systemGeneratedCaseDocuments(documentList) + .build(); + // When + var params = callbackParamsOf(caseData, ABOUT_TO_START); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + //Then + assertThat(response.getData()).extracting("respondent1ClaimResponseDocumentSpec").isNotNull(); + } } @Nested @@ -966,6 +1002,7 @@ void shouldNullDocument_whenCaseFileEnabled() { // Then assertThat(response.getData()).extracting("respondent1GeneratedResponseDocument").isNull(); assertThat(response.getData()).extracting("respondent2GeneratedResponseDocument").isNull(); + assertThat(response.getData()).extracting("respondent1ClaimResponseDocumentSpec").isNull(); } @Test @@ -1054,6 +1091,7 @@ void shouldChangeCaseStateToJudicialReferral_ONE_V_TWO_ONE_REP() { .addRespondent2(YES) .respondentResponseIsSame(YES) .responseClaimTrack(FAST_CLAIM.name()) + .applicant1ProceedWithClaim(YES) .applicant1DQ(Applicant1DQ.builder().applicant1RespondToClaimExperts( ExpertDetails.builder().build()).build()) .respondent1(Party.builder().type(Party.Type.INDIVIDUAL).build()).build(); @@ -1074,6 +1112,7 @@ void shouldChangeCaseStateToJudicialReferral_ONE_V_TWO_TWO_REP() { .respondent2SameLegalRepresentative(NO) .addRespondent2(YES) .responseClaimTrack(FAST_CLAIM.name()) + .applicant1ProceedWithClaim(YES) .applicant1DQ(Applicant1DQ.builder().applicant1RespondToClaimExperts( ExpertDetails.builder().build()).build()) .respondent1(Party.builder().type(Party.Type.INDIVIDUAL).build()).build(); @@ -1330,7 +1369,9 @@ class SetUpPaymentDateToStringField { void shouldSetUpPaymentDateToString() { when(featureToggleService.isPinInPostEnabled()).thenReturn(true); - LocalDate whenWillPay = LocalDate.now().plusDays(5); + given(workingDayIndicator.isWorkingDay(any())).willReturn(true); + LocalDate whenWillPay = LocalDate.now(); + given(deadlineCalculatorService.calculateExtendedDeadline(any(), anyInt())).willReturn(whenWillPay); RespondToClaimAdmitPartLRspec respondToClaimAdmitPartLRspec = RespondToClaimAdmitPartLRspec.builder() @@ -1358,6 +1399,7 @@ void shouldSetUpPaymentDateToStringForPartAdmitPaid() { when(featureToggleService.isPinInPostEnabled()).thenReturn(true); LocalDate whenWillPay = LocalDate.now().plusDays(5); + given(deadlineCalculatorService.calculateExtendedDeadline(any(), anyInt())).willReturn(whenWillPay); RespondToClaim respondToAdmittedClaim = RespondToClaim.builder() @@ -1385,7 +1427,9 @@ void shouldSetUpPaymentDateToStringForPartAdmitPaid() { void shouldSetUpPaymentDateForResponseDateToString() { when(featureToggleService.isPinInPostEnabled()).thenReturn(true); - LocalDate whenWillPay = LocalDate.now().plusDays(5); + given(workingDayIndicator.isWorkingDay(any())).willReturn(true); + LocalDate whenWillPay = LocalDate.now(); + given(deadlineCalculatorService.calculateExtendedDeadline(any(), anyInt())).willReturn(whenWillPay); CaseData caseData = CaseData.builder() .respondent1ResponseDate(LocalDateTime.now()) diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/SetAsideJudgmentCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/SetAsideJudgmentCallbackHandlerTest.java new file mode 100644 index 00000000000..1e3f1fe8b55 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/SetAsideJudgmentCallbackHandlerTest.java @@ -0,0 +1,117 @@ +package uk.gov.hmcts.reform.civil.handler.callback.user; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.SubmittedCallbackResponse; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CallbackType; +import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; + +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.SET_ASIDE_JUDGMENT; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = { + SetAsideJudgmentCallbackHandler.class, + JacksonAutoConfiguration.class +}) +class SetAsideJudgmentCallbackHandlerTest extends BaseCallbackHandlerTest { + + @Autowired + private SetAsideJudgmentCallbackHandler handler; + + @Autowired + private ObjectMapper objectMapper; + + @Test + void handleEventsReturnsTheExpectedCallbackEvents() { + assertThat(handler.handledEvents()).containsOnly(SET_ASIDE_JUDGMENT); + } + + @Nested + class AboutToSubmitCallback { + @Test + void shouldPopulateSetAsideOrderDate() { + //Given : Casedata in All_FINAL_ORDERS_ISSUED State + CaseData caseData = CaseDataBuilder.builder().buildJudmentOnlineCaseDataWithPaymentByInstalment(); + caseData.setJoSetAsideDate(LocalDate.of(2022, 12, 12)); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + + //When: handler is called with ABOUT_TO_SUBMIT event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + //Then: setAsideDate should be set correctly + assertThat(response.getData()).containsEntry("joSetAsideDate", "2022-12-12"); + } + } + + @Nested + class MidCallback { + @Test + void shouldValidateSetAsideDate() { + + CaseData caseData = CaseDataBuilder.builder().buildJudmentOnlineCaseDataWithPaymentByInstalment(); + caseData.setJoSetAsideDate(LocalDate.now().plusDays(5)); + + CallbackParams params = callbackParamsOf(caseData, MID, "validate-setAside-date"); + //When: handler is called with MID event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors()).contains("Date must be in the past"); + } + + @Test + void shouldValidatePaymentPaidByDate() { + + CaseData caseData = CaseDataBuilder.builder().buildJudmentOnlineCaseDataWithPaymentByDate(); + caseData.setJoSetAsideDate(LocalDate.now().minusDays(5)); + + CallbackParams params = callbackParamsOf(caseData, MID, "validate-setAside-date"); + //When: handler is called with MID event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors()).isEmpty(); + } + + @Test + void shouldValidateOrderDate() { + + CaseData caseData = CaseDataBuilder.builder().buildJudmentOnlineCaseDataWithPaymentByInstalment(); + caseData.setJoSetAsideDate(LocalDate.now()); + + CallbackParams params = callbackParamsOf(caseData, MID, "validate-setAside-date"); + //When: handler is called with MID event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors()).isEmpty(); + } + } + + @Nested + class SubmittedCallback { + @Test + public void whenSubmitted_thenIncludeHeader() { + CaseData caseData = CaseDataBuilder.builder().buildJudmentOnlineCaseDataWithPaymentByInstalment(); + CallbackParams params = CallbackParams.builder() + .caseData(caseData) + .type(CallbackType.SUBMITTED) + .build(); + SubmittedCallbackResponse response = + (SubmittedCallbackResponse) handler.handle(params); + Assertions.assertTrue(response.getConfirmationHeader().contains("# Judgment set aside")); + Assertions.assertTrue(response.getConfirmationBody().contains("The judgment has been set aside")); + } + } + +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/StandardDirectionOrderDJTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/StandardDirectionOrderDJTest.java index 5d43f8c81f8..3fea6f64824 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/StandardDirectionOrderDJTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/StandardDirectionOrderDJTest.java @@ -5,6 +5,8 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -17,6 +19,7 @@ import uk.gov.hmcts.reform.civil.crd.model.Category; import uk.gov.hmcts.reform.civil.crd.model.CategorySearchResult; import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.helpers.LocationHelper; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.common.DynamicList; import uk.gov.hmcts.reform.civil.model.common.DynamicListElement; @@ -48,6 +51,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; @@ -56,6 +61,7 @@ import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; import static uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType.ACKNOWLEDGEMENT_OF_CLAIM; import static uk.gov.hmcts.reform.civil.enums.CaseCategory.UNSPEC_CLAIM; +import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.element; @@ -64,7 +70,8 @@ DefaultJudgmentOrderFormGenerator.class, StandardDirectionOrderDJ.class, JacksonAutoConfiguration.class, - AssignCategoryId.class + AssignCategoryId.class, + LocationHelper.class }) public class StandardDirectionOrderDJTest extends BaseCallbackHandlerTest { @@ -542,6 +549,44 @@ void shouldPrePopulateDJTrialHearingToggle() { var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); assertThat(response.getData()).extracting("trialHearingVariationsDirectionsDJToggle").isNotNull(); + assertThat(response.getData()).extracting("trialHearingVariationsDirectionsDJToggle").isNotNull(); + } + + @Test + void shouldPopulateLocationListsWithPreselectedCourt() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimDraft() + .atStateClaimIssuedTrialHearing() + .build(); + + String preSelectedCourt = "214320"; + + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + List locations = List.of( + LocationRefData.builder().epimmsId("00001").courtLocationCode("00001") + .siteName("court 1").courtAddress("1 address").postcode("Y01 7RB").build(), + LocationRefData.builder().epimmsId(preSelectedCourt).courtLocationCode(preSelectedCourt) + .siteName("court 2").courtAddress("2 address").postcode("Y02 7RB").build(), + LocationRefData.builder().epimmsId("00003").courtLocationCode("00003") + .siteName("court 3").courtAddress("3 address").postcode("Y03 7RB").build() + ); + + when(locationRefDataService.getCourtLocationsForDefaultJudgments(anyString())).thenReturn(locations); + + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + CaseData responseCaseData = mapper.convertValue(response.getData(), CaseData.class); + DynamicList expected = DynamicList.builder() + .listItems(List.of( + DynamicListElement.builder().code("00001").label("court 1 - 1 address - Y01 7RB").build(), + DynamicListElement.builder().code(preSelectedCourt).label("court 2 - 2 address - Y02 7RB").build(), + DynamicListElement.builder().code("00003").label("court 3 - 3 address - Y03 7RB").build() + ) + ) + .value(DynamicListElement.builder().code(preSelectedCourt).label("court 2 - 2 address - Y02 7RB").build()) + .build(); + + assertThat(responseCaseData.getTrialHearingMethodInPersonDJ()).isEqualTo(expected); + assertThat(responseCaseData.getDisposalHearingMethodInPersonDJ()).isEqualTo(expected); } @Test @@ -589,6 +634,20 @@ private DynamicList getHearingMethodValuesTrialHearingDJ(AboutToStartOrSubmitCal class MidEventCreateOrderCallback { private static final String PAGE_ID = "create-order"; + @Test + void shouldThrowErrorWhenEnteringNegativeNumberOfWitness() { + CaseData caseData = CaseDataBuilder.builder() + .atTrialHearingWitnessOfFactWithNegativeInputs() + .build() + .toBuilder() + .build(); + + CallbackParams params = callbackParamsOf(caseData, MID, PAGE_ID); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors().get(0)).isEqualTo("The number entered cannot be less than zero"); + } + @Test void shouldCreateAndSaveSDOOrder_whenStateClaimIssuedTrialSDOInPersonHearing() { CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft() @@ -677,54 +736,24 @@ void shouldCreateAndSaveSDOOrder_whenStateClaimIssuedDisposalSDOVideoCall() { @Nested class AboutToSubmitCallback { - @Test - void shouldFinishBusinessProcess() { - CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build(); - CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); - var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); - assertThat(response.getData()).extracting("businessProcess").isNotNull(); - } - @Test - void shouldReturnCaseManagementListFromTrialHearing() { - List temporaryLocationList = List.of( - DynamicListElement.builder().label("Loc 1").build()); - CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build() - .toBuilder().trialHearingMethodInPersonDJ(DynamicList.builder().listItems(temporaryLocationList) - .value(DynamicListElement.builder().label("Loc - 1 - 1") - .build()).build()).build(); - List locations = new ArrayList<>(); - locations.add(LocationRefData.builder().siteName("Loc").courtAddress("1").postcode("1") - .courtName("Court Name").region("Region").regionId("1").courtVenueId("000") - .epimmsId("123").build()); - when(locationRefDataService.getCourtLocationsForDefaultJudgments(any())).thenReturn(locations); - CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); - var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); - assertThat(response.getData()).extracting("caseManagementLocation").extracting("region") - .isEqualTo(locations.get(0).getRegionId()); - assertThat(response.getData()).extracting("caseManagementLocation").extracting("baseLocation") - .isEqualTo(locations.get(0).getEpimmsId()); + @BeforeEach + void setup() { + given(featureToggleService.isEarlyAdoptersEnabled()).willReturn(true); } @Test - void shouldReturnCaseManagementListFromDisposalHearing() { - List temporaryLocationList = List.of( - DynamicListElement.builder().label("Loc 1").build()); + void shouldFinishBusinessProcess() { + List items = List.of("label 1", "label 2", "label 3"); + DynamicList options = DynamicList.fromList(items, Object::toString, Object::toString, items.get(0), false); CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build() - .toBuilder().disposalHearingMethodInPersonDJ(DynamicList.builder().listItems(temporaryLocationList) - .value(DynamicListElement.builder().label("Loc - 1 - 1") - .build()).build()).build(); - List locations = new ArrayList<>(); - locations.add(LocationRefData.builder().siteName("Loc").courtAddress("1").postcode("1") - .courtName("Court Name").region("Region").regionId("1").courtVenueId("000") - .epimmsId("123").build()); - when(locationRefDataService.getCourtLocationsForDefaultJudgments(any())).thenReturn(locations); + .toBuilder() + .disposalHearingMethodInPersonDJ(options) + .trialHearingMethodInPersonDJ(options) + .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); - assertThat(response.getData()).extracting("caseManagementLocation").extracting("region") - .isEqualTo(locations.get(0).getRegionId()); - assertThat(response.getData()).extracting("caseManagementLocation").extracting("baseLocation") - .isEqualTo(locations.get(0).getEpimmsId()); + assertThat(response.getData()).extracting("businessProcess").isNotNull(); } @Test @@ -743,9 +772,13 @@ void shouldAssignCategoryId_whenInvoked() { .build(); List> documentList = new ArrayList<>(); documentList.add(element(testDocument)); + List items = List.of("label 1", "label 2", "label 3"); + DynamicList options = DynamicList.fromList(items, Object::toString, items.get(0), false); //Given when(featureToggleService.isCaseFileViewEnabled()).thenReturn(true); CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build().toBuilder() + .trialHearingMethodInPersonDJ(options) + .disposalHearingMethodInPersonDJ(options) .orderSDODocumentDJCollection(documentList) .build(); @@ -756,6 +789,88 @@ void shouldAssignCategoryId_whenInvoked() { //Then assertThat(updatedData.getOrderSDODocumentDJCollection().get(0).getValue().getDocumentLink().getCategoryID()).isEqualTo("sdo"); } + + @ParameterizedTest + @CsvSource({"true", "false"}) + void shouldPopulateEarlyAdoptersFlag_whenDisposalHearingMethodInPersonDJIsSet(Boolean isLocationWhiteListed) { + DynamicList options = DynamicList.builder() + .listItems(List.of( + DynamicListElement.builder().code("00001").label("court 1 - 1 address - Y01 7RB").build(), + DynamicListElement.builder().code("00002").label("court 2 - 2 address - Y02 7RB").build(), + DynamicListElement.builder().code("00003").label("court 3 - 3 address - Y03 7RB").build() + ) + ) + .value(DynamicListElement.builder().code("00002").label("court 2 - 2 address - Y02 7RB").build()) + .build(); + + CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build() + .toBuilder() + .disposalHearingMethodInPersonDJ(options) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + when(featureToggleService.isLocationWhiteListedForCaseProgression(eq(options.getValue().getCode()))).thenReturn( + isLocationWhiteListed); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + CaseData responseCaseData = mapper.convertValue(response.getData(), CaseData.class); + + assertThat(responseCaseData.getEaCourtLocation()).isEqualTo(isLocationWhiteListed ? YES : NO); + } + + @Test + void shouldNotPopulateEarlyAdoptersFlag_whenEarlyAdoptersToggleIsOff() { + DynamicList options = DynamicList.builder() + .listItems(List.of( + DynamicListElement.builder().code("00001").label("court 1 - 1 address - Y01 7RB").build(), + DynamicListElement.builder().code("00002").label("court 2 - 2 address - Y02 7RB").build(), + DynamicListElement.builder().code("00003").label("court 3 - 3 address - Y03 7RB").build() + ) + ) + .value(DynamicListElement.builder().code("00002").label("court 2 - 2 address - Y02 7RB").build()) + .build(); + + CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build() + .toBuilder() + .disposalHearingMethodInPersonDJ(options) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + when(featureToggleService.isEarlyAdoptersEnabled()).thenReturn(false); + when(featureToggleService.isLocationWhiteListedForCaseProgression(eq(options.getValue().getCode()))) + .thenReturn(true); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + CaseData responseCaseData = mapper.convertValue(response.getData(), CaseData.class); + + assertThat(responseCaseData.getEaCourtLocation()).isNull(); + } + } + + @ParameterizedTest + @CsvSource({"true", "false"}) + void shouldPopulateEarlyAdoptersFlag_whenTrialHearingMethodInPersonDJIsSet(Boolean isLocationWhiteListed) { + DynamicList options = DynamicList.builder() + .listItems(List.of( + DynamicListElement.builder().code("00001").label("court 1 - 1 address - Y01 7RB").build(), + DynamicListElement.builder().code("00002").label("court 2 - 2 address - Y02 7RB").build(), + DynamicListElement.builder().code("00003").label("court 3 - 3 address - Y03 7RB").build() + ) + ) + .value(DynamicListElement.builder().code("00002").label("court 2 - 2 address - Y02 7RB").build()) + .build(); + + CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build() + .toBuilder() + .trialHearingMethodInPersonDJ(options) + .build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + when(featureToggleService.isEarlyAdoptersEnabled()).thenReturn(true); + when(featureToggleService.isLocationWhiteListedForCaseProgression(eq(options.getValue().getCode()))).thenReturn( + isLocationWhiteListed); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + CaseData responseCaseData = mapper.convertValue(response.getData(), CaseData.class); + + assertThat(responseCaseData.getEaCourtLocation()).isEqualTo(isLocationWhiteListed ? YES : NO); } @Nested diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/TransferOnlineCaseCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/TransferOnlineCaseCallbackHandlerTest.java new file mode 100644 index 00000000000..b68d54ff9e8 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/TransferOnlineCaseCallbackHandlerTest.java @@ -0,0 +1,231 @@ +package uk.gov.hmcts.reform.civil.handler.callback.user; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.ccd.client.model.SubmittedCallbackResponse; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.callback.CaseEvent; +import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.common.DynamicList; +import uk.gov.hmcts.reform.civil.model.common.DynamicListElement; +import uk.gov.hmcts.reform.civil.model.defaultjudgment.CaseLocationCivil; +import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; +import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; +import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; +import uk.gov.hmcts.reform.civil.sampledata.LocationRefSampleDataBuilder; +import uk.gov.hmcts.reform.civil.utils.CourtLocationUtils; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.MID; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.SUBMITTED; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = { + TransferOnlineCaseCallbackHandler.class, + JacksonAutoConfiguration.class}) +class TransferOnlineCaseCallbackHandlerTest extends BaseCallbackHandlerTest { + + private static final String CONFIRMATION_HEADER = "# Case transferred to new location"; + + @Autowired + private TransferOnlineCaseCallbackHandler handler; + + @MockBean + protected LocationRefDataService locationRefDataService; + @MockBean + protected CourtLocationUtils courtLocationUtils; + + @Nested + class AboutToStartCallback extends LocationRefSampleDataBuilder { + + @BeforeEach + void setup() { + given(locationRefDataService.getCourtLocationsForDefaultJudgments(any())) + .willReturn(getSampleCourLocationsRefObject()); + } + + @Test + void shouldReturnLocationDataWhenAboutToStartCalled() { + CaseData caseData = CaseDataBuilder.builder().atStateApplicantRespondToDefenceAndProceed().build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_START); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getData()) + .extracting("transferCourtLocationList") + .extracting("list_items") + .asList().hasSize(3); + } + } + + @Nested + class MidCallback extends LocationRefSampleDataBuilder { + + @BeforeEach + void setup() { + given(locationRefDataService.getCourtLocationsForDefaultJudgments(any())) + .willReturn(getSampleCourLocationsRefObject()); + } + + @Test + void shouldGiveErrorIfSameCourtLocationSelected() { + + CaseData caseData = CaseDataBuilder.builder().atStateApplicantRespondToDefenceAndProceed() + .caseManagementLocation(CaseLocationCivil.builder() + .region("2") + .baseLocation("111") + .build()) + .transferCourtLocationList(DynamicList.builder().value(DynamicListElement.builder() + .label("Site 1 - Adr 1 - AAA 111").build()).build()).build(); + given(courtLocationUtils.findPreferredLocationData(any(), any())) + .willReturn(LocationRefData.builder().siteName("") + .epimmsId("111") + .siteName("Site 1").courtAddress("Adr 1").postcode("AAA 111") + .courtLocationCode("court1").build()); + + CallbackParams params = callbackParamsOf(caseData, MID, "validate-court-location"); + //When: handler is called with MID event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors()).contains("Select a different hearing court location to transfer!"); + } + + @Test + void shouldGiveErrorIfNoCourtLocationSelected() { + + CaseData caseData = CaseDataBuilder.builder().atStateApplicantRespondToDefenceAndProceed() + .transferCourtLocationList(DynamicList.builder().value(DynamicListElement.builder() + .label("Site 1 - Adr 1 - AAA 111").build()).build()).build(); + given(courtLocationUtils.findPreferredLocationData(any(), any())) + .willReturn(LocationRefData.builder().siteName("") + .epimmsId("111") + .siteName("Site 1").courtAddress("Adr 1").postcode("AAA 111") + .courtLocationCode("court1").build()); + + CallbackParams params = callbackParamsOf(caseData, MID, "validate-court-location"); + //When: handler is called with MID event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors()).isEmpty(); + } + + @Test + void shouldNotGiveErrorIfDifferentCourtLocationSelected() { + + CaseData caseData = CaseDataBuilder.builder().atStateApplicantRespondToDefenceAndProceed() + .caseManagementLocation(CaseLocationCivil.builder() + .region("2") + .baseLocation("111") + .build()) + .transferCourtLocationList(DynamicList.builder().value(DynamicListElement.builder() + .label("Site 1 - Adr 1 - AAA 111").build()).build()).build(); + + given(courtLocationUtils.findPreferredLocationData(any(), any())) + .willReturn(LocationRefData.builder().siteName("") + .epimmsId("111") + .siteName("Site 1").courtAddress("Adr 1").postcode("AAA 111") + .courtLocationCode("other code").build()); + CallbackParams params = callbackParamsOf(caseData, MID, "validate-court-location"); + //When: handler is called with MID event + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors()).isEmpty(); + } + } + + @Nested + class AboutToSubmitCallback { + @Test + void shouldPopulateCorrectCaseDataWhenSubmitted() { + CaseData caseData = CaseDataBuilder.builder().atStateApplicantRespondToDefenceAndProceed() + .caseManagementLocation(CaseLocationCivil.builder() + .region("2") + .baseLocation("111") + .build()) + .reasonForTransfer("Reason") + .transferCourtLocationList(DynamicList.builder().value(DynamicListElement.builder() + .label("Site 1 - Adr 1 - AAA 111").build()).build()).build(); + given(courtLocationUtils.findPreferredLocationData(any(), any())) + .willReturn(LocationRefData.builder().siteName("") + .epimmsId("222") + .siteName("Site 2").courtAddress("Adr 2").postcode("BBB 222") + .courtLocationCode("other code").build()); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getData()) + .extracting("reasonForTransfer") + .isEqualTo("Reason"); + assertThat(response.getData()) + .extracting("transferCourtLocationList") + .extracting("value") + .extracting("label") + .isEqualTo("Site 1 - Adr 1 - AAA 111"); + assertThat(response.getData()) + .extracting("transferCourtLocationList") + .extracting("list_items") + .isNull(); + assertThat(response.getData()) + .extracting("caseManagementLocation") + .extracting("baseLocation") + .isEqualTo("222"); + } + + @Test + void shouldPopulateCorrectCaseDataWhenSubmittedAndNoNewCourtLocation() { + CaseData caseData = CaseDataBuilder.builder().atStateApplicantRespondToDefenceAndProceed() + .caseManagementLocation(CaseLocationCivil.builder() + .region("2") + .baseLocation("111") + .build()) + .transferCourtLocationList(DynamicList.builder().value(DynamicListElement.builder() + .label("Site 1 - Adr 1 - AAA 111").build()).build()).build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getData()) + .extracting("caseManagementLocation") + .extracting("baseLocation") + .isEqualTo("111"); + } + } + + @Nested + class SubmittedCallback { + @Test + void shouldReturnExpectedSubmittedCallbackResponse() { + String newCourtLocationSiteName = "Site 2"; + CaseData caseData = CaseDataBuilder.builder().atStateApplicantRespondToDefenceAndProceed().build(); + given(courtLocationUtils.findPreferredLocationData(any(), any())) + .willReturn(LocationRefData.builder().siteName("") + .epimmsId("222") + .siteName(newCourtLocationSiteName).courtAddress("Adr 2").postcode("BBB 222") + .courtLocationCode("other code").build()); + + CallbackParams params = callbackParamsOf(caseData, SUBMITTED); + SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); + + String body = "

    What happens next

    " + + "The case has now been transferred to " + + newCourtLocationSiteName + + ". If the case has moved out of your region, you will no longer see it.

    "; + + assertThat(response).usingRecursiveComparison().isEqualTo( + SubmittedCallbackResponse.builder() + .confirmationHeader(CONFIRMATION_HEADER) + .confirmationBody(body) + .build()); + } + } + + @Test + void handleEventsReturnsTheExpectedCallbackEvent() { + assertThat(handler.handledEvents()).contains(CaseEvent.TRANSFER_ONLINE_CASE); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/TrialReadinessCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/TrialReadinessCallbackHandlerTest.java index 081252021e1..66dbe5568ee 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/TrialReadinessCallbackHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/TrialReadinessCallbackHandlerTest.java @@ -1,6 +1,5 @@ package uk.gov.hmcts.reform.civil.handler.callback.user; -import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -24,10 +23,10 @@ import uk.gov.hmcts.reform.idam.client.models.UserInfo; import java.time.LocalDate; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_START; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; @@ -38,6 +37,7 @@ TrialReadinessCallbackHandler.class, JacksonAutoConfiguration.class }) + public class TrialReadinessCallbackHandlerTest extends BaseCallbackHandlerTest { @Autowired @@ -61,27 +61,40 @@ public class TrialReadinessCallbackHandlerTest extends BaseCallbackHandlerTest { + "If you want the date of the hearing to be changed (or any other order to make the case ready for trial)" + "you will need to make an application to the court and pay the appropriate fee."; - @BeforeEach - public void setup() { - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - } - @Nested class AboutToStartCallback { + @BeforeEach + public void setup() { + when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + } + @Test void shouldNotReturnError_WhenAboutToStartIsInvoked_ApplicantSolicitor() { //given: applicant solicitor logs in more than 3 weeks before hearing CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build(); CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_START, caseData).build(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.APPLICANTSOLICITORONE))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.APPLICANTSOLICITORONE.getFormattedName())); //when: Event is started AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler .handle(params); + //then: no error is given + assertThat(response.getErrors()).isEmpty(); + } + @Test + void shouldNotReturnError_WhenAboutToStartIsInvoked_Claimant() { + //given: claimant logs in more than 3 weeks before hearing + CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_START, caseData).build(); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.CLAIMANT.getFormattedName())); + + //when: Event is started + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); //then: no error is given assertThat(response.getErrors()).isEmpty(); } @@ -91,14 +104,27 @@ void shouldNotReturnError_WhenAboutToStartIsInvoked_RespondentSolicitor1() { //given: respondent 1 solicitor logs in more than 3 weeks before hearing CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build(); CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_START, caseData).build(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.RESPONDENTSOLICITORONE))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.RESPONDENTSOLICITORONE.getFormattedName())); //when: Event is started AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler .handle(params); + //then: no error is given + assertThat(response.getErrors()).isEmpty(); + } + + @Test + void shouldNotReturnError_WhenAboutToStartIsInvoked_Defendant() { + //given: defendant logs in more than 3 weeks before hearing + CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_START, caseData).build(); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.DEFENDANT.getFormattedName())); + //when: Event is started + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); //then: no error is given assertThat(response.getErrors()).isEmpty(); } @@ -108,14 +134,12 @@ void shouldNotReturnError_WhenAboutToStartIsInvoked_RespondentSolicitor2() { //given: respondent 2 solicitor logs in more than 3 weeks before hearing CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build(); CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_START, caseData).build(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.RESPONDENTSOLICITORTWO))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.RESPONDENTSOLICITORTWO.getFormattedName())); //when: Event is started AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler .handle(params); - //then: no error is given assertThat(response.getErrors()).isEmpty(); } @@ -126,14 +150,28 @@ void shouldReturnError_WhenAboutToStartIsInvokedWithinThreeWeeksOfHearingDate_Ap CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck() .hearingDate(LocalDate.now().plusWeeks(2).plusDays(6)).build(); CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_START, caseData).build(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.APPLICANTSOLICITORONE))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.APPLICANTSOLICITORONE.getFormattedName())); //when: Event is started AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler .handle(params); + //then: an error is returned + assertThat(response.getErrors()).isNotEmpty(); + } + @Test + void shouldReturnError_WhenAboutToStartIsInvokedWithinThreeWeeksOfHearingDate_Claimant() { + //given: claimant logs in less than 3 weeks before the hearing + CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck() + .hearingDate(LocalDate.now().plusWeeks(2).plusDays(6)).build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_START, caseData).build(); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.CLAIMANT.getFormattedName())); + + //when: Event is started + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); //then: an error is returned assertThat(response.getErrors()).isNotEmpty(); } @@ -144,14 +182,28 @@ void shouldReturnError_WhenAboutToStartIsInvokedWithinThreeWeeksOfHearingDate_Re CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck() .hearingDate(LocalDate.now().plusWeeks(2).plusDays(6)).build(); CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_START, caseData).build(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.RESPONDENTSOLICITORONE))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.RESPONDENTSOLICITORONE.getFormattedName())); //when: Event is started AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler .handle(params); + //then: an error is returned + assertThat(response.getErrors()).isNotEmpty(); + } + @Test + void shouldReturnError_WhenAboutToStartIsInvokedWithinThreeWeeksOfHearingDate_Defendant() { + //given: respondent 1 solicitor logs in less than 3 weeks before the hearing + CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck() + .hearingDate(LocalDate.now().plusWeeks(2).plusDays(6)).build(); + CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_START, caseData).build(); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.DEFENDANT.getFormattedName())); + + //when: Event is started + AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler + .handle(params); //then: an error is returned assertThat(response.getErrors()).isNotEmpty(); } @@ -162,14 +214,12 @@ void shouldReturnError_WhenAboutToStartIsInvokedWithinThreeWeeksOfHearingDate_Re CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck() .hearingDate(LocalDate.now().plusWeeks(2).plusDays(6)).build(); CallbackParams params = CallbackParamsBuilder.builder().of(ABOUT_TO_START, caseData).build(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.RESPONDENTSOLICITORTWO))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.RESPONDENTSOLICITORTWO.getFormattedName())); //when: Event is started AboutToStartOrSubmitCallbackResponse response = (AboutToStartOrSubmitCallbackResponse) handler .handle(params); - //then: an error is returned assertThat(response.getErrors()).isNotEmpty(); } @@ -178,14 +228,18 @@ void shouldReturnError_WhenAboutToStartIsInvokedWithinThreeWeeksOfHearingDate_Re @Nested class AboutToSubmitCallback { + @BeforeEach + public void setup() { + when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + } + @Test void shouldTriggerApplicantNotifyOthers_WhenAboutToSubmitIsInvoked_ApplicantSolicitor() { CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build().toBuilder() .trialReadyApplicant(YesOrNo.YES).build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.APPLICANTSOLICITORONE))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.APPLICANTSOLICITORONE.getFormattedName())); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -193,7 +247,22 @@ void shouldTriggerApplicantNotifyOthers_WhenAboutToSubmitIsInvoked_ApplicantSoli assertThat(response.getData()).extracting("businessProcess") .extracting("camundaEvent", "status") .containsOnly(CaseEvent.APPLICANT_TRIAL_READY_NOTIFY_OTHERS.name(), "READY"); + } + + @Test + void shouldTriggerApplicantNotifyOthers_WhenAboutToSubmitIsInvoked_Claimant() { + CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build().toBuilder() + .trialReadyApplicant(YesOrNo.YES).build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.CLAIMANT.getFormattedName())); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors()).isNull(); + assertThat(response.getData()).extracting("businessProcess") + .extracting("camundaEvent", "status") + .containsOnly(CaseEvent.APPLICANT_TRIAL_READY_NOTIFY_OTHERS.name(), "READY"); } @Test @@ -201,11 +270,8 @@ void shouldTriggerRespondent1NotifyOthers_WhenAboutToSubmitIsInvoked_Respondent1 CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build().toBuilder() .trialReadyRespondent1(YesOrNo.YES).build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); - ObjectMapper objectmapper = new ObjectMapper(); - CaseData.CaseDataBuilder updatedData = caseData.toBuilder(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.RESPONDENTSOLICITORONE))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.RESPONDENTSOLICITORONE.getFormattedName())); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -213,7 +279,22 @@ void shouldTriggerRespondent1NotifyOthers_WhenAboutToSubmitIsInvoked_Respondent1 assertThat(response.getData()).extracting("businessProcess") .extracting("camundaEvent", "status") .containsOnly(CaseEvent.RESPONDENT1_TRIAL_READY_NOTIFY_OTHERS.name(), "READY"); + } + + @Test + void shouldTriggerRespondent1NotifyOthers_WhenAboutToSubmitIsInvoked_Defendant() { + CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build().toBuilder() + .trialReadyRespondent1(YesOrNo.YES).build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.DEFENDANT.getFormattedName())); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getErrors()).isNull(); + assertThat(response.getData()).extracting("businessProcess") + .extracting("camundaEvent", "status") + .containsOnly(CaseEvent.RESPONDENT1_TRIAL_READY_NOTIFY_OTHERS.name(), "READY"); } @Test @@ -221,11 +302,8 @@ void shouldTriggerRespondent2NotifyOthers_WhenAboutToSubmitIsInvoked_Respondent2 CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build().toBuilder() .trialReadyRespondent2(YesOrNo.YES).build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); - ObjectMapper objectmapper = new ObjectMapper(); - CaseData.CaseDataBuilder updatedData = caseData.toBuilder(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.RESPONDENTSOLICITORTWO))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.RESPONDENTSOLICITORTWO.getFormattedName())); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -240,9 +318,8 @@ void shouldTriggerApplicantDocument_WhenAboutToSubmitIsInvoked_ApplicantSolicito CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build().toBuilder() .trialReadyApplicant(YesOrNo.NO).build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.APPLICANTSOLICITORONE))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.APPLICANTSOLICITORONE.getFormattedName())); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -250,7 +327,22 @@ void shouldTriggerApplicantDocument_WhenAboutToSubmitIsInvoked_ApplicantSolicito assertThat(response.getData()).extracting("businessProcess") .extracting("camundaEvent", "status") .containsOnly(CaseEvent.GENERATE_TRIAL_READY_DOCUMENT_APPLICANT.name(), "READY"); + } + @Test + void shouldTriggerApplicantDocument_WhenAboutToSubmitIsInvoked_Claimant() { + CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build().toBuilder() + .trialReadyApplicant(YesOrNo.NO).build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.CLAIMANT.getFormattedName())); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getErrors()).isNull(); + assertThat(response.getData()).extracting("businessProcess") + .extracting("camundaEvent", "status") + .containsOnly(CaseEvent.GENERATE_TRIAL_READY_DOCUMENT_APPLICANT.name(), "READY"); } @Test @@ -258,11 +350,8 @@ void shouldTriggerRespondent1Document_WhenAboutToSubmitIsInvoked_Respondent1Soli CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build().toBuilder() .trialReadyRespondent1(YesOrNo.NO).build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); - ObjectMapper objectmapper = new ObjectMapper(); - CaseData.CaseDataBuilder updatedData = caseData.toBuilder(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.RESPONDENTSOLICITORONE))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.RESPONDENTSOLICITORONE.getFormattedName())); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -270,7 +359,22 @@ void shouldTriggerRespondent1Document_WhenAboutToSubmitIsInvoked_Respondent1Soli assertThat(response.getData()).extracting("businessProcess") .extracting("camundaEvent", "status") .containsOnly(CaseEvent.GENERATE_TRIAL_READY_DOCUMENT_RESPONDENT1.name(), "READY"); + } + @Test + void shouldTriggerRespondent1Document_WhenAboutToSubmitIsInvoked_Defendant() { + CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build().toBuilder() + .trialReadyRespondent1(YesOrNo.NO).build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.DEFENDANT.getFormattedName())); + + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + + assertThat(response.getErrors()).isNull(); + assertThat(response.getData()).extracting("businessProcess") + .extracting("camundaEvent", "status") + .containsOnly(CaseEvent.GENERATE_TRIAL_READY_DOCUMENT_RESPONDENT1.name(), "READY"); } @Test @@ -278,11 +382,8 @@ void shouldTriggerRespondent2Document_WhenAboutToSubmitIsInvoked_Respondent2Soli CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyCheck().build().toBuilder() .trialReadyRespondent2(YesOrNo.NO).build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); - ObjectMapper objectmapper = new ObjectMapper(); - CaseData.CaseDataBuilder updatedData = caseData.toBuilder(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.RESPONDENTSOLICITORTWO))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.RESPONDENTSOLICITORTWO.getFormattedName())); var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); @@ -296,18 +397,40 @@ void shouldTriggerRespondent2Document_WhenAboutToSubmitIsInvoked_Respondent2Soli @Nested class SubmittedCallback { + @BeforeEach + public void setup() { + when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); + } + @Test void shouldReturnConfirmationScreen_when1v1ReadySubmitted_ApplicantSolicitor() { //given: applicant solicitor selects Ready CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyApplicant().build(); CallbackParams params = CallbackParamsBuilder.builder().of(SUBMITTED, caseData).build(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.APPLICANTSOLICITORONE))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.APPLICANTSOLICITORONE.getFormattedName())); //when: Event is submitted SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); + //then: header + body for the ready status get used in the confirmation + assertThat(response).usingRecursiveComparison().isEqualTo( + SubmittedCallbackResponse.builder() + .confirmationHeader(READY_HEADER) + .confirmationBody(READY_BODY) + .build() + ); + } + + @Test + void shouldReturnConfirmationScreen_when1v1ReadySubmitted_Claimant() { + //given: claimant selects Ready + CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyApplicant().build(); + CallbackParams params = CallbackParamsBuilder.builder().of(SUBMITTED, caseData).build(); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.CLAIMANT.getFormattedName())); + //when: Event is submitted + SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); //then: header + body for the ready status get used in the confirmation assertThat(response).usingRecursiveComparison().isEqualTo( SubmittedCallbackResponse.builder() @@ -322,13 +445,30 @@ void shouldReturnConfirmationScreen_when1v1NotReadySubmitted_ApplicantSolicitor( //given: applicant solicitor selects Not Ready CaseData caseData = CaseDataBuilder.builder().atStateTrialNotReadyApplicant().build(); CallbackParams params = CallbackParamsBuilder.builder().of(SUBMITTED, caseData).build(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.APPLICANTSOLICITORONE))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.APPLICANTSOLICITORONE.getFormattedName())); //when: Event is submitted SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); + //then: header + body for the not ready status get used in the confirmation + assertThat(response).usingRecursiveComparison().isEqualTo( + SubmittedCallbackResponse.builder() + .confirmationHeader(NOT_READY_HEADER) + .confirmationBody(NOT_READY_BODY) + .build() + ); + } + + @Test + void shouldReturnConfirmationScreen_when1v1NotReadySubmitted_Claimant() { + //given: claimant selects Not Ready + CaseData caseData = CaseDataBuilder.builder().atStateTrialNotReadyApplicant().build(); + CallbackParams params = CallbackParamsBuilder.builder().of(SUBMITTED, caseData).build(); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.CLAIMANT.getFormattedName())); + //when: Event is submitted + SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); //then: header + body for the not ready status get used in the confirmation assertThat(response).usingRecursiveComparison().isEqualTo( SubmittedCallbackResponse.builder() @@ -343,13 +483,30 @@ void shouldReturnConfirmationScreen_when1v1ReadySubmitted_Respondent1Solicitor() //given: respondent 1 solicitor selects Ready CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyRespondent1().build(); CallbackParams params = CallbackParamsBuilder.builder().of(SUBMITTED, caseData).build(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.RESPONDENTSOLICITORONE))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.RESPONDENTSOLICITORONE.getFormattedName())); //when: Event is submitted SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); + //then: header + body for the ready status get used in the confirmation + assertThat(response).usingRecursiveComparison().isEqualTo( + SubmittedCallbackResponse.builder() + .confirmationHeader(READY_HEADER) + .confirmationBody(READY_BODY) + .build() + ); + } + @Test + void shouldReturnConfirmationScreen_when1v1ReadySubmitted_Defendant() { + //given: defendant selects Ready + CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyRespondent1().build(); + CallbackParams params = CallbackParamsBuilder.builder().of(SUBMITTED, caseData).build(); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.DEFENDANT.getFormattedName())); + + //when: Event is submitted + SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); //then: header + body for the ready status get used in the confirmation assertThat(response).usingRecursiveComparison().isEqualTo( SubmittedCallbackResponse.builder() @@ -364,13 +521,30 @@ void shouldReturnConfirmationScreen_when1v1NotReadySubmitted_Respondent1Solicito //given: respondent 1 solicitor selects Not Ready CaseData caseData = CaseDataBuilder.builder().atStateTrialNotReadyRespondent1().build(); CallbackParams params = CallbackParamsBuilder.builder().of(SUBMITTED, caseData).build(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.RESPONDENTSOLICITORONE))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.RESPONDENTSOLICITORONE.getFormattedName())); //when: Event is submitted SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); + //then: header + body for the not ready status get used in the confirmation + assertThat(response).usingRecursiveComparison().isEqualTo( + SubmittedCallbackResponse.builder() + .confirmationHeader(NOT_READY_HEADER) + .confirmationBody(NOT_READY_BODY) + .build() + ); + } + + @Test + void shouldReturnConfirmationScreen_when1v1NotReadySubmitted_Defendant() { + //given: defendant selects Not Ready + CaseData caseData = CaseDataBuilder.builder().atStateTrialNotReadyRespondent1().build(); + CallbackParams params = CallbackParamsBuilder.builder().of(SUBMITTED, caseData).build(); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.DEFENDANT.getFormattedName())); + //when: Event is submitted + SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); //then: header + body for the not ready status get used in the confirmation assertThat(response).usingRecursiveComparison().isEqualTo( SubmittedCallbackResponse.builder() @@ -385,13 +559,11 @@ void shouldReturnConfirmationScreen_when1v1ReadySubmitted_Respondent2Solicitor() //given: Respondent 2 selects Ready CaseData caseData = CaseDataBuilder.builder().atStateTrialReadyRespondent2().build(); CallbackParams params = CallbackParamsBuilder.builder().of(SUBMITTED, caseData).build(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.RESPONDENTSOLICITORTWO))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.RESPONDENTSOLICITORTWO.getFormattedName())); //when: Event is submitted SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); - //then: head + body for ready status are used in confirmation assertThat(response).usingRecursiveComparison().isEqualTo( SubmittedCallbackResponse.builder() @@ -406,13 +578,11 @@ void shouldReturnConfirmationScreen_when1v1NotReadySubmitted_Respondent2Solicito //given: Respondent 2 solicitor selects Not Ready CaseData caseData = CaseDataBuilder.builder().atStateTrialNotReadyRespondent2().build(); CallbackParams params = CallbackParamsBuilder.builder().of(SUBMITTED, caseData).build(); - when(userService.getUserInfo(anyString())).thenReturn(UserInfo.builder().uid("uid").build()); - when(coreCaseUserService.userHasCaseRole(anyString(), anyString(), eq(CaseRole.RESPONDENTSOLICITORTWO))) - .thenReturn(true); + when(coreCaseUserService.getUserCaseRoles(anyString(), anyString())) + .thenReturn(List.of(CaseRole.RESPONDENTSOLICITORTWO.getFormattedName())); //when: Event is submitted SubmittedCallbackResponse response = (SubmittedCallbackResponse) handler.handle(params); - //then: head + body for not ready status are used in confirmation assertThat(response).usingRecursiveComparison().isEqualTo( SubmittedCallbackResponse.builder() diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/UploadTranslatedDocumentHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/UploadTranslatedDocumentHandlerTest.java index d9a30c4ffec..b7cab32c2fd 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/UploadTranslatedDocumentHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/UploadTranslatedDocumentHandlerTest.java @@ -10,7 +10,6 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; import uk.gov.hmcts.reform.civil.callback.CallbackParams; -import uk.gov.hmcts.reform.civil.enums.CaseState; import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; import uk.gov.hmcts.reform.civil.handler.callback.user.strategy.translateddocuments.UploadTranslatedDocumentDefaultStrategy; import uk.gov.hmcts.reform.civil.handler.callback.user.strategy.translateddocuments.UploadTranslatedDocumentStrategyFactory; @@ -18,16 +17,19 @@ import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; import uk.gov.hmcts.reform.civil.model.citizenui.TranslatedDocument; +import uk.gov.hmcts.reform.civil.model.common.Element; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; import static uk.gov.hmcts.reform.civil.model.citizenui.TranslatedDocumentType.DEFENDANT_RESPONSE; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.element; import uk.gov.hmcts.reform.civil.documentmanagement.model.Document; import uk.gov.hmcts.reform.civil.service.SystemGeneratedDocumentService; import java.util.ArrayList; +import java.util.List; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = { @@ -54,6 +56,7 @@ class UploadTranslatedDocumentHandlerTest extends BaseCallbackHandlerTest { @Autowired private ObjectMapper objectMapper; + private static final String FILE_NAME_1 = "Some file 1"; @Nested class AboutToSubmitCallback { @@ -61,6 +64,15 @@ class AboutToSubmitCallback { @Test void shouldUploadTranslatedDocumentSuccessfully() { //Given + TranslatedDocument translatedDocument1 = TranslatedDocument + .builder() + .documentType(DEFENDANT_RESPONSE) + .file(Document.builder().documentFileName(FILE_NAME_1).build()) + .build(); + List> translatedDocument = List.of( + element(translatedDocument1) + ); + CaseData caseData = CaseDataBuilder .builder() .atStatePendingClaimIssued() @@ -69,19 +81,14 @@ void shouldUploadTranslatedDocumentSuccessfully() { .systemGeneratedCaseDocuments(new ArrayList<>()) .caseDataLiP(CaseDataLiP .builder() - .translatedDocument(TranslatedDocument - .builder() - .documentType(DEFENDANT_RESPONSE) - .file(Document.builder().build()) - .build()) + .translatedDocuments(translatedDocument) .build()) .build(); CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); //When var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); //Then - assertThat(response.getData()).extracting("translatedDocument").isNotNull(); - assertThat(response.getState()).isEqualTo(CaseState.AWAITING_APPLICANT_INTENTION.name()); + assertThat(response.getData()).extracting("translatedDocument").isNull(); } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/strategy/translateddocuments/UploadTranslatedDocumentDefaultStrategyTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/strategy/translateddocuments/UploadTranslatedDocumentDefaultStrategyTest.java index 6e3747c07e1..c7ce17f9984 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/strategy/translateddocuments/UploadTranslatedDocumentDefaultStrategyTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/callback/user/strategy/translateddocuments/UploadTranslatedDocumentDefaultStrategyTest.java @@ -11,7 +11,6 @@ import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.documentmanagement.model.Document; -import uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; import uk.gov.hmcts.reform.civil.model.citizenui.TranslatedDocument; @@ -34,7 +33,8 @@ }) class UploadTranslatedDocumentDefaultStrategyTest { - private static final String FILE_NAME = "Some file"; + private static final String FILE_NAME_1 = "Some file 1"; + private static final String FILE_NAME_2 = "Some file 2"; @Autowired private UploadTranslatedDocumentDefaultStrategy uploadTranslatedDocumentDefaultStrategy; @@ -45,11 +45,22 @@ class UploadTranslatedDocumentDefaultStrategyTest { @Test void shouldReturnDocumentListWithTranslatedDocument() { //Given - TranslatedDocument translatedDocument = TranslatedDocument + TranslatedDocument translatedDocument1 = TranslatedDocument .builder() .documentType(DEFENDANT_RESPONSE) - .file(Document.builder().documentFileName(FILE_NAME).build()) + .file(Document.builder().documentFileName(FILE_NAME_1).build()) .build(); + TranslatedDocument translatedDocument2 = TranslatedDocument + .builder() + .documentType(DEFENDANT_RESPONSE) + .file(Document.builder().documentFileName(FILE_NAME_2).build()) + .build(); + + List> translatedDocument = List.of( + element(translatedDocument1), + element(translatedDocument2) + ); + CaseData caseData = CaseDataBuilder .builder() .atStatePendingClaimIssued() @@ -57,13 +68,14 @@ void shouldReturnDocumentListWithTranslatedDocument() { .builder() .caseDataLiP(CaseDataLiP .builder() - .translatedDocument(translatedDocument) + .translatedDocuments(translatedDocument) .build()) .build(); CallbackParams callbackParams = CallbackParams.builder().caseData(caseData).build(); - List> documents = List.of(element(CaseDocument.builder().documentName(FILE_NAME).build())); - given(systemGeneratedDocumentService.getSystemGeneratedDocumentsWithAddedDocument(any(Document.class), any( - DocumentType.class), any(CallbackParams.class))).willReturn(documents); + List> documents = List.of( + element(CaseDocument.builder().documentName(FILE_NAME_1).build()), + element(CaseDocument.builder().documentName(FILE_NAME_2).build())); + given(systemGeneratedDocumentService.getSystemGeneratedDocumentsWithAddedDocument(any(), any(CallbackParams.class))).willReturn(documents); //When var response = (AboutToStartOrSubmitCallbackResponse) uploadTranslatedDocumentDefaultStrategy.uploadDocument( callbackParams); @@ -73,8 +85,7 @@ void shouldReturnDocumentListWithTranslatedDocument() { .extracting("value") .extracting("documentName") .isNotNull(); - assertThat(response.getData()).extracting("respondent1ClaimResponseDocumentSpec") - .isNotNull(); + } @Test @@ -90,8 +101,6 @@ void shouldReturnExistingSystemGeneratedDocumentListWhenNothingReturnedFromServi callbackParams); //Then assertThat(response.getData()).extracting("systemGeneratedCaseDocuments") - .isNull(); - assertThat(response.getData()).extracting("respondent1ClaimResponseDocumentSpec") - .isNull(); + .isNotNull(); } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/event/BundleCreationTriggerEventHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/event/BundleCreationTriggerEventHandlerTest.java index 58a76906c01..e16bed27992 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/event/BundleCreationTriggerEventHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/event/BundleCreationTriggerEventHandlerTest.java @@ -214,7 +214,7 @@ void testPrepareNewBundlePopulatesAllFields() { generatedBundle.getValue().getDescription() ); Assertions.assertEquals(bundle.getValue().getTitle(), generatedBundle.getValue().getTitle()); - Assertions.assertEquals(bundle.getValue().getFileName(), generatedBundle.getValue().getFilename()); + Assertions.assertEquals(bundle.getValue().getFileName(), generatedBundle.getValue().getFileName()); Assertions.assertEquals(bundle.getValue().getStitchedDocument().getDocumentFileName(), generatedBundle.getValue().getStitchedDocument().get().getDocumentFileName()); Assertions.assertEquals(caseData.getHearingDate(), generatedBundle.getValue().getBundleHearingDate().get()); @@ -230,7 +230,7 @@ void testPrepareCaseContent() { List> caseBundles = new ArrayList<>(); caseBundles.add(new IdValue<>("1", uk.gov.hmcts.reform.civil.model.Bundle.builder() - .title("Trial Bundle").filename("TrialBundle.pdf") + .title("Trial Bundle").fileName("TrialBundle.pdf") .stitchStatus(Optional.of("NEW")).build())); // When: I call the prepareCaseContent method CaseDataContent caseDataContent = bundleCreationTriggerEventHandler.prepareCaseContent(caseBundles, diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/event/EvidenceUploadNotificationEventHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/event/EvidenceUploadNotificationEventHandlerTest.java index e03aa29680d..7d8eccce7bc 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/event/EvidenceUploadNotificationEventHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/event/EvidenceUploadNotificationEventHandlerTest.java @@ -6,6 +6,7 @@ import org.mockito.Mock; import org.springframework.test.context.junit.jupiter.SpringExtension; import uk.gov.hmcts.reform.ccd.client.model.CaseDetails; +import uk.gov.hmcts.reform.ccd.client.model.StartEventResponse; import uk.gov.hmcts.reform.civil.event.EvidenceUploadNotificationEvent; import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; import uk.gov.hmcts.reform.civil.model.CaseData; @@ -18,6 +19,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.EVIDENCE_UPLOAD_CHECK; @ExtendWith(SpringExtension.class) class EvidenceUploadNotificationEventHandlerTest { @@ -43,6 +45,8 @@ void shouldNotifyAllSolicitors() { CaseDetails caseDetails = CaseDetailsBuilder.builder().data(caseData).build(); when(coreCaseDataService.getCase(caseId)).thenReturn(caseDetails); when(caseDetailsConverter.toCaseData(caseDetails)).thenReturn(caseData); + when(coreCaseDataService.startUpdate(caseId.toString(), EVIDENCE_UPLOAD_CHECK)) + .thenReturn(StartEventResponse.builder().caseDetails(caseDetails).build()); EvidenceUploadNotificationEvent event = new EvidenceUploadNotificationEvent(caseId); //when: Evidence upload Notification handler is called handler.sendEvidenceUploadNotification(event); @@ -62,6 +66,8 @@ void shouldContinueRespondentNotificationIfApplicantFailed() { //when: Exception is thrown from applicant notification handler when(coreCaseDataService.getCase(caseId)).thenReturn(caseDetails); when(caseDetailsConverter.toCaseData(caseDetails)).thenReturn(caseData); + when(coreCaseDataService.startUpdate(caseId.toString(), EVIDENCE_UPLOAD_CHECK)) + .thenReturn(StartEventResponse.builder().caseDetails(caseDetails).build()); doThrow(new RuntimeException()).when(applicantNotificationHandler).notifyApplicantEvidenceUpload(caseData); EvidenceUploadNotificationEvent event = new EvidenceUploadNotificationEvent(caseId); handler.sendEvidenceUploadNotification(event); @@ -80,6 +86,8 @@ void shouldContinueRespondent2IfRespondent1Failed() { //when: Exception is thrown for repondent1 notification handler when(coreCaseDataService.getCase(caseId)).thenReturn(caseDetails); when(caseDetailsConverter.toCaseData(caseDetails)).thenReturn(caseData); + when(coreCaseDataService.startUpdate(caseId.toString(), EVIDENCE_UPLOAD_CHECK)) + .thenReturn(StartEventResponse.builder().caseDetails(caseDetails).build()); doThrow(new RuntimeException()).when(respondentNotificationHandler).notifyRespondentEvidenceUpload(caseData, true); EvidenceUploadNotificationEvent event = new EvidenceUploadNotificationEvent(caseId); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/event/StitchingCompleteCallbackHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/event/StitchingCompleteCallbackHandlerTest.java new file mode 100644 index 00000000000..73d98374dc0 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/event/StitchingCompleteCallbackHandlerTest.java @@ -0,0 +1,64 @@ +package uk.gov.hmcts.reform.civil.handler.event; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import uk.gov.hmcts.reform.ccd.client.model.AboutToStartOrSubmitCallbackResponse; +import uk.gov.hmcts.reform.civil.callback.CallbackParams; +import uk.gov.hmcts.reform.civil.documentmanagement.model.Document; +import uk.gov.hmcts.reform.civil.handler.callback.BaseCallbackHandlerTest; +import uk.gov.hmcts.reform.civil.handler.event.StitchingCompleteCallbackHandler; +import uk.gov.hmcts.reform.civil.model.Bundle; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.IdValue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.gov.hmcts.reform.civil.callback.CallbackType.ABOUT_TO_SUBMIT; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.asyncStitchingComplete; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = { + StitchingCompleteCallbackHandler.class, JacksonAutoConfiguration.class +}) +public class StitchingCompleteCallbackHandlerTest extends BaseCallbackHandlerTest { + + @Autowired + StitchingCompleteCallbackHandler handler; + @Autowired + private ObjectMapper mapper; + private List> caseBundles; + private CaseData caseData; + + @Test + void handleEventsReturnsTheExpectedCallbackEvent() { + assertThat(handler.handledEvents()).contains(asyncStitchingComplete); + } + + @Test + void shouldSetCategoryId() { + caseBundles = new ArrayList<>(); + caseBundles.add(new IdValue<>("1", Bundle.builder().id("1") + .title("Trial Bundle") + .stitchStatus(Optional.of("NEW")).description("Trial Bundle") + .stitchedDocument(Optional.of(Document.builder() + .documentUrl("url") + .documentFileName("name") + .build())) + .build())); + caseData = CaseData.builder().caseBundles(caseBundles).build(); + CallbackParams params = callbackParamsOf(caseData, ABOUT_TO_SUBMIT); + var response = (AboutToStartOrSubmitCallbackResponse) handler.handle(params); + assertThat(response.getErrors()).isNull(); + CaseData updatedData = mapper.convertValue(response.getData(), CaseData.class); + assertThat(updatedData.getCaseBundles().get(0) + .getValue().getStitchedDocument().get().getCategoryID()).isEqualTo("bundles"); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/handler/tasks/UpdateFromGACaseEventTaskHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/handler/tasks/UpdateFromGACaseEventTaskHandlerTest.java index 3cbd98ac6ac..eb228c648b8 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/handler/tasks/UpdateFromGACaseEventTaskHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/handler/tasks/UpdateFromGACaseEventTaskHandlerTest.java @@ -520,6 +520,50 @@ void shouldNotAddDirectionOrderDocument() { verify(externalTaskService).complete(mockExternalTask); } + @Test + void shouldNotAddgaResponseDocument() { + String uid = "f000aa01-0451-4000-b000-000000000000"; + String uid1 = "f000aa01-0451-4000-b000-000000000111"; + CaseData caseData = new CaseDataBuilder().atStateClaimDraft() + .businessProcess(BusinessProcess.builder().status(BusinessProcessStatus.READY).build()) + .build(); + CaseData updatedCaseData = caseData.toBuilder() + .directionOrderDocument(singletonList(Element.builder() + .id(UUID.fromString(uid)) + .value(pdfDocument).build())).build(); + CaseData updatedCaseData1 = caseData.toBuilder() + .gaRespDocStaff(singletonList(Element.builder().id(UUID.fromString(uid1)) + .value(pdfDocument1).build())) + .gaRespDocClaimant(singletonList(Element.builder().id(UUID.fromString(uid1)) + .value(pdfDocument1).build())).build(); + CaseDetails caseDetails = CaseDetailsBuilder.builder().data(updatedCaseData).build(); + StartEventResponse startEventResponse = startEventResponse(caseDetails); + + CaseData generalCaseData = GeneralApplicationDetailsBuilder.builder() + .getTestCaseDataWithDirectionResponseDocument(CaseData.builder().build()); + + when(caseDetailsConverter.toGACaseData(coreCaseDataService.getCase(parseLong(GENERAL_APP_CASE_ID)))) + .thenReturn(generalCaseData); + + when(coreCaseDataService.startUpdate(CIVIL_CASE_ID, ADD_PDF_TO_MAIN_CASE)).thenReturn(startEventResponse); + + when(caseDetailsConverter.toCaseData(startEventResponse.getCaseDetails())).thenReturn(updatedCaseData); + + when(coreCaseDataService.submitUpdate(eq(CIVIL_CASE_ID), any(CaseDataContent.class))) + .thenReturn(updatedCaseData1); + + handler.execute(mockExternalTask, externalTaskService); + + assertThat(updatedCaseData1.getGaRespDocClaimant().size()) + .isEqualTo(generalCaseData.getGaRespDocument().size()); + assertThat(updatedCaseData1.getGaRespDocStaff().size()) + .isEqualTo(generalCaseData.getGaRespDocument().size()); + + verify(coreCaseDataService).startUpdate(CIVIL_CASE_ID, ADD_PDF_TO_MAIN_CASE); + verify(coreCaseDataService).submitUpdate(eq(CIVIL_CASE_ID), any(CaseDataContent.class)); + verify(externalTaskService).complete(mockExternalTask); + } + @Nested class NotRetryableFailureTest { @Test @@ -621,4 +665,10 @@ void checkIfDocumentExists_whenDocumentTypeIsDocumentClass() { .documentBinaryUrl("binary-url") .build()) .build(); + + public final Document pdfDocument1 = Document.builder() + .documentUrl("fake-url") + .documentFileName("file-name") + .documentBinaryUrl("binary-url") + .build(); } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/helpers/bundle/BundleRequestMapperTest.java b/src/test/java/uk/gov/hmcts/reform/civil/helpers/bundle/BundleRequestMapperTest.java index 00954d80d05..1e4665f1f00 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/helpers/bundle/BundleRequestMapperTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/helpers/bundle/BundleRequestMapperTest.java @@ -8,6 +8,7 @@ import uk.gov.hmcts.reform.civil.enums.caseprogression.TypeOfDocDocumentaryEvidenceOfTrial; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.model.ServedDocumentFiles; import uk.gov.hmcts.reform.civil.model.bundle.BundleCreateRequest; import uk.gov.hmcts.reform.civil.model.caseprogression.UploadEvidenceDocumentType; import uk.gov.hmcts.reform.civil.model.caseprogression.UploadEvidenceExpert; @@ -40,13 +41,8 @@ class BundleRequestMapperTest { @Test void testBundleRequestMapperWithAllDocs() { // Given - List> witnessEvidenceDocs = getWitnessDocs(); - List> expertEvidenceDocs = getExpertDocs(); - List> otherEvidenceDocs = setupOtherEvidenceDocs(); - List> systemGeneratedCaseDocuments = setupSystemGeneratedCaseDocs(); //Add all type of documents and other request details in case data - CaseData caseData = getCaseData(witnessEvidenceDocs, expertEvidenceDocs, otherEvidenceDocs, - systemGeneratedCaseDocuments); + CaseData caseData = getCaseData(); // When BundleCreateRequest bundleCreateRequest = bundleRequestMapper.mapCaseDataToBundleCreateRequest(caseData, "sample" + @@ -81,20 +77,22 @@ void testBundleRequestMapperWithAllDocs() { bundleCreateRequest.getCaseDetails().getCaseData().getTrialDocuments().get(11).getValue().getDocumentFileName()); assertEquals("Claim Form 10/02/2023", bundleCreateRequest.getCaseDetails().getCaseData().getStatementsOfCaseDocuments().get(0).getValue().getDocumentFileName()); - assertEquals("DF 1 Defence 10/02/2023", + assertEquals("Particulars Of Claim 10/02/2023", bundleCreateRequest.getCaseDetails().getCaseData().getStatementsOfCaseDocuments().get(1).getValue().getDocumentFileName()); - assertEquals("CL's reply 10/02/2023", + assertEquals("DF 1 Defence 10/02/2023", bundleCreateRequest.getCaseDetails().getCaseData().getStatementsOfCaseDocuments().get(2).getValue().getDocumentFileName()); - assertEquals("CL 1 reply to part 18 request 12/01/2023", + assertEquals("CL's reply 10/02/2023", bundleCreateRequest.getCaseDetails().getCaseData().getStatementsOfCaseDocuments().get(3).getValue().getDocumentFileName()); - assertEquals("CL 2 reply to part 18 request 12/01/2023", + assertEquals("CL 1 reply to part 18 request 12/01/2023", bundleCreateRequest.getCaseDetails().getCaseData().getStatementsOfCaseDocuments().get(4).getValue().getDocumentFileName()); - assertEquals("DF 1 reply to part 18 request 12/01/2023", + assertEquals("CL 2 reply to part 18 request 12/01/2023", bundleCreateRequest.getCaseDetails().getCaseData().getStatementsOfCaseDocuments().get(5).getValue().getDocumentFileName()); - assertEquals("DF 2 reply to part 18 request 12/01/2023", + assertEquals("DF 1 reply to part 18 request 12/01/2023", bundleCreateRequest.getCaseDetails().getCaseData().getStatementsOfCaseDocuments().get(6).getValue().getDocumentFileName()); - assertEquals("Directions Questionnaire 10/02/2023", + assertEquals("DF 2 reply to part 18 request 12/01/2023", bundleCreateRequest.getCaseDetails().getCaseData().getStatementsOfCaseDocuments().get(7).getValue().getDocumentFileName()); + assertEquals("Directions Questionnaire 10/02/2023", + bundleCreateRequest.getCaseDetails().getCaseData().getStatementsOfCaseDocuments().get(8).getValue().getDocumentFileName()); assertEquals("Directions Order 10/02/2023", bundleCreateRequest.getCaseDetails().getCaseData().getOrdersDocuments().get(0).getValue().getDocumentFileName()); assertEquals("Order 10/02/2023", @@ -103,27 +101,39 @@ void testBundleRequestMapperWithAllDocs() { bundleCreateRequest.getCaseDetails().getCaseData().getOrdersDocuments().get(2).getValue().getDocumentFileName()); assertEquals("CL 1 - Statement 10/02/2023", bundleCreateRequest.getCaseDetails().getCaseData().getClaimant1WitnessStatements().get(0).getValue().getDocumentFileName()); - assertEquals("CL 2 - Statement 10/02/2023", + assertEquals("CL 2 - Statement 12/02/2023", bundleCreateRequest.getCaseDetails().getCaseData().getClaimant2WitnessStatements().get(0).getValue().getDocumentFileName()); - assertEquals("DF 1 - Statement 10/02/2023", + assertEquals("DF 1 - Statement 11/02/2023", bundleCreateRequest.getCaseDetails().getCaseData().getDefendant1WitnessStatements().get(0).getValue().getDocumentFileName()); - assertEquals("DF 2 - Statement 10/02/2023", + assertEquals("DF 2 - Statement 13/02/2023", bundleCreateRequest.getCaseDetails().getCaseData().getDefendant2WitnessStatements().get(0).getValue().getDocumentFileName()); - assertEquals("Witness Statement cl2Fname 1 10/02/2023", + assertEquals("Witness Statement cl2Fname 1 12/02/2023", bundleCreateRequest.getCaseDetails().getCaseData().getClaimant1WitnessStatements().get(1).getValue().getDocumentFileName()); + assertEquals("Witness Statement FirstName LastName 1 14/02/2023", + bundleCreateRequest.getCaseDetails().getCaseData().getClaimant1WitnessStatements().get(2).getValue().getDocumentFileName()); + assertEquals("Witness Statement df2Fname 1 13/02/2023", + bundleCreateRequest.getCaseDetails().getCaseData().getClaimant1WitnessStatements().get(3).getValue().getDocumentFileName()); + assertEquals("Witness Statement df1Fname 1 11/02/2023", + bundleCreateRequest.getCaseDetails().getCaseData().getClaimant1WitnessStatements().get(4).getValue().getDocumentFileName()); + assertEquals("Witness Summary cl1Fname 12/12/2023", + bundleCreateRequest.getCaseDetails().getCaseData().getClaimant1WitnessStatements().get(5).getValue().getDocumentFileName()); + assertEquals("Documents referred to in statement 1 12/12/2022", + bundleCreateRequest.getCaseDetails().getCaseData().getClaimant1WitnessStatements().get(10).getValue().getDocumentFileName()); assertEquals("Expert Evidence expert1 Test 12/01/2023", bundleCreateRequest.getCaseDetails().getCaseData().getClaimant1ExpertEvidence().get(0).getValue().getDocumentFileName()); assertEquals("Questions to expert1 12/01/2023", bundleCreateRequest.getCaseDetails().getCaseData().getClaimant1ExpertEvidence().get(1).getValue().getDocumentFileName()); assertEquals("Replies from expert1 12/01/2023", bundleCreateRequest.getCaseDetails().getCaseData().getClaimant1ExpertEvidence().get(2).getValue().getDocumentFileName()); - assertEquals("Expert Evidence expert1 Test 12/01/2023", + assertEquals("Questions to Other expert 12/01/2023", + bundleCreateRequest.getCaseDetails().getCaseData().getClaimant1ExpertEvidence().get(3).getValue().getDocumentFileName()); + assertEquals("Expert Evidence expert2 Test 12/01/2023", bundleCreateRequest.getCaseDetails().getCaseData().getClaimant2ExpertEvidence().get(0).getValue().getDocumentFileName()); - assertEquals("Expert Evidence expert1 Test 12/01/2023", + assertEquals("Expert Evidence expert3 Test 12/01/2023", bundleCreateRequest.getCaseDetails().getCaseData().getDefendant1ExpertEvidence().get(0).getValue().getDocumentFileName()); - assertEquals("Expert Evidence expert1 Test 12/01/2023", + assertEquals("Expert Evidence expert4 Test 12/01/2023", bundleCreateRequest.getCaseDetails().getCaseData().getDefendant2ExpertEvidence().get(0).getValue().getDocumentFileName()); - assertEquals("Joint statement of experts expert1 Test1 Test2 12/01/2023", + assertEquals("Joint statement of experts expert5 Test1 Test2 12/01/2023", bundleCreateRequest.getCaseDetails().getCaseData().getJointStatementOfExperts().get(0).getValue().getDocumentFileName()); assertEquals("testFileName", bundleCreateRequest.getCaseDetails().getCaseData().getClaimant1DisclosedDocuments().get(0).getValue().getDocumentFileName()); @@ -141,63 +151,61 @@ void testBundleRequestMapperWithAllDocs() { bundleCreateRequest.getCaseDetails().getCaseData().getDefendant1CostsBudgets().get(0).getValue().getDocumentFileName()); assertEquals("testFileName 12/12/2023", bundleCreateRequest.getCaseDetails().getCaseData().getDefendant2CostsBudgets().get(0).getValue().getDocumentFileName()); + } - private CaseData getCaseData(List> witnessEvidenceDocs, - List> expertEvidenceDocs, - List> otherEvidenceDocs, - List> systemGeneratedCaseDocuments) { + private CaseData getCaseData() { return CaseData.builder().ccdCaseReference(1L) - .documentWitnessStatement(witnessEvidenceDocs) - .documentWitnessStatementApp2(witnessEvidenceDocs) - .documentWitnessStatementRes(witnessEvidenceDocs) - .documentWitnessStatementRes2(witnessEvidenceDocs) - .documentWitnessSummary(witnessEvidenceDocs) - .documentWitnessSummaryApp2(witnessEvidenceDocs) - .documentWitnessSummaryRes(witnessEvidenceDocs) - .documentWitnessSummaryRes2(witnessEvidenceDocs) - .documentHearsayNotice(witnessEvidenceDocs) - .documentHearsayNoticeApp2(witnessEvidenceDocs) - .documentHearsayNoticeRes(witnessEvidenceDocs) - .documentHearsayNoticeRes2(witnessEvidenceDocs) - .documentReferredInStatement(otherEvidenceDocs) - .documentReferredInStatementApp2(otherEvidenceDocs) - .documentReferredInStatementRes(otherEvidenceDocs) - .documentReferredInStatementRes2(otherEvidenceDocs) - .documentExpertReport(expertEvidenceDocs) - .documentExpertReportApp2(expertEvidenceDocs) - .documentExpertReportRes(expertEvidenceDocs) - .documentExpertReportRes2(expertEvidenceDocs) - .documentJointStatement(expertEvidenceDocs) - .documentJointStatementApp2(expertEvidenceDocs) - .documentJointStatementRes(expertEvidenceDocs) - .documentJointStatementRes2(expertEvidenceDocs) - .documentAnswers(expertEvidenceDocs) - .documentAnswersApp2(expertEvidenceDocs) - .documentAnswersRes(expertEvidenceDocs) - .documentAnswersRes2(expertEvidenceDocs) - .documentQuestions(expertEvidenceDocs) - .documentQuestionsApp2(expertEvidenceDocs) - .documentQuestionsRes(expertEvidenceDocs) - .documentQuestionsRes2(expertEvidenceDocs) + .documentWitnessStatement(getWitnessDocs()) + .documentWitnessStatementApp2(getWitnessDocs()) + .documentWitnessStatementRes(getWitnessDocs()) + .documentWitnessStatementRes2(getWitnessDocs()) + .documentWitnessSummary(getWitnessDocs()) + .documentWitnessSummaryApp2(getWitnessDocs()) + .documentWitnessSummaryRes(getWitnessDocs()) + .documentWitnessSummaryRes2(getWitnessDocs()) + .documentHearsayNotice(getWitnessDocs()) + .documentHearsayNoticeApp2(getWitnessDocs()) + .documentHearsayNoticeRes(getWitnessDocs()) + .documentHearsayNoticeRes2(getWitnessDocs()) + .documentReferredInStatement(setupOtherEvidenceDocs()) + .documentReferredInStatementApp2(setupOtherEvidenceDocs()) + .documentReferredInStatementRes(setupOtherEvidenceDocs()) + .documentReferredInStatementRes2(setupOtherEvidenceDocs()) + .documentExpertReport(getExpertDocs("expert1")) + .documentExpertReportApp2(getExpertDocs("expert2")) + .documentExpertReportRes(getExpertDocs("expert3")) + .documentExpertReportRes2(getExpertDocs("expert4")) + .documentJointStatement(getExpertDocs("expert5")) + .documentJointStatementApp2(getExpertDocs("expert6")) + .documentJointStatementRes(getExpertDocs("expert7")) + .documentJointStatementRes2(getExpertDocs("expert8")) + .documentAnswers(getExpertDocs("expert1")) + .documentAnswersApp2(getExpertDocs("expert2")) + .documentAnswersRes(getExpertDocs("expert3")) + .documentAnswersRes2(getExpertDocs("expert4")) + .documentQuestions(getExpertOtherPartyQuestionDocs("cl1Fname")) + .documentQuestionsApp2(getExpertOtherPartyQuestionDocs("cl2Fname")) + .documentQuestionsRes(getExpertOtherPartyQuestionDocs("df1Fname")) + .documentQuestionsRes2(getExpertOtherPartyQuestionDocs("df2Fname")) .documentEvidenceForTrial(getDocumentEvidenceForTrial()) .documentEvidenceForTrialApp2(getDocumentEvidenceForTrial()) .documentEvidenceForTrialRes(getDocumentEvidenceForTrial()) .documentEvidenceForTrialRes2(getDocumentEvidenceForTrial()) - .documentCaseSummary(otherEvidenceDocs) - .documentCaseSummaryApp2(otherEvidenceDocs) - .documentCaseSummaryRes(otherEvidenceDocs) - .documentCaseSummaryRes2(otherEvidenceDocs) - .documentForDisclosure(otherEvidenceDocs) + .documentCaseSummary(setupOtherEvidenceDocs()) + .documentCaseSummaryApp2(setupOtherEvidenceDocs()) + .documentCaseSummaryRes(setupOtherEvidenceDocs()) + .documentCaseSummaryRes2(setupOtherEvidenceDocs()) + .documentForDisclosure(setupOtherEvidenceDocs()) .defendantResponseDocuments(getDefendantResponseDocs()) .claimantResponseDocuments(getClaimantResponseDocs()) .dismissalOrderDocStaff(getOrderDoc(DocumentType.DISMISSAL_ORDER)) .generalOrderDocStaff(getOrderDoc(DocumentType.GENERAL_ORDER)) - .documentCosts(otherEvidenceDocs) - .documentCostsApp2(otherEvidenceDocs) - .documentCostsRes(otherEvidenceDocs) - .documentCostsRes2(otherEvidenceDocs) - .systemGeneratedCaseDocuments(systemGeneratedCaseDocuments) + .documentCosts(setupOtherEvidenceDocs()) + .documentCostsApp2(setupOtherEvidenceDocs()) + .documentCostsRes(setupOtherEvidenceDocs()) + .documentCostsRes2(setupOtherEvidenceDocs()) + .systemGeneratedCaseDocuments(setupSystemGeneratedCaseDocs()) .applicant1(Party.builder().individualLastName("lastname").individualFirstName("cl1Fname").partyName( "applicant1").type(Party.Type.INDIVIDUAL).build()) .respondent1(Party.builder().individualLastName("lastname").individualFirstName("df1Fname").partyName( @@ -209,10 +217,58 @@ private CaseData getCaseData(List> witnessEvidenc .respondent2(Party.builder().individualLastName("lastname").individualFirstName("df2Fname").partyName( "respondent2").type(Party.Type.INDIVIDUAL).build()) .hearingDate(LocalDate.now()) - .hearingLocation(DynamicList.builder().value(DynamicListElement.builder().label("County Court").build()).build()) + .submittedDate(LocalDateTime.of(2023, 2, 10, 2, + 2, 2)) + .servedDocumentFiles(setupParticularsOfClaimDocs()) .build(); } + private ServedDocumentFiles setupParticularsOfClaimDocs() { + List> particularsOfClaim = new ArrayList<>(); + Document document = Document.builder().documentFileName(TEST_FILE_NAME).documentUrl(TEST_URL).build(); + particularsOfClaim.add(ElementUtils.element(document)); + return ServedDocumentFiles.builder().particularsOfClaimDocument(particularsOfClaim).build(); + } + + private List> getExpertOtherPartyQuestionDocs(String partyName) { + String expertName = ""; + String otherParty = ""; + if (partyName.equals("cl1Fname")) { + expertName = "expert3"; + otherParty = "df1Fname"; + } else if (partyName.equals("cl2Fname")) { + expertName = "expert4"; + otherParty = "df2Fname"; + } else if (partyName.equals("df1Fname")) { + expertName = "expert1"; + otherParty = "cl1Fname"; + } else { + expertName = "expert2"; + otherParty = "cl2Fname"; + } + List> expertEvidenceDocs = new ArrayList<>(); + expertEvidenceDocs.add(ElementUtils.element(UploadEvidenceExpert + .builder() + .expertDocument(Document.builder().documentBinaryUrl(TEST_URL) + .documentFileName(TEST_FILE_NAME).build()) + .expertOptionExpertise("Test") + .expertOptionOtherParty(otherParty) + .expertOptionExpertises("Test1 Test2") + .expertOptionUploadDate(LocalDate.of(2023, 1, 12)) + .expertOptionName(expertName).build())); + expertEvidenceDocs.add(ElementUtils.element(UploadEvidenceExpert + .builder() + .expertDocument(Document.builder().documentBinaryUrl(TEST_URL) + .documentFileName(TEST_FILE_NAME).build()) + .expertOptionExpertise("Test") + .expertOptionOtherParty("wrong party name") + .expertOptionExpertises("Test1 Test2") + .expertOptionUploadDate(LocalDate.of(2023, 1, 12)) + .expertOptionName("Other expert").build())); + + return expertEvidenceDocs; + } + private List> getClaimantResponseDocs() { List> systemGeneratedCaseDocuments = new ArrayList<>(); CaseDocument caseDocumentDC = @@ -278,11 +334,12 @@ private List> setupOtherEvidenceDocs() { .builder() .documentUpload(Document.builder().documentBinaryUrl(TEST_URL) .documentFileName(TEST_FILE_NAME).build()) + .documentIssuedDate(LocalDate.of(2022, 12, 12)) .createdDatetime(LocalDateTime.of(2023, 12, 12, 8, 8, 5)).build())); return otherEvidenceDocs; } - private List> getExpertDocs() { + private List> getExpertDocs(String expertName) { List> expertEvidenceDocs = new ArrayList<>(); expertEvidenceDocs.add(ElementUtils.element(UploadEvidenceExpert .builder() @@ -291,7 +348,7 @@ private List> getExpertDocs() { .expertOptionExpertise("Test") .expertOptionExpertises("Test1 Test2") .expertOptionUploadDate(LocalDate.of(2023, 1, 12)) - .expertOptionName("expert1").build())); + .expertOptionName(expertName).build())); return expertEvidenceDocs; } @@ -299,6 +356,7 @@ private List> getExpertDocs() { private List> getWitnessDocs() { List witnessNames = new ArrayList<>(Arrays.asList("cl1Fname", "df1Fname", "cl2Fname", "df2Fname", "FirstName LastName")); List> witnessEvidenceDocs = new ArrayList<>(); + LocalDateTime createdDateTime = LocalDateTime.of(2023, 12, 12, 8, 8, 5); witnessNames.forEach(witnessName -> { witnessEvidenceDocs.add(ElementUtils.element(UploadEvidenceWitness .builder() @@ -306,7 +364,8 @@ private List> getWitnessDocs() { TEST_URL) .documentFileName(TEST_FILE_NAME).build()) .witnessOptionName(witnessName) - .witnessOptionUploadDate(LocalDate.of(2023, 2, 10)).build())); + .witnessOptionUploadDate(LocalDate.of(2023, 2, 10).plusDays(witnessNames.indexOf(witnessName))) + .createdDatetime(LocalDateTime.of(2023, 12, 12, 8, 8, 5)).build())); }); return witnessEvidenceDocs; } @@ -315,7 +374,7 @@ private List> setupSystemGeneratedCaseDocs() { List> systemGeneratedCaseDocuments = new ArrayList<>(); CaseDocument caseDocumentClaim = CaseDocument.builder().documentType(DocumentType.SEALED_CLAIM).documentLink(Document.builder().documentUrl( - TEST_URL).documentFileName(TEST_FILE_NAME).build()).createdDatetime(LocalDateTime.of(2023, 2, 10, 2, + TEST_URL).documentFileName(TEST_FILE_NAME).categoryID("detailsOfClaim").build()).createdDatetime(LocalDateTime.of(2023, 2, 10, 2, 2, 2)).build(); systemGeneratedCaseDocuments.add(ElementUtils.element(caseDocumentClaim)); CaseDocument caseDocumentDQ = diff --git a/src/test/java/uk/gov/hmcts/reform/civil/helpers/judgmentsonline/JudgmentsOnlineHelperTest.java b/src/test/java/uk/gov/hmcts/reform/civil/helpers/judgmentsonline/JudgmentsOnlineHelperTest.java new file mode 100644 index 00000000000..24a85ad9e40 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/helpers/judgmentsonline/JudgmentsOnlineHelperTest.java @@ -0,0 +1,31 @@ +package uk.gov.hmcts.reform.civil.helpers.judgmentsonline; + +import org.junit.jupiter.api.Test; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentStatusType; + +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; + +public class JudgmentsOnlineHelperTest { + + @Test + void test_getRTLStatusBasedOnJudgementStatus() { + assertThat(JudgmentsOnlineHelper.getRTLStatusBasedOnJudgementStatus(JudgmentStatusType.ISSUED)).isEqualTo("R"); + assertThat(JudgmentsOnlineHelper.getRTLStatusBasedOnJudgementStatus(JudgmentStatusType.MODIFIED)).isEqualTo( + "M"); + assertThat(JudgmentsOnlineHelper.getRTLStatusBasedOnJudgementStatus(JudgmentStatusType.CANCELLED)).isEqualTo( + "C"); + assertThat(JudgmentsOnlineHelper.getRTLStatusBasedOnJudgementStatus(JudgmentStatusType.SET_ASIDE)).isEqualTo( + "C"); + assertThat(JudgmentsOnlineHelper.getRTLStatusBasedOnJudgementStatus(JudgmentStatusType.SATISFIED)).isEqualTo( + "S"); + } + + @Test + void test_validateIfFutureDate() { + assertThat(JudgmentsOnlineHelper.validateIfFutureDate(LocalDate.now())).isFalse(); + assertThat(JudgmentsOnlineHelper.validateIfFutureDate(LocalDate.now().minusDays(3))).isFalse(); + assertThat(JudgmentsOnlineHelper.validateIfFutureDate(LocalDate.now().plusDays(3))).isTrue(); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/model/BundleTest.java b/src/test/java/uk/gov/hmcts/reform/civil/model/BundleTest.java index b73bc0993fb..8e5e0164bb9 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/model/BundleTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/model/BundleTest.java @@ -59,7 +59,7 @@ public void buildsObjectCorrectly() { assertEquals(bundle.getStitchedDocument(), stitchedDocument); assertEquals(bundle.getHasCoversheets(), hasCoversheets); assertEquals(bundle.getHasTableOfContents(), hasTableOfContents); - assertEquals(bundle.getFilename(), filename); + assertEquals(bundle.getFileName(), filename); } @Test diff --git a/src/test/java/uk/gov/hmcts/reform/civil/model/CaseDataTest.java b/src/test/java/uk/gov/hmcts/reform/civil/model/CaseDataTest.java index c419c6b70f1..6652420c25f 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/model/CaseDataTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/model/CaseDataTest.java @@ -4,7 +4,6 @@ import uk.gov.hmcts.reform.ccd.model.Organisation; import uk.gov.hmcts.reform.ccd.model.OrganisationPolicy; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; -import uk.gov.hmcts.reform.civil.documentmanagement.model.Document; import uk.gov.hmcts.reform.civil.enums.AllocatedTrack; import uk.gov.hmcts.reform.civil.enums.MediationDecision; import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec; @@ -12,12 +11,10 @@ import uk.gov.hmcts.reform.civil.handler.callback.user.spec.show.ResponseOneVOneShowTag; import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; import uk.gov.hmcts.reform.civil.model.citizenui.ClaimantMediationLip; -import uk.gov.hmcts.reform.civil.model.citizenui.TranslatedDocument; import uk.gov.hmcts.reform.civil.model.common.Element; import uk.gov.hmcts.reform.civil.model.dq.RecurringExpenseLRspec; import uk.gov.hmcts.reform.civil.model.dq.RecurringIncomeLRspec; import uk.gov.hmcts.reform.civil.model.dq.Respondent1DQ; -import uk.gov.hmcts.reform.civil.model.common.Element; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.sampledata.PartyBuilder; @@ -29,18 +26,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import static uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType.DEFENCE_TRANSLATED_DOCUMENT; import static uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec.FULL_ADMISSION; import static uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType.SDO_ORDER; import static uk.gov.hmcts.reform.civil.enums.CaseCategory.SPEC_CLAIM; import static uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec.FULL_DEFENCE; import static uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec.PART_ADMISSION; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; -import static uk.gov.hmcts.reform.civil.model.citizenui.TranslatedDocumentType.DEFENDANT_RESPONSE; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.element; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; public class CaseDataTest { + private static final String FILE_NAME_1 = "Some file 1"; + @Test public void applicant1Proceed_when1v1() { CaseData caseData = CaseData.builder() @@ -230,10 +229,11 @@ void applicant_isPartAdmitConfirmAmountNotPaid() { } @Test - public void givenRespondentUnrepresentedAndOnvOne_whenIsLRvLipOneVOne_thenTrue() { + public void givenRespondentUnrepresentedAndOnevOne_whenIsLRvLipOneVOne_thenTrue() { //Given CaseData caseData = CaseData.builder() .respondent1Represented(YesOrNo.NO) + .applicant1Represented(YesOrNo.YES) .respondent1(Party.builder().build()) .applicant1(Party.builder().build()) .build(); @@ -241,6 +241,67 @@ public void givenRespondentUnrepresentedAndOnvOne_whenIsLRvLipOneVOne_thenTrue() assertTrue(caseData.isLRvLipOneVOne()); } + @Test + public void givenRespondentRepresentedAndOnevOne_whenIsLRvLipOneVOne_thenFalse() { + //Given + CaseData caseData = CaseData.builder() + .respondent1Represented(YesOrNo.YES) + .applicant1Represented(YesOrNo.YES) + .respondent1(Party.builder().build()) + .applicant1(Party.builder().build()) + .build(); + //Then + assertFalse(caseData.isLRvLipOneVOne()); + } + + @Test + public void givenApplicantUnrepresentedAndOnevOne_whenIsLRvLipOneVOne_thenFalse() { + //Given + CaseData caseData = CaseData.builder() + .respondent1Represented(YesOrNo.NO) + .applicant1Represented(YesOrNo.NO) + .respondent1(Party.builder().build()) + .applicant1(Party.builder().build()) + .build(); + //Then + assertFalse(caseData.isLRvLipOneVOne()); + } + + @Test + public void givenRespondentUnrepresentedAndApplicantUnrepresentedAndOnevOne_whenIsLipvLipOneVOne_thenTrue() { + //Given + CaseData caseData = CaseData.builder() + .respondent1Represented(YesOrNo.NO) + .applicant1Represented(YesOrNo.NO) + .respondent1(Party.builder().build()) + .applicant1(Party.builder().build()) + .build(); + //Then + assertTrue(caseData.isLipvLipOneVOne()); + } + + @Test + public void givenApplicantUnrepresented_whenIsApplicant1NotRepresented_thenTrue() { + //Given + CaseData caseData = CaseData.builder() + .applicant1Represented(YesOrNo.NO) + .applicant1(Party.builder().build()) + .build(); + //Then + assertTrue(caseData.isApplicant1NotRepresented()); + } + + @Test + public void givenApplicantRepresented_whenIsApplicant1NotRepresented_thenFalse() { + //Given + CaseData caseData = CaseData.builder() + .applicant1Represented(YesOrNo.YES) + .applicant1(Party.builder().build()) + .build(); + //Then + assertFalse(caseData.isApplicant1NotRepresented()); + } + @Test void isClaimantNotSettlePartAdmitClaim_thenTrue() { //Given @@ -427,9 +488,7 @@ void shouldReturnEmptyString_whenNoOrganisationDetailsArePresent() { void isTranslatedDocumentUploaded_thenFalse() { //Given CaseData caseData = CaseData.builder() - .caseDataLiP(CaseDataLiP.builder() - .build()) - .build(); + .systemGeneratedCaseDocuments(null).build(); //When //Then assertFalse(caseData.isTranslatedDocumentUploaded()); @@ -439,15 +498,7 @@ void isTranslatedDocumentUploaded_thenFalse() { void isTranslatedDocumentUploaded_thenTrue() { //Given CaseData caseData = CaseData.builder() - .caseDataLiP(CaseDataLiP - .builder() - .translatedDocument(TranslatedDocument - .builder() - .documentType(DEFENDANT_RESPONSE) - .file(Document.builder().build()) - .build()) - .build()) - .build(); + .systemGeneratedCaseDocuments(wrapElements(CaseDocument.builder().documentType(DEFENCE_TRANSLATED_DOCUMENT).build())).build(); //When //Then assertTrue(caseData.isTranslatedDocumentUploaded()); @@ -606,6 +657,17 @@ void isApplicationDeadlinePassed_thenTrue() { //Then assertTrue(caseData.getApplicant1ResponseDeadlinePassed()); } + + @Test + void shouldReturnEmptyArrayListOfManageDocumentsIfNull() { + //Given + CaseData caseData = CaseDataBuilder.builder().build(); + //When + //Then + assertThat(caseData.getManageDocumentsList()).isNotNull(); + assertThat(caseData.getManageDocumentsList()).isEmpty(); + + } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/model/PartyTest.java b/src/test/java/uk/gov/hmcts/reform/civil/model/PartyTest.java index 87ee19e09cc..177d6930853 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/model/PartyTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/model/PartyTest.java @@ -61,4 +61,28 @@ void shouldGetSoulTraderPartyNameExcludingTitle_whenInstantiated() { assertThat(party.getPartyName(true)).isEqualTo("James Carver"); } + @Test + void shouldReturnTrueWhenPartyIsCompany() { + Party party = Party.builder().type(Party.Type.COMPANY) + .build(); + + assertThat(party.isCompanyOROrganisation()).isTrue(); + } + + @Test + void shouldReturnTrueWhenPartyIsOrganisation() { + Party party = Party.builder().type(Party.Type.ORGANISATION) + .build(); + + assertThat(party.isCompanyOROrganisation()).isTrue(); + } + + @Test + void shouldReturnTrueWhenPartyIsNOTOrganisationOrCompany() { + Party party = Party.builder().type(Party.Type.INDIVIDUAL) + .build(); + + assertThat(party.isCompanyOROrganisation()).isFalse(); + } + } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/model/allowance/DisabilityAllowanceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/model/allowance/DisabilityAllowanceTest.java new file mode 100644 index 00000000000..d77fc0ec182 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/model/allowance/DisabilityAllowanceTest.java @@ -0,0 +1,49 @@ +package uk.gov.hmcts.reform.civil.model.allowance; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.gov.hmcts.reform.civil.model.allowance.DisabilityAllowance.getDisabilityAllowance; + +class DisabilityAllowanceTest { + + static Stream shouldReturnCalculatedDisabilityAllowance() { + DisabilityParam severelyDisabledAndCarer = DisabilityParam.builder() + .carer(true) + .severelyDisabled(true) + .build(); + DisabilityParam severelyDisabledCouple = DisabilityParam.builder() + .severelyDisabled(true) + .hasPartner(true) + .build(); + DisabilityParam disabledCouple = DisabilityParam.builder() + .disabled(true) + .hasPartner(true) + .build(); + DisabilityParam hasDependantDisabledAndIsCarer = DisabilityParam.builder() + .dependant(true) + .carer(true) + .build(); + return Stream.of( + Arguments.of(severelyDisabledAndCarer, 417.94), + Arguments.of(severelyDisabledCouple, 536.03), + Arguments.of(disabledCouple, 199.12), + Arguments.of(hasDependantDisabledAndIsCarer, 410.19), + Arguments.of(null, 0.0) + ); + } + + @ParameterizedTest + @MethodSource + void shouldReturnCalculatedDisabilityAllowance(DisabilityParam disabilityParam, double expectedResult) { + //When + double actualResult = getDisabilityAllowance(disabilityParam); + //Then + assertThat(actualResult).isEqualTo(expectedResult); + } + +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/model/allowance/PensionerAllowanceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/model/allowance/PensionerAllowanceTest.java new file mode 100644 index 00000000000..1e7108d6d8e --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/model/allowance/PensionerAllowanceTest.java @@ -0,0 +1,36 @@ +package uk.gov.hmcts.reform.civil.model.allowance; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.gov.hmcts.reform.civil.model.allowance.PensionerAllowance.getPensionerAllowance; + +class PensionerAllowanceTest { + + static Stream shouldReturnPensionerAllowance() { + Arguments singlePensioner = Arguments.of(true, false, 335.83); + Arguments partnerPensioner = Arguments.of(false, true, 335.83); + Arguments couplePensioners = Arguments.of(true, true, 502.66); + Arguments notPensioner = Arguments.of(false, false, 0.0); + return Stream.of( + singlePensioner, + partnerPensioner, + couplePensioners, + notPensioner + ); + } + + @ParameterizedTest + @MethodSource + void shouldReturnPensionerAllowance(boolean pensioner, boolean partnerPensioner, double expectedResult) { + //When + double actualResult = getPensionerAllowance(pensioner, partnerPensioner); + //Then + assertThat(actualResult).isEqualTo(expectedResult); + } + +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/model/allowance/PersonalAllowanceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/model/allowance/PersonalAllowanceTest.java new file mode 100644 index 00000000000..505cba8a6cf --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/model/allowance/PersonalAllowanceTest.java @@ -0,0 +1,37 @@ +package uk.gov.hmcts.reform.civil.model.allowance; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.gov.hmcts.reform.civil.model.allowance.PersonalAllowance.COUPLES_OVER_18; +import static uk.gov.hmcts.reform.civil.model.allowance.PersonalAllowance.COUPLES_UNDER_18_OVER_25; +import static uk.gov.hmcts.reform.civil.model.allowance.PersonalAllowance.COUPLES_UNDER_18_UNDER_25; +import static uk.gov.hmcts.reform.civil.model.allowance.PersonalAllowance.SINGLE_OVER_25; +import static uk.gov.hmcts.reform.civil.model.allowance.PersonalAllowance.SINGLE_UNDER_25; + +class PersonalAllowanceTest { + + static Stream shouldReturnCorrespondingEnum() { + return Stream.of( + Arguments.of(24, false, false, SINGLE_UNDER_25), + Arguments.of(26, false, false, SINGLE_OVER_25), + Arguments.of(24, true, false, COUPLES_UNDER_18_UNDER_25), + Arguments.of(31, true, false, COUPLES_UNDER_18_OVER_25), + Arguments.of(30, true, true, COUPLES_OVER_18) + ); + } + + @ParameterizedTest + @MethodSource + void shouldReturnCorrespondingEnum(int age, boolean hasPartner, boolean partnerUnder18, PersonalAllowance expectedResult) { + //When + PersonalAllowance personalAllowance = PersonalAllowance.getPersonalAllowance(age, hasPartner, partnerUnder18); + //Then + assertThat(personalAllowance).isEqualTo(expectedResult); + } + +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/model/citizenui/CcdClaimStatusDashboardFactoryTest.java b/src/test/java/uk/gov/hmcts/reform/civil/model/citizenui/CcdClaimStatusDashboardFactoryTest.java index bbe8d6b0a43..50208255a98 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/model/citizenui/CcdClaimStatusDashboardFactoryTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/model/citizenui/CcdClaimStatusDashboardFactoryTest.java @@ -1,12 +1,15 @@ package uk.gov.hmcts.reform.civil.model.citizenui; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; -import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType; import uk.gov.hmcts.reform.civil.enums.CaseState; +import uk.gov.hmcts.reform.civil.enums.DJPaymentTypeSelection; import uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec; import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec; import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpecPaidStatus; @@ -21,6 +24,7 @@ import uk.gov.hmcts.reform.civil.model.dq.RequestedCourt; import uk.gov.hmcts.reform.civil.model.sdo.FastTrackHearingTime; import uk.gov.hmcts.reform.civil.model.sdo.SmallClaimsHearing; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import java.time.LocalDate; import java.time.LocalDateTime; @@ -29,14 +33,23 @@ import java.util.UUID; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.mockito.BDDMockito.given; import static uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec.PART_ADMISSION; -@ExtendWith(SpringExtension.class) +@ExtendWith(MockitoExtension.class) class CcdClaimStatusDashboardFactoryTest { + @Mock + private FeatureToggleService featureToggleService; + @InjectMocks private DashboardClaimStatusFactory ccdClaimStatusDashboardFactory; + @BeforeEach + void setUp() { + ccdClaimStatusDashboardFactory = new DashboardClaimStatusFactory(); + } + @Test void given_hasResponsePending_whenGetStatus_thenReturnNoResponse() { CaseData claim = CaseData.builder() @@ -44,7 +57,7 @@ void given_hasResponsePending_whenGetStatus_thenReturnNoResponse() { .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.NO_RESPONSE); } @@ -56,10 +69,23 @@ void given_isEligibleForCCJ_whenGetStatus_thenReturnEligibleForCCJStatus() { .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.ELIGIBLE_FOR_CCJ); } + @Test + void given_isEligibleForCCJ_whenGetStatus_thenReturnDefaultJudgementStatus() { + CaseData claim = CaseData.builder() + .respondent1ResponseDate(LocalDateTime.now()) + .respondent1ResponseDeadline(LocalDateTime.of(2022, 2, 2, 16, 0)) + .paymentTypeSelection(DJPaymentTypeSelection.IMMEDIATELY) + .build(); + + DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( + claim, featureToggleService)); + assertThat(status).isEqualTo(DashboardClaimStatus.DEFAULT_JUDGEMENT); + } + @Test void given_hasResponseDueToday_whenGetStatus_thenReturnResponseDueNow() { CaseData claim = CaseData.builder() @@ -67,7 +93,7 @@ void given_hasResponseDueToday_whenGetStatus_thenReturnResponseDueNow() { .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.RESPONSE_DUE_NOW); } @@ -79,7 +105,7 @@ void given_moreTimeRequested_whenGetStatus_thenReturnMoreTimeRequested() { .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.MORE_TIME_REQUESTED); } @@ -88,7 +114,7 @@ void given_responseAdmitPayImmediately_whenGetStatus_thenReturnAdmitPayImmediate CaseData claim = getClaimWithFullAdmitResponse(RespondentResponsePartAdmissionPaymentTimeLRspec.IMMEDIATELY); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.ADMIT_PAY_IMMEDIATELY); } @@ -97,7 +123,7 @@ void given_responseAdmitPayBySetDate_whenGetStatus_thenReturnAdmitPayBySetDate() CaseData claim = getClaimWithFullAdmitResponse(RespondentResponsePartAdmissionPaymentTimeLRspec.BY_SET_DATE); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.ADMIT_PAY_BY_SET_DATE); } @@ -106,7 +132,7 @@ void given_responseAdmitPayByInstallments_whenGetStatus_thenReturnAdmitPayByInst CaseData claim = getClaimWithFullAdmitResponse(RespondentResponsePartAdmissionPaymentTimeLRspec.SUGGESTION_OF_REPAYMENT_PLAN); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.ADMIT_PAY_INSTALLMENTS); } @@ -120,7 +146,7 @@ void given_claimantConfirmedDefendantPaid_whenGetStatus_thenReturnClaimantAccept .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.CLAIMANT_ACCEPTED_STATES_PAID); } @@ -133,7 +159,7 @@ void given_defendantPayedInFull_whenGetStatus_thenReturnSettled() { .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.SETTLED); } @@ -146,7 +172,7 @@ void given_claimantAcceptedDefendantResponse_whenGetStatus_thenReturnSettled() { .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.SETTLED); } @@ -159,7 +185,7 @@ void given_claimantRequestedCountyCourtJudgement_whenGetStatus_thenReturnRequest .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.REQUESTED_COUNTRY_COURT_JUDGEMENT); } @@ -173,7 +199,7 @@ void given_claimantAcceptedAdmission_whenGetStatus_thenReturnRelevantStatus() { .applicant1AcceptPartAdmitPaymentPlanSpec(YesOrNo.YES) .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.CLAIMANT_ACCEPTED_ADMISSION_OF_AMOUNT); } @@ -185,7 +211,7 @@ void given_defendantRespondedWithPartAdmit_whenGetStatus_thenReturnRelevantStatu .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.PART_ADMISSION) .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.DEFENDANT_PART_ADMIT); } @@ -198,43 +224,49 @@ void given_hearingNoticeDocumentIssued_whenGetStatus_thenReturnHearingFormGenera .build()).build())) .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.HEARING_FORM_GENERATED); } @Test void given_hearingDateForSmallClaimIsAfterToday_and_SDOBeenDrawn_whenGetStatus_moreDetailsRequired() { - Element document = new Element<>(UUID.fromString("5fc03087-d265-11e7-b8c6-83e29cd24f4c"), - CaseDocument.builder() - .documentType(DocumentType.SDO_ORDER) - .build()); + Element document = new Element<>( + UUID.fromString("5fc03087-d265-11e7-b8c6-83e29cd24f4c"), + CaseDocument.builder() + .documentType(DocumentType.SDO_ORDER) + .build() + ); CaseData claim = CaseData.builder() .smallClaimsHearing(SmallClaimsHearing.builder() - .dateFrom(LocalDate.now().plusDays(10)) + .dateFrom(LocalDate.now().plusDays(10)) .build()) .respondent1ResponseDate(LocalDateTime.now()) .systemGeneratedCaseDocuments(List.of(document)) .build(); + given(featureToggleService.isCaseProgressionEnabled()).willReturn(true); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.MORE_DETAILS_REQUIRED); } @Test void given_hearingDateForFastTrackClaimIsAfterToday_and_SDOBeenDrawn_whenGetStatus_moreDetailsRequired() { - Element document = new Element<>(UUID.fromString("5fc03087-d265-11e7-b8c6-83e29cd24f4c"), - CaseDocument.builder() - .documentType(DocumentType.SDO_ORDER) - .build()); + Element document = new Element<>( + UUID.fromString("5fc03087-d265-11e7-b8c6-83e29cd24f4c"), + CaseDocument.builder() + .documentType(DocumentType.SDO_ORDER) + .build() + ); CaseData claim = CaseData.builder() .fastTrackHearingTime(FastTrackHearingTime.builder() - .dateFrom(LocalDate.now().plusDays(10)) - .build()) + .dateFrom(LocalDate.now().plusDays(10)) + .build()) .respondent1ResponseDate(LocalDateTime.now()) .systemGeneratedCaseDocuments(List.of(document)) .build(); + given(featureToggleService.isCaseProgressionEnabled()).willReturn(true); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.MORE_DETAILS_REQUIRED); } @@ -249,7 +281,7 @@ void given_mediation_whenGetSatus_mediationSuccessful() { .build()) .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.MEDIATION_SUCCESSFUL); } @@ -262,7 +294,7 @@ void given_mediation_whenGetStatus_mediationUnsuccessful() { .build()) .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.MEDIATION_UNSUCCESSFUL); } @@ -277,7 +309,7 @@ void given_mediation_whenGetStatus_mediationPending() { .build()) .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.IN_MEDIATION); } @@ -290,7 +322,7 @@ void given_court_whenGetStatus_courtReview() { .applicant1ResponseDate(LocalDateTime.now()) .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.WAITING_COURT_REVIEW); } @@ -303,7 +335,7 @@ void given_respondentFullDefenceAndApplicantNotProceedsWithClaim_whenGetStatus_c .applicant1ResponseDate(LocalDateTime.now()) .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.CLAIM_ENDED); } @@ -316,7 +348,7 @@ void given_applicantRejectPartialAdmit_whenGetStatus_rejectOffer() { .ccdState(CaseState.JUDICIAL_REFERRAL) .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.CLAIMANT_REJECT_PARTIAL_ADMISSION); } @@ -345,7 +377,7 @@ void given_SDOBeenDrawn_whenGetStatus_sdoOrderCreatedRequired() { .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.SDO_ORDER_CREATED); } @@ -357,7 +389,7 @@ void given_claimantNotRespondedWithInDeadLine_whenGetStatus_claimEnded() { .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.CLAIM_ENDED); } @@ -370,7 +402,25 @@ void given_claimantRejectsDefendantsPaymentPlan() { .ccdState(CaseState.PROCEEDS_IN_HERITAGE_SYSTEM) .build(); DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( - claim)); + claim, featureToggleService)); assertThat(status).isEqualTo(DashboardClaimStatus.WAITING_COURT_REVIEW); } + + @Test + void givenClaimStatusInProcessHeritageSystem_WhenGetStatus_thenReturnResponseByPost() { + given(featureToggleService.isLipVLipEnabled()).willReturn(true); + + CaseData claim = CaseData.builder() + .respondent1ResponseDate(LocalDateTime.now()) + .respondent1ClaimResponseTypeForSpec(PART_ADMISSION) + .applicant1AcceptPartAdmitPaymentPlanSpec(YesOrNo.NO) + .takenOfflineDate(LocalDateTime.now()) + .ccdState(CaseState.PROCEEDS_IN_HERITAGE_SYSTEM) + .build(); + + DashboardClaimStatus status = ccdClaimStatusDashboardFactory.getDashboardClaimStatus(new CcdDashboardClaimMatcher( + claim, featureToggleService)); + + assertThat(status).isEqualTo(DashboardClaimStatus.RESPONSE_BY_POST); + } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/model/citizenui/dto/RepaymentDecisionTypeTest.java b/src/test/java/uk/gov/hmcts/reform/civil/model/citizenui/dto/RepaymentDecisionTypeTest.java new file mode 100644 index 00000000000..ba7a521b827 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/model/citizenui/dto/RepaymentDecisionTypeTest.java @@ -0,0 +1,25 @@ +package uk.gov.hmcts.reform.civil.model.citizenui.dto; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RepaymentDecisionTypeTest { + + @Test + void shouldReturnTrue_whenRepaymentDecisionIsInFavourOfDefendant() { + //Given + RepaymentDecisionType repaymentDecisionType = RepaymentDecisionType.IN_FAVOUR_OF_DEFENDANT; + //Then + assertTrue(repaymentDecisionType.isInFavourOfDefendant()); + } + + @Test + void shouldReturnFalse_whenRepaymentDecisionIsInFavourOfClaimant() { + //Given + RepaymentDecisionType repaymentDecisionType = RepaymentDecisionType.IN_FAVOUR_OF_CLAIMANT; + //Then + assertFalse(repaymentDecisionType.isInFavourOfDefendant()); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/model/common/DynamicListTest.java b/src/test/java/uk/gov/hmcts/reform/civil/model/common/DynamicListTest.java new file mode 100644 index 00000000000..1aef0b2539b --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/model/common/DynamicListTest.java @@ -0,0 +1,57 @@ +package uk.gov.hmcts.reform.civil.model.common; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import java.util.Arrays; +import java.util.List; +import java.util.function.Function; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class DynamicListTest { + + private List listItems; + + @BeforeEach + public void setUp() { + listItems = Arrays.asList("Item1", "Item2", "Item3"); + } + + @Test + public void shouldPopulateDynamicListFromList_whenCodeFunctionIsProvided() { + Function toCode = item -> item + "_code"; + Function toLabel = item -> item + "_label"; + String value = "Item2"; + + DynamicList actual = DynamicList.fromList(listItems, toCode, toLabel, value, true); + + DynamicList expected = DynamicList.builder() + .listItems(List.of( + DynamicListElement.builder().code("Item1_code").label("Item1_label").build(), + DynamicListElement.builder().code("Item2_code").label("Item2_label").build(), + DynamicListElement.builder().code("Item3_code").label("Item3_label").build() + )) + .value(DynamicListElement.builder().code("Item2_code").label("Item2_label").build()) + .build(); + + assertEquals(expected, actual); + } + + @Test + public void shouldPopulateDynamicListFromList_whenCodeFunctionIsNotProvided() { + Function toLabel = item -> item + "_label"; + String value = "Item2"; + + DynamicList actual = DynamicList.fromList(listItems, null, toLabel, value, true); + + assertNotNull(actual.getListItems().get(0).getCode()); + assertEquals("Item1_label", actual.getListItems().get(0).getLabel()); + assertNotNull(actual.getListItems().get(1).getCode()); + assertEquals("Item2_label", actual.getListItems().get(1).getLabel()); + assertNotNull(actual.getListItems().get(2).getCode()); + assertEquals("Item3_label", actual.getListItems().get(2).getLabel()); + assertNotNull(actual.getValue().getCode()); + assertEquals("Item2_label", actual.getValue().getLabel()); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/model/repaymentplan/ClaimantProposedPlanTest.java b/src/test/java/uk/gov/hmcts/reform/civil/model/repaymentplan/ClaimantProposedPlanTest.java new file mode 100644 index 00000000000..14a96ed7f8b --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/model/repaymentplan/ClaimantProposedPlanTest.java @@ -0,0 +1,87 @@ +package uk.gov.hmcts.reform.civil.model.repaymentplan; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import uk.gov.hmcts.reform.civil.model.RepaymentPlanLRspec; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec.BY_SET_DATE; +import static uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec.IMMEDIATELY; +import static uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec.SUGGESTION_OF_REPAYMENT_PLAN; + +@ExtendWith(MockitoExtension.class) +class ClaimantProposedPlanTest { + + @Mock + private RepaymentPlanLRspec repaymentPlan; + + @Test + void shouldGetRepaymentDate_fromSetDate() { + //Given + LocalDate proposedDate = LocalDate.of(2023, 2, 1); + ClaimantProposedPlan claimantProposedPlan = ClaimantProposedPlan + .builder() + .repaymentByDate(proposedDate) + .build(); + //When + LocalDate result = claimantProposedPlan.getRepaymentDate(new BigDecimal(2345)); + //Then + assertThat(result).isEqualTo(proposedDate); + } + + @Test + void shouldGetRepaymentDate_fromRepaymentPlan() { + //Given + LocalDate proposedDate = LocalDate.of(2023, 2, 1); + given(repaymentPlan.finalPaymentBy(any())).willReturn(proposedDate); + ClaimantProposedPlan claimantProposedPlan = ClaimantProposedPlan + .builder() + .repaymentPlanLRspec(repaymentPlan) + .build(); + //When + LocalDate result = claimantProposedPlan.getRepaymentDate(new BigDecimal(2345)); + //Then + assertThat(result).isEqualTo(proposedDate); + } + + @Test + void shouldReturnTrue_whenProposedToPayImmediately() { + //Given + ClaimantProposedPlan claimantProposedPlan = ClaimantProposedPlan + .builder() + .proposedRepaymentType(IMMEDIATELY) + .build(); + //Then + assertThat(claimantProposedPlan.hasProposedPayImmediately()).isTrue(); + } + + @Test + void shouldReturnTrue_whenProposedToPayBySetDate() { + //Given + ClaimantProposedPlan claimantProposedPlan = ClaimantProposedPlan + .builder() + .proposedRepaymentType(BY_SET_DATE) + .build(); + //Then + assertThat(claimantProposedPlan.hasProposedPayBySetDate()).isTrue(); + } + + @Test + void shouldReturnTrue_whenProposedToPayByInstallments() { + //Given + ClaimantProposedPlan claimantProposedPlan = ClaimantProposedPlan + .builder() + .proposedRepaymentType(SUGGESTION_OF_REPAYMENT_PLAN) + .build(); + //Then + assertThat(claimantProposedPlan.hasProposedPayByInstallments()).isTrue(); + } + +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadApplicantNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadApplicantNotificationHandlerTest.java index f1ebab3128e..8a90e4fbfd0 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadApplicantNotificationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadApplicantNotificationHandlerTest.java @@ -19,8 +19,10 @@ import java.util.Map; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.CLAIM_REFERENCE_NUMBER; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.UPLOADED_DOCUMENTS; @SpringBootTest(classes = { EvidenceUploadApplicantNotificationHandler.class, @@ -47,7 +49,9 @@ void setup() { @Test void shouldNotifyApplicantSolicitor_whenInvoked() { //given: case where applicant solicitor has email as applicantsolicitor@example.com - CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build(); + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .notificationText("example of uploaded documents") + .build(); //when: ApplicantNotificationhandler is called handler.notifyApplicantEvidenceUpload(caseData); //then: email should be sent to applicant solicitor @@ -62,7 +66,8 @@ void shouldNotifyApplicantSolicitor_whenInvoked() { @Test void shouldNotifyApplicantLip_whenInvoked() { //given: case where applicant litigant in person has email as applicant@example.com - CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified() + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .notificationText("example of uploaded documents") .applicant1Represented(YesOrNo.NO) .applicant1(Party.builder().partyName("Billy").partyEmail("applicant@example.com").build()) .build(); @@ -77,10 +82,41 @@ void shouldNotifyApplicantLip_whenInvoked() { ); } + @Test + void shouldNotNotifyApplicantLip_whenInvokedAndNoNotificationContent() { + //Once emails are sent, we want to null notificationText, so any future emails will not contain past content. + //unable to null directly in EvidenceUploadNotificationEventHandler, so assigned as NULLED. + //given: case where applicant litigant in person has email as applicant@example.com + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().builder() + .notificationText("NULLED") + .applicant1Represented(YesOrNo.NO) + .applicant1(Party.builder().partyName("Billy").partyEmail("applicant@example.com").build()) + .build(); + //when: ApplicantNotificationhandler is called + handler.notifyApplicantEvidenceUpload(caseData); + //then: email should be sent to applicant + verifyNoInteractions(notificationService); + } + + @Test + void shouldNotNotifyApplicantLip_whenInvokedAndNoNotificationContentNull() { + //given: case where applicant litigant in person has email as applicant@example.com + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .notificationText(null) + .applicant1Represented(YesOrNo.NO) + .applicant1(Party.builder().partyName("Billy").partyEmail("applicant@example.com").build()) + .build(); + //when: ApplicantNotificationhandler is called + handler.notifyApplicantEvidenceUpload(caseData); + //then: email should be sent to applicant + verifyNoInteractions(notificationService); + } + @NotNull private Map getNotificationDataMap(CaseData caseData) { return Map.of( - CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference() + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + UPLOADED_DOCUMENTS, "example of uploaded documents" ); } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadRespondentNotificationHandlerTest.java b/src/test/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadRespondentNotificationHandlerTest.java index 85d39b3c4b4..db5d359d8d4 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadRespondentNotificationHandlerTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/notification/EvidenceUploadRespondentNotificationHandlerTest.java @@ -19,8 +19,10 @@ import java.util.Map; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.CLAIM_REFERENCE_NUMBER; +import static uk.gov.hmcts.reform.civil.handler.callback.camunda.notification.NotificationData.UPLOADED_DOCUMENTS; @SpringBootTest(classes = { EvidenceUploadRespondentNotificationHandler.class, @@ -47,7 +49,9 @@ void setup() { @Test void shouldNotifyRespondent1Solicitor_whenInvoked() { //given: case data has one respondent solicitor - CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build(); + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .notificationText("example of uploaded documents") + .build();; //when: RepondentNotificationhandler for solictior1 is called handler.notifyRespondentEvidenceUpload(caseData, true); //then: email should be sent to respondent solicitor1 @@ -62,7 +66,8 @@ void shouldNotifyRespondent1Solicitor_whenInvoked() { @Test void shouldNotifyRespondent1Lip_whenInvoked() { //given: case data has one respondent litigant in person - CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified() + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .notificationText("example of uploaded documents") .respondent1Represented(YesOrNo.NO) .respondent1(Party.builder().partyName("Billy").partyEmail("respondent@example.com").build()) .build(); @@ -81,8 +86,9 @@ void shouldNotifyRespondent1Lip_whenInvoked() { @Test void shouldNotifyRespondent2Solicitor_whenInvoked() { //given: case data has two respondent solicitor - CaseData caseData = CaseDataBuilder.builder() - .atStateClaimDetailsNotified().addRespondent2(YesOrNo.YES) + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .notificationText("example of uploaded documents") + .addRespondent2(YesOrNo.YES) .respondentSolicitor2EmailAddress("respondentsolicitor2@example.com") .build(); //when: RepondentNotificationhandler for solictior2 is called @@ -99,8 +105,9 @@ void shouldNotifyRespondent2Solicitor_whenInvoked() { @Test void shouldNotifyRespondent2Lip_whenInvoked() { //given: case data has two respondents, with second being litigant in person - CaseData caseData = CaseDataBuilder.builder() - .atStateClaimDetailsNotified().addRespondent2(YesOrNo.YES) + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .notificationText("example of uploaded documents") + .addRespondent2(YesOrNo.YES) .respondent2Represented(YesOrNo.NO) .respondent2(Party.builder().partyName("Billy").partyEmail("respondent@example.com").build()) .build(); @@ -115,10 +122,37 @@ void shouldNotifyRespondent2Lip_whenInvoked() { ); } + @Test + void shouldNotNotifyRespondent1Solicitor_whenInvokedAndNoNotificationContent() { + //Once emails are sent, we want to null notificationText, so any future emails will not contain past content. + //unable to null directly in EvidenceUploadNotificationEventHandler, so assigned as NULLED. + //given: case data has one respondent solicitor + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .notificationText("NULLED") + .build(); + //when: RepondentNotificationhandler for solictior1 is called + handler.notifyRespondentEvidenceUpload(caseData, true); + //then: email should be sent to respondent solicitor1 + verifyNoInteractions(notificationService); + } + + @Test + void shouldNotNotifyRespondent1Solicitor_whenInvokedAndNoContentNull() { + //given: case data has one respondent solicitor + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .notificationText(null) + .build(); + //when: RepondentNotificationhandler for solictior1 is called + handler.notifyRespondentEvidenceUpload(caseData, true); + //then: email should be sent to respondent solicitor1 + verifyNoInteractions(notificationService); + } + @NotNull private Map getNotificationDataMap(CaseData caseData) { return Map.of( - CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference() + CLAIM_REFERENCE_NUMBER, caseData.getLegacyCaseReference(), + UPLOADED_DOCUMENTS, "example of uploaded documents" ); } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/sampledata/CaseDataBuilder.java b/src/test/java/uk/gov/hmcts/reform/civil/sampledata/CaseDataBuilder.java index 28753b12a9c..df35ed83ab4 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/sampledata/CaseDataBuilder.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/sampledata/CaseDataBuilder.java @@ -13,6 +13,7 @@ import uk.gov.hmcts.reform.civil.enums.CaseState; import uk.gov.hmcts.reform.civil.enums.ClaimType; import uk.gov.hmcts.reform.civil.enums.ExpertReportsSent; +import uk.gov.hmcts.reform.civil.enums.MediationDecision; import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; import uk.gov.hmcts.reform.civil.enums.PaymentFrequencyLRspec; import uk.gov.hmcts.reform.civil.enums.PaymentStatus; @@ -59,6 +60,7 @@ import uk.gov.hmcts.reform.civil.model.IdamUserDetails; import uk.gov.hmcts.reform.civil.model.LengthOfUnemploymentComplexTypeLRspec; import uk.gov.hmcts.reform.civil.model.LitigationFriend; +import uk.gov.hmcts.reform.civil.model.Mediation; import uk.gov.hmcts.reform.civil.model.PartnerAndDependentsLRspec; import uk.gov.hmcts.reform.civil.model.Party; import uk.gov.hmcts.reform.civil.model.PartyFlagStructure; @@ -84,6 +86,7 @@ import uk.gov.hmcts.reform.civil.model.caseflags.Flags; import uk.gov.hmcts.reform.civil.model.caseprogression.RevisedHearingRequirements; import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; +import uk.gov.hmcts.reform.civil.model.citizenui.ClaimantMediationLip; import uk.gov.hmcts.reform.civil.model.common.DynamicList; import uk.gov.hmcts.reform.civil.model.common.DynamicListElement; import uk.gov.hmcts.reform.civil.model.common.Element; @@ -93,6 +96,7 @@ import uk.gov.hmcts.reform.civil.model.defaultjudgment.DisposalHearingJudgesRecitalDJ; import uk.gov.hmcts.reform.civil.model.defaultjudgment.TrialHearingJudgesRecital; import uk.gov.hmcts.reform.civil.model.defaultjudgment.TrialHearingTrial; +import uk.gov.hmcts.reform.civil.model.defaultjudgment.TrialHearingWitnessOfFact; import uk.gov.hmcts.reform.civil.model.dq.Applicant1DQ; import uk.gov.hmcts.reform.civil.model.dq.Applicant2DQ; import uk.gov.hmcts.reform.civil.model.dq.DisclosureOfElectronicDocuments; @@ -118,6 +122,13 @@ import uk.gov.hmcts.reform.civil.model.interestcalc.InterestClaimOptions; import uk.gov.hmcts.reform.civil.model.interestcalc.InterestClaimUntilType; import uk.gov.hmcts.reform.civil.model.interestcalc.SameRateInterestSelection; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentInstalmentDetails; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentRecordedReason; +import uk.gov.hmcts.reform.civil.model.judgmentonline.PaymentFrequency; +import uk.gov.hmcts.reform.civil.model.judgmentonline.PaymentPlanSelection; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentPaidInFull; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentStatusType; +import uk.gov.hmcts.reform.civil.model.judgmentonline.JudgmentStatusDetails; import uk.gov.hmcts.reform.civil.model.noc.ChangeOrganisationRequest; import uk.gov.hmcts.reform.civil.model.sdo.DisposalHearingFinalDisposalHearingTimeDJ; import uk.gov.hmcts.reform.civil.model.sdo.DisposalHearingHearingTime; @@ -125,9 +136,13 @@ import uk.gov.hmcts.reform.civil.model.sdo.DisposalOrderWithoutHearing; import uk.gov.hmcts.reform.civil.model.sdo.FastTrackHearingTime; import uk.gov.hmcts.reform.civil.model.sdo.FastTrackOrderWithoutJudgement; +import uk.gov.hmcts.reform.civil.model.sdo.FastTrackWitnessOfFact; import uk.gov.hmcts.reform.civil.model.sdo.ReasonNotSuitableSDO; +import uk.gov.hmcts.reform.civil.model.sdo.SmallClaimsWitnessStatement; import uk.gov.hmcts.reform.civil.model.sdo.TrialHearingTimeDJ; import uk.gov.hmcts.reform.civil.model.sdo.TrialOrderMadeWithoutHearingDJ; +import uk.gov.hmcts.reform.civil.model.transferonlinecase.NotSuitableSdoOptions; +import uk.gov.hmcts.reform.civil.model.transferonlinecase.TocTransferCaseReason; import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; import uk.gov.hmcts.reform.civil.service.flowstate.FlowState; @@ -365,6 +380,7 @@ public class CaseDataBuilder { private YesOrNo applicantsProceedIntention; private SmallClaimMedicalLRspec applicant1ClaimMediationSpecRequired; private SmallClaimMedicalLRspec applicantMPClaimMediationSpecRequired; + private Mediation mediation; private YesOrNo specAoSApplicantCorrespondenceAddressRequired; private Address specAoSApplicantCorrespondenceAddressDetails; private YesOrNo specAoSRespondent2HomeAddressRequired; @@ -458,6 +474,9 @@ public class CaseDataBuilder { private YesOrNo specDefenceFullAdmitted2Required; private RespondentResponsePartAdmissionPaymentTimeLRspec defenceAdmitPartPaymentTimeRouteRequired; private ResponseOneVOneShowTag showResponseOneVOneFlag; + private SmallClaimsWitnessStatement smallClaimsWitnessStatement; + private FastTrackWitnessOfFact fastTrackWitnessOfFact; + private TrialHearingWitnessOfFact trialHearingWitnessOfFactDJ; private HearingSupportRequirementsDJ hearingSupportRequirementsDJ; private List> defaultJudgmentDocuments = new ArrayList<>(); @@ -465,9 +484,27 @@ public class CaseDataBuilder { private UpdateDetailsForm updateDetailsForm; + private TocTransferCaseReason tocTransferCaseReason; + + private NotSuitableSdoOptions notSuitableSdoOptions; + + private List> applicant1LRIndividuals; + private List> respondent1LRIndividuals; + private List> respondent2LRIndividuals; + + private List> applicant1OrgIndividuals; + private List> applicant2OrgIndividuals; + private List> respondent1OrgIndividuals; + private List> respondent2OrgIndividuals; + protected String hearingReference; protected ListingOrRelisting listingOrRelisting; + private YesOrNo drawDirectionsOrderRequired; + + private DynamicList transferCourtLocationList; + private String reasonForTransfer; + public CaseDataBuilder sameRateInterestSelection(SameRateInterestSelection sameRateInterestSelection) { this.sameRateInterestSelection = sameRateInterestSelection; return this; @@ -808,6 +845,19 @@ public CaseDataBuilder respondent1DQWithUnavailableDateRange() { return this; } + public CaseDataBuilder respondent2DQWithUnavailableDateRange() { + UnavailableDate unavailableDate = UnavailableDate.builder() + .fromDate(LocalDate.now().plusDays(1)) + .toDate(LocalDate.now().plusDays(2)) + .unavailableDateType(UnavailableDateType.DATE_RANGE) + .build(); + this.respondent2DQ = Respondent2DQ.builder() + .respondent2DQHearing(Hearing.builder().hearingLength(MORE_THAN_DAY).unavailableDatesRequired(YES) + .unavailableDates(wrapElements(List.of(unavailableDate))).build()) + .build(); + return this; + } + public CaseDataBuilder applicant1DQWithUnavailableDateRange() { UnavailableDate unavailableDate = UnavailableDate.builder() .fromDate(LocalDate.now().plusDays(1)) @@ -1493,6 +1543,11 @@ public CaseDataBuilder claimDismissedDate(LocalDateTime date) { return this; } + public CaseDataBuilder caseDismissedHearingFeeDueDate(LocalDateTime date) { + this.caseDismissedHearingFeeDueDate = date; + return this; + } + public CaseDataBuilder addLegalRepDeadline(LocalDateTime date) { this.addLegalRepDeadline = date; return this; @@ -1555,6 +1610,11 @@ public CaseDataBuilder applicant1ResponseDate(LocalDateTime date) { return this; } + public CaseDataBuilder reasonNotSuitableSDO(ReasonNotSuitableSDO reasonNotSuitableSDO) { + this.reasonNotSuitableSDO = reasonNotSuitableSDO; + return this; + } + public CaseDataBuilder atState(FlowState.Main flowState) { return atState(flowState, ONE_V_ONE); } @@ -2089,8 +2149,6 @@ public CaseDataBuilder atStateClaimDraft() { .organisation(Organisation.builder().organisationID("QWERTY R2").build()) .orgPolicyCaseAssignedRole("[RESPONDENTSOLICITORTWO]") .build(); - respondent1OrganisationIDCopy = respondent1OrganisationPolicy.getOrganisation().getOrganisationID(); - respondent2OrganisationIDCopy = respondent2OrganisationPolicy.getOrganisation().getOrganisationID(); respondentSolicitor1EmailAddress = "respondentsolicitor@example.com"; respondentSolicitor2EmailAddress = "respondentsolicitor2@example.com"; applicantSolicitor1UserDetails = IdamUserDetails.builder().email("applicantsolicitor@example.com").build(); @@ -2235,6 +2293,8 @@ public CaseDataBuilder atStateClaimSubmittedNoRespondentRepresented() { atStateClaimSubmitted(); addRespondent2 = YES; respondent2SameLegalRepresentative = NO; + respondent1OrgRegistered = NO; + respondent2OrgRegistered = NO; respondent1Represented = NO; respondent2Represented = NO; respondent2 = PartyBuilder.builder().individual().build().toBuilder().partyID("res-2-party-id").build(); @@ -2761,7 +2821,6 @@ public CaseDataBuilder atStateClaimIssued() { atStatePendingClaimIssued(); claimNotificationDeadline = NOTIFICATION_DEADLINE; ccdState = CASE_ISSUED; - respondent1OrganisationIDCopy = "QWERTY R"; buildHmctsInternalCaseName(); return this; } @@ -4507,6 +4566,35 @@ public CaseDataBuilder atStateBeforeTakenOfflineSDONotDrawnOverLimit() { return this; } + public CaseDataBuilder atStateBeforeTransferCaseSDONotDrawn() { + + atStateApplicantRespondToDefenceAndProceed(); + + ccdState = JUDICIAL_REFERRAL; + notSuitableSdoOptions = NotSuitableSdoOptions.CHANGE_LOCATION; + + tocTransferCaseReason = TocTransferCaseReason.builder() + .reasonForCaseTransferJudgeTxt("unforeseen complexities") + .build(); + unsuitableSDODate = applicant1ResponseDate.plusDays(1); + return this; + } + + public CaseDataBuilder atStateBeforeTransferCaseSDONotDrawnOverLimit() { + + atStateApplicantRespondToDefenceAndProceed(); + + ccdState = JUDICIAL_REFERRAL; + notSuitableSdoOptions = NotSuitableSdoOptions.CHANGE_LOCATION; + + tocTransferCaseReason = TocTransferCaseReason.builder() + .reasonForCaseTransferJudgeTxt("This is more than 150 111111111111111111111111111111111111111111111111111111111111111111111111111" + + "111111111111111111111111111111111111111111111111111111") + .build(); + unsuitableSDODate = applicant1ResponseDate.plusDays(1); + return this; + } + public CaseDataBuilder atStateTakenOfflineSDONotDrawn(MultiPartyScenario mpScenario) { atStateApplicantRespondToDefenceAndProceed(mpScenario); @@ -4612,11 +4700,27 @@ public CaseDataBuilder atStateTakenOfflineAfterSDO(MultiPartyScenario mpScenario atStateBothApplicantsRespondToDefenceAndProceed_2v1(); } + drawDirectionsOrderRequired = NO; ccdState = PROCEEDS_IN_HERITAGE_SYSTEM; takenOfflineDate = applicant1ResponseDate.plusDays(1); return this; } + public CaseDataBuilder atStateTakenOfflineByStaffAfterSDO(MultiPartyScenario mpScenario) { + atStateApplicantRespondToDefenceAndProceed(mpScenario); + if (mpScenario == ONE_V_TWO_ONE_LEGAL_REP) { + atStateApplicantRespondToDefenceAndProceedVsBothDefendants_1v2(); + } else if (mpScenario == TWO_V_ONE) { + atStateBothApplicantsRespondToDefenceAndProceed_2v1(); + } + + drawDirectionsOrderRequired = NO; + ccdState = PROCEEDS_IN_HERITAGE_SYSTEM; + takenOfflineDate = applicant1ResponseDate.plusDays(1); + takenOfflineByStaffDate = applicant1ResponseDate.plusDays(1); + return this; + } + public CaseDataBuilder atStateApplicantProceedAllMediation(MultiPartyScenario mpScenario) { applicant1ClaimMediationSpecRequired = new SmallClaimMedicalLRspec(YES); @@ -4647,6 +4751,20 @@ public CaseDataBuilder atStateApplicantProceedAllMediation(MultiPartyScenario mp return this; } + public CaseDataBuilder atStateMediationUnsuccessful(MultiPartyScenario mpScenario) { + atStateApplicantProceedAllMediation(mpScenario); + applicantsProceedIntention = YES; + caseDataLiP = CaseDataLiP.builder() + .applicant1ClaimMediationSpecRequiredLip( + ClaimantMediationLip.builder() + .hasAgreedFreeMediation(MediationDecision.Yes) + .build()).build(); + + mediation = Mediation.builder().unsuccessfulMediationReason("Unsuccessful").build(); + + return this; + } + public CaseDataBuilder businessProcess(BusinessProcess businessProcess) { this.businessProcess = businessProcess; return this; @@ -4747,6 +4865,7 @@ public CaseDataBuilder addBothRespondent1LitigationFriend() { public CaseDataBuilder multiPartyClaimTwoDefendantSolicitors() { this.addRespondent2 = YES; this.respondent2 = PartyBuilder.builder().individual().build().toBuilder().partyID("res-2-party-id").build(); + this.respondent2Represented = YES; this.respondent2SameLegalRepresentative = NO; this.respondentSolicitor2Reference = "01234"; return this; @@ -5060,6 +5179,16 @@ public CaseDataBuilder removeSolicitorReferences() { return this; } + public CaseDataBuilder transferCourtLocationList(DynamicList transferCourtLocationList) { + this.transferCourtLocationList = transferCourtLocationList; + return this; + } + + public CaseDataBuilder reasonForTransfer(String reasonForTransfer) { + this.reasonForTransfer = reasonForTransfer; + return this; + } + public CaseData buildMakePaymentsCaseData() { Organisation orgId = Organisation.builder() .organisationID("OrgId").build(); @@ -5344,6 +5473,74 @@ public CaseData buildPaymentSuccessfulCaseData() { .build(); } + public CaseData buildJudmentOnlineCaseDataWithPaymentByInstalment() { + return build().toBuilder() + .ccdState(CaseState.All_FINAL_ORDERS_ISSUED) + .joJudgmentRecordReason(JudgmentRecordedReason.JUDGE_ORDER) + .joJudgmentInstalmentDetails(JudgmentInstalmentDetails.builder() + .firstInstalmentDate(LocalDate.of(2022, 12, 12)) + .instalmentAmount("120") + .paymentFrequency(PaymentFrequency.MONTHLY).build()) + .joAmountOrdered("1200") + .joAmountCostOrdered("1100") + .joPaymentPlanSelection(PaymentPlanSelection.PAY_IN_INSTALMENTS) + .joOrderMadeDate(LocalDate.of(2022, 12, 12)) + .joIsRegisteredWithRTL(YES).build(); + } + + public CaseData buildJudmentOnlineCaseDataWithPaymentImmediately() { + return build().toBuilder() + .ccdState(CaseState.All_FINAL_ORDERS_ISSUED) + .joJudgmentRecordReason(JudgmentRecordedReason.JUDGE_ORDER) + .joAmountOrdered("1200") + .joAmountCostOrdered("1100") + .joPaymentPlanSelection(PaymentPlanSelection.PAY_IMMEDIATELY) + .joOrderMadeDate(LocalDate.of(2022, 12, 12)) + .joIsRegisteredWithRTL(YES).build(); + } + + public CaseData buildJudmentOnlineCaseDataWithPaymentByDate() { + return build().toBuilder() + .ccdState(CaseState.All_FINAL_ORDERS_ISSUED) + .joJudgmentRecordReason(JudgmentRecordedReason.JUDGE_ORDER) + .joAmountOrdered("1200") + .joAmountCostOrdered("1100") + .joPaymentPlanSelection(PaymentPlanSelection.PAY_BY_DATE) + .joOrderMadeDate(LocalDate.of(2022, 12, 12)) + .joPaymentToBeMadeByDate(LocalDate.of(2023, 12, 12)) + .joIsRegisteredWithRTL(YES).build(); + } + + public CaseData buildJudgmentOnlineCaseWithMarkJudgementPaidAfter30Days() { + JudgmentStatusDetails judgmentStatusDetails = JudgmentStatusDetails.builder() + .judgmentStatusTypes(JudgmentStatusType.SATISFIED) + .lastUpdatedDate(LocalDateTime.now()).build(); + return build().toBuilder() + .ccdState(CaseState.All_FINAL_ORDERS_ISSUED) + .joOrderMadeDate(LocalDate.of(2023, 7, 1)) + .joJudgmentPaidInFull(JudgmentPaidInFull.builder() + .dateOfFullPaymentMade(LocalDate.of(2023, 9, 15)) + .confirmFullPaymentMade(List.of("CONFIRMED")) + .build()) + .joIsRegisteredWithRTL(YES) + .joJudgmentStatusDetails(judgmentStatusDetails).build(); + } + + public CaseData buildJudgmentOnlineCaseWithMarkJudgementPaidWithin30Days() { + JudgmentStatusDetails judgmentStatusDetails = JudgmentStatusDetails.builder() + .judgmentStatusTypes(JudgmentStatusType.SATISFIED) + .lastUpdatedDate(LocalDateTime.now()).build(); + return build().toBuilder() + .ccdState(CaseState.All_FINAL_ORDERS_ISSUED) + .joOrderMadeDate(LocalDate.of(2023, 9, 1)) + .joJudgmentPaidInFull(JudgmentPaidInFull.builder() + .dateOfFullPaymentMade(LocalDate.of(2023, 9, 15)) + .confirmFullPaymentMade(List.of("CONFIRMED")) + .build()) + .joIsRegisteredWithRTL(YES) + .joJudgmentStatusDetails(judgmentStatusDetails).build(); + } + public CaseDataBuilder setUnassignedCaseListDisplayOrganisationReferences() { this.unassignedCaseListDisplayOrganisationReferences = "Organisation references String"; return this; @@ -5888,8 +6085,177 @@ public CaseDataBuilder claimantUserDetails(IdamUserDetails claimantUserDetails) return this; } - public CaseDataBuilder updateDetailsForm(UpdateDetailsForm additionalDates) { - this.updateDetailsForm = additionalDates; + public CaseDataBuilder updateDetailsForm(UpdateDetailsForm form) { + this.updateDetailsForm = form; + return this; + } + + public CaseDataBuilder atSmallClaimsWitnessStatementWithNegativeInputs() { + atStateClaimNotified(); + this.smallClaimsWitnessStatement = SmallClaimsWitnessStatement.builder() + .input2("-3") + .input3("-3") + .build(); + + return this; + } + + public CaseDataBuilder atFastTrackWitnessOfFactWithNegativeInputs() { + atStateClaimNotified(); + this.fastTrackWitnessOfFact = FastTrackWitnessOfFact.builder() + .input2("-3") + .input3("-3") + .build(); + + return this; + } + + public CaseDataBuilder atSmallClaimsWitnessStatementWithPositiveInputs() { + atStateClaimNotified(); + this.smallClaimsWitnessStatement = SmallClaimsWitnessStatement.builder() + .input2("3") + .input3("3") + .build(); + + return this; + } + + public CaseDataBuilder atFastTrackWitnessOfFactWithPositiveInputs() { + atStateClaimNotified(); + this.fastTrackWitnessOfFact = FastTrackWitnessOfFact.builder() + .input2("3") + .input3("3") + .build(); + + return this; + } + + public CaseDataBuilder atTrialHearingWitnessOfFactWithNegativeInputs() { + atStateClaimNotified(); + this.trialHearingWitnessOfFactDJ = TrialHearingWitnessOfFact.builder() + .input2("-3") + .input3("-3") + .build(); + + return this; + } + + public CaseDataBuilder addApplicantLRIndividual(String firstName, String lastName) { + List> individual = + wrapElements(PartyFlagStructure.builder() + .partyID("app-lr-ind-party-id") + .firstName(firstName) + .lastName(lastName) + .email("abc@def.ghi") + .phone("07777777777") + .build()); + if (this.applicant1LRIndividuals != null && !this.applicant1LRIndividuals.isEmpty()) { + this.applicant1LRIndividuals.addAll(individual); + } else { + this.applicant1LRIndividuals = individual; + } + return this; + } + + public CaseDataBuilder addRespondent1LRIndividual(String firstName, String lastName) { + List> individual = + wrapElements(PartyFlagStructure.builder() + .partyID("res-1-lr-ind-party-id") + .firstName(firstName) + .lastName(lastName) + .email("abc@def.ghi") + .phone("07777777777") + .build()); + if (this.respondent1LRIndividuals != null && !this.respondent1LRIndividuals.isEmpty()) { + this.respondent1LRIndividuals.addAll(individual); + } else { + this.respondent1LRIndividuals = individual; + } + return this; + } + + public CaseDataBuilder addRespondent2LRIndividual(String firstName, String lastName) { + List> individual = + wrapElements(PartyFlagStructure.builder() + .partyID("res-2-lr-ind-party-id") + .firstName(firstName) + .lastName(lastName) + .email("abc@def.ghi") + .phone("07777777777") + .build()); + if (this.respondent2LRIndividuals != null && !this.respondent2LRIndividuals.isEmpty()) { + this.respondent2LRIndividuals.addAll(individual); + } else { + this.respondent2LRIndividuals = individual; + } + return this; + } + + public CaseDataBuilder addApplicant1OrgIndividual(String firstName, String lastName) { + List> individual = + wrapElements(PartyFlagStructure.builder() + .partyID("app-1-org-ind-party-id") + .firstName(firstName) + .lastName(lastName) + .email("abc@def.ghi") + .phone("07777777777") + .build()); + if (this.applicant1OrgIndividuals != null && !this.applicant1OrgIndividuals.isEmpty()) { + this.applicant1OrgIndividuals.addAll(individual); + } else { + this.applicant1OrgIndividuals = individual; + } + return this; + } + + public CaseDataBuilder addApplicant2OrgIndividual(String firstName, String lastName) { + List> individual = + wrapElements(PartyFlagStructure.builder() + .partyID("app-2-org-ind-party-id") + .firstName(firstName) + .lastName(lastName) + .email("abc@def.ghi") + .phone("07777777777") + .build()); + if (this.applicant2OrgIndividuals != null && !this.applicant2OrgIndividuals.isEmpty()) { + this.applicant2OrgIndividuals.addAll(individual); + } else { + this.applicant2OrgIndividuals = individual; + } + return this; + } + + public CaseDataBuilder addRespondent1OrgIndividual(String firstName, String lastName) { + List> individual = + wrapElements(PartyFlagStructure.builder() + .partyID("res-1-org-ind-party-id") + .firstName(firstName) + .lastName(lastName) + .email("abc@def.ghi") + .phone("07777777777") + .build()); + if (this.respondent1OrgIndividuals != null && !this.respondent1OrgIndividuals.isEmpty()) { + this.respondent1OrgIndividuals.addAll(individual); + } else { + this.respondent1OrgIndividuals = individual; + } + return this; + } + + public CaseDataBuilder addRespondent2OrgIndividual(String firstName, String lastName) { + List> individual = + wrapElements(PartyFlagStructure.builder() + .partyID("res-2-org-ind-party-id") + .firstName(firstName) + .lastName(lastName) + .email("abc@def.ghi") + .phone("07777777777") + .build()); + if (this.respondent2OrgIndividuals != null && !this.respondent2OrgIndividuals.isEmpty()) { + this.respondent2OrgIndividuals.addAll(individual); + } else { + this.respondent2OrgIndividuals = individual; + } return this; } @@ -6077,6 +6443,7 @@ public CaseData build() { .applicantMPClaimMediationSpecRequired(applicantMPClaimMediationSpecRequired) .responseClaimMediationSpecRequired(respondent1MediationRequired) .responseClaimMediationSpec2Required(respondent1MediationRequired) + .mediation(mediation) .respondentSolicitor2Reference(respondentSolicitor2Reference) .claimant1ClaimResponseTypeForSpec(claimant1ClaimResponseTypeForSpec) .claimant2ClaimResponseTypeForSpec(claimant2ClaimResponseTypeForSpec) @@ -6168,6 +6535,22 @@ public CaseData build() { .claimantUserDetails(claimantUserDetails) .updateDetailsForm(updateDetailsForm) .defaultJudgmentDocuments(defaultJudgmentDocuments) + .smallClaimsWitnessStatement(smallClaimsWitnessStatement) + .fastTrackWitnessOfFact(fastTrackWitnessOfFact) + .trialHearingWitnessOfFactDJ(trialHearingWitnessOfFactDJ) + //Transfer Online Case + .notSuitableSdoOptions(notSuitableSdoOptions) + .tocTransferCaseReason(tocTransferCaseReason) + .drawDirectionsOrderRequired(drawDirectionsOrderRequired) + .transferCourtLocationList(transferCourtLocationList) + .reasonForTransfer(reasonForTransfer) + .applicant1LRIndividuals(applicant1LRIndividuals) + .respondent1LRIndividuals(respondent1LRIndividuals) + .respondent2LRIndividuals(respondent2LRIndividuals) + .applicant1OrgIndividuals(applicant1OrgIndividuals) + .applicant2OrgIndividuals(applicant2OrgIndividuals) + .respondent1OrgIndividuals(respondent1OrgIndividuals) + .respondent2OrgIndividuals(respondent2OrgIndividuals) .build(); } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/sampledata/CaseDetailsBuilder.java b/src/test/java/uk/gov/hmcts/reform/civil/sampledata/CaseDetailsBuilder.java index b1eb58e674e..e92b4fecdc9 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/sampledata/CaseDetailsBuilder.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/sampledata/CaseDetailsBuilder.java @@ -13,13 +13,13 @@ import java.util.Map; import static uk.gov.hmcts.reform.civil.enums.CaseCategory.SPEC_CLAIM; +import static uk.gov.hmcts.reform.civil.enums.CaseState.CASE_ISSUED; import static uk.gov.hmcts.reform.civil.enums.CaseState.AWAITING_APPLICANT_INTENTION; import static uk.gov.hmcts.reform.civil.enums.CaseState.AWAITING_CASE_DETAILS_NOTIFICATION; import static uk.gov.hmcts.reform.civil.enums.CaseState.AWAITING_RESPONDENT_ACKNOWLEDGEMENT; -import static uk.gov.hmcts.reform.civil.enums.CaseState.CASE_ISSUED; -import static uk.gov.hmcts.reform.civil.enums.CaseState.PENDING_CASE_ISSUED; import static uk.gov.hmcts.reform.civil.enums.CaseState.PREPARE_FOR_HEARING_CONDUCT_HEARING; import static uk.gov.hmcts.reform.civil.enums.CaseState.PROCEEDS_IN_HERITAGE_SYSTEM; +import static uk.gov.hmcts.reform.civil.enums.CaseState.PENDING_CASE_ISSUED; @SuppressWarnings("unchecked") public class CaseDetailsBuilder { diff --git a/src/test/java/uk/gov/hmcts/reform/civil/sampledata/GeneralApplicationDetailsBuilder.java b/src/test/java/uk/gov/hmcts/reform/civil/sampledata/GeneralApplicationDetailsBuilder.java index 08ca9549cd1..cdd3e35fc73 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/sampledata/GeneralApplicationDetailsBuilder.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/sampledata/GeneralApplicationDetailsBuilder.java @@ -1411,6 +1411,22 @@ public CaseData getTestCaseDataWithDirectionOrderPDFDocument(CaseData caseData) .build(); } + public CaseData getTestCaseDataWithDirectionResponseDocument(CaseData caseData) { + String uid = "f000aa01-0451-4000-b000-000000000111"; + String uid1 = "f000aa01-0451-4000-b000-000000000000"; + return caseData.toBuilder() + .ccdCaseReference(1234L) + .generalAppType(GAApplicationType.builder() + .types(singletonList(EXTEND_TIME)) + .build()) + .generalAppEvidenceDocument(wrapElements(Document.builder().documentUrl(STRING_CONSTANT).build())) + .generalOrderDocument(singletonList(Element.builder().id(UUID.fromString(uid)) + .value(pdfDocument).build())) + .gaRespDocument(singletonList(Element.builder().id(UUID.fromString(uid1)) + .value(pdfDocument1).build())) + .build(); + } + public CaseData getTestCaseDataWithConsentOrderPDFDocument(CaseData caseData) { String uid = "f000aa01-0451-4000-b000-000000000111"; String uid1 = "f000aa01-0451-4000-b000-000000000000"; @@ -1663,4 +1679,10 @@ public CaseData getVaryJudgmentWithN245TestData() { .documentBinaryUrl("binary-url") .build()) .build(); + + public final Document pdfDocument1 = Document.builder() + .documentUrl("fake-url") + .documentFileName("file-name") + .documentBinaryUrl("binary-url") + .build(); } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/CaseNoteServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/CaseNoteServiceTest.java index d8fe26551b4..5cb2b9f02ac 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/CaseNoteServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/CaseNoteServiceTest.java @@ -20,6 +20,7 @@ import static org.assertj.core.api.Assertions.within; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.unwrapElements; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; @@ -41,11 +42,17 @@ class CaseNoteServiceTest { @MockBean private IdamClient idamClient; + @MockBean + private Time time; + private LocalDateTime timeNow = LocalDateTime.of(2023, 10, 9, 1, 1, 1); + @Nested class BuildCaseNote { @BeforeEach void setUp() { + given(idamClient.getUserDetails(BEARER_TOKEN)).willReturn(USER_DETAILS); + when(time.now()).thenReturn(timeNow); } @Test @@ -55,44 +62,46 @@ void shouldBuildNote_whenInvoked() { assertThat(caseNote.getNote()).isEqualTo(caseNoteForToday(note).getNote()); assertThat(caseNote.getCreatedBy()).isEqualTo(caseNoteForToday(note).getCreatedBy()); - assertThat(caseNote.getCreatedOn()).isCloseTo(caseNoteForToday(note).getCreatedOn(), - within(1, ChronoUnit.SECONDS)); + assertThat(caseNote.getCreatedOn()).isCloseTo( + caseNoteForToday(note).getCreatedOn(), + within(1, ChronoUnit.SECONDS) + ); verify(idamClient).getUserDetails(BEARER_TOKEN); } - } - @Test - void shouldAddNoteToList_WhenNullList() { - CaseNote caseNote = caseNoteForToday("new note"); - List> caseNotes = caseNoteService.addNoteToList(caseNote, null); + @Test + void shouldAddNoteToList_WhenNullList() { + CaseNote caseNote = caseNoteForToday("new note"); + List> caseNotes = caseNoteService.addNoteToListStart(caseNote, null); - assertThat(unwrapElements(caseNotes)).contains(caseNote); - } + assertThat(unwrapElements(caseNotes)).contains(caseNote); + } - @Test - void shouldAddNoteToList_WhenEmptyList() { - CaseNote caseNote = caseNoteForToday("new note"); - List> caseNotes = caseNoteService.addNoteToList(caseNote, new ArrayList<>()); + @Test + void shouldAddNoteToList_WhenEmptyList() { + CaseNote caseNote = caseNoteForToday("new note"); + List> caseNotes = caseNoteService.addNoteToListStart(caseNote, new ArrayList<>()); - assertThat(unwrapElements(caseNotes)).contains(caseNote); - } + assertThat(unwrapElements(caseNotes)).contains(caseNote); + } - @Test - void shouldAddNoteToListWithNewestAtTop_WhenExistingNotes() { - LocalDateTime today = LocalDateTime.now(); - CaseNote newNote = caseNoteWithDate(today); - CaseNote oldNote = caseNoteWithDate(today.minusDays(5)); + @Test + void shouldAddNoteToListWithNewestAtTop_WhenExistingNotes() { + LocalDateTime today = time.now(); + CaseNote newNote = caseNoteWithDate(today); + CaseNote oldNote = caseNoteWithDate(today.minusDays(5)); - List> caseNotes = caseNoteService.addNoteToList(newNote, wrapElements(oldNote)); + List> caseNotes = caseNoteService.addNoteToListStart(newNote, wrapElements(oldNote)); - assertThat(unwrapElements(caseNotes)).isEqualTo(List.of(newNote, oldNote)); + assertThat(unwrapElements(caseNotes)).isEqualTo(List.of(newNote, oldNote)); + } } private CaseNote caseNoteForToday(String note) { return CaseNote.builder() .note(note) .createdBy(USER_DETAILS.getFullName()) - .createdOn(LocalDateTime.now()) + .createdOn(time.now()) .build(); } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/FeatureToggleServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/FeatureToggleServiceTest.java index 4decc30b393..cba681c75a8 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/FeatureToggleServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/FeatureToggleServiceTest.java @@ -141,6 +141,44 @@ void shouldReturnCorrectValue_whenUpdateContactDetailsEnabled(Boolean toggleStat assertThat(featureToggleService.isUpdateContactDetailsEnabled()).isEqualTo(toggleStat); } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void shouldReturnCorrectValue_whenLocationWhiteListed(Boolean toggleStat) { + final String feature = "case-progression-location-whitelist"; + String location = "000000"; + when(featureToggleApi.isFeatureEnabledForLocation(eq(feature), eq(location), eq(true))) + .thenReturn(toggleStat); + + assertThat(featureToggleService.isLocationWhiteListedForCaseProgression(location)).isEqualTo(toggleStat); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void shouldReturnCorrectValue_whenIsTransferCaseOnlineEnabled(Boolean toggleStat) { + var transferCaseOnlineKey = "isTransferOnlineCaseEnabled"; + givenToggle(transferCaseOnlineKey, toggleStat); + + assertThat(featureToggleService.isTransferOnlineCaseEnabled()).isEqualTo(toggleStat); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void shouldReturnCorrectValue_whenCaseProgressionEnabled(Boolean toggleStat) { + var caseFileKey = "cui-case-progression"; + givenToggle(caseFileKey, toggleStat); + + assertThat(featureToggleService.isCaseProgressionEnabled()).isEqualTo(toggleStat); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void shouldReturnCorrectValue_whenEarlyAdopterEnabled(Boolean toggleStat) { + var caseFileKey = "early-adopters"; + givenToggle(caseFileKey, toggleStat); + + assertThat(featureToggleService.isEarlyAdoptersEnabled()).isEqualTo(toggleStat); + } + private void givenToggle(String feature, boolean state) { when(featureToggleApi.isFeatureEnabled(eq(feature))) .thenReturn(state); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/GenAppStateHelperServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/GenAppStateHelperServiceTest.java index 6aa26270c72..f6626efde69 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/GenAppStateHelperServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/GenAppStateHelperServiceTest.java @@ -18,14 +18,19 @@ import uk.gov.hmcts.reform.civil.model.genapplication.CaseLocationCivil; import uk.gov.hmcts.reform.civil.model.genapplication.GADetailsRespondentSol; import uk.gov.hmcts.reform.civil.model.genapplication.GeneralApplicationsDetails; +import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; +import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.sampledata.GeneralApplicationDetailsBuilder; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -50,13 +55,19 @@ class GenAppStateHelperServiceTest { @MockBean private CoreCaseDataService coreCaseDataService; + @MockBean + private InitiateGeneralApplicationService genAppService; @Autowired private CaseDetailsConverter caseDetailsConverter; + @MockBean + private LocationRefDataService locationRefDataService; + private static final String APPLICATION_CLOSED_TEXT = "Application Closed"; private static final String APPLICATION_OFFLINE_TEXT = "Proceeds In Heritage"; private static final String SET_DATE = "2022-08-31T22:50:11.2509019"; + private static final String authToken = "Bearer TestAuthToken"; @Nested class StatusChangeInApplicationDetailsInClaim { @@ -393,6 +404,10 @@ private CaseDetails getCaseDetails( @Test void updateApplicationLocationDetailsLists() { + when(locationRefDataService.getCourtLocationsByEpimmsId(any(), any())) + .thenReturn(getSampleCourLocationsRefObject()); + when(genAppService.getWorkAllocationLocationDetails(any(), any())) + .thenReturn(getSampleCourLocationsRefObject1()); CaseData caseData = GeneralApplicationDetailsBuilder.builder() .getTestCaseDataWithDetails(CaseData.builder().build(), true, @@ -404,8 +419,10 @@ void updateApplicationLocationDetailsLists() { Pair caseLocation = Pair.of(CaseLocationCivil.builder() .region("2") .baseLocation("00000").siteName("locationOfRegion2") + .address("Prince William House, Peel Cross Road, Salford") + .postcode("M5 4RR") .build(), false); - CaseData updatedData = service.updateApplicationLocationDetailsInClaim(caseData); + CaseData updatedData = service.updateApplicationLocationDetailsInClaim(caseData, authToken); assertThat(getGADetailsFromUpdatedCaseData(updatedData, "1234")).isNotNull(); assertThat(updatedData.getGeneralApplications().get(0).getValue().getCaseManagementLocation()).isEqualTo(caseLocation.getLeft()); @@ -416,6 +433,23 @@ void updateApplicationLocationDetailsLists() { assertThat(updatedData.getGeneralApplications().get(2).getValue().getIsCcmccLocation()).isEqualTo(YesOrNo.NO); } + protected List getSampleCourLocationsRefObject() { + return new ArrayList<>(List.of( + LocationRefData.builder() + .epimmsId("00000").siteName("locationOfRegion2").courtAddress("Prince William House, Peel Cross Road, Salford") + .postcode("M5 4RR") + .courtLocationCode("court1").build() + )); + } + + protected LocationRefData getSampleCourLocationsRefObject1() { + return + LocationRefData.builder() + .epimmsId("00000").siteName("locationOfRegion2").courtAddress("Prince William House, Peel Cross Road, Salford") + .postcode("M5 4RR") + .courtLocationCode("court1").build(); + } + @Test void noLocationUpdatesToCaseDataIfThereAreNoGeneralApplications() { setupForApplicationOffline(); @@ -427,8 +461,7 @@ void noLocationUpdatesToCaseDataIfThereAreNoGeneralApplications() { Map.of() ); - CaseData response = service.updateApplicationLocationDetailsInClaim( - caseData); + CaseData response = service.updateApplicationLocationDetailsInClaim(caseData, authToken); CaseData updatedData = mapper.convertValue(response, CaseData.class); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/GeneralAppFeesServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/GeneralAppFeesServiceTest.java index c046c16a432..c1203a52713 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/GeneralAppFeesServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/GeneralAppFeesServiceTest.java @@ -333,7 +333,7 @@ void vary_types_should_be_14() { @Test void settle_should_be_108() { CaseData caseDataWithNotice = getFeeCase( - List.of(GeneralApplicationTypes.SETTLE_OR_DISCONTINUE_CONSENT), + List.of(GeneralApplicationTypes.SETTLE_BY_CONSENT), YesOrNo.YES, YesOrNo.YES, null); Fee feeDto = feesService.getFeeForGA(caseDataWithNotice); assertThat(feeDto).isEqualTo(FEE_PENCE_108); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/InitiateGeneralApplicationServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/InitiateGeneralApplicationServiceTest.java index c31cee41aa0..c4e659ce307 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/InitiateGeneralApplicationServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/InitiateGeneralApplicationServiceTest.java @@ -33,12 +33,15 @@ import uk.gov.hmcts.reform.civil.sampledata.GeneralApplicationDetailsBuilder; import uk.gov.hmcts.reform.civil.sampledata.LocationRefSampleDataBuilder; import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; +import uk.gov.hmcts.reform.civil.utils.UserRoleCaching; import uk.gov.hmcts.reform.idam.client.models.UserDetails; import uk.gov.hmcts.reform.civil.prd.client.OrganisationApi; import java.io.IOException; import java.time.LocalDate; import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -83,6 +86,7 @@ class InitiateGeneralApplicationServiceTest extends LocationRefSampleDataBuilder public static final String APPLICANT_EMAIL_ID_CONSTANT = "testUser@gmail.com"; public static final String DEFENDANT_EMAIL_ID_CONSTANT = "testUser1@gmail.com"; + private static final String authToken = "Bearer TestAuthToken"; private static final LocalDateTime weekdayDate = LocalDate.of(2022, 2, 15).atTime(12, 0); private static final Applicant1DQ applicant1DQ = Applicant1DQ.builder().applicant1DQRequestedCourt(RequestedCourt.builder() @@ -125,6 +129,8 @@ class InitiateGeneralApplicationServiceTest extends LocationRefSampleDataBuilder @MockBean private UserService userService; + @MockBean + private UserRoleCaching userRoleCaching; @MockBean private CrossAccessUserConfiguration crossAccessUserConfiguration; @@ -189,11 +195,13 @@ void shouldReturnTrue_whenRespondent1SolIsAssigned_1V1() { .caseReference(1L) .respondent1OrganisationPolicy(respondent1Organization) .build(); + List userRoles = new ArrayList<>(Arrays.asList("[APPLICANTSOLICITORONE]", "[RESPONDENTSOLICITORONE]")); + when(userRoleCaching.getUserRoles(any(), any())).thenReturn(userRoles); when(caseAccessDataStoreApi.getUserRoles(any(), any(), any())) .thenReturn(CaseAssignedUserRolesResource.builder() .caseAssignedUserRoles(applicant1Respondent1SolAssigned()).build()); - assertThat(service.respondentAssigned(caseData)).isTrue(); + assertThat(service.respondentAssigned(caseData, authToken)).isTrue(); } @Test @@ -206,7 +214,7 @@ void shouldReturnFalse_whenRespondentSolIsNotAssigned_1V1() { .thenReturn(CaseAssignedUserRolesResource.builder() .caseAssignedUserRoles(onlyApplicantSolicitorAssigned()).build()); - assertThat(service.respondentAssigned(caseData)).isFalse(); + assertThat(service.respondentAssigned(caseData, authToken)).isFalse(); } /* 1V2 Same defendant org scenarios */ @@ -218,11 +226,13 @@ void shouldReturnTrue_whenR1SolicitorsIsAssigned_1V2_SAME() { .respondent1OrganisationPolicy(respondent1Organization) .respondent2OrganisationPolicy(respondent2Organization) .build(); + List userRoles = new ArrayList<>(Arrays.asList("[APPLICANTSOLICITORONE]", "[RESPONDENTSOLICITORONE]")); + when(userRoleCaching.getUserRoles(any(), any())).thenReturn(userRoles); when(caseAccessDataStoreApi.getUserRoles(any(), any(), any())) .thenReturn(CaseAssignedUserRolesResource.builder() .caseAssignedUserRoles(applicant1Respondent1SolAssigned()).build()); - assertThat(service.respondentAssigned(caseData)).isTrue(); + assertThat(service.respondentAssigned(caseData, authToken)).isTrue(); } @Test @@ -233,11 +243,13 @@ void shouldReturnTrue_whenR1AndR2AreAssigned_1V2_SAME() { .respondent1OrganisationPolicy(respondent1Organization) .respondent2OrganisationPolicy(respondent2Organization) .build(); + List userRoles = new ArrayList<>(Arrays.asList("[APPLICANTSOLICITORONE]", "[RESPONDENTSOLICITORONE]", "[RESPONDENTSOLICITORTWO]")); + when(userRoleCaching.getUserRoles(any(), any())).thenReturn(userRoles); when(caseAccessDataStoreApi.getUserRoles(any(), any(), any())) .thenReturn(CaseAssignedUserRolesResource.builder() .caseAssignedUserRoles(applicant1Respondent1Respondent2SolAssigned()).build()); - assertThat(service.respondentAssigned(caseData)).isTrue(); + assertThat(service.respondentAssigned(caseData, authToken)).isTrue(); } @Test @@ -252,7 +264,7 @@ void shouldReturnFalse_whenRespondent1SolOnlyIsAssigned_1V2_SAME() { .thenReturn(CaseAssignedUserRolesResource.builder() .caseAssignedUserRoles(applicant1Respondent2SolAssigned()).build()); - assertThat(service.respondentAssigned(caseData)).isFalse(); + assertThat(service.respondentAssigned(caseData, authToken)).isFalse(); } @Test @@ -267,7 +279,7 @@ void shouldReturnTrue_whenRespondent1SolOnlyIsAssigned_1V2_SAME() { .thenReturn(CaseAssignedUserRolesResource.builder() .caseAssignedUserRoles(onlyApplicantSolicitorAssigned()).build()); - assertThat(service.respondentAssigned(caseData)).isFalse(); + assertThat(service.respondentAssigned(caseData, authToken)).isFalse(); } /* 1V2 Different defendant org scenarios */ @@ -280,11 +292,13 @@ void shouldReturnTrue_whenR1R2SolsAreAssigned_1V2_DIFF() { .respondent1OrganisationPolicy(respondent1Organization) .respondent2OrganisationPolicy(respondent2Organization) .build(); + List userRoles = new ArrayList<>(Arrays.asList("[APPLICANTSOLICITORONE]", "[RESPONDENTSOLICITORONE]", "[RESPONDENTSOLICITORTWO]")); + when(userRoleCaching.getUserRoles(any(), any())).thenReturn(userRoles); when(caseAccessDataStoreApi.getUserRoles(any(), any(), any())) .thenReturn(CaseAssignedUserRolesResource.builder() .caseAssignedUserRoles(applicant1Respondent1Respondent2SolAssigned()).build()); - assertThat(service.respondentAssigned(caseData)).isTrue(); + assertThat(service.respondentAssigned(caseData, authToken)).isTrue(); } @Test @@ -299,7 +313,7 @@ void shouldReturnFalse_whenR1R2SolsAreNotAssigned_1V2_DIFF() { .thenReturn(CaseAssignedUserRolesResource.builder() .caseAssignedUserRoles(onlyApplicantSolicitorAssigned()).build()); - assertThat(service.respondentAssigned(caseData)).isFalse(); + assertThat(service.respondentAssigned(caseData, authToken)).isFalse(); } @Test @@ -314,7 +328,7 @@ void shouldReturnFalse_whenR1AssignedButR2NotAssigned_1V2_DIFF() { .thenReturn(CaseAssignedUserRolesResource.builder() .caseAssignedUserRoles(applicant1Respondent1SolAssigned()).build()); - assertThat(service.respondentAssigned(caseData)).isFalse(); + assertThat(service.respondentAssigned(caseData, authToken)).isFalse(); } @Test @@ -329,7 +343,7 @@ void shouldReturnFalse_whenR2AssignedButR1NotAssigned_1V2_DIFF() { .thenReturn(CaseAssignedUserRolesResource.builder() .caseAssignedUserRoles(applicant1Respondent2SolAssigned()).build()); - assertThat(service.respondentAssigned(caseData)).isFalse(); + assertThat(service.respondentAssigned(caseData, authToken)).isFalse(); } } @@ -850,17 +864,16 @@ void shouldPopulatePartyNameDetails() { void shouldReturnTrue_whenApplicantIsClaimantAtMainCase() { CaseData caseData = GeneralApplicationDetailsBuilder.builder() .getTestCaseData(CaseDataBuilder.builder().build()); - + List userRoles = new ArrayList<>(Arrays.asList("[APPLICANTSOLICITORONE]")); CaseData.CaseDataBuilder builder = caseData.toBuilder(); builder.applicant1OrganisationPolicy(OrganisationPolicy .builder().orgPolicyCaseAssignedRole("[APPLICANTSOLICITORONE]").build()); - + when(userRoleCaching.getUserRoles(any(), any())).thenReturn(userRoles); when(caseAccessDataStoreApi.getUserRoles(any(), any(), any())) .thenReturn(CaseAssignedUserRolesResource.builder() .caseAssignedUserRoles(onlyApplicantSolicitorAssigned()).build()); - boolean result = service.isGAApplicantSameAsParentCaseClaimant(builder.build(), UserDetails.builder() - .id("org1Sol1").build()); + boolean result = service.isGAApplicantSameAsParentCaseClaimant(builder.build(), authToken); assertTrue(result); } @@ -868,17 +881,17 @@ void shouldReturnTrue_whenApplicantIsClaimantAtMainCase() { void shouldReturnFalse_whenApplicantIsClaimantAtMainCase() { CaseData caseData = GeneralApplicationDetailsBuilder.builder() .getTestCaseData(CaseDataBuilder.builder().build()); + List userRoles = new ArrayList<>(Arrays.asList("[APPLICANTSOLICITORONE]", "[RESPONDENTSOLICITORTWO]")); CaseData.CaseDataBuilder builder = caseData.toBuilder(); builder.applicant1OrganisationPolicy(OrganisationPolicy .builder().orgPolicyCaseAssignedRole("[APPLICANTSOLICITORONE]").build()); - + when(userRoleCaching.getUserRoles(any(), any())).thenReturn(userRoles); when(caseAccessDataStoreApi.getUserRoles(any(), any(), any())) .thenReturn(CaseAssignedUserRolesResource.builder() .caseAssignedUserRoles(applicant1Respondent2SolAssigned()).build()); - boolean result = service.isGAApplicantSameAsParentCaseClaimant(builder.build(), UserDetails.builder() - .id("org3Sol1").build()); + boolean result = service.isGAApplicantSameAsParentCaseClaimant(builder.build(), authToken); assertFalse(result); } @@ -888,7 +901,8 @@ void shouldPopulateApplicantDetails() { CaseData caseData = GeneralApplicationDetailsBuilder.builder() .getTestCaseDataForConsentUnconsentCheck(GARespondentOrderAgreement.builder().hasAgreed(NO).build()); when(locationRefDataService.getCcmccLocation(any())) - .thenReturn(LocationRefData.builder().regionId("9").epimmsId("574546").siteName("CCMCC").build()); + .thenReturn(LocationRefData.builder().regionId("9").epimmsId("574546").siteName("CCMCC") + .courtAddress("Prince William House, Peel Cross Road, Salford").postcode("M5 4RR").build()); CaseData result = service.buildCaseData(caseData.toBuilder(), caseData, UserDetails.builder() .email(APPLICANT_EMAIL_ID_CONSTANT).id(STRING_NUM_CONSTANT).build(), CallbackParams.builder().toString()); @@ -901,11 +915,98 @@ void shouldPopulateApplicantDetails() { assertThat(result.getGeneralApplications().get(0).getValue().getLocationName()) .isEqualTo("CCMCC"); + assertThat(result.getGeneralApplications().get(0).getValue().getCaseManagementLocation().getAddress()) + .isEqualTo("Prince William House, Peel Cross Road, Salford"); + assertThat(result.getGeneralApplications().get(0).getValue().getCaseManagementLocation().getPostcode()) + .isEqualTo("M5 4RR"); assertThat(result.getGeneralApplications().get(0).getValue().getGeneralAppRespondentSolicitors() .stream().filter(e -> STRING_NUM_CONSTANT.equals(e.getValue().getId())).count()).isEqualTo(0); } + @Test + void shouldPopulateLocationDetailsForBaseLocation() { + when(locationRefDataService.getCourtLocationsByEpimmsId(any(), any())).thenReturn(getSampleCourLocationsRefObject()); + CaseData caseData = GeneralApplicationDetailsBuilder.builder() + .getCaseDataForWorkAllocation(null, null, INDIVIDUAL, applicant1DQ, respondent1DQ, + respondent2DQ); + CaseData result = service.buildCaseData(caseData.toBuilder(), caseData, UserDetails.builder() + .email(APPLICANT_EMAIL_ID_CONSTANT).build(), CallbackParams.builder().toString()); + assertThat(result.getGeneralApplications().get(0).getValue().getCaseManagementLocation().getBaseLocation()) + .isEqualTo("11111"); + assertThat(result.getGeneralApplications().get(0).getValue().getCaseManagementLocation().getSiteName()) + .isEqualTo("locationOfRegion2"); + assertThat(result.getGeneralApplications().get(0).getValue().getCaseManagementLocation().getAddress()) + .isEqualTo("Prince William House, Peel Cross Road, Salford"); + assertThat(result.getGeneralApplications().get(0).getValue().getCaseManagementLocation().getPostcode()) + .isEqualTo("M5 4RR"); + } + + protected List getSampleCourLocationsRefObject() { + return new ArrayList<>(List.of( + LocationRefData.builder() + .epimmsId("11111").siteName("locationOfRegion2").courtAddress("Prince William House, Peel Cross Road, Salford") + .postcode("M5 4RR") + .courtLocationCode("court1").build() + )); + } + + protected List getEmptyCourLocationsRefObject() { + return new ArrayList<>(List.of( + LocationRefData.builder().build() + )); + } + + protected List getSampleCourtLocationsRefObjectMultipleValues() { + return new ArrayList<>(List.of( + LocationRefData.builder() + .epimmsId("11111").siteName("locationOfRegion2").courtAddress("Prince William House, Peel Cross Road, Salford") + .postcode("M5 4RR") + .courtLocationCode("court1").build(), + + LocationRefData.builder() + .epimmsId("11111").siteName("locationOfRegion2").courtAddress("Prince William House, Peel Cross Road, Salford") + .postcode("M5 4RR") + .courtLocationCode("court1").build() + )); + } + + @Test + void shouldPopulateLocationDetailsForBaseLocationWhereListIsEmpty() { + when(locationRefDataService.getCourtLocationsByEpimmsId(any(), any())).thenReturn(getEmptyCourLocationsRefObject()); + CaseData caseData = GeneralApplicationDetailsBuilder.builder() + .getCaseDataForWorkAllocation(null, null, INDIVIDUAL, applicant1DQ, respondent1DQ, + respondent2DQ); + CaseData result = service.buildCaseData(caseData.toBuilder(), caseData, UserDetails.builder() + .email(APPLICANT_EMAIL_ID_CONSTANT).build(), CallbackParams.builder().toString()); + assertThat(result.getGeneralApplications().get(0).getValue().getCaseManagementLocation().getBaseLocation()) + .isEqualTo("11111"); + assertThat(result.getGeneralApplications().get(0).getValue().getCaseManagementLocation().getSiteName()) + .isNull(); + assertThat(result.getGeneralApplications().get(0).getValue().getCaseManagementLocation().getAddress()) + .isNull(); + assertThat(result.getGeneralApplications().get(0).getValue().getCaseManagementLocation().getPostcode()) + .isNull(); + } + + @Test + void shouldPopulateLocationDetailsForBaseLocationWithMultipleListValues() { + when(locationRefDataService.getCourtLocationsByEpimmsId(any(), any())).thenReturn(getSampleCourtLocationsRefObjectMultipleValues()); + CaseData caseData = GeneralApplicationDetailsBuilder.builder() + .getCaseDataForWorkAllocation(null, null, INDIVIDUAL, applicant1DQ, respondent1DQ, + respondent2DQ); + CaseData result = service.buildCaseData(caseData.toBuilder(), caseData, UserDetails.builder() + .email(APPLICANT_EMAIL_ID_CONSTANT).build(), CallbackParams.builder().toString()); + assertThat(result.getGeneralApplications().get(0).getValue().getCaseManagementLocation().getBaseLocation()) + .isEqualTo("11111"); + assertThat(result.getGeneralApplications().get(0).getValue().getCaseManagementLocation().getSiteName()) + .isEqualTo("locationOfRegion2"); + assertThat(result.getGeneralApplications().get(0).getValue().getCaseManagementLocation().getAddress()) + .isEqualTo("Prince William House, Peel Cross Road, Salford"); + assertThat(result.getGeneralApplications().get(0).getValue().getCaseManagementLocation().getPostcode()) + .isEqualTo("M5 4RR"); + } + @Test void shouldPopulateWorkAllocationLocationOnAboutToSubmit_beforeSDOHasBeenMade() { when(locationRefDataService.getCcmccLocation(any())) diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/OrganisationDetailsServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/OrganisationDetailsServiceTest.java new file mode 100644 index 00000000000..4beaee8238b --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/OrganisationDetailsServiceTest.java @@ -0,0 +1,109 @@ +package uk.gov.hmcts.reform.civil.service; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import uk.gov.hmcts.reform.ccd.model.OrganisationPolicy; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.prd.model.Organisation; +import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@ExtendWith(SpringExtension.class) +public class OrganisationDetailsServiceTest { + + @Mock + private OrganisationService organisationService; + + @InjectMocks + private OrganisationDetailsService organisationDetailsService; + + private final Organisation organisation = Organisation.builder().name("test org").build(); + + @Test + void shouldReturnApplicantOrgNameWhenOrgNameExist() { + when(organisationService.findOrganisationById(any())).thenReturn(Optional.ofNullable(organisation)); + //Given + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimDraft() + .legacyCaseReference("100MC001") + .applicant1OrganisationPolicy(OrganisationPolicy.builder() + .organisation(uk.gov.hmcts.reform.ccd.model.Organisation.builder() + .organisationID("test org") + .build()) + .build()) + .build(); + + caseData.getApplicantSolicitor1ClaimStatementOfTruth().setName("OrgClaimName"); + //When + String organisationID = organisationDetailsService.getApplicantLegalOrganizationName(caseData); + //Then + assertThat(organisationID).isEqualTo("test org"); + } + + @Test + void shouldGetApplicantSolicitor1ClaimStatementOfTruthName_whenNoOrgFound() { + when(organisationService.findOrganisationById(any())).thenReturn(Optional.empty()); + //Given + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimDraft() + .legacyCaseReference("100MC001") + .applicant1OrganisationPolicy(OrganisationPolicy.builder() + .organisation(uk.gov.hmcts.reform.ccd.model.Organisation.builder() + .organisationID("test org") + .build()) + .build()) + .build(); + caseData.getApplicantSolicitor1ClaimStatementOfTruth().setName("OrgClaimName"); + + //When + String organisationID = organisationDetailsService.getApplicantLegalOrganizationName(caseData); + + //Then + assertThat(organisationID).isEqualTo("OrgClaimName"); + } + + @Test + void shouldReturnRespondent1OrgNameWhenOrgNameExist() { + when(organisationService.findOrganisationById(any())).thenReturn(Optional.ofNullable(organisation)); + //Given + CaseData caseData = CaseDataBuilder.builder() + .legacyCaseReference("100MC001") + .applicant1OrganisationPolicy(OrganisationPolicy.builder() + .organisation(uk.gov.hmcts.reform.ccd.model.Organisation.builder() + .organisationID("test org") + .build()) + .build()) + .build(); + //When + String organisationID = organisationDetailsService.getRespondentLegalOrganizationName(caseData); + //Then + assertThat(organisationID).isEqualTo("test org"); + } + + @Test + void shouldReturnNullForRespondent1OrgName_whenNoOrgFound() { + when(organisationService.findOrganisationById(any())).thenReturn(Optional.empty()); + //Given + CaseData caseData = CaseDataBuilder.builder() + .legacyCaseReference("100MC001") + .applicant1OrganisationPolicy(OrganisationPolicy.builder() + .organisation(uk.gov.hmcts.reform.ccd.model.Organisation.builder() + .organisationID("test org") + .build()) + .build()) + .build(); + //When + String organisationID = organisationDetailsService.getRespondentLegalOrganizationName(caseData); + //Then + assertNull(organisationID); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/SendSDOBulkPrintServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/SendSDOBulkPrintServiceTest.java index a0e1c3ef842..bfd9f7732f2 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/SendSDOBulkPrintServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/SendSDOBulkPrintServiceTest.java @@ -41,6 +41,7 @@ class SendSDOBulkPrintServiceTest { private static final String TEST = "test"; private static final Document DOCUMENT_LINK = new Document("document/url", TEST, TEST, TEST, TEST); private static final byte[] LETTER_CONTENT = new byte[]{37, 80, 68, 70, 45, 49, 46, 53, 10, 37, -61, -92}; + private static final String BEARER_TOKEN = "BEARER_TOKEN"; @Test void shouldDownloadDocumentAndPrintLetterSuccessfully() { @@ -50,10 +51,10 @@ void shouldDownloadDocumentAndPrintLetterSuccessfully() { .systemGeneratedCaseDocuments(wrapElements(CaseDocument.builder().documentType(SDO_ORDER).documentLink(DOCUMENT_LINK).build())) .respondent1(respondent1) .build(); - given(documentDownloadService.downloadDocument(any())).willReturn(new DownloadedDocumentResponse(new ByteArrayResource(LETTER_CONTENT), "test", "test")); + given(documentDownloadService.downloadDocument(any(), any())).willReturn(new DownloadedDocumentResponse(new ByteArrayResource(LETTER_CONTENT), "test", "test")); // when - sendSDOBulkPrintService.sendSDOToDefendantLIP(caseData); + sendSDOBulkPrintService.sendSDOToDefendantLIP(BEARER_TOKEN, caseData); // then verify(bulkPrintService) .printLetter( @@ -72,7 +73,7 @@ void shouldNotDownloadDocument_whenNull() { .systemGeneratedCaseDocuments(null).build(); // when - sendSDOBulkPrintService.sendSDOToDefendantLIP(caseData); + sendSDOBulkPrintService.sendSDOToDefendantLIP(BEARER_TOKEN, caseData); // then verifyNoInteractions(bulkPrintService); @@ -85,7 +86,7 @@ void shouldNotDownloadDocument_whenSDOOrderAbsent() { .systemGeneratedCaseDocuments(wrapElements(CaseDocument.builder().documentType(SEALED_CLAIM).build())).build(); // when - sendSDOBulkPrintService.sendSDOToDefendantLIP(caseData); + sendSDOBulkPrintService.sendSDOToDefendantLIP(BEARER_TOKEN, caseData); // then verifyNoInteractions(bulkPrintService); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/SystemGeneratedDocumentServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/SystemGeneratedDocumentServiceTest.java index f91fd762a1e..528cf806959 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/SystemGeneratedDocumentServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/SystemGeneratedDocumentServiceTest.java @@ -4,43 +4,51 @@ import uk.gov.hmcts.reform.civil.callback.CallbackParams; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.documentmanagement.model.Document; -import uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.citizenui.TranslatedDocument; import uk.gov.hmcts.reform.civil.model.common.Element; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; +import static uk.gov.hmcts.reform.civil.model.citizenui.TranslatedDocumentType.DEFENDANT_RESPONSE; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.element; class SystemGeneratedDocumentServiceTest { - private static final String FILE_NAME = "Important file"; + private static final String FILE_NAME_1 = "Some file 1"; + private SystemGeneratedDocumentService systemGeneratedDocumentService = new SystemGeneratedDocumentService(); @Test void shouldAddDocumentToSystemGeneratedDocuments() { //Given - Document document = Document.builder().documentFileName(FILE_NAME).build(); + TranslatedDocument translatedDocument1 = TranslatedDocument + .builder() + .documentType(DEFENDANT_RESPONSE) + .file(Document.builder().documentFileName(FILE_NAME_1).build()) + .build(); + + List> translatedDocument = List.of( + element(translatedDocument1) + ); CaseData caseData = CaseData.builder().systemGeneratedCaseDocuments(new ArrayList<>()) .build(); CallbackParams callbackParams = CallbackParams.builder().caseData(caseData).build(); //When List> result = systemGeneratedDocumentService - .getSystemGeneratedDocumentsWithAddedDocument( - document, - DocumentType.DEFENDANT_DEFENCE, - callbackParams - ); + .getSystemGeneratedDocumentsWithAddedDocument(translatedDocument, callbackParams); + //Then assertThat(result.get(0)).isNotNull(); - assertThat(result.get(0).getValue().getDocumentName()).isEqualTo(FILE_NAME); + assertThat(result.get(0).getValue().getDocumentName()).isEqualTo(FILE_NAME_1); } @Test void shouldAddCaseDocumentToSystemGeneratedDocuments() { //Given - CaseDocument caseDocument = CaseDocument.builder().documentName(FILE_NAME).build(); + CaseDocument caseDocument = CaseDocument.builder().documentName(FILE_NAME_1).build(); CaseData caseData = CaseData.builder().systemGeneratedCaseDocuments(new ArrayList<>()) .build(); //When @@ -51,6 +59,6 @@ void shouldAddCaseDocumentToSystemGeneratedDocuments() { ); //Then assertThat(result.get(0)).isNotNull(); - assertThat(result.get(0).getValue().getDocumentName()).isEqualTo(FILE_NAME); + assertThat(result.get(0).getValue().getDocumentName()).isEqualTo(FILE_NAME_1); } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/AllowanceCalculatorTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/AllowanceCalculatorTest.java new file mode 100644 index 00000000000..21fc02db658 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/AllowanceCalculatorTest.java @@ -0,0 +1,102 @@ +package uk.gov.hmcts.reform.civil.service.citizen.repaymentplan; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.ChildrenByAgeGroupLRspec; +import uk.gov.hmcts.reform.civil.model.PartnerAndDependentsLRspec; +import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.model.UnemployedComplexTypeLRspec; +import uk.gov.hmcts.reform.civil.model.allowance.DisabilityAllowance; +import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; +import uk.gov.hmcts.reform.civil.model.citizenui.FinancialDetailsLiP; + +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static uk.gov.hmcts.reform.civil.model.allowance.PensionerAllowance.SINGLE; +import static uk.gov.hmcts.reform.civil.model.allowance.PersonalAllowance.SINGLE_UNDER_25; +import static uk.gov.hmcts.reform.civil.service.citizen.repaymentplan.AllowanceCalculator.RETIRED; + +@ExtendWith(MockitoExtension.class) +class AllowanceCalculatorTest { + + @Mock + private CaseData caseData; + @Mock + private CaseDataLiP caseDataLiP; + @Mock + private PartnerAndDependentsLRspec partnerAndDependants; + @Mock + private ChildrenByAgeGroupLRspec children; + @Mock + private UnemployedComplexTypeLRspec unemploymentType; + @Mock + private FinancialDetailsLiP defendantFinancialDetailsLiP; + @Mock + private Party respondent1; + + private AllowanceCalculator allowanceCalculator; + + @BeforeEach + void setUp() { + allowanceCalculator = new AllowanceCalculator(); + given(caseData.getCaseDataLiP()).willReturn(caseDataLiP); + given(caseDataLiP.getRespondent1LiPFinancialDetails()).willReturn(defendantFinancialDetailsLiP); + given(caseData.getRespondent1()).willReturn(respondent1); + given(respondent1.getDateOfBirth()).willReturn(LocalDate.of(2000, 1, 1)); + } + + @Test + void shouldCalculateAllowanceWithNoPartnerInformation() { + //Given + double expectedResultWithPersonalAllowance = 250.90; + //When + double actualResult = allowanceCalculator.calculateAllowance(caseData); + //Then + assertThat(actualResult).isEqualTo(expectedResultWithPersonalAllowance); + } + + @Test + void shouldCalculateDependantsAllowance() { + //Given + given(caseData.getRespondent1PartnerAndDependent()).willReturn(partnerAndDependants); + given(partnerAndDependants.getSupportPeopleNumber()).willReturn("2"); + given(partnerAndDependants.getHowManyChildrenByAgeGroup()).willReturn(children); + given(children.getTotalChildren()).willReturn(3); + double expectedResultWithDependantsAndPersonalSingleAllowance = 1700.4; + //When + double actualResult = allowanceCalculator.calculateAllowance(caseData); + //Then + assertThat(actualResult).isEqualTo(expectedResultWithDependantsAndPersonalSingleAllowance); + } + + @Test + void shouldCalculatePensionerAllowance() { + //Given + double expectedResultWithPersonalAllowanceAndPension = SINGLE.getAllowance() + SINGLE_UNDER_25.getAllowance(); + given(caseData.getRespondToClaimAdmitPartUnemployedLRspec()).willReturn(unemploymentType); + given(unemploymentType.getUnemployedComplexTypeRequired()).willReturn(RETIRED); + //When + double actualResult = allowanceCalculator.calculateAllowance(caseData); + //Then + assertThat(actualResult).isEqualTo(expectedResultWithPersonalAllowanceAndPension); + } + + @Test + void shouldCalculateDisabilityAllowance() { + //Given + double expectedResultWithPersonalAllowanceAndSingleDisability = SINGLE_UNDER_25.getAllowance() + + DisabilityAllowance.SINGLE.getAllowance(); + given(caseData.getDisabilityPremiumPayments()).willReturn(YesOrNo.YES); + //When + double actualResult = allowanceCalculator.calculateAllowance(caseData); + //Then + assertThat(actualResult).isEqualTo(expectedResultWithPersonalAllowanceAndSingleDisability); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/ExpenditureCalculatorTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/ExpenditureCalculatorTest.java new file mode 100644 index 00000000000..a43a7d21b95 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/ExpenditureCalculatorTest.java @@ -0,0 +1,127 @@ +package uk.gov.hmcts.reform.civil.service.citizen.repaymentplan; + +import org.junit.jupiter.api.Test; +import uk.gov.hmcts.reform.civil.enums.DebtTypeLRspec; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.model.DebtLRspec; +import uk.gov.hmcts.reform.civil.model.LoanCardDebtLRspec; +import uk.gov.hmcts.reform.civil.model.Respondent1CourtOrderDetails; +import uk.gov.hmcts.reform.civil.model.Respondent1DebtLRspec; +import uk.gov.hmcts.reform.civil.model.common.Element; +import uk.gov.hmcts.reform.civil.model.dq.RecurringExpenseLRspec; + +import java.math.BigDecimal; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.gov.hmcts.reform.civil.enums.PaymentFrequencyLRspec.ONCE_TWO_WEEKS; +import static uk.gov.hmcts.reform.civil.enums.dq.ExpenseTypeLRspec.MORTGAGE; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; + +class ExpenditureCalculatorTest { + + @Test + void shouldCalculateMonthlyExpenses() { + //Given + double expectedResult = 433.0; + List> expenses = createExpensesList(); + //When + double result = new ExpenditureCalculator() + .calculateTotalExpenditure(expenses, null, null); + //Then + assertThat(result).isEqualTo(expectedResult); + } + + @Test + void shouldCalculateDebtsWithoutCreditCards() { + //Given + double expectedResult = 433.0; + Respondent1DebtLRspec debtsWithoutCreditCardDebts = createDebtsWithoutCreditCard(); + //When + double result = new ExpenditureCalculator() + .calculateTotalExpenditure(null, debtsWithoutCreditCardDebts, null); + //Then + assertThat(result).isEqualTo(expectedResult); + } + + @Test + void shouldCalculateDebtsWitCreditCards() { + //Given + double expectedResult = 733.0; + Respondent1DebtLRspec debtsWithCreditCardDebts = createDebtWithCreditCard(); + //When + double result = new ExpenditureCalculator() + .calculateTotalExpenditure(null, debtsWithCreditCardDebts, null); + //Then + assertThat(result).isEqualTo(expectedResult); + } + + @Test + void shouldCalculateCourtOrders() { + //Given + double expectedResult = 300.0; + List> courtOrders = createCourtOrders(); + //When + double result = new ExpenditureCalculator() + .calculateTotalExpenditure(null, null, courtOrders); + //Then + assertThat(result).isEqualTo(expectedResult); + } + + @Test + void shouldCalculateTotalExpenditure() { + //Given + double expectedResult = 1466.0; + List> expenses = createExpensesList(); + Respondent1DebtLRspec debtsWithCreditCardDebts = createDebtWithCreditCard(); + List> courtOrders = createCourtOrders(); + //When + double result = new ExpenditureCalculator() + .calculateTotalExpenditure(expenses, debtsWithCreditCardDebts, courtOrders); + //Then + assertThat(result).isEqualTo(expectedResult); + } + + private List> createExpensesList() { + return wrapElements(RecurringExpenseLRspec.builder() + .amount(new BigDecimal(20000)) + .frequency(ONCE_TWO_WEEKS) + .type(MORTGAGE) + .build()); + } + + private Respondent1DebtLRspec createDebtsWithoutCreditCard() { + return Respondent1DebtLRspec.builder() + .debtDetails(createDebts()) + .hasLoanCardDebt(YesOrNo.NO) + .build(); + } + + private Respondent1DebtLRspec createDebtWithCreditCard() { + return Respondent1DebtLRspec.builder() + .debtDetails(createDebts()) + .hasLoanCardDebt(YesOrNo.YES) + .loanCardDebtDetails(createLoanCardDents()) + .build(); + } + + private List> createDebts() { + return wrapElements(DebtLRspec.builder() + .debtType(DebtTypeLRspec.MORTGAGE) + .paymentAmount(new BigDecimal(20000)) + .paymentFrequency(ONCE_TWO_WEEKS) + .build()); + } + + private List> createLoanCardDents() { + return wrapElements(LoanCardDebtLRspec.builder() + .monthlyPayment(new BigDecimal(30000)) + .build()); + } + + private List> createCourtOrders() { + return wrapElements(Respondent1CourtOrderDetails.builder() + .monthlyInstalmentAmount(new BigDecimal(30000)) + .build()); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/IncomeCalculatorTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/IncomeCalculatorTest.java new file mode 100644 index 00000000000..7a7104c4afd --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/IncomeCalculatorTest.java @@ -0,0 +1,131 @@ +package uk.gov.hmcts.reform.civil.service.citizen.repaymentplan; + +import org.junit.jupiter.api.Test; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.model.Respondent1SelfEmploymentLRspec; +import uk.gov.hmcts.reform.civil.model.account.AccountSimple; +import uk.gov.hmcts.reform.civil.model.common.Element; +import uk.gov.hmcts.reform.civil.model.dq.RecurringIncomeLRspec; + +import java.math.BigDecimal; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.gov.hmcts.reform.civil.enums.PaymentFrequencyLRspec.ONCE_THREE_WEEKS; +import static uk.gov.hmcts.reform.civil.enums.PaymentFrequencyLRspec.ONCE_TWO_WEEKS; +import static uk.gov.hmcts.reform.civil.enums.dq.IncomeTypeLRspec.JOB; +import static uk.gov.hmcts.reform.civil.model.account.AccountType.CURRENT; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; + +class IncomeCalculatorTest { + + @Test + void shouldCalculateTotalSavings_positiveOnlyValues() { + //Given + double expectedResult = 1500.55; + List> bankAccountElements = createBankAccountsWithPositiveAndNegativeBalance(); + //When + double result = new IncomeCalculator().calculateTotalMonthlyIncome(bankAccountElements, null, null); + //Then + assertThat(result).isEqualTo(expectedResult); + } + + @Test + void shouldCalculateTotalRegularIncome_positiveValuesOnly() { + //Given + double expectedResult = 2384.0; + List> recurringIncomeList = createRecurringIncomeWithPositiveAndNegativeAmount(); + //When + double result = new IncomeCalculator().calculateTotalMonthlyIncome(null, recurringIncomeList, null); + //Then + assertThat(result).isEqualTo(expectedResult); + } + + @Test + void shouldCalculateMonthlyIncomeFromAnnualTurnover() { + //Given + double expectedResult = 5583.33; + Respondent1SelfEmploymentLRspec annualTurnover = createAnnualIncome(); + //When + double result = new IncomeCalculator().calculateTotalMonthlyIncome(null, null, annualTurnover); + //Then + assertThat(result).isEqualTo(expectedResult); + } + + @Test + void shouldCombineTotalSavingsMonthlyIncomeMonthlyTurnoverInIncomeCalculation() { + //Given + double expectedResult = 9467.88; + Respondent1SelfEmploymentLRspec annualTurnover = createAnnualIncome(); + List> bankAccountElements = createBankAccountsWithPositiveAndNegativeBalance(); + List> recurringIncomeList = createRecurringIncomeWithPositiveAndNegativeAmount(); + //When + double result = new IncomeCalculator().calculateTotalMonthlyIncome( + bankAccountElements, + recurringIncomeList, + annualTurnover + ); + //Then + assertThat(result).isEqualTo(expectedResult); + } + + @Test + void shouldReturnZero_whenNoIncome() { + //Given + double expectedResult = 0.00; + //When + double result = new IncomeCalculator().calculateTotalMonthlyIncome(null, null, null); + //Then + assertThat(result).isEqualTo(expectedResult); + + } + + private static List> createBankAccountsWithPositiveAndNegativeBalance() { + List> bankAccountElements = + wrapElements( + AccountSimple.builder() + .balance(new BigDecimal(1000.55)) + .jointAccount(YesOrNo.YES) + .accountType(CURRENT) + .build(), + AccountSimple.builder() + .balance(new BigDecimal(-789)) + .jointAccount(YesOrNo.NO) + .accountType(CURRENT) + .build(), + AccountSimple.builder() + .balance(new BigDecimal(500)) + .jointAccount(YesOrNo.YES) + .accountType(CURRENT) + .build() + ); + return bankAccountElements; + } + + private static List> createRecurringIncomeWithPositiveAndNegativeAmount() { + return + wrapElements( + RecurringIncomeLRspec.builder() + .amount(new BigDecimal(10000)) + .frequency(ONCE_TWO_WEEKS) + .type(JOB) + .build(), + RecurringIncomeLRspec.builder() + .amount(new BigDecimal(-6000)) + .frequency(ONCE_TWO_WEEKS) + .type(JOB) + .build(), + RecurringIncomeLRspec.builder() + .amount(new BigDecimal(150000)) + .frequency(ONCE_THREE_WEEKS) + .type(JOB) + .build() + ); + } + + private static Respondent1SelfEmploymentLRspec createAnnualIncome() { + return Respondent1SelfEmploymentLRspec.builder() + .annualTurnover(new BigDecimal(6700000)) + .build(); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/RepaymentPlanDecisionCalculatorTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/RepaymentPlanDecisionCalculatorTest.java new file mode 100644 index 00000000000..4c1af3e6811 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/citizen/repaymentplan/RepaymentPlanDecisionCalculatorTest.java @@ -0,0 +1,238 @@ +package uk.gov.hmcts.reform.civil.service.citizen.repaymentplan; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.RepaymentPlanLRspec; +import uk.gov.hmcts.reform.civil.model.RespondToClaimAdmitPartLRspec; +import uk.gov.hmcts.reform.civil.model.citizenui.dto.RepaymentDecisionType; +import uk.gov.hmcts.reform.civil.model.dq.Respondent1DQ; +import uk.gov.hmcts.reform.civil.model.repaymentplan.ClaimantProposedPlan; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec.BY_SET_DATE; +import static uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec.SUGGESTION_OF_REPAYMENT_PLAN; + +@ExtendWith(MockitoExtension.class) +class RepaymentPlanDecisionCalculatorTest { + + private static final double CALCULATED_INCOME = 2466.56; + private static final double CALCULATED_EXPENDITURE = 1500; + private static final double CALCULATED_ALLOWANCE = 400; + //Disposable income is 566.56; + private static final BigDecimal AFFORDABLE_CLAIM_TOTAL = new BigDecimal(300); + private static final BigDecimal UNAFFORDABLE_CLAIM_TOTAL = new BigDecimal(1000); + + @Mock + private IncomeCalculator incomeCalculator; + @Mock + private ExpenditureCalculator expenditureCalculator; + @Mock + private AllowanceCalculator allowanceCalculator; + @Mock + private CaseData caseData; + @Mock + private Respondent1DQ respondent1DQ; + @Mock + private RepaymentPlanLRspec defendantRepaymentPlan; + + @Mock + private ClaimantProposedPlan claimantProposedPlan; + @InjectMocks + private RepaymentPlanDecisionCalculator repaymentPlanDecisionCalculator; + + @BeforeEach + void setUp() { + given(incomeCalculator.calculateTotalMonthlyIncome(any(), any(), any())).willReturn(CALCULATED_INCOME); + given(expenditureCalculator.calculateTotalExpenditure(any(), any(), any())).willReturn(CALCULATED_EXPENDITURE); + given(allowanceCalculator.calculateAllowance(any())).willReturn(CALCULATED_ALLOWANCE); + given(caseData.getRespondent1DQ()).willReturn(respondent1DQ); + + } + + @Nested + class DecisionCalculationOnPayImmediatelyTest { + + @BeforeEach + void setUp() { + given(claimantProposedPlan.hasProposedPayImmediately()).willReturn(true); + } + + @Test + void shouldAcceptClaimantProposition_whenDefendantCanAffordIt() { + //Given + given(caseData.getRespondToAdmittedClaimOwingAmountPounds()).willReturn(AFFORDABLE_CLAIM_TOTAL); + //When + RepaymentDecisionType decision = repaymentPlanDecisionCalculator.calculateRepaymentDecision( + caseData, + claimantProposedPlan + ); + //Then + assertThat(decision.isInFavourOfDefendant()).isFalse(); + } + + @Test + void shouldDeclineClaimantProposition_whenDefendantCantAffordIt() { + //Given + given(caseData.getRespondToAdmittedClaimOwingAmountPounds()).willReturn(UNAFFORDABLE_CLAIM_TOTAL); + //When + RepaymentDecisionType decision = repaymentPlanDecisionCalculator.calculateRepaymentDecision( + caseData, + claimantProposedPlan + ); + //Then + assertThat(decision.isInFavourOfDefendant()).isTrue(); + } + } + + @Nested + class DecisionCalculationOnPayBySetDate { + + private static final LocalDate DEFENDANT_REPAYMENT_DATE = LocalDate.of(2023, 9, 22); + private static final LocalDate CLAIMANT_PROPOSED_DATE_BEFORE_DEFENDANT_DATE = LocalDate.of(2023, 8, 22); + private static final LocalDate CLAIMANT_PROPOSED_DATE_AFTER_DEFENDANT_DATE = LocalDate.of(2023, 10, 22); + + @Mock + private RespondToClaimAdmitPartLRspec respondToClaimAdmitPartLRspec; + + @BeforeEach + void setUp() { + given(claimantProposedPlan.hasProposedPayBySetDate()).willReturn(true); + } + + @Test + void shouldReturnRepaymentDateByDefendant_whenDefendantChosePayBySetDate() { + //Given + given(caseData.getDefenceAdmitPartPaymentTimeRouteRequired()).willReturn(BY_SET_DATE); + given(caseData.getRespondToClaimAdmitPartLRspec()).willReturn(respondToClaimAdmitPartLRspec); + given(respondToClaimAdmitPartLRspec.getWhenWillThisAmountBePaid()).willReturn(DEFENDANT_REPAYMENT_DATE); + given(caseData.getRespondToAdmittedClaimOwingAmountPounds()).willReturn(UNAFFORDABLE_CLAIM_TOTAL); + given(claimantProposedPlan.getRepaymentByDate()).willReturn(CLAIMANT_PROPOSED_DATE_BEFORE_DEFENDANT_DATE); + //When + repaymentPlanDecisionCalculator.calculateRepaymentDecision( + caseData, + claimantProposedPlan + ); + //Then + verify(caseData).getRespondToClaimAdmitPartLRspec(); + } + + @Test + void shouldReturnFinalDateOfDefendantRepaymentPlan_whenDefendantChosePayByInstallments() { + //Given + given(caseData.getDefenceAdmitPartPaymentTimeRouteRequired()).willReturn(SUGGESTION_OF_REPAYMENT_PLAN); + given(caseData.getRespondent1RepaymentPlan()).willReturn(defendantRepaymentPlan); + given(defendantRepaymentPlan.finalPaymentBy(any())).willReturn(DEFENDANT_REPAYMENT_DATE); + given(caseData.getRespondToAdmittedClaimOwingAmountPounds()).willReturn(UNAFFORDABLE_CLAIM_TOTAL); + given(claimantProposedPlan.getRepaymentByDate()).willReturn(CLAIMANT_PROPOSED_DATE_BEFORE_DEFENDANT_DATE); + //When + repaymentPlanDecisionCalculator.calculateRepaymentDecision( + caseData, + claimantProposedPlan + ); + //Then + verify(caseData, never()).getRespondToClaimAdmitPartLRspec(); + verify(caseData).getRespondent1RepaymentPlan(); + } + + @Test + void shouldChooseClaimantPlan_whenDefednantCanAfford() { + //Given + given(caseData.getRespondToAdmittedClaimOwingAmountPounds()).willReturn(AFFORDABLE_CLAIM_TOTAL); + //When + RepaymentDecisionType decision = repaymentPlanDecisionCalculator.calculateRepaymentDecision( + caseData, + claimantProposedPlan + ); + //Then + assertThat(decision.isInFavourOfDefendant()).isFalse(); + } + + @Test + void shouldChooseClaimantPlan_whenDefendantCantAffordAndClaimantPayDateIsAfterDefendantPayDate() { + //Given + given(caseData.getDefenceAdmitPartPaymentTimeRouteRequired()).willReturn(BY_SET_DATE); + given(caseData.getRespondToClaimAdmitPartLRspec()).willReturn(respondToClaimAdmitPartLRspec); + given(respondToClaimAdmitPartLRspec.getWhenWillThisAmountBePaid()).willReturn(DEFENDANT_REPAYMENT_DATE); + given(caseData.getRespondToAdmittedClaimOwingAmountPounds()).willReturn(UNAFFORDABLE_CLAIM_TOTAL); + given(claimantProposedPlan.getRepaymentByDate()).willReturn(CLAIMANT_PROPOSED_DATE_AFTER_DEFENDANT_DATE); + //When + RepaymentDecisionType decision = repaymentPlanDecisionCalculator.calculateRepaymentDecision( + caseData, + claimantProposedPlan + ); + //Then + assertThat(decision.isInFavourOfDefendant()).isFalse(); + } + + @Test + void shouldChooseDefendantPlan_whenDefendantCantAffordAndClaimantDateIsBeforeDefendantPayDate() { + //Given + given(caseData.getDefenceAdmitPartPaymentTimeRouteRequired()).willReturn(BY_SET_DATE); + given(caseData.getRespondToClaimAdmitPartLRspec()).willReturn(respondToClaimAdmitPartLRspec); + given(respondToClaimAdmitPartLRspec.getWhenWillThisAmountBePaid()).willReturn(DEFENDANT_REPAYMENT_DATE); + given(caseData.getRespondToAdmittedClaimOwingAmountPounds()).willReturn(UNAFFORDABLE_CLAIM_TOTAL); + given(claimantProposedPlan.getRepaymentByDate()).willReturn(CLAIMANT_PROPOSED_DATE_BEFORE_DEFENDANT_DATE); + + //When + RepaymentDecisionType decision = repaymentPlanDecisionCalculator.calculateRepaymentDecision( + caseData, + claimantProposedPlan + ); + //Then + assertThat(decision.isInFavourOfDefendant()).isTrue(); + } + } + + @Nested + class DecisionCalculationOnPayByInstalments { + + @Mock + private RepaymentPlanLRspec claimantRepaymentPlan; + + @BeforeEach + void setUp() { + given(claimantProposedPlan.hasProposedPayByInstallments()).willReturn(true); + } + + @Test + void shouldAcceptClaimantProposal_whenDefendantCanAffordIt() { + //Given + given(claimantProposedPlan.getCalculatedPaymentPerMonthFromRepaymentPlan()).willReturn( + AFFORDABLE_CLAIM_TOTAL.doubleValue()); + //When + RepaymentDecisionType decision = repaymentPlanDecisionCalculator.calculateRepaymentDecision( + caseData, + claimantProposedPlan + ); + //Then + assertThat(decision.isInFavourOfDefendant()).isFalse(); + } + + @Test + void shouldDeclineClaimantProposal_whenDefendantCantAffordIt() { + //Given + given(claimantProposedPlan.getCalculatedPaymentPerMonthFromRepaymentPlan()).willReturn( + UNAFFORDABLE_CLAIM_TOTAL.doubleValue()); + //When + RepaymentDecisionType decision = repaymentPlanDecisionCalculator.calculateRepaymentDecision( + caseData, + claimantProposedPlan + ); + //Then + assertThat(decision.isInFavourOfDefendant()).isTrue(); + } + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/citizenui/DashboardClaimInfoServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/citizenui/DashboardClaimInfoServiceTest.java index 0bdd31655fc..c5b82cc4fed 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/citizenui/DashboardClaimInfoServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/citizenui/DashboardClaimInfoServiceTest.java @@ -1,11 +1,13 @@ package uk.gov.hmcts.reform.civil.service.citizenui; +import org.elasticsearch.common.inject.Inject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; import org.mockito.Mock; -import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import uk.gov.hmcts.reform.ccd.client.model.CaseDetails; import uk.gov.hmcts.reform.ccd.client.model.SearchResult; import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; @@ -17,12 +19,14 @@ import uk.gov.hmcts.reform.civil.model.citizenui.DashboardClaimStatusFactory; import uk.gov.hmcts.reform.civil.model.citizenui.DashboardResponse; import uk.gov.hmcts.reform.civil.service.CoreCaseDataService; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.civil.service.claimstore.ClaimStoreService; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -30,7 +34,8 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; -@ExtendWith(SpringExtension.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class DashboardClaimInfoServiceTest { private static final String CLAIMANT_NAME = "Harry Porter"; @@ -45,10 +50,13 @@ public class DashboardClaimInfoServiceTest { @Mock private CaseDetailsConverter caseDetailsConverter; + @Mock + private FeatureToggleService featureToggleService; + @Mock private DashboardClaimStatusFactory dashboardClaimStatusFactory; - @InjectMocks + @Inject private DashboardClaimInfoService dashboardClaimInfoService; private static final BigDecimal PART_ADMIT_PAY_IMMEDIATELY_AMOUNT = BigDecimal.valueOf(500); @@ -56,10 +64,10 @@ public class DashboardClaimInfoServiceTest { private static final LocalDateTime DATE_IN_2022 = LocalDateTime.of(2022, 2, 20, 0, 0); private static final LocalDateTime DATE_IN_2025 = LocalDateTime.of(2025, 2, 20, 0, 0); private static final List CLAIM_STORE_SERVICE_RESULTS = - Arrays.asList(DashboardClaimInfo.builder() - .ocmc(true) - .createdDate(DATE_IN_2025) - .build()); + Collections.singletonList(DashboardClaimInfo.builder() + .ocmc(true) + .createdDate(DATE_IN_2025) + .build()); private static final CaseDetails CASE_DETAILS = CaseDetails.builder() .id(1L) .createdDate(DATE_IN_2021) @@ -83,6 +91,15 @@ public class DashboardClaimInfoServiceTest { @BeforeEach void setUp() { + + dashboardClaimInfoService = new DashboardClaimInfoService( + caseDetailsConverter, + claimStoreService, + coreCaseDataService, + dashboardClaimStatusFactory, + featureToggleService + ); + given(claimStoreService.getClaimsForClaimant(any(), any())).willReturn(CLAIM_STORE_SERVICE_RESULTS); given(claimStoreService.getClaimsForDefendant(any(), any())).willReturn(CLAIM_STORE_SERVICE_RESULTS); @@ -127,7 +144,9 @@ void setUp() { } @Test - void shouldReturnClaimsForClaimantSuccessfully() { + void shouldReturnClaimsForClaimantSuccessfullyWhenLipVLipEnabled() { + given(featureToggleService.isLipVLipEnabled()).willReturn(true); + List cases = List.of(CASE_DETAILS, CASE_DETAILS_2); SearchResult searchResult = SearchResult.builder().total(cases.size()).cases(cases).build(); given(coreCaseDataService.getCCDClaimsForLipClaimant(any(), eq(0))).willReturn(searchResult); @@ -140,6 +159,19 @@ void shouldReturnClaimsForClaimantSuccessfully() { assertThat(claimsForClaimant.getClaims().get(2)).isEqualTo(CLAIM_STORE_SERVICE_RESULTS.get(0)); } + @Test + void shouldReturnOnlyOcmcClaimsForClaimantSuccessfullyWhenLipVLipDisabled() { + given(featureToggleService.isLipVLipEnabled()).willReturn(false); + + DashboardResponse claimsForClaimant = dashboardClaimInfoService.getDashboardClaimantResponse( + "authorisation", + "123", + CURRENT_PAGE_NO + ); + assertThat(claimsForClaimant.getClaims().size()).isEqualTo(1); + assertThat(claimsForClaimant.getClaims().get(0)).isEqualTo(CLAIM_STORE_SERVICE_RESULTS.get(0)); + } + @Test void shouldReturnClaimsForDefendantSuccessfully() { diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/citizenui/responsedeadline/DeadlineExtensionCalculatorServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/citizenui/responsedeadline/DeadlineExtensionCalculatorServiceTest.java index 736974f4cce..dcc0e6f718c 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/citizenui/responsedeadline/DeadlineExtensionCalculatorServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/citizenui/responsedeadline/DeadlineExtensionCalculatorServiceTest.java @@ -26,30 +26,54 @@ public class DeadlineExtensionCalculatorServiceTest { @Test void shouldReturnTheSameGivenDateWhenDateIsWorkday() { - given(workingDayIndicator.isWorkingDay(any())).willReturn(true); + given(workingDayIndicator.getNextWorkingDay(any())).willReturn(LocalDate.now()); LocalDate proposedExtensionDeadline = LocalDate.now(); LocalDate calculatedDeadline = deadlineExtensionCalculatorService.calculateExtendedDeadline( - proposedExtensionDeadline); + proposedExtensionDeadline, 0); assertThat(calculatedDeadline).isEqualTo(proposedExtensionDeadline); - verify(workingDayIndicator).isWorkingDay(proposedExtensionDeadline); - verify(workingDayIndicator, never()).getNextWorkingDay(proposedExtensionDeadline); + verify(workingDayIndicator).getNextWorkingDay(proposedExtensionDeadline); + verify(workingDayIndicator, never()).isWorkingDay(proposedExtensionDeadline); } @Test void shouldReturnNextWorkingDayWhenDateIsHoliday() { - given(workingDayIndicator.isWorkingDay(any())).willReturn(false); + LocalDate proposedExtensionDeadline = LocalDate.of(2022, 6, 3); LocalDate calculatedNextWorkingDay = LocalDate.of(2022, 6, 4); + given(workingDayIndicator.getNextWorkingDay(any())).willReturn(calculatedNextWorkingDay); - LocalDate proposedExtensionDeadline = LocalDate.of(2022, 6, 3); LocalDate calculatedDeadline = deadlineExtensionCalculatorService.calculateExtendedDeadline( - proposedExtensionDeadline); + proposedExtensionDeadline, 0); assertThat(calculatedDeadline).isEqualTo(calculatedNextWorkingDay); - verify(workingDayIndicator).isWorkingDay(proposedExtensionDeadline); - verify(workingDayIndicator).getNextWorkingDay(proposedExtensionDeadline); + verify(workingDayIndicator, never()).isWorkingDay(calculatedNextWorkingDay); + } + + @Test + void shouldReturnFifthWorkingDayFromTheGivenDateWhen_NoHoliday_NoWeekend_InBetween() { + given(workingDayIndicator.isWorkingDay(any())).willReturn(true); + LocalDate proposedExtensionDeadline = LocalDate.of(2023, 11, 17); + LocalDate expectedExtensionDeadline = LocalDate.of(2023, 11, 22); + + LocalDate calculatedDeadline = deadlineExtensionCalculatorService.calculateExtendedDeadline( + proposedExtensionDeadline, 5); + + assertThat(calculatedDeadline).isEqualTo(expectedExtensionDeadline); + } + + @Test + void shouldReturnFifthWorkingDayFromTheGivenDateWhen_Holiday_InBetween() { + given(workingDayIndicator.isWorkingDay(any())).willReturn(true); + given(workingDayIndicator.isWorkingDay(LocalDate.of(2023, 11, 19))).willReturn(false); + LocalDate proposedExtensionDeadline = LocalDate.of(2023, 11, 17); + LocalDate expectedExtensionDeadline = LocalDate.of(2023, 11, 23); + + LocalDate calculatedDeadline = deadlineExtensionCalculatorService.calculateExtendedDeadline( + proposedExtensionDeadline, 5); + + assertThat(calculatedDeadline).isEqualTo(expectedExtensionDeadline); } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/RepresentativeServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/RepresentativeServiceTest.java index e1e00ec1211..6f0b54ba275 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/RepresentativeServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/RepresentativeServiceTest.java @@ -436,6 +436,39 @@ void shouldReturnValidOrganisationDetails_whenDefendantIsRepresentedAndHasNotPro ); } + @Test + void shouldReturnValidOrganisationDetails_whenOrganisationIDIsEmpty() { + CaseData caseData = CaseDataBuilder.builder().atStateClaimIssued() + .multiPartyClaimTwoDefendantSolicitors() + .applicantSolicitor1ServiceAddress(applicantSolicitorServiceAddress) + .build(); + + Representative representative = representativeService.getRespondent2Representative(caseData); + + verify(organisationService).findOrganisationById( + caseData.getRespondent2OrganisationPolicy().getOrganisation().getOrganisationID()); + assertThat(representative).extracting("organisationName").isEqualTo(respondent2Organisation.getName()); + assertThat(representative).extracting("dxAddress").isEqualTo( + respondent2ContactInformation.getDxAddress().get(0).getDxNumber()); + assertThat(representative).extracting("emailAddress").isEqualTo( + caseData.getRespondentSolicitor2EmailAddress()); + assertThat(representative).extracting("serviceAddress").extracting( + "AddressLine1", + "AddressLine2", + "AddressLine3", + "County", + "Country", + "PostCode" + ).containsExactly( + respondent2ContactInformation.getAddressLine1(), + respondent2ContactInformation.getAddressLine2(), + respondent2ContactInformation.getAddressLine3(), + respondent2ContactInformation.getCounty(), + respondent2ContactInformation.getCountry(), + respondent2ContactInformation.getPostCode() + ); + } + @Nested class ToBeRemovedAfterNOC { @BeforeEach diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/caseprogression/JudgeFinalOrderGeneratorTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/caseprogression/JudgeFinalOrderGeneratorTest.java index 8721cc9db97..4df8a53ee4d 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/caseprogression/JudgeFinalOrderGeneratorTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/caseprogression/JudgeFinalOrderGeneratorTest.java @@ -4,6 +4,9 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; @@ -13,16 +16,19 @@ import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.documentmanagement.model.PDF; import uk.gov.hmcts.reform.civil.enums.CaseState; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.enums.caseprogression.FinalOrderSelection; import uk.gov.hmcts.reform.civil.enums.finalorders.AppealList; +import uk.gov.hmcts.reform.civil.enums.finalorders.ApplicationAppealList; import uk.gov.hmcts.reform.civil.enums.finalorders.AssistedCostTypesList; -import uk.gov.hmcts.reform.civil.enums.finalorders.HearingLengthFinalOrderList; -import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrderToggle; +import uk.gov.hmcts.reform.civil.enums.finalorders.CostEnums; import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrderRepresentationList; -import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersJudgePapers; -import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersClaimantRepresentationList; +import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrderToggle; import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersClaimantDefendantNotAttending; +import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersClaimantRepresentationList; import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersDefendantRepresentationList; +import uk.gov.hmcts.reform.civil.enums.finalorders.FinalOrdersJudgePapers; +import uk.gov.hmcts.reform.civil.enums.finalorders.HearingLengthFinalOrderList; import uk.gov.hmcts.reform.civil.enums.finalorders.OrderMadeOnTypes; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.caseprogression.FreeFormOrderValues; @@ -31,6 +37,8 @@ import uk.gov.hmcts.reform.civil.model.common.MappableObject; import uk.gov.hmcts.reform.civil.model.docmosis.DocmosisDocument; +import uk.gov.hmcts.reform.civil.model.finalorders.AppealChoiceSecondDropdown; +import uk.gov.hmcts.reform.civil.model.finalorders.AppealGrantedRefused; import uk.gov.hmcts.reform.civil.model.finalorders.AssistedOrderCostDetails; import uk.gov.hmcts.reform.civil.model.finalorders.AssistedOrderReasons; import uk.gov.hmcts.reform.civil.model.finalorders.CaseHearingLengthElement; @@ -42,6 +50,7 @@ import uk.gov.hmcts.reform.civil.model.finalorders.FinalOrderRepresentation; import uk.gov.hmcts.reform.civil.model.finalorders.OrderMade; import uk.gov.hmcts.reform.civil.model.finalorders.OrderMadeOnDetails; +import uk.gov.hmcts.reform.civil.model.finalorders.OrderMadeOnDetailsOrderWithoutNotice; import uk.gov.hmcts.reform.civil.model.finalorders.TrialNoticeProcedure; import uk.gov.hmcts.reform.civil.referencedata.LocationRefDataService; import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; @@ -50,22 +59,36 @@ import uk.gov.hmcts.reform.civil.sampledata.PartyBuilder; import uk.gov.hmcts.reform.civil.service.docmosis.DocumentGeneratorService; import uk.gov.hmcts.reform.civil.service.docmosis.DocumentHearingLocationHelper; +import uk.gov.hmcts.reform.civil.utils.MonetaryConversions; import uk.gov.hmcts.reform.idam.client.IdamClient; import uk.gov.hmcts.reform.idam.client.models.UserDetails; +import java.math.BigDecimal; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.stream.Stream; +import static java.lang.String.format; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.documentmanagement.model.DocumentType.JUDGE_FINAL_ORDER; +import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; +import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; +import static uk.gov.hmcts.reform.civil.enums.finalorders.CostEnums.CLAIMANT; +import static uk.gov.hmcts.reform.civil.enums.finalorders.CostEnums.COSTS; +import static uk.gov.hmcts.reform.civil.enums.finalorders.CostEnums.DEFENDANT; +import static uk.gov.hmcts.reform.civil.enums.finalorders.CostEnums.INDEMNITY_BASIS; +import static uk.gov.hmcts.reform.civil.enums.finalorders.CostEnums.SUBJECT_DETAILED_ASSESSMENT; +import static uk.gov.hmcts.reform.civil.enums.hearing.HearingChannel.IN_PERSON; +import static uk.gov.hmcts.reform.civil.helpers.DateFormatHelper.formatLocalDate; import static uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates.ASSISTED_ORDER_PDF; import static uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates.FREE_FORM_ORDER_PDF; @@ -78,8 +101,9 @@ public class JudgeFinalOrderGeneratorTest { private static final String BEARER_TOKEN = "Bearer Token"; private static final byte[] bytes = {1, 2, 3, 4, 5, 6}; - private static final String fileFreeForm = String.format(FREE_FORM_ORDER_PDF.getDocumentTitle(), LocalDate.now()); - private static final String assistedForm = String.format(ASSISTED_ORDER_PDF.getDocumentTitle(), LocalDate.now()); + private static final String DATE_FORMAT = "dd/MM/yyyy"; + private static final String fileFreeForm = format(FREE_FORM_ORDER_PDF.getDocumentTitle(), formatLocalDate(LocalDate.now(), DATE_FORMAT)); + private static final String assistedForm = format(ASSISTED_ORDER_PDF.getDocumentTitle(), formatLocalDate(LocalDate.now(), DATE_FORMAT)); List toggleList = new ArrayList(Arrays.asList(FinalOrderToggle.SHOW)); private static final CaseDocument FREE_FROM_ORDER = CaseDocumentBuilder.builder() .documentName(fileFreeForm) @@ -104,7 +128,7 @@ public class JudgeFinalOrderGeneratorTest { @Autowired private JudgeFinalOrderGenerator generator; - private static LocationRefData locationRefData = LocationRefData.builder().siteName("SiteName") + private static LocationRefData locationRefData = LocationRefData.builder().siteName("SiteName") .courtAddress("1").postcode("1") .courtName("Court Name").region("Region").regionId("4").courtVenueId("000") .courtTypeId("10").courtLocationCode("121") @@ -188,7 +212,7 @@ void shouldGenerateFreeFormOrder_whenOrderWithoutNoticeIsSelected() { .thenReturn(FREE_FROM_ORDER); CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderSelection(FinalOrderSelection.FREE_FORM_ORDER) - .ccdState(CaseState.JUDICIAL_REFERRAL) + .ccdState(CaseState.CASE_PROGRESSION) .orderWithoutNotice(FreeFormOrderValues.builder().withoutNoticeSelectionTextArea("test without notice") .withoutNoticeSelectionDate(LocalDate.now()).build()) .respondent2(PartyBuilder.builder().individual().build().toBuilder() @@ -208,8 +232,8 @@ void shouldGenerateFreeFormOrder_whenOrderWithoutNoticeIsSelected() { } @Test - void shouldGenerateAssistedFormOrder_whenClaimantAndDefendantReferenceNotAddedToCase() { - //Given: case data with claimant and defendant ref not added + void shouldGenerateAssistedFormOrder_whenOptionalSectionsNotPresent() { + //Given: case data without recitals selected when(documentGeneratorService.generateDocmosisDocument(any(MappableObject.class), eq(ASSISTED_ORDER_PDF))) .thenReturn(new DocmosisDocument(ASSISTED_ORDER_PDF.getDocumentTitle(), bytes)); when(documentManagementService @@ -217,16 +241,37 @@ void shouldGenerateAssistedFormOrder_whenClaimantAndDefendantReferenceNotAddedTo .thenReturn(ASSISTED_FROM_ORDER); CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() - .solicitorReferences(null) - .finalOrderDateHeardComplex(OrderMade.builder().singleDateSelection(DatesFinalOrders.builder().singleDate(LocalDate.now()).build()).build()) + .ccdState(CaseState.CASE_PROGRESSION) .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) - .assistedOrderCostList(AssistedCostTypesList.NO_ORDER_TO_COST) + // Order made section + .finalOrderMadeSelection(NO) + // judge heard from section + .finalOrderJudgeHeardFrom(null) + // recitals section + .finalOrderRecitals(null) + // ordered section + .finalOrderOrderedThatText("order text") + // Further hearing section + .finalOrderFurtherHearingToggle(null) + .finalOrderFurtherHearingComplex(null) + // Costs section + .assistedOrderCostList(AssistedCostTypesList.COSTS_IN_THE_CASE) + .assistedOrderMakeAnOrderForCosts(null) + .assistedOrderMakeAnOrderForCosts(AssistedOrderCostDetails.builder().makeAnOrderForCostsList(null).build()) + .publicFundingCostsProtection(NO) + // Appeal section + .finalOrderAppealToggle(null) + // initiative or without notice section .orderMadeOnDetailsList(OrderMadeOnTypes.COURTS_INITIATIVE) - .orderMadeOnDetailsOrderCourt(OrderMadeOnDetails.builder().ownInitiativeDate(LocalDate.now()).build()) + .orderMadeOnDetailsOrderCourt(OrderMadeOnDetails.builder() + .ownInitiativeText("own initiative test") + .ownInitiativeDate(LocalDate.now()) + .build()) + .finalOrderGiveReasonsYesNo(NO) .build(); + //When: Assisted order document generation called CaseDocument caseDocument = generator.generate(caseData, BEARER_TOKEN); - //Then: It should generate assisted order document assertNotNull(caseDocument); verify(documentManagementService) @@ -234,7 +279,7 @@ void shouldGenerateAssistedFormOrder_whenClaimantAndDefendantReferenceNotAddedTo } @Test - void shouldGenerateAssistedFormOrder_whenRecitalsNotSelected() { + void shouldGenerateAssistedFormOrder_whenOtherOptions() { //Given: case data without recitals selected when(documentGeneratorService.generateDocmosisDocument(any(MappableObject.class), eq(ASSISTED_ORDER_PDF))) .thenReturn(new DocmosisDocument(ASSISTED_ORDER_PDF.getDocumentTitle(), bytes)); @@ -243,13 +288,52 @@ void shouldGenerateAssistedFormOrder_whenRecitalsNotSelected() { .thenReturn(ASSISTED_FROM_ORDER); CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() - .finalOrderRecitals(null) + .ccdState(CaseState.CASE_PROGRESSION) .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) - .finalOrderDateHeardComplex(OrderMade.builder().singleDateSelection(DatesFinalOrders.builder().singleDate(LocalDate.now()).build()).build()) - .assistedOrderCostList(AssistedCostTypesList.NO_ORDER_TO_COST) + // Order made section + .finalOrderDateHeardComplex(OrderMade.builder().singleDateSelection(DatesFinalOrders.builder().singleDate( + LocalDate.now()).build()).build()) + // Papers considered + .finalOrderJudgePapers(null) + // judge heard from section + .finalOrderRepresentation(FinalOrderRepresentation.builder() + .typeRepresentationList(FinalOrderRepresentationList.OTHER_REPRESENTATION) + .typeRepresentationOtherComplex(ClaimantAndDefendantHeard + .builder().detailsRepresentationText("Test").build()).build()) + // Order made on court's own initiative section .orderMadeOnDetailsList(OrderMadeOnTypes.COURTS_INITIATIVE) .orderMadeOnDetailsOrderCourt(OrderMadeOnDetails.builder().ownInitiativeDate(LocalDate.now()).build()) + // Further hearing section + .finalOrderFurtherHearingToggle(toggleList) + .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing.builder() + .alternativeHearingList(null) + .hearingMethodList(IN_PERSON).build()) + // Costs section + .assistedOrderCostList(AssistedCostTypesList.MAKE_AN_ORDER_FOR_DETAILED_COSTS) + .assistedOrderMakeAnOrderForCosts(AssistedOrderCostDetails.builder() + .makeAnOrderForCostsYesOrNo(YES) + .assistedOrderAssessmentSecondDropdownList1(INDEMNITY_BASIS) + .assistedOrderAssessmentSecondDropdownList2(CostEnums.YES) + .makeAnOrderForCostsList(COSTS) + .assistedOrderAssessmentThirdDropdownAmount(BigDecimal.valueOf(10000L)) + .makeAnOrderForCostsYesOrNo(YesOrNo.NO) + .assistedOrderClaimantDefendantFirstDropdown(SUBJECT_DETAILED_ASSESSMENT).build()) + .publicFundingCostsProtection(YES) + // Appeal section + .finalOrderAppealComplex(FinalOrderAppeal.builder() + .applicationList(ApplicationAppealList.REFUSED) + .appealRefusedDropdown(AppealGrantedRefused.builder() + .circuitOrHighCourtListRefuse(ApplicationAppealList.CIRCUIT_COURT) + .appealChoiceSecondDropdownA(AppealChoiceSecondDropdown.builder() + .build()).build()).build()) + // initiative or without notice section + .orderMadeOnDetailsList(OrderMadeOnTypes.COURTS_INITIATIVE) + .orderMadeOnDetailsOrderCourt(OrderMadeOnDetails.builder() + .ownInitiativeText("own initiative test") + .ownInitiativeDate(LocalDate.now()) + .build()) .build(); + //When: Assisted order document generation called CaseDocument caseDocument = generator.generate(caseData, BEARER_TOKEN); //Then: It should generate assisted order document @@ -274,22 +358,59 @@ void shouldGenerateAssistedFormOrder_withAllDetails() { List finalOrdersJudgePapersList = new ArrayList<>(Arrays.asList(FinalOrdersJudgePapers.CONSIDERED)); CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() - .finalOrderRecitals(null) .finalOrderSelection(FinalOrderSelection.ASSISTED_ORDER) - .assistedOrderCostList(AssistedCostTypesList.NO_ORDER_TO_COST) - .orderMadeOnDetailsList(OrderMadeOnTypes.COURTS_INITIATIVE) - .orderMadeOnDetailsOrderCourt(OrderMadeOnDetails.builder().ownInitiativeDate(LocalDate.now()).build()) - .finalOrderDateHeardComplex(OrderMade.builder().singleDateSelection(DatesFinalOrders.builder().singleDate(LocalDate.now()).build()).build()) - .finalOrderRepresentation(FinalOrderRepresentation.builder().typeRepresentationJudgePapersList(finalOrdersJudgePapersList) - .typeRepresentationList(FinalOrderRepresentationList.CLAIMANT_AND_DEFENDANT).typeRepresentationOtherComplex( - ClaimantAndDefendantHeard.builder().detailsRepresentationText("Test").build()).build()) + // Order made section + .finalOrderDateHeardComplex(OrderMade.builder().singleDateSelection(DatesFinalOrders.builder().singleDate( + LocalDate.now()).build()).build()) + //Papers considered + .finalOrderJudgePapers( + finalOrdersJudgePapersList) + // judge heard from section + .respondent2(PartyBuilder.builder().individual().build()) + .addRespondent2(YES) + .respondent2SameLegalRepresentative(YES) + .applicant2(PartyBuilder.builder().individual().build()) + .addApplicant2(YES) + .finalOrderRepresentation(FinalOrderRepresentation.builder() + .typeRepresentationList(FinalOrderRepresentationList.CLAIMANT_AND_DEFENDANT) + .typeRepresentationComplex(ClaimantAndDefendantHeard.builder().build()).build()) + // recitals section .finalOrderRecitals(toggleList) .finalOrderRecitalsRecorded(FinalOrderRecitalsRecorded.builder().text("Test").build()) + // further hearing section + .finalOrderFurtherHearingToggle(toggleList) + .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing.builder() + .alternativeHearingList(dynamicList) + .hearingMethodList(IN_PERSON) + .hearingNotesText("test hearing notes") + .datesToAvoidDateDropdown(DatesFinalOrders.builder().datesToAvoidDates(LocalDate.now()) + .build()).build()) + // Costs section + .assistedOrderCostList(AssistedCostTypesList.MAKE_AN_ORDER_FOR_DETAILED_COSTS) + .assistedOrderMakeAnOrderForCosts(AssistedOrderCostDetails.builder() + .makeAnOrderForCostsYesOrNo(YesOrNo.NO) + .assistedOrderAssessmentSecondDropdownList2(CostEnums.NO) + .makeAnOrderForCostsList(COSTS) + .assistedOrderClaimantDefendantFirstDropdown(COSTS) + .assistedOrderCostsFirstDropdownAmount(BigDecimal.valueOf(10000L)) + .makeAnOrderForCostsYesOrNo(YesOrNo.YES).build()) .assistedOrderCostsReserved(AssistedOrderCostDetails.builder().detailsRepresentationText("Test").build()) - .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing.builder().alternativeHearingList(dynamicList).build()) .finalOrderGiveReasonsComplex(AssistedOrderReasons.builder().reasonsText("Test").build()) .assistedOrderCostsBespoke(AssistedOrderCostDetails.builder().besPokeCostDetailsText("Test").build()) - .finalOrderAppealToggle(toggleList) + .publicFundingCostsProtection(YES) + // Appeal section + .finalOrderAppealComplex(FinalOrderAppeal.builder() + .applicationList(ApplicationAppealList.GRANTED) + .appealGrantedDropdown(AppealGrantedRefused.builder() + .circuitOrHighCourtList(ApplicationAppealList.HIGH_COURT) + .appealChoiceSecondDropdownB(AppealChoiceSecondDropdown.builder() + .build()).build()).build()) + // initiative or without notice section + .orderMadeOnDetailsList(OrderMadeOnTypes.WITHOUT_NOTICE) + .orderMadeOnDetailsOrderWithoutNotice(OrderMadeOnDetailsOrderWithoutNotice.builder() + .withOutNoticeText("without notice test") + .withOutNoticeDate(LocalDate.now()) + .build()) .build(); //When: Assisted order document generation called CaseDocument caseDocument = generator.generate(caseData, BEARER_TOKEN); @@ -301,132 +422,225 @@ void shouldGenerateAssistedFormOrder_withAllDetails() { } @Test - void testGetRepresentedDefendant() { - for (FinalOrdersDefendantRepresentationList finalOrdersDefendantRepresentationList : List.of(FinalOrdersDefendantRepresentationList.values())) { + void testDefendantOneAttendsOrRepresentedTextBuilder() { + for (FinalOrdersDefendantRepresentationList finalOrdersDefendantRepresentationList : List.of( + FinalOrdersDefendantRepresentationList.values())) { CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderRecitals(null) .finalOrderRepresentation(FinalOrderRepresentation.builder().typeRepresentationComplex( ClaimantAndDefendantHeard.builder().typeRepresentationDefendantList( finalOrdersDefendantRepresentationList).build()).build()) .build(); - String response = generator.getRepresentedDefendant(caseData); + String name = caseData.getRespondent1().getPartyName(); + String response = generator.defendantAttendsOrRepresentedTextBuilder(caseData, false); + switch (finalOrdersDefendantRepresentationList) { + case COUNSEL_FOR_DEFENDANT -> assertEquals(format("Counsel for %s, the defendant.", name), response); + case SOLICITOR_FOR_DEFENDANT -> assertEquals(format("Solicitor for %s, the defendant.", name), response); + case COST_DRAFTSMAN_FOR_THE_DEFENDANT -> assertEquals(format("Costs draftsman for %s, the defendant.", name), response); + case THE_DEFENDANT_IN_PERSON -> assertEquals(format("%s, the defendant, in person.", name), response); + case LAY_REPRESENTATIVE_FOR_THE_DEFENDANT -> assertEquals(format("A lay representative for %s, the defendant.", name), response); + default -> { + } + } + } + } + + @Test + void testDefendantTwoAttendsOrRepresentedTextBuilder() { + for (FinalOrdersDefendantRepresentationList finalOrdersDefendantRepresentationList : List.of( + FinalOrdersDefendantRepresentationList.values())) { + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .respondent2(PartyBuilder.builder().individual().build()) + .addRespondent2(YES) + .respondent2SameLegalRepresentative(YES) + .finalOrderRecitals(null) + .finalOrderRepresentation(FinalOrderRepresentation.builder().typeRepresentationComplex( + ClaimantAndDefendantHeard.builder().typeRepresentationDefendantTwoList( + finalOrdersDefendantRepresentationList).build()).build()) + .build(); + String name = caseData.getRespondent2().getPartyName(); + String response = generator.defendantAttendsOrRepresentedTextBuilder(caseData, true); switch (finalOrdersDefendantRepresentationList) { - case COUNSEL_FOR_DEFENDANT: - assertEquals("counsel for defendant", response); - break; - case SOLICITOR_FOR_DEFENDANT: - assertEquals("solicitor for defendant", response); - break; - case COST_DRAFTSMAN_FOR_THE_DEFENDANT: - assertEquals("costs draftsman for the defendant", response); - break; - case THE_DEFENDANT_IN_PERSON: - assertEquals("the defendant in person", response); - break; - case LAY_REPRESENTATIVE_FOR_THE_DEFENDANT: - assertEquals("lay representative for the defendant", response); - break; - default: - break; + case COUNSEL_FOR_DEFENDANT -> assertEquals(format("Counsel for %s, the defendant.", name), response); + case SOLICITOR_FOR_DEFENDANT -> assertEquals(format("Solicitor for %s, the defendant.", name), response); + case COST_DRAFTSMAN_FOR_THE_DEFENDANT -> assertEquals(format("Costs draftsman for %s, the defendant.", name), response); + case THE_DEFENDANT_IN_PERSON -> assertEquals(format("%s, the defendant, in person.", name), response); + case LAY_REPRESENTATIVE_FOR_THE_DEFENDANT -> assertEquals(format("A lay representative for %s, the defendant.", name), response); + default -> { + } } } } @Test - void testGetRepresentedClaimant() { - for (FinalOrdersClaimantRepresentationList finalOrdersClaimantRepresentationList : List.of(FinalOrdersClaimantRepresentationList.values())) { + void testClaimantOneAttendsOrRepresentedTextBuilder() { + for (FinalOrdersClaimantRepresentationList finalOrdersClaimantRepresentationList : List.of( + FinalOrdersClaimantRepresentationList.values())) { CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderRecitals(null) .finalOrderRepresentation(FinalOrderRepresentation.builder().typeRepresentationComplex( ClaimantAndDefendantHeard.builder().typeRepresentationClaimantList( finalOrdersClaimantRepresentationList).build()).build()) .build(); - String response = generator.getRepresentedClaimant(caseData); + String name = caseData.getApplicant1().getPartyName(); + String response = generator.claimantAttendsOrRepresentedTextBuilder(caseData, false); switch (finalOrdersClaimantRepresentationList) { - case COST_DRAFTSMAN_FOR_THE_CLAIMANT: - assertEquals("costs draftsman for the claimant", response); - break; - case COUNSEL_FOR_CLAIMANT: - assertEquals("counsel for claimant", response); - break; - case SOLICITOR_FOR_CLAIMANT: - assertEquals("solicitor for claimant", response); - break; - case THE_CLAIMANT_IN_PERSON: - assertEquals("the claimant in person", response); - break; - case LAY_REPRESENTATIVE_FOR_THE_CLAIMANT: - assertEquals("lay representative for the claimant", response); - break; - default: - break; + case COUNSEL_FOR_CLAIMANT -> assertEquals(format("Counsel for %s, the claimant.", name), response); + case SOLICITOR_FOR_CLAIMANT -> assertEquals(format("Solicitor for %s, the claimant.", name), response); + case COST_DRAFTSMAN_FOR_THE_CLAIMANT -> assertEquals(format("Costs draftsman for %s, the claimant.", name), response); + case THE_CLAIMANT_IN_PERSON -> assertEquals(format("%s, the claimant, in person.", name), response); + case LAY_REPRESENTATIVE_FOR_THE_CLAIMANT -> assertEquals(format("A lay representative for %s, the claimant.", name), response); + default -> { + } } } } @Test - void testGetDefendantNotAttendedText() { - for (FinalOrdersClaimantDefendantNotAttending finalOrdersClaimantDefendantNotAttending : List.of(FinalOrdersClaimantDefendantNotAttending.values())) { + void testClaimantTwoAttendsOrRepresentedTextBuilder() { + for (FinalOrdersClaimantRepresentationList finalOrdersClaimantRepresentationList : List.of( + FinalOrdersClaimantRepresentationList.values())) { + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .addApplicant2(YesOrNo.YES) + .applicant2(PartyBuilder.builder().individual().build()) + .finalOrderRecitals(null) + .finalOrderRepresentation(FinalOrderRepresentation.builder().typeRepresentationComplex( + ClaimantAndDefendantHeard.builder().typeRepresentationClaimantListTwo( + finalOrdersClaimantRepresentationList).build()).build()) + .build(); + String name = caseData.getApplicant2().getPartyName(); + String response = generator.claimantAttendsOrRepresentedTextBuilder(caseData, true); + switch (finalOrdersClaimantRepresentationList) { + case COUNSEL_FOR_CLAIMANT -> assertEquals(format("Counsel for %s, the claimant.", name), response); + case SOLICITOR_FOR_CLAIMANT -> assertEquals(format("Solicitor for %s, the claimant.", name), response); + case COST_DRAFTSMAN_FOR_THE_CLAIMANT -> assertEquals(format("Costs draftsman for %s, the claimant.", name), response); + case THE_CLAIMANT_IN_PERSON -> assertEquals(format("%s, the claimant, in person.", name), response); + case LAY_REPRESENTATIVE_FOR_THE_CLAIMANT -> assertEquals(format("A lay representative for %s, the claimant.", name), response); + default -> { + } + } + } + } + + @Test + void testDefendantOneNotAttendingText() { + for (FinalOrdersClaimantDefendantNotAttending finalOrdersClaimantDefendantNotAttending : List.of( + FinalOrdersClaimantDefendantNotAttending.values())) { CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderRecitals(null) .finalOrderRepresentation(FinalOrderRepresentation.builder().typeRepresentationComplex( ClaimantAndDefendantHeard.builder().trialProcedureComplex(TrialNoticeProcedure.builder().listDef( finalOrdersClaimantDefendantNotAttending).build()).build()).build()) .build(); - String response = generator.getDefendantNotAttendedText(caseData); + String name = caseData.getRespondent1().getPartyName(); + String response = generator.defendantNotAttendingText(caseData, false, name); switch (finalOrdersClaimantDefendantNotAttending) { - case NOT_SATISFIED_NOTICE_OF_TRIAL: - assertEquals("The defendant did not attend the trial, but the" + - " Judge was not satisfied that they had received notice" + - " of the hearing and it was not reasonable to proceed in their absence", response); - break; - case SATISFIED_NOTICE_OF_TRIAL: - assertEquals("The defendant did not attend the trial and whilst the Judge was satisfied " + - "that they had received notice of the trial it was not reasonable to proceed in their absence", - response); - break; - case SATISFIED_REASONABLE_TO_PROCEED: - assertEquals( - "The defendant did not attend the trial," + - " but the Judge was satisfied that they had received notice of the trial and it was " + - "reasonable to proceed in their absence", - response - ); - break; - default: - break; + case NOT_SATISFIED_NOTICE_OF_TRIAL -> assertEquals(format( + "%s, the defendant, did not attend the trial. " + + "The Judge was not satisfied that they had received notice of the hearing " + + "and it was not reasonable to proceed in their absence.", name), response); + case SATISFIED_NOTICE_OF_TRIAL -> assertEquals(format( + "%s, the defendant, did not attend the trial and, whilst the Judge was satisfied that they had " + + "received notice of the trial, the Judge was not satisfied that it was reasonable to proceed in their absence.", name), response); + case SATISFIED_REASONABLE_TO_PROCEED -> assertEquals( + format( + "%s, the defendant, did not attend the trial. The Judge was satisfied that they had " + + "received notice of the trial and determined that it was reasonable to proceed in their absence.", name), response); + default -> { + } } } } @Test - void testGetClaimantNotAttendedText() { - for (FinalOrdersClaimantDefendantNotAttending finalOrdersClaimantDefendantNotAttending : List.of(FinalOrdersClaimantDefendantNotAttending.values())) { + void testDefendantTwoNotAttendingText() { + for (FinalOrdersClaimantDefendantNotAttending finalOrdersClaimantDefendantNotAttending : List.of( + FinalOrdersClaimantDefendantNotAttending.values())) { + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .respondent2(PartyBuilder.builder().individual().build()) + .addRespondent2(YES) + .respondent2SameLegalRepresentative(YES) + .finalOrderRecitals(null) + .finalOrderRepresentation(FinalOrderRepresentation.builder().typeRepresentationComplex( + ClaimantAndDefendantHeard.builder().trialProcedureDefTwoComplex(TrialNoticeProcedure.builder().listDefTwo( + finalOrdersClaimantDefendantNotAttending).build()).build()).build()) + .build(); + String name = caseData.getRespondent2().getPartyName(); + String response = generator.defendantNotAttendingText(caseData, true, name); + switch (finalOrdersClaimantDefendantNotAttending) { + case NOT_SATISFIED_NOTICE_OF_TRIAL -> assertEquals(format( + "%s, the defendant, did not attend the trial. " + + "The Judge was not satisfied that they had received notice of the hearing " + + "and it was not reasonable to proceed in their absence.", name), response); + case SATISFIED_NOTICE_OF_TRIAL -> assertEquals(format( + "%s, the defendant, did not attend the trial and, whilst the Judge was satisfied that they had " + + "received notice of the trial, the Judge was not satisfied that it was reasonable to proceed in their absence.", name), response); + case SATISFIED_REASONABLE_TO_PROCEED -> assertEquals( + format( + "%s, the defendant, did not attend the trial. The Judge was satisfied that they had " + + "received notice of the trial and determined that it was reasonable to proceed in their absence.", name), response); + default -> { + } + } + } + } + + @Test + void testGetClaimantOneNotAttendedText() { + for (FinalOrdersClaimantDefendantNotAttending finalOrdersClaimantDefendantNotAttending : List.of( + FinalOrdersClaimantDefendantNotAttending.values())) { CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderRecitals(null) .finalOrderRepresentation(FinalOrderRepresentation.builder().typeRepresentationComplex( ClaimantAndDefendantHeard.builder().trialProcedureClaimantComplex(TrialNoticeProcedure.builder().list( finalOrdersClaimantDefendantNotAttending).build()).build()).build()) .build(); - String response = generator.getClaimantNotAttendedText(caseData); + String name = caseData.getApplicant1().getPartyName(); + String response = generator.claimantNotAttendingText(caseData, false, name); + switch (finalOrdersClaimantDefendantNotAttending) { + case NOT_SATISFIED_NOTICE_OF_TRIAL -> assertEquals(format( + "%s, the claimant, did not attend the trial. " + + "The Judge was not satisfied that they had received notice of the hearing " + + "and it was not reasonable to proceed in their absence.", name), response); + case SATISFIED_NOTICE_OF_TRIAL -> assertEquals(format( + "%s, the claimant, did not attend the trial and, whilst the Judge was satisfied that they had " + + "received notice of the trial, the Judge was not satisfied that it was reasonable to proceed in their absence.", name), response); + case SATISFIED_REASONABLE_TO_PROCEED -> assertEquals(format( + "%s, the claimant, did not attend the trial. The Judge was satisfied that they had " + + "received notice of the trial and determined that it was reasonable to proceed in their absence.", name), response); + default -> { + } + } + } + } + + @Test + void testGetClaimantTwoNotAttendedText() { + for (FinalOrdersClaimantDefendantNotAttending finalOrdersClaimantDefendantNotAttending : List.of( + FinalOrdersClaimantDefendantNotAttending.values())) { + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .addApplicant2(YesOrNo.YES) + .applicant2(PartyBuilder.builder().individual().build()) + .finalOrderRecitals(null) + .finalOrderRepresentation(FinalOrderRepresentation.builder().typeRepresentationComplex( + ClaimantAndDefendantHeard.builder().trialProcedClaimTwoComplex(TrialNoticeProcedure.builder().listClaimTwo( + finalOrdersClaimantDefendantNotAttending).build()).build()).build()) + .build(); + String name = caseData.getApplicant2().getPartyName(); + String response = generator.claimantNotAttendingText(caseData, true, name); switch (finalOrdersClaimantDefendantNotAttending) { - case NOT_SATISFIED_NOTICE_OF_TRIAL: - assertEquals("The claimant did not attend the trial, " + - "but the Judge was not satisfied that they had received notice of the hearing and it was not " + - "reasonable to proceed in their absence", response); - break; - case SATISFIED_NOTICE_OF_TRIAL: - assertEquals("The claimant did not attend the trial and whilst the Judge was satisfied that they had " + - "received notice of the trial it was not reasonable to proceed in their absence", - response); - break; - case SATISFIED_REASONABLE_TO_PROCEED: - assertEquals("The claimant did not attend the trial, but the Judge was satisfied that they had " + - "received notice of the trial and it was reasonable to proceed in their absence", - response); - break; - default: - break; + case NOT_SATISFIED_NOTICE_OF_TRIAL -> assertEquals(format( + "%s, the claimant, did not attend the trial. " + + "The Judge was not satisfied that they had received notice of the hearing " + + "and it was not reasonable to proceed in their absence.", name), response); + case SATISFIED_NOTICE_OF_TRIAL -> assertEquals(format( + "%s, the claimant, did not attend the trial and, whilst the Judge was satisfied that they had " + + "received notice of the trial, the Judge was not satisfied that it was reasonable to proceed in their absence.", name), response); + case SATISFIED_REASONABLE_TO_PROCEED -> assertEquals(format( + "%s, the claimant, did not attend the trial. The Judge was satisfied that they had " + + "received notice of the trial and determined that it was reasonable to proceed in their absence.", name), response); + default -> { + } } } } @@ -437,58 +651,70 @@ void testGetFurtherHearingLength() { CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderRecitals(null) .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing.builder().lengthList( - hearingLengthFinalOrderList).build()).build(); + hearingLengthFinalOrderList) + .lengthListOther(CaseHearingLengthElement.builder() + .lengthListOtherDays("12") + .lengthListOtherHours("1") + .lengthListOtherMinutes("30") + .build()).build()).build(); String response = generator.getFurtherHearingLength(caseData); switch (hearingLengthFinalOrderList) { - case MINUTES_15: - assertEquals("15 minutes", response); - break; - case MINUTES_30: - assertEquals("30 minutes", response); - break; - case HOUR_1: - assertEquals("1 hour", response); - break; - case HOUR_1_5: - assertEquals("1.5 hours", response); - break; - case HOUR_2: - assertEquals("2 hours", response); - break; - default: - break; + case MINUTES_15 -> assertEquals("15 minutes", response); + case MINUTES_30 -> assertEquals("30 minutes", response); + case HOUR_1 -> assertEquals("1 hour", response); + case HOUR_1_5 -> assertEquals("1.5 hours", response); + case HOUR_2 -> assertEquals("2 hours", response); + case OTHER -> assertEquals("12 days 1 hours 30 minutes", response); + default -> { + } } } } @Test - void testGetFurtherHearingLengthForOther() { - CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() - .finalOrderRecitals(null) - .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing.builder() - .lengthListOther(CaseHearingLengthElement.builder() - .lengthListOtherDays("12") - .lengthListOtherHours("1") - .lengthListOtherMinutes("30").build()).build()).build(); - String response = generator.getFurtherHearingLength(caseData); - assertEquals("12 days 1 hours 30 minutes", response); + void testGetFurtherHearingLengthOther() { + CaseData minCaseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderRecitals(null) + .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing.builder().lengthList(HearingLengthFinalOrderList.OTHER) + .lengthListOther(CaseHearingLengthElement.builder() + //.lengthListOtherDays("12") + //.lengthListOtherHours("1") + .lengthListOtherMinutes("30") + .build()).build()).build(); + String response = generator.getFurtherHearingLength(minCaseData); + assertEquals("30 minutes", response); + + CaseData hourCaseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderRecitals(null) + .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing.builder().lengthList(HearingLengthFinalOrderList.OTHER) + .lengthListOther(CaseHearingLengthElement.builder() + //.lengthListOtherDays("12") + .lengthListOtherHours("1") + //.lengthListOtherMinutes("30") + .build()).build()).build(); + response = generator.getFurtherHearingLength(hourCaseData); + assertEquals("1 hours ", response); + + CaseData dayCaseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderRecitals(null) + .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing.builder().lengthList(HearingLengthFinalOrderList.OTHER) + .lengthListOther(CaseHearingLengthElement.builder() + .lengthListOtherDays("12") + //.lengthListOtherHours("1") + //.lengthListOtherMinutes("30") + .build()).build()).build(); + response = generator.getFurtherHearingLength(dayCaseData); + assertEquals("12 days ", response); } @Test - void testGetIfAttended() { + void testGetFurtherHearingLengthWhenNull() { CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() .finalOrderRecitals(null) - .finalOrderRepresentation(FinalOrderRepresentation.builder().typeRepresentationComplex( - ClaimantAndDefendantHeard.builder().typeRepresentationDefendantList(FinalOrdersDefendantRepresentationList.THE_DEFENDANT_IN_PERSON).build()).build()).build(); - boolean response = generator.getIfAttended(caseData, true); - assertEquals(true, response); + .finalOrderFurtherHearingComplex(null).build(); - CaseData caseDataClaimant = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() - .finalOrderRecitals(null) - .finalOrderRepresentation(FinalOrderRepresentation.builder().typeRepresentationComplex( - ClaimantAndDefendantHeard.builder().typeRepresentationClaimantList(FinalOrdersClaimantRepresentationList.THE_CLAIMANT_IN_PERSON).build()).build()).build(); - response = generator.getIfAttended(caseDataClaimant, false); - assertEquals(true, response); + String response = generator.getFurtherHearingLength(caseData); + assertEquals("", response); } @Test @@ -497,10 +723,12 @@ void testGetFurtherHearingFromDate() { .finalOrderRecitals(null) .finalOrderFurtherHearingToggle(toggleList) .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing.builder().listFromDate(LocalDate.of(2022, 12, - 12)).build()).build(); + 12 + )).build()).build(); LocalDate response = generator.getFurtherHearingDate(caseData, true); assertEquals(LocalDate.of(2022, 12, - 12), response); + 12 + ), response); } @Test @@ -509,10 +737,12 @@ void testGetFurtherHearingToDate() { .finalOrderRecitals(null) .finalOrderFurtherHearingToggle(toggleList) .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing.builder().dateToDate(LocalDate.of(2022, 12, - 12)).build()).build(); + 12 + )).build()).build(); LocalDate response = generator.getFurtherHearingDate(caseData, false); assertEquals(LocalDate.of(2022, 12, - 12), response); + 12 + ), response); } @Test @@ -521,7 +751,7 @@ void testGetAppealFor() { .finalOrderRecitals(null) .finalOrderAppealComplex(FinalOrderAppeal.builder().list(AppealList.CLAIMANT).build()).build(); String response = generator.getAppealFor(caseData); - assertEquals(AppealList.CLAIMANT.name().toLowerCase(), response); + assertEquals(AppealList.CLAIMANT.name().toLowerCase() + "'s", response); } @Test @@ -532,5 +762,273 @@ void testGetAppealForOthers() { String response = generator.getAppealFor(caseData); assertEquals("test", response); } -} + @ParameterizedTest + @MethodSource("testData") + void orderMadeDateBuilder(CaseData caseData, String expectedResponse) { + String response = generator.orderMadeDateBuilder(caseData); + assertEquals(expectedResponse, response); + } + + static Stream testData() { + return Stream.of( + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderDateHeardComplex(OrderMade.builder().singleDateSelection(DatesFinalOrders.builder() + .singleDate(LocalDate.of( + 2023, + 9, + 15 + )) + .build()).build()).build(), + "on 15 September 2023" + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderDateHeardComplex(OrderMade.builder().dateRangeSelection(DatesFinalOrders.builder() + .dateRangeFrom(LocalDate.of( + 2023, + 9, + 13 + )) + .dateRangeTo(LocalDate.of( + 2023, + 9, + 14 + )) + .build()).build()).build(), + "between 13 September 2023 and 14 September 2023" + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderDateHeardComplex(OrderMade.builder().bespokeRangeSelection(DatesFinalOrders.builder() + .bespokeRangeTextArea( + "date between 12 feb 2023, and 14 feb 2023") + .build()).build()).build(), + "on date between 12 feb 2023, and 14 feb 2023" + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderDateHeardComplex(OrderMade.builder().bespokeRangeSelection(null) + .build()).build(), + null + ) + ); + } + + @Test + void testPopulateInterimPaymentText() { + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .assistedOrderMakeAnOrderForCosts(AssistedOrderCostDetails + .builder().assistedOrderAssessmentThirdDropdownAmount(BigDecimal.valueOf( + 10000L)).build()) + .build(); + String response = generator.populateInterimPaymentText(caseData); + assertEquals(format( + "An interim payment of £%s on account of costs shall be paid by 4pm on ", + MonetaryConversions.penniesToPounds(caseData.getAssistedOrderMakeAnOrderForCosts().getAssistedOrderAssessmentThirdDropdownAmount())), response); + } + + @Test + void testPopulateSummarilyAssessedText() { + CaseData caseDataClaimant = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .assistedOrderMakeAnOrderForCosts(AssistedOrderCostDetails.builder() + .makeAnOrderForCostsList(CLAIMANT) + .assistedOrderCostsFirstDropdownAmount(BigDecimal.valueOf(10000L)).build()) + .build(); + CaseData caseDataDefendant = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .assistedOrderMakeAnOrderForCosts(AssistedOrderCostDetails.builder() + .makeAnOrderForCostsList(DEFENDANT) + .assistedOrderCostsFirstDropdownAmount(BigDecimal.valueOf(10000L)).build()) + .build(); + String responseClaimant = generator.populateSummarilyAssessedText(caseDataClaimant); + String responseDefendant = generator.populateSummarilyAssessedText(caseDataDefendant); + assertEquals(format( + "The claimant shall pay the defendant's costs (both fixed and summarily assessed as appropriate) " + + "in the sum of £%s. Such sum shall be paid by 4pm on", + MonetaryConversions.penniesToPounds(caseDataClaimant + .getAssistedOrderMakeAnOrderForCosts().getAssistedOrderCostsFirstDropdownAmount())), responseClaimant); + assertEquals(format( + "The defendant shall pay the claimant's costs (both fixed and summarily assessed as appropriate) " + + "in the sum of £%s. Such sum shall be paid by 4pm on", + MonetaryConversions.penniesToPounds(caseDataDefendant + .getAssistedOrderMakeAnOrderForCosts().getAssistedOrderCostsFirstDropdownAmount())), responseDefendant); + } + + @Test + void testPopulateDetailedAssessmentText() { + CaseData caseDataClaimant = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .assistedOrderMakeAnOrderForCosts(AssistedOrderCostDetails.builder() + .assistedOrderAssessmentSecondDropdownList1(INDEMNITY_BASIS) + .makeAnOrderForCostsList(CLAIMANT).build()) + .build(); + CaseData caseDataDefendant = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .assistedOrderMakeAnOrderForCosts(AssistedOrderCostDetails.builder() + .assistedOrderAssessmentSecondDropdownList1(COSTS) + .makeAnOrderForCostsList(DEFENDANT).build()) + .build(); + String responseClaimant = generator.populateDetailedAssessmentText(caseDataClaimant); + String responseDefendant = generator.populateDetailedAssessmentText(caseDataDefendant); + assertEquals("The claimant shall pay the defendant's costs to be subject to a " + + "detailed assessment on the indemnity basis if not agreed", responseClaimant); + assertEquals("The defendant shall pay the claimant's costs to be subject to" + + " a detailed assessment on the standard basis if not agreed", responseDefendant); + } + + @Test + void testIsDefaultCourt() { + CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderFurtherHearingToggle(toggleList) + .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing + .builder().hearingLocationList(DynamicList + .builder().value(DynamicListElement + .builder() + .code("LOCATION_LIST") + .build()) + .build()).build()) + .build(); + CaseData caseDataWhenFalse = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderFurtherHearingToggle(toggleList) + .finalOrderFurtherHearingComplex(FinalOrderFurtherHearing + .builder().hearingLocationList(DynamicList + .builder().value(DynamicListElement + .builder() + .code("OTHER_LOCATION") + .build()) + .build()).build()) + .build(); + Boolean response = generator.isDefaultCourt(caseData); + Boolean responseFalse = generator.isDefaultCourt(caseDataWhenFalse); + assertEquals(true, response); + assertEquals(false, responseFalse); + + } + + @ParameterizedTest + @MethodSource("testCircuitOrHighCourtData") + void testCircuitOrHighCourt(CaseData caseData, String expectedResponse) { + String response = generator.circuitOrHighCourt(caseData); + assertEquals(expectedResponse, response); + } + + static Stream testCircuitOrHighCourtData() { + return Stream.of( + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderAppealComplex(FinalOrderAppeal + .builder().applicationList(ApplicationAppealList.REFUSED) + .appealRefusedDropdown(AppealGrantedRefused.builder() + .circuitOrHighCourtListRefuse(ApplicationAppealList.CIRCUIT_COURT) + .build()).build()).build(), + "a" + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderAppealComplex(FinalOrderAppeal + .builder().applicationList(ApplicationAppealList.GRANTED) + .appealGrantedDropdown(AppealGrantedRefused.builder() + .circuitOrHighCourtList(ApplicationAppealList.CIRCUIT_COURT) + .build()).build()).build(), + "a" + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderAppealComplex(FinalOrderAppeal + .builder().applicationList(ApplicationAppealList.REFUSED) + .appealRefusedDropdown(AppealGrantedRefused.builder() + .circuitOrHighCourtListRefuse(ApplicationAppealList.HIGH_COURT) + .build()).build()).build(), + "b" + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderAppealComplex(FinalOrderAppeal + .builder().applicationList(ApplicationAppealList.GRANTED) + .appealGrantedDropdown(AppealGrantedRefused.builder() + .circuitOrHighCourtList(ApplicationAppealList.HIGH_COURT) + .build()).build()).build(), + "b" + ) + ); + } + + @ParameterizedTest + @MethodSource("testGetAppealDateData") + void testGetAppealDate(CaseData caseData, LocalDate expectedResponse) { + LocalDate response = generator.getAppealDate(caseData); + assertEquals(expectedResponse, response); + } + + static Stream testGetAppealDateData() { + return Stream.of( + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderAppealComplex(FinalOrderAppeal + .builder().applicationList(ApplicationAppealList.REFUSED) + .appealRefusedDropdown(AppealGrantedRefused.builder() + .circuitOrHighCourtListRefuse(ApplicationAppealList.CIRCUIT_COURT) + .appealChoiceSecondDropdownA(AppealChoiceSecondDropdown.builder() + .appealGrantedRefusedDate(LocalDate.now().plusDays(1)) + .build()).build()).build()).build(), + LocalDate.now().plusDays(1) + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderAppealComplex(FinalOrderAppeal + .builder().applicationList(ApplicationAppealList.GRANTED) + .appealGrantedDropdown(AppealGrantedRefused.builder() + .circuitOrHighCourtList(ApplicationAppealList.CIRCUIT_COURT) + .appealChoiceSecondDropdownA(AppealChoiceSecondDropdown.builder() + .appealGrantedRefusedDate(LocalDate.now().plusDays(10)) + .build()).build()).build()).build(), + LocalDate.now().plusDays(10) + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderAppealComplex(FinalOrderAppeal + .builder().applicationList(ApplicationAppealList.REFUSED) + .appealRefusedDropdown(AppealGrantedRefused.builder() + .circuitOrHighCourtListRefuse(ApplicationAppealList.HIGH_COURT) + .appealChoiceSecondDropdownB(AppealChoiceSecondDropdown.builder() + .appealGrantedRefusedDate(LocalDate.now().plusDays(5)) + .build()).build()).build()).build(), + LocalDate.now().plusDays(5) + ), + Arguments.of( + CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .finalOrderAppealComplex(FinalOrderAppeal + .builder().applicationList(ApplicationAppealList.GRANTED) + .appealGrantedDropdown(AppealGrantedRefused.builder() + .circuitOrHighCourtList(ApplicationAppealList.HIGH_COURT) + .appealChoiceSecondDropdownB(AppealChoiceSecondDropdown.builder() + .appealGrantedRefusedDate(LocalDate.now().plusDays(5)) + .build()).build()).build()).build(), + LocalDate.now().plusDays(5) + ) + ); + } + + @Test + void testGetInitiativeTextWithoutNotice() { + CaseData caseDataInitiative = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .orderMadeOnDetailsList(OrderMadeOnTypes.COURTS_INITIATIVE) + .orderMadeOnDetailsOrderCourt(OrderMadeOnDetails.builder().ownInitiativeText("test initiative text").build()) + .build(); + String responseInitiative = generator.getInitiativeOrWithoutNotice(caseDataInitiative); + assertEquals("test initiative text", responseInitiative); + + CaseData caseDataWithoutNotice = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .orderMadeOnDetailsList(OrderMadeOnTypes.WITHOUT_NOTICE) + .orderMadeOnDetailsOrderWithoutNotice(OrderMadeOnDetailsOrderWithoutNotice.builder().withOutNoticeText("test without notice text").build()) + .build(); + String responseWithoutNotice = generator.getInitiativeOrWithoutNotice(caseDataWithoutNotice); + assertEquals("test without notice text", responseWithoutNotice); + + CaseData caseDataWhenNone = CaseDataBuilder.builder().atStateNotificationAcknowledged().build().toBuilder() + .orderMadeOnDetailsList(OrderMadeOnTypes.NONE) + .build(); + String responseWhenNone = generator.getInitiativeOrWithoutNotice(caseDataWhenNone); + assertNull(responseWhenNone); + } + +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipClaimantFormMapperTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipClaimantFormMapperTest.java new file mode 100644 index 00000000000..4b26e787dde --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipClaimantFormMapperTest.java @@ -0,0 +1,100 @@ +package uk.gov.hmcts.reform.civil.service.docmosis.dq; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; +import uk.gov.hmcts.reform.civil.model.citizenui.ClaimantLiPResponse; +import uk.gov.hmcts.reform.civil.model.citizenui.DQExtraDetailsLip; +import uk.gov.hmcts.reform.civil.model.citizenui.ExpertLiP; +import uk.gov.hmcts.reform.civil.model.docmosis.dq.DirectionsQuestionnaireForm; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class DQLipClaimantFormMapperTest { + + @Mock + private CaseDataLiP caseDataLiPMock; + @Mock + private DQExtraDetailsLip dqExtraDetailsLipMock; + @Mock + private ExpertLiP expertLiPMock; + @Mock + private ClaimantLiPResponse claimantLiPResponse; + @Mock + private CaseData caseData; + @Mock + private Party applicant1; + @InjectMocks + private DQLipClaimantFormMapper dqLipClaimantFormMapper; + private DirectionsQuestionnaireForm form; + private static final String NAME = "Claimant"; + + @BeforeEach + void setUp() { + form = DirectionsQuestionnaireForm.builder().build(); + } + + @Test + void shouldNotPopulateDtoWithLipData_whenCaseDataLipIsNull() { + //Given + Optional emptyOptional = Optional.empty(); + //When + DirectionsQuestionnaireForm resultForm = dqLipClaimantFormMapper.addLipDQs(form, emptyOptional); + //Then + assertThat(resultForm.getLipExtraDQ()).isNull(); + } + + @Test + void shouldNotPopulateLipExtraDQ_whenDQExtraDetailsLipIsNull() { + //Given + Optional caseDataLiPOptional = Optional.of(caseDataLiPMock); + given(caseDataLiPMock.getApplicant1LiPResponse()).willReturn(claimantLiPResponse); + given(claimantLiPResponse.getApplicant1DQExtraDetails()).willReturn(null); + //When + DirectionsQuestionnaireForm resultForm = dqLipClaimantFormMapper.addLipDQs(form, caseDataLiPOptional); + //Then + assertThat(resultForm.getLipExtraDQ()).isNull(); + } + + @Test + void shouldPopulateLipExtraDQ_whenDQExtraDetailsLipIsNotNull() { + //Given + Optional caseDataLiPOptional = Optional.of(caseDataLiPMock); + given(caseDataLiPMock.getApplicant1LiPResponse()).willReturn(claimantLiPResponse); + given(claimantLiPResponse.getApplicant1DQExtraDetails()).willReturn(dqExtraDetailsLipMock); + given(dqExtraDetailsLipMock.getApplicant1DQLiPExpert()).willReturn(expertLiPMock); + given(dqExtraDetailsLipMock.getTriedToSettle()).willReturn(YesOrNo.YES); + given(dqExtraDetailsLipMock.getRequestExtra4weeks()).willReturn(YesOrNo.YES); + given(dqExtraDetailsLipMock.getGiveEvidenceYourSelf()).willReturn(YesOrNo.YES); + given(dqExtraDetailsLipMock.getConsiderClaimantDocumentsDetails()).willReturn("test"); + given(dqExtraDetailsLipMock.getDeterminationWithoutHearingRequired()).willReturn(YesOrNo.NO); + //When + DirectionsQuestionnaireForm resultForm = dqLipClaimantFormMapper.addLipDQs(form, caseDataLiPOptional); + //Then + assertThat(resultForm.getLipExtraDQ()).isNotNull(); + } + + @Test + void shouldReturnClaimantSignature_whenGetStatementOfTruth() { + //Given + given(caseData.getApplicant1()).willReturn(applicant1); + given(applicant1.getPartyName()).willReturn(NAME); + //When + String result = dqLipClaimantFormMapper.getStatementOfTruthName(caseData); + //Then + assertThat(result).isEqualTo(NAME); + verify(caseData).getApplicant1(); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipDefendantFormMapperTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipDefendantFormMapperTest.java new file mode 100644 index 00000000000..d86e2fad0cb --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipDefendantFormMapperTest.java @@ -0,0 +1,78 @@ +package uk.gov.hmcts.reform.civil.service.docmosis.dq; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; +import uk.gov.hmcts.reform.civil.model.citizenui.DQExtraDetailsLip; +import uk.gov.hmcts.reform.civil.model.citizenui.ExpertLiP; +import uk.gov.hmcts.reform.civil.model.citizenui.RespondentLiPResponse; +import uk.gov.hmcts.reform.civil.model.docmosis.dq.DirectionsQuestionnaireForm; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class DQLipDefendantFormMapperTest { + + private static final String NAME = "Defendant"; + @Mock + private CaseDataLiP caseDataLiPMock; + @Mock + private DQExtraDetailsLip dqExtraDetailsLipMock; + @Mock + private ExpertLiP expertLiPMock; + @Mock + private RespondentLiPResponse respondentLiPResponse; + @Mock + private CaseData caseData; + @Mock + private Party respondent1; + @InjectMocks + private DQLipDefendantFormMapper dqLipDefendantFormMapper; + private DirectionsQuestionnaireForm form; + + @BeforeEach + void setUp() { + form = DirectionsQuestionnaireForm.builder().build(); + } + + @Test + void shouldPopulateLipExtraDQ_whenDQExtraDetailsLipIsNotNull() { + //Given + Optional caseDataLiPOptional = Optional.of(caseDataLiPMock); + given(caseDataLiPMock.getRespondent1LiPResponse()).willReturn(respondentLiPResponse); + given(respondentLiPResponse.getRespondent1DQExtraDetails()).willReturn(dqExtraDetailsLipMock); + given(dqExtraDetailsLipMock.getRespondent1DQLiPExpert()).willReturn(expertLiPMock); + given(dqExtraDetailsLipMock.getTriedToSettle()).willReturn(YesOrNo.YES); + given(dqExtraDetailsLipMock.getRequestExtra4weeks()).willReturn(YesOrNo.YES); + given(dqExtraDetailsLipMock.getGiveEvidenceYourSelf()).willReturn(YesOrNo.YES); + given(dqExtraDetailsLipMock.getConsiderClaimantDocumentsDetails()).willReturn("test"); + given(dqExtraDetailsLipMock.getDeterminationWithoutHearingRequired()).willReturn(YesOrNo.NO); + //When + DirectionsQuestionnaireForm resultForm = dqLipDefendantFormMapper.addLipDQs(form, caseDataLiPOptional); + //Then + assertThat(resultForm.getLipExtraDQ()).isNotNull(); + } + + @Test + void shouldReturnClaimantSignature_whenGetStatementOfTruth() { + //Given + given(caseData.getRespondent1()).willReturn(respondent1); + given(respondent1.getPartyName()).willReturn(NAME); + //When + String result = dqLipDefendantFormMapper.getStatementOfTruthName(caseData); + //Then + assertThat(result).isEqualTo(NAME); + verify(caseData).getRespondent1(); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipFormMapperFactoryTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipFormMapperFactoryTest.java new file mode 100644 index 00000000000..1836a018ca9 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DQLipFormMapperFactoryTest.java @@ -0,0 +1,40 @@ +package uk.gov.hmcts.reform.civil.service.docmosis.dq; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import uk.gov.hmcts.reform.civil.model.CaseData; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; + +@ExtendWith(MockitoExtension.class) +class DQLipFormMapperFactoryTest { + + @Mock + private CaseData caseData; + @InjectMocks + private DQLipFormMapperFactory factory; + + @Test + void shouldReturnMapperForClaimant_whenCamundaProcessIsForClaimantResponse() { + //Given + given(caseData.getCurrentCamundaBusinessProcessName()).willReturn(DQLipFormMapperFactory.CLAIMANT_LIP_RESPONSE_PROCESS); + //When + DQLipFormMapper mapper = factory.getDQLipFormMapper(caseData); + //Then + assertThat(mapper).isInstanceOf(DQLipClaimantFormMapper.class); + } + + @Test + void shouldReturnMapperForDefendant_whenCamundaProcessIsForDefendantResponse() { + //Given + given(caseData.getCurrentCamundaBusinessProcessName()).willReturn("abracadabra"); + //When + DQLipFormMapper mapper = factory.getDQLipFormMapper(caseData); + //Then + assertThat(mapper).isInstanceOf(DQLipDefendantFormMapper.class); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionQuestionnaireLipGeneratorFactoryTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionQuestionnaireLipGeneratorFactoryTest.java new file mode 100644 index 00000000000..aaa95440d09 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionQuestionnaireLipGeneratorFactoryTest.java @@ -0,0 +1,44 @@ +package uk.gov.hmcts.reform.civil.service.docmosis.dq; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; + +@ExtendWith(MockitoExtension.class) +class DirectionQuestionnaireLipGeneratorFactoryTest { + + @Mock + private FeatureToggleService featureToggleService; + @Mock + private DirectionsQuestionnaireLipGenerator directionsQuestionnaireLipGenerator; + @Mock + private DirectionQuestionnaireLipResponseGenerator directionQuestionnaireLipResponseGenerator; + @InjectMocks + private DirectionQuestionnaireLipGeneratorFactory factory; + + @Test + void shouldReturnDirectionQuestionnaireLipGenerator_whenLipVLipIsDisabled() { + + //When + DirectionsQuestionnaireGenerator directionsQuestionnaireGenerator = factory.getDirectionQuestionnaire(); + //Then + assertThat(directionsQuestionnaireGenerator).isInstanceOf(DirectionsQuestionnaireLipGenerator.class); + } + + @Test + void shouldReturnDirectionQuestionnaireLipResposeGenerator_whenLipVLipIsEnabled() { + //Given + given(featureToggleService.isLipVLipEnabled()).willReturn(true); + //When + DirectionsQuestionnaireGenerator directionsQuestionnaireGenerator = factory.getDirectionQuestionnaire(); + //Then + assertThat(directionsQuestionnaireGenerator).isInstanceOf(DirectionQuestionnaireLipResponseGenerator.class); + } + +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionQuestionnaireLipResponseGeneratorTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionQuestionnaireLipResponseGeneratorTest.java new file mode 100644 index 00000000000..a733374681e --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/dq/DirectionQuestionnaireLipResponseGeneratorTest.java @@ -0,0 +1,66 @@ +package uk.gov.hmcts.reform.civil.service.docmosis.dq; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; +import uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates.DQ_LIP_RESPONSE; + +@ExtendWith(MockitoExtension.class) +class DirectionQuestionnaireLipResponseGeneratorTest { + + @Mock + private FeatureToggleService featureToggleService; + @Mock + private CaseData caseData; + @InjectMocks + private DirectionQuestionnaireLipResponseGenerator generator; + + @Test + void shouldReturnLipTemplate_whenLipVLipEnabledAndClaimantLip() { + //Given + given(featureToggleService.isLipVLipEnabled()).willReturn(true); + given(caseData.isApplicantNotRepresented()).willReturn(true); + //When + DocmosisTemplates docmosisTemplate = generator.getTemplateId(caseData); + //Then + assertThat(docmosisTemplate).isEqualTo(DQ_LIP_RESPONSE); + } + + @Test + void shouldReturnLipTempate_whenLipVLipEnabledAndDefendantLip() { + //Given + given(featureToggleService.isLipVLipEnabled()).willReturn(true); + given(caseData.isRespondent1NotRepresented()).willReturn(true); + //When + DocmosisTemplates docmosisTemplate = generator.getTemplateId(caseData); + //Then + assertThat(docmosisTemplate).isEqualTo(DQ_LIP_RESPONSE); + } + + @Test + void shouldNotReturnLipTemplateWhenLipvLipIsNotEnabled() { + //Given + given(featureToggleService.isLipVLipEnabled()).willReturn(false); + given(caseData.isRespondent1NotRepresented()).willReturn(true); + //When + DocmosisTemplates docmosisTemplate = generator.getTemplateId(caseData); + //Then + assertThat(docmosisTemplate).isNotEqualTo(DQ_LIP_RESPONSE); + } + + @Test + void shouldNotReturnLipTemplateWhenLrvLr() { + //When + DocmosisTemplates docmosisTemplate = generator.getTemplateId(caseData); + //Then + assertThat(docmosisTemplate).isNotEqualTo(DQ_LIP_RESPONSE); + } +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingFormGeneratorTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingFormGeneratorTest.java index 97f5e353865..23b051fd7fa 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingFormGeneratorTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingFormGeneratorTest.java @@ -10,6 +10,7 @@ import uk.gov.hmcts.reform.civil.enums.hearing.HearingChannel; import uk.gov.hmcts.reform.civil.enums.hearing.HearingDuration; import uk.gov.hmcts.reform.civil.enums.hearing.HearingNoticeList; +import uk.gov.hmcts.reform.civil.enums.hearing.ListingOrRelisting; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.common.DynamicList; import uk.gov.hmcts.reform.civil.model.common.DynamicListElement; @@ -21,6 +22,7 @@ import uk.gov.hmcts.reform.civil.sampledata.CaseDocumentBuilder; import uk.gov.hmcts.reform.civil.service.docmosis.DocumentGeneratorService; import uk.gov.hmcts.reform.civil.documentmanagement.UnsecuredDocumentManagementService; +import uk.gov.hmcts.reform.civil.utils.AssignCategoryId; import java.math.BigDecimal; import java.util.List; @@ -56,7 +58,8 @@ public class HearingFormGeneratorTest { @MockBean private DocumentGeneratorService documentGeneratorService; - + @MockBean + private AssignCategoryId assignCategoryId; @Autowired private HearingFormGenerator generator; @@ -70,6 +73,7 @@ void shouldHearingFormGeneratorOneForm_whenValidDataIsProvided() { .thenReturn(CASE_DOCUMENT); CaseData caseData = CaseDataBuilder.builder().atStateNotificationAcknowledged() + .listingOrRelisting(ListingOrRelisting.LISTING) .totalClaimAmount(new BigDecimal(2000)) .build().toBuilder() .hearingLocation(DynamicList.builder().value(DynamicListElement.builder().label("County Court").build()) diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingNoticeHmcGeneratorTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingNoticeHmcGeneratorTest.java index ab14fb470a3..c7ab605231c 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingNoticeHmcGeneratorTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/hearing/HearingNoticeHmcGeneratorTest.java @@ -30,6 +30,7 @@ import uk.gov.hmcts.reform.civil.sampledata.CaseDocumentBuilder; import uk.gov.hmcts.reform.civil.service.docmosis.DocumentGeneratorService; import uk.gov.hmcts.reform.civil.service.hearings.HearingFeesService; +import uk.gov.hmcts.reform.civil.utils.AssignCategoryId; import uk.gov.hmcts.reform.hmc.model.hearing.HearingDaySchedule; import uk.gov.hmcts.reform.hmc.model.hearing.HearingDetails; import uk.gov.hmcts.reform.hmc.model.hearing.HearingGetResponse; @@ -84,6 +85,8 @@ class HearingNoticeHmcGeneratorTest { private LocationRefDataService locationRefDataService; @MockBean private HearingFeesService hearingFeesService; + @MockBean + private AssignCategoryId assignCategoryId; @BeforeEach void setupTest() { diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimFormGeneratorTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimFormGeneratorTest.java index 0f407476ba3..30145dcf1b0 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimFormGeneratorTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimFormGeneratorTest.java @@ -190,7 +190,10 @@ class GetTemplateData { @Test void whenCaseIsAtClaimDetailsNotified_shouldGetSealedClaimFormDataFor1V1() { CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() - .applicant1LitigationFriend(LitigationFriend.builder().fullName("applicant LF").build()) + .applicant1LitigationFriend(LitigationFriend.builder() + .firstName("applicant") + .lastName("LF") + .build()) .build(); var templateData = sealedClaimFormGenerator.getTemplateData(caseData, BEARER_TOKEN); @@ -205,7 +208,10 @@ void whenCaseIsAtClaimDetailsNotified_shouldGetSealedClaimFormDataFor1V2Differen CaseData caseData = CaseDataBuilder.builder() .atStateClaimDetailsNotified() .multiPartyClaimTwoDefendantSolicitors().build().toBuilder() - .applicant1LitigationFriend(LitigationFriend.builder().fullName("applicant LF").build()) + .applicant1LitigationFriend(LitigationFriend.builder() + .firstName("applicant") + .lastName("LF") + .build()) .build(); final var templateData = sealedClaimFormGenerator.getTemplateData(caseData, BEARER_TOKEN); @@ -221,8 +227,14 @@ void whenCaseIsAtClaimDetailsNotified_shouldGetSealedClaimFormDataFor2V1() { CaseData caseData = CaseDataBuilder.builder() .atStateClaimDetailsNotified() .multiPartyClaimTwoApplicants().build().toBuilder() - .applicant1LitigationFriend(LitigationFriend.builder().fullName("applicant LF").build()) - .applicant2LitigationFriend(LitigationFriend.builder().fullName("applicant2 LF").build()) + .applicant1LitigationFriend(LitigationFriend.builder() + .firstName("applicant") + .lastName("LF") + .build()) + .applicant2LitigationFriend(LitigationFriend.builder() + .firstName("applicant2") + .lastName("LF") + .build()) .build(); var templateData = sealedClaimFormGenerator.getTemplateData(caseData, BEARER_TOKEN); @@ -237,7 +249,10 @@ void whenCaseIsAtClaimDetailsNotified_shouldGetSealedClaimFormDataFor1V2SameSoli CaseData caseData = CaseDataBuilder.builder() .atStateClaimDetailsNotified() .multiPartyClaimOneDefendantSolicitor().build().toBuilder() - .applicant1LitigationFriend(LitigationFriend.builder().fullName("applicant LF").build()) + .applicant1LitigationFriend(LitigationFriend.builder() + .firstName("applicant") + .lastName("LF") + .build()) .build(); var templateData = sealedClaimFormGenerator.getTemplateData(caseData, BEARER_TOKEN); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimLipResponseFormGeneratorTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimLipResponseFormGeneratorTest.java index 42195ae6fa2..ab25f0fbe0e 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimLipResponseFormGeneratorTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimLipResponseFormGeneratorTest.java @@ -50,6 +50,7 @@ import uk.gov.hmcts.reform.civil.model.dq.RecurringExpenseLRspec; import uk.gov.hmcts.reform.civil.model.dq.RecurringIncomeLRspec; import uk.gov.hmcts.reform.civil.model.dq.Respondent1DQ; +import uk.gov.hmcts.reform.civil.service.citizenui.responsedeadline.DeadlineExtensionCalculatorService; import uk.gov.hmcts.reform.civil.service.docmosis.DocumentGeneratorService; import uk.gov.hmcts.reform.civil.utils.ElementUtils; @@ -81,6 +82,8 @@ class SealedClaimLipResponseFormGeneratorTest { private DocumentGeneratorService documentGeneratorService; @MockBean private DocumentManagementService documentManagementService; + @MockBean + private DeadlineExtensionCalculatorService deadlineCalculatorService; @Autowired private SealedClaimLipResponseFormGenerator generator; @Captor @@ -115,15 +118,20 @@ void shouldGenerateDocumentSuccessfully() { @Test void admitPayImmediate() { - CaseData caseData = commonData() + LocalDate whenWillPay = LocalDate.now().plusDays(5); + CaseData.CaseDataBuilder builder = commonData() .respondent1(company("B")) .respondent2(individual("C")) .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_ADMISSION) .defenceAdmitPartPaymentTimeRouteRequired(RespondentResponsePartAdmissionPaymentTimeLRspec.IMMEDIATELY) - .build(); + .respondToClaimAdmitPartLRspec( + RespondToClaimAdmitPartLRspec.builder() + .whenWillThisAmountBePaid(whenWillPay) + .build() + ); SealedClaimLipResponseForm templateData = generator - .getTemplateData(caseData); + .getTemplateData(builder.build()); Assertions.assertEquals(LocalDate.now(), templateData.getGenerationDate()); } @@ -171,6 +179,7 @@ void admitPayByDate() { @Test void partAdmitPayImmediate() { + LocalDate whenWillPay = LocalDate.now().plusDays(5); CaseData.CaseDataBuilder builder = commonData() .respondent1(company("B")) .respondent2(individual("C")) @@ -178,7 +187,12 @@ void partAdmitPayImmediate() { .specDefenceAdmittedRequired(YesOrNo.NO) .respondToAdmittedClaimOwingAmount(BigDecimal.valueOf(2000)) .detailsOfWhyDoesYouDisputeTheClaim("Reason to dispute the claim") - .defenceAdmitPartPaymentTimeRouteRequired(RespondentResponsePartAdmissionPaymentTimeLRspec.IMMEDIATELY); + .defenceAdmitPartPaymentTimeRouteRequired(RespondentResponsePartAdmissionPaymentTimeLRspec.IMMEDIATELY) + .respondToClaimAdmitPartLRspec( + RespondToClaimAdmitPartLRspec.builder() + .whenWillThisAmountBePaid(whenWillPay) + .build() + ); CaseData caseData = timeline(financialDetails(builder)) .build(); @@ -204,7 +218,7 @@ void shouldNotBuildRepaymentPlan_whenRespondent1RepaymentPlanisNull() { .build(); SealedClaimLipResponseForm templateData = generator .getTemplateData(caseData); - assertThat(templateData.getRepaymentPlan()).isNull(); + assertThat(templateData.getCommonDetails().getRepaymentPlan()).isNull(); } @Test @@ -231,7 +245,7 @@ void partAdmitPayInstalments() { SealedClaimLipResponseForm templateData = generator .getTemplateData(caseData); Assertions.assertEquals(LocalDate.now(), templateData.getGenerationDate()); - assertThat(templateData.getRepaymentPlan()).isNotNull(); + assertThat(templateData.getCommonDetails().getRepaymentPlan()).isNotNull(); } @Test @@ -334,6 +348,70 @@ void counterClaim() { Assertions.assertEquals(LocalDate.now(), templateData.getGenerationDate()); } + @Test + void shouldGenerateDocumentSuccessfullyForFullAdmit() { + //Given + LocalDate whenWillPay = LocalDate.now().plusDays(5); + CaseData caseData = commonData() + .respondent1(company("B")) + .respondent2(individual("C")) + .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_ADMISSION) + .defenceAdmitPartPaymentTimeRouteRequired(RespondentResponsePartAdmissionPaymentTimeLRspec.IMMEDIATELY) + .respondToClaimAdmitPartLRspec( + RespondToClaimAdmitPartLRspec.builder() + .whenWillThisAmountBePaid(whenWillPay) + .build() + ) + .build(); + String fileName = "someName"; + DocmosisDocument docmosisDocument = mock(DocmosisDocument.class); + byte[] bytes = {}; + given(docmosisDocument.getBytes()).willReturn(bytes); + CaseDocument caseDocument = CaseDocument.builder().documentName(fileName).build(); + given(documentGeneratorService.generateDocmosisDocument(any(MappableObject.class), any())).willReturn( + docmosisDocument); + given(documentManagementService.uploadDocument(anyString(), any(PDF.class))).willReturn(caseDocument); + SealedClaimLipResponseForm templateData = generator + .getTemplateData(caseData); + //When + CaseDocument result = generator.generate(caseData, AUTHORIZATION); + //Then + assertThat(result).isEqualTo(caseDocument); + } + + @Test + void shouldGenerateDocumentSuccessfullyForPartAdmit() { + //Given + LocalDate whenWillPay = LocalDate.now().plusDays(5); + CaseData caseData = commonData() + .respondent1(company("B")) + .respondent2(individual("C")) + .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.PART_ADMISSION) + .specDefenceAdmittedRequired(YesOrNo.NO) + .respondToAdmittedClaimOwingAmount(BigDecimal.valueOf(2000)) + .detailsOfWhyDoesYouDisputeTheClaim("Reason to dispute the claim") + .defenceAdmitPartPaymentTimeRouteRequired(RespondentResponsePartAdmissionPaymentTimeLRspec.IMMEDIATELY) + .respondToClaimAdmitPartLRspec( + RespondToClaimAdmitPartLRspec.builder() + .whenWillThisAmountBePaid(whenWillPay) + .build() + ).build(); + String fileName = "someName"; + DocmosisDocument docmosisDocument = mock(DocmosisDocument.class); + byte[] bytes = {}; + given(docmosisDocument.getBytes()).willReturn(bytes); + CaseDocument caseDocument = CaseDocument.builder().documentName(fileName).build(); + given(documentGeneratorService.generateDocmosisDocument(any(MappableObject.class), any())).willReturn( + docmosisDocument); + given(documentManagementService.uploadDocument(anyString(), any(PDF.class))).willReturn(caseDocument); + SealedClaimLipResponseForm templateData = generator + .getTemplateData(caseData); + //When + CaseDocument result = generator.generate(caseData, AUTHORIZATION); + //Then + assertThat(result).isEqualTo(caseDocument); + } + private static AccountSimple account(@NotNull AccountType type, @NotNull YesOrNo joint, @NotNull BigDecimal balance) { AccountSimple a = new AccountSimple(); a.setAccountType(type); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimResponseFormGeneratorForSpecTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimResponseFormGeneratorForSpecTest.java index 74d85171b96..3fe807389e4 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimResponseFormGeneratorForSpecTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/sealedclaim/SealedClaimResponseFormGeneratorForSpecTest.java @@ -1,8 +1,11 @@ package uk.gov.hmcts.reform.civil.service.docmosis.sealedclaim; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.mock.mockito.MockBean; @@ -15,12 +18,16 @@ import uk.gov.hmcts.reform.civil.model.StatementOfTruth; import uk.gov.hmcts.reform.civil.model.TimelineOfEventDetails; import uk.gov.hmcts.reform.civil.model.TimelineOfEvents; +import uk.gov.hmcts.reform.civil.model.common.MappableObject; import uk.gov.hmcts.reform.civil.model.defaultjudgment.CaseLocationCivil; +import uk.gov.hmcts.reform.civil.model.docmosis.DocmosisDocument; import uk.gov.hmcts.reform.civil.model.docmosis.sealedclaim.SealedClaimResponseFormForSpec; import uk.gov.hmcts.reform.civil.model.dq.RequestedCourt; import uk.gov.hmcts.reform.civil.model.dq.Respondent1DQ; import uk.gov.hmcts.reform.civil.model.dq.Respondent2DQ; import uk.gov.hmcts.reform.civil.referencedata.model.LocationRefData; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; +import uk.gov.hmcts.reform.civil.service.docmosis.DocmosisTemplates; import uk.gov.hmcts.reform.civil.service.docmosis.DocumentGeneratorService; import uk.gov.hmcts.reform.civil.service.docmosis.RepresentativeService; import uk.gov.hmcts.reform.civil.documentmanagement.DocumentManagementService; @@ -33,13 +40,21 @@ import java.util.ArrayList; import java.util.List; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; @ExtendWith(SpringExtension.class) public class SealedClaimResponseFormGeneratorForSpecTest { private static final String BEARER_TOKEN = "Bearer Token"; + private static final List LOCATIONS = List.of(LocationRefData.builder().siteName("SiteName").courtAddress("1").postcode("1") + .courtName("Court Name").region("Region").regionId("4").courtVenueId("000") + .courtTypeId("10").courtLocationCode("121") + .epimmsId("000000").build()); + private static final CaseData CASE_DATA_WITH_RESPONDENT1 = getCaseDataWithRespondent1Data(); + @InjectMocks private SealedClaimResponseFormGeneratorForSpec generator; @@ -53,73 +68,40 @@ public class SealedClaimResponseFormGeneratorForSpecTest { private CourtLocationUtils courtLocationUtils; @Mock private LocationRefDataService locationRefDataService; + @Mock + private FeatureToggleService featureToggleService; + @Captor + private ArgumentCaptor docmosisTemplatesArgumentCaptor; + @Captor + private ArgumentCaptor templateDataCaptor; - @Test - public void contentCheckRespondent1() { - List locations = new ArrayList<>(); - locations.add(LocationRefData.builder().siteName("SiteName").courtAddress("1").postcode("1") - .courtName("Court Name").region("Region").regionId("4").courtVenueId("000") - .courtTypeId("10").courtLocationCode("121") - .epimmsId("000000").build()); - when(locationRefDataService.getCourtLocationsByEpimmsId(any(), any())).thenReturn(locations); - - CaseData caseData = CaseData.builder() - .legacyCaseReference("case reference") - .detailsOfWhyDoesYouDisputeTheClaim("why dispute the claim") - .respondent1DQ(Respondent1DQ.builder() - .respondent1DQStatementOfTruth( - StatementOfTruth.builder() - .name("sot name") - .role("sot role") - .build() - ) - .respondent1DQRequestedCourt( - RequestedCourt.builder() - .responseCourtCode("121") - .reasonForHearingAtSpecificCourt("test") - .caseLocation(CaseLocationCivil.builder() - .region("2") - .baseLocation("000000") - .build()) - .build()) - .build()) - .applicant1(Party.builder() - .type(Party.Type.COMPANY) - .companyName("applicant name") - .build()) - .respondent1(Party.builder() - .type(Party.Type.COMPANY) - .companyName("defendant name") - .build()) - .respondent1ResponseDate(LocalDateTime.now()) - .build(); + @BeforeEach + void setUp() { + given(locationRefDataService.getCourtLocationsByEpimmsId(any(), any())).willReturn(LOCATIONS); + } + @Test + void contentCheckRespondent1() { SealedClaimResponseFormForSpec templateData = generator.getTemplateData( - caseData, BEARER_TOKEN); + CASE_DATA_WITH_RESPONDENT1, BEARER_TOKEN); - Assertions.assertEquals(caseData.getLegacyCaseReference(), templateData.getReferenceNumber()); + Assertions.assertEquals(CASE_DATA_WITH_RESPONDENT1.getLegacyCaseReference(), templateData.getReferenceNumber()); Assertions.assertEquals( - caseData.getDetailsOfWhyDoesYouDisputeTheClaim(), + CASE_DATA_WITH_RESPONDENT1.getDetailsOfWhyDoesYouDisputeTheClaim(), templateData.getWhyDisputeTheClaim() ); Assertions.assertEquals( - caseData.getRespondent1DQ().getRespondent1DQStatementOfTruth().getName(), + CASE_DATA_WITH_RESPONDENT1.getRespondent1DQ().getRespondent1DQStatementOfTruth().getName(), templateData.getStatementOfTruth().getName() ); Assertions.assertEquals( - caseData.getRespondent1DQ().getRespondent1DQStatementOfTruth().getRole(), + CASE_DATA_WITH_RESPONDENT1.getRespondent1DQ().getRespondent1DQStatementOfTruth().getRole(), templateData.getStatementOfTruth().getRole() ); } @Test public void contentCheckRespondent2() { - List locations = new ArrayList<>(); - locations.add(LocationRefData.builder().siteName("SiteName").courtAddress("1").postcode("1") - .courtName("Court Name2").region("Region").regionId("4").courtVenueId("000") - .courtTypeId("10").courtLocationCode("121") - .epimmsId("000000").build()); - when(locationRefDataService.getCourtLocationsByEpimmsId(any(), any())).thenReturn(locations); CaseData caseData = CaseData.builder() .legacyCaseReference("case reference") .detailsOfWhyDoesYouDisputeTheClaim("why dispute the claim") @@ -170,19 +152,12 @@ public void contentCheckRespondent2() { templateData.getStatementOfTruth().getName()); Assertions.assertEquals(caseData.getRespondent2DQ().getRespondent2DQStatementOfTruth().getRole(), templateData.getStatementOfTruth().getRole()); - Assertions.assertEquals(locations.get(0).getCourtName(), + Assertions.assertEquals(LOCATIONS.get(0).getCourtName(), templateData.getHearingCourtLocation()); } @Test public void contentCheckMultiparty() { - List locations = new ArrayList<>(); - locations.add(LocationRefData.builder().siteName("SiteName").courtAddress("1").postcode("1") - .courtName("Court Name2").region("Region").regionId("4").courtVenueId("000") - .courtTypeId("10").courtLocationCode("121") - .epimmsId("000000").build()); - when(locationRefDataService.getCourtLocationsByEpimmsId(any(), any())).thenReturn(locations); - List timelines = new ArrayList<>(); timelines.add(TimelineOfEvents.builder() .value(TimelineOfEventDetails.builder() @@ -264,4 +239,85 @@ public void contentCheckMultiparty() { templateData.getStatementOfTruth().getRole() ); } + + @Test + void shouldSelectTemplateWithRepaymentPlan_whenPinAndPostEnabled() { + //Given + DocmosisDocument docmosisDocument = DocmosisDocument.builder().build(); + given(featureToggleService.isPinInPostEnabled()).willReturn(true); + given(documentGeneratorService.generateDocmosisDocument(any(MappableObject.class), any())) + .willReturn(docmosisDocument); + //When + generator.generate(CASE_DATA_WITH_RESPONDENT1, BEARER_TOKEN); + //Then + verify(documentGeneratorService).generateDocmosisDocument(templateDataCaptor.capture(), docmosisTemplatesArgumentCaptor.capture()); + assertThat(docmosisTemplatesArgumentCaptor.getValue()).isEqualTo(DocmosisTemplates.DEFENDANT_RESPONSE_SPEC_SEALED_1V1_INSTALLMENTS); + } + + @Test + void shouldSelectTemplateWithoutRepaymentPlan_whenPinAndPostDisabled() { + //Given + DocmosisDocument docmosisDocument = DocmosisDocument.builder().build(); + given(featureToggleService.isPinInPostEnabled()).willReturn(false); + given(documentGeneratorService.generateDocmosisDocument(any(MappableObject.class), any())) + .willReturn(docmosisDocument); + //When + generator.generate(CASE_DATA_WITH_RESPONDENT1, BEARER_TOKEN); + //Then + verify(documentGeneratorService).generateDocmosisDocument(templateDataCaptor.capture(), docmosisTemplatesArgumentCaptor.capture()); + assertThat(docmosisTemplatesArgumentCaptor.getValue()).isEqualTo(DocmosisTemplates.DEFENDANT_RESPONSE_SPEC_SEALED_1v1); + } + + @Test + void shouldSelectMultipartyTemplate_whenMultipartyCase() { + //Given + DocmosisDocument docmosisDocument = DocmosisDocument.builder().build(); + given(documentGeneratorService.generateDocmosisDocument(any(MappableObject.class), any())) + .willReturn(docmosisDocument); + CaseData multipartyCaseData = CASE_DATA_WITH_RESPONDENT1.toBuilder() + .respondent2(Party.builder() + .type(Party.Type.COMPANY) + .companyName("defendant2 name") + .build()) + .respondentResponseIsSame(YesOrNo.YES) + .build(); + //When + generator.generate(multipartyCaseData, BEARER_TOKEN); + //Then + verify(documentGeneratorService).generateDocmosisDocument(templateDataCaptor.capture(), docmosisTemplatesArgumentCaptor.capture()); + assertThat(docmosisTemplatesArgumentCaptor.getValue()).isEqualTo(DocmosisTemplates.DEFENDANT_RESPONSE_SPEC_SEALED_1v2); + } + + private static CaseData getCaseDataWithRespondent1Data() { + return CaseData.builder() + .legacyCaseReference("case reference") + .detailsOfWhyDoesYouDisputeTheClaim("why dispute the claim") + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQStatementOfTruth( + StatementOfTruth.builder() + .name("sot name") + .role("sot role") + .build() + ) + .respondent1DQRequestedCourt( + RequestedCourt.builder() + .responseCourtCode("121") + .reasonForHearingAtSpecificCourt("test") + .caseLocation(CaseLocationCivil.builder() + .region("2") + .baseLocation("000000") + .build()) + .build()) + .build()) + .applicant1(Party.builder() + .type(Party.Type.COMPANY) + .companyName("applicant name") + .build()) + .respondent1(Party.builder() + .type(Party.Type.COMPANY) + .companyName("defendant name") + .build()) + .respondent1ResponseDate(LocalDateTime.now()) + .build(); + } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/trialready/TrialReadyFormGeneratorTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/trialready/TrialReadyFormGeneratorTest.java index 5c583547a63..42ad5fd28d5 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/trialready/TrialReadyFormGeneratorTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/docmosis/trialready/TrialReadyFormGeneratorTest.java @@ -10,6 +10,7 @@ import uk.gov.hmcts.reform.civil.documentmanagement.UnsecuredDocumentManagementService; import uk.gov.hmcts.reform.civil.documentmanagement.model.CaseDocument; import uk.gov.hmcts.reform.civil.documentmanagement.model.PDF; +import uk.gov.hmcts.reform.civil.enums.CaseRole; import uk.gov.hmcts.reform.civil.enums.YesOrNo; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.Party; @@ -37,7 +38,7 @@ TrialReadyFormGenerator.class, JacksonAutoConfiguration.class }) -public class TrialReadyFormGeneratorTest { +class TrialReadyFormGeneratorTest { private static final String BEARER_TOKEN = "Bearer Token"; private static final byte[] bytes = {1, 2, 3, 4, 5, 6}; @@ -47,13 +48,10 @@ public class TrialReadyFormGeneratorTest { .documentName(fileName_application) .documentType(TRIAL_READY_DOCUMENT) .build(); - @MockBean private UnsecuredDocumentManagementService documentManagementService; - @MockBean private DocumentGeneratorService documentGeneratorService; - @Autowired private TrialReadyFormGenerator generator; @@ -72,7 +70,8 @@ void shouldTrialReadyFormGeneratorOneForm_whenValidDataIsProvided() { .revisedHearingRequirements(YesOrNo.YES) .revisedHearingComments("Revised Hearing Comments").build()).build(); // When - CaseDocument caseDocument = generator.generate(caseData, BEARER_TOKEN, "GenerateTrialReadyFormApplicant"); + CaseDocument caseDocument = generator.generate(caseData, BEARER_TOKEN, "GenerateTrialReadyFormApplicant", + CaseRole.APPLICANTSOLICITORONE); // Then assertThat(caseDocument).isNotNull(); @@ -97,7 +96,8 @@ void shouldTrialReadyFormGeneratorOneForm_whenRespondent1GenerateDocs() { .revisedHearingRequirements(YesOrNo.YES) .revisedHearingComments("Revised Hearing Comments").build()).build(); // When - CaseDocument caseDocument = generator.generate(caseData, BEARER_TOKEN, "GenerateTrialReadyFormRespondent1"); + CaseDocument caseDocument = generator.generate(caseData, BEARER_TOKEN, "GenerateTrialReadyFormRespondent1", + CaseRole.RESPONDENTSOLICITORONE); // Then assertThat(caseDocument).isNotNull(); @@ -123,7 +123,8 @@ void shouldTrialReadyFormGeneratorOneForm_whenRespondent2GenerateDocs() { .revisedHearingRequirements(YesOrNo.YES) .revisedHearingComments("Revised Hearing Comments").build()).build(); // When - CaseDocument caseDocument = generator.generate(caseData, BEARER_TOKEN, "GenerateTrialReadyFormRespondent2"); + CaseDocument caseDocument = generator.generate(caseData, BEARER_TOKEN, "GenerateTrialReadyFormRespondent2", + CaseRole.RESPONDENTSOLICITORTWO); // Then assertThat(caseDocument).isNotNull(); @@ -149,7 +150,8 @@ void shouldTrialReadyFormGeneratorOneForm_whenRespondent2OrganisationGenerateDoc .revisedHearingRequirements(YesOrNo.NO) .revisedHearingComments("Revised Hearing Comments").build()).build(); // When - CaseDocument caseDocument = generator.generate(caseData, BEARER_TOKEN, "GenerateTrialReadyFormRespondent2"); + CaseDocument caseDocument = generator.generate(caseData, BEARER_TOKEN, "GenerateTrialReadyFormRespondent2", + CaseRole.RESPONDENTSOLICITORTWO); // Then assertThat(caseDocument).isNotNull(); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/documentmanagement/DocumentDownloadServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/documentmanagement/DocumentDownloadServiceTest.java index c4e8f3795af..97268efc706 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/documentmanagement/DocumentDownloadServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/documentmanagement/DocumentDownloadServiceTest.java @@ -6,7 +6,6 @@ import org.mockito.Mock; import org.springframework.core.io.ByteArrayResource; import org.springframework.test.context.junit.jupiter.SpringExtension; -import uk.gov.hmcts.reform.civil.config.SystemUpdateUserConfiguration; import uk.gov.hmcts.reform.civil.documentmanagement.DocumentManagementService; import uk.gov.hmcts.reform.civil.documentmanagement.model.DownloadedDocumentResponse; import uk.gov.hmcts.reform.civil.service.UserService; @@ -19,12 +18,11 @@ @ExtendWith(SpringExtension.class) public class DocumentDownloadServiceTest { + private static final String BEARER_TOKEN = "Bearer Token"; @Mock private UserService userService; @Mock private DocumentManagementService documentManagementService; - @Mock - private SystemUpdateUserConfiguration userConfig; @InjectMocks private DocumentDownloadService documentDownloadService; @@ -40,7 +38,7 @@ void testDownloadDocumentById() { when(documentManagementService.downloadDocumentWithMetaData(anyString(), anyString())).thenReturn(expectedDoc); // when - DownloadedDocumentResponse downloadedDoc = documentDownloadService.downloadDocument(documentId); + DownloadedDocumentResponse downloadedDoc = documentDownloadService.downloadDocument(BEARER_TOKEN, documentId); //Then assertEquals(downloadedDoc, expectedDoc); } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowPredicateTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowPredicateTest.java index 4667917b19e..89a8e8f507a 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowPredicateTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowPredicateTest.java @@ -14,6 +14,7 @@ import uk.gov.hmcts.reform.civil.handler.callback.user.spec.show.ResponseOneVOneShowTag; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.DefendantPinToPostLRspec; +import uk.gov.hmcts.reform.civil.model.Mediation; import uk.gov.hmcts.reform.civil.model.Party; import uk.gov.hmcts.reform.civil.model.SmallClaimMedicalLRspec; import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; @@ -99,14 +100,20 @@ import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.specClaim; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineAfterClaimDetailsNotified; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineAfterClaimNotified; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineAfterNotSuitableForSdo; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineAfterSDO; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaff; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterClaimDetailsNotified; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterClaimDetailsNotifiedExtension; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterClaimIssue; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterClaimNotified; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterClaimantResponseBeforeSDO; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterDefendantResponse; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterNotificationAcknowledged; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterNotificationAcknowledgedTimeExtension; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffAfterSDO; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffBeforeClaimIssued; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineByStaffBeforeMediationUnsuccessful; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineBySystem; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineSDONotDrawn; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowPredicate.takenOfflineSDONotDrawnAfterClaimDetailsNotified; @@ -157,6 +164,14 @@ void shouldReturnFalse_whenCaseDataAtDraftState() { CaseData caseData = CaseDataBuilder.builder().atStateClaimDraft().build(); assertFalse(claimSubmittedOneRespondentRepresentative.test(caseData)); } + + @Test + void shouldReturnTrue_whenCaseTakenOfflineBeforeIssue() { + CaseData caseData = CaseDataBuilder.builder().atStateClaimSubmitted() + .takenOfflineByStaff() + .build(); + assertTrue(takenOfflineByStaffBeforeClaimIssued.test(caseData)); + } } @Nested @@ -1256,6 +1271,50 @@ void shouldReturnFalse_whenCaseDataAtStateCaseProceedsInCaseman() { CaseData caseData = CaseDataBuilder.builder().atStateTakenOfflineByStaff().build(); assertFalse(fullDefence.test(caseData)); } + + @Test + void shouldReturnTrue_whenTakenOfflineBeforeClaimantResponseAfterDefendantResponse1v1() { + CaseData caseData = CaseDataBuilder.builder() + .atStateRespondentFullDefence() + .takenOfflineByStaff().build(); + assertTrue(takenOfflineByStaffAfterDefendantResponse.test(caseData)); + } + + @Test + void shouldReturnTrue_whenTakenOfflineBeforeClaimantResponseAfterDefendantResponse1v2DS() { + CaseData caseData = CaseDataBuilder.builder() + .multiPartyClaimTwoDefendantSolicitors() + .atStateRespondentFullDefence() + .respondent2Responds(FULL_DEFENCE) + .takenOfflineByStaff().build(); + assertTrue(takenOfflineByStaffAfterDefendantResponse.test(caseData)); + } + + @Test + void shouldReturnTrue_whenTakenOfflineBeforeClaimantResponseAfterDefendantResponse1v2SS() { + CaseData caseData = CaseDataBuilder.builder() + .multiPartyClaimOneDefendantSolicitor() + .atStateBothRespondentsSameResponse(FULL_DEFENCE) + .takenOfflineByStaff().build(); + assertTrue(takenOfflineByStaffAfterDefendantResponse.test(caseData)); + } + + @Test + void shouldReturnTrue_whenTakenOfflineBeforeClaimantResponseAfterDefendantResponse2v1() { + CaseData caseData = CaseDataBuilder.builder() + .multiPartyClaimTwoApplicants() + .atStateRespondentFullDefence() + .takenOfflineByStaff().build(); + assertTrue(takenOfflineByStaffAfterDefendantResponse.test(caseData)); + } + + @Test + void shouldReturnFalse_whenTakenOfflineAfterClaimantResponseAfterDefendantResponse() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .takenOfflineByStaff().build(); + assertFalse(takenOfflineByStaffAfterDefendantResponse.test(caseData)); + } } @Nested @@ -1705,6 +1764,49 @@ void shouldReturnTrue_whenTakenOfflineBySystem() { assertTrue(takenOfflineBySystem.test(caseData)); } + + @Test + void shouldReturnTrue_whenTakenOfflineByStaffAferClaimantResponseBeforeSdo() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .takenOfflineByStaff() + .build(); + + assertTrue(takenOfflineByStaffAfterClaimantResponseBeforeSDO.test(caseData)); + } + + @Test + void shouldReturnFalse_whenTakenOfflineByStaffAferClaimantResponseAfterSdo() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .takenOfflineByStaff() + .build().toBuilder() + .drawDirectionsOrderRequired(YES).build(); + + assertFalse(takenOfflineByStaffAfterClaimantResponseBeforeSDO.test(caseData)); + } + + @Test + void shouldReturnFalse_whenTakenOfflineByStaffMediationUnsuccessful() { + CaseData caseData = CaseDataBuilder.builder() + .atStateMediationUnsuccessful(MultiPartyScenario.ONE_V_ONE) + .takenOfflineByStaff() + .build(); + + assertFalse(takenOfflineByStaffBeforeMediationUnsuccessful.test(caseData)); + } + + @Test + void shouldReturnFalse_whenTakenOfflineByStaffInMediation() { + CaseData caseData = CaseDataBuilder.builder() + .atStateMediationUnsuccessful(MultiPartyScenario.ONE_V_ONE) + .takenOfflineByStaff() + .build().toBuilder() + .mediation(Mediation.builder().build()) + .build(); + + assertTrue(takenOfflineByStaffBeforeMediationUnsuccessful.test(caseData)); + } } @Nested @@ -2911,6 +3013,27 @@ void shouldReturnFalse_whenTakenOfflineAfterSdoDrawn() { assertFalse(takenOfflineSDONotDrawn.test(caseData)); assertTrue(takenOfflineAfterSDO.test(caseData)); } + + @Test + void shouldReturnTrue_whenTakenOfflineByStaffAfterSdoDrawn() { + CaseData caseData = CaseDataBuilder.builder() + .atStateTakenOfflineByStaffAfterSDO(MultiPartyScenario.ONE_V_ONE) + .build(); + assertFalse(takenOfflineSDONotDrawn.test(caseData)); + assertFalse(takenOfflineAfterSDO.test(caseData)); + assertTrue(takenOfflineByStaffAfterSDO.test(caseData)); + } + + @Test + void shouldReturnTrue_whenTakenOfflineByStaffAfterNotSuitableSdo() { + CaseData caseData = CaseDataBuilder.builder() + .atStateTakenOfflineSDONotDrawn(MultiPartyScenario.ONE_V_ONE) + .takenOfflineByStaff() + .build(); + assertFalse(takenOfflineSDONotDrawn.test(caseData)); + assertFalse(takenOfflineAfterSDO.test(caseData)); + assertTrue(takenOfflineAfterNotSuitableForSdo.test(caseData)); + } } @Nested diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowStateAllowedEventServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowStateAllowedEventServiceTest.java index 523323fcc98..f1dd6858eae 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowStateAllowedEventServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/flowstate/FlowStateAllowedEventServiceTest.java @@ -80,7 +80,12 @@ import static uk.gov.hmcts.reform.civil.callback.CaseEvent.TRIAL_READINESS; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.UPLOAD_TRANSLATED_DOCUMENT; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.WITHDRAW_CLAIM; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.asyncStitchingComplete; import static uk.gov.hmcts.reform.civil.callback.CaseEvent.migrateCase; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.SET_ASIDE_JUDGMENT; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.JUDGMENT_PAID_IN_FULL; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.RECORD_JUDGMENT; +import static uk.gov.hmcts.reform.civil.callback.CaseEvent.TRANSFER_ONLINE_CASE; import static uk.gov.hmcts.reform.civil.enums.CaseCategory.SPEC_CLAIM; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.AWAITING_RESPONSES_FULL_DEFENCE_RECEIVED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.AWAITING_RESPONSES_NOT_FULL_DEFENCE_RECEIVED; @@ -132,6 +137,8 @@ class FlowStateAllowedEventServiceTest { @Autowired FlowStateAllowedEventService flowStateAllowedEventService; + // used by StateFlowEngine bean + @SuppressWarnings("unused") @MockBean private FeatureToggleService toggleService; @@ -312,7 +319,9 @@ public Stream provideArguments(ExtensionContext context) { EVIDENCE_UPLOAD_RESPONDENT, GENERATE_DIRECTIONS_ORDER, TRIAL_READINESS, - BUNDLE_CREATION_NOTIFICATION + BUNDLE_CREATION_NOTIFICATION, + TRANSFER_ONLINE_CASE, + asyncStitchingComplete } ), of( @@ -461,7 +470,8 @@ public Stream provideArguments(ExtensionContext context) { CREATE_SDO, NotSuitable_SDO, APPLICATION_OFFLINE_UPDATE_CLAIM, - migrateCase + migrateCase, + CLAIMANT_RESPONSE_CUI } ), of( @@ -478,7 +488,8 @@ public Stream provideArguments(ExtensionContext context) { CREATE_SDO, NotSuitable_SDO, APPLICATION_OFFLINE_UPDATE_CLAIM, - migrateCase + migrateCase, + CLAIMANT_RESPONSE_CUI } ), of( @@ -555,7 +566,12 @@ public Stream provideArguments(ExtensionContext context) { EVIDENCE_UPLOAD_JUDGE, TRIAL_READINESS, BUNDLE_CREATION_NOTIFICATION, - ADD_UNAVAILABLE_DATES + ADD_UNAVAILABLE_DATES, + SET_ASIDE_JUDGMENT, + JUDGMENT_PAID_IN_FULL, + RECORD_JUDGMENT, + TRANSFER_ONLINE_CASE, + asyncStitchingComplete } ), of( @@ -653,7 +669,8 @@ public Stream provideArguments(ExtensionContext context) { new CaseEvent[]{ DISMISS_CLAIM, migrateCase, - CREATE_SDO + CREATE_SDO, + NotSuitable_SDO } ), of( @@ -744,7 +761,8 @@ public Stream provideArguments(ExtensionContext context) { GENERATE_DIRECTIONS_ORDER, TRIAL_READINESS, BUNDLE_CREATION_NOTIFICATION, - ADD_UNAVAILABLE_DATES + ADD_UNAVAILABLE_DATES, + asyncStitchingComplete } ) ); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/flowstate/StateFlowEngineTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/flowstate/StateFlowEngineTest.java index 2c46dc87319..e281096e8cd 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/flowstate/StateFlowEngineTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/flowstate/StateFlowEngineTest.java @@ -69,6 +69,7 @@ import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.FULL_DEFENCE_PROCEED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.IN_HEARING_READINESS; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.IN_MEDIATION; +import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.MEDIATION_UNSUCCESSFUL_PROCEED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.NOTIFICATION_ACKNOWLEDGED; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.NOTIFICATION_ACKNOWLEDGED_TIME_EXTENSION; import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.PART_ADMISSION; @@ -137,6 +138,36 @@ void shouldReturnClaimSubmitted_whenCaseDataAtStateClaimSubmittedWithOneResponde ); } + @Test + void shouldReturnTakenOffline_whenCaseTakenOfflineBeforeIssue() { + // Given + CaseData caseData = CaseDataBuilder.builder().atStateClaimSubmitted() + .takenOfflineByStaff() + .build(); + + // When + StateFlow stateFlow = stateFlowEngine.evaluate(caseData); + + // Then + assertThat(stateFlow.getState()) + .extracting(State::getName) + .isNotNull() + .isEqualTo(TAKEN_OFFLINE_BY_STAFF.fullName()); + assertThat(stateFlow.getStateHistory()) + .hasSize(3) + .extracting(State::getName) + .containsExactly( + DRAFT.fullName(), CLAIM_SUBMITTED.fullName(), TAKEN_OFFLINE_BY_STAFF.fullName()); + + assertThat(stateFlow.getFlags()).hasSize(5).contains( + entry(FlowFlag.NOTICE_OF_CHANGE.name(), false), + entry(FlowFlag.BULK_CLAIM_ENABLED.name(), false), + entry(FlowFlag.CERTIFICATE_OF_SERVICE.name(), false), + entry(FlowFlag.GENERAL_APPLICATION_ENABLED.name(), false), + entry("ONE_RESPONDENT_REPRESENTATIVE", true) + ); + } + @Test void shouldReturnClaimSubmitted_whenCaseDataAtStateClaimSubmittedTwoRespondentRepresentatives() { // Given @@ -2405,6 +2436,34 @@ void shouldReturnFullDefenceProceed_whenCaseDataAtStateApplicantRespondToDefence } } + @Test + void shouldReturnTakenOfflineAfterSDO_whenTransitionedFromMediationUnsuccessfulProceed() { + // Given + CaseData caseData = CaseDataBuilder.builder() + .atStateMediationUnsuccessful(MultiPartyScenario.ONE_V_ONE) + .takenOfflineDate(LocalDateTime.now()) + .build().toBuilder() + .drawDirectionsOrderRequired(NO).build(); + + // When + StateFlow stateFlow = stateFlowEngine.evaluate(caseData); + + // Then + assertThat(stateFlow.getState()) + .extracting(State::getName) + .isNotNull() + .isEqualTo(TAKEN_OFFLINE_AFTER_SDO.fullName()); + assertThat(stateFlow.getStateHistory()) + .hasSize(9) + .extracting(State::getName) + .containsExactly( + SPEC_DRAFT.fullName(), CLAIM_SUBMITTED.fullName(), CLAIM_ISSUED_PAYMENT_SUCCESSFUL.fullName(), + PENDING_CLAIM_ISSUED.fullName(), CLAIM_ISSUED.fullName(), FULL_DEFENCE.fullName(), + IN_MEDIATION.fullName(), MEDIATION_UNSUCCESSFUL_PROCEED.fullName(), TAKEN_OFFLINE_AFTER_SDO.fullName() + ); + + } + //1v2 Different solicitor scenario-first response FullDefence received and with time extension @Test void shouldAwaitResponse_1v2DiffSol_whenFirstResponseIsFullDefenceAndTimeExtension() { @@ -2703,6 +2762,34 @@ void shouldReturnClaimDismissedState_whenPastClaimNotificationDeadlineAndProcess ); } + @Test + void shouldReturnClaimDismissedHearingFeeDueDeadline_whenTransitionedFromMediationUnsuccessfulProceed() { + // Given + CaseData caseData = CaseDataBuilder.builder() + .atStateMediationUnsuccessful(MultiPartyScenario.ONE_V_ONE) + .caseDismissedHearingFeeDueDate(LocalDateTime.now().minusDays(1)) + .build(); + + // When + StateFlow stateFlow = stateFlowEngine.evaluate(caseData); + + // Then + assertThat(stateFlow.getState()) + .extracting(State::getName) + .isNotNull() + .isEqualTo(CLAIM_DISMISSED_HEARING_FEE_DUE_DEADLINE.fullName()); + assertThat(stateFlow.getStateHistory()) + .hasSize(9) + .extracting(State::getName) + .containsExactly( + SPEC_DRAFT.fullName(), CLAIM_SUBMITTED.fullName(), CLAIM_ISSUED_PAYMENT_SUCCESSFUL.fullName(), + PENDING_CLAIM_ISSUED.fullName(), CLAIM_ISSUED.fullName(), FULL_DEFENCE.fullName(), + IN_MEDIATION.fullName(), MEDIATION_UNSUCCESSFUL_PROCEED.fullName(), + CLAIM_DISMISSED_HEARING_FEE_DUE_DEADLINE.fullName() + ); + + } + @Test void shouldReturnAwaitingCamundaState_whenCaseDataIsPastClaimDetailsNotification() { // Given @@ -4570,62 +4657,126 @@ void partAdmitNoMediationSpec() { } } - @Test - void shouldReturnInHearingReadiness_whenTransitionedFromCaseDetailsNotified() { - // Given + @Nested + class ToInHearingReadiness { - CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() - .hearingReferenceNumber("11111111") - .listingOrRelisting(ListingOrRelisting.LISTING) - .build(); + @Test + void shouldReturnInHearingReadiness_whenTransitionedFromCaseDetailsNotified() { + // Given - // When - StateFlow stateFlow = stateFlowEngine.evaluate(caseData); + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build().toBuilder() + .hearingReferenceNumber("11111111") + .listingOrRelisting(ListingOrRelisting.LISTING) + .build(); - // Then - assertThat(stateFlow.getState()) - .extracting(State::getName) - .isNotNull() - .isEqualTo(IN_HEARING_READINESS.fullName()); - assertThat(stateFlow.getStateHistory()) - .hasSize(8) - .extracting(State::getName) - .containsExactly( - DRAFT.fullName(), CLAIM_SUBMITTED.fullName(), CLAIM_ISSUED_PAYMENT_SUCCESSFUL.fullName(), - PENDING_CLAIM_ISSUED.fullName(), CLAIM_ISSUED.fullName(), CLAIM_NOTIFIED.fullName(), - CLAIM_DETAILS_NOTIFIED.fullName(), IN_HEARING_READINESS.fullName() + // When + StateFlow stateFlow = stateFlowEngine.evaluate(caseData); + + // Then + assertThat(stateFlow.getState()) + .extracting(State::getName) + .isNotNull() + .isEqualTo(IN_HEARING_READINESS.fullName()); + assertThat(stateFlow.getStateHistory()) + .hasSize(8) + .extracting(State::getName) + .containsExactly( + DRAFT.fullName(), CLAIM_SUBMITTED.fullName(), CLAIM_ISSUED_PAYMENT_SUCCESSFUL.fullName(), + PENDING_CLAIM_ISSUED.fullName(), CLAIM_ISSUED.fullName(), CLAIM_NOTIFIED.fullName(), + CLAIM_DETAILS_NOTIFIED.fullName(), IN_HEARING_READINESS.fullName() + ); + + assertThat(stateFlow.getFlags()).hasSize(5).contains( + entry(FlowFlag.BULK_CLAIM_ENABLED.name(), false), + entry(FlowFlag.NOTICE_OF_CHANGE.name(), false), + entry(FlowFlag.GENERAL_APPLICATION_ENABLED.name(), false), + entry("ONE_RESPONDENT_REPRESENTATIVE", true), + entry(FlowFlag.CERTIFICATE_OF_SERVICE.name(), false) ); + } + + @Test + void shouldReturnInHearingReadiness_whenTransitionedFromFullDefenseProceed() { + // Given + CaseData caseData = CaseData.builder() + .caseAccessCategory(SPEC_CLAIM) + .submittedDate(LocalDateTime.now()) + .respondent1Represented(YES) + .paymentSuccessfulDate(LocalDateTime.now()) + .issueDate(LocalDate.now()) + .respondent1OrgRegistered(YES) + .claimNotificationDeadline(LocalDateTime.now()) + .respondent1ResponseDate(LocalDateTime.now()) + .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_DEFENCE) + .claimNotificationDate(LocalDateTime.now()) + .responseClaimTrack(AllocatedTrack.SMALL_CLAIM.name()) + .responseClaimMediationSpecRequired(YES) + .applicant1ProceedWithClaim(YES) + .applicant1ClaimMediationSpecRequired( + SmallClaimMedicalLRspec.builder() + .hasAgreedFreeMediation(NO) + .build()) + .hearingReferenceNumber("11111111") + .listingOrRelisting(ListingOrRelisting.LISTING) + .build(); - assertThat(stateFlow.getFlags()).hasSize(5).contains( - entry(FlowFlag.BULK_CLAIM_ENABLED.name(), false), - entry(FlowFlag.NOTICE_OF_CHANGE.name(), false), - entry(FlowFlag.GENERAL_APPLICATION_ENABLED.name(), false), - entry("ONE_RESPONDENT_REPRESENTATIVE", true), - entry(FlowFlag.CERTIFICATE_OF_SERVICE.name(), false) - ); + // When + StateFlow stateFlow = stateFlowEngine.evaluate(caseData); + + // Then + assertThat(stateFlow.getState()) + .extracting(State::getName) + .isNotNull() + .isEqualTo(IN_HEARING_READINESS.fullName()); + assertThat(stateFlow.getStateHistory()) + .hasSize(8) + .extracting(State::getName) + .containsExactly( + SPEC_DRAFT.fullName(), CLAIM_SUBMITTED.fullName(), CLAIM_ISSUED_PAYMENT_SUCCESSFUL.fullName(), + PENDING_CLAIM_ISSUED.fullName(), CLAIM_ISSUED.fullName(), FULL_DEFENCE.fullName(), + FULL_DEFENCE_PROCEED.fullName(), IN_HEARING_READINESS.fullName() + ); + } + + @Test + void shouldReturnInHearingReadiness_whenTransitionedFromPartAdmitNotSettledNoMediation() { + CaseData caseData = CaseData.builder() + // spec claim + .caseAccessCategory(SPEC_CLAIM) + // claim submitted + .submittedDate(LocalDateTime.now()) + .respondent1Represented(YES) + // payment successful + .paymentSuccessfulDate(LocalDateTime.now()) + // pending claim issued + .issueDate(LocalDate.now()) + .respondent1OrgRegistered(YES) + // claim issued + .claimNotificationDeadline(LocalDateTime.now()) + // part admit + .respondent1ResponseDate(LocalDateTime.now()) + .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.PART_ADMISSION) + .claimNotificationDate(LocalDateTime.now()) + .responseClaimTrack(AllocatedTrack.SMALL_CLAIM.name()) + .responseClaimMediationSpecRequired(NO) + .applicant1PartAdmitConfirmAmountPaidSpec(NO) + .hearingReferenceNumber("11111111") + .listingOrRelisting(ListingOrRelisting.LISTING) + .build(); + + // When + StateFlow fullState = stateFlowEngine.evaluate(caseData); + + // Then + assertEquals(IN_HEARING_READINESS.fullName(), fullState.getState().getName()); + } } @Test - void shouldReturnInHearingReadiness_whenTransitionedFromFullDefenseProceed() { + void shouldReturnInHearingReadiness_whenTransitionedFromMediationUnsuccesfulProceed() { // Given - CaseData caseData = CaseData.builder() - .caseAccessCategory(SPEC_CLAIM) - .submittedDate(LocalDateTime.now()) - .respondent1Represented(YES) - .paymentSuccessfulDate(LocalDateTime.now()) - .issueDate(LocalDate.now()) - .respondent1OrgRegistered(YES) - .claimNotificationDeadline(LocalDateTime.now()) - .respondent1ResponseDate(LocalDateTime.now()) - .respondent1ClaimResponseTypeForSpec(RespondentResponseTypeSpec.FULL_DEFENCE) - .claimNotificationDate(LocalDateTime.now()) - .responseClaimTrack(AllocatedTrack.SMALL_CLAIM.name()) - .responseClaimMediationSpecRequired(YES) - .applicant1ProceedWithClaim(YES) - .applicant1ClaimMediationSpecRequired( - SmallClaimMedicalLRspec.builder() - .hasAgreedFreeMediation(NO) - .build()) + CaseData caseData = CaseDataBuilder.builder() + .atStateMediationUnsuccessful(MultiPartyScenario.ONE_V_ONE) .hearingReferenceNumber("11111111") .listingOrRelisting(ListingOrRelisting.LISTING) .build(); @@ -4639,12 +4790,12 @@ void shouldReturnInHearingReadiness_whenTransitionedFromFullDefenseProceed() { .isNotNull() .isEqualTo(IN_HEARING_READINESS.fullName()); assertThat(stateFlow.getStateHistory()) - .hasSize(8) + .hasSize(9) .extracting(State::getName) .containsExactly( SPEC_DRAFT.fullName(), CLAIM_SUBMITTED.fullName(), CLAIM_ISSUED_PAYMENT_SUCCESSFUL.fullName(), PENDING_CLAIM_ISSUED.fullName(), CLAIM_ISSUED.fullName(), FULL_DEFENCE.fullName(), - FULL_DEFENCE_PROCEED.fullName(), IN_HEARING_READINESS.fullName() + IN_MEDIATION.fullName(), MEDIATION_UNSUCCESSFUL_PROCEED.fullName(), IN_HEARING_READINESS.fullName() ); } @@ -4797,6 +4948,34 @@ void shouldReaturnTakenOfflineSdoNotDrawn_whenCaseDataAtStateClaimAcknowledgeTim entry(FlowFlag.CERTIFICATE_OF_SERVICE.name(), false) ); } + + @Test + void shouldReturnTakenOfflineSDONotDrawn_whenTransitionedFromMediationUnsuccessfulProceed() { + // Given + CaseData caseData = CaseDataBuilder.builder() + .atStateMediationUnsuccessful(MultiPartyScenario.ONE_V_ONE) + .reasonNotSuitableSDO(ReasonNotSuitableSDO.builder().input("Unsuitable").build()) + .takenOfflineDate(LocalDateTime.now()) + .build(); + + // When + StateFlow stateFlow = stateFlowEngine.evaluate(caseData); + + // Then + assertThat(stateFlow.getState()) + .extracting(State::getName) + .isNotNull() + .isEqualTo(TAKEN_OFFLINE_SDO_NOT_DRAWN.fullName()); + assertThat(stateFlow.getStateHistory()) + .hasSize(9) + .extracting(State::getName) + .containsExactly( + SPEC_DRAFT.fullName(), CLAIM_SUBMITTED.fullName(), CLAIM_ISSUED_PAYMENT_SUCCESSFUL.fullName(), + PENDING_CLAIM_ISSUED.fullName(), CLAIM_ISSUED.fullName(), FULL_DEFENCE.fullName(), + IN_MEDIATION.fullName(), MEDIATION_UNSUCCESSFUL_PROCEED.fullName(), TAKEN_OFFLINE_SDO_NOT_DRAWN.fullName() + ); + + } } @Nested diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/hearings/HearingValuesServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/hearings/HearingValuesServiceTest.java index 54aabdac7e9..90bbaa24824 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/hearings/HearingValuesServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/hearings/HearingValuesServiceTest.java @@ -26,11 +26,14 @@ import uk.gov.hmcts.reform.civil.enums.dq.Language; import uk.gov.hmcts.reform.civil.enums.hearing.CategoryType; import uk.gov.hmcts.reform.civil.exceptions.CaseNotFoundException; -import uk.gov.hmcts.reform.civil.exceptions.PartyIdsUpdatedException; +import uk.gov.hmcts.reform.civil.exceptions.MissingFieldsUpdatedException; import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.UnavailableDate; +import uk.gov.hmcts.reform.civil.model.caseflags.Flags; import uk.gov.hmcts.reform.civil.model.defaultjudgment.CaseLocationCivil; import uk.gov.hmcts.reform.civil.model.dq.Applicant1DQ; +import uk.gov.hmcts.reform.civil.model.dq.Hearing; import uk.gov.hmcts.reform.civil.model.dq.Respondent1DQ; import uk.gov.hmcts.reform.civil.model.dq.WelshLanguageRequirements; import uk.gov.hmcts.reform.civil.model.hearingvalues.CaseCategoryModel; @@ -48,6 +51,7 @@ import uk.gov.hmcts.reform.civil.service.CategoryService; import uk.gov.hmcts.reform.civil.service.CoreCaseDataService; import uk.gov.hmcts.reform.civil.service.OrganisationService; +import uk.gov.hmcts.reform.civil.utils.CaseFlagsInitialiser; import java.time.format.DateTimeFormatter; import java.util.List; @@ -67,11 +71,13 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.enums.CaseCategory.UNSPEC_CLAIM; +import static uk.gov.hmcts.reform.civil.enums.dq.UnavailableDateType.SINGLE_DATE; import static uk.gov.hmcts.reform.civil.enums.hearing.HMCLocationType.COURT; import static uk.gov.hmcts.reform.civil.enums.hearing.PartyType.IND; import static uk.gov.hmcts.reform.civil.enums.hearing.PartyType.ORG; import static uk.gov.hmcts.reform.civil.helpers.hearingsmappings.CaseFlagsMapper.getCaseFlags; import static uk.gov.hmcts.reform.civil.helpers.hearingsmappings.ScreenFlowMapper.getScreenFlow; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = { @@ -93,6 +99,8 @@ public class HearingValuesServiceTest { private CategoryService categoryService; @Mock private OrganisationService organisationService; + @Mock + private CaseFlagsInitialiser caseFlagsInitialiser; @Autowired private ObjectMapper mapper; @@ -125,6 +133,10 @@ void shouldReturnExpectedHearingValuesWhenCaseDataIsReturned() throws Exception .applicant1DQ(applicant1DQ) .respondent1DQ(respondent1DQ) .build(); + caseData = caseData.toBuilder() + .applicant1(caseData.getApplicant1().toBuilder() + .flags(Flags.builder().partyName("party name").build()) + .build()).build(); Long caseId = 1L; CaseDetails caseDetails = CaseDetails.builder() .data(caseData.toMap(mapper)) @@ -203,12 +215,48 @@ void shouldReturnExpectedHearingValuesWhenCaseDataIsReturned() throws Exception @SneakyThrows @Test - void shouldTriggerEventAndThrowPartyFlagsUpdatedExceptionIfPartyIdMissingFromApplicant1() throws Exception { + void shouldTriggerEventAndThrowMissingFieldsUpdatedExceptionIfPartyIdMissingFromApplicant1() throws Exception { + Long caseId = 1L; + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued() + .caseReference(caseId) + .applicant1(PartyBuilder.builder().individual().build().toBuilder() + .flags(Flags.builder().partyName("party name").build()).build()) + .respondent1(PartyBuilder.builder().company().build()) + .respondent2(PartyBuilder.builder().company().build()) + .multiPartyClaimTwoDefendantSolicitors() + .caseAccessCategory(UNSPEC_CLAIM) + .caseManagementLocation(CaseLocationCivil.builder().baseLocation(BASE_LOCATION_ID) + .region(WELSH_REGION_ID).build()) + .build(); + CaseDetails caseDetails = CaseDetails.builder() + .data(caseData.toMap(mapper)) + .id(caseId).build(); + + when(caseDataService.getCase(caseId)).thenReturn(caseDetails); + when(caseDetailsConverter.toCaseData(caseDetails.getData())).thenReturn(caseData); + when(organisationService.findOrganisationById(APPLICANT_ORG_ID)) + .thenReturn(Optional.of(Organisation.builder() + .name(APPLICANT_LR_ORG_NAME) + .build())); + when(organisationService.findOrganisationById(RESPONDENT_ONE_ORG_ID)) + .thenReturn(Optional.of(Organisation.builder() + .name(RESPONDENT_ONE_LR_ORG_NAME) + .build())); + given(manageCaseBaseUrlConfiguration.getManageCaseBaseUrl()).willReturn("http://localhost:3333"); + given(paymentsConfiguration.getSiteId()).willReturn("AAA7"); + + assertThrows(MissingFieldsUpdatedException.class, () -> { + hearingValuesService.getValues(caseId, "8AB87C89", "auth"); + }); + + verify(caseDataService).triggerEvent(eq(caseId), eq(CaseEvent.UPDATE_MISSING_FIELDS), any()); + } + + @SneakyThrows + @Test + void shouldTriggerEventAndThrowMissingFieldsUpdatedExceptionIfCaseFlagsMissingFromApplicant1() throws Exception { Long caseId = 1L; - Applicant1DQ applicant1DQ = Applicant1DQ.builder().applicant1DQLanguage( - WelshLanguageRequirements.builder().court(Language.ENGLISH).build()).build(); - Respondent1DQ respondent1DQ = Respondent1DQ.builder().respondent1DQLanguage( - WelshLanguageRequirements.builder().court(Language.WELSH).build()).build(); CaseData caseData = CaseDataBuilder.builder() .atStateClaimIssued() .caseReference(caseId) @@ -218,8 +266,6 @@ void shouldTriggerEventAndThrowPartyFlagsUpdatedExceptionIfPartyIdMissingFromApp .caseAccessCategory(UNSPEC_CLAIM) .caseManagementLocation(CaseLocationCivil.builder().baseLocation(BASE_LOCATION_ID) .region(WELSH_REGION_ID).build()) - .applicant1DQ(applicant1DQ) - .respondent1DQ(respondent1DQ) .build(); CaseDetails caseDetails = CaseDetails.builder() .data(caseData.toMap(mapper)) @@ -238,20 +284,78 @@ void shouldTriggerEventAndThrowPartyFlagsUpdatedExceptionIfPartyIdMissingFromApp given(manageCaseBaseUrlConfiguration.getManageCaseBaseUrl()).willReturn("http://localhost:3333"); given(paymentsConfiguration.getSiteId()).willReturn("AAA7"); - assertThrows(PartyIdsUpdatedException.class, () -> { + assertThrows(MissingFieldsUpdatedException.class, () -> { hearingValuesService.getValues(caseId, "8AB87C89", "auth"); }); - verify(caseDataService).triggerEvent(eq(caseId), eq(CaseEvent.UPDATE_PARTY_IDS), any()); + verify(caseDataService).triggerEvent(eq(caseId), eq(CaseEvent.UPDATE_MISSING_FIELDS), any()); } + @SneakyThrows @Test - void shouldNotTriggerEventIfPartyIdExistsForApplicant1() throws Exception { + void shouldTriggerEventAndThrowMissingFieldsUpdatedExceptionIfUnavailableDatesMissingFromApplicant1() throws Exception { + Long caseId = 1L; + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued() + .caseReference(caseId) + .applicant1(PartyBuilder.builder().individual().build().toBuilder() + .partyID("party-id") + .flags(Flags.builder().partyName("party name").build()) + .unavailableDates(wrapElements(List.of(UnavailableDate.builder() + .unavailableDateType(SINGLE_DATE) + .date(LocalDate.of(2023, 10, 5)) + .build()))) + .build()) + .respondent1(PartyBuilder.builder().company().build()) + .respondent2(PartyBuilder.builder().company().build()) + .multiPartyClaimTwoDefendantSolicitors() + .caseAccessCategory(UNSPEC_CLAIM) + .caseManagementLocation(CaseLocationCivil.builder().baseLocation(BASE_LOCATION_ID) + .region(WELSH_REGION_ID).build()) + .build(); + CaseDetails caseDetails = CaseDetails.builder() + .data(caseData.toMap(mapper)) + .id(caseId).build(); + + when(caseDataService.getCase(caseId)).thenReturn(caseDetails); + when(caseDetailsConverter.toCaseData(caseDetails.getData())).thenReturn(caseData); + when(organisationService.findOrganisationById(APPLICANT_ORG_ID)) + .thenReturn(Optional.of(Organisation.builder() + .name(APPLICANT_LR_ORG_NAME) + .build())); + when(organisationService.findOrganisationById(RESPONDENT_ONE_ORG_ID)) + .thenReturn(Optional.of(Organisation.builder() + .name(RESPONDENT_ONE_LR_ORG_NAME) + .build())); + given(manageCaseBaseUrlConfiguration.getManageCaseBaseUrl()).willReturn("http://localhost:3333"); + given(paymentsConfiguration.getSiteId()).willReturn("AAA7"); + + assertThrows(MissingFieldsUpdatedException.class, () -> { + hearingValuesService.getValues(caseId, "8AB87C89", "auth"); + }); + + verify(caseDataService).triggerEvent(eq(caseId), eq(CaseEvent.UPDATE_MISSING_FIELDS), any()); + } + + @Test + void shouldNotTriggerEventIfPartyIdCaseFlagsUnavailableDatesExistsForApplicant1() throws Exception { Long caseId = 1L; Applicant1DQ applicant1DQ = Applicant1DQ.builder().applicant1DQLanguage( - WelshLanguageRequirements.builder().court(Language.ENGLISH).build()).build(); + WelshLanguageRequirements.builder().court(Language.ENGLISH).build()) + .applicant1DQHearing(Hearing.builder() + .unavailableDates(wrapElements(List.of(UnavailableDate.builder() + .unavailableDateType(SINGLE_DATE) + .date(LocalDate.of(2023, 10, 20)) + .build()))).build()) + .build(); Respondent1DQ respondent1DQ = Respondent1DQ.builder().respondent1DQLanguage( - WelshLanguageRequirements.builder().court(Language.WELSH).build()).build(); + WelshLanguageRequirements.builder().court(Language.WELSH).build()) + .respondent1DQHearing(Hearing.builder() + .unavailableDates(wrapElements(List.of(UnavailableDate.builder() + .unavailableDateType(SINGLE_DATE) + .date(LocalDate.of(2023, 10, 20)) + .build()))).build()) + .build(); CaseData caseData = CaseDataBuilder.builder() .atStateClaimIssued() .applicant1(PartyBuilder.builder().build() @@ -261,7 +365,6 @@ void shouldNotTriggerEventIfPartyIdExistsForApplicant1() throws Exception { .caseReference(caseId) .applicant1(PartyBuilder.builder().individual().build()) .respondent1(PartyBuilder.builder().company().build()) - .respondent2(PartyBuilder.builder().company().build()) .caseAccessCategory(UNSPEC_CLAIM) .caseManagementLocation(CaseLocationCivil.builder().baseLocation(BASE_LOCATION_ID) .region(WELSH_REGION_ID).build()) @@ -286,7 +389,7 @@ void shouldNotTriggerEventIfPartyIdExistsForApplicant1() throws Exception { given(paymentsConfiguration.getSiteId()).willReturn("AAA7"); verify(caseDataService, times(0)) - .triggerEvent(eq(caseId), eq(CaseEvent.UPDATE_PARTY_IDS), any()); + .triggerEvent(eq(caseId), eq(CaseEvent.UPDATE_MISSING_FIELDS), any()); } @SneakyThrows diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/mediation/MediationCSVLrvLipServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/mediation/MediationCSVLrvLipServiceTest.java index 8925aec6879..4cf67cf7439 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/mediation/MediationCSVLrvLipServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/mediation/MediationCSVLrvLipServiceTest.java @@ -39,6 +39,7 @@ public class MediationCSVLrvLipServiceTest { private static final String RESPONDENT_INDIVIDUAL_SOLE_TRADER_LAST_NAME = "Respondent Sole Trader Last Name"; private static final String TOTAL_AMOUNT = "9000"; private static final String ID = "123456789"; + private static final String RESPONDENT = "2"; @Mock private uk.gov.hmcts.reform.civil.prd.model.Organisation organisation; @@ -64,7 +65,7 @@ void shouldReturn_properDataForFile_ForCompany() { String result = service.generateCSVContent(caseData); //Then assertThat(result).contains(ID); - assertThat(result).contains(Party.Type.COMPANY.name()); + assertThat(result).contains(RESPONDENT); assertThat(result).contains(RESPONDENT_COMPANY_NAME); assertThat(result).contains(TOTAL_AMOUNT); assertThat(result).contains(RESPONDENT_PHONE_NUMBER); @@ -79,7 +80,7 @@ void shouldReturn_properDataForFile_ForOrganisation() { String result = service.generateCSVContent(caseData); //Then assertThat(result).contains(ID); - assertThat(result).contains("ORGANISATION"); + assertThat(result).contains(RESPONDENT); assertThat(result).contains(RESPONDENT_ORGANISATION_NAME); assertThat(result).contains(TOTAL_AMOUNT); assertThat(result).contains(RESPONDENT_PHONE_NUMBER); @@ -94,7 +95,7 @@ void shouldReturn_properDataForFile_ForIndividual() { String result = service.generateCSVContent(caseData); //Then assertThat(result).contains(ID); - assertThat(result).contains(Party.Type.INDIVIDUAL.name()); + assertThat(result).contains(RESPONDENT); assertThat(result).contains(RESPONDENT_INDIVIDUAL_FIST_NAME + " " + RESPONDENT_INDIVIDUAL_LAST_NAME); assertThat(result).contains(TOTAL_AMOUNT); assertThat(result).contains(RESPONDENT_PHONE_NUMBER); @@ -109,7 +110,7 @@ void shouldReturn_properDataForFile_ForSoleTrader() { String result = service.generateCSVContent(caseData); //Then assertThat(result).contains(ID); - assertThat(result).contains("SOLE_TRADER"); + assertThat(result).contains(RESPONDENT); assertThat(result).contains(RESPONDENT_INDIVIDUAL_SOLE_TRADER_FIRST_NAME + " " + RESPONDENT_INDIVIDUAL_SOLE_TRADER_LAST_NAME); assertThat(result).contains(TOTAL_AMOUNT); assertThat(result).contains(RESPONDENT_PHONE_NUMBER); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/robotics/RoboticsNotificationServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/robotics/RoboticsNotificationServiceTest.java index dc2c58165e4..a07d9933a66 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/robotics/RoboticsNotificationServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/robotics/RoboticsNotificationServiceTest.java @@ -470,4 +470,108 @@ void shouldNotifyJudgementByAdmissionLiP_whenLipDefendant() { assertThat(capturedEmailData.getMessage()).isEqualTo(message); assertThat(capturedEmailData.getTo()).isEqualTo(emailConfiguration.getLipJRecipient()); } + + @Test + void shouldNotifyJudgementLiP_whenLipvsLiPEnabled() { + //Given + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build() + .toBuilder().respondent1Represented(NO).applicant1Represented(NO).caseAccessCategory(SPEC_CLAIM).build(); + when(featureToggleService.isPinInPostEnabled()).thenReturn(true); + when(featureToggleService.isLipVLipEnabled()).thenReturn(true); + String lastEventText = "event text"; + RoboticsCaseDataSpec build = RoboticsCaseDataSpec.builder() + .events(EventHistory.builder() + .miscellaneous(Event.builder() + .eventDetailsText(lastEventText) + .dateReceived(LocalDateTime.now()) + .build()) + .build()) + .build(); + when(roboticsDataMapperForSpec.toRoboticsCaseData(caseData)).thenReturn(build); + + //When + service.notifyJudgementLip(caseData); + + //Then + verify(sendGridClient).sendEmail(eq(emailConfiguration.getSender()), emailDataArgumentCaptor.capture()); + + EmailData capturedEmailData = emailDataArgumentCaptor.getValue(); + String reference = caseData.getLegacyCaseReference(); + String message = format("Robotics case data JSON is attached for %s", reference); + String subject = format("LiP v LiP Case Data for %s", reference); + + assertThat(capturedEmailData.getSubject()).isEqualTo(subject); + assertThat(capturedEmailData.getMessage()).isEqualTo(message); + assertThat(capturedEmailData.getTo()).isEqualTo(emailConfiguration.getLipJRecipient()); + } + + @Test + void shouldNotifyDefaultJudgementLiP_whenLipvsLiPEnabled() { + //Given + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build() + .toBuilder().respondent1Represented(NO).applicant1Represented(NO).caseAccessCategory(SPEC_CLAIM).paymentTypeSelection( + DJPaymentTypeSelection.SET_DATE).build(); + when(featureToggleService.isPinInPostEnabled()).thenReturn(true); + when(featureToggleService.isLipVLipEnabled()).thenReturn(true); + String lastEventText = "event text"; + RoboticsCaseDataSpec build = RoboticsCaseDataSpec.builder() + .events(EventHistory.builder() + .miscellaneous(Event.builder() + .eventDetailsText(lastEventText) + .dateReceived(LocalDateTime.now()) + .build()) + .build()) + .build(); + when(roboticsDataMapperForSpec.toRoboticsCaseData(caseData)).thenReturn(build); + + //When + service.notifyJudgementLip(caseData); + + //Then + verify(sendGridClient).sendEmail(eq(emailConfiguration.getSender()), emailDataArgumentCaptor.capture()); + + EmailData capturedEmailData = emailDataArgumentCaptor.getValue(); + String reference = caseData.getLegacyCaseReference(); + String message = format("Robotics case data JSON is attached for %s", reference); + String subject = format("LiP v LiP Default Judgement Case Data for %s", reference); + + assertThat(capturedEmailData.getSubject()).isEqualTo(subject); + assertThat(capturedEmailData.getMessage()).isEqualTo(message); + assertThat(capturedEmailData.getTo()).isEqualTo(emailConfiguration.getLipJRecipient()); + } + + @Test + void shouldNotifyJudgementByAdmissionLiP_whenLipvsLiPEnabled() { + //Given + CaseData caseData = CaseDataBuilder.builder().atStateClaimDetailsNotified().build() + .toBuilder().respondent1Represented(NO).applicant1Represented(NO).caseAccessCategory(SPEC_CLAIM) + .ccjPaymentDetails(CCJPaymentDetails.builder().ccjPaymentPaidSomeOption(YES).build()).build(); + when(featureToggleService.isPinInPostEnabled()).thenReturn(true); + when(featureToggleService.isLipVLipEnabled()).thenReturn(true); + String lastEventText = "event text"; + RoboticsCaseDataSpec build = RoboticsCaseDataSpec.builder() + .events(EventHistory.builder() + .miscellaneous(Event.builder() + .eventDetailsText(lastEventText) + .dateReceived(LocalDateTime.now()) + .build()) + .build()) + .build(); + when(roboticsDataMapperForSpec.toRoboticsCaseData(caseData)).thenReturn(build); + + //When + service.notifyJudgementLip(caseData); + + //Then + verify(sendGridClient).sendEmail(eq(emailConfiguration.getSender()), emailDataArgumentCaptor.capture()); + + EmailData capturedEmailData = emailDataArgumentCaptor.getValue(); + String reference = caseData.getLegacyCaseReference(); + String message = format("Robotics case data JSON is attached for %s", reference); + String subject = format("LiP v LiP Judgement by Admission Case Data for %s", reference); + + assertThat(capturedEmailData.getSubject()).isEqualTo(subject); + assertThat(capturedEmailData.getMessage()).isEqualTo(message); + assertThat(capturedEmailData.getTo()).isEqualTo(emailConfiguration.getLipJRecipient()); + } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/EventHistoryMapperTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/EventHistoryMapperTest.java index 30078d1964a..b7632f0aad4 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/EventHistoryMapperTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/EventHistoryMapperTest.java @@ -14,22 +14,22 @@ import uk.gov.hmcts.reform.civil.enums.MediationDecision; import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; import uk.gov.hmcts.reform.civil.enums.PartyRole; +import uk.gov.hmcts.reform.civil.enums.PaymentFrequencyLRspec; import uk.gov.hmcts.reform.civil.enums.RepaymentFrequencyDJ; +import uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec; import uk.gov.hmcts.reform.civil.enums.RespondentResponseTypeSpec; import uk.gov.hmcts.reform.civil.enums.ResponseIntention; import uk.gov.hmcts.reform.civil.enums.YesOrNo; -import uk.gov.hmcts.reform.civil.enums.RespondentResponsePartAdmissionPaymentTimeLRspec; -import uk.gov.hmcts.reform.civil.enums.PaymentFrequencyLRspec; import uk.gov.hmcts.reform.civil.helpers.CaseDetailsConverter; +import uk.gov.hmcts.reform.civil.model.CCJPaymentDetails; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.CaseNote; -import uk.gov.hmcts.reform.civil.model.CCJPaymentDetails; import uk.gov.hmcts.reform.civil.model.DefendantPinToPostLRspec; import uk.gov.hmcts.reform.civil.model.HearingSupportRequirementsDJ; import uk.gov.hmcts.reform.civil.model.Party; import uk.gov.hmcts.reform.civil.model.PartyData; -import uk.gov.hmcts.reform.civil.model.RespondToClaim; import uk.gov.hmcts.reform.civil.model.RepaymentPlanLRspec; +import uk.gov.hmcts.reform.civil.model.RespondToClaim; import uk.gov.hmcts.reform.civil.model.RespondToClaimAdmitPartLRspec; import uk.gov.hmcts.reform.civil.model.citizenui.CaseDataLiP; import uk.gov.hmcts.reform.civil.model.citizenui.ClaimantMediationLip; @@ -90,8 +90,8 @@ import static uk.gov.hmcts.reform.civil.service.flowstate.FlowState.Main.TAKEN_OFFLINE_SDO_NOT_DRAWN; import static uk.gov.hmcts.reform.civil.service.robotics.RoboticsNotificationService.findLatestEventTriggerReason; import static uk.gov.hmcts.reform.civil.service.robotics.mapper.EventHistoryMapper.RPA_IN_MEDIATION; -import static uk.gov.hmcts.reform.civil.service.robotics.mapper.EventHistoryMapper.RPA_REASON_MANUAL_DETERMINATION; import static uk.gov.hmcts.reform.civil.service.robotics.mapper.EventHistoryMapper.RPA_REASON_JUDGMENT_BY_ADMISSION; +import static uk.gov.hmcts.reform.civil.service.robotics.mapper.EventHistoryMapper.RPA_REASON_MANUAL_DETERMINATION; @SpringBootTest(classes = { JacksonAutoConfiguration.class, @@ -1890,15 +1890,6 @@ void shouldPrepareExpectedEvents_when1v1ClaimWithRespondentFullAdmissionToBoth() .eventDetails(EventDetails.builder() .miscText("Claim issued in CCD.") .build()) - .build(), - Event.builder() - .eventSequence(3) - .eventCode("999") - .dateReceived(caseData.getRespondent1ResponseDate()) - .eventDetailsText("RPA Reason: Defendant fully admits.") - .eventDetails(EventDetails.builder() - .miscText("RPA Reason: Defendant fully admits.") - .build()) .build() ); @@ -1908,7 +1899,7 @@ void shouldPrepareExpectedEvents_when1v1ClaimWithRespondentFullAdmissionToBoth() assertThat(eventHistory).extracting("receiptOfAdmission").asList() .containsExactly(expectedReceiptOfAdmission); assertThat(eventHistory).extracting("miscellaneous").asList() - .containsExactly(expectedMiscellaneousEvents.get(0), expectedMiscellaneousEvents.get(1)); + .containsExactly(expectedMiscellaneousEvents.get(0)); assertEmptyEvents( eventHistory, @@ -1950,15 +1941,6 @@ void shouldPrepareExpectedEvents_when2v1ClaimWithRespondentFullAdmissionToBoth() .eventDetails(EventDetails.builder() .miscText("Claim issued in CCD.") .build()) - .build(), - Event.builder() - .eventSequence(3) - .eventCode("999") - .dateReceived(caseData.getRespondent1ResponseDate()) - .eventDetailsText("RPA Reason: Defendant fully admits.") - .eventDetails(EventDetails.builder() - .miscText("RPA Reason: Defendant fully admits.") - .build()) .build() ); @@ -1968,7 +1950,7 @@ void shouldPrepareExpectedEvents_when2v1ClaimWithRespondentFullAdmissionToBoth() assertThat(eventHistory).extracting("receiptOfAdmission").asList() .containsExactly(expectedReceiptOfAdmission); assertThat(eventHistory).extracting("miscellaneous").asList() - .containsExactly(expectedMiscellaneousEvents.get(0), expectedMiscellaneousEvents.get(1)); + .containsExactly(expectedMiscellaneousEvents.get(0)); assertEmptyEvents( eventHistory, @@ -2001,8 +1983,7 @@ void shouldPrepareExpectedEvents_when1v2ClaimWithRespondentFullAdmissionToBoth() .litigiousPartyID("002") .build(); - List expectedMiscellaneousEvents = List.of( - Event.builder() + Event expectedMiscellaneousEvents = Event.builder() .eventSequence(1) .eventCode("999") .dateReceived(caseData.getIssueDate().atStartOfDay()) @@ -2010,19 +1991,7 @@ void shouldPrepareExpectedEvents_when1v2ClaimWithRespondentFullAdmissionToBoth() .eventDetails(EventDetails.builder() .miscText("Claim issued in CCD.") .build()) - .build(), - Event.builder() - .eventSequence(3) - .eventCode("999") - .dateReceived(caseData.getRespondent1ResponseDate()) - .eventDetailsText( - "RPA Reason: [1 of 2 - 2020-08-01] Defendant: Mr. Sole Trader has responded: FULL_ADMISSION") - .eventDetails(EventDetails.builder() - .miscText("RPA Reason: [1 of 2 - 2020-08-01] " - + "Defendant: Mr. Sole Trader has responded: FULL_ADMISSION") - .build()) - .build() - ); + .build(); var eventHistory = mapper.buildEvents(caseData); @@ -2030,7 +1999,7 @@ void shouldPrepareExpectedEvents_when1v2ClaimWithRespondentFullAdmissionToBoth() assertThat(eventHistory).extracting("receiptOfAdmission").asList() .containsExactly(expectedReceiptOfAdmission); assertThat(eventHistory).extracting("miscellaneous").asList() - .containsExactly(expectedMiscellaneousEvents.get(0), expectedMiscellaneousEvents.get(1)); + .containsExactly(expectedMiscellaneousEvents); assertEmptyEvents( eventHistory, @@ -2069,8 +2038,7 @@ void shouldPrepareExpectedEvents_when2v1ClaimWithRespondentPartAdmissionToBoth() .litigiousPartyID("002") .build(); - List expectedMiscellaneousEvents = List.of( - Event.builder() + Event expectedMiscellaneousEvents = Event.builder() .eventSequence(1) .eventCode("999") .dateReceived(caseData.getIssueDate().atStartOfDay()) @@ -2078,17 +2046,7 @@ void shouldPrepareExpectedEvents_when2v1ClaimWithRespondentPartAdmissionToBoth() .eventDetails(EventDetails.builder() .miscText("Claim issued in CCD.") .build()) - .build(), - Event.builder() - .eventSequence(4) - .eventCode("999") - .dateReceived(caseData.getRespondent1ResponseDate()) - .eventDetailsText("RPA Reason: Defendant partial admission.") - .eventDetails(EventDetails.builder() - .miscText("RPA Reason: Defendant partial admission.") - .build()) - .build() - ); + .build(); List expectedDirectionsQuestionnaireFiled = List.of( Event.builder() @@ -2115,7 +2073,7 @@ void shouldPrepareExpectedEvents_when2v1ClaimWithRespondentPartAdmissionToBoth() assertThat(eventHistory).extracting("receiptOfPartAdmission").asList() .containsExactly(expectedReceiptOfPartAdmission); assertThat(eventHistory).extracting("miscellaneous").asList() - .containsExactly(expectedMiscellaneousEvents.get(0), expectedMiscellaneousEvents.get(1)); + .containsExactly(expectedMiscellaneousEvents); assertThat(eventHistory).extracting("directionsQuestionnaireFiled").asList() .contains(expectedDirectionsQuestionnaireFiled.get(0)); @@ -8005,6 +7963,7 @@ public void shouldGenerateRPA_PartAdmitRejectPayment() { ) .build() ) + .specDefenceAdmittedRequired(YES) .build(); List expectedDirectionsQuestionnaireFiled = @@ -8030,6 +7989,8 @@ public void shouldGenerateRPA_PartAdmitRejectPayment() { var eventHistory = mapper.buildEvents(caseData); assertThat(eventHistory).extracting("miscellaneous").asList() .extracting("eventCode").asString().contains("999"); + assertThat(eventHistory).extracting("statesPaid").asList() + .extracting("eventCode").asString().contains("49"); assertThat(eventHistory).extracting("miscellaneous").asList() .extracting("eventDetailsText").asString().contains(RPA_REASON_MANUAL_DETERMINATION); assertThat(eventHistory).extracting("directionsQuestionnaireFiled").asList() @@ -8095,6 +8056,7 @@ public void shouldGenerateRPA_ForPartAdmit_WhenClaimIsInMediation() { ) .build() ) + .specDefenceAdmittedRequired(NO) .build(); List expectedDirectionsQuestionnaireFiled = @@ -8322,6 +8284,7 @@ public void shouldGenerateRPA_ForFullAdmit_WhenClaimAgreedRepaymentPlan_BySetDat .ccjPaymentDetails(ccjPaymentDetails) .defenceAdmitPartPaymentTimeRouteRequired(RespondentResponsePartAdmissionPaymentTimeLRspec.BY_SET_DATE) .respondToClaimAdmitPartLRspec(paymentDetails) + .applicant1ResponseDate(LocalDateTime.now()) .totalInterest(BigDecimal.ZERO) .build(); @@ -8420,6 +8383,52 @@ public void shouldGenerateRPA_ForFullAdmit_WhenClaimImmediately() { .defenceAdmitPartPaymentTimeRouteRequired(RespondentResponsePartAdmissionPaymentTimeLRspec.IMMEDIATELY) .respondToClaimAdmitPartLRspec(paymentDetails) .totalInterest(BigDecimal.ZERO) + .applicant1ResponseDate(LocalDateTime.now()) + .build(); + + var eventHistory = mapper.buildEvents(caseData); + assertThat(eventHistory).isNotNull(); + assertThat(eventHistory).extracting("judgmentByAdmission").isNotNull(); + assertThat(eventHistory).extracting("judgmentByAdmission").asList() + .extracting("eventCode").asString().contains("240"); + assertThat(eventHistory).extracting("judgmentByAdmission").asList() + .extracting("eventDetails").asList() + .extracting("isJudgmentForthwith").contains(true); + assertThat(eventHistory).extracting("miscellaneous").asList() + .extracting("eventCode").asString().contains("999"); + assertThat(eventHistory).extracting("miscellaneous").asList() + .extracting("eventDetailsText").asString().contains(RPA_REASON_JUDGMENT_BY_ADMISSION); + } + + @Test + public void shouldGenerateRPA_ForFullAdmit_WhenClaimImmediatelyForLip() { + LocalDate whenWillPay = LocalDate.now().plusDays(5); + + CCJPaymentDetails ccjPaymentDetails = CCJPaymentDetails.builder() + .ccjPaymentPaidSomeOption(NO) + .ccjJudgmentAmountClaimAmount(BigDecimal.valueOf(1500)) + .ccjJudgmentFixedCostAmount(BigDecimal.valueOf(40)) + .ccjJudgmentAmountClaimFee(BigDecimal.valueOf(40)) + .ccjPaymentPaidSomeAmountInPounds(ZERO) + .ccjJudgmentLipInterest(ZERO) + .build(); + + RespondToClaimAdmitPartLRspec paymentDetails = RespondToClaimAdmitPartLRspec.builder() + .whenWillThisAmountBePaid(whenWillPay) + .build(); + + CaseData caseData = CaseDataBuilder.builder() + .setClaimTypeToSpecClaim() + .atStateSpec1v1ClaimSubmitted() + .atStateRespondent1v1FullAdmissionSpec().build().toBuilder() + .ccjPaymentDetails(ccjPaymentDetails) + .defenceAdmitPartPaymentTimeRouteRequired(RespondentResponsePartAdmissionPaymentTimeLRspec.IMMEDIATELY) + .respondToClaimAdmitPartLRspec(paymentDetails) + .totalInterest(BigDecimal.ZERO) + .applicant1ResponseDate(LocalDateTime.now()) + .respondent1Represented(YesOrNo.NO) + .specRespondent1Represented(YesOrNo.NO) + .applicant1Represented(YesOrNo.NO) .build(); var eventHistory = mapper.buildEvents(caseData); @@ -8435,5 +8444,39 @@ public void shouldGenerateRPA_ForFullAdmit_WhenClaimImmediately() { assertThat(eventHistory).extracting("miscellaneous").asList() .extracting("eventDetailsText").asString().contains(RPA_REASON_JUDGMENT_BY_ADMISSION); } + + @Test + void shouldNotThrowNullPointerException_whenRepaymentPlanIsNull() { + //Given + CCJPaymentDetails ccjPaymentDetails = CCJPaymentDetails.builder() + .ccjJudgmentAmountClaimAmount(BigDecimal.valueOf(1500)) + .ccjJudgmentAmountClaimFee(BigDecimal.valueOf(40)) + .ccjPaymentPaidSomeAmountInPounds(ZERO) + .ccjJudgmentFixedCostAmount(ZERO) + .ccjPaymentPaidSomeOption(NO) + .ccjJudgmentFixedCostOption(NO) + .build(); + CaseData caseData = CaseDataBuilder.builder() + .setClaimTypeToSpecClaim() + .atStateSpec1v1ClaimSubmitted() + .atStateRespondent1v1FullAdmissionSpec().build().toBuilder() + .ccjPaymentDetails(ccjPaymentDetails) + .defenceAdmitPartPaymentTimeRouteRequired(RespondentResponsePartAdmissionPaymentTimeLRspec.SUGGESTION_OF_REPAYMENT_PLAN) + .totalInterest(BigDecimal.ZERO) + .build(); + //When + var eventHistory = mapper.buildEvents(caseData); + //Then + assertThat(eventHistory).extracting("judgmentByAdmission").asList() + .extracting("eventDetails").asList() + .extracting("firstInstallmentDate").isNotNull(); + assertThat(eventHistory).extracting("judgmentByAdmission").asList() + .extracting("eventDetails").asList() + .extracting("installmentPeriod").isNotNull(); + assertThat(eventHistory).extracting("judgmentByAdmission").asList() + .extracting("eventDetails").asList() + .extracting("installmentAmount").isNotNull(); + + } } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/RoboticsDataMapperTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/RoboticsDataMapperTest.java index 60111d9c03e..230d1ff387c 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/RoboticsDataMapperTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/robotics/mapper/RoboticsDataMapperTest.java @@ -1,8 +1,10 @@ package uk.gov.hmcts.reform.civil.service.robotics.mapper; +import feign.FeignException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @@ -298,6 +300,21 @@ void shouldMapToRoboticsCaseDataWhen2ndDefendantIsRepresentedSameSolicitor() { assertThat(roboticsCaseData.getSolicitors()).hasSize(2); } + @Test + void shouldCheck_whenFeignException() { + CaseData caseData = CaseDataBuilder.builder().atStatePaymentSuccessful().build().toBuilder() + .respondent2(PartyBuilder.builder().company().build()) + .addRespondent2(YES) + .respondent2Represented(YES) + .respondent2SameLegalRepresentative(YES) + .build(); + given(organisationApi.findOrganisationById(any(), any(), any())) + .willThrow(Mockito.mock(FeignException.class)); + RoboticsCaseData roboticsCaseData = mapper.toRoboticsCaseData(caseData, BEARER_TOKEN); + CustomAssertions.assertThat(roboticsCaseData).isEqualTo(caseData); + assertThat(roboticsCaseData.getSolicitors()).hasSize(2); + } + @Test void shouldMapToRoboticsCaseDataWhen2ndDefendantIsRepresentedDifferentSolicitor() { CaseData caseData = CaseDataBuilder.builder().atStatePaymentSuccessful().build().toBuilder() diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyCheckSearchServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyCheckSearchServiceTest.java index 0aefcb6a5c2..24a6e6b3716 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyCheckSearchServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyCheckSearchServiceTest.java @@ -26,7 +26,10 @@ protected Query buildQuery(int fromValue) { .should(boolQuery() .must(rangeQuery("data.hearingDate").lt(LocalDate.now().atTime(LocalTime.MIN).plusWeeks(3) .toString())) - .must(boolQuery().must(matchQuery("state", "PREPARE_FOR_HEARING_CONDUCT_HEARING"))) + .must(boolQuery() + .minimumShouldMatch(1) + .should(boolQuery().must(matchQuery("state", "PREPARE_FOR_HEARING_CONDUCT_HEARING"))) + .should(boolQuery().must(matchQuery("state", "HEARING_READINESS")))) .mustNot(matchQuery("data.allocatedTrack", "SMALL_CLAIM")) .mustNot(matchQuery("data.trialReadyChecked", "Yes"))); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyNotificationSearchServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyNotificationSearchServiceTest.java index 961b2c67253..f94d49c3430 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyNotificationSearchServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/search/TrialReadyNotificationSearchServiceTest.java @@ -28,10 +28,13 @@ protected Query buildQuery(int fromValue) { .should(boolQuery() .must(rangeQuery("data.hearingDate").lt(LocalDate.now().atTime(LocalTime.MIN).plusWeeks(6) .toString())) - .must(boolQuery().must(matchQuery("state", "PREPARE_FOR_HEARING_CONDUCT_HEARING")))) + .must(boolQuery() + .minimumShouldMatch(1) + .should(boolQuery().must(matchQuery("state", "PREPARE_FOR_HEARING_CONDUCT_HEARING"))) + .should(boolQuery().must(matchQuery("state", "HEARING_READINESS")))) .mustNot(matchQuery("data.allocatedTrack", "SMALL_CLAIM")) .mustNot(matchQuery("data.listingOrRelisting", ListingOrRelisting.RELISTING)) - .mustNot(matchQuery("data.trialReadyNotified", YesOrNo.YES)); + .mustNot(matchQuery("data.trialReadyNotified", YesOrNo.YES))); return new Query(query, List.of("reference"), fromValue); } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/service/stitching/CivilDocumentStitchingServiceTest.java b/src/test/java/uk/gov/hmcts/reform/civil/service/stitching/CivilDocumentStitchingServiceTest.java index 9ff8b4571c8..6117ffa1ad8 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/service/stitching/CivilDocumentStitchingServiceTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/service/stitching/CivilDocumentStitchingServiceTest.java @@ -121,12 +121,29 @@ void whenCaseDataIsNotNullWithCaseBundlesAndNoStitchingDocumentThenCaseDocumentI } @Test - void whenStitchingDocumentIsPresentAndCaseDataNotNullThenCaseDocumentNotNull() { + void whenStitchingDocumentIsPresentAndRespondent1ResponseDateNotNullInCaseDataThenCaseDocumentNotNull() { //Given: Payload,case data with case bundle details and stitching document Optional stitchedDocument = Optional.of(mock(Document.class)); List documentMetaDataList = buildDocumentMetaDataList(); Bundle bundle = Bundle.builder().stitchedDocument(stitchedDocument).build(); CaseData caseData1 = buildCaseData(bundle); + CaseData caseData = CaseDataBuilder.builder().legacyCaseReference("ClaimNumber").respondent1ResponseDate(LocalDateTime.now()).build(); + given(bundleRequestExecutor.post(any(BundleRequest.class), anyString(), anyString())).willReturn(caseData1); + //when: bundle Request post is called and case data is retrieved with stitching document + CaseDocument caseDocument = civilDocumentStitchingService.bundle(documentMetaDataList, "Auth", + "Title", "FileName", caseData); + //Then: Case Document is retrieved + Assertions.assertNotNull(caseDocument); + } + + @Test + void whenStitchingDocumentIsPresentAndRespondent2ResponseDateNotNullInCaseDataThenCaseDocumentNotNull() { + //Given: Payload,case data with case bundle details and stitching document + Optional stitchedDocument = Optional.of(mock(Document.class)); + List documentMetaDataList = buildDocumentMetaDataList(); + Bundle bundle = Bundle.builder().stitchedDocument(stitchedDocument).build(); + CaseData caseData1 = buildCaseData(bundle); + CaseData caseData = CaseDataBuilder.builder().legacyCaseReference("ClaimNumber").respondent2ResponseDate(LocalDateTime.now()).build(); given(bundleRequestExecutor.post(any(BundleRequest.class), anyString(), anyString())).willReturn(caseData1); //when: bundle Request post is called and case data is retrieved with stitching document CaseDocument caseDocument = civilDocumentStitchingService.bundle(documentMetaDataList, "Auth", diff --git a/src/test/java/uk/gov/hmcts/reform/civil/utils/AssignCategoryIdTests.java b/src/test/java/uk/gov/hmcts/reform/civil/utils/AssignCategoryIdTests.java index 77bb1352c03..c9c61fbbc28 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/utils/AssignCategoryIdTests.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/utils/AssignCategoryIdTests.java @@ -50,7 +50,7 @@ void setup() { } @Test - public void shouldNotAssignCategory_whenInvokedAndToggleFalse() { + void shouldNotAssignCategory_whenInvokedAndToggleFalse() { when(featureToggleService.isCaseFileViewEnabled()).thenReturn(false); List> documentList = new ArrayList<>(); documentList.add(element(testCaseDocument)); @@ -65,7 +65,7 @@ public void shouldNotAssignCategory_whenInvokedAndToggleFalse() { } @Test - public void shouldAssignCaseDocumentCategoryId_whenInvoked() { + void shouldAssignCaseDocumentCategoryId_whenInvoked() { when(featureToggleService.isCaseFileViewEnabled()).thenReturn(true); assignCategoryId.assignCategoryIdToCaseDocument(testCaseDocument, "testCaseDocumentID"); @@ -73,7 +73,7 @@ public void shouldAssignCaseDocumentCategoryId_whenInvoked() { } @Test - public void shouldAssignDocumentCategoryId_whenInvoked() { + void shouldAssignDocumentCategoryId_whenInvoked() { when(featureToggleService.isCaseFileViewEnabled()).thenReturn(true); assignCategoryId.assignCategoryIdToDocument(testDocument, "testDocumentID"); @@ -81,7 +81,7 @@ public void shouldAssignDocumentCategoryId_whenInvoked() { } @Test - public void shouldAssignDocumentIdCollection_whenInvoked() { + void shouldAssignDocumentIdCollection_whenInvoked() { when(featureToggleService.isCaseFileViewEnabled()).thenReturn(true); List> documentList = new ArrayList<>(); documentList.add(element(testCaseDocument)); @@ -91,4 +91,35 @@ public void shouldAssignDocumentIdCollection_whenInvoked() { assertThat(documentList.get(0).getValue().getDocumentLink().getCategoryID()).isEqualTo("testDocumentCollectionID"); } + @Test + void shouldCopyDocumentWithCategoryId_whenInvoked() { + when(featureToggleService.isCaseFileViewEnabled()).thenReturn(true); + CaseDocument copy = assignCategoryId.copyCaseDocumentWithCategoryId(testCaseDocument, "testDocumentID"); + assertThat(copy.getDocumentLink().getCategoryID()).isEqualTo("testDocumentID"); + } + + @Test + void shouldCopyDocumentsWithCategoryId_whenInvoked() { + when(featureToggleService.isCaseFileViewEnabled()).thenReturn(true); + List> documentList = new ArrayList<>(); + documentList.add(element(testCaseDocument)); + List> copyList = assignCategoryId.copyCaseDocumentListWithCategoryId(documentList, + "testDocumentCollectionID"); + + assertThat(copyList.get(0).getValue().getDocumentLink().getCategoryID()).isEqualTo("testDocumentCollectionID"); + } + + @Test + void shouldNotCopy_whenInvokedAndToggleFalse() { + when(featureToggleService.isCaseFileViewEnabled()).thenReturn(false); + List> documentList = new ArrayList<>(); + documentList.add(element(testCaseDocument)); + CaseDocument copy = assignCategoryId.copyCaseDocumentWithCategoryId(testCaseDocument, "testDocumentID"); + List> copyList = assignCategoryId.copyCaseDocumentListWithCategoryId(documentList, + "testDocumentCollectionID"); + + assertThat(copyList).isNull(); + assertThat(copy).isNull(); + } + } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/utils/CaseFlagUtilsTest.java b/src/test/java/uk/gov/hmcts/reform/civil/utils/CaseFlagUtilsTest.java index 802505acdc7..aae666611d3 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/utils/CaseFlagUtilsTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/utils/CaseFlagUtilsTest.java @@ -1,5 +1,6 @@ package uk.gov.hmcts.reform.civil.utils; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -7,6 +8,7 @@ import uk.gov.hmcts.reform.civil.model.PartyFlagStructure; import uk.gov.hmcts.reform.civil.model.LitigationFriend; import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.model.UpdateDetailsForm; import uk.gov.hmcts.reform.civil.model.caseflags.FlagDetail; import uk.gov.hmcts.reform.civil.model.caseflags.Flags; import uk.gov.hmcts.reform.civil.model.common.Element; @@ -18,15 +20,21 @@ import uk.gov.hmcts.reform.civil.model.dq.Respondent2DQ; import uk.gov.hmcts.reform.civil.model.dq.Witness; import uk.gov.hmcts.reform.civil.model.dq.Witnesses; +import uk.gov.hmcts.reform.civil.prd.model.Organisation; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.sampledata.PartyBuilder; +import uk.gov.hmcts.reform.civil.service.OrganisationService; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.NO; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.APPLICANT_SOLICITOR_EXPERT; @@ -39,10 +47,35 @@ import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.addRespondentDQPartiesFlagStructure; import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.filter; import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.getAllCaseFlags; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.unwrapElements; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_LEGAL_REP_INDIVIDUALS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_ORG_INDIVIDUALS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_TWO_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_TWO_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_TWO_ORG_INDIVIDUALS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_LEGAL_REP_INDIVIDUALS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_ORG_INDIVIDUALS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_LEGAL_REP_INDIVIDUALS_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_ORG_INDIVIDUALS_ID; class CaseFlagUtilsTest { + private OrganisationService organisationService; + + @BeforeEach + void setUp() { + organisationService = mock(OrganisationService.class); + when(organisationService.findOrganisationById(anyString())) + .thenReturn(Optional.of(Organisation.builder().name("Civil - Organisation").build())); + } + @Nested class CreateFlags { @@ -129,9 +162,9 @@ public void shouldCreateFlagsStructureForRespondentExperts() { .multiPartyClaimTwoDefendantSolicitors() .build(); - Expert expert1 = Expert.builder().firstName("First").lastName("Name").build(); - Expert expert2 = Expert.builder().firstName("Second").lastName("expert").build(); - Expert expert3 = Expert.builder().firstName("Third").lastName("experto").build(); + Expert expert1 = Expert.builder().partyID("partyId1").firstName("First").lastName("Name").build(); + Expert expert2 = Expert.builder().partyID("partyId2").firstName("Second").lastName("expert").build(); + Expert expert3 = Expert.builder().partyID("partyId3").firstName("Third").lastName("experto").build(); CaseData updatedCaseData = caseData.toBuilder() .respondent1DQ(Respondent1DQ.builder() @@ -174,10 +207,12 @@ public void shouldCreateFlagsStructureForRespondentExperts() { assertThat(respondent1ExpertsWithFlags).hasSize(2); assertThat(respondent1ExpertsWithFlags.get(0).getValue().getFlags()).isEqualTo(expectedExpert1Flags); + assertThat(respondent1ExpertsWithFlags.get(0).getValue().getPartyID()).isEqualTo("partyId1"); assertThat(respondent1ExpertsWithFlags.get(0).getValue().getFirstName()).isEqualTo("First"); assertThat(respondent1ExpertsWithFlags.get(0).getValue().getLastName()).isEqualTo("Name"); assertThat(respondent1ExpertsWithFlags.get(1).getValue().getFlags()).isEqualTo(expectedExpert2Flags); + assertThat(respondent1ExpertsWithFlags.get(1).getValue().getPartyID()).isEqualTo("partyId2"); assertThat(respondent1ExpertsWithFlags.get(1).getValue().getFirstName()).isEqualTo("Second"); assertThat(respondent1ExpertsWithFlags.get(1).getValue().getLastName()).isEqualTo("expert"); @@ -185,6 +220,7 @@ public void shouldCreateFlagsStructureForRespondentExperts() { assertThat(respondent2ExpertsWithFlags).hasSize(1); assertThat(respondent2ExpertsWithFlags.get(0).getValue().getFlags()).isEqualTo(expectedExpert3Flags); + assertThat(respondent2ExpertsWithFlags.get(0).getValue().getPartyID()).isEqualTo("partyId3"); assertThat(respondent2ExpertsWithFlags.get(0).getValue().getFirstName()).isEqualTo("Third"); assertThat(respondent2ExpertsWithFlags.get(0).getValue().getLastName()).isEqualTo("experto"); } @@ -196,9 +232,9 @@ public void shouldCreateFlagsStructureForRespondentWitness() { .multiPartyClaimTwoDefendantSolicitors() .build(); - Witness witness1 = Witness.builder().firstName("First").lastName("Name").build(); - Witness witness2 = Witness.builder().firstName("Second").lastName("witness").build(); - Witness witness3 = Witness.builder().firstName("Third").lastName("witnessy").build(); + Witness witness1 = Witness.builder().partyID("partyId1").firstName("First").lastName("Name").build(); + Witness witness2 = Witness.builder().partyID("partyId2").firstName("Second").lastName("witness").build(); + Witness witness3 = Witness.builder().partyID("partyId3").firstName("Third").lastName("witnessy").build(); CaseData updatedCaseData = caseData.toBuilder() .respondent1DQ(Respondent1DQ.builder() @@ -242,10 +278,12 @@ public void shouldCreateFlagsStructureForRespondentWitness() { assertThat(respondent1WitnessWithFlags).hasSize(2); assertThat(respondent1WitnessWithFlags.get(0).getValue().getFlags()).isEqualTo(expectedWitness1Flags); + assertThat(respondent1WitnessWithFlags.get(0).getValue().getPartyID()).isEqualTo("partyId1"); assertThat(respondent1WitnessWithFlags.get(0).getValue().getFirstName()).isEqualTo("First"); assertThat(respondent1WitnessWithFlags.get(0).getValue().getLastName()).isEqualTo("Name"); assertThat(respondent1WitnessWithFlags.get(1).getValue().getFlags()).isEqualTo(expectedWitness2Flags); + assertThat(respondent1WitnessWithFlags.get(1).getValue().getPartyID()).isEqualTo("partyId2"); assertThat(respondent1WitnessWithFlags.get(1).getValue().getFirstName()).isEqualTo("Second"); assertThat(respondent1WitnessWithFlags.get(1).getValue().getLastName()).isEqualTo("witness"); @@ -253,6 +291,7 @@ public void shouldCreateFlagsStructureForRespondentWitness() { assertThat(respondent2WitnessWithFlags).hasSize(1); assertThat(respondent2WitnessWithFlags.get(0).getValue().getFlags()).isEqualTo(expectedWitness3Flags); + assertThat(respondent2WitnessWithFlags.get(0).getValue().getPartyID()).isEqualTo("partyId3"); assertThat(respondent2WitnessWithFlags.get(0).getValue().getFirstName()).isEqualTo("Third"); assertThat(respondent2WitnessWithFlags.get(0).getValue().getLastName()).isEqualTo("witnessy"); } @@ -264,9 +303,9 @@ public void shouldCreateFlagsStructureForApplicantWitness() { .multiPartyClaimTwoApplicants() .build(); - Witness witness1 = Witness.builder().firstName("First").lastName("Name").build(); - Witness witness2 = Witness.builder().firstName("Second").lastName("witness").build(); - Witness witness3 = Witness.builder().firstName("Third").lastName("witnessy").build(); + Witness witness1 = Witness.builder().partyID("partyId1").firstName("First").lastName("Name").build(); + Witness witness2 = Witness.builder().partyID("partyId2").firstName("Second").lastName("witness").build(); + Witness witness3 = Witness.builder().partyID("partyId3").firstName("Third").lastName("witnessy").build(); CaseData updatedCaseData = caseData.toBuilder() .applicant1DQ(Applicant1DQ.builder() @@ -309,14 +348,17 @@ public void shouldCreateFlagsStructureForApplicantWitness() { assertThat(applicantWitnesses).hasSize(3); assertThat(applicantWitnesses.get(0).getValue().getFlags()).isEqualTo(expectedWitness1Flags); + assertThat(applicantWitnesses.get(0).getValue().getPartyID()).isEqualTo("partyId1"); assertThat(applicantWitnesses.get(0).getValue().getFirstName()).isEqualTo("First"); assertThat(applicantWitnesses.get(0).getValue().getLastName()).isEqualTo("Name"); assertThat(applicantWitnesses.get(1).getValue().getFlags()).isEqualTo(expectedWitness2Flags); + assertThat(applicantWitnesses.get(1).getValue().getPartyID()).isEqualTo("partyId2"); assertThat(applicantWitnesses.get(1).getValue().getFirstName()).isEqualTo("Second"); assertThat(applicantWitnesses.get(1).getValue().getLastName()).isEqualTo("witness"); assertThat(applicantWitnesses.get(2).getValue().getFlags()).isEqualTo(expectedWitness3Flags); + assertThat(applicantWitnesses.get(2).getValue().getPartyID()).isEqualTo("partyId3"); assertThat(applicantWitnesses.get(2).getValue().getFirstName()).isEqualTo("Third"); assertThat(applicantWitnesses.get(2).getValue().getLastName()).isEqualTo("witnessy"); } @@ -328,9 +370,9 @@ public void shouldCreateFlagsStructureForApplicantExperts() { .multiPartyClaimTwoApplicants() .build(); - Expert expert1 = Expert.builder().firstName("First").lastName("Name").build(); - Expert expert2 = Expert.builder().firstName("Second").lastName("expert").build(); - Expert expert3 = Expert.builder().firstName("Third").lastName("expert").build(); + Expert expert1 = Expert.builder().partyID("partyId1").firstName("First").lastName("Name").build(); + Expert expert2 = Expert.builder().partyID("partyId2").firstName("Second").lastName("expert").build(); + Expert expert3 = Expert.builder().partyID("partyId3").firstName("Third").lastName("expert").build(); CaseData updatedCaseData = caseData.toBuilder() .applicant1DQ(Applicant1DQ.builder() @@ -372,14 +414,17 @@ public void shouldCreateFlagsStructureForApplicantExperts() { assertThat(applicantExperts).hasSize(3); assertThat(applicantExperts.get(0).getValue().getFlags()).isEqualTo(expectedExpert1Flags); + assertThat(applicantExperts.get(0).getValue().getPartyID()).isEqualTo("partyId1"); assertThat(applicantExperts.get(0).getValue().getFirstName()).isEqualTo("First"); assertThat(applicantExperts.get(0).getValue().getLastName()).isEqualTo("Name"); assertThat(applicantExperts.get(1).getValue().getFlags()).isEqualTo(expectedExpert2Flags); + assertThat(applicantExperts.get(1).getValue().getPartyID()).isEqualTo("partyId2"); assertThat(applicantExperts.get(1).getValue().getFirstName()).isEqualTo("Second"); assertThat(applicantExperts.get(1).getValue().getLastName()).isEqualTo("expert"); assertThat(applicantExperts.get(2).getValue().getFlags()).isEqualTo(expectedExpert3Flags); + assertThat(applicantExperts.get(2).getValue().getPartyID()).isEqualTo("partyId3"); assertThat(applicantExperts.get(2).getValue().getFirstName()).isEqualTo("Third"); assertThat(applicantExperts.get(2).getValue().getLastName()).isEqualTo("expert"); } @@ -636,4 +681,663 @@ private List hearingRelevantFlagDetails() { return List.of(details1, details2, details3); } } + + @Nested + class CreateAndUpdateFlagNamesAfterManageContactInformationEvent { + + @Nested + class Parties { + + @Test + void shouldUpdateFlagName_whenClaimant1NameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(CLAIMANT_ONE_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .applicant1(caseData.getApplicant1().toBuilder() + .flags(Flags.builder() + .partyName("Mr. John Rambo") + .roleOnCase("applicant") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .individualFirstName("Johnny") + .individualLastName("Rambo new").build()); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + Flags actual = builder.build().getApplicant1().getFlags(); + Flags expected = Flags.builder().partyName("Mr. Johnny Rambo new") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("applicant").build(); + + assertThat(actual).isEqualTo(expected); + } + + @Test + void shouldUpdateFlagName_whenClaimant2NameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .multiPartyClaimTwoApplicants() + .atStateClaimIssued() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(CLAIMANT_TWO_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .applicant2(caseData.getApplicant2().toBuilder() + .flags(Flags.builder() + .partyName("Mr. Jason Rambo") + .roleOnCase("applicant") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .individualFirstName("JJ") + .individualLastName("Rambo edited").build()); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + Flags actual = builder.build().getApplicant2().getFlags(); + Flags expected = Flags.builder().partyName("Mr. JJ Rambo edited") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("applicant").build(); + + assertThat(actual).isEqualTo(expected); + } + + @Test + void shouldUpdateFlagName_whenRespondent1NameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(DEFENDANT_ONE_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .respondent1(caseData.getRespondent1().toBuilder() + .flags(Flags.builder() + .partyName("Mr. Sole Trader") + .roleOnCase("respondent") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .soleTraderFirstName("Solo") + .soleTraderLastName("New trader").build()); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + Flags actual = builder.build().getRespondent1().getFlags(); + Flags expected = Flags.builder().partyName("Mr. Solo New trader") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("respondent").build(); + + assertThat(actual).isEqualTo(expected); + } + + @Test + void shouldUpdateFlagName_whenRespondent2NameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued() + .multiPartyClaimTwoDefendantSolicitors() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(DEFENDANT_TWO_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .respondent2(caseData.getRespondent2().toBuilder() + .flags(Flags.builder() + .partyName("Mr. John Rambo") + .roleOnCase("respondent") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .individualTitle("Miss") + .individualFirstName("Jenny") + .individualLastName("Rombo").build()); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + Flags actual = builder.build().getRespondent2().getFlags(); + Flags expected = Flags.builder().partyName("Miss Jenny Rombo") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("respondent").build(); + + assertThat(actual).isEqualTo(expected); + } + } + + @Nested + class LitigationFriend { + + @Test + void shouldUpdateFlagName_whenClaimant1LitigationFriendNameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .addApplicant1LitigationFriend() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(CLAIMANT_ONE_LITIGATION_FRIEND_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .applicant1LitigationFriend(caseData.getApplicant1LitigationFriend().toBuilder() + .flags(Flags.builder() + .partyName("Mr. Applicant Litigation Friend") + .roleOnCase("litigation friend") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .fullName(null) + .firstName("Johnny").lastName("Rambo new") + .build()); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + Flags actual = builder.build().getApplicant1LitigationFriend().getFlags(); + Flags expected = Flags.builder().partyName("Johnny Rambo new") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("litigation friend").build(); + + assertThat(actual).isEqualTo(expected); + } + + @Test + void shouldUpdateFlagName_whenClaimant2LitigationFriendNameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .addApplicant2LitigationFriend() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(CLAIMANT_TWO_LITIGATION_FRIEND_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .applicant2LitigationFriend(caseData.getApplicant2LitigationFriend().toBuilder() + .flags(Flags.builder() + .partyName("Applicant Two Litigation Friend") + .roleOnCase("litigation friend") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .fullName(null) + .firstName("Johnny").lastName("Rambo new") + .build()); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + Flags actual = builder.build().getApplicant2LitigationFriend().getFlags(); + Flags expected = Flags.builder().partyName("Johnny Rambo new") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("litigation friend").build(); + + assertThat(actual).isEqualTo(expected); + } + + @Test + void shouldUpdateFlagName_whenRespondent1LitigationFriendNameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .addRespondent1LitigationFriend() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(DEFENDANT_ONE_LITIGATION_FRIEND_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .respondent1LitigationFriend(caseData.getRespondent1LitigationFriend().toBuilder() + .flags(Flags.builder() + .partyName("Litigation Friend") + .roleOnCase("litigation friend") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .fullName(null) + .firstName("Johnny").lastName("Rambo new") + .build()); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + Flags actual = builder.build().getRespondent1LitigationFriend().getFlags(); + Flags expected = Flags.builder().partyName("Johnny Rambo new") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("litigation friend").build(); + + assertThat(actual).isEqualTo(expected); + } + + @Test + void shouldUpdateFlagName_whenRespondent2LitigationFriendNameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .multiPartyClaimTwoDefendantSolicitors() + .atStateApplicantRespondToDefenceAndProceed() + .addRespondent2LitigationFriend() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(DEFENDANT_TWO_LITIGATION_FRIEND_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .respondent2LitigationFriend(caseData.getRespondent2LitigationFriend().toBuilder() + .flags(Flags.builder() + .partyName("Litigation Friend") + .roleOnCase("litigation friend") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .fullName(null) + .firstName("Johnny").lastName("Rambo new") + .build()); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + Flags actual = builder.build().getRespondent2LitigationFriend().getFlags(); + Flags expected = Flags.builder().partyName("Johnny Rambo new") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("litigation friend").build(); + + assertThat(actual).isEqualTo(expected); + } + } + + @Nested + class LegalRepIndividuals { + + @Test + void shouldCreateFlag_whenClaimantLRIndividualAdded() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(CLAIMANT_ONE_LEGAL_REP_INDIVIDUALS_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .applicant1LRIndividuals(wrapElements(PartyFlagStructure.builder() + .firstName("Legally").lastName("Rep") + .build())); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + PartyFlagStructure individual = unwrapElements(builder.build().getApplicant1LRIndividuals()).get(0); + Flags actualFlags = individual.getFlags(); + Flags expectedFlags = Flags.builder().partyName("Legally Rep") + .details(List.of()) + .roleOnCase("Civil - Organisation").build(); + + assertThat(actualFlags).isEqualTo(expectedFlags); + assertThat(individual.getPartyID()).isNotNull(); + } + + @Test + void shouldUpdateFlagName_whenClaimantLRIndividualNameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .addApplicantLRIndividual("Legal", "Rep") + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(CLAIMANT_ONE_LEGAL_REP_INDIVIDUALS_ID).build()) + .build(); + + PartyFlagStructure lrIndividual = unwrapElements(caseData.getApplicant1LRIndividuals()).get(0); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .applicant1LRIndividuals(wrapElements(lrIndividual.toBuilder() + .flags(Flags.builder() + .partyName("Legal Rep") + .roleOnCase("Civil - Organisation") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .firstName("Legally").lastName("Rep") + .build())); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + PartyFlagStructure individual = unwrapElements(builder.build().getApplicant1LRIndividuals()).get(0); + Flags actualFlags = individual.getFlags(); + Flags expectedFlags = Flags.builder().partyName("Legally Rep") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("Civil - Organisation").build(); + + assertThat(actualFlags).isEqualTo(expectedFlags); + assertThat(individual.getPartyID()).isEqualTo("app-lr-ind-party-id"); + } + + @Test + void shouldCreateFlag_whenRespondent1LRIndividualAdded() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(DEFENDANT_ONE_LEGAL_REP_INDIVIDUALS_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .respondent1LRIndividuals(wrapElements(PartyFlagStructure.builder() + .firstName("Legally").lastName("Rep") + .build())); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + PartyFlagStructure individual = unwrapElements(builder.build().getRespondent1LRIndividuals()).get(0); + Flags actualFlags = individual.getFlags(); + Flags expectedFlags = Flags.builder().partyName("Legally Rep") + .details(List.of()) + .roleOnCase("Civil - Organisation").build(); + + assertThat(actualFlags).isEqualTo(expectedFlags); + assertThat(individual.getPartyID()).isNotNull(); + } + + @Test + void shouldUpdateFlagName_whenRespondent1LRIndividualNameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .addRespondent1LRIndividual("Legal", "Rep") + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(DEFENDANT_ONE_LEGAL_REP_INDIVIDUALS_ID).build()) + .build(); + + PartyFlagStructure lrIndividual = unwrapElements(caseData.getRespondent1LRIndividuals()).get(0); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .respondent1LRIndividuals(wrapElements(lrIndividual.toBuilder() + .flags(Flags.builder() + .partyName("Legal Rep") + .roleOnCase("Civil - Organisation") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .firstName("Legally").lastName("Rep") + .build())); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + PartyFlagStructure individual = unwrapElements(builder.build().getRespondent1LRIndividuals()).get(0); + Flags actualFlags = individual.getFlags(); + Flags expectedFlags = Flags.builder().partyName("Legally Rep") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("Civil - Organisation").build(); + + assertThat(actualFlags).isEqualTo(expectedFlags); + assertThat(individual.getPartyID()).isEqualTo("res-1-lr-ind-party-id"); + } + + @Test + void shouldCreateFlag_whenRespondent2LRIndividualAdded() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(DEFENDANT_TWO_LEGAL_REP_INDIVIDUALS_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .respondent2LRIndividuals(wrapElements(PartyFlagStructure.builder() + .firstName("Legally").lastName("Rep") + .build())); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + PartyFlagStructure individual = unwrapElements(builder.build().getRespondent2LRIndividuals()).get(0); + Flags actualFlags = individual.getFlags(); + Flags expectedFlags = Flags.builder().partyName("Legally Rep") + .details(List.of()) + .roleOnCase("Civil - Organisation").build(); + + assertThat(actualFlags).isEqualTo(expectedFlags); + assertThat(individual.getPartyID()).isNotNull(); + } + + @Test + void shouldUpdateFlagName_whenRespondent2LRIndividualNameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .addRespondent2LRIndividual("Legal", "Rep") + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(DEFENDANT_TWO_LEGAL_REP_INDIVIDUALS_ID).build()) + .build(); + + PartyFlagStructure lrIndividual = unwrapElements(caseData.getRespondent2LRIndividuals()).get(0); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .respondent2LRIndividuals(wrapElements(lrIndividual.toBuilder() + .flags(Flags.builder() + .partyName("Legal Rep") + .roleOnCase("Civil - Organisation") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .firstName("Legally").lastName("Rep") + .build())); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + PartyFlagStructure individual = unwrapElements(builder.build().getRespondent2LRIndividuals()).get(0); + Flags actualFlags = individual.getFlags(); + Flags expectedFlags = Flags.builder().partyName("Legally Rep") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("Civil - Organisation").build(); + + assertThat(actualFlags).isEqualTo(expectedFlags); + assertThat(individual.getPartyID()).isEqualTo("res-2-lr-ind-party-id"); + } + } + + @Nested + class OrgIndividuals { + + @Test + void shouldCreateFlag_whenClaimant1OrgIndividualAdded() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(CLAIMANT_ONE_ORG_INDIVIDUALS_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .applicant1OrgIndividuals(wrapElements(PartyFlagStructure.builder() + .firstName("Org").lastName("Ind") + .build())); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + PartyFlagStructure individual = unwrapElements(builder.build().getApplicant1OrgIndividuals()).get(0); + Flags actualFlags = individual.getFlags(); + Flags expectedFlags = Flags.builder().partyName("Org Ind") + .details(List.of()) + .roleOnCase("Mr. John Rambo").build(); + + assertThat(actualFlags).isEqualTo(expectedFlags); + assertThat(individual.getPartyID()).isNotNull(); + } + + @Test + void shouldUpdateFlagName_whenClaimant1OrgIndividualNameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .addApplicant1OrgIndividual("Org", "Person") + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(CLAIMANT_ONE_ORG_INDIVIDUALS_ID).build()) + .build(); + + PartyFlagStructure orgIndividual = unwrapElements(caseData.getApplicant1OrgIndividuals()).get(0); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .applicant1OrgIndividuals(wrapElements(orgIndividual.toBuilder() + .flags(Flags.builder() + .partyName("Org Person") + .roleOnCase("Mr. John Rambo") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .firstName("Org").lastName("Ind") + .build())); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + PartyFlagStructure individual = unwrapElements(builder.build().getApplicant1OrgIndividuals()).get(0); + Flags actualFlags = individual.getFlags(); + Flags expectedFlags = Flags.builder().partyName("Org Ind") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("Mr. John Rambo").build(); + + assertThat(actualFlags).isEqualTo(expectedFlags); + assertThat(individual.getPartyID()).isEqualTo("app-1-org-ind-party-id"); + } + + @Test + void shouldCreateFlag_whenClaimant2OrgIndividualAdded() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued() + .multiPartyClaimTwoApplicants() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(CLAIMANT_TWO_ORG_INDIVIDUALS_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .applicant2OrgIndividuals(wrapElements(PartyFlagStructure.builder() + .firstName("Org").lastName("Ind") + .build())); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + PartyFlagStructure individual = unwrapElements(builder.build().getApplicant2OrgIndividuals()).get(0); + Flags actualFlags = individual.getFlags(); + Flags expectedFlags = Flags.builder().partyName("Org Ind") + .details(List.of()) + .roleOnCase("Mr. Jason Rambo").build(); + + assertThat(actualFlags).isEqualTo(expectedFlags); + assertThat(individual.getPartyID()).isNotNull(); + } + + @Test + void shouldUpdateFlagName_whenClaimant2OrgIndividualNameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued() + .multiPartyClaimTwoApplicants() + .addApplicant2OrgIndividual("Org", "Person") + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(CLAIMANT_TWO_ORG_INDIVIDUALS_ID).build()) + .build(); + + PartyFlagStructure orgIndividual = unwrapElements(caseData.getApplicant2OrgIndividuals()).get(0); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .applicant2OrgIndividuals(wrapElements(orgIndividual.toBuilder() + .flags(Flags.builder() + .partyName("Org Person") + .roleOnCase("Mr. Jason Rambo") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .firstName("Org").lastName("Ind") + .build())); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + PartyFlagStructure individual = unwrapElements(builder.build().getApplicant2OrgIndividuals()).get(0); + Flags actualFlags = individual.getFlags(); + Flags expectedFlags = Flags.builder().partyName("Org Ind") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("Mr. Jason Rambo").build(); + + assertThat(actualFlags).isEqualTo(expectedFlags); + assertThat(individual.getPartyID()).isEqualTo("app-2-org-ind-party-id"); + } + + @Test + void shouldCreateFlag_whenRespondent1OrgIndividualAdded() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(DEFENDANT_ONE_ORG_INDIVIDUALS_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .respondent1OrgIndividuals(wrapElements(PartyFlagStructure.builder() + .firstName("Org").lastName("Ind") + .build())); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + PartyFlagStructure individual = unwrapElements(builder.build().getRespondent1OrgIndividuals()).get(0); + Flags actualFlags = individual.getFlags(); + Flags expectedFlags = Flags.builder().partyName("Org Ind") + .details(List.of()) + .roleOnCase("Mr. Sole Trader").build(); + + assertThat(actualFlags).isEqualTo(expectedFlags); + assertThat(individual.getPartyID()).isNotNull(); + } + + @Test + void shouldUpdateFlagName_whenRespondent1OrgIndividualNameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .addRespondent1OrgIndividual("Org", "Person") + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(DEFENDANT_ONE_ORG_INDIVIDUALS_ID).build()) + .build(); + + PartyFlagStructure orgIndividual = unwrapElements(caseData.getRespondent1OrgIndividuals()).get(0); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .respondent1OrgIndividuals(wrapElements(orgIndividual.toBuilder() + .flags(Flags.builder() + .partyName("Org Person") + .roleOnCase("Mr. Sole Trader") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .firstName("Org").lastName("Ind") + .build())); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + PartyFlagStructure individual = unwrapElements(builder.build().getRespondent1OrgIndividuals()).get(0); + Flags actualFlags = individual.getFlags(); + Flags expectedFlags = Flags.builder().partyName("Org Ind") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("Mr. Sole Trader").build(); + + assertThat(actualFlags).isEqualTo(expectedFlags); + assertThat(individual.getPartyID()).isEqualTo("res-1-org-ind-party-id"); + } + + @Test + void shouldCreateFlag_whenRespondent2OrgIndividualAdded() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued() + .multiPartyClaimTwoDefendantSolicitors() + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(DEFENDANT_TWO_ORG_INDIVIDUALS_ID).build()) + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .respondent2OrgIndividuals(wrapElements(PartyFlagStructure.builder() + .firstName("Org").lastName("Ind") + .build())); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + PartyFlagStructure individual = unwrapElements(builder.build().getRespondent2OrgIndividuals()).get(0); + Flags actualFlags = individual.getFlags(); + Flags expectedFlags = Flags.builder().partyName("Org Ind") + .details(List.of()) + .roleOnCase("Mr. John Rambo").build(); + + assertThat(actualFlags).isEqualTo(expectedFlags); + assertThat(individual.getPartyID()).isNotNull(); + } + + @Test + void shouldUpdateFlagName_whenRespondent2OrgIndividualNameUpdated() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimIssued() + .multiPartyClaimTwoDefendantSolicitors() + .addRespondent2OrgIndividual("Org", "Person") + .updateDetailsForm(UpdateDetailsForm.builder().partyChosenId(DEFENDANT_TWO_ORG_INDIVIDUALS_ID).build()) + .build(); + + PartyFlagStructure lrIndividual = unwrapElements(caseData.getRespondent2OrgIndividuals()).get(0); + + CaseData.CaseDataBuilder builder = caseData.toBuilder() + .respondent2OrgIndividuals(wrapElements(lrIndividual.toBuilder() + .flags(Flags.builder() + .partyName("Org Person") + .roleOnCase("Mr. John Rambo") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))).build()) + .firstName("Org").lastName("Ind") + .build())); + + CaseFlagUtils.createOrUpdateFlags(builder, builder.build(), organisationService); + + PartyFlagStructure individual = unwrapElements(builder.build().getRespondent2OrgIndividuals()).get(0); + Flags actualFlags = individual.getFlags(); + Flags expectedFlags = Flags.builder().partyName("Org Ind") + .details(wrapElements(List.of( + FlagDetail.builder().name("flag name").build()))) + .roleOnCase("Mr. John Rambo").build(); + + assertThat(actualFlags).isEqualTo(expectedFlags); + assertThat(individual.getPartyID()).isEqualTo("res-2-org-ind-party-id"); + } + } + } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/utils/CaseFlagsInitialiserTest.java b/src/test/java/uk/gov/hmcts/reform/civil/utils/CaseFlagsInitialiserTest.java index 02eca86e0aa..334bb719764 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/utils/CaseFlagsInitialiserTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/utils/CaseFlagsInitialiserTest.java @@ -2,18 +2,47 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import uk.gov.hmcts.reform.ccd.model.OrganisationPolicy; import uk.gov.hmcts.reform.civil.callback.CaseEvent; -import uk.gov.hmcts.reform.civil.service.FeatureToggleService; +import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.model.PartyFlagStructure; +import uk.gov.hmcts.reform.civil.model.caseflags.FlagDetail; +import uk.gov.hmcts.reform.civil.model.dq.Applicant1DQ; +import uk.gov.hmcts.reform.civil.model.dq.Applicant2DQ; +import uk.gov.hmcts.reform.civil.model.dq.Expert; +import uk.gov.hmcts.reform.civil.model.dq.Experts; +import uk.gov.hmcts.reform.civil.model.dq.Respondent1DQ; +import uk.gov.hmcts.reform.civil.model.dq.Respondent2DQ; +import uk.gov.hmcts.reform.civil.model.dq.Witness; +import uk.gov.hmcts.reform.civil.model.dq.Witnesses; +import uk.gov.hmcts.reform.civil.model.UpdateDetailsForm; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.LitigationFriend; import uk.gov.hmcts.reform.civil.model.caseflags.Flags; +import uk.gov.hmcts.reform.civil.prd.model.Organisation; import uk.gov.hmcts.reform.civil.sampledata.PartyBuilder; +import uk.gov.hmcts.reform.civil.service.FeatureToggleService; +import uk.gov.hmcts.reform.civil.service.OrganisationService; import java.util.List; +import java.util.Optional; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.APPLICANT_SOLICITOR_EXPERT; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.APPLICANT_SOLICITOR_WITNESS; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.RESPONDENT_SOLICITOR_ONE_EXPERT; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.RESPONDENT_SOLICITOR_ONE_WITNESS; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.RESPONDENT_SOLICITOR_TWO_EXPERT; +import static uk.gov.hmcts.reform.civil.utils.CaseFlagUtils.RESPONDENT_SOLICITOR_TWO_WITNESS; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.unwrapElements; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_LEGAL_REP_INDIVIDUALS_ID; class CaseFlagsInitialiserTest { @@ -21,11 +50,16 @@ class CaseFlagsInitialiserTest { private FeatureToggleService featureToggleService; + private OrganisationService organisationService; + @BeforeEach void setup() { featureToggleService = mock(FeatureToggleService.class); - caseFlagsInitialiser = new CaseFlagsInitialiser(featureToggleService); + organisationService = mock(OrganisationService.class); + caseFlagsInitialiser = new CaseFlagsInitialiser(featureToggleService, organisationService); when(featureToggleService.isCaseFlagsEnabled()).thenReturn(true); + when(organisationService.findOrganisationById(anyString())) + .thenReturn(Optional.of(Organisation.builder().name("Civil - Organisation 1").build())); } @Test @@ -157,4 +191,832 @@ void shouldNotInitialiseCaseFlagsWhenCaseFlagsToggleIsOff() { assertEquals(expected, actual.build()); } + @Test + void shouldInitialiseCaseFlagsForManageContactInformationEvent() { + CaseData caseData = CaseData.builder() + .applicant1OrganisationPolicy(OrganisationPolicy.builder() + .organisation(uk.gov.hmcts.reform.ccd.model.Organisation.builder() + .organisationID("id") + .build()) + .build()) + .updateDetailsForm(UpdateDetailsForm.builder() + .partyChosenId(CLAIMANT_ONE_LEGAL_REP_INDIVIDUALS_ID) + .build()) + .build(); + + caseFlagsInitialiser.initialiseCaseFlags(CaseEvent.MANAGE_CONTACT_INFORMATION, caseData.toBuilder()); + + verify(organisationService).findOrganisationById("id"); + } + + @Test + void shouldReinitialiseMissingCaseFlags() { + Party applicant1 = PartyBuilder.builder().individual().build(); + Party applicant2 = PartyBuilder.builder().company().build(); + Party respondent1 = PartyBuilder.builder().soleTrader().build(); + LitigationFriend applicant1LitFriend = LitigationFriend.builder().firstName("Jason").lastName("Wilson").build(); + LitigationFriend applicant2LitFriend = LitigationFriend.builder().firstName("Jenny").lastName("Carter").build(); + Witness witness1 = Witness.builder().firstName("First").lastName("Name").build(); + Witness witness2 = Witness.builder().firstName("Second").lastName("witness").build(); + Witness witness3 = Witness.builder().firstName("Third").lastName("witnessy").build(); + Expert expert1 = Expert.builder().firstName("First").lastName("Name").build(); + Expert expert2 = Expert.builder().firstName("Second").lastName("expert").build(); + Expert expert3 = Expert.builder().firstName("Third").lastName("experto").build(); + + CaseData expected = CaseData.builder() + .applicant1( + applicant1.toBuilder().flags( + Flags.builder() + .partyName("Mr. John Rambo") + .roleOnCase("Applicant 1") + .details(List.of()).build()).build()) + .applicant2( + applicant2.toBuilder().flags( + Flags.builder() + .partyName("Company ltd") + .roleOnCase("Applicant 2") + .details(List.of()).build()).build()) + .applicant1LitigationFriend( + applicant1LitFriend.toBuilder().flags( + Flags.builder() + .partyName("Jason Wilson") + .roleOnCase("Applicant 1 Litigation Friend") + .details(List.of()).build()) + .build() + ) + .applicant2LitigationFriend( + applicant2LitFriend.toBuilder().flags( + Flags.builder() + .partyName("Jenny Carter") + .roleOnCase("Applicant 2 Litigation Friend") + .details(List.of()).build()) + .build()) + .respondent1( + respondent1.toBuilder().flags( + Flags.builder() + .partyName("Mr. Sole Trader") + .roleOnCase("Respondent 1") + .details(List.of()).build()).build()) + .applicantWitnesses(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .partyName("First Name") + .roleOnCase(APPLICANT_SOLICITOR_WITNESS) + .details(List.of()) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("witness") + .flags(Flags.builder() + .partyName("Second witness") + .roleOnCase(APPLICANT_SOLICITOR_WITNESS) + .details(List.of()) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Third") + .lastName("witnessy") + .flags(Flags.builder() + .partyName("Third witnessy") + .roleOnCase(APPLICANT_SOLICITOR_WITNESS) + .details(List.of()) + .build()) + .build()))) + .applicantExperts(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .partyName("First Name") + .roleOnCase(APPLICANT_SOLICITOR_EXPERT) + .details(List.of()) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("expert") + .flags(Flags.builder() + .partyName("Second expert") + .roleOnCase(APPLICANT_SOLICITOR_EXPERT) + .details(List.of()) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Third") + .lastName("experto") + .flags(Flags.builder() + .partyName("Third experto") + .roleOnCase(APPLICANT_SOLICITOR_EXPERT) + .details(List.of()) + .build()) + .build()))) + .respondent1Witnesses(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .partyName("First Name") + .roleOnCase(RESPONDENT_SOLICITOR_ONE_WITNESS) + .details(List.of()) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("witness") + .flags(Flags.builder() + .partyName("Second witness") + .roleOnCase(RESPONDENT_SOLICITOR_ONE_WITNESS) + .details(List.of()) + .build()) + .build()))) + .respondent1Experts(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .partyName("First Name") + .roleOnCase(RESPONDENT_SOLICITOR_ONE_EXPERT) + .details(List.of()) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("expert") + .flags(Flags.builder() + .partyName("Second expert") + .roleOnCase(RESPONDENT_SOLICITOR_ONE_EXPERT) + .details(List.of()) + .build()) + .build()))) + .build(); + + CaseData.CaseDataBuilder builder = CaseData.builder() + .applicant1(applicant1) + .applicant1LitigationFriend(applicant1LitFriend) + .applicant2(applicant2) + .addApplicant2(YES) + .addRespondent2(YES) + .applicant2LitigationFriend(applicant2LitFriend) + .applicant1DQ(Applicant1DQ.builder() + .applicant1DQWitnesses(Witnesses + .builder() + .details(wrapElements(witness1, witness2)) + .build()) + .applicant1DQExperts(Experts + .builder() + .details(wrapElements(expert1, expert2)) + .build()) + .build()) + .applicant2DQ(Applicant2DQ.builder() + .applicant2DQWitnesses(Witnesses + .builder() + .details(wrapElements(witness3)) + .build()) + .applicant2DQExperts(Experts + .builder() + .details(wrapElements(expert3)) + .build()) + .build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQExperts(Experts + .builder() + .details(wrapElements(expert1, expert2)) + .build()) + .respondent1DQWitnesses(Witnesses + .builder() + .details(wrapElements(witness1, witness2)) + .build()) + .build()) + .respondent1(respondent1); + + caseFlagsInitialiser.initialiseMissingCaseFlags(builder); + CaseData actual = builder.build(); + + assertFlags(expected, actual, false); + } + + @Test + void shouldNotReinitialiseCaseFlagsForRespondentDQ_whenRespondent1DQFlagsExist() { + Party applicant1 = PartyBuilder.builder().individual().build(); + Party applicant2 = PartyBuilder.builder().company().build(); + Party respondent1 = PartyBuilder.builder().soleTrader().build(); + Party respondent2 = PartyBuilder.builder().organisation().build(); + LitigationFriend applicant1LitFriend = LitigationFriend.builder().firstName("Jason").lastName("Wilson").build(); + LitigationFriend applicant2LitFriend = LitigationFriend.builder().firstName("Jenny").lastName("Carter").build(); + Witness witness1 = Witness.builder().firstName("First").lastName("Name").build(); + Witness witness2 = Witness.builder().firstName("Second").lastName("witness").build(); + Witness witness3 = Witness.builder().firstName("Third").lastName("witnessy").build(); + Expert expert1 = Expert.builder().firstName("First").lastName("Name").build(); + Expert expert2 = Expert.builder().firstName("Second").lastName("expert").build(); + Expert expert3 = Expert.builder().firstName("Third").lastName("experto").build(); + + CaseData expected = CaseData.builder() + .applicant1( + applicant1.toBuilder().flags( + Flags.builder() + .partyName("Mr. John Rambo") + .roleOnCase("Applicant 1") + .details(List.of()).build()).build()) + .applicant2( + applicant2.toBuilder().flags( + Flags.builder() + .partyName("Company ltd") + .roleOnCase("Applicant 2") + .details(List.of()).build()).build()) + .applicant1LitigationFriend( + applicant1LitFriend.toBuilder().flags( + Flags.builder() + .partyName("Jason Wilson") + .roleOnCase("Applicant 1 Litigation Friend") + .details(List.of()).build()) + .build() + ) + .applicant2LitigationFriend( + applicant2LitFriend.toBuilder().flags( + Flags.builder() + .partyName("Jenny Carter") + .roleOnCase("Applicant 2 Litigation Friend") + .details(List.of()).build()) + .build()) + .respondent1( + respondent1.toBuilder().flags( + Flags.builder() + .partyName("Mr. Sole Trader") + .roleOnCase("Respondent 1") + .details(List.of()).build()).build()) + .respondent2( + respondent2.toBuilder().flags( + Flags.builder() + .partyName("The Organisation") + .roleOnCase("Respondent 2") + .details(List.of()).build()).build()) + .applicantWitnesses(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .partyName("First Name") + .roleOnCase(APPLICANT_SOLICITOR_WITNESS) + .details(List.of()) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("witness") + .flags(Flags.builder() + .partyName("Second witness") + .roleOnCase(APPLICANT_SOLICITOR_WITNESS) + .details(List.of()) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Third") + .lastName("witnessy") + .flags(Flags.builder() + .partyName("Third witnessy") + .roleOnCase(APPLICANT_SOLICITOR_WITNESS) + .details(List.of()) + .build()) + .build()))) + .applicantExperts(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .partyName("First Name") + .roleOnCase(APPLICANT_SOLICITOR_EXPERT) + .details(List.of()) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("expert") + .flags(Flags.builder() + .partyName("Second expert") + .roleOnCase(APPLICANT_SOLICITOR_EXPERT) + .details(List.of()) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Third") + .lastName("experto") + .flags(Flags.builder() + .partyName("Third experto") + .roleOnCase(APPLICANT_SOLICITOR_EXPERT) + .details(List.of()) + .build()) + .build()))) + .respondent1Witnesses(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(RESPONDENT_SOLICITOR_ONE_WITNESS) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("witness") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(RESPONDENT_SOLICITOR_ONE_WITNESS) + .build()) + .build()))) + .respondent1Experts(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(RESPONDENT_SOLICITOR_ONE_EXPERT) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("expert") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(RESPONDENT_SOLICITOR_ONE_EXPERT) + .build()) + .build()))) + .respondent2Witnesses(wrapElements(List.of(PartyFlagStructure.builder() + .firstName("Third") + .lastName("witnessy") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(RESPONDENT_SOLICITOR_TWO_WITNESS) + .build()) + .build()))) + .respondent2Experts(wrapElements(List.of(PartyFlagStructure.builder() + .firstName("Third") + .lastName("experto") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(RESPONDENT_SOLICITOR_TWO_EXPERT) + .build()).build()))) + .build(); + + CaseData.CaseDataBuilder builder = CaseData.builder() + .applicant1(applicant1) + .applicant1LitigationFriend(applicant1LitFriend) + .applicant2(applicant2) + .addApplicant2(YES) + .applicant2LitigationFriend(applicant2LitFriend) + .applicant1DQ(Applicant1DQ.builder() + .applicant1DQWitnesses(Witnesses + .builder() + .details(wrapElements(witness1, witness2)) + .build()) + .applicant1DQExperts(Experts + .builder() + .details(wrapElements(expert1, expert2)) + .build()) + .build()) + .applicant2DQ(Applicant2DQ.builder() + .applicant2DQWitnesses(Witnesses + .builder() + .details(wrapElements(witness3)) + .build()) + .applicant2DQExperts(Experts + .builder() + .details(wrapElements(expert3)) + .build()) + .build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQExperts(Experts + .builder() + .details(wrapElements(expert1, expert2)) + .build()) + .respondent1DQWitnesses(Witnesses + .builder() + .details(wrapElements(witness1, witness2)) + .build()) + .build()) + .respondent2DQ(Respondent2DQ.builder() + .respondent2DQExperts(Experts.builder() + .details(wrapElements(expert3)) + .build()) + .respondent2DQWitnesses(Witnesses + .builder() + .details(wrapElements(witness3)) + .build()) + .build()) + .addRespondent2(YES) + .respondent1Witnesses(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .roleOnCase(RESPONDENT_SOLICITOR_ONE_WITNESS) + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("witness") + .flags(Flags.builder() + .roleOnCase(RESPONDENT_SOLICITOR_ONE_WITNESS) + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .build()) + .build()))) + .respondent1Experts(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .roleOnCase(RESPONDENT_SOLICITOR_ONE_EXPERT) + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("expert") + .flags(Flags.builder() + .roleOnCase(RESPONDENT_SOLICITOR_ONE_EXPERT) + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .build()) + .build()))) + .respondent2Witnesses(wrapElements(List.of(PartyFlagStructure.builder() + .firstName("Third") + .lastName("witnessy") + .flags(Flags.builder() + .roleOnCase(RESPONDENT_SOLICITOR_TWO_WITNESS) + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .build()) + .build()))) + .respondent2Experts(wrapElements(List.of(PartyFlagStructure.builder() + .firstName("Third") + .lastName("experto") + .flags(Flags.builder() + .roleOnCase(RESPONDENT_SOLICITOR_TWO_EXPERT) + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .build()).build()))) + .respondent1(respondent1) + .respondent2(respondent2); + + caseFlagsInitialiser.initialiseMissingCaseFlags(builder); + CaseData actual = builder.build(); + + assertFlags(expected, actual, true); + } + + @Test + void shouldNotReinitialiseCaseFlagsForApplicantDQ_whenApplicantDQFlagsExist() { + Party applicant1 = PartyBuilder.builder().individual().build(); + Party applicant2 = PartyBuilder.builder().company().build(); + Party respondent1 = PartyBuilder.builder().soleTrader().build(); + Party respondent2 = PartyBuilder.builder().organisation().build(); + LitigationFriend applicant1LitFriend = LitigationFriend.builder().firstName("Jason").lastName("Wilson").build(); + LitigationFriend applicant2LitFriend = LitigationFriend.builder().firstName("Jenny").lastName("Carter").build(); + Witness witness1 = Witness.builder().firstName("First").lastName("Name").build(); + Witness witness2 = Witness.builder().firstName("Second").lastName("witness").build(); + Witness witness3 = Witness.builder().firstName("Third").lastName("witnessy").build(); + Expert expert1 = Expert.builder().firstName("First").lastName("Name").build(); + Expert expert2 = Expert.builder().firstName("Second").lastName("expert").build(); + Expert expert3 = Expert.builder().firstName("Third").lastName("experto").build(); + + CaseData expected = CaseData.builder() + .applicant1( + applicant1.toBuilder().flags( + Flags.builder() + .partyName("Mr. John Rambo") + .roleOnCase("Applicant 1") + .details(List.of()).build()).build()) + .applicant2( + applicant2.toBuilder().flags( + Flags.builder() + .partyName("Company ltd") + .roleOnCase("Applicant 2") + .details(List.of()).build()).build()) + .applicant1LitigationFriend( + applicant1LitFriend.toBuilder().flags( + Flags.builder() + .partyName("Jason Wilson") + .roleOnCase("Applicant 1 Litigation Friend") + .details(List.of()).build()) + .build() + ) + .applicant2LitigationFriend( + applicant2LitFriend.toBuilder().flags( + Flags.builder() + .partyName("Jenny Carter") + .roleOnCase("Applicant 2 Litigation Friend") + .details(List.of()).build()) + .build()) + .respondent1( + respondent1.toBuilder().flags( + Flags.builder() + .partyName("Mr. Sole Trader") + .roleOnCase("Respondent 1") + .details(List.of()).build()).build()) + .respondent2( + respondent2.toBuilder().flags( + Flags.builder() + .partyName("The Organisation") + .roleOnCase("Respondent 2") + .details(List.of()).build()).build()) + .applicantWitnesses(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(APPLICANT_SOLICITOR_WITNESS) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("witness") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(APPLICANT_SOLICITOR_WITNESS) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Third") + .lastName("witnessy") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(APPLICANT_SOLICITOR_WITNESS) + .build()) + .build()))) + .applicantExperts(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(APPLICANT_SOLICITOR_EXPERT) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("expert") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(APPLICANT_SOLICITOR_EXPERT) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Third") + .lastName("experto") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(APPLICANT_SOLICITOR_EXPERT) + .build()) + .build()))) + .respondent1Witnesses(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .partyName("First Name") + .roleOnCase(RESPONDENT_SOLICITOR_ONE_WITNESS) + .details(wrapElements(List.of())) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("witness") + .flags(Flags.builder() + .partyName("Second witness") + .roleOnCase(RESPONDENT_SOLICITOR_ONE_WITNESS) + .details(wrapElements(List.of())) + .build()) + .build()))) + .respondent1Experts(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .partyName("First Name") + .roleOnCase(RESPONDENT_SOLICITOR_ONE_EXPERT) + .details(wrapElements(List.of())) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("expert") + .flags(Flags.builder() + .partyName("Second expert") + .roleOnCase(RESPONDENT_SOLICITOR_ONE_EXPERT) + .details(wrapElements(List.of())) + .build()) + .build()))) + .respondent2Witnesses(wrapElements(List.of(PartyFlagStructure.builder() + .firstName("Third") + .lastName("witnessy") + .flags(Flags.builder() + .partyName("Third witnessy") + .roleOnCase(RESPONDENT_SOLICITOR_TWO_WITNESS) + .details(wrapElements(List.of())) + .build()) + .build()))) + .respondent2Experts(wrapElements(List.of(PartyFlagStructure.builder() + .firstName("Third") + .lastName("experto") + .flags(Flags.builder() + .partyName("Third experto") + .roleOnCase(RESPONDENT_SOLICITOR_TWO_EXPERT) + .details(wrapElements(List.of())) + .build()).build()))) + .build(); + + CaseData.CaseDataBuilder builder = CaseData.builder() + .applicant1(applicant1) + .applicant1LitigationFriend(applicant1LitFriend) + .applicant2(applicant2) + .applicant2LitigationFriend(applicant2LitFriend) + .applicant1DQ(Applicant1DQ.builder() + .applicant1DQWitnesses(Witnesses + .builder() + .details(wrapElements(witness1, witness2)) + .build()) + .applicant1DQExperts(Experts + .builder() + .details(wrapElements(expert1, expert2)) + .build()) + .build()) + .applicant2DQ(Applicant2DQ.builder() + .applicant2DQWitnesses(Witnesses + .builder() + .details(wrapElements(witness3)) + .build()) + .applicant2DQExperts(Experts + .builder() + .details(wrapElements(expert3)) + .build()) + .build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQExperts(Experts + .builder() + .details(wrapElements(expert1, expert2)) + .build()) + .respondent1DQWitnesses(Witnesses + .builder() + .details(wrapElements(witness1, witness2)) + .build()) + .build()) + .respondent2DQ(Respondent2DQ.builder() + .respondent2DQExperts(Experts.builder() + .details(wrapElements(expert3)) + .build()) + .respondent2DQWitnesses(Witnesses + .builder() + .details(wrapElements(witness3)) + .build()) + .build()) + .respondent1(respondent1) + .respondent2(respondent2) + .applicantWitnesses(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(APPLICANT_SOLICITOR_WITNESS) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("witness") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(APPLICANT_SOLICITOR_WITNESS) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Third") + .lastName("witnessy") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(APPLICANT_SOLICITOR_WITNESS) + .build()) + .build() + ))) + .applicantExperts(wrapElements(List.of( + PartyFlagStructure.builder() + .firstName("First") + .lastName("Name") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(APPLICANT_SOLICITOR_EXPERT) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Second") + .lastName("expert") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(APPLICANT_SOLICITOR_EXPERT) + .build()) + .build(), + PartyFlagStructure.builder() + .firstName("Third") + .lastName("experto") + .flags(Flags.builder() + .details(wrapElements(List.of(FlagDetail.builder() + .name("Flag name") + .flagCode("123") + .build()))) + .roleOnCase(APPLICANT_SOLICITOR_EXPERT) + .build()) + .build() + ))); + + caseFlagsInitialiser.initialiseMissingCaseFlags(builder); + CaseData actual = builder.build(); + + assertFlags(expected, actual, true); + } + + private void assertFlags(CaseData expected, CaseData actual, boolean respondent2) { + assertThat(actual.getApplicant1().getFlags()).isEqualTo(expected.getApplicant1().getFlags()); + assertThat(actual.getApplicant2().getFlags()).isEqualTo(expected.getApplicant2().getFlags()); + assertThat(actual.getRespondent1().getFlags()).isEqualTo(expected.getRespondent1().getFlags()); + assertThat(actual.getApplicant1LitigationFriend().getFlags()).isEqualTo(expected.getApplicant1LitigationFriend().getFlags()); + assertThat(actual.getApplicant2LitigationFriend().getFlags()).isEqualTo(expected.getApplicant2LitigationFriend().getFlags()); + assertThat(unwrapElements(actual.getApplicantWitnesses())).isEqualTo(unwrapElements(expected.getApplicantWitnesses())); + assertThat(unwrapElements(actual.getApplicantExperts())).isEqualTo(unwrapElements(expected.getApplicantExperts())); + assertThat(unwrapElements(actual.getRespondent1Witnesses())).isEqualTo(unwrapElements(expected.getRespondent1Witnesses())); + assertThat(unwrapElements(actual.getRespondent1Experts())).isEqualTo(unwrapElements(expected.getRespondent1Experts())); + if (respondent2) { + assertThat(actual.getRespondent2().getFlags()).isEqualTo(expected.getRespondent2().getFlags()); + assertThat(unwrapElements(actual.getRespondent2Witnesses())).isEqualTo(unwrapElements(expected.getRespondent2Witnesses())); + assertThat(unwrapElements(actual.getRespondent2Experts())).isEqualTo(unwrapElements(expected.getRespondent2Experts())); + } + } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/utils/DocmosisTemplateDataUtilsTest.java b/src/test/java/uk/gov/hmcts/reform/civil/utils/DocmosisTemplateDataUtilsTest.java index c1e7adb37be..a5c4eeb9836 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/utils/DocmosisTemplateDataUtilsTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/utils/DocmosisTemplateDataUtilsTest.java @@ -83,6 +83,170 @@ void shouldReturnCaseName_whenMultiApplicant() { assertThat(caseName).isEqualTo("1 Mr. Sam Clark & 2 Mr. White Clark \nvs Mr. Alex Richards"); } + @Test + void shouldReturnCaseName_whenMultiApplicantAndApplicant2HaveLF() { + CaseData caseData = CaseData.builder() + .applicant1(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("Sam") + .individualLastName("Clark") + .partyName("Mr. Sam Clark") + .build()) + .applicant2(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("White") + .individualLastName("Clark") + .build()) + .applicant2LitigationFriend(LitigationFriend.builder().firstName("Litigation") + .lastName("Friend").build()) + .respondent1(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("Alex") + .individualLastName("Richards") + .build()) + .build(); + + String caseName = toCaseName.apply(caseData); + assertThat(caseName).isEqualTo("1 Mr. Sam Clark & 2 Mr. White Clark (proceeding by L/F Litigation Friend) \nvs Mr. Alex Richards"); + } + + @Test + void shouldReturnCaseName_whenMultiApplicantAndApplicant1HaveLF() { + CaseData caseData = CaseData.builder() + .applicant1(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("Sam") + .individualLastName("Clark") + .partyName("Mr. Sam Clark") + .build()) + .applicant1LitigationFriend(LitigationFriend.builder().firstName("Litigation") + .lastName("Friend").build()) + .applicant2(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("White") + .individualLastName("Clark") + .build()) + .respondent1(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("Alex") + .individualLastName("Richards") + .build()) + .build(); + + String caseName = toCaseName.apply(caseData); + assertThat(caseName).isEqualTo("1 Mr. Sam Clark (proceeding by L/F Litigation Friend) & 2 Mr. White Clark \nvs Mr. Alex Richards"); + } + + @Test + void shouldReturnCaseName_whenMultiApplicantAndBothApplicantsHaveLF() { + CaseData caseData = CaseData.builder() + .applicant1(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("Sam") + .individualLastName("Clark") + .partyName("Mr. Sam Clark") + .build()) + .applicant1LitigationFriend(LitigationFriend.builder().firstName("Litigation") + .lastName("Friend").build()) + .applicant2(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("White") + .individualLastName("Clark") + .build()) + .applicant2LitigationFriend(LitigationFriend.builder().firstName("Litigation") + .lastName("Friend").build()) + .respondent1(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("Alex") + .individualLastName("Richards") + .build()) + .build(); + + String caseName = toCaseName.apply(caseData); + assertThat(caseName).isEqualTo("1 Mr. Sam Clark (proceeding by L/F Litigation Friend) & 2 Mr. White Clark (proceeding by L/F Litigation Friend) \nvs Mr. Alex Richards"); + } + + @Test + void shouldReturnCaseName_whenMultiApplicantAndBothApplicantsAndRespondent1HaveLF() { + CaseData caseData = CaseData.builder() + .applicant1(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("Sam") + .individualLastName("Clark") + .partyName("Mr. Sam Clark") + .build()) + .applicant1LitigationFriend(LitigationFriend.builder().firstName("Litigation") + .lastName("Friend").build()) + .applicant2(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("White") + .individualLastName("Clark") + .build()) + .applicant2LitigationFriend(LitigationFriend.builder().firstName("Litigation") + .lastName("Friend").build()) + .respondent1(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("Alex") + .individualLastName("Richards") + .build()) + .respondent1LitigationFriend(LitigationFriend.builder().firstName("Respondent Litigation") + .lastName("Friend").build()) + .build(); + + String caseName = toCaseName.apply(caseData); + assertThat(caseName).isEqualTo("1 Mr. Sam Clark (proceeding by L/F Litigation Friend) & " + + "2 Mr. White Clark (proceeding by L/F Litigation Friend) \nvs " + + "Mr. Alex Richards (proceeding by L/F Respondent Litigation Friend)"); + } + + @Test + void shouldReturnCaseName_whenMultiRespondentAndBothApplicantAndRespondentsHaveLF() { + CaseData caseData = CaseData.builder() + .applicant1(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("Sam") + .individualLastName("Clark") + .partyName("Mr. Sam Clark") + .build()) + .applicant1LitigationFriend(LitigationFriend.builder().firstName("Litigation") + .lastName("Friend").build()) + .respondent1(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("Alex") + .individualLastName("Richards") + .build()) + .respondent1LitigationFriend(LitigationFriend.builder().firstName("Respondent Litigation") + .lastName("Friend").build()) + .respondent2(Party.builder() + .type(Party.Type.INDIVIDUAL) + .individualTitle("Mr.") + .individualFirstName("White") + .individualLastName("Richards") + .build()) + .respondent2LitigationFriend(LitigationFriend.builder().firstName("Respondent2 Litigation") + .lastName("Friend").build()) + .build(); + + String caseName = toCaseName.apply(caseData); + assertThat(caseName).isEqualTo("Mr. Sam Clark (proceeding by L/F Litigation Friend) \n" + + "vs 1 Mr. Alex Richards (proceeding by L/F Respondent Litigation Friend) &" + + " 2 Mr. White Richards (proceeding by L/F Respondent2 Litigation Friend)"); + } + @Test void shouldReturnCaseName_whenMultiRespondent() { CaseData caseData = CaseData.builder() @@ -196,11 +360,12 @@ void shouldReturnCaseName_whenRespondentHasLitigationFriend() { .individualLastName("Richards") .partyName("Mr. Other Party") .build()) - .respondent1LitigationFriend(LitigationFriend.builder().fullName("Mr. Litigation Friend").build()) + .respondent1LitigationFriend(LitigationFriend.builder().firstName("Litigation") + .lastName("Friend").build()) .build(); String caseName = toCaseName.apply(caseData); assertThat(caseName) - .isEqualTo("Mr. Sam Clark \nvs Mr. Alex Richards (proceeding by L/F Mr. Litigation Friend)"); + .isEqualTo("Mr. Sam Clark \nvs Mr. Alex Richards (proceeding by L/F Litigation Friend)"); } @Test @@ -212,7 +377,8 @@ void shouldReturnCaseName_whenApplicantHasLitigationFriend() { .individualFirstName("Sam") .individualLastName("Clark") .build()) - .applicant1LitigationFriend(LitigationFriend.builder().fullName("Mr. Litigation Friend").build()) + .applicant1LitigationFriend(LitigationFriend.builder().firstName("Litigation") + .lastName("Friend").build()) .respondent1(Party.builder() .type(Party.Type.INDIVIDUAL) .individualTitle("Mr.") @@ -223,7 +389,7 @@ void shouldReturnCaseName_whenApplicantHasLitigationFriend() { .build(); String caseName = toCaseName.apply(caseData); assertThat(caseName) - .isEqualTo("Mr. Sam Clark (proceeding by L/F Mr. Litigation Friend) \nvs Mr. Alex Richards"); + .isEqualTo("Mr. Sam Clark (proceeding by L/F Litigation Friend) \nvs Mr. Alex Richards"); } @Test @@ -236,18 +402,21 @@ void shouldReturnCaseName_whenBothHasLitigationFriend() { .individualLastName("Clark") .partyName("Mr. Sam Clark") .build()) - .applicant1LitigationFriend(LitigationFriend.builder().fullName("Mr. Applicant Friend").build()) + .applicant1LitigationFriend(LitigationFriend.builder().firstName("Applicant") + .lastName("Friend").build()) .respondent1(Party.builder() .type(Party.Type.INDIVIDUAL) .individualTitle("Mr.") .individualFirstName("Alex") .individualLastName("Richards") .build()) - .respondent1LitigationFriend(LitigationFriend.builder().fullName("Mr. Respondent Friend").build()) + .respondent1LitigationFriend(LitigationFriend.builder() + .firstName("Respondent") + .lastName("Friend").build()) .build(); String caseName = toCaseName.apply(caseData); - assertThat(caseName).isEqualTo("Mr. Sam Clark (proceeding by L/F Mr. Applicant Friend) \nvs Mr. Alex Richards " - + "(proceeding by L/F Mr. Respondent Friend)"); + assertThat(caseName).isEqualTo("Mr. Sam Clark (proceeding by L/F Applicant Friend) \nvs Mr. Alex Richards " + + "(proceeding by L/F Respondent Friend)"); } @Nested diff --git a/src/test/java/uk/gov/hmcts/reform/civil/utils/JudicialReferralUtilsTest.java b/src/test/java/uk/gov/hmcts/reform/civil/utils/JudicialReferralUtilsTest.java new file mode 100644 index 00000000000..72601e30b71 --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/utils/JudicialReferralUtilsTest.java @@ -0,0 +1,53 @@ +package uk.gov.hmcts.reform.civil.utils; + +import org.junit.jupiter.api.Test; +import uk.gov.hmcts.reform.civil.enums.CaseCategory; +import uk.gov.hmcts.reform.civil.enums.YesOrNo; +import uk.gov.hmcts.reform.civil.model.CaseData; +import uk.gov.hmcts.reform.civil.model.ClaimValue; + +import java.math.BigDecimal; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; + +public class JudicialReferralUtilsTest { + + @Test + public void testShouldMoveToJudicialReferralForSpecClaim() { + CaseData caseData = CaseData.builder() + .caseAccessCategory(CaseCategory.SPEC_CLAIM) + .applicant1ProceedWithClaim(YesOrNo.YES) + .build(); + + boolean judicialReferralUtils = JudicialReferralUtils.shouldMoveToJudicialReferral(caseData); + assertTrue(judicialReferralUtils); + } + + @Test + public void testShouldNotMoveToJudicialReferralForSpecClaim() { + CaseData caseData = CaseData.builder() + .caseAccessCategory(CaseCategory.SPEC_CLAIM) + .applicant1ProceedWithClaim(YesOrNo.NO) + .build(); + + boolean judicialReferralUtils = JudicialReferralUtils.shouldMoveToJudicialReferral(caseData); + + assertFalse(judicialReferralUtils); + } + + @Test + public void testShouldMoveToJudicialReferralForUnspecClaim() { + CaseData caseData = CaseData.builder() + .caseAccessCategory(CaseCategory.UNSPEC_CLAIM) + .claimValue(ClaimValue.builder() + .statementOfValueInPennies(BigDecimal.valueOf(10000_00)) + .build()) + .applicant1ProceedWithClaim(YesOrNo.YES) + .build(); + + boolean judicialReferralUtils = JudicialReferralUtils.shouldMoveToJudicialReferral(caseData); + assertTrue(judicialReferralUtils); + } + +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/utils/ManageContactInformationUtilsTest.java b/src/test/java/uk/gov/hmcts/reform/civil/utils/ManageContactInformationUtilsTest.java index f8fc3f207cb..ac5effba420 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/utils/ManageContactInformationUtilsTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/utils/ManageContactInformationUtilsTest.java @@ -1,11 +1,16 @@ package uk.gov.hmcts.reform.civil.utils; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.Party; +import uk.gov.hmcts.reform.civil.model.UpdatePartyDetailsForm; import uk.gov.hmcts.reform.civil.model.common.DynamicListElement; +import uk.gov.hmcts.reform.civil.model.dq.Expert; +import uk.gov.hmcts.reform.civil.model.dq.Witness; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; - +import java.math.BigDecimal; +import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @@ -14,13 +19,26 @@ import static uk.gov.hmcts.reform.civil.enums.RespondentResponseType.FULL_DEFENCE; import static uk.gov.hmcts.reform.civil.enums.YesOrNo.YES; import static uk.gov.hmcts.reform.civil.model.Party.Type.COMPANY; +import static uk.gov.hmcts.reform.civil.model.Party.Type.INDIVIDUAL; import static uk.gov.hmcts.reform.civil.model.Party.Type.ORGANISATION; +import static uk.gov.hmcts.reform.civil.model.Party.Type.SOLE_TRADER; import static uk.gov.hmcts.reform.civil.model.common.DynamicListElement.dynamicElementFromCode; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_ONE_LITIGATION_FRIEND_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.CLAIMANT_TWO_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_ONE_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_ID; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.DEFENDANT_TWO_LITIGATION_FRIEND_ID; import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.addApplicant1Options; import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.addApplicantOptions2v1; import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.addDefendant1Options; import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.addDefendant2Options; import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.addDefendantOptions1v2SameSolicitor; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.appendUserAndType; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.mapExpertsToUpdatePartyDetailsForm; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.mapUpdatePartyDetailsFormToDQExperts; +import static uk.gov.hmcts.reform.civil.utils.ManageContactInformationUtils.mapUpdatePartyDetailsFormToDQWitnesses; class ManageContactInformationUtilsTest { @@ -246,11 +264,219 @@ void shouldAddCorrectOptions_forDefendant1v2SameSolicitorAsAdmin() { assertThat(options).isEqualTo(expectedDefendants1v2SameSolicitorOptions(true, true)); } + @Test + void shouldMapExpertsToUpdatePartyDetailsForm() { + Expert expert1 = Expert.builder().firstName("First").lastName("Name").partyID("id").eventAdded("event").build(); + Expert expert2 = Expert.builder().firstName("Second").lastName("expert").fieldOfExpertise("field") + .phoneNumber("1").emailAddress("email").partyID("id2").build(); + UpdatePartyDetailsForm party = UpdatePartyDetailsForm.builder().firstName("First").lastName("Name") + .partyId("id").build(); + UpdatePartyDetailsForm party2 = UpdatePartyDetailsForm.builder().firstName("Second").lastName("expert") + .fieldOfExpertise("field").phoneNumber("1").emailAddress("email").partyId("id2").build(); + + assertThat(mapExpertsToUpdatePartyDetailsForm(wrapElements(expert1, expert2))) + .isEqualTo(wrapElements(party, party2)); + } + + @Test + void shouldMapExpertsToUpdatePartyDetailsForm_ifEmpty() { + assertThat(mapExpertsToUpdatePartyDetailsForm(null)).isEqualTo(new ArrayList<>()); + } + + @Nested + class MapToDQExperts { + UpdatePartyDetailsForm party = UpdatePartyDetailsForm.builder().firstName("Lewis").lastName("John") + .partyId("id").build(); + UpdatePartyDetailsForm party2 = UpdatePartyDetailsForm.builder().firstName("Second").lastName("expert") + .fieldOfExpertise("field").phoneNumber("1").emailAddress("expertemail").partyId("id2").build(); + + LocalDate date = LocalDate.of(2020, 3, 20); + + Expert expert1 = Expert.builder().firstName("First").lastName("Name").partyID("id").eventAdded("event") + .dateAdded(date).estimatedCost(BigDecimal.valueOf(10000)).build(); + Expert expert2 = Expert.builder().firstName("Second").lastName("expert").fieldOfExpertise("field") + .eventAdded("event").dateAdded(date).phoneNumber("1").emailAddress("email").partyID("id2").build(); + + @Test + void shouldEditExperts() { + Expert expectedExpert1 = Expert.builder().firstName("Lewis").lastName("John").partyID("id") + .eventAdded("event").dateAdded(date).estimatedCost(BigDecimal.valueOf(10000)).build(); + Expert expectedExpert2 = Expert.builder().firstName("Second").lastName("expert").fieldOfExpertise("field") + .eventAdded("event").dateAdded(date).phoneNumber("1").emailAddress("expertemail").partyID("id2").build(); + + assertThat(mapUpdatePartyDetailsFormToDQExperts(wrapElements(expert1, expert2), wrapElements(party, party2))) + .isEqualTo(wrapElements(expectedExpert1, expectedExpert2)); + } + + @Test + void shouldAddExperts() { + Expert expectedExpert1 = Expert.builder().firstName("Lewis").lastName("John") + .eventAdded("Manage Contact Information Event").dateAdded(LocalDate.now()) + .partyID(null) //change this for CIV-10382 + .build(); + Expert expectedExpert2 = Expert.builder().firstName("Second").lastName("expert").fieldOfExpertise("field") + .eventAdded("Manage Contact Information Event").dateAdded(LocalDate.now()).phoneNumber("1") + .emailAddress("expertemail") + .partyID(null) //change this for CIV-10382 + .build(); + + assertThat(mapUpdatePartyDetailsFormToDQExperts(null, wrapElements(party, party2))) + .isEqualTo(wrapElements(expectedExpert1, expectedExpert2)); + } + + @Test + void shouldAddExpertsWithExistingExperts() { + Expert expectedExpert1 = Expert.builder().firstName("Lewis").lastName("John").partyID("id") + .eventAdded("event").dateAdded(date).estimatedCost(BigDecimal.valueOf(10000)).build(); + Expert expectedExpert2 = Expert.builder().firstName("Second").lastName("expert").fieldOfExpertise("field") + .eventAdded("Manage Contact Information Event").dateAdded(LocalDate.now()).phoneNumber("1") + .emailAddress("expertemail") + .partyID(null) //change this for CIV-10382 + .build(); + + assertThat(mapUpdatePartyDetailsFormToDQExperts(wrapElements(expert1), wrapElements(party, party2))) + .isEqualTo(wrapElements(expectedExpert1, expectedExpert2)); + } + } + + @Nested + class MapToDQWitnesses { + UpdatePartyDetailsForm party = UpdatePartyDetailsForm.builder().firstName("Lewis").lastName("John") + .partyId("id").build(); + UpdatePartyDetailsForm party2 = UpdatePartyDetailsForm.builder().firstName("Second").lastName("witness") + .phoneNumber("1").emailAddress("witnessemail").partyId("id2").build(); + + LocalDate date = LocalDate.of(2020, 3, 20); + + Witness witness1 = Witness.builder().firstName("First").lastName("Name").partyID("id").eventAdded("event") + .dateAdded(date).reasonForWitness("reason").build(); + Witness witness2 = Witness.builder().firstName("Second").lastName("expert").eventAdded("event") + .dateAdded(date).phoneNumber("1").emailAddress("email").partyID("id2").build(); + + @Test + void shouldEditWitnesses() { + Witness expectedWitness1 = Witness.builder().firstName("Lewis").lastName("John") + .eventAdded("event").dateAdded(date).reasonForWitness("reason").partyID("id").build(); + + Witness expectedWitness2 = Witness.builder().firstName("Second").lastName("witness") + .eventAdded("event").dateAdded(date).phoneNumber("1").emailAddress("witnessemail") + .partyID("id2").build(); + + assertThat(mapUpdatePartyDetailsFormToDQWitnesses(wrapElements(witness1, witness2), wrapElements(party, party2))) + .isEqualTo(wrapElements(expectedWitness1, expectedWitness2)); + } + + @Test + void shouldAddWitnesses() { + Witness expectedWitness1 = Witness.builder().firstName("Lewis").lastName("John") + .eventAdded("Manage Contact Information Event").dateAdded(LocalDate.now()) + .partyID(null).build(); // CIV-10382 + Witness expectedWitness2 = Witness.builder().firstName("Second").lastName("witness") + .eventAdded("Manage Contact Information Event").dateAdded(LocalDate.now()).phoneNumber("1") + .emailAddress("witnessemail") + .partyID(null).build(); // CIV-10382 + + assertThat(mapUpdatePartyDetailsFormToDQWitnesses(null, wrapElements(party, party2))) + .isEqualTo(wrapElements(expectedWitness1, expectedWitness2)); + } + + @Test + void shouldRemoveWitnesses() { + assertThat(mapUpdatePartyDetailsFormToDQWitnesses(wrapElements(witness1, witness2), null)) + .isEmpty(); + } + + @Test + void shouldAddWitnessesWithExistingWitnesses() { + Witness expectedWitness1 = Witness.builder().firstName("Lewis").lastName("John").partyID("id") + .reasonForWitness("reason").eventAdded("event").dateAdded(date).build(); + Witness expectedWitness2 = Witness.builder().firstName("Second").lastName("witness") + .eventAdded("Manage Contact Information Event").dateAdded(LocalDate.now()).phoneNumber("1") + .emailAddress("witnessemail") + .partyID(null) //change this for CIV-10382 + .build(); + + assertThat(mapUpdatePartyDetailsFormToDQWitnesses(wrapElements(witness1), wrapElements(party, party2))) + .isEqualTo(wrapElements(expectedWitness1, expectedWitness2)); + } + } + + @Nested + class AppendCorrectUserAndType { + @Test + void shouldHaveCorrectID_ClaimantOneAdminIndividual() { + CaseData caseData = CaseDataBuilder.builder() + .applicant1(Party.builder().type(INDIVIDUAL).build()).build(); + + String result = appendUserAndType(CLAIMANT_ONE_ID, caseData, true); + + assertThat(result).isEqualTo("CLAIMANT_1_ADMIN_INDIVIDUAL"); + } + + @Test + void shouldHaveCorrectID_ClaimantTwoAdminSoleTrader() { + CaseData caseData = CaseDataBuilder.builder() + .applicant2(Party.builder().type(SOLE_TRADER).build()).build(); + + String result = appendUserAndType(CLAIMANT_TWO_ID, caseData, true); + + assertThat(result).isEqualTo("CLAIMANT_2_ADMIN_SOLE_TRADER"); + } + + @Test + void shouldHaveCorrectID_DefendantOneAdminOrganisation() { + CaseData caseData = CaseDataBuilder.builder() + .respondent1(Party.builder().type(ORGANISATION).build()).build(); + + String result = appendUserAndType(DEFENDANT_ONE_ID, caseData, true); + + assertThat(result).isEqualTo("DEFENDANT_1_ADMIN_ORGANISATION"); + } + + @Test + void shouldHaveCorrectID_DefendantTwoAdminCompany() { + CaseData caseData = CaseDataBuilder.builder() + .respondent2(Party.builder().type(COMPANY).build()).build(); + + String result = appendUserAndType(DEFENDANT_TWO_ID, caseData, true); + + assertThat(result).isEqualTo("DEFENDANT_2_ADMIN_COMPANY"); + } + + @Test + void shouldHaveCorrectID_DefendantTwoLegalRepIndividual() { + CaseData caseData = CaseDataBuilder.builder() + .respondent2(Party.builder().type(INDIVIDUAL).build()).build(); + + String result = appendUserAndType(DEFENDANT_TWO_ID, caseData, false); + + assertThat(result).isEqualTo("DEFENDANT_2_LR_INDIVIDUAL"); + } + + @Test + void shouldHaveCorrectID_Applicant1LitigationFriendAdmin() { + CaseData caseData = CaseDataBuilder.builder().build(); + + String result = appendUserAndType(CLAIMANT_ONE_LITIGATION_FRIEND_ID, caseData, false); + + assertThat(result).isEqualTo("CLAIMANT_1_LITIGATION_FRIEND_LR"); + } + + @Test + void shouldHaveCorrectID_Defendant2LitigationFriendAdmin() { + CaseData caseData = CaseDataBuilder.builder().build(); + + String result = appendUserAndType(DEFENDANT_TWO_LITIGATION_FRIEND_ID, caseData, true); + + assertThat(result).isEqualTo("DEFENDANT_2_LITIGATION_FRIEND_ADMIN"); + } + } + private List expectedApplicant1Options(boolean withExpertsAndWitnesses, boolean isAdmin) { List list = new ArrayList<>(); list.add(dynamicElementFromCode("CLAIMANT_1", "CLAIMANT 1: Mr. John Rambo")); - list.add(dynamicElementFromCode("CLAIMANT_1_LITIGATIONFRIEND", "CLAIMANT 1: Litigation Friend: Applicant Litigation Friend")); - list.add(dynamicElementFromCode("CLAIMANT_1_INDIVIDUALSSOLICITORORG", "CLAIMANT 1: Individuals attending for the legal representative")); + list.add(dynamicElementFromCode("CLAIMANT_1_LITIGATION_FRIEND", "CLAIMANT 1: Litigation Friend: Applicant Litigation Friend")); + list.add(dynamicElementFromCode("CLAIMANT_1_LR_INDIVIDUALS", "CLAIMANT 1: Individuals attending for the legal representative")); if (withExpertsAndWitnesses || isAdmin) { list.add(dynamicElementFromCode("CLAIMANT_1_WITNESSES", "CLAIMANT 1: Witnesses")); list.add(dynamicElementFromCode("CLAIMANT_1_EXPERTS", "CLAIMANT 1: Experts")); @@ -261,8 +487,8 @@ private List expectedApplicant1Options(boolean withExpertsAn private List expectedApplicant1OrgOptions(boolean withExpertsAndWitnesses, boolean isAdmin) { List list = new ArrayList<>(); list.add(dynamicElementFromCode("CLAIMANT_1", "CLAIMANT 1: Test Inc")); - list.add(dynamicElementFromCode("CLAIMANT_1_INDIVIDUALSORG", "CLAIMANT 1: Individuals attending for the organisation")); - list.add(dynamicElementFromCode("CLAIMANT_1_INDIVIDUALSSOLICITORORG", "CLAIMANT 1: Individuals attending for the legal representative")); + list.add(dynamicElementFromCode("CLAIMANT_1_ORGANISATION_INDIVIDUALS", "CLAIMANT 1: Individuals attending for the organisation")); + list.add(dynamicElementFromCode("CLAIMANT_1_LR_INDIVIDUALS", "CLAIMANT 1: Individuals attending for the legal representative")); if (withExpertsAndWitnesses || isAdmin) { list.add(dynamicElementFromCode("CLAIMANT_1_WITNESSES", "CLAIMANT 1: Witnesses")); list.add(dynamicElementFromCode("CLAIMANT_1_EXPERTS", "CLAIMANT 1: Experts")); @@ -273,10 +499,10 @@ private List expectedApplicant1OrgOptions(boolean withExpert private List expectedApplicants2v1Options(boolean withExpertsAndWitnesses, boolean isAdmin) { List list = new ArrayList<>(); list.add(dynamicElementFromCode("CLAIMANT_1", "CLAIMANT 1: Mr. John Rambo")); - list.add(dynamicElementFromCode("CLAIMANT_1_LITIGATIONFRIEND", "CLAIMANT 1: Litigation Friend: Applicant Litigation Friend")); + list.add(dynamicElementFromCode("CLAIMANT_1_LITIGATION_FRIEND", "CLAIMANT 1: Litigation Friend: Applicant Litigation Friend")); list.add(dynamicElementFromCode("CLAIMANT_2", "CLAIMANT 2: Mr. Jason Rambo")); - list.add(dynamicElementFromCode("CLAIMANT_2_LITIGATIONFRIEND", "CLAIMANT 2: Litigation Friend: Applicant Two Litigation Friend")); - list.add(dynamicElementFromCode("CLAIMANT_1_INDIVIDUALSSOLICITORORG", "CLAIMANTS: Individuals attending for the legal representative")); + list.add(dynamicElementFromCode("CLAIMANT_2_LITIGATION_FRIEND", "CLAIMANT 2: Litigation Friend: Applicant Two Litigation Friend")); + list.add(dynamicElementFromCode("CLAIMANT_1_LR_INDIVIDUALS", "CLAIMANTS: Individuals attending for the legal representative")); if (withExpertsAndWitnesses || isAdmin) { list.add(dynamicElementFromCode("CLAIMANT_1_WITNESSES", "CLAIMANTS: Witnesses")); list.add(dynamicElementFromCode("CLAIMANT_1_EXPERTS", "CLAIMANTS: Experts")); @@ -287,8 +513,8 @@ private List expectedApplicants2v1Options(boolean withExpert private List expectedDefendant1Options(boolean withExpertsAndWitnesses, boolean isAdmin) { List list = new ArrayList<>(); list.add(dynamicElementFromCode("DEFENDANT_1", "DEFENDANT 1: Mr. Sole Trader")); - list.add(dynamicElementFromCode("DEFENDANT_1_LITIGATIONFRIEND", "DEFENDANT 1: Litigation Friend: Litigation Friend")); - list.add(dynamicElementFromCode("DEFENDANT_1_INDIVIDUALSSOLICITORORG", "DEFENDANT 1: Individuals attending for the legal representative")); + list.add(dynamicElementFromCode("DEFENDANT_1_LITIGATION_FRIEND", "DEFENDANT 1: Litigation Friend: Litigation Friend")); + list.add(dynamicElementFromCode("DEFENDANT_1_LR_INDIVIDUALS", "DEFENDANT 1: Individuals attending for the legal representative")); if (withExpertsAndWitnesses || isAdmin) { list.add(dynamicElementFromCode("DEFENDANT_1_WITNESSES", "DEFENDANT 1: Witnesses")); list.add(dynamicElementFromCode("DEFENDANT_1_EXPERTS", "DEFENDANT 1: Experts")); @@ -299,8 +525,8 @@ private List expectedDefendant1Options(boolean withExpertsAn private List expectedDefendant2Options(boolean withExpertsAndWitnesses, boolean isAdmin) { List list = new ArrayList<>(); list.add(dynamicElementFromCode("DEFENDANT_2", "DEFENDANT 2: Mr. John Rambo")); - list.add(dynamicElementFromCode("DEFENDANT_2_LITIGATIONFRIEND", "DEFENDANT 2: Litigation Friend: Litigation Friend")); - list.add(dynamicElementFromCode("DEFENDANT_2_INDIVIDUALSSOLICITORORG", "DEFENDANT 2: Individuals attending for the legal representative")); + list.add(dynamicElementFromCode("DEFENDANT_2_LITIGATION_FRIEND", "DEFENDANT 2: Litigation Friend: Litigation Friend")); + list.add(dynamicElementFromCode("DEFENDANT_2_LR_INDIVIDUALS", "DEFENDANT 2: Individuals attending for the legal representative")); if (withExpertsAndWitnesses || isAdmin) { list.add(dynamicElementFromCode("DEFENDANT_2_WITNESSES", "DEFENDANT 2: Witnesses")); list.add(dynamicElementFromCode("DEFENDANT_2_EXPERTS", "DEFENDANT 2: Experts")); @@ -311,10 +537,10 @@ private List expectedDefendant2Options(boolean withExpertsAn private List expectedDefendants1v2SameSolicitorOptions(boolean withExpertsAndWitnesses, boolean isAdmin) { List list = new ArrayList<>(); list.add(dynamicElementFromCode("DEFENDANT_1", "DEFENDANT 1: Mr. Sole Trader")); - list.add(dynamicElementFromCode("DEFENDANT_1_LITIGATIONFRIEND", "DEFENDANT 1: Litigation Friend: Litigation Friend")); + list.add(dynamicElementFromCode("DEFENDANT_1_LITIGATION_FRIEND", "DEFENDANT 1: Litigation Friend: Litigation Friend")); list.add(dynamicElementFromCode("DEFENDANT_2", "DEFENDANT 2: Mr. John Rambo")); - list.add(dynamicElementFromCode("DEFENDANT_2_LITIGATIONFRIEND", "DEFENDANT 2: Litigation Friend: Litigation Friend")); - list.add(dynamicElementFromCode("DEFENDANT_1_INDIVIDUALSSOLICITORORG", "DEFENDANTS: Individuals attending for the legal representative")); + list.add(dynamicElementFromCode("DEFENDANT_2_LITIGATION_FRIEND", "DEFENDANT 2: Litigation Friend: Litigation Friend")); + list.add(dynamicElementFromCode("DEFENDANT_1_LR_INDIVIDUALS", "DEFENDANTS: Individuals attending for the legal representative")); if (withExpertsAndWitnesses || isAdmin) { list.add(dynamicElementFromCode("DEFENDANT_1_WITNESSES", "DEFENDANTS: Witnesses")); list.add(dynamicElementFromCode("DEFENDANT_1_EXPERTS", "DEFENDANTS: Experts")); diff --git a/src/test/java/uk/gov/hmcts/reform/civil/utils/PartyUtilsTest.java b/src/test/java/uk/gov/hmcts/reform/civil/utils/PartyUtilsTest.java index b01e00d3b95..fee3080f0a0 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/utils/PartyUtilsTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/utils/PartyUtilsTest.java @@ -12,6 +12,15 @@ import uk.gov.hmcts.reform.civil.model.PartyFlagStructure; import uk.gov.hmcts.reform.civil.model.SolicitorReferences; import uk.gov.hmcts.reform.civil.model.common.Element; +import uk.gov.hmcts.reform.civil.model.dq.Applicant1DQ; +import uk.gov.hmcts.reform.civil.model.dq.Applicant2DQ; +import uk.gov.hmcts.reform.civil.model.dq.Expert; +import uk.gov.hmcts.reform.civil.model.dq.ExpertDetails; +import uk.gov.hmcts.reform.civil.model.dq.Experts; +import uk.gov.hmcts.reform.civil.model.dq.Respondent1DQ; +import uk.gov.hmcts.reform.civil.model.dq.Respondent2DQ; +import uk.gov.hmcts.reform.civil.model.dq.Witness; +import uk.gov.hmcts.reform.civil.model.dq.Witnesses; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.sampledata.PartyBuilder; @@ -31,6 +40,7 @@ import static uk.gov.hmcts.reform.civil.enums.RespondentResponseType.FULL_DEFENCE; import static uk.gov.hmcts.reform.civil.enums.RespondentResponseType.PART_ADMISSION; import static uk.gov.hmcts.reform.civil.sampledata.PartyBuilder.DATE_OF_BIRTH; +import static uk.gov.hmcts.reform.civil.utils.ElementUtils.unwrapElements; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; class PartyUtilsTest { @@ -144,8 +154,11 @@ void shouldProvideName_whenPartyTypeIsIndividualAndLitigationFriend() { .individualFirstName("Jacob") .individualLastName("Martin") .type(Party.Type.INDIVIDUAL).build(); - LitigationFriend litigationFriend = LitigationFriend.builder().fullName("Mr Litigious Friend").build(); - assertEquals("Mr Jacob Martin L/F Mr Litigious Friend", + LitigationFriend litigationFriend = LitigationFriend.builder() + .firstName("Litigious") + .lastName("Friend") + .build(); + assertEquals("Mr Jacob Martin L/F Litigious Friend", PartyUtils.getLitigiousPartyName(individual, litigationFriend)); } @@ -658,13 +671,7 @@ void shouldPopulatePartyIds_withinGivenCaseDataBuilder() { .respondent2(Party.builder().partyName("mock party 5").build()) .applicant1LitigationFriend(LitigationFriend.builder().firstName("mock litfriend 1").build()) .respondent1LitigationFriend(LitigationFriend.builder().firstName("mock litfriend 2").build()) - .respondent2LitigationFriend(LitigationFriend.builder().firstName("mock litfriend 3").build()) - .applicantExperts(wrapElements(List.of(PartyFlagStructure.builder().firstName("expert 1").build()))) - .respondent1Experts(wrapElements(List.of(PartyFlagStructure.builder().firstName("expert 2").build()))) - .respondent2Experts(wrapElements(List.of(PartyFlagStructure.builder().firstName("expert 3").build()))) - .applicantWitnesses(wrapElements(List.of(PartyFlagStructure.builder().firstName("witness 1").build()))) - .respondent1Witnesses(wrapElements(List.of(PartyFlagStructure.builder().firstName("witness 2").build()))) - .respondent2Witnesses(wrapElements(List.of(PartyFlagStructure.builder().firstName("witness 3").build()))); + .respondent2LitigationFriend(LitigationFriend.builder().firstName("mock litfriend 3").build()); PartyUtils.populateWithPartyIds(builder); CaseData actual = builder.build(); @@ -676,12 +683,6 @@ void shouldPopulatePartyIds_withinGivenCaseDataBuilder() { assertNotNull(actual.getApplicant1LitigationFriend().getPartyID()); assertNotNull(actual.getRespondent1LitigationFriend().getPartyID()); assertNotNull(actual.getRespondent2LitigationFriend().getPartyID()); - assertNotNull(actual.getApplicantExperts().get(0).getValue().getPartyID()); - assertNotNull(actual.getRespondent1Experts().get(0).getValue().getPartyID()); - assertNotNull(actual.getRespondent2Experts().get(0).getValue().getPartyID()); - assertNotNull(actual.getApplicantWitnesses().get(0).getValue().getPartyID()); - assertNotNull(actual.getRespondent1Witnesses().get(0).getValue().getPartyID()); - assertNotNull(actual.getRespondent2Witnesses().get(0).getValue().getPartyID()); } @Test @@ -690,11 +691,7 @@ void shouldNotPopulateAlreadyNullPartyFields_withinCaseDataBuilder() { .applicant1(Party.builder().partyName("mock party 1").build()) .respondent1(Party.builder().partyName("mock party 4").build()) .applicant1LitigationFriend(LitigationFriend.builder().firstName("mock litfriend 1").build()) - .respondent1LitigationFriend(LitigationFriend.builder().firstName("mock litfriend 2").build()) - .applicantExperts(wrapElements(List.of(PartyFlagStructure.builder().firstName("expert 1").build()))) - .respondent1Experts(wrapElements(List.of(PartyFlagStructure.builder().firstName("expert 2").build()))) - .applicantWitnesses(wrapElements(List.of(PartyFlagStructure.builder().firstName("witness 1").build()))) - .respondent1Witnesses(wrapElements(List.of(PartyFlagStructure.builder().firstName("witness 2").build()))); + .respondent1LitigationFriend(LitigationFriend.builder().firstName("mock litfriend 2").build()); PartyUtils.populateWithPartyIds(builder); CaseData actual = builder.build(); @@ -702,8 +699,216 @@ void shouldNotPopulateAlreadyNullPartyFields_withinCaseDataBuilder() { assertNull(actual.getApplicant2()); assertNull(actual.getRespondent2()); assertNull(actual.getRespondent2LitigationFriend()); - assertNull(actual.getRespondent2Experts()); - assertNull(actual.getRespondent2Witnesses()); + } + } + + @Nested + class PopulateDQPartyIds { + + @Test + void shouldDQPopulatePartyIds_withinGivenCaseDataBuilder() { + CaseData.CaseDataBuilder builder = CaseData.builder() + .applicant1DQ(Applicant1DQ.builder() + .applicant1DQWitnesses(buildWitnesses("app1witness")) + .applicant1DQExperts(buildExperts("app1expert")) + .applicant1RespondToClaimExperts(buildExpertDetails("app1expertdetails")) + .build()) + .applicant2DQ(Applicant2DQ.builder() + .applicant2DQWitnesses(buildWitnesses("app2witness")) + .applicant2DQExperts(buildExperts("app2expert")) + .applicant2RespondToClaimExperts(buildExpertDetails("app2expertdetails")) + .build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQWitnesses(buildWitnesses("res1witness")) + .respondent1DQExperts(buildExperts("res1expert")) + .respondToClaimExperts(buildExpertDetails("res1expertdetails")) + .build()) + .respondent2DQ(Respondent2DQ.builder() + .respondent2DQWitnesses(buildWitnesses("res2witness")) + .respondent2DQExperts(buildExperts("res2expert")) + .respondToClaimExperts2(buildExpertDetails("res2expertdetails")) + .build()); + + PartyUtils.populateDQPartyIds(builder); + + CaseData actual = builder.build(); + + var app1Witness = unwrapElements(actual.getApplicant1DQ().getApplicant1DQWitnesses().getDetails()).get(0); + assertNotNull(app1Witness.getPartyID()); + assertEquals(app1Witness.getFirstName(), "app1witness"); + + var app2Witness = unwrapElements(actual.getApplicant2DQ().getApplicant2DQWitnesses().getDetails()).get(0); + assertNotNull(app2Witness.getPartyID()); + assertEquals(app2Witness.getFirstName(), "app2witness"); + + var res1Witness = unwrapElements(actual.getRespondent1DQ().getRespondent1DQWitnesses().getDetails()).get(0); + assertNotNull(res1Witness.getPartyID()); + assertEquals(res1Witness.getFirstName(), "res1witness"); + + var res2Witness = unwrapElements(actual.getRespondent2DQ().getRespondent2DQWitnesses().getDetails()).get(0); + assertNotNull(res2Witness.getPartyID()); + assertEquals(res2Witness.getFirstName(), "res2witness"); + + var app1Expert = unwrapElements(actual.getApplicant1DQ().getApplicant1DQExperts().getDetails()).get(0); + assertNotNull(app1Expert.getPartyID()); + assertEquals(app1Expert.getFirstName(), "app1expert"); + + var app1ExpertDetails = actual.getApplicant1DQ().getApplicant1RespondToClaimExperts(); + assertNotNull(app1ExpertDetails.getPartyID()); + assertEquals(app1ExpertDetails.getFirstName(), "app1expertdetails"); + + var app2Expert = unwrapElements(actual.getApplicant2DQ().getApplicant2DQExperts().getDetails()).get(0); + assertNotNull(app2Expert.getPartyID()); + assertEquals(app2Expert.getFirstName(), "app2expert"); + + var app2ExpertDetails = actual.getApplicant2DQ().getApplicant2RespondToClaimExperts(); + assertNotNull(app2ExpertDetails.getPartyID()); + assertEquals(app2ExpertDetails.getFirstName(), "app2expertdetails"); + + var res1Expert = unwrapElements(actual.getRespondent1DQ().getRespondent1DQExperts().getDetails()).get(0); + assertNotNull(res1Expert.getPartyID()); + assertEquals(res1Expert.getFirstName(), "res1expert"); + + var res1ExpertDetails = actual.getRespondent1DQ().getRespondToClaimExperts(); + assertNotNull(res1ExpertDetails.getPartyID()); + assertEquals(res1ExpertDetails.getFirstName(), "res1expertdetails"); + + var res2Expert = unwrapElements(actual.getRespondent2DQ().getRespondent2DQExperts().getDetails()).get(0); + assertNotNull(res2Expert.getPartyID()); + assertEquals(res2Expert.getFirstName(), "res2expert"); + + var res2ExpertDetails = actual.getRespondent2DQ().getRespondToClaimExperts2(); + assertNotNull(res2ExpertDetails.getPartyID()); + assertEquals(res2ExpertDetails.getFirstName(), "res2expertdetails"); + } + + @Test + void shouldNotOverWritePartyIds_whenPartyIdsExist() { + CaseData.CaseDataBuilder builder = CaseData.builder() + .applicant1DQ(Applicant1DQ.builder() + .applicant1DQWitnesses(buildWitnesses("app1witness", "app1witnesspartyid")) + .applicant1DQExperts(buildExperts("app1expert", "app1expertpartyid")) + .applicant1RespondToClaimExperts(buildExpertDetails("app1expertdetails", "app1expertdetailspartyid")) + .build()) + .applicant2DQ(Applicant2DQ.builder() + .applicant2DQWitnesses(buildWitnesses("app2witness", "app2witnesspartyid")) + .applicant2DQExperts(buildExperts("app2expert", "app2expertpartyid")) + .applicant2RespondToClaimExperts(buildExpertDetails("app2expertdetails", "app2expertdetailspartyid")) + .build()) + .respondent1DQ(Respondent1DQ.builder() + .respondent1DQWitnesses(buildWitnesses("res1witness", "res1witnesspartyid")) + .respondent1DQExperts(buildExperts("res1expert", "res1expertpartyid")) + .respondToClaimExperts(buildExpertDetails("res1expertdetails", "res1expertdetailspartyid")) + .build()) + .respondent2DQ(Respondent2DQ.builder() + .respondent2DQWitnesses(buildWitnesses("res2witness", "res2witnesspartyid")) + .respondent2DQExperts(buildExperts("res2expert", "res2expertpartyid")) + .respondToClaimExperts2(buildExpertDetails("res2expertdetails", "res2expertdetailspartyid")) + .build()); + + PartyUtils.populateDQPartyIds(builder); + + CaseData actual = builder.build(); + + var app1Witness = unwrapElements(actual.getApplicant1DQ().getApplicant1DQWitnesses().getDetails()).get(0); + assertEquals(app1Witness.getPartyID(), "app1witnesspartyid"); + + var app2Witness = unwrapElements(actual.getApplicant2DQ().getApplicant2DQWitnesses().getDetails()).get(0); + assertEquals(app2Witness.getPartyID(), "app2witnesspartyid"); + + var res1Witness = unwrapElements(actual.getRespondent1DQ().getRespondent1DQWitnesses().getDetails()).get(0); + assertEquals(res1Witness.getPartyID(), "res1witnesspartyid"); + + var res2Witness = unwrapElements(actual.getRespondent2DQ().getRespondent2DQWitnesses().getDetails()).get(0); + assertEquals(res2Witness.getPartyID(), "res2witnesspartyid"); + + var app1Expert = unwrapElements(actual.getApplicant1DQ().getApplicant1DQExperts().getDetails()).get(0); + assertEquals(app1Expert.getPartyID(), "app1expertpartyid"); + + var app1ExpertDetails = actual.getApplicant1DQ().getApplicant1RespondToClaimExperts(); + assertEquals(app1ExpertDetails.getPartyID(), "app1expertdetailspartyid"); + + var app2Expert = unwrapElements(actual.getApplicant2DQ().getApplicant2DQExperts().getDetails()).get(0); + assertEquals(app2Expert.getPartyID(), "app2expertpartyid"); + + var app2ExpertDetails = actual.getApplicant2DQ().getApplicant2RespondToClaimExperts(); + assertEquals(app2ExpertDetails.getPartyID(), "app2expertdetailspartyid"); + + var res1Expert = unwrapElements(actual.getRespondent1DQ().getRespondent1DQExperts().getDetails()).get(0); + assertEquals(res1Expert.getPartyID(), "res1expertpartyid"); + + var res1ExpertDetails = actual.getRespondent1DQ().getRespondToClaimExperts(); + assertEquals(res1ExpertDetails.getPartyID(), "res1expertdetailspartyid"); + + var res2Expert = unwrapElements(actual.getRespondent2DQ().getRespondent2DQExperts().getDetails()).get(0); + assertEquals(res2Expert.getPartyID(), "res2expertpartyid"); + + var res2ExpertDetails = actual.getRespondent2DQ().getRespondToClaimExperts2(); + assertEquals(res2ExpertDetails.getPartyID(), "res2expertdetailspartyid"); + } + + @Test + void shouldReturnNullWitnessExpertFields_whenCaseDataBuilderHasNullWitnessExpertFields() { + CaseData.CaseDataBuilder builder = CaseData.builder() + .applicant1DQ(Applicant1DQ.builder().build()) + .applicant2DQ(Applicant2DQ.builder().build()) + .respondent1DQ(Respondent1DQ.builder().build()) + .respondent2DQ(Respondent2DQ.builder().build()); + + PartyUtils.populateDQPartyIds(builder); + CaseData actual = builder.build(); + + assertNull(actual.getApplicant1DQ().getApplicant1DQWitnesses()); + assertNull(actual.getApplicant2DQ().getApplicant2DQWitnesses()); + assertNull(actual.getRespondent1DQ().getRespondent1DQWitnesses()); + assertNull(actual.getRespondent2DQ().getRespondent2DQWitnesses()); + assertNull(actual.getApplicant1DQ().getApplicant1DQExperts()); + assertNull(actual.getApplicant1DQ().getApplicant1RespondToClaimExperts()); + assertNull(actual.getApplicant2DQ().getApplicant2DQExperts()); + assertNull(actual.getApplicant2DQ().getApplicant2RespondToClaimExperts()); + assertNull(actual.getRespondent1DQ().getRespondent1DQExperts()); + assertNull(actual.getRespondent1DQ().getRespondToClaimExperts()); + assertNull(actual.getRespondent2DQ().getRespondent2DQExperts()); + assertNull(actual.getRespondent2DQ().getRespondToClaimExperts2()); + } + + @Test + void shouldReturnNullDQFields_whenCaseDataBuilderHasNullDQFields() { + CaseData.CaseDataBuilder builder = CaseData.builder(); + + PartyUtils.populateDQPartyIds(builder); + CaseData actual = builder.build(); + + assertNull(actual.getApplicant1DQ()); + assertNull(actual.getApplicant2DQ()); + assertNull(actual.getRespondent1DQ()); + assertNull(actual.getRespondent2DQ()); + } + + private Witnesses buildWitnesses(String firstName, String partyId) { + return Witnesses.builder().details( + wrapElements(List.of(Witness.builder().partyID(partyId).firstName(firstName).build()))).build(); + } + + private Witnesses buildWitnesses(String firstName) { + return buildWitnesses(firstName, null); + } + + private Experts buildExperts(String firstName, String partyId) { + return Experts.builder().details( + wrapElements(List.of(Expert.builder().partyID(partyId).firstName(firstName).build()))).build(); + } + + private Experts buildExperts(String firstName) { + return buildExperts(firstName, null); + } + + private ExpertDetails buildExpertDetails(String firstName, String partyId) { + return ExpertDetails.builder().partyID(partyId).firstName(firstName).build(); + } + + private ExpertDetails buildExpertDetails(String firstName) { + return buildExpertDetails(firstName, null); } } } diff --git a/src/test/java/uk/gov/hmcts/reform/civil/utils/PaymentFrequencyCalculatorTest.java b/src/test/java/uk/gov/hmcts/reform/civil/utils/PaymentFrequencyCalculatorTest.java new file mode 100644 index 00000000000..e5abb80c8fd --- /dev/null +++ b/src/test/java/uk/gov/hmcts/reform/civil/utils/PaymentFrequencyCalculatorTest.java @@ -0,0 +1,40 @@ +package uk.gov.hmcts.reform.civil.utils; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import uk.gov.hmcts.reform.civil.enums.PaymentFrequencyLRspec; + +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.gov.hmcts.reform.civil.enums.PaymentFrequencyLRspec.ONCE_FOUR_WEEKS; +import static uk.gov.hmcts.reform.civil.enums.PaymentFrequencyLRspec.ONCE_ONE_WEEK; +import static uk.gov.hmcts.reform.civil.enums.PaymentFrequencyLRspec.ONCE_THREE_WEEKS; +import static uk.gov.hmcts.reform.civil.enums.PaymentFrequencyLRspec.ONCE_TWO_WEEKS; +import static uk.gov.hmcts.reform.civil.utils.PaymentFrequencyCalculator.calculatePaymentPerMonth; + +class PaymentFrequencyCalculatorTest { + + private static double EXPECTED_RESULT = 433.0; + + static Stream shouldCalculatePaymentFrequencyPerMonth() { + return Stream.of( + Arguments.of(ONCE_ONE_WEEK, 100.0, EXPECTED_RESULT), + Arguments.of(ONCE_TWO_WEEKS, 200.0, EXPECTED_RESULT), + Arguments.of(ONCE_THREE_WEEKS, 300.0, EXPECTED_RESULT), + Arguments.of(ONCE_FOUR_WEEKS, 400.0, EXPECTED_RESULT) + ); + + } + + @ParameterizedTest + @MethodSource + void shouldCalculatePaymentFrequencyPerMonth(PaymentFrequencyLRspec paymentFrequency, double amount, double expectedResult) { + //When + double actualResult = calculatePaymentPerMonth(amount, paymentFrequency); + //Then + assertThat(actualResult).isEqualTo(expectedResult); + } + +} diff --git a/src/test/java/uk/gov/hmcts/reform/civil/utils/UnavailabilityDatesUtilsTest.java b/src/test/java/uk/gov/hmcts/reform/civil/utils/UnavailabilityDatesUtilsTest.java index 4ccf58e76d3..de76b679d10 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/utils/UnavailabilityDatesUtilsTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/utils/UnavailabilityDatesUtilsTest.java @@ -2,6 +2,7 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +import uk.gov.hmcts.reform.civil.enums.MultiPartyScenario; import uk.gov.hmcts.reform.civil.enums.dq.UnavailableDateType; import uk.gov.hmcts.reform.civil.model.CaseData; import uk.gov.hmcts.reform.civil.model.UnavailableDate; @@ -12,11 +13,14 @@ import uk.gov.hmcts.reform.civil.model.dq.Respondent2DQ; import uk.gov.hmcts.reform.civil.sampledata.CaseDataBuilder; import uk.gov.hmcts.reform.civil.sampledata.PartyBuilder; + import java.time.LocalDate; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; + import static java.time.LocalDate.now; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -25,6 +29,11 @@ import static uk.gov.hmcts.reform.civil.enums.dq.UnavailableDateType.SINGLE_DATE; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.unwrapElements; import static uk.gov.hmcts.reform.civil.utils.ElementUtils.wrapElements; +import static uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils.shouldUpdateApplicant1UnavailableDates; +import static uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils.shouldUpdateApplicant2UnavailableDates; +import static uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils.shouldUpdateRespondent1UnavailableDates; +import static uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils.shouldUpdateRespondent2UnavailableDates; +import static uk.gov.hmcts.reform.civil.utils.UnavailabilityDatesUtils.updateMissingUnavailableDatesForApplicants; public class UnavailabilityDatesUtilsTest { @@ -96,6 +105,64 @@ public void shouldReturnDateRangesWhenProvidedForApplicant1() { assertEquals(result.getFromDate(), expected.getFromDate()); } + @Test + public void shouldUpdateUnavailableDatesForRespondentWhenEnabled() { + // Przygotowanie danych testowych za pomocą metod respondent1DQWithUnavailableDateRange i respondent2DQWithUnavailableDateRange + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed(MultiPartyScenario.ONE_V_TWO_TWO_LEGAL_REP) + .respondent1DQWithUnavailableDateRange() + .respondent2DQWithUnavailableDateRange() + .respondent1ResponseDate(LocalDateTime.now()) + .build(); + CaseData.CaseDataBuilder builder = caseData.toBuilder(); + boolean updateContactDetailsEnabled = true; + + // Wywołanie metody do przetestowania + UnavailabilityDatesUtils.rollUpUnavailabilityDatesForRespondent(builder, updateContactDetailsEnabled); + + // Pobranie zaktualizowanych niedostępności dla Respondentów + List> updatedUnavailableDatesResp1 = + builder.build().getRespondent1().getUnavailableDates(); + List> updatedUnavailableDatesResp2 = + builder.build().getRespondent2().getUnavailableDates(); + + // Aserty dla Respondenta 1 + assertThat(updatedUnavailableDatesResp1) + .isNotNull() + .hasSize(1); + + UnavailableDate updatedDateResp1 = updatedUnavailableDatesResp1.get(0).getValue(); + + // Oczekiwane dane dla Respondenta 1 + UnavailableDate expectedDateResp1 = UnavailableDate.builder() + .fromDate(LocalDate.now().plusDays(1)) // Oczekiwana data rozpoczęcia + .toDate(LocalDate.now().plusDays(2)) // Oczekiwana data zakończenia + .unavailableDateType(UnavailableDateType.DATE_RANGE) // Ustawić odpowiedni typ + .build(); + + assertThat(updatedDateResp1.getFromDate()).isEqualTo(expectedDateResp1.getFromDate()); + assertThat(updatedDateResp1.getToDate()).isEqualTo(expectedDateResp1.getToDate()); + assertThat(updatedDateResp1.getUnavailableDateType()).isEqualTo(expectedDateResp1.getUnavailableDateType()); + + // Aserty dla Respondenta 2 + assertThat(updatedUnavailableDatesResp2) + .isNotNull() + .hasSize(1); + + UnavailableDate updatedDateResp2 = updatedUnavailableDatesResp2.get(0).getValue(); + + // Oczekiwane dane dla Respondenta 2 + UnavailableDate expectedDateResp2 = UnavailableDate.builder() + .fromDate(LocalDate.now().plusDays(1)) // Oczekiwana data rozpoczęcia + .toDate(LocalDate.now().plusDays(2)) // Oczekiwana data zakończenia + .unavailableDateType(UnavailableDateType.DATE_RANGE) // Ustawić odpowiedni typ + .build(); + + assertThat(updatedDateResp2.getFromDate()).isEqualTo(expectedDateResp2.getFromDate()); + assertThat(updatedDateResp2.getToDate()).isEqualTo(expectedDateResp2.getToDate()); + assertThat(updatedDateResp2.getUnavailableDateType()).isEqualTo(expectedDateResp2.getUnavailableDateType()); + } + @Test public void shouldReturnSingleUnavailabilityDateWhenProvidedForApplicant1() { CaseData caseData = CaseDataBuilder.builder() @@ -368,6 +435,200 @@ public void shouldReturnUnavailabilityDateWhenProvidedForApplicantDJ2v1() { assertThat(builder.build().getApplicant1().getUnavailableDates()).isEqualTo(expected); } + + @Test + public void shouldRollupUnavailableDatesForClaimant_whenEventIsClaimantResponse() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .applicant1DQWithUnavailableDate() + .build(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder(); + updateMissingUnavailableDatesForApplicants(caseData, builder, true); + UnavailableDate expected = UnavailableDate.builder() + .date(LocalDate.now().plusDays(1)) + .unavailableDateType(SINGLE_DATE) + .dateAdded(caseData.getApplicant1ResponseDate().toLocalDate()) + .eventAdded(CLAIMANT_INTENTION_EVENT) + .build(); + UnavailableDate result = unwrapElements(builder.build().getApplicant1().getUnavailableDates()).get(0); + assertEquals(expected.getDate(), result.getDate()); + assertEquals(expected.getUnavailableDateType(), result.getUnavailableDateType()); + } + + @Test + public void shouldRollupUnavailableDatesForClaimant_whenEventIsDefaultJudgement() { + CaseData caseData = CaseDataBuilder.builder() + .atStateClaimDetailsNotified() + .atStateClaimantRequestsDJWithUnavailableDates() + .build(); + + LocalDate dateAdded = LocalDate.now(); + + CaseData.CaseDataBuilder builder = caseData.toBuilder(); + updateMissingUnavailableDatesForApplicants(caseData, builder, true); + + UnavailableDate expectedSingleDate = UnavailableDate.builder() + .unavailableDateType(SINGLE_DATE) + .date(LocalDate.of(2023, 8, 20)) + .dateAdded(dateAdded) + .eventAdded(DJ_EVENT) + .build(); + + UnavailableDate expectedDateRange = UnavailableDate.builder() + .unavailableDateType(DATE_RANGE) + .fromDate(LocalDate.of(2023, 8, 20)) + .toDate(LocalDate.of(2023, 8, 22)) + .dateAdded(dateAdded) + .eventAdded(DJ_EVENT) + .build(); + + List> expected = wrapElements(List.of(expectedSingleDate, expectedDateRange)); + + assertThat(builder.build().getApplicant1().getUnavailableDates()).isEqualTo(expected); + } + + @Test + public void shouldReturnFalse_whenApplicant1HasNoMissingUnavailableDates() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .build(); + caseData = caseData.toBuilder().applicant1(caseData.getApplicant1().toBuilder() + .unavailableDates(wrapElements(List.of(UnavailableDate.builder() + .unavailableDateType(DATE_RANGE) + .fromDate(LocalDate.of(2023, 8, 20)) + .toDate(LocalDate.of(2023, 8, 22)) + .dateAdded(LocalDate.of(2023, 6, 22)) + .eventAdded(DJ_EVENT) + .build()))).build()).build(); + + boolean actual = shouldUpdateApplicant1UnavailableDates(caseData); + assertThat(actual).isFalse(); + } + + @Test + public void shouldReturnTrue_whenApplicant1HasMissingUnavailableDates() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .build(); + caseData = caseData.toBuilder().applicant1(caseData.getApplicant1().toBuilder() + .unavailableDates(wrapElements(List.of(UnavailableDate.builder() + .unavailableDateType(DATE_RANGE) + .fromDate(LocalDate.of(2023, 8, 20)) + .toDate(LocalDate.of(2023, 8, 22)) + .build()))).build()).build(); + + boolean actual = shouldUpdateApplicant1UnavailableDates(caseData); + assertThat(actual).isTrue(); + } + + @Test + public void shouldReturnFalse_whenApplicant2HasNoMissingUnavailableDates() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .multiPartyClaimTwoApplicants() + .addApplicant2() + .build(); + caseData = caseData.toBuilder().applicant2(caseData.getApplicant2().toBuilder() + .unavailableDates(wrapElements(List.of(UnavailableDate.builder() + .unavailableDateType(DATE_RANGE) + .fromDate(LocalDate.of(2023, 8, 20)) + .toDate(LocalDate.of(2023, 8, 22)) + .dateAdded(LocalDate.of(2023, 6, 22)) + .eventAdded(DJ_EVENT) + .build()))).build()).build(); + + boolean actual = shouldUpdateApplicant2UnavailableDates(caseData); + assertThat(actual).isFalse(); + } + + @Test + public void shouldReturnTrue_whenApplicant2HasMissingUnavailableDates() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .addApplicant2() + .multiPartyClaimTwoApplicants() + .build(); + caseData = caseData.toBuilder().applicant2(caseData.getApplicant2().toBuilder() + .unavailableDates(wrapElements(List.of(UnavailableDate.builder() + .unavailableDateType(DATE_RANGE) + .fromDate(LocalDate.of(2023, 8, 20)) + .toDate(LocalDate.of(2023, 8, 22)) + .build()))).build()).build(); + + boolean actual = shouldUpdateApplicant2UnavailableDates(caseData); + assertThat(actual).isTrue(); + } + + @Test + public void shouldReturnFalse_whenRespondent1HasNoMissingUnavailableDates() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .build(); + caseData = caseData.toBuilder().respondent1(caseData.getRespondent1().toBuilder() + .unavailableDates(wrapElements(List.of(UnavailableDate.builder() + .unavailableDateType(DATE_RANGE) + .fromDate(LocalDate.of(2023, 8, 20)) + .toDate(LocalDate.of(2023, 8, 22)) + .dateAdded(LocalDate.of(2023, 6, 22)) + .eventAdded(DEFENDANT_RESPONSE_EVENT) + .build()))).build()).build(); + + boolean actual = shouldUpdateRespondent1UnavailableDates(caseData); + assertThat(actual).isFalse(); + } + + @Test + public void shouldReturnTrue_whenRespondent1HasMissingUnavailableDates() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .build(); + caseData = caseData.toBuilder().respondent1(caseData.getRespondent1().toBuilder() + .unavailableDates(wrapElements(List.of(UnavailableDate.builder() + .unavailableDateType(DATE_RANGE) + .fromDate(LocalDate.of(2023, 8, 20)) + .toDate(LocalDate.of(2023, 8, 22)) + .build()))).build()).build(); + + boolean actual = shouldUpdateRespondent1UnavailableDates(caseData); + assertThat(actual).isTrue(); + } + + @Test + public void shouldReturnFalse_whenRespondent2HasNoMissingUnavailableDates() { + CaseData caseData = CaseDataBuilder.builder() + .multiPartyClaimTwoDefendantSolicitors() + .atStateApplicantRespondToDefenceAndProceed() + .build(); + caseData = caseData.toBuilder().respondent2(caseData.getRespondent1().toBuilder() + .unavailableDates(wrapElements(List.of(UnavailableDate.builder() + .unavailableDateType(DATE_RANGE) + .fromDate(LocalDate.of(2023, 8, 20)) + .toDate(LocalDate.of(2023, 8, 22)) + .dateAdded(LocalDate.of(2023, 6, 22)) + .eventAdded(DEFENDANT_RESPONSE_EVENT) + .build()))).build()).build(); + + boolean actual = shouldUpdateRespondent2UnavailableDates(caseData); + assertThat(actual).isFalse(); + } + + @Test + public void shouldReturnTrue_whenRespondent2HasMissingUnavailableDates() { + CaseData caseData = CaseDataBuilder.builder() + .atStateApplicantRespondToDefenceAndProceed() + .multiPartyClaimTwoDefendantSolicitors() + .build(); + caseData = caseData.toBuilder().respondent2(caseData.getRespondent2().toBuilder() + .unavailableDates(wrapElements(List.of(UnavailableDate.builder() + .unavailableDateType(DATE_RANGE) + .fromDate(LocalDate.of(2023, 8, 20)) + .toDate(LocalDate.of(2023, 8, 22)) + .build()))).build()).build(); + + boolean actual = shouldUpdateRespondent2UnavailableDates(caseData); + assertThat(actual).isTrue(); + } } @Nested diff --git a/src/test/java/uk/gov/hmcts/reform/civil/utils/UserRoleUtilsTest.java b/src/test/java/uk/gov/hmcts/reform/civil/utils/UserRoleUtilsTest.java index de3bd301659..23c56155f5a 100644 --- a/src/test/java/uk/gov/hmcts/reform/civil/utils/UserRoleUtilsTest.java +++ b/src/test/java/uk/gov/hmcts/reform/civil/utils/UserRoleUtilsTest.java @@ -7,12 +7,14 @@ import static org.assertj.core.api.Assertions.assertThat; import static uk.gov.hmcts.reform.civil.utils.UserRoleUtils.isApplicantSolicitor; +import static uk.gov.hmcts.reform.civil.utils.UserRoleUtils.isLIPClaimant; +import static uk.gov.hmcts.reform.civil.utils.UserRoleUtils.isLIPDefendant; import static uk.gov.hmcts.reform.civil.utils.UserRoleUtils.isRespondentSolicitorOne; import static uk.gov.hmcts.reform.civil.utils.UserRoleUtils.isRespondentSolicitorTwo; class UserRoleUtilsTest { - private final List roles = Arrays.asList("[APPLICANTSOLICITORONE]", "[RESPONDENTSOLICITORONE]", "[RESPONDENTSOLICITORTWO]"); + private final List roles = Arrays.asList("[APPLICANTSOLICITORONE]", "[RESPONDENTSOLICITORONE]", "[RESPONDENTSOLICITORTWO]", "[CLAIMANT]", "[DEFENDANT]"); private final List randomRoles = Arrays.asList("random role", "another role"); @Test @@ -44,4 +46,24 @@ void shouldReturnTrue_whenUserHasRespondentSolicitorTwoRole() { void shouldReturnFalse_whenUserHasRespondentSolicitorTwoRole() { assertThat(isRespondentSolicitorTwo(randomRoles)).isFalse(); } + + @Test + void shouldReturnTrue_whenUserHasClaimantRole() { + assertThat(isLIPClaimant(roles)).isTrue(); + } + + @Test + void shouldReturnFalse_whenUserHasNotClaimantRole() { + assertThat(isLIPClaimant(randomRoles)).isFalse(); + } + + @Test + void shouldReturnTrue_whenUserHasDefendantRole() { + assertThat(isLIPDefendant(roles)).isTrue(); + } + + @Test + void shouldReturnFalse_whenUserHasNotDefendantRole() { + assertThat(isLIPDefendant(randomRoles)).isFalse(); + } } diff --git a/src/test/java/uk/gov/hmcts/reform/fees/client/FeeClientTest.java b/src/test/java/uk/gov/hmcts/reform/fees/client/FeeClientTest.java index c1a1c692ff2..6614da86721 100644 --- a/src/test/java/uk/gov/hmcts/reform/fees/client/FeeClientTest.java +++ b/src/test/java/uk/gov/hmcts/reform/fees/client/FeeClientTest.java @@ -4,7 +4,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.mockito.junit.jupiter.MockitoExtension; import uk.gov.hmcts.reform.civil.config.FeesConfiguration; import uk.gov.hmcts.reform.civil.service.FeatureToggleService; import uk.gov.hmcts.reform.fees.client.model.FeeLookupResponseDto; @@ -16,13 +16,17 @@ import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static uk.gov.hmcts.reform.fees.client.FeesClient.EVENT_HEARING; +import static uk.gov.hmcts.reform.fees.client.FeesClient.EVENT_ISSUE; +import static uk.gov.hmcts.reform.fees.client.FeesClient.FAST_TRACK_HEARING; +import static uk.gov.hmcts.reform.fees.client.FeesClient.HEARING_SMALL_CLAIMS; +import static uk.gov.hmcts.reform.fees.client.FeesClient.MONEY_CLAIM; -@ExtendWith(SpringExtension.class) +@ExtendWith(MockitoExtension.class) class FeeClientTest { private static final String CHANNEL = "channel"; - private static final String EVENT = "event"; - private static final String HEARING_EVENT = "hearingEvent"; + private static final BigDecimal TEST_FEE_AMOUNT_POUNDS = new BigDecimal("1.00"); @Mock private FeesApi feesApi; @@ -34,10 +38,14 @@ class FeeClientTest { @BeforeEach void setUp() { - given(feesConfiguration.getChannel()).willReturn(CHANNEL); - given(feesConfiguration.getEvent()).willReturn(EVENT); - given(feesConfiguration.getHearingEvent()).willReturn(HEARING_EVENT); - feesClient = new FeesClient(feesApi, featureToggleService, "civil", "jurisdiction1", "jurisdiction2"); + feesClient = new FeesClient( + feesApi, + featureToggleService, + "civil", + "jurisdiction1", + "jurisdiction2", + "jurisdictionFastTrackClaim" + ); } @Test @@ -56,15 +64,15 @@ void shouldReturnFeeData_whenValidClaimValueWhenFeatureIsEnabled() { .version(1) .build(); - FeeLookupResponseDto feeLookupResponseDto = feesClient.lookupFee(CHANNEL, EVENT, new BigDecimal("50.00")); + FeeLookupResponseDto feeLookupResponseDto = feesClient.lookupFee(CHANNEL, EVENT_ISSUE, new BigDecimal("50.00")); verify(feesApi).lookupFee( "civil", "jurisdiction1", "jurisdiction2", CHANNEL, - EVENT, - "HearingSmallClaims", + EVENT_ISSUE, + MONEY_CLAIM, new BigDecimal("50.00") ); assertThat(feeLookupResponseDto).isEqualTo(expectedFeeDtoFeeLookupResponseDto); @@ -86,17 +94,70 @@ void shouldReturnFeeData_whenValidClaimValueWhenFeatureIsNotEnabled() { .version(1) .build(); - FeeLookupResponseDto feeLookupResponseDto = feesClient.lookupFee(CHANNEL, EVENT, new BigDecimal("50.00")); + FeeLookupResponseDto feeLookupResponseDto = feesClient.lookupFee(CHANNEL, EVENT_ISSUE, new BigDecimal("50.00")); verify(feesApi).lookupFeeWithoutKeyword( "civil", "jurisdiction1", "jurisdiction2", CHANNEL, - EVENT, + EVENT_ISSUE, new BigDecimal("50.00") ); assertThat(feeLookupResponseDto).isEqualTo(expectedFeeDtoFeeLookupResponseDto); } + @Test + void shouldCallLookupFeeWhenFastTrackClaimWithHearingEventAndLipVLipFeatureEnabled() { + when(featureToggleService.isFeatureEnabled("fee-keywords-enable")).thenReturn(true); + when(featureToggleService.isLipVLipEnabled()).thenReturn(true); + + given(feesApi.lookupFee(any(), any(), any(), any(), any(), any(), any())) + .willReturn(FeeLookupResponseDto.builder() + .feeAmount(TEST_FEE_AMOUNT_POUNDS) + .code("test_fee_code") + .version(1) + .build()); + + FeeLookupResponseDto feeLookupResponseDto = feesClient.lookupFee( + CHANNEL, + EVENT_HEARING, + new BigDecimal("10001.00") + ); + + verify(feesApi).lookupFee( + "civil", + "jurisdiction1", + "jurisdictionFastTrackClaim", + CHANNEL, + EVENT_HEARING, + FAST_TRACK_HEARING, + new BigDecimal("10001.00") + ); + + } + + @Test + void shouldCallLookupFeeWithKeyWordHearingSmallClaimsWhenEventIsNotIssue() { + when(featureToggleService.isFeatureEnabled("fee-keywords-enable")).thenReturn(true); + given(feesApi.lookupFee(any(), any(), any(), any(), any(), any(), any())) + .willReturn(FeeLookupResponseDto.builder() + .feeAmount(TEST_FEE_AMOUNT_POUNDS) + .code("test_fee_code") + .version(1) + .build()); + + FeeLookupResponseDto feeLookupResponseDto = feesClient.lookupFee(CHANNEL, "EventOtherThanIssueOrHearing", new BigDecimal("50.00")); + + verify(feesApi).lookupFee( + "civil", + "jurisdiction1", + "jurisdiction2", + CHANNEL, + "EventOtherThanIssueOrHearing", + HEARING_SMALL_CLAIMS, + new BigDecimal("50.00") + ); + + } }