From b187b6644dea2a39ac084477706627224d4aaff9 Mon Sep 17 00:00:00 2001
From: Phil Payne
Date: Wed, 10 Jan 2024 11:16:15 +0000
Subject: [PATCH] feature/ccls-1974_proceedings_and_costs
* CCLS-1976
* CCLS-1977
* CCLS-1978
* CCLS-1979
* CCLS-1980
* CCLS-1981
* CCLS-1982
* CCLS-1983
* CCLS-1984
* CCLS-1985
* CCLS-1986
* CCLS-1987
* CCLS-1988
* CCLS-1989
---
.github/workflows/on-tag.yml | 2 +-
.github/workflows/pr-merge-main.yml | 2 +-
.github/workflows/push-branch.yml | 2 +-
caab-api/open-api-specification.yml | 516 +++++++++++++-
caab-service/build.gradle | 10 +-
.../data/api/AbstractIntegrationTest.java | 29 -
.../data/api/IntegrationTestInterface.java | 24 +
.../data/api/OracleContainerSingleton.java | 26 +
...icationControllerIntegrationLocalTest.java | 23 +
.../ApplicationControllerIntegrationTest.java | 378 +---------
...eApplicationControllerIntegrationTest.java | 660 ++++++++++++++++++
...pplicationServiceIntegrationLocalTest.java | 24 +
.../ApplicationServiceIntegrationTest.java | 506 +-------------
...BaseApplicationServiceIntegrationTest.java | 500 +++++++++++++
.../resources/json/base_client_new.json | 4 +
.../resources/json/linked_cases_new.json | 13 +
.../resources/json/prior_authority_new.json | 14 +
.../resources/json/proceeding_new.json | 61 ++
.../resources/json/scope_limitation_new.json | 15 +
.../resources/sql/cost_structure_insert.sql | 0
.../resources/sql/delete_data.sql | 24 +
.../resources/sql/linked_cases_insert.sql | 3 +
.../resources/sql/prior_authority_insert.sql | 3 +
.../resources/sql/proceeding_insert.sql | 3 +
.../resources/sql/scope_limitation_insert.sql | 3 +
.../api/controller/ApplicationController.java | 175 ++++-
.../laa/ccms/caab/api/entity/Application.java | 6 +-
.../ccms/caab/api/entity/PriorAuthority.java | 3 +
.../caab/api/mapper/ApplicationMapper.java | 61 +-
.../api/repository/ApplicationRepository.java | 16 +-
.../api/repository/LinkedCaseRepository.java | 17 +
.../repository/PriorAuthorityRepository.java | 18 +
.../api/repository/ProceedingRepository.java | 18 +
.../repository/ScopeLimitationRepository.java | 18 +
.../caab/api/service/ApplicationService.java | 160 ++++-
.../caab/api/service/LinkedCaseService.java | 70 ++
.../api/service/PriorAuthorityService.java | 70 ++
.../caab/api/service/ProceedingService.java | 122 ++++
.../api/service/ScopeLimitationService.java | 70 ++
.../controller/ApplicationControllerTest.java | 290 +++++++-
.../api/mapper/ApplicationMapperTest.java | 87 +++
.../api/service/ApplicationServiceTest.java | 232 ++++--
.../api/service/LinkedCaseServiceTest.java | 95 +++
.../service/PriorAuthorityServiceTest.java | 89 +++
.../api/service/ProceedingServiceTest.java | 158 +++++
.../service/ScopeLimitationServiceTest.java | 84 +++
46 files changed, 3623 insertions(+), 1081 deletions(-)
delete mode 100644 caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/AbstractIntegrationTest.java
create mode 100644 caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/IntegrationTestInterface.java
create mode 100644 caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/OracleContainerSingleton.java
create mode 100644 caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/controller/ApplicationControllerIntegrationLocalTest.java
create mode 100644 caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/controller/BaseApplicationControllerIntegrationTest.java
create mode 100644 caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/service/ApplicationServiceIntegrationLocalTest.java
create mode 100644 caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/service/BaseApplicationServiceIntegrationTest.java
create mode 100644 caab-service/src/integrationTest/resources/json/base_client_new.json
create mode 100644 caab-service/src/integrationTest/resources/json/linked_cases_new.json
create mode 100644 caab-service/src/integrationTest/resources/json/prior_authority_new.json
create mode 100644 caab-service/src/integrationTest/resources/json/proceeding_new.json
create mode 100644 caab-service/src/integrationTest/resources/json/scope_limitation_new.json
create mode 100644 caab-service/src/integrationTest/resources/sql/cost_structure_insert.sql
create mode 100644 caab-service/src/integrationTest/resources/sql/delete_data.sql
create mode 100644 caab-service/src/integrationTest/resources/sql/linked_cases_insert.sql
create mode 100644 caab-service/src/integrationTest/resources/sql/prior_authority_insert.sql
create mode 100644 caab-service/src/integrationTest/resources/sql/proceeding_insert.sql
create mode 100644 caab-service/src/integrationTest/resources/sql/scope_limitation_insert.sql
create mode 100644 caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/LinkedCaseRepository.java
create mode 100644 caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/PriorAuthorityRepository.java
create mode 100644 caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/ProceedingRepository.java
create mode 100644 caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/ScopeLimitationRepository.java
create mode 100644 caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/LinkedCaseService.java
create mode 100644 caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/PriorAuthorityService.java
create mode 100644 caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/ProceedingService.java
create mode 100644 caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/ScopeLimitationService.java
create mode 100644 caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/LinkedCaseServiceTest.java
create mode 100644 caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/PriorAuthorityServiceTest.java
create mode 100644 caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/ProceedingServiceTest.java
create mode 100644 caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/ScopeLimitationServiceTest.java
diff --git a/.github/workflows/on-tag.yml b/.github/workflows/on-tag.yml
index 3ecf951..2f85eca 100644
--- a/.github/workflows/on-tag.yml
+++ b/.github/workflows/on-tag.yml
@@ -53,7 +53,7 @@ jobs:
- name: Integration Test
uses: gradle/gradle-build-action@749f47bda3e44aa060e82d7b3ef7e40d953bd629
with:
- arguments: integrationTest
+ arguments: integrationTest -tests '*IntegrationTest'
- name: Capture version
shell: bash
diff --git a/.github/workflows/pr-merge-main.yml b/.github/workflows/pr-merge-main.yml
index f0d7ec8..9bb11c5 100644
--- a/.github/workflows/pr-merge-main.yml
+++ b/.github/workflows/pr-merge-main.yml
@@ -44,7 +44,7 @@ jobs:
- name: Integration Test
uses: gradle/gradle-build-action@749f47bda3e44aa060e82d7b3ef7e40d953bd629
with:
- arguments: integrationTest
+ arguments: integrationTest -tests '*IntegrationTest'
- name: Set to github user
run: |
diff --git a/.github/workflows/push-branch.yml b/.github/workflows/push-branch.yml
index 94527b8..f53e741 100644
--- a/.github/workflows/push-branch.yml
+++ b/.github/workflows/push-branch.yml
@@ -39,7 +39,7 @@ jobs:
- name: Integration Test
uses: gradle/gradle-build-action@749f47bda3e44aa060e82d7b3ef7e40d953bd629
with:
- arguments: integrationTest
+ arguments: integrationTest -tests '*IntegrationTest'
- name: Update snapshot version
uses: gradle/gradle-build-action@749f47bda3e44aa060e82d7b3ef7e40d953bd629
diff --git a/caab-api/open-api-specification.yml b/caab-api/open-api-specification.yml
index 816e67b..5280700 100644
--- a/caab-api/open-api-specification.yml
+++ b/caab-api/open-api-specification.yml
@@ -61,7 +61,6 @@ paths:
description: 'Not found'
'500':
description: 'Internal server error'
-
post:
tags:
- applications
@@ -120,6 +119,42 @@ paths:
description: 'Not found'
'500':
description: 'Internal server error'
+ /applications/clients/{client-reference-id}:
+ patch:
+ tags:
+ - clients
+ summary: 'Update a client for all applications with matching client reference id'
+ operationId: 'updateApplicationClient'
+ requestBody:
+ description: Update client
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/baseClient'
+ parameters:
+ - name: 'client-reference-id'
+ in: 'path'
+ required: true
+ schema:
+ type: 'string'
+ example: '1234567890'
+ - name: 'Caab-User-Login-Id'
+ in: header
+ required: true
+ schema:
+ type: 'string'
+ example: ''
+ responses:
+ '204':
+ description: 'No Content'
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
/applications/{id}/application-type:
get:
tags:
@@ -315,10 +350,74 @@ paths:
description: 'Not found'
'500':
description: 'Internal server error'
- /applications/{id}/linked-cases:
+ /applications/{id}/cost-structure:
get:
tags:
- applications
+ summary: 'Get an application''s prior authorities'
+ operationId: 'getApplicationCostStructure'
+ parameters:
+ - name: 'id'
+ in: 'path'
+ required: true
+ schema:
+ type: 'integer'
+ format: 'int64'
+ example: '1234567890'
+ responses:
+ '200':
+ description: 'Successful operation'
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/costStructure"
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
+ put:
+ tags:
+ - applications
+ summary: 'Update an applications cost structure'
+ operationId: 'updateApplicationCostStructure'
+ parameters:
+ - name: 'id'
+ in: 'path'
+ required: true
+ schema:
+ type: 'integer'
+ format: 'int64'
+ - name: 'Caab-User-Login-Id'
+ in: header
+ required: true
+ schema:
+ type: 'string'
+ example: 'SOMEUSER@COMPANY.CO.UK'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/costStructure"
+ responses:
+ '200':
+ description: 'Case updated successfully'
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
+ /applications/{id}/linked-cases:
+ get:
+ tags:
+ - linked cases
summary: 'Get an application''s linked cases'
operationId: 'getApplicationLinkedCases'
parameters:
@@ -348,7 +447,7 @@ paths:
description: 'Internal server error'
post:
tags:
- - applications
+ - linked cases
summary: 'Add a linked case to an application'
operationId: 'addApplicationLinkedCase'
parameters:
@@ -381,19 +480,42 @@ paths:
description: 'Not found'
'500':
description: 'Internal server error'
- /applications/{id}/linked-cases/{linked-case-id}:
+ /linked-cases/{linked-case-id}:
delete:
tags:
- - applications
+ - linked cases
summary: 'Remove a linked case from an application'
operationId: 'removeApplicationLinkedCase'
parameters:
- - name: 'id'
+ - name: 'linked-case-id'
in: 'path'
required: true
schema:
type: 'integer'
format: 'int64'
+ - name: 'Caab-User-Login-Id'
+ in: header
+ required: true
+ schema:
+ type: 'string'
+ example: 'SOMEUSER@COMPANY.CO.UK'
+ responses:
+ '204':
+ description: 'No Content'
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
+ patch:
+ tags:
+ - linked cases
+ summary: 'Update a linked case of an application'
+ operationId: 'updateApplicationLinkedCase'
+ parameters:
- name: 'linked-case-id'
in: 'path'
required: true
@@ -406,6 +528,108 @@ paths:
schema:
type: 'string'
example: 'SOMEUSER@COMPANY.CO.UK'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/linkedCase"
+ responses:
+ '200':
+ description: 'Case updated successfully'
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
+ /applications/{id}/proceedings:
+ get:
+ tags:
+ - proceedings
+ summary: 'Get an application''s proceedings'
+ operationId: 'getApplicationProceedings'
+ parameters:
+ - name: 'id'
+ in: 'path'
+ required: true
+ schema:
+ type: 'integer'
+ format: 'int64'
+ example: '1234567890'
+ responses:
+ '200':
+ description: 'Successful operation'
+ content:
+ application/json:
+ schema:
+ type: 'array'
+ items:
+ $ref: "#/components/schemas/proceeding"
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
+ post:
+ tags:
+ - proceedings
+ summary: 'Add a proceeding to an application'
+ operationId: 'addApplicationProceeding'
+ parameters:
+ - name: 'id'
+ in: 'path'
+ required: true
+ schema:
+ type: 'integer'
+ format: 'int64'
+ - name: 'Caab-User-Login-Id'
+ in: header
+ required: true
+ schema:
+ type: 'string'
+ example: 'SOMEUSER@COMPANY.CO.UK'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/proceeding"
+ responses:
+ '201':
+ description: 'Case added successfully'
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
+ /proceedings/{proceeding-id}:
+ delete:
+ tags:
+ - proceedings
+ summary: 'Remove a proceeding'
+ operationId: 'removeProceeding'
+ parameters:
+ - name: 'proceeding-id'
+ in: 'path'
+ required: true
+ schema:
+ type: 'integer'
+ format: 'int64'
+ - name: 'Caab-User-Login-Id'
+ in: header
+ required: true
+ schema:
+ type: 'string'
+ example: 'SOMEUSER@COMPANY.CO.UK'
responses:
'204':
description: 'No Content'
@@ -419,9 +643,176 @@ paths:
description: 'Internal server error'
patch:
tags:
- - applications
- summary: 'Update a linked case of an application'
- operationId: 'updateApplicationLinkedCase'
+ - proceedings
+ summary: 'Update a proceeding'
+ operationId: 'updateProceeding'
+ parameters:
+ - name: 'proceeding-id'
+ in: 'path'
+ required: true
+ schema:
+ type: 'integer'
+ format: 'int64'
+ - name: 'Caab-User-Login-Id'
+ in: header
+ required: true
+ schema:
+ type: 'string'
+ example: 'SOMEUSER@COMPANY.CO.UK'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/proceeding"
+ responses:
+ '200':
+ description: 'Case updated successfully'
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
+ /proceedings/{proceeding-id}/scope-limitations:
+ get:
+ tags:
+ - scope limitations
+ summary: 'Get a proceedings''s scope limitations'
+ operationId: 'getApplicationScopeLimitations'
+ parameters:
+ - name: 'proceeding-id'
+ in: 'path'
+ required: true
+ schema:
+ type: 'integer'
+ format: 'int64'
+ example: '1234567890'
+ responses:
+ '200':
+ description: 'Successful operation'
+ content:
+ application/json:
+ schema:
+ type: 'array'
+ items:
+ $ref: "#/components/schemas/scopeLimitation"
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
+ post:
+ tags:
+ - scope limitations
+ summary: 'Add a scope limitations to an proceeding'
+ operationId: 'addProceedingScopeLimitation'
+ parameters:
+ - name: 'proceeding-id'
+ in: 'path'
+ required: true
+ schema:
+ type: 'integer'
+ format: 'int64'
+ - name: 'Caab-User-Login-Id'
+ in: header
+ required: true
+ schema:
+ type: 'string'
+ example: 'SOMEUSER@COMPANY.CO.UK'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/scopeLimitation"
+ responses:
+ '201':
+ description: 'Case added successfully'
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
+ /scope-limitations/{scope-limitation-id}:
+ delete:
+ tags:
+ - scope limitations
+ summary: 'Remove a scope limitations'
+ operationId: 'removeScopeLimitation'
+ parameters:
+ - name: 'scope-limitation-id'
+ in: 'path'
+ required: true
+ schema:
+ type: 'integer'
+ format: 'int64'
+ - name: 'Caab-User-Login-Id'
+ in: header
+ required: true
+ schema:
+ type: 'string'
+ example: 'SOMEUSER@COMPANY.CO.UK'
+ responses:
+ '204':
+ description: 'No Content'
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
+ patch:
+ tags:
+ - scope limitations
+ summary: 'Update a scope limitation'
+ operationId: 'updateScopeLimitation'
+ parameters:
+ - name: 'scope-limitation-id'
+ in: 'path'
+ required: true
+ schema:
+ type: 'integer'
+ format: 'int64'
+ - name: 'Caab-User-Login-Id'
+ in: header
+ required: true
+ schema:
+ type: 'string'
+ example: 'SOMEUSER@COMPANY.CO.UK'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/scopeLimitation"
+ responses:
+ '200':
+ description: 'Case updated successfully'
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
+ /applications/{id}/prior-authorities:
+ get:
+ tags:
+ - prior authorities
+ summary: 'Get an application''s prior authorities'
+ operationId: 'getApplicationPriorAuthorities'
parameters:
- name: 'id'
in: 'path'
@@ -429,7 +820,31 @@ paths:
schema:
type: 'integer'
format: 'int64'
- - name: 'linked-case-id'
+ example: '1234567890'
+ responses:
+ '200':
+ description: 'Successful operation'
+ content:
+ application/json:
+ schema:
+ type: 'array'
+ items:
+ $ref: "#/components/schemas/priorAuthority"
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
+ post:
+ tags:
+ - prior authorities
+ summary: 'Add a prior authority to an application'
+ operationId: 'addApplicationPriorAuthority'
+ parameters:
+ - name: 'id'
in: 'path'
required: true
schema:
@@ -446,7 +861,72 @@ paths:
content:
application/json:
schema:
- $ref: "#/components/schemas/linkedCase"
+ $ref: "#/components/schemas/priorAuthority"
+ responses:
+ '201':
+ description: 'Case added successfully'
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
+ /prior-authorities/{prior-authority-id}:
+ delete:
+ tags:
+ - prior authorities
+ summary: 'Remove a prior authority'
+ operationId: 'removePriorAuthority'
+ parameters:
+ - name: 'prior-authority-id'
+ in: 'path'
+ required: true
+ schema:
+ type: 'integer'
+ format: 'int64'
+ - name: 'Caab-User-Login-Id'
+ in: header
+ required: true
+ schema:
+ type: 'string'
+ example: 'SOMEUSER@COMPANY.CO.UK'
+ responses:
+ '204':
+ description: 'No Content'
+ '400':
+ description: 'Bad request'
+ '401':
+ description: 'Unauthorized'
+ '404':
+ description: 'Not found'
+ '500':
+ description: 'Internal server error'
+ patch:
+ tags:
+ - prior authorities
+ summary: 'Update a prior authority'
+ operationId: 'updatePriorAuthority'
+ parameters:
+ - name: 'prior-authority-id'
+ in: 'path'
+ required: true
+ schema:
+ type: 'integer'
+ format: 'int64'
+ - name: 'Caab-User-Login-Id'
+ in: header
+ required: true
+ schema:
+ type: 'string'
+ example: 'SOMEUSER@COMPANY.CO.UK'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/priorAuthority"
responses:
'200':
description: 'Case updated successfully'
@@ -458,6 +938,7 @@ paths:
description: 'Not found'
'500':
description: 'Internal server error'
+
components:
schemas:
intDisplayValue:
@@ -527,13 +1008,18 @@ components:
type: 'boolean'
audit_trail:
$ref: "#/components/schemas/auditDetail"
- client:
+ baseClient:
type: 'object'
properties:
first_name:
type: 'string'
surname:
type: 'string'
+ client:
+ allOf:
+ - $ref: "#/components/schemas/baseClient"
+ type: 'object'
+ properties:
reference:
type: 'string'
required:
@@ -583,6 +1069,8 @@ components:
scopeLimitation:
type: 'object'
properties:
+ id:
+ type: 'integer'
scope_limitation:
$ref: "#/components/schemas/stringDisplayValue"
ebs_id:
@@ -639,6 +1127,8 @@ components:
proceeding:
type: 'object'
properties:
+ id:
+ type: 'integer'
ebs_id:
type: 'string'
matter_type:
@@ -723,6 +1213,8 @@ components:
priorAuthority:
type: 'object'
properties:
+ id:
+ type: 'integer'
ebs_id:
type: 'string'
status:
diff --git a/caab-service/build.gradle b/caab-service/build.gradle
index 5f69a36..f226f65 100644
--- a/caab-service/build.gradle
+++ b/caab-service/build.gradle
@@ -68,7 +68,10 @@ jacocoTestReport {
sourceDirectories.from files('build/generated/sources/annotationProcessor/java/main')
afterEvaluate {
classDirectories.setFrom(files(classDirectories.files.collect {
- fileTree(dir: it, exclude: ['**/CaabApiApplication.class'])
+ fileTree(dir: it, exclude: [
+ '**/CaabApiApplication.class',
+ '**/ApplicationConfig.class',
+ '**/AuditorAwareImpl.class'])
}))
}
@@ -79,7 +82,10 @@ jacocoTestCoverageVerification {
afterEvaluate {
classDirectories.setFrom(files(classDirectories.files.collect {
- fileTree(dir: it, exclude: ['**/CaabApiApplication.class'])
+ fileTree(dir: it, exclude: [
+ '**/CaabApiApplication.class',
+ '**/ApplicationConfig.class',
+ '**/AuditorAwareImpl.class'])
}))
}
diff --git a/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/AbstractIntegrationTest.java b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/AbstractIntegrationTest.java
deleted file mode 100644
index 5457fe8..0000000
--- a/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/AbstractIntegrationTest.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package uk.gov.laa.ccms.data.api;
-
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.DynamicPropertyRegistry;
-import org.springframework.test.context.DynamicPropertySource;
-import org.testcontainers.containers.OracleContainer;
-import org.testcontainers.junit.jupiter.Testcontainers;
-
-@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
-@Testcontainers
-@DirtiesContext
-public class AbstractIntegrationTest {
- public static OracleContainer oracleDB;
-
- static {
- oracleDB = new OracleContainer("gvenzl/oracle-xe:21-slim-faststart");
- oracleDB.start();
- }
-
- @DynamicPropertySource
- public static void properties(DynamicPropertyRegistry registry) {
- registry.add("spring.datasource.url",oracleDB::getJdbcUrl);
- registry.add("spring.datasource.username", oracleDB::getUsername);
- registry.add("spring.datasource.password", oracleDB::getPassword);
- }
-
-}
\ No newline at end of file
diff --git a/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/IntegrationTestInterface.java b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/IntegrationTestInterface.java
new file mode 100644
index 0000000..dae9a1b
--- /dev/null
+++ b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/IntegrationTestInterface.java
@@ -0,0 +1,24 @@
+package uk.gov.laa.ccms.data.api;
+
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.DynamicPropertyRegistry;
+import org.springframework.test.context.DynamicPropertySource;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+@Testcontainers
+@DirtiesContext
+public interface IntegrationTestInterface {
+
+ OracleContainerSingleton oracleContainerSingleton = OracleContainerSingleton.getInstance();
+
+ @DynamicPropertySource
+ static void properties(DynamicPropertyRegistry registry) {
+ registry.add("spring.datasource.url", oracleContainerSingleton.getOracleContainer()::getJdbcUrl);
+ registry.add("spring.datasource.username", oracleContainerSingleton.getOracleContainer()::getUsername);
+ registry.add("spring.datasource.password", oracleContainerSingleton.getOracleContainer()::getPassword);
+ }
+}
+
diff --git a/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/OracleContainerSingleton.java b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/OracleContainerSingleton.java
new file mode 100644
index 0000000..d63bdbe
--- /dev/null
+++ b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/OracleContainerSingleton.java
@@ -0,0 +1,26 @@
+package uk.gov.laa.ccms.data.api;
+
+import org.testcontainers.containers.OracleContainer;
+
+public class OracleContainerSingleton {
+
+ private static OracleContainerSingleton instance;
+ private final OracleContainer oracleContainer;
+
+ private OracleContainerSingleton() {
+ oracleContainer = new OracleContainer("gvenzl/oracle-xe:21-slim-faststart");
+ oracleContainer.start();
+ }
+
+ public static synchronized OracleContainerSingleton getInstance() {
+ if (instance == null) {
+ instance = new OracleContainerSingleton();
+ }
+ return instance;
+ }
+
+ public OracleContainer getOracleContainer() {
+ return oracleContainer;
+ }
+}
+
diff --git a/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/controller/ApplicationControllerIntegrationLocalTest.java b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/controller/ApplicationControllerIntegrationLocalTest.java
new file mode 100644
index 0000000..237f1ff
--- /dev/null
+++ b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/controller/ApplicationControllerIntegrationLocalTest.java
@@ -0,0 +1,23 @@
+package uk.gov.laa.ccms.data.api.controller;
+
+import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD;
+import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.BEFORE_TEST_METHOD;
+import static org.springframework.test.context.jdbc.SqlMergeMode.MergeMode.MERGE;
+
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.jdbc.Sql;
+import org.springframework.test.context.jdbc.SqlMergeMode;
+import uk.gov.laa.ccms.caab.api.CaabApiApplication;
+
+@SpringBootTest(classes = CaabApiApplication.class)
+@SqlMergeMode(MERGE)
+@ActiveProfiles("local")
+@Sql(executionPhase = AFTER_TEST_METHOD, scripts = "/sql/delete_data.sql")
+@Sql(executionPhase = BEFORE_TEST_METHOD, scripts = "/sql/delete_data.sql")
+public class ApplicationControllerIntegrationLocalTest extends BaseApplicationControllerIntegrationTest {
+
+ //this runs all tests in BaseApplicationControllerIntegrationTest, do not add anything here
+ //this is an easy way to run the tests if you have the containerised database running locally already
+
+}
diff --git a/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/controller/ApplicationControllerIntegrationTest.java b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/controller/ApplicationControllerIntegrationTest.java
index 892b671..0e8707a 100644
--- a/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/controller/ApplicationControllerIntegrationTest.java
+++ b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/controller/ApplicationControllerIntegrationTest.java
@@ -1,391 +1,23 @@
package uk.gov.laa.ccms.data.api.controller;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD;
import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.BEFORE_TEST_METHOD;
import static org.springframework.test.context.jdbc.SqlMergeMode.MergeMode.MERGE;
-import static uk.gov.laa.ccms.caab.api.audit.AuditorAwareImpl.currentUserHolder;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.URI;
-import java.util.List;
-import java.util.Random;
-import java.util.stream.Stream;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-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.test.context.SpringBootTest;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.data.domain.Pageable;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlMergeMode;
import uk.gov.laa.ccms.caab.api.CaabApiApplication;
-import uk.gov.laa.ccms.caab.api.controller.ApplicationController;
-import uk.gov.laa.ccms.caab.api.entity.AuditTrail;
-import uk.gov.laa.ccms.caab.api.service.ApplicationService;
-import uk.gov.laa.ccms.caab.model.ApplicationDetail;
-import uk.gov.laa.ccms.caab.model.LinkedCase;
-import uk.gov.laa.ccms.caab.model.ApplicationDetails;
-import uk.gov.laa.ccms.caab.model.BaseApplication;
-import uk.gov.laa.ccms.data.api.AbstractIntegrationTest;
+import uk.gov.laa.ccms.data.api.IntegrationTestInterface;
@SpringBootTest(classes = CaabApiApplication.class)
@SqlMergeMode(MERGE)
-//@ActiveProfiles("local")
-//public class ApplicationControllerIntegrationTest {
@Sql(executionPhase = BEFORE_TEST_METHOD, scripts = "/sql/application_tables_create_schema.sql")
@Sql(executionPhase = AFTER_TEST_METHOD, scripts = "/sql/application_tables_drop_schema.sql")
-public class ApplicationControllerIntegrationTest extends AbstractIntegrationTest {
+public class ApplicationControllerIntegrationTest extends BaseApplicationControllerIntegrationTest implements
+ IntegrationTestInterface {
- @Autowired
- private ApplicationController applicationController;
-
- @Autowired
- private ApplicationService applicationService;
-
- private final String caabUserLoginId = "audit@user.com";
-
- @BeforeEach
- public void setup() {
- currentUserHolder.set(caabUserLoginId);
- }
-
- /**
- * Loads the JSON file from the classpath and parses it into an ApplicationDetail object.
- *
- * @param jsonFilePath The path to the JSON file to load
- */
- private ApplicationDetail loadApplicationDetailFromJsonFile(String jsonFilePath) throws
- IOException {
- ObjectMapper objectMapper = new ObjectMapper();
- ClassPathResource resource = new ClassPathResource(jsonFilePath);
- return objectMapper.readValue(resource.getInputStream(), ApplicationDetail.class);
- }
-
- /**
- * Generates a random 12-digit number string to be used as a case reference number.
- */
- private String generateTestCaseRef(){
- Random random = new Random();
- StringBuilder stringBuilder = new StringBuilder(12);
-
- for (int i = 0; i < 12; i++) {
- int digit = random.nextInt(10); // Generate a random digit (0-9)
- stringBuilder.append(digit);
- }
-
- return stringBuilder.toString();
- }
-
- /**
- * Arguments for the testCreateApplication test method.
- */
- private static Stream createApplicationArguments() {
- return Stream.of(
- Arguments.of("/json/applicationDetail_base.json",
- "getAuditTrail",
- List.of("auditTrail")),
- Arguments.of("/json/applicationDetail_costStructure.json",
- "getCosts.getAuditTrail",
- List.of("costs.auditTrail", "auditTrail")),
- Arguments.of("/json/applicationDetail_costEntries.json",
- "getCosts.getCostEntries.getAuditTrail",
- List.of("costs.costEntries.auditTrail","costs.auditTrail", "auditTrail")),
- Arguments.of("/json/applicationDetail_correspondenceAddress.json",
- "getCorrespondenceAddress.getAuditTrail",
- List.of("correspondenceAddress.auditTrail", "auditTrail")),
- Arguments.of("/json/applicationDetail_proceedings.json",
- "getProceedings.getAuditTrail",
- List.of("proceedings.auditTrail", "auditTrail")),
- Arguments.of("/json/applicationDetail_scopeLimitation.json",
- "getProceedings.getScopeLimitations.getAuditTrail",
- List.of("proceedings.scopeLimitations.auditTrail","proceedings.auditTrail", "auditTrail")),
- Arguments.of("/json/applicationDetail_linkedCase.json",
- "getLinkedCases.getAuditTrail",
- List.of("linkedCases.auditTrail", "auditTrail")),
- Arguments.of("/json/applicationDetail_priorAuthority.json",
- "getPriorAuthorities.getAuditTrail",
- List.of("priorAuthorities.auditTrail", "auditTrail")),
-
- //No Audit data for reference data items
- Arguments.of("/json/applicationDetail_referenceDataItem.json",
- "getPriorAuthorities.getAuditTrail",
- List.of("priorAuthorities.auditTrail", "auditTrail")),
- Arguments.of("/json/applicationDetail_opponent.json",
- "getOpponents.getAuditTrail",
- List.of("opponents.auditTrail", "auditTrail")),
- Arguments.of("/json/applicationDetail_opponentAddress.json",
- "getOpponents.getAddress.getAuditTrail",
- List.of("opponents.address.auditTrail","opponents.auditTrail", "auditTrail"))
- );
- }
-
- /**
- * Parameterized test to create an application and verify that the audit trail and non-transient
- * variables are set correctly.
- *
- * @param fileInput The path to the JSON file to load
- * @param auditTrailMethod The method to call to get the audit trail object
- * (e.g. "getAuditTrail" or "getCosts.getAuditTrail")
- * @param auditTrailsToNull A list of audit trails to set to null
- * (e.g. "auditTrail" or "costs.auditTrail")
- */
- @ParameterizedTest
- @MethodSource("createApplicationArguments")
- public void testCreateApplication(String fileInput, String auditTrailMethod, List auditTrailsToNull)
- throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException,
- NoSuchFieldException {
- // Load and parse the JSON file into yourApplicationDetailObject
- ApplicationDetail applicationDetail = loadApplicationDetailFromJsonFile(
- fileInput);
-
- String caseReference = generateTestCaseRef();
- applicationDetail.setCaseReferenceNumber(caseReference);
-
- String auditUser = "audit@user.com";
- // Call the createApplication method directly
- ResponseEntity responseEntity = applicationController.createApplication(auditUser, applicationDetail);
-
- assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode());
- URI locationUri = responseEntity.getHeaders().getLocation();
-
- String path = locationUri.getPath();
- String id = path.substring(path.lastIndexOf('/') + 1);
-
- ApplicationDetail savedApplicationDetails = applicationService.getApplication(Long.valueOf(id));
-
- assertAuditTrail(savedApplicationDetails, auditTrailMethod, auditUser);
- setAuditPropertiesToNull(savedApplicationDetails, auditTrailsToNull);
-
- //null out the id's as they are generated by the database
- //theses will always be different
- if (savedApplicationDetails.getLinkedCases() != null){
- for (LinkedCase linkedCase : savedApplicationDetails.getLinkedCases()){
- linkedCase.setId(null);
- }
- }
-
- assertEquals(applicationDetail, savedApplicationDetails);
- }
-
- /**
- * Test to query for applications by casereference only
- *
- */
- @Test
- @Sql(scripts = "/sql/application_insert.sql")
- public void testGetApplications_caseref_returnsdata() {
- String caseRef = "300001644516";
- String provCaseRef = "329635";
- String clientSurname = "Payne";
- String clientRef = "PhilTest";
- Integer officeId = 145512;
- String feeEarner = "2027148";
- String status = "UNSUBMITTED";
-
- // Call the getApplications method directly
- ResponseEntity responseEntity = applicationController.getApplications(
- caseRef,
- null,
- null,
- null,
- null,
- null,
- null,
- Pageable.unpaged());
-
- assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
-
- assertNotNull(responseEntity.getBody());
- assertNotNull(responseEntity.getBody().getContent());
- assertEquals(1, responseEntity.getBody().getSize());
- BaseApplication result = responseEntity.getBody().getContent().get(0);
- assertEquals(caseRef, result.getCaseReferenceNumber());
- assertEquals(provCaseRef, result.getProviderDetails().getProviderCaseReference());
- assertEquals(clientSurname, result.getClient().getSurname());
- assertEquals(clientRef, result.getClient().getReference());
- assertEquals(feeEarner, result.getProviderDetails().getFeeEarner().getId());
- assertEquals(officeId, result.getProviderDetails().getOffice().getId());
- assertEquals(status, result.getStatus().getId());
- }
-
- /**
- * Test to query for applications using all criteria
- *
- */
- @Test
- @Sql(scripts = "/sql/application_insert.sql")
- public void testGetApplications_allfields_returnsdata() {
- String caseRef = "300001644516";
- String provCaseRef = "329635";
- String clientSurname = "Payne";
- String clientRef = "PhilTest";
- Integer officeId = 145512;
- String feeEarner = "2027148";
- String status = "UNSUBMITTED";
-
- // Call the getApplications method directly
- ResponseEntity responseEntity = applicationController.getApplications(
- caseRef,
- provCaseRef,
- clientSurname,
- clientRef,
- feeEarner,
- officeId,
- status,
- Pageable.unpaged());
-
- assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
-
- assertNotNull(responseEntity.getBody());
- assertNotNull(responseEntity.getBody().getContent());
- assertEquals(1, responseEntity.getBody().getSize());
- BaseApplication result = responseEntity.getBody().getContent().get(0);
- assertEquals(caseRef, result.getCaseReferenceNumber());
- assertEquals(provCaseRef, result.getProviderDetails().getProviderCaseReference());
- assertEquals(clientSurname, result.getClient().getSurname());
- assertEquals(clientRef, result.getClient().getReference());
- assertEquals(feeEarner, result.getProviderDetails().getFeeEarner().getId());
- assertEquals(officeId, result.getProviderDetails().getOffice().getId());
- assertEquals(status, result.getStatus().getId());
- }
-
- /**
- * Test to query for applications and verify no results are returned
- *
- */
- @Test
- @Sql(scripts = "/sql/application_insert.sql")
- public void testGetApplications_allfields_nomatch() {
- String caseRef = "unknown";
- String provCaseRef = "329635";
- String clientSurname = "Payne";
- String clientRef = "PhilTest";
- Integer officeId = 145512;
- String feeEarner = "2027148";
- String status = "UNSUBMITTED";
-
- // Call the getApplications method directly
- ResponseEntity responseEntity = applicationController.getApplications(
- caseRef,
- provCaseRef,
- clientSurname,
- clientRef,
- feeEarner,
- officeId,
- status,
- Pageable.unpaged());
-
- assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
-
- assertNotNull(responseEntity.getBody());
- assertNotNull(responseEntity.getBody().getContent());
- assertEquals(0, responseEntity.getBody().getSize());
- }
-
- /**
- * Assert that the audit trail is set correctly in the object. Uses reflection to navigate the
- * auditTrailMethod path and assert that the audit trail is set correctly.
- */
- private void assertAuditTrail(Object object, String auditMethod, String expectedAuditUser)
- throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
- String[] methodCalls = auditMethod.split("\\.");
- assertAuditTrailRecursive(object, methodCalls, 0, expectedAuditUser);
- }
-
- /**
- * Recursively navigate the object using the methodCalls array and assert that the audit trail is
- * set correctly.
- */
- private void assertAuditTrailRecursive(Object object, String[] methodCalls, int index, String expectedAuditUser)
- throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
- if (index >= methodCalls.length || object == null) {
- return;
- }
-
- Method method = object.getClass().getMethod(methodCalls[index]);
- object = method.invoke(object);
-
- if (object instanceof List> list) {
- for (Object item : list) {
- assertAuditTrailRecursive(item, methodCalls, index + 1, expectedAuditUser);
- }
- } else {
- if (index == methodCalls.length - 1) {
- assertAuditDetailsInObject(object, expectedAuditUser);
- } else {
- assertAuditTrailRecursive(object, methodCalls, index + 1, expectedAuditUser);
- }
- }
- }
-
- /**
- * Used to assert that the audit trail is set correctly in the object.
- *
- * @param object The object to check
- * @param expectedAuditUser The expected audit user
- */
- private void assertAuditDetailsInObject(Object object, String expectedAuditUser) {
- if (object instanceof AuditTrail auditTrail) {
- assertNotNull(auditTrail);
- assertEquals(expectedAuditUser, auditTrail.getCreatedBy());
- assertEquals(expectedAuditUser, auditTrail.getLastSavedBy());
- assertNotNull(auditTrail.getCreated());
- assertNotNull(auditTrail.getLastSaved());
- }
- }
-
- /**
- * Sets the audit trail properties to null in the object. Uses reflection to navigate the
- * list of auditTrailsToNull and set the audit trail to null.
- */
- private void setAuditPropertiesToNull(Object object, List auditTrailsToNull) throws NoSuchFieldException, IllegalAccessException {
- if (object == null || auditTrailsToNull == null) {
- return;
- }
- for (String trail : auditTrailsToNull) {
- String[] fields = trail.split("\\.");
- nullifyFieldRecursive(object, fields, 0);
- }
- }
-
- /**
- * Recursively navigate the object using the fields array and set the field to null.
- */
- private static void nullifyFieldRecursive(Object object, String[] fields, int index)
- throws NoSuchFieldException, IllegalAccessException {
- if (object == null || index >= fields.length) {
- return;
- }
-
- if (object instanceof List> list) {
- // Handle List objects
- for (Object item : list) {
- nullifyFieldRecursive(item, fields, index);
- }
- } else {
- Field field = object.getClass().getDeclaredField(fields[index]);
- field.setAccessible(true);
-
- if (index == fields.length - 1) {
- // Last field in the path, set to null
- field.set(object, null);
- } else {
- // Not the last field, navigate to the next object or list in the path
- Object nextObject = field.get(object);
- nullifyFieldRecursive(nextObject, fields, index + 1);
- }
- }
- }
+ //this runs all tests in BaseApplicationControllerIntegrationTest, do not add anything here
+ //running this class takes longer than the local version, but it is used for running tests in a pipeline
}
diff --git a/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/controller/BaseApplicationControllerIntegrationTest.java b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/controller/BaseApplicationControllerIntegrationTest.java
new file mode 100644
index 0000000..cd8c6fd
--- /dev/null
+++ b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/controller/BaseApplicationControllerIntegrationTest.java
@@ -0,0 +1,660 @@
+package uk.gov.laa.ccms.data.api.controller;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static uk.gov.laa.ccms.caab.api.audit.AuditorAwareImpl.currentUserHolder;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.URI;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+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.core.io.ClassPathResource;
+import org.springframework.data.domain.Pageable;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.test.context.jdbc.Sql;
+import uk.gov.laa.ccms.caab.api.controller.ApplicationController;
+import uk.gov.laa.ccms.caab.api.entity.AuditTrail;
+import uk.gov.laa.ccms.caab.api.service.ApplicationService;
+import uk.gov.laa.ccms.caab.model.ApplicationDetail;
+import uk.gov.laa.ccms.caab.model.ApplicationDetails;
+import uk.gov.laa.ccms.caab.model.BaseApplication;
+import uk.gov.laa.ccms.caab.model.BaseClient;
+import uk.gov.laa.ccms.caab.model.LinkedCase;
+import uk.gov.laa.ccms.caab.model.PriorAuthority;
+import uk.gov.laa.ccms.caab.model.Proceeding;
+import uk.gov.laa.ccms.caab.model.ScopeLimitation;
+
+public abstract class BaseApplicationControllerIntegrationTest {
+
+ @Autowired
+ private ApplicationController applicationController;
+
+ @Autowired
+ private ApplicationService applicationService;
+
+ private final String caabUserLoginId = "audit@user.com";
+
+ @BeforeEach
+ public void setup() {
+ currentUserHolder.set(caabUserLoginId);
+ }
+
+ /**
+ * Loads the JSON file from the classpath and parses it into a specified object.
+ *
+ * @param jsonFilePath The path to the JSON file to load
+ */
+ private T loadObjectFromJson(String jsonFilePath, Class objectType) throws IOException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ ClassPathResource resource = new ClassPathResource(jsonFilePath);
+ return objectMapper.readValue(resource.getInputStream(), objectType);
+ }
+
+
+ /**
+ * Generates a random 12-digit number string to be used as a case reference number.
+ */
+ private String generateTestCaseRef(){
+ Random random = new Random();
+ StringBuilder stringBuilder = new StringBuilder(12);
+
+ for (int i = 0; i < 12; i++) {
+ int digit = random.nextInt(10); // Generate a random digit (0-9)
+ stringBuilder.append(digit);
+ }
+
+ return stringBuilder.toString();
+ }
+
+ /**
+ * Arguments for the testCreateApplication test method.
+ */
+ private static Stream createApplicationArguments() {
+ return Stream.of(
+ Arguments.of("/json/applicationDetail_base.json",
+ "getAuditTrail",
+ List.of("auditTrail")),
+ Arguments.of("/json/applicationDetail_costStructure.json",
+ "getCosts.getAuditTrail",
+ List.of("costs.auditTrail", "auditTrail")),
+ Arguments.of("/json/applicationDetail_costEntries.json",
+ "getCosts.getCostEntries.getAuditTrail",
+ List.of("costs.costEntries.auditTrail","costs.auditTrail", "auditTrail")),
+ Arguments.of("/json/applicationDetail_correspondenceAddress.json",
+ "getCorrespondenceAddress.getAuditTrail",
+ List.of("correspondenceAddress.auditTrail", "auditTrail")),
+ Arguments.of("/json/applicationDetail_proceedings.json",
+ "getProceedings.getAuditTrail",
+ List.of("proceedings.auditTrail", "auditTrail")),
+ Arguments.of("/json/applicationDetail_scopeLimitation.json",
+ "getProceedings.getScopeLimitations.getAuditTrail",
+ List.of("proceedings.scopeLimitations.auditTrail","proceedings.auditTrail", "auditTrail")),
+ Arguments.of("/json/applicationDetail_linkedCase.json",
+ "getLinkedCases.getAuditTrail",
+ List.of("linkedCases.auditTrail", "auditTrail")),
+ Arguments.of("/json/applicationDetail_priorAuthority.json",
+ "getPriorAuthorities.getAuditTrail",
+ List.of("priorAuthorities.auditTrail", "auditTrail")),
+
+ //No Audit data for reference data items
+ Arguments.of("/json/applicationDetail_referenceDataItem.json",
+ "getPriorAuthorities.getAuditTrail",
+ List.of("priorAuthorities.auditTrail", "auditTrail")),
+ Arguments.of("/json/applicationDetail_opponent.json",
+ "getOpponents.getAuditTrail",
+ List.of("opponents.auditTrail", "auditTrail")),
+ Arguments.of("/json/applicationDetail_opponentAddress.json",
+ "getOpponents.getAddress.getAuditTrail",
+ List.of("opponents.address.auditTrail","opponents.auditTrail", "auditTrail"))
+ );
+ }
+
+ /**
+ * Parameterized test to create an application and verify that the audit trail and non-transient
+ * variables are set correctly.
+ *
+ * @param fileInput The path to the JSON file to load
+ * @param auditTrailMethod The method to call to get the audit trail object
+ * (e.g. "getAuditTrail" or "getCosts.getAuditTrail")
+ * @param auditTrailsToNull A list of audit trails to set to null
+ * (e.g. "auditTrail" or "costs.auditTrail")
+ */
+ @ParameterizedTest
+ @MethodSource("createApplicationArguments")
+ public void testCreateApplication(String fileInput, String auditTrailMethod, List auditTrailsToNull)
+ throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException,
+ NoSuchFieldException {
+ // Load and parse the JSON file into yourApplicationDetailObject
+ ApplicationDetail applicationDetail = loadObjectFromJson(
+ fileInput, ApplicationDetail.class);
+
+ String caseReference = generateTestCaseRef();
+ applicationDetail.setCaseReferenceNumber(caseReference);
+
+ String auditUser = "audit@user.com";
+ // Call the createApplication method directly
+ ResponseEntity responseEntity =
+ applicationController.createApplication(auditUser, applicationDetail);
+
+ assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode());
+ URI locationUri = responseEntity.getHeaders().getLocation();
+
+ String path = locationUri.getPath();
+ String id = path.substring(path.lastIndexOf('/') + 1);
+
+ ApplicationDetail savedApplicationDetails = applicationService.getApplication(Long.valueOf(id));
+
+ assertAuditTrail(savedApplicationDetails, auditTrailMethod, auditUser);
+ setAuditPropertiesToNull(savedApplicationDetails, auditTrailsToNull);
+
+ // null/ignore the ids as theses are generated by the database
+ nullModelIds(savedApplicationDetails);
+
+ assertEquals(applicationDetail, savedApplicationDetails);
+ }
+
+ private void nullModelIds(ApplicationDetail applicationDetail) {
+ if (applicationDetail.getLinkedCases() != null) {
+ for (LinkedCase linkedCase : applicationDetail.getLinkedCases()) {
+ linkedCase.setId(null);
+ }
+ }
+
+ if (applicationDetail.getProceedings() != null) {
+ for (Proceeding proceeding : applicationDetail.getProceedings()) {
+ proceeding.setId(null);
+ if (proceeding.getScopeLimitations() != null) {
+ for (ScopeLimitation scopeLimitation : proceeding.getScopeLimitations()) {
+ scopeLimitation.setId(null);
+ }
+ }
+ }
+ }
+
+ if (applicationDetail.getPriorAuthorities() != null) {
+ for (uk.gov.laa.ccms.caab.model.PriorAuthority priorAuthority : applicationDetail.getPriorAuthorities()) {
+ priorAuthority.setId(null);
+ }
+ }
+ }
+
+ /**
+ * Test to query for applications by casereference only
+ *
+ */
+ @Test
+ @Sql(scripts = "/sql/application_insert.sql")
+ public void testGetApplications_caseref_returnsdata() {
+ String caseRef = "300001644516";
+ String provCaseRef = "329635";
+ String clientSurname = "Payne";
+ String clientRef = "PhilTest";
+ Integer officeId = 145512;
+ String feeEarner = "2027148";
+ String status = "UNSUBMITTED";
+
+ // Call the getApplications method directly
+ ResponseEntity responseEntity = applicationController.getApplications(
+ caseRef,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ Pageable.unpaged());
+
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+
+ assertNotNull(responseEntity.getBody());
+ assertNotNull(responseEntity.getBody().getContent());
+ assertEquals(1, responseEntity.getBody().getSize());
+ BaseApplication result = responseEntity.getBody().getContent().get(0);
+ assertEquals(caseRef, result.getCaseReferenceNumber());
+ assertEquals(provCaseRef, result.getProviderDetails().getProviderCaseReference());
+ assertEquals(clientSurname, result.getClient().getSurname());
+ assertEquals(clientRef, result.getClient().getReference());
+ assertEquals(feeEarner, result.getProviderDetails().getFeeEarner().getId());
+ assertEquals(officeId, result.getProviderDetails().getOffice().getId());
+ assertEquals(status, result.getStatus().getId());
+ }
+
+ /**
+ * Test to query for applications using all criteria
+ *
+ */
+ @Test
+ @Sql(scripts = "/sql/application_insert.sql")
+ public void testGetApplications_allfields_returnsdata() {
+ String caseRef = "300001644516";
+ String provCaseRef = "329635";
+ String clientSurname = "Payne";
+ String clientRef = "PhilTest";
+ Integer officeId = 145512;
+ String feeEarner = "2027148";
+ String status = "UNSUBMITTED";
+
+ // Call the getApplications method directly
+ ResponseEntity responseEntity = applicationController.getApplications(
+ caseRef,
+ provCaseRef,
+ clientSurname,
+ clientRef,
+ feeEarner,
+ officeId,
+ status,
+ Pageable.unpaged());
+
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+
+ assertNotNull(responseEntity.getBody());
+ assertNotNull(responseEntity.getBody().getContent());
+ assertEquals(1, responseEntity.getBody().getSize());
+ BaseApplication result = responseEntity.getBody().getContent().get(0);
+ assertEquals(caseRef, result.getCaseReferenceNumber());
+ assertEquals(provCaseRef, result.getProviderDetails().getProviderCaseReference());
+ assertEquals(clientSurname, result.getClient().getSurname());
+ assertEquals(clientRef, result.getClient().getReference());
+ assertEquals(feeEarner, result.getProviderDetails().getFeeEarner().getId());
+ assertEquals(officeId, result.getProviderDetails().getOffice().getId());
+ assertEquals(status, result.getStatus().getId());
+ }
+
+ /**
+ * Test to query for applications and verify no results are returned
+ *
+ */
+ @Test
+ @Sql(scripts = "/sql/application_insert.sql")
+ public void testGetApplications_allfields_nomatch() {
+ String caseRef = "unknown";
+ String provCaseRef = "329635";
+ String clientSurname = "Payne";
+ String clientRef = "PhilTest";
+ Integer officeId = 145512;
+ String feeEarner = "2027148";
+ String status = "UNSUBMITTED";
+
+ // Call the getApplications method directly
+ ResponseEntity responseEntity = applicationController.getApplications(
+ caseRef,
+ provCaseRef,
+ clientSurname,
+ clientRef,
+ feeEarner,
+ officeId,
+ status,
+ Pageable.unpaged());
+
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+
+ assertNotNull(responseEntity.getBody());
+ assertNotNull(responseEntity.getBody().getContent());
+ assertEquals(0, responseEntity.getBody().getSize());
+ }
+
+ @Test
+ @Sql(scripts = {"/sql/application_insert.sql"})
+ public void addApplicationProceedings() throws IOException {
+ Long caseRef = 41L;
+
+ Proceeding proceeding = loadObjectFromJson("/json/proceeding_new.json", Proceeding.class);
+ ResponseEntity response = applicationController.addApplicationProceeding(
+ caseRef, caabUserLoginId, proceeding);
+
+ assertEquals(HttpStatus.CREATED, response.getStatusCode());
+
+ ResponseEntity> responseEntity =
+ applicationController.getApplicationProceedings(caseRef);
+
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertNotNull(responseEntity.getBody());
+
+ List proceedings = responseEntity.getBody();
+ assertEquals(1, proceedings.size());
+ }
+
+ @Test
+ @Sql(scripts = {"/sql/application_insert.sql", "/sql/proceeding_insert.sql"})
+ public void updateProceeding() throws IOException {
+ Long proceedingId = 2L;
+
+ Proceeding updatedProceeding = loadObjectFromJson("/json/proceeding_new.json", Proceeding.class);
+
+ ResponseEntity response = applicationController.updateProceeding(proceedingId, caabUserLoginId, updatedProceeding);
+
+ assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode());
+ }
+
+ @Test
+ @Sql(scripts = {"/sql/application_insert.sql", "/sql/proceeding_insert.sql"})
+ public void getApplicationProceedings() {
+ Long caseRef = 41L;
+
+ ResponseEntity> responseEntity = applicationController.getApplicationProceedings(caseRef);
+
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertNotNull(responseEntity.getBody());
+
+ List proceedings = responseEntity.getBody();
+ assertEquals(1, proceedings.size());
+ }
+
+ @Test
+ @Sql(scripts = {"/sql/application_insert.sql", "/sql/proceeding_insert.sql"})
+ public void deleteApplicationProceedings() {
+ Long caseRef = 41L;
+ Long proceedingRef = 2L;
+
+ applicationController.removeProceeding(proceedingRef, caabUserLoginId);
+ ResponseEntity> responseEntity = applicationController.getApplicationProceedings(caseRef);
+
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertNotNull(responseEntity.getBody());
+
+ List proceedings = responseEntity.getBody();
+ assertEquals(0, proceedings.size());
+ }
+
+ @Test
+ @Sql(scripts = {"/sql/application_insert.sql"})
+ public void addLinkedCase() throws IOException {
+ Long caseRef = 41L; // Assuming this is the ID of an application
+
+ LinkedCase newLinkedCase = loadObjectFromJson("/json/linked_cases_new.json", LinkedCase.class);
+
+ ResponseEntity response =
+ applicationController.addApplicationLinkedCase(caseRef, caabUserLoginId,
+ newLinkedCase);
+
+ assertEquals(HttpStatus.CREATED, response.getStatusCode());
+
+ ResponseEntity> responseEntity =
+ applicationController.getApplicationLinkedCases(caseRef);
+
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertNotNull(responseEntity.getBody());
+
+ List linkedCases = responseEntity.getBody();
+ assertEquals(1, linkedCases.size());
+ }
+
+ @Test
+ @Sql(scripts = {"/sql/application_insert.sql", "/sql/linked_cases_insert.sql"})
+ public void getLinkedCase() {
+ Long caseRef = 41L;
+
+ ResponseEntity> responseEntity = applicationController.getApplicationLinkedCases(caseRef);
+
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertNotNull(responseEntity.getBody());
+
+ List linkedCases = responseEntity.getBody();
+ assertEquals(1, linkedCases.size());
+ }
+
+ @Test
+ @Sql(scripts = {"/sql/application_insert.sql", "/sql/linked_cases_insert.sql"})
+ public void deleteLinkedCase() {
+ Long caseRef = 41L;
+ Long linkedCaseRef = 2L;
+
+ applicationController.removeApplicationLinkedCase(linkedCaseRef, caabUserLoginId);
+ ResponseEntity> responseEntity = applicationController.getApplicationLinkedCases(caseRef);
+
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertNotNull(responseEntity.getBody());
+
+ List linkedCases = responseEntity.getBody();
+ assertEquals(0, linkedCases.size());
+ }
+
+ @Test
+ @Sql(scripts = {"/sql/application_insert.sql"})
+ public void addPriorAuthority() throws IOException {
+ Long caseRef = 41L;
+
+ PriorAuthority
+ priorAuthority = loadObjectFromJson("/json/prior_authority_new.json", PriorAuthority.class);
+
+ ResponseEntity response = applicationController.addApplicationPriorAuthority(caseRef, caabUserLoginId, priorAuthority);
+
+ assertEquals(HttpStatus.CREATED, response.getStatusCode());
+ }
+
+ @Test
+ @Sql(scripts = {"/sql/application_insert.sql", "/sql/prior_authority_insert.sql"})
+ public void updatePriorAuthority() throws IOException {
+ Long priorAuthorityId = 2L;
+
+ PriorAuthority updatedPriorAuthority = loadObjectFromJson("/json/prior_authority_new.json", PriorAuthority.class);
+
+ ResponseEntity response = applicationController.updatePriorAuthority(priorAuthorityId, caabUserLoginId, updatedPriorAuthority);
+
+ assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode());
+ }
+
+ @Test
+ @Sql(scripts = {"/sql/application_insert.sql", "/sql/prior_authority_insert.sql"})
+ public void getPriorAuthority() {
+ Long caseRef = 41L;
+
+ ResponseEntity> responseEntity = applicationController.getApplicationPriorAuthorities(caseRef);
+
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertNotNull(responseEntity.getBody());
+
+ List priorAuthorities = responseEntity.getBody();
+ assertEquals(1, priorAuthorities.size());
+ }
+
+ @Test
+ @Sql(scripts = {"/sql/application_insert.sql", "/sql/prior_authority_insert.sql"})
+ public void deletePriorAuthority() {
+ Long caseRef = 41L;
+ Long priorAuthorityRef = 2L;
+
+ applicationController.removePriorAuthority(priorAuthorityRef, caabUserLoginId);
+ ResponseEntity> responseEntity = applicationController.getApplicationPriorAuthorities(caseRef);
+
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertNotNull(responseEntity.getBody());
+
+ List priorAuthorities = responseEntity.getBody();
+ assertEquals(0, priorAuthorities.size());
+ }
+
+ @Test
+ @Sql(scripts = {"/sql/application_insert.sql", "/sql/proceeding_insert.sql"})
+ public void addScopeLimitationToProceeding() throws IOException {
+ Long proceedingId = 2L;
+
+ ScopeLimitation scopeLimitation = loadObjectFromJson("/json/scope_limitation_new.json", ScopeLimitation.class);
+
+ ResponseEntity response = applicationController.addProceedingScopeLimitation(proceedingId, caabUserLoginId, scopeLimitation);
+
+ assertEquals(HttpStatus.CREATED, response.getStatusCode());
+ }
+
+ @Test
+ @Sql(scripts = {"/sql/application_insert.sql", "/sql/proceeding_insert.sql", "/sql/scope_limitation_insert.sql"})
+ public void updateScopeLimitationInProceeding() throws IOException {
+ Long scopeLimitationId = 3L;
+
+ ScopeLimitation updatedScopeLimitation = loadObjectFromJson("/json/scope_limitation_new.json", ScopeLimitation.class);
+
+ ResponseEntity response = applicationController.updateScopeLimitation(scopeLimitationId, caabUserLoginId, updatedScopeLimitation);
+
+ assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode());
+ }
+
+
+ @Test
+ @Sql(scripts = {
+ "/sql/application_insert.sql",
+ "/sql/proceeding_insert.sql",
+ "/sql/scope_limitation_insert.sql"})
+ public void getScopeLimitationsForProceeding() {
+ Long proceedingId = 2L;
+
+ ResponseEntity> responseEntity = applicationController.getApplicationScopeLimitations(proceedingId);
+
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertNotNull(responseEntity.getBody());
+
+ List scopeLimitations = responseEntity.getBody();
+ assertFalse(scopeLimitations.isEmpty());
+ }
+
+ @Test
+ @Sql(scripts = {
+ "/sql/application_insert.sql",
+ "/sql/proceeding_insert.sql",
+ "/sql/scope_limitation_insert.sql"})
+ public void removeScopeLimitationFromProceeding() {
+ Long scopeLimitationId = 3L;
+
+ ResponseEntity response = applicationController.removeScopeLimitation(scopeLimitationId, caabUserLoginId);
+ assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode());
+
+ ResponseEntity> responseEntity = applicationController.getApplicationScopeLimitations(2L);
+
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertNotNull(responseEntity.getBody());
+
+ List scopeLimitations = responseEntity.getBody();
+ assertTrue(scopeLimitations.isEmpty());
+ }
+
+ @Test
+ @Sql(scripts = {"/sql/application_insert.sql"})
+ public void updateClient() throws IOException {
+ Long caseRef = 41L;
+ String clientReferenceId = "62595640";
+
+ BaseClient baseClient = loadObjectFromJson("/json/base_client_new.json", BaseClient.class);
+
+ ResponseEntity response = applicationController.updateApplicationClient(clientReferenceId,caabUserLoginId, baseClient);
+ assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode());
+
+ ResponseEntity responseEntity = applicationController.getApplication(caseRef);
+
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertNotNull(responseEntity.getBody());
+
+ ApplicationDetail applicationDetail = responseEntity.getBody();
+ assertEquals(clientReferenceId, applicationDetail.getClient().getReference());
+ assertEquals(baseClient.getFirstName(), applicationDetail.getClient().getFirstName());
+ assertEquals(baseClient.getSurname(), applicationDetail.getClient().getSurname());
+ }
+
+ /**
+ * Assert that the audit trail is set correctly in the object. Uses reflection to navigate the
+ * auditTrailMethod path and assert that the audit trail is set correctly.
+ */
+ private void assertAuditTrail(Object object, String auditMethod, String expectedAuditUser)
+ throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
+ String[] methodCalls = auditMethod.split("\\.");
+ assertAuditTrailRecursive(object, methodCalls, 0, expectedAuditUser);
+ }
+
+ /**
+ * Recursively navigate the object using the methodCalls array and assert that the audit trail is
+ * set correctly.
+ */
+ private void assertAuditTrailRecursive(Object object, String[] methodCalls, int index, String expectedAuditUser)
+ throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
+ if (index >= methodCalls.length || object == null) {
+ return;
+ }
+
+ Method method = object.getClass().getMethod(methodCalls[index]);
+ object = method.invoke(object);
+
+ if (object instanceof List> list) {
+ for (Object item : list) {
+ assertAuditTrailRecursive(item, methodCalls, index + 1, expectedAuditUser);
+ }
+ } else {
+ if (index == methodCalls.length - 1) {
+ assertAuditDetailsInObject(object, expectedAuditUser);
+ } else {
+ assertAuditTrailRecursive(object, methodCalls, index + 1, expectedAuditUser);
+ }
+ }
+ }
+
+ /**
+ * Used to assert that the audit trail is set correctly in the object.
+ *
+ * @param object The object to check
+ * @param expectedAuditUser The expected audit user
+ */
+ private void assertAuditDetailsInObject(Object object, String expectedAuditUser) {
+ if (object instanceof AuditTrail auditTrail) {
+ assertNotNull(auditTrail);
+ assertEquals(expectedAuditUser, auditTrail.getCreatedBy());
+ assertEquals(expectedAuditUser, auditTrail.getLastSavedBy());
+ assertNotNull(auditTrail.getCreated());
+ assertNotNull(auditTrail.getLastSaved());
+ }
+ }
+
+ /**
+ * Sets the audit trail properties to null in the object. Uses reflection to navigate the
+ * list of auditTrailsToNull and set the audit trail to null.
+ */
+ private void setAuditPropertiesToNull(Object object, List auditTrailsToNull) throws NoSuchFieldException, IllegalAccessException {
+ if (object == null || auditTrailsToNull == null) {
+ return;
+ }
+ for (String trail : auditTrailsToNull) {
+ String[] fields = trail.split("\\.");
+ nullifyFieldRecursive(object, fields, 0);
+ }
+ }
+
+ /**
+ * Recursively navigate the object using the fields array and set the field to null.
+ */
+ private static void nullifyFieldRecursive(Object object, String[] fields, int index)
+ throws NoSuchFieldException, IllegalAccessException {
+ if (object == null || index >= fields.length) {
+ return;
+ }
+
+ if (object instanceof List> list) {
+ // Handle List objects
+ for (Object item : list) {
+ nullifyFieldRecursive(item, fields, index);
+ }
+ } else {
+ Field field = object.getClass().getDeclaredField(fields[index]);
+ field.setAccessible(true);
+
+ if (index == fields.length - 1) {
+ // Last field in the path, set to null
+ field.set(object, null);
+ } else {
+ // Not the last field, navigate to the next object or list in the path
+ Object nextObject = field.get(object);
+ nullifyFieldRecursive(nextObject, fields, index + 1);
+ }
+ }
+ }
+
+}
diff --git a/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/service/ApplicationServiceIntegrationLocalTest.java b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/service/ApplicationServiceIntegrationLocalTest.java
new file mode 100644
index 0000000..880bd13
--- /dev/null
+++ b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/service/ApplicationServiceIntegrationLocalTest.java
@@ -0,0 +1,24 @@
+package uk.gov.laa.ccms.data.api.service;
+
+import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD;
+import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.BEFORE_TEST_METHOD;
+import static org.springframework.test.context.jdbc.SqlMergeMode.MergeMode.MERGE;
+
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.jdbc.Sql;
+import org.springframework.test.context.jdbc.SqlMergeMode;
+import uk.gov.laa.ccms.caab.api.CaabApiApplication;
+
+@SpringBootTest(classes = CaabApiApplication.class)
+@SqlMergeMode(MERGE)
+@ActiveProfiles("local")
+@Sql(executionPhase = AFTER_TEST_METHOD, scripts = "/sql/delete_data.sql")
+@Sql(executionPhase = BEFORE_TEST_METHOD, scripts = "/sql/delete_data.sql")
+public class ApplicationServiceIntegrationLocalTest extends
+ BaseApplicationServiceIntegrationTest {
+
+ //this runs all tests in BaseApplicationServiceIntegrationTest, do not add anything here
+ //this is an easy way to run the tests if you have the containerised database running locally already
+
+}
diff --git a/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/service/ApplicationServiceIntegrationTest.java b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/service/ApplicationServiceIntegrationTest.java
index a5bc0fb..4f68545 100644
--- a/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/service/ApplicationServiceIntegrationTest.java
+++ b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/service/ApplicationServiceIntegrationTest.java
@@ -1,518 +1,24 @@
package uk.gov.laa.ccms.data.api.service;
-
-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.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD;
import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.BEFORE_TEST_METHOD;
import static org.springframework.test.context.jdbc.SqlMergeMode.MergeMode.MERGE;
-import static uk.gov.laa.ccms.caab.api.audit.AuditorAwareImpl.currentUserHolder;
-import jakarta.transaction.Transactional;
-import java.math.BigDecimal;
-import java.text.SimpleDateFormat;
-import java.time.Instant;
-import java.util.Date;
-import java.util.TimeZone;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.CsvSource;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.http.HttpStatus;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlMergeMode;
import uk.gov.laa.ccms.caab.api.CaabApiApplication;
-import uk.gov.laa.ccms.caab.api.entity.Application;
-import uk.gov.laa.ccms.caab.api.exception.CaabApiException;
-import uk.gov.laa.ccms.caab.api.repository.ApplicationRepository;
-import uk.gov.laa.ccms.caab.api.service.ApplicationService;
-import uk.gov.laa.ccms.caab.model.Address;
-import uk.gov.laa.ccms.caab.model.ApplicationDetail;
-import uk.gov.laa.ccms.caab.model.ApplicationProviderDetails;
-import uk.gov.laa.ccms.caab.model.ApplicationType;
-import uk.gov.laa.ccms.caab.model.Client;
-import uk.gov.laa.ccms.caab.model.CostLimit;
-import uk.gov.laa.ccms.caab.model.CostStructure;
-import uk.gov.laa.ccms.caab.model.DevolvedPowers;
-import uk.gov.laa.ccms.caab.model.IntDisplayValue;
-import uk.gov.laa.ccms.caab.model.StringDisplayValue;
-import uk.gov.laa.ccms.data.api.AbstractIntegrationTest;
+import uk.gov.laa.ccms.data.api.IntegrationTestInterface;
@SpringBootTest(classes = CaabApiApplication.class)
@SqlMergeMode(MERGE)
@Sql(executionPhase = BEFORE_TEST_METHOD, scripts = "/sql/application_tables_create_schema.sql")
@Sql(executionPhase = AFTER_TEST_METHOD, scripts = "/sql/application_tables_drop_schema.sql")
-public class ApplicationServiceIntegrationTest extends AbstractIntegrationTest {
-//@ActiveProfiles("local")
-//public class ApplicationServiceIntegrationTest {
-
- @Autowired
- private ApplicationService applicationService;
- @Autowired
- private ApplicationRepository applicationRepository;
- private final String lscCaseReference = "LSC001";
- private final Integer providerId = 123456;
- private final String providerCaseReference = "PRD_CASE_REF_001";
- private final String providerDisplayValue = "Provider Display";
- private final Integer officeId = 987;
- private final String officeDisplayValue = "Office Display";
- private final String supervisor = "Supervisor1";
- private final String supervisorDisplayValue = "Supervisor Display";
- private final String feeEarner = "Fee Earner";
- private final String feeEarnerDisplayValue = "Fee Earner Display";
- private final String providerContact = "Provider Contact";
- private final String providerContactDisplayValue = "Provider Contact Display";
- private final String categoryOfLaw = "Category of Law";
- private final String categoryOfLawDisplayValue = "Category of Law Display";
- private final String relationToLinkedCase = "Relation to Linked Case";
- private final Boolean opponentAppliedForFunding = false;
- private final String displayStatus = "Display Status";
- private final String actualStatus = "Actual Status";
- private final String clientFirstName = "Client First Name";
- private final String clientSurname = "Client Surname";
- private final String clientReference = "Client Reference";
- private final Boolean amendment = false;
- private final Boolean meansAssessmentAmended = false;
- private final Boolean meritsAssessmentAmended = false;
- private final Boolean costLimitChanged = false;
- private final BigDecimal costLimitAtTimeOfMerits = BigDecimal.valueOf(10000);
- private final String applicationType = "Application Type";
- private final String applicationTypeDisplayValue = "Application Type Display";
- private final Boolean devolvedPowersUsed = false;
- private final Date dateDevolvedPowersUsed = Date.from(Instant.now());
- private final String devolvedPowersContractFlag = "Devolved Powers Contract Flag";
- private final Boolean meritsReassessmentReqdInd = false;
- private final Boolean larScopeFlag = true;
- private final Boolean leadProceedingChanged = false;
-
- //cost structure
- private final BigDecimal defaultCostLimitation = BigDecimal.valueOf(11111.11);
- private final BigDecimal grantedCostLimitation = BigDecimal.valueOf(22222.22);
- private final BigDecimal requestedCostLimitation = BigDecimal.valueOf(33333.33);
-
- //Address
- private final boolean noFixedAbode = false;
- private final String postCode = "SW1A 1AA";
- private final String houseNameNumber = "10";
- private final String addressLine1 = "Downing Street";
- private final String addressLine2 = "Westminster";
- private final String city = "London";
- private final String county = "Greater London";
- private final String country = "GBR";
- private final String careOf = "Prime Minister's Office";
- private final String preferredAddress = "PROVIDER";
-
- private final String caabUserLoginId = "audit@user.com";
-
- @BeforeEach
- public void setup() {
- currentUserHolder.set(caabUserLoginId);
- }
-
- @Test
- public void testSaveApplication_requiredFields(){
- ApplicationDetail application = buildRequiredApplicationDetail();
-
- Long savedId = applicationService.createApplication(application);
-
- // Assert that the saved application has been assigned an ID
- assertNotNull(savedId);
-
- // Fetch the saved application from the database
- Application fetchedApplication = applicationRepository.findById(savedId)
- .orElse(null);
-
- // Assert that the fetched application is not null and has the expected values
- assertNotNull(fetchedApplication);
- assertEquals(lscCaseReference, fetchedApplication.getLscCaseReference());
- assertEquals(providerId.toString(), fetchedApplication.getProviderId());
- assertEquals(categoryOfLaw, fetchedApplication.getCategoryOfLaw());
- assertEquals(clientReference, fetchedApplication.getClientReference());
- }
-
- @Test
- public void testSaveApplication_allFields(){
- ApplicationDetail application = buildApplication();
-
- Long savedId = applicationService.createApplication(application);
-
- // Assert that the saved application has been assigned an ID
- assertNotNull(savedId);
-
- // Fetch the saved application from the database
- Application fetchedApplication = applicationRepository.findById(savedId).orElse(null);
-
- // Assert that the fetched application is not null and has the expected values
- assertNotNull(fetchedApplication);
- assertEquals(lscCaseReference, fetchedApplication.getLscCaseReference());
- assertEquals(providerId.toString(), fetchedApplication.getProviderId());
- assertEquals(providerCaseReference, fetchedApplication.getProviderCaseReference());
- assertEquals(providerDisplayValue, fetchedApplication.getProviderDisplayValue());
- assertEquals(officeId, fetchedApplication.getOfficeId().intValue());
- assertEquals(officeDisplayValue, fetchedApplication.getOfficeDisplayValue());
- assertEquals(supervisor, fetchedApplication.getSupervisor());
- assertEquals(supervisorDisplayValue, fetchedApplication.getSupervisorDisplayValue());
- assertEquals(feeEarner, fetchedApplication.getFeeEarner());
- assertEquals(feeEarnerDisplayValue, fetchedApplication.getFeeEarnerDisplayValue());
- assertEquals(providerContact, fetchedApplication.getProviderContact());
- assertEquals(providerContactDisplayValue, fetchedApplication.getProviderContactDisplayValue());
- assertEquals(categoryOfLaw, fetchedApplication.getCategoryOfLaw());
- assertEquals(categoryOfLawDisplayValue, fetchedApplication.getCategoryOfLawDisplayValue());
- assertEquals(relationToLinkedCase, fetchedApplication.getRelationToLinkedCase());
- assertEquals(opponentAppliedForFunding, fetchedApplication.getOpponentAppliedForFunding());
- assertEquals(displayStatus, fetchedApplication.getDisplayStatus());
- assertEquals(actualStatus, fetchedApplication.getActualStatus());
- assertEquals(clientFirstName, fetchedApplication.getClientFirstName());
- assertEquals(clientSurname, fetchedApplication.getClientSurname());
- assertEquals(clientReference, fetchedApplication.getClientReference());
- assertEquals(amendment, fetchedApplication.isAmendment());
- assertEquals(meansAssessmentAmended, fetchedApplication.isMeansAssessmentAmended());
- assertEquals(meritsAssessmentAmended, fetchedApplication.isMeritsAssessmentAmended());
- assertEquals(costLimitChanged, fetchedApplication.isCostLimitChanged());
- assertEquals(costLimitAtTimeOfMerits, fetchedApplication.getCostLimitAtTimeOfMerits());
- assertEquals(applicationType, fetchedApplication.getApplicationType());
- assertEquals(applicationTypeDisplayValue, fetchedApplication.getApplicationTypeDisplayValue());
- assertEquals(devolvedPowersUsed, fetchedApplication.getDevolvedPowersUsed());
-
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- sdf.setTimeZone(TimeZone.getTimeZone("BST"));
- assertEquals(sdf.format(dateDevolvedPowersUsed), sdf.format(fetchedApplication.getDateDevolvedPowersUsed()));
-
- assertEquals(devolvedPowersContractFlag, fetchedApplication.getDevolvedPowersContractFlag());
- assertEquals(meritsReassessmentReqdInd, fetchedApplication.isMeritsReassessmentReqdInd());
- assertEquals(larScopeFlag, fetchedApplication.getLarScopeFlag());
- assertEquals(leadProceedingChanged, fetchedApplication.isLeadProceedingChangedOpaInput());
-
- assertEquals(caabUserLoginId, fetchedApplication.getAuditTrail().getLastSavedBy());
- assertEquals(caabUserLoginId, fetchedApplication.getAuditTrail().getCreatedBy());
- assertNotNull(fetchedApplication.getAuditTrail().getCreated());
- assertNotNull(fetchedApplication.getAuditTrail().getLastSaved());
-
- }
-
- @Test
- @Transactional
- public void testSaveApplication_costStructure(){
-
- ApplicationDetail application = buildRequiredApplicationDetail();
- application.setCosts(buildCosts());
-
- Long savedId = applicationService.createApplication(application);
-
- // Fetch the saved application from the database
- Application fetchedApplication = applicationRepository.findById(savedId).orElse(null);
-
- // Assert that the fetched application is not null and has the expected values
- assertNotNull(fetchedApplication);
- assertNotNull(fetchedApplication.getCosts());
- assertEquals(defaultCostLimitation, fetchedApplication.getCosts().getDefaultCostLimitation());
- assertEquals(grantedCostLimitation, fetchedApplication.getCosts().getGrantedCostLimitation());
- assertEquals(requestedCostLimitation, fetchedApplication.getCosts().getRequestedCostLimitation());
-
- assertEquals(caabUserLoginId, fetchedApplication.getCosts().getAuditTrail().getLastSavedBy());
- assertEquals(caabUserLoginId, fetchedApplication.getCosts().getAuditTrail().getCreatedBy());
- }
-
- @Test
- @Transactional
- public void testSaveApplication_address(){
- ApplicationDetail application = buildRequiredApplicationDetail();
- application.setCorrespondenceAddress(buildAddress());
-
- Long savedId = applicationService.createApplication(application);
-
- // Fetch the saved application from the database
- Application fetchedApplication = applicationRepository.findById(savedId).orElse(null);
-
- // Assert that the fetched application is not null and has the expected values
- assertNotNull(fetchedApplication);
- assertNotNull(fetchedApplication.getCorrespondenceAddress());
-
- // Assert the properties of the correspondence address
- assertEquals(noFixedAbode, fetchedApplication.getCorrespondenceAddress().getNoFixedAbode());
- assertEquals(postCode, fetchedApplication.getCorrespondenceAddress().getPostCode());
- assertEquals(houseNameNumber, fetchedApplication.getCorrespondenceAddress().getHouseNameNumber());
- assertEquals(addressLine1, fetchedApplication.getCorrespondenceAddress().getAddressLine1());
- assertEquals(addressLine2, fetchedApplication.getCorrespondenceAddress().getAddressLine2());
- assertEquals(city, fetchedApplication.getCorrespondenceAddress().getCity());
- assertEquals(county, fetchedApplication.getCorrespondenceAddress().getCounty());
- assertEquals(country, fetchedApplication.getCorrespondenceAddress().getCountry());
- assertEquals(careOf, fetchedApplication.getCorrespondenceAddress().getCareOf());
- assertEquals(preferredAddress, fetchedApplication.getCorrespondenceAddress().getPreferredAddress());
-
- // Audit Trail asserts for the address
- assertEquals(caabUserLoginId, fetchedApplication.getCorrespondenceAddress().getAuditTrail().getLastSavedBy());
- assertEquals(caabUserLoginId, fetchedApplication.getCorrespondenceAddress().getAuditTrail().getCreatedBy());
- }
-
- @Test
- @Transactional
- @Sql(scripts = "/sql/application_insert.sql")
- public void testGetApplication() {
- Long applicationId = 24L;
-
- ApplicationDetail result = applicationService.getApplication(applicationId);
-
- // Assert the result
- assertNotNull(result);
-
- assertEquals("300001644517", result.getCaseReferenceNumber());
- assertEquals(26517, result.getProviderDetails().getProvider().getId());
- assertEquals("329635", result.getProviderDetails().getProviderCaseReference());
- assertEquals("SWITALSKI'S SOLICITORS LTD", result.getProviderDetails().getProvider().getDisplayValue());
- assertEquals(145512, result.getProviderDetails().getOffice().getId());
- assertEquals("SWITALSKI'S SOLICITORS LTD-2L847Q", result.getProviderDetails().getOffice().getDisplayValue());
- assertEquals("2854148", result.getProviderDetails().getSupervisor().getId());
- assertEquals("David Greenwood", result.getProviderDetails().getSupervisor().getDisplayValue());
- assertEquals("2027148", result.getProviderDetails().getFeeEarner().getId());
- assertEquals("Carole Spencer", result.getProviderDetails().getFeeEarner().getDisplayValue());
- assertEquals("2027079", result.getProviderDetails().getProviderContact().getId());
- assertEquals("CAROLE.SPENCER@SWITALSKIS.COM", result.getProviderDetails().getProviderContact().getDisplayValue());
- assertEquals("AAP", result.getCategoryOfLaw().getId());
- assertEquals("Claim Against Public Authority", result.getCategoryOfLaw().getDisplayValue());
- assertNull(result.getRelationToLinkedCase());
- assertNull(result.getOpponentAppliedForFunding());
- assertEquals("Unsubmitted", result.getStatus().getDisplayValue());
- assertEquals("UNSUBMITTED", result.getStatus().getId());
- assertEquals("Phil", result.getClient().getFirstName());
- assertEquals("Payne", result.getClient().getSurname());
- assertEquals("PhilTest", result.getClient().getReference());
- assertEquals("ECF", result.getApplicationType().getId());
- assertEquals("Exceptional Case Funding", result.getApplicationType().getDisplayValue());
- }
-
- @Test
- @Sql(scripts = "/sql/application_insert.sql")
- public void testGetApplication_noData() {
- Long applicationId = 999L;
-
- // Use assertThrows to check if the method throws the expected exception
- CaabApiException exception = assertThrows(CaabApiException.class, () -> {
- applicationService.getApplicationType(applicationId);
- });
-
- assertEquals(
- String.format("Application with id %s not found", applicationId),
- exception.getMessage());
- assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
- }
-
- @Test
- @Sql(scripts = "/sql/application_insert.sql")
- public void testGetApplicationType() {
- Long applicationId = 24L;
-
- // Call the service method
- ApplicationType result = applicationService.getApplicationType(applicationId);
-
- // Assert the result
- assertNotNull(result);
-
- assertEquals("ECF", result.getId());
- assertEquals("Exceptional Case Funding", result.getDisplayValue());
- assertEquals(false, result.getDevolvedPowers().getUsed());
- assertNull(result.getDevolvedPowers().getDateUsed());
- assertEquals("Yes - Excluding JR Proceedings", result.getDevolvedPowers().getContractFlag());
- }
-
- @Test
- @Sql(scripts = "/sql/application_insert.sql")
- public void testPutApplicationType() {
- Long applicationId = 24L;
- String amendedApplicationTypeId = "APP TYPE";
- String amendedApplicationTypeDisplay = "Application Type";
-
- ApplicationType amendedApplicationType
- = new ApplicationType()
- .id(amendedApplicationTypeId)
- .displayValue(amendedApplicationTypeDisplay);
-
- // Call the service method
- applicationService.putApplicationType(applicationId, amendedApplicationType);
-
- Application result = applicationRepository.findById(applicationId).orElse(null);
-
- // Assert the result
- assertNotNull(result);
- assertEquals(amendedApplicationTypeId, result.getApplicationType());
- assertEquals(amendedApplicationTypeDisplay, result.getApplicationTypeDisplayValue());
- }
-
- @ParameterizedTest
- @CsvSource({
- "24, NewProviderCaseRef1, New Provider Display1, 12345, 67890, FeeEarnerId1, SupervisorId1, ProviderContactId1, TestUser",
- "21, NewProviderCaseRef2, New Provider Display2, 54321, 98760, FeeEarnerId2, SupervisorId2, ProviderContactId2, AnotherUser",
- "41, NewProviderCaseRef3, New Provider Display3, 13579, 24680, FeeEarnerId3, SupervisorId3, ProviderContactId3, ThirdUser"
- })
- @Sql(scripts = "/sql/application_insert.sql")
- public void testPutProviderDetails(
- Long applicationId,
- String newProviderCaseReference,
- String newProviderDisplayValue,
- Integer newProviderId,
- Integer newOfficeId,
- String newFeeEarnerId,
- String newSupervisorId,
- String newProviderContactId,
- String patchedCaabUserLoginId) {
-
- // Create an ApplicationProviderDetails instance with the provided values
- ApplicationProviderDetails providerDetails = new ApplicationProviderDetails();
- IntDisplayValue provider = new IntDisplayValue().id(newProviderId).displayValue(newProviderDisplayValue);
- IntDisplayValue office = new IntDisplayValue().id(newOfficeId);
- StringDisplayValue feeEarner = new StringDisplayValue().id(newFeeEarnerId);
- StringDisplayValue supervisor = new StringDisplayValue().id(newSupervisorId);
- StringDisplayValue providerContact = new StringDisplayValue().id(newProviderContactId);
-
- providerDetails.setProvider(provider);
- providerDetails.setProviderCaseReference(newProviderCaseReference);
- providerDetails.setOffice(office);
- providerDetails.setFeeEarner(feeEarner);
- providerDetails.setSupervisor(supervisor);
- providerDetails.setProviderContact(providerContact);
-
- currentUserHolder.set(patchedCaabUserLoginId);
-
- // Call the patchProviderDetails method
- applicationService.putProviderDetails(applicationId, providerDetails);
-
- // Fetch the application from the database after the update
- Application updatedApplication = applicationRepository.findById(applicationId).orElse(null);
-
- // Assert that the updated application has the expected provider details
- assertNotNull(updatedApplication);
- assertEquals(newProviderCaseReference, updatedApplication.getProviderCaseReference());
- assertEquals(newProviderDisplayValue, updatedApplication.getProviderDisplayValue());
-
- // Assert for other provider details
- assertEquals(provider.getId().toString(), updatedApplication.getProviderId());
- assertEquals(office.getId().toString(), updatedApplication.getOfficeId().toString());
- assertEquals(feeEarner.getId(), updatedApplication.getFeeEarner());
- assertEquals(supervisor.getId(), updatedApplication.getSupervisor());
- assertEquals(providerContact.getId(), updatedApplication.getProviderContact());
-
- assertEquals(patchedCaabUserLoginId, updatedApplication.getAuditTrail().getLastSavedBy());
- assertTrue(updatedApplication.getAuditTrail().getLastSaved().after(updatedApplication.getAuditTrail().getCreated()));
- }
-
- @Test
- @Sql(scripts = "/sql/application_insert.sql")
- public void testPutProviderDetails_ApplicationNotFound() {
- Long nonExistentApplicationId = 999L;
-
- ApplicationProviderDetails providerDetails = new ApplicationProviderDetails();
-
- // Use assertThrows to check if the method throws the expected exception
- CaabApiException exception = assertThrows(CaabApiException.class, () -> {
- applicationService.putProviderDetails(nonExistentApplicationId, providerDetails);
- });
-
- assertEquals(
- String.format("Application with id %s not found", nonExistentApplicationId),
- exception.getMessage());
- assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
- }
-
-
- private ApplicationDetail buildRequiredApplicationDetail() {
- ApplicationDetail application = new ApplicationDetail();
- application.setCaseReferenceNumber(lscCaseReference);
- application.setProviderDetails(new ApplicationProviderDetails().provider(new IntDisplayValue().id(providerId)));
- application.setCategoryOfLaw(new StringDisplayValue().id(categoryOfLaw));
- application.setClient(new Client().reference(clientReference));
- return application;
- }
-
- private ApplicationDetail buildApplication(){
- ApplicationDetail application = buildRequiredApplicationDetail();
- //provider details
- ApplicationProviderDetails providerDetails = application.getProviderDetails();
- providerDetails.setProviderCaseReference(providerCaseReference);
- providerDetails.getProvider().setDisplayValue(providerDisplayValue);
- providerDetails.setOffice(new IntDisplayValue()
- .id(officeId)
- .displayValue(officeDisplayValue));
- providerDetails.setSupervisor(new StringDisplayValue()
- .id(supervisor)
- .displayValue(supervisorDisplayValue));
- providerDetails.setFeeEarner(new StringDisplayValue()
- .id(feeEarner)
- .displayValue(feeEarnerDisplayValue));
- providerDetails.setProviderContact(new StringDisplayValue()
- .id(providerContact)
- .displayValue(providerContactDisplayValue));
-
- //category of law
- application.getCategoryOfLaw().setDisplayValue(categoryOfLawDisplayValue);
-
- application.setRelationToLinkedCase(relationToLinkedCase);
- application.setOpponentAppliedForFunding(opponentAppliedForFunding);
-
- StringDisplayValue statusObj = new StringDisplayValue()
- .id(actualStatus)
- .displayValue(displayStatus);
- application.setStatus(statusObj);
-
- Client clientObj = new Client()
- .reference(clientReference)
- .firstName(clientFirstName)
- .surname(clientSurname);
- application.setClient(clientObj);
-
- application.setAmendment(amendment);
- application.setMeansAssessmentAmended(meansAssessmentAmended);
- application.setMeritsAssessmentAmended(meritsAssessmentAmended);
- CostLimit costLimitObj = new CostLimit()
- .changed(costLimitChanged)
- .limitAtTimeOfMerits(costLimitAtTimeOfMerits);
- application.setCostLimit(costLimitObj);
-
- DevolvedPowers devolvedPowersObj = new DevolvedPowers()
- .used(devolvedPowersUsed)
- .dateUsed(dateDevolvedPowersUsed)
- .contractFlag(devolvedPowersContractFlag);
- ApplicationType applicationTypeObj = new ApplicationType()
- .id(applicationType)
- .displayValue(applicationTypeDisplayValue)
- .devolvedPowers(devolvedPowersObj);
- application.setApplicationType(applicationTypeObj);
-
- application.setMeritsReassessmentRequired(meritsReassessmentReqdInd);
- application.setLarScopeFlag(larScopeFlag);
- application.setLeadProceedingChanged(leadProceedingChanged);
-
- return application;
- }
-
- private CostStructure buildCosts(){
- CostStructure costs = new CostStructure();
- costs.setDefaultCostLimitation(defaultCostLimitation);
- costs.setGrantedCostLimitation(grantedCostLimitation);
- costs.setRequestedCostLimitation(requestedCostLimitation);
- return costs;
- }
-
- private Address buildAddress(){
- Address address = new Address();
- address.setNoFixedAbode(noFixedAbode);
- address.setPostcode(postCode);
- address.setHouseNameOrNumber(houseNameNumber);
- address.setAddressLine1(addressLine1);
- address.setAddressLine2(addressLine2);
- address.setCity(city);
- address.setCounty(county);
- address.setCountry(country);
- address.setCareOf(careOf);
- address.setPreferredAddress(preferredAddress);
- return address;
- }
-
-
+public class ApplicationServiceIntegrationTest extends
+ BaseApplicationServiceIntegrationTest implements
+ IntegrationTestInterface {
+ //this runs all tests in BaseApplicationServiceIntegrationTest, do not add anything here
+ //running this class takes longer than the local version, but it is used for running tests in a pipeline
}
diff --git a/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/service/BaseApplicationServiceIntegrationTest.java b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/service/BaseApplicationServiceIntegrationTest.java
new file mode 100644
index 0000000..2110f08
--- /dev/null
+++ b/caab-service/src/integrationTest/java/uk/gov/laa/ccms/data/api/service/BaseApplicationServiceIntegrationTest.java
@@ -0,0 +1,500 @@
+package uk.gov.laa.ccms.data.api.service;
+
+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.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static uk.gov.laa.ccms.caab.api.audit.AuditorAwareImpl.currentUserHolder;
+
+import jakarta.transaction.Transactional;
+import java.math.BigDecimal;
+import java.text.SimpleDateFormat;
+import java.time.Instant;
+import java.util.Date;
+import java.util.TimeZone;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.test.context.jdbc.Sql;
+import uk.gov.laa.ccms.caab.api.entity.Application;
+import uk.gov.laa.ccms.caab.api.exception.CaabApiException;
+import uk.gov.laa.ccms.caab.api.repository.ApplicationRepository;
+import uk.gov.laa.ccms.caab.api.service.ApplicationService;
+import uk.gov.laa.ccms.caab.model.Address;
+import uk.gov.laa.ccms.caab.model.ApplicationDetail;
+import uk.gov.laa.ccms.caab.model.ApplicationProviderDetails;
+import uk.gov.laa.ccms.caab.model.ApplicationType;
+import uk.gov.laa.ccms.caab.model.Client;
+import uk.gov.laa.ccms.caab.model.CostLimit;
+import uk.gov.laa.ccms.caab.model.CostStructure;
+import uk.gov.laa.ccms.caab.model.DevolvedPowers;
+import uk.gov.laa.ccms.caab.model.IntDisplayValue;
+import uk.gov.laa.ccms.caab.model.StringDisplayValue;
+
+public abstract class BaseApplicationServiceIntegrationTest {
+
+ @Autowired
+ private ApplicationService applicationService;
+ @Autowired
+ private ApplicationRepository applicationRepository;
+ private final String lscCaseReference = "LSC001";
+ private final Integer providerId = 123456;
+ private final String providerCaseReference = "PRD_CASE_REF_001";
+ private final String providerDisplayValue = "Provider Display";
+ private final Integer officeId = 987;
+ private final String officeDisplayValue = "Office Display";
+ private final String supervisor = "Supervisor1";
+ private final String supervisorDisplayValue = "Supervisor Display";
+ private final String feeEarner = "Fee Earner";
+ private final String feeEarnerDisplayValue = "Fee Earner Display";
+ private final String providerContact = "Provider Contact";
+ private final String providerContactDisplayValue = "Provider Contact Display";
+ private final String categoryOfLaw = "Category of Law";
+ private final String categoryOfLawDisplayValue = "Category of Law Display";
+ private final String relationToLinkedCase = "Relation to Linked Case";
+ private final Boolean opponentAppliedForFunding = false;
+ private final String displayStatus = "Display Status";
+ private final String actualStatus = "Actual Status";
+ private final String clientFirstName = "Client First Name";
+ private final String clientSurname = "Client Surname";
+ private final String clientReference = "Client Reference";
+ private final Boolean amendment = false;
+ private final Boolean meansAssessmentAmended = false;
+ private final Boolean meritsAssessmentAmended = false;
+ private final Boolean costLimitChanged = false;
+ private final BigDecimal costLimitAtTimeOfMerits = BigDecimal.valueOf(10000);
+ private final String applicationType = "Application Type";
+ private final String applicationTypeDisplayValue = "Application Type Display";
+ private final Boolean devolvedPowersUsed = false;
+ private final Date dateDevolvedPowersUsed = Date.from(Instant.now());
+ private final String devolvedPowersContractFlag = "Devolved Powers Contract Flag";
+ private final Boolean meritsReassessmentReqdInd = false;
+ private final Boolean larScopeFlag = true;
+ private final Boolean leadProceedingChanged = false;
+
+ //cost structure
+ private final BigDecimal defaultCostLimitation = BigDecimal.valueOf(11111.11);
+ private final BigDecimal grantedCostLimitation = BigDecimal.valueOf(22222.22);
+ private final BigDecimal requestedCostLimitation = BigDecimal.valueOf(33333.33);
+
+ //Address
+ private final boolean noFixedAbode = false;
+ private final String postCode = "SW1A 1AA";
+ private final String houseNameNumber = "10";
+ private final String addressLine1 = "Downing Street";
+ private final String addressLine2 = "Westminster";
+ private final String city = "London";
+ private final String county = "Greater London";
+ private final String country = "GBR";
+ private final String careOf = "Prime Minister's Office";
+ private final String preferredAddress = "PROVIDER";
+
+ private final String caabUserLoginId = "audit@user.com";
+
+ @BeforeEach
+ public void setup() {
+ currentUserHolder.set(caabUserLoginId);
+ }
+
+ @Test
+ public void testSaveApplication_requiredFields(){
+ ApplicationDetail application = buildRequiredApplicationDetail();
+
+ Long savedId = applicationService.createApplication(application);
+
+ // Assert that the saved application has been assigned an ID
+ assertNotNull(savedId);
+
+ // Fetch the saved application from the database
+ Application fetchedApplication = applicationRepository.findById(savedId)
+ .orElse(null);
+
+ // Assert that the fetched application is not null and has the expected values
+ assertNotNull(fetchedApplication);
+ assertEquals(lscCaseReference, fetchedApplication.getLscCaseReference());
+ assertEquals(providerId.toString(), fetchedApplication.getProviderId());
+ assertEquals(categoryOfLaw, fetchedApplication.getCategoryOfLaw());
+ assertEquals(clientReference, fetchedApplication.getClientReference());
+ }
+
+ @Test
+ public void testSaveApplication_allFields(){
+ ApplicationDetail application = buildApplication();
+
+ Long savedId = applicationService.createApplication(application);
+
+ // Assert that the saved application has been assigned an ID
+ assertNotNull(savedId);
+
+ // Fetch the saved application from the database
+ Application fetchedApplication = applicationRepository.findById(savedId).orElse(null);
+
+ // Assert that the fetched application is not null and has the expected values
+ assertNotNull(fetchedApplication);
+ assertEquals(lscCaseReference, fetchedApplication.getLscCaseReference());
+ assertEquals(providerId.toString(), fetchedApplication.getProviderId());
+ assertEquals(providerCaseReference, fetchedApplication.getProviderCaseReference());
+ assertEquals(providerDisplayValue, fetchedApplication.getProviderDisplayValue());
+ assertEquals(officeId, fetchedApplication.getOfficeId().intValue());
+ assertEquals(officeDisplayValue, fetchedApplication.getOfficeDisplayValue());
+ assertEquals(supervisor, fetchedApplication.getSupervisor());
+ assertEquals(supervisorDisplayValue, fetchedApplication.getSupervisorDisplayValue());
+ assertEquals(feeEarner, fetchedApplication.getFeeEarner());
+ assertEquals(feeEarnerDisplayValue, fetchedApplication.getFeeEarnerDisplayValue());
+ assertEquals(providerContact, fetchedApplication.getProviderContact());
+ assertEquals(providerContactDisplayValue, fetchedApplication.getProviderContactDisplayValue());
+ assertEquals(categoryOfLaw, fetchedApplication.getCategoryOfLaw());
+ assertEquals(categoryOfLawDisplayValue, fetchedApplication.getCategoryOfLawDisplayValue());
+ assertEquals(relationToLinkedCase, fetchedApplication.getRelationToLinkedCase());
+ assertEquals(opponentAppliedForFunding, fetchedApplication.getOpponentAppliedForFunding());
+ assertEquals(displayStatus, fetchedApplication.getDisplayStatus());
+ assertEquals(actualStatus, fetchedApplication.getActualStatus());
+ assertEquals(clientFirstName, fetchedApplication.getClientFirstName());
+ assertEquals(clientSurname, fetchedApplication.getClientSurname());
+ assertEquals(clientReference, fetchedApplication.getClientReference());
+ assertEquals(amendment, fetchedApplication.isAmendment());
+ assertEquals(meansAssessmentAmended, fetchedApplication.isMeansAssessmentAmended());
+ assertEquals(meritsAssessmentAmended, fetchedApplication.isMeritsAssessmentAmended());
+ assertEquals(costLimitChanged, fetchedApplication.isCostLimitChanged());
+ assertEquals(costLimitAtTimeOfMerits, fetchedApplication.getCostLimitAtTimeOfMerits());
+ assertEquals(applicationType, fetchedApplication.getApplicationType());
+ assertEquals(applicationTypeDisplayValue, fetchedApplication.getApplicationTypeDisplayValue());
+ assertEquals(devolvedPowersUsed, fetchedApplication.getDevolvedPowersUsed());
+
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ sdf.setTimeZone(TimeZone.getTimeZone("BST"));
+ assertEquals(sdf.format(dateDevolvedPowersUsed), sdf.format(fetchedApplication.getDateDevolvedPowersUsed()));
+
+ assertEquals(devolvedPowersContractFlag, fetchedApplication.getDevolvedPowersContractFlag());
+ assertEquals(meritsReassessmentReqdInd, fetchedApplication.isMeritsReassessmentReqdInd());
+ assertEquals(larScopeFlag, fetchedApplication.getLarScopeFlag());
+ assertEquals(leadProceedingChanged, fetchedApplication.isLeadProceedingChangedOpaInput());
+
+ assertEquals(caabUserLoginId, fetchedApplication.getAuditTrail().getLastSavedBy());
+ assertEquals(caabUserLoginId, fetchedApplication.getAuditTrail().getCreatedBy());
+ assertNotNull(fetchedApplication.getAuditTrail().getCreated());
+ assertNotNull(fetchedApplication.getAuditTrail().getLastSaved());
+
+ }
+
+ @Test
+ @Transactional
+ public void testSaveApplication_costStructure(){
+
+ ApplicationDetail application = buildRequiredApplicationDetail();
+ application.setCosts(buildCosts());
+
+ Long savedId = applicationService.createApplication(application);
+
+ // Fetch the saved application from the database
+ Application fetchedApplication = applicationRepository.findById(savedId).orElse(null);
+
+ // Assert that the fetched application is not null and has the expected values
+ assertNotNull(fetchedApplication);
+ assertNotNull(fetchedApplication.getCosts());
+ assertEquals(defaultCostLimitation, fetchedApplication.getCosts().getDefaultCostLimitation());
+ assertEquals(grantedCostLimitation, fetchedApplication.getCosts().getGrantedCostLimitation());
+ assertEquals(requestedCostLimitation, fetchedApplication.getCosts().getRequestedCostLimitation());
+
+ assertEquals(caabUserLoginId, fetchedApplication.getCosts().getAuditTrail().getLastSavedBy());
+ assertEquals(caabUserLoginId, fetchedApplication.getCosts().getAuditTrail().getCreatedBy());
+ }
+
+ @Test
+ @Transactional
+ public void testSaveApplication_address(){
+ ApplicationDetail application = buildRequiredApplicationDetail();
+ application.setCorrespondenceAddress(buildAddress());
+
+ Long savedId = applicationService.createApplication(application);
+
+ // Fetch the saved application from the database
+ Application fetchedApplication = applicationRepository.findById(savedId).orElse(null);
+
+ // Assert that the fetched application is not null and has the expected values
+ assertNotNull(fetchedApplication);
+ assertNotNull(fetchedApplication.getCorrespondenceAddress());
+
+ // Assert the properties of the correspondence address
+ assertEquals(noFixedAbode, fetchedApplication.getCorrespondenceAddress().getNoFixedAbode());
+ assertEquals(postCode, fetchedApplication.getCorrespondenceAddress().getPostCode());
+ assertEquals(houseNameNumber, fetchedApplication.getCorrespondenceAddress().getHouseNameNumber());
+ assertEquals(addressLine1, fetchedApplication.getCorrespondenceAddress().getAddressLine1());
+ assertEquals(addressLine2, fetchedApplication.getCorrespondenceAddress().getAddressLine2());
+ assertEquals(city, fetchedApplication.getCorrespondenceAddress().getCity());
+ assertEquals(county, fetchedApplication.getCorrespondenceAddress().getCounty());
+ assertEquals(country, fetchedApplication.getCorrespondenceAddress().getCountry());
+ assertEquals(careOf, fetchedApplication.getCorrespondenceAddress().getCareOf());
+ assertEquals(preferredAddress, fetchedApplication.getCorrespondenceAddress().getPreferredAddress());
+
+ // Audit Trail asserts for the address
+ assertEquals(caabUserLoginId, fetchedApplication.getCorrespondenceAddress().getAuditTrail().getLastSavedBy());
+ assertEquals(caabUserLoginId, fetchedApplication.getCorrespondenceAddress().getAuditTrail().getCreatedBy());
+ }
+
+ @Test
+ @Transactional
+ @Sql(scripts = "/sql/application_insert.sql")
+ public void testGetApplication() {
+ Long applicationId = 24L;
+
+ ApplicationDetail result = applicationService.getApplication(applicationId);
+
+ // Assert the result
+ assertNotNull(result);
+
+ assertEquals("300001644517", result.getCaseReferenceNumber());
+ assertEquals(26517, result.getProviderDetails().getProvider().getId());
+ assertEquals("329635", result.getProviderDetails().getProviderCaseReference());
+ assertEquals("SWITALSKI'S SOLICITORS LTD", result.getProviderDetails().getProvider().getDisplayValue());
+ assertEquals(145512, result.getProviderDetails().getOffice().getId());
+ assertEquals("SWITALSKI'S SOLICITORS LTD-2L847Q", result.getProviderDetails().getOffice().getDisplayValue());
+ assertEquals("2854148", result.getProviderDetails().getSupervisor().getId());
+ assertEquals("David Greenwood", result.getProviderDetails().getSupervisor().getDisplayValue());
+ assertEquals("2027148", result.getProviderDetails().getFeeEarner().getId());
+ assertEquals("Carole Spencer", result.getProviderDetails().getFeeEarner().getDisplayValue());
+ assertEquals("2027079", result.getProviderDetails().getProviderContact().getId());
+ assertEquals("CAROLE.SPENCER@SWITALSKIS.COM", result.getProviderDetails().getProviderContact().getDisplayValue());
+ assertEquals("AAP", result.getCategoryOfLaw().getId());
+ assertEquals("Claim Against Public Authority", result.getCategoryOfLaw().getDisplayValue());
+ assertNull(result.getRelationToLinkedCase());
+ assertNull(result.getOpponentAppliedForFunding());
+ assertEquals("Unsubmitted", result.getStatus().getDisplayValue());
+ assertEquals("UNSUBMITTED", result.getStatus().getId());
+ assertEquals("Phil", result.getClient().getFirstName());
+ assertEquals("Payne", result.getClient().getSurname());
+ assertEquals("PhilTest", result.getClient().getReference());
+ assertEquals("ECF", result.getApplicationType().getId());
+ assertEquals("Exceptional Case Funding", result.getApplicationType().getDisplayValue());
+ }
+
+ @Test
+ @Sql(scripts = "/sql/application_insert.sql")
+ public void testGetApplication_noData() {
+ Long applicationId = 999L;
+
+ // Use assertThrows to check if the method throws the expected exception
+ CaabApiException exception = assertThrows(CaabApiException.class, () -> {
+ applicationService.getApplicationType(applicationId);
+ });
+
+ assertEquals(
+ String.format("Application with id %s not found", applicationId),
+ exception.getMessage());
+ assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
+ }
+
+ @Test
+ @Sql(scripts = "/sql/application_insert.sql")
+ public void testGetApplicationType() {
+ Long applicationId = 24L;
+
+ // Call the service method
+ ApplicationType result = applicationService.getApplicationType(applicationId);
+
+ // Assert the result
+ assertNotNull(result);
+
+ assertEquals("ECF", result.getId());
+ assertEquals("Exceptional Case Funding", result.getDisplayValue());
+ assertEquals(false, result.getDevolvedPowers().getUsed());
+ assertNull(result.getDevolvedPowers().getDateUsed());
+ assertEquals("Yes - Excluding JR Proceedings", result.getDevolvedPowers().getContractFlag());
+ }
+
+ @Test
+ @Sql(scripts = "/sql/application_insert.sql")
+ public void testPutApplicationType() {
+ Long applicationId = 24L;
+ String amendedApplicationTypeId = "APP TYPE";
+ String amendedApplicationTypeDisplay = "Application Type";
+
+ ApplicationType amendedApplicationType
+ = new ApplicationType()
+ .id(amendedApplicationTypeId)
+ .displayValue(amendedApplicationTypeDisplay);
+
+ // Call the service method
+ applicationService.putApplicationType(applicationId, amendedApplicationType);
+
+ Application result = applicationRepository.findById(applicationId).orElse(null);
+
+ // Assert the result
+ assertNotNull(result);
+ assertEquals(amendedApplicationTypeId, result.getApplicationType());
+ assertEquals(amendedApplicationTypeDisplay, result.getApplicationTypeDisplayValue());
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "24, NewProviderCaseRef1, New Provider Display1, 12345, 67890, FeeEarnerId1, SupervisorId1, ProviderContactId1, TestUser",
+ "21, NewProviderCaseRef2, New Provider Display2, 54321, 98760, FeeEarnerId2, SupervisorId2, ProviderContactId2, AnotherUser",
+ "41, NewProviderCaseRef3, New Provider Display3, 13579, 24680, FeeEarnerId3, SupervisorId3, ProviderContactId3, ThirdUser"
+ })
+ @Sql(scripts = "/sql/application_insert.sql")
+ public void testPutProviderDetails(
+ Long applicationId,
+ String newProviderCaseReference,
+ String newProviderDisplayValue,
+ Integer newProviderId,
+ Integer newOfficeId,
+ String newFeeEarnerId,
+ String newSupervisorId,
+ String newProviderContactId,
+ String patchedCaabUserLoginId) {
+
+ // Create an ApplicationProviderDetails instance with the provided values
+ ApplicationProviderDetails providerDetails = new ApplicationProviderDetails();
+ IntDisplayValue provider = new IntDisplayValue().id(newProviderId).displayValue(newProviderDisplayValue);
+ IntDisplayValue office = new IntDisplayValue().id(newOfficeId);
+ StringDisplayValue feeEarner = new StringDisplayValue().id(newFeeEarnerId);
+ StringDisplayValue supervisor = new StringDisplayValue().id(newSupervisorId);
+ StringDisplayValue providerContact = new StringDisplayValue().id(newProviderContactId);
+
+ providerDetails.setProvider(provider);
+ providerDetails.setProviderCaseReference(newProviderCaseReference);
+ providerDetails.setOffice(office);
+ providerDetails.setFeeEarner(feeEarner);
+ providerDetails.setSupervisor(supervisor);
+ providerDetails.setProviderContact(providerContact);
+
+ currentUserHolder.set(patchedCaabUserLoginId);
+
+ // Call the patchProviderDetails method
+ applicationService.putProviderDetails(applicationId, providerDetails);
+
+ // Fetch the application from the database after the update
+ Application updatedApplication = applicationRepository.findById(applicationId).orElse(null);
+
+ // Assert that the updated application has the expected provider details
+ assertNotNull(updatedApplication);
+ assertEquals(newProviderCaseReference, updatedApplication.getProviderCaseReference());
+ assertEquals(newProviderDisplayValue, updatedApplication.getProviderDisplayValue());
+
+ // Assert for other provider details
+ assertEquals(provider.getId().toString(), updatedApplication.getProviderId());
+ assertEquals(office.getId().toString(), updatedApplication.getOfficeId().toString());
+ assertEquals(feeEarner.getId(), updatedApplication.getFeeEarner());
+ assertEquals(supervisor.getId(), updatedApplication.getSupervisor());
+ assertEquals(providerContact.getId(), updatedApplication.getProviderContact());
+
+ assertEquals(patchedCaabUserLoginId, updatedApplication.getAuditTrail().getLastSavedBy());
+ assertTrue(updatedApplication.getAuditTrail().getLastSaved().after(updatedApplication.getAuditTrail().getCreated()));
+ }
+
+ @Test
+ @Sql(scripts = "/sql/application_insert.sql")
+ public void testPutProviderDetails_ApplicationNotFound() {
+ Long nonExistentApplicationId = 999L;
+
+ ApplicationProviderDetails providerDetails = new ApplicationProviderDetails();
+
+ // Use assertThrows to check if the method throws the expected exception
+ CaabApiException exception = assertThrows(CaabApiException.class, () -> {
+ applicationService.putProviderDetails(nonExistentApplicationId, providerDetails);
+ });
+
+ assertEquals(
+ String.format("Application with id %s not found", nonExistentApplicationId),
+ exception.getMessage());
+ assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
+ }
+
+
+ private ApplicationDetail buildRequiredApplicationDetail() {
+ ApplicationDetail application = new ApplicationDetail();
+ application.setCaseReferenceNumber(lscCaseReference);
+ application.setProviderDetails(new ApplicationProviderDetails().provider(new IntDisplayValue().id(providerId)));
+ application.setCategoryOfLaw(new StringDisplayValue().id(categoryOfLaw));
+ application.setClient(new Client().reference(clientReference));
+ return application;
+ }
+
+ private ApplicationDetail buildApplication(){
+ ApplicationDetail application = buildRequiredApplicationDetail();
+ //provider details
+ ApplicationProviderDetails providerDetails = application.getProviderDetails();
+ providerDetails.setProviderCaseReference(providerCaseReference);
+ providerDetails.getProvider().setDisplayValue(providerDisplayValue);
+ providerDetails.setOffice(new IntDisplayValue()
+ .id(officeId)
+ .displayValue(officeDisplayValue));
+ providerDetails.setSupervisor(new StringDisplayValue()
+ .id(supervisor)
+ .displayValue(supervisorDisplayValue));
+ providerDetails.setFeeEarner(new StringDisplayValue()
+ .id(feeEarner)
+ .displayValue(feeEarnerDisplayValue));
+ providerDetails.setProviderContact(new StringDisplayValue()
+ .id(providerContact)
+ .displayValue(providerContactDisplayValue));
+
+ //category of law
+ application.getCategoryOfLaw().setDisplayValue(categoryOfLawDisplayValue);
+
+ application.setRelationToLinkedCase(relationToLinkedCase);
+ application.setOpponentAppliedForFunding(opponentAppliedForFunding);
+
+ StringDisplayValue statusObj = new StringDisplayValue()
+ .id(actualStatus)
+ .displayValue(displayStatus);
+ application.setStatus(statusObj);
+
+ Client clientObj = new Client()
+ .reference(clientReference)
+ .firstName(clientFirstName)
+ .surname(clientSurname);
+ application.setClient(clientObj);
+
+ application.setAmendment(amendment);
+ application.setMeansAssessmentAmended(meansAssessmentAmended);
+ application.setMeritsAssessmentAmended(meritsAssessmentAmended);
+ CostLimit costLimitObj = new CostLimit()
+ .changed(costLimitChanged)
+ .limitAtTimeOfMerits(costLimitAtTimeOfMerits);
+ application.setCostLimit(costLimitObj);
+
+ DevolvedPowers devolvedPowersObj = new DevolvedPowers()
+ .used(devolvedPowersUsed)
+ .dateUsed(dateDevolvedPowersUsed)
+ .contractFlag(devolvedPowersContractFlag);
+ ApplicationType applicationTypeObj = new ApplicationType()
+ .id(applicationType)
+ .displayValue(applicationTypeDisplayValue)
+ .devolvedPowers(devolvedPowersObj);
+ application.setApplicationType(applicationTypeObj);
+
+ application.setMeritsReassessmentRequired(meritsReassessmentReqdInd);
+ application.setLarScopeFlag(larScopeFlag);
+ application.setLeadProceedingChanged(leadProceedingChanged);
+
+ return application;
+ }
+
+ private CostStructure buildCosts(){
+ CostStructure costs = new CostStructure();
+ costs.setDefaultCostLimitation(defaultCostLimitation);
+ costs.setGrantedCostLimitation(grantedCostLimitation);
+ costs.setRequestedCostLimitation(requestedCostLimitation);
+ return costs;
+ }
+
+ private Address buildAddress(){
+ Address address = new Address();
+ address.setNoFixedAbode(noFixedAbode);
+ address.setPostcode(postCode);
+ address.setHouseNameOrNumber(houseNameNumber);
+ address.setAddressLine1(addressLine1);
+ address.setAddressLine2(addressLine2);
+ address.setCity(city);
+ address.setCounty(county);
+ address.setCountry(country);
+ address.setCareOf(careOf);
+ address.setPreferredAddress(preferredAddress);
+ return address;
+ }
+}
diff --git a/caab-service/src/integrationTest/resources/json/base_client_new.json b/caab-service/src/integrationTest/resources/json/base_client_new.json
new file mode 100644
index 0000000..5193f5e
--- /dev/null
+++ b/caab-service/src/integrationTest/resources/json/base_client_new.json
@@ -0,0 +1,4 @@
+{
+ "first_name": "test name",
+ "surname": "test"
+}
\ No newline at end of file
diff --git a/caab-service/src/integrationTest/resources/json/linked_cases_new.json b/caab-service/src/integrationTest/resources/json/linked_cases_new.json
new file mode 100644
index 0000000..e77c2e8
--- /dev/null
+++ b/caab-service/src/integrationTest/resources/json/linked_cases_new.json
@@ -0,0 +1,13 @@
+{
+ "lsc_case_reference": "BLAH123456",
+ "relation_to_case": "Relation to Case Example",
+ "client": {
+ "first_name": "BLAH",
+ "surname": "BLAH",
+ "reference": "1234"
+ },
+ "provider_case_reference": "BLAH123",
+ "category_of_law": "Category of Law Example",
+ "fee_earner": "Fee Earner Name",
+ "status": "Active"
+}
\ No newline at end of file
diff --git a/caab-service/src/integrationTest/resources/json/prior_authority_new.json b/caab-service/src/integrationTest/resources/json/prior_authority_new.json
new file mode 100644
index 0000000..fe1d7a5
--- /dev/null
+++ b/caab-service/src/integrationTest/resources/json/prior_authority_new.json
@@ -0,0 +1,14 @@
+{
+ "id": null,
+ "ebs_id": null,
+ "status": null,
+ "type": {
+ "id": null,
+ "display_value": null
+ },
+ "summary": null,
+ "justification": null,
+ "value_required": null,
+ "amount_requested": null,
+ "items": []
+}
\ No newline at end of file
diff --git a/caab-service/src/integrationTest/resources/json/proceeding_new.json b/caab-service/src/integrationTest/resources/json/proceeding_new.json
new file mode 100644
index 0000000..ab54984
--- /dev/null
+++ b/caab-service/src/integrationTest/resources/json/proceeding_new.json
@@ -0,0 +1,61 @@
+{
+ "ebs_id": null,
+ "matter_type": {
+ "id": "KPBLB",
+ "display_value": "Pub Law - Fam"
+ },
+ "proceeding_type": {
+ "id": "PBM32",
+ "display_value": "Special Guardianship Order - Pub Law - Fam"
+ },
+ "level_of_service": {
+ "id": "3",
+ "display_value": "Full Representation"
+ },
+ "client_involvement": {
+ "id": "W",
+ "display_value": "Subject of proceedings (child)"
+ },
+ "type_of_order": {
+ "id": null,
+ "display_value": null
+ },
+ "cost_limitation": 5000,
+ "status": {
+ "id": "Draft",
+ "display_value": "Unchanged"
+ },
+ "description": "Special Guardianship Order - Pub Law - Fam",
+ "date_granted": null,
+ "date_costs_valid": null,
+ "edited": false,
+ "scope_limitations": [
+ {
+ "scope_limitation": {
+ "id": "FM062",
+ "display_value": "Final Hearing (fam/public law)"
+ },
+ "ebs_id": null,
+ "scope_limitation_wording": "Limited to all steps up to and including final hearing and any action necessary to implement (but not enforce) the order.",
+ "default_ind": false,
+ "delegated_func_apply_ind": {
+ "flag": false,
+ "display_value": null
+ },
+ "non_default_wording_reqd": null,
+ "stage": null
+ }
+ ],
+ "default_scope_limitation": null,
+ "stage": "8",
+ "lead_proceeding_ind": false,
+ "lar_scope": "I",
+ "granted_using_devolved_powers": null,
+ "date_devolved_powers_used": null,
+ "proceeding_case_id": null,
+ "outcome": null,
+ "order_type_req_flag": null,
+ "order_type_display_flag": null,
+ "delete_scope_limitation_flag": null,
+ "available_functions": null
+}
\ No newline at end of file
diff --git a/caab-service/src/integrationTest/resources/json/scope_limitation_new.json b/caab-service/src/integrationTest/resources/json/scope_limitation_new.json
new file mode 100644
index 0000000..b322576
--- /dev/null
+++ b/caab-service/src/integrationTest/resources/json/scope_limitation_new.json
@@ -0,0 +1,15 @@
+{
+ "scope_limitation": {
+ "id": "FM062",
+ "display_value": "Final Hearing (fam/public law)"
+ },
+ "ebs_id": null,
+ "scope_limitation_wording": "Limited to all steps up to and including final hearing and any action necessary to implement (but not enforce) the order.",
+ "default_ind": false,
+ "delegated_func_apply_ind": {
+ "flag": false,
+ "display_value": null
+ },
+ "non_default_wording_reqd": null,
+ "stage": null
+}
\ No newline at end of file
diff --git a/caab-service/src/integrationTest/resources/sql/cost_structure_insert.sql b/caab-service/src/integrationTest/resources/sql/cost_structure_insert.sql
new file mode 100644
index 0000000..e69de29
diff --git a/caab-service/src/integrationTest/resources/sql/delete_data.sql b/caab-service/src/integrationTest/resources/sql/delete_data.sql
new file mode 100644
index 0000000..cf5de6c
--- /dev/null
+++ b/caab-service/src/integrationTest/resources/sql/delete_data.sql
@@ -0,0 +1,24 @@
+-- Clear XXCCMS_REFERENCE_DATA_ITEM
+DELETE FROM XXCCMS_REFERENCE_DATA_ITEM;
+-- Clear XXCCMS_SCOPE_LIMITATION
+DELETE FROM XXCCMS_SCOPE_LIMITATION;
+-- Clear XXCCMS_PROCEEDING_OUTCOME
+DELETE FROM XXCCMS_PROCEEDING_OUTCOME;
+-- Clear XXCCMS_PROCEEDING
+DELETE FROM XXCCMS_PROCEEDING;
+-- Clear XXCCMS_PRIOR_AUTHORITY
+DELETE FROM XXCCMS_PRIOR_AUTHORITY;
+-- Clear XXCCMS_OPPONENT
+DELETE FROM XXCCMS_OPPONENT;
+-- Clear XXCCMS_CASE_OUTCOME
+DELETE FROM XXCCMS_CASE_OUTCOME;
+-- Clear XXCCMS_LINKED_CASE
+DELETE FROM XXCCMS_LINKED_CASE;
+-- Clear XXCCMS_COST_ENTRY
+DELETE FROM XXCCMS_COST_ENTRY;
+-- Clear XXCCMS_APPLICATION
+DELETE FROM XXCCMS_APPLICATION;
+-- Clear XXCCMS_COST_STRUCTURE
+DELETE FROM XXCCMS_COST_STRUCTURE;
+-- Clear XXCCMS_ADDRESS
+DELETE FROM XXCCMS_ADDRESS;
diff --git a/caab-service/src/integrationTest/resources/sql/linked_cases_insert.sql b/caab-service/src/integrationTest/resources/sql/linked_cases_insert.sql
new file mode 100644
index 0000000..aed97bc
--- /dev/null
+++ b/caab-service/src/integrationTest/resources/sql/linked_cases_insert.sql
@@ -0,0 +1,3 @@
+INSERT INTO XXCCMS_LINKED_CASE
+(ID, LSC_CASE_REFERENCE, PROVIDER_CASE_REFERENCE, FEE_EARNER, CLIENT_FIRST_NAME, CLIENT_SURNAME, CLIENT_REFERENCE, CATEGORY_OF_LAW, RELATION_TO_LINKED_CASE, STATUS, FK_APPLICATION, CREATED, CREATED_BY, MODIFIED, MODIFIED_BY)
+VALUES(2, 'BLAH123456', 'BLAH123', 'Fee Earner Name', 'BLAH', 'BLAH', 'BLAH', 'Category of Law Example', 'Relation to Case Example', 'Active', 41, TIMESTAMP '2024-01-15 10:18:39.961000', 'TEST', TIMESTAMP '2024-01-15 10:18:39.961000', 'TEST');
\ No newline at end of file
diff --git a/caab-service/src/integrationTest/resources/sql/prior_authority_insert.sql b/caab-service/src/integrationTest/resources/sql/prior_authority_insert.sql
new file mode 100644
index 0000000..a64a011
--- /dev/null
+++ b/caab-service/src/integrationTest/resources/sql/prior_authority_insert.sql
@@ -0,0 +1,3 @@
+INSERT INTO XXCCMS_PRIOR_AUTHORITY
+(ID, EBS_ID, "TYPE", TYPE_DISPLAY_VALUE, SUMMARY, JUSTIFICATION, VALUE_REQUIRED_FLAG, AMOUNT_REQUESTED, STATUS, FK_APPLICATION, CREATED, CREATED_BY, MODIFIED, MODIFIED_BY)
+VALUES(2, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'Draft', 41, TIMESTAMP '2024-01-15 14:43:13.902000', 'TEST', TIMESTAMP '2024-01-15 14:43:13.919000', 'TEST');
\ No newline at end of file
diff --git a/caab-service/src/integrationTest/resources/sql/proceeding_insert.sql b/caab-service/src/integrationTest/resources/sql/proceeding_insert.sql
new file mode 100644
index 0000000..dcc8da9
--- /dev/null
+++ b/caab-service/src/integrationTest/resources/sql/proceeding_insert.sql
@@ -0,0 +1,3 @@
+INSERT INTO XXCCMS_PROCEEDING
+(ID, EBS_ID, MATTER_TYPE, MATTER_TYPE_DISPLAY_VALUE, PROCEEDING_TYPE, PROCEEDING_TYPE_DISPLAY_VALUE, DESCRIPTION, LEVEL_OF_SERVICE, LEVEL_OF_SERVICE_DISPLAY_VALUE, CLIENT_INVOLVEMENT, CLIENT_DISPLAY_VALUE, COST_LIMITATION, STATUS, DISPLAY_STATUS, TYPE_OF_ORDER, DATE_GRANTED, EDITED, DEFAULT_SCOPE_LIMITATION, STAGE, DATE_COSTS_VALID, LEAD_PROCEEDING_IND, LAR_SCOPE, FK_APPLICATION, CREATED, CREATED_BY, MODIFIED, MODIFIED_BY)
+VALUES(2, NULL, 'KPBLB', 'Pub Law - Fam', 'PBM32', 'Special Guardianship Order - Pub Law - Fam', 'Special Guardianship Order - Pub Law - Fam', '3', 'Full Representation', 'W', 'Subject of proceedings (child)', 0, 'Draft', 'Unchanged', NULL, NULL, 0, NULL, '8', NULL, 0, 'I', 41, TIMESTAMP '2023-12-06 15:34:21.464000', 'PENNY.WALL@SWITALSKIS.COM', TIMESTAMP '2023-12-06 15:34:21.464000', 'PENNY.WALL@SWITALSKIS.COM');
\ No newline at end of file
diff --git a/caab-service/src/integrationTest/resources/sql/scope_limitation_insert.sql b/caab-service/src/integrationTest/resources/sql/scope_limitation_insert.sql
new file mode 100644
index 0000000..b9bbf8b
--- /dev/null
+++ b/caab-service/src/integrationTest/resources/sql/scope_limitation_insert.sql
@@ -0,0 +1,3 @@
+INSERT INTO XXCCMS_SCOPE_LIMITATION
+(ID, EBS_ID, SCOPE_LIMITATION, SCOPE_LIMITATION_DISPLAY_VALUE, SCOPE_LIMITATION_WORDING, DEFAULT_IND, DELEGATED_FUNC_APPLY_IND, FK_PROCEEDING, CREATED, CREATED_BY, MODIFIED, MODIFIED_BY)
+VALUES(3, NULL, 'FM062', 'Final Hearing (fam/public law)', 'Limited to all steps up to and including final hearing and any action necessary to implement (but not enforce) the order.', 0, 0, 2, TIMESTAMP '2024-01-16 09:06:05.679000', 'PENNY.WALL@SWITALSKIS.COM', TIMESTAMP '2024-01-16 09:06:05.679000', 'PENNY.WALL@SWITALSKIS.COM');
\ No newline at end of file
diff --git a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/controller/ApplicationController.java b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/controller/ApplicationController.java
index ddeec57..5c27d96 100644
--- a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/controller/ApplicationController.java
+++ b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/controller/ApplicationController.java
@@ -11,13 +11,27 @@
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import uk.gov.laa.ccms.caab.api.ApplicationsApi;
+import uk.gov.laa.ccms.caab.api.ClientsApi;
+import uk.gov.laa.ccms.caab.api.LinkedCasesApi;
+import uk.gov.laa.ccms.caab.api.PriorAuthoritiesApi;
+import uk.gov.laa.ccms.caab.api.ProceedingsApi;
+import uk.gov.laa.ccms.caab.api.ScopeLimitationsApi;
import uk.gov.laa.ccms.caab.api.service.ApplicationService;
+import uk.gov.laa.ccms.caab.api.service.LinkedCaseService;
+import uk.gov.laa.ccms.caab.api.service.PriorAuthorityService;
+import uk.gov.laa.ccms.caab.api.service.ProceedingService;
+import uk.gov.laa.ccms.caab.api.service.ScopeLimitationService;
import uk.gov.laa.ccms.caab.model.Address;
import uk.gov.laa.ccms.caab.model.ApplicationDetail;
import uk.gov.laa.ccms.caab.model.ApplicationDetails;
import uk.gov.laa.ccms.caab.model.ApplicationProviderDetails;
import uk.gov.laa.ccms.caab.model.ApplicationType;
+import uk.gov.laa.ccms.caab.model.BaseClient;
+import uk.gov.laa.ccms.caab.model.CostStructure;
import uk.gov.laa.ccms.caab.model.LinkedCase;
+import uk.gov.laa.ccms.caab.model.PriorAuthority;
+import uk.gov.laa.ccms.caab.model.Proceeding;
+import uk.gov.laa.ccms.caab.model.ScopeLimitation;
/**
* Represents the main controller handling application-related requests.
@@ -27,10 +41,14 @@
*/
@RestController
@RequiredArgsConstructor
-public class ApplicationController implements ApplicationsApi {
+public class ApplicationController implements ApplicationsApi, LinkedCasesApi, ProceedingsApi,
+ ScopeLimitationsApi, PriorAuthoritiesApi, ClientsApi {
private final ApplicationService applicationService;
-
+ private final LinkedCaseService linkedCaseService;
+ private final ProceedingService proceedingService;
+ private final PriorAuthorityService priorAuthorityService;
+ private final ScopeLimitationService scopeLimitationService;
/**
* Creates a new application and returns the URI of the created resource.
@@ -98,9 +116,7 @@ public ResponseEntity getApplications(
@Override
public ResponseEntity getApplication(
final Long applicationId) {
-
ApplicationDetail application = applicationService.getApplication(applicationId);
-
return new ResponseEntity<>(application, HttpStatus.OK);
}
@@ -117,7 +133,6 @@ public ResponseEntity getApplicationCorrespondenceAddress(
final Long applicationId) {
Address correspondenceAddress =
applicationService.getApplicationCorrespondenceAddress(applicationId);
-
return new ResponseEntity<>(correspondenceAddress, HttpStatus.OK);
}
@@ -135,7 +150,6 @@ public ResponseEntity putApplicationCorrespondenceAddress(
final String caabUserLoginId,
final Address address) {
applicationService.putCorrespondenceAddress(applicationId, address);
-
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@@ -152,7 +166,6 @@ public ResponseEntity getApplicationProviderDetails(
final Long applicationId) {
ApplicationProviderDetails applicationProviderDetails =
applicationService.getApplicationProviderDetails(applicationId);
-
return new ResponseEntity<>(applicationProviderDetails, HttpStatus.OK);
}
@@ -170,7 +183,6 @@ public ResponseEntity putApplicationProviderDetails(
final String caabUserLoginId,
final ApplicationProviderDetails applicationProviderDetails) {
applicationService.putProviderDetails(applicationId, applicationProviderDetails);
-
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@@ -186,7 +198,6 @@ public ResponseEntity putApplicationProviderDetails(
public ResponseEntity getApplicationType(
final Long applicationId) {
ApplicationType applicationType = applicationService.getApplicationType(applicationId);
-
return new ResponseEntity<>(applicationType, HttpStatus.OK);
}
@@ -204,7 +215,24 @@ public ResponseEntity putApplicationType(
final String caabUserLoginId,
final ApplicationType applicationType) {
applicationService.putApplicationType(applicationId, applicationType);
+ return new ResponseEntity<>(HttpStatus.NO_CONTENT);
+ }
+
+ //Cost Structure
+ @Override
+ public ResponseEntity getApplicationCostStructure(final Long applicationId) {
+ CostStructure costStructure =
+ applicationService.getApplicationCostStructure(applicationId);
+ return new ResponseEntity<>(costStructure, HttpStatus.OK);
+ }
+
+ @Override
+ public ResponseEntity updateApplicationCostStructure(
+ final Long applicationId,
+ final String caabUserLoginId,
+ final CostStructure costStructure) {
+ applicationService.putCostStructure(applicationId, costStructure);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@@ -219,7 +247,6 @@ public ResponseEntity putApplicationType(
@Override
public ResponseEntity> getApplicationLinkedCases(final Long applicationId) {
List linkedCases = applicationService.getLinkedCasesForApplication(applicationId);
-
return new ResponseEntity<>(linkedCases, HttpStatus.OK);
}
@@ -237,14 +264,12 @@ public ResponseEntity addApplicationLinkedCase(
final String caabUserLoginId,
final LinkedCase linkedCase) {
applicationService.createLinkedCaseForApplication(applicationId, linkedCase);
-
return new ResponseEntity<>(HttpStatus.CREATED);
}
/**
- * Updates a linked case of a specific application.
+ * Updates a linked case.
*
- * @param applicationId the unique identifier of the application
* @param linkedCaseId the unique identifier of the linked case
* @param caabUserLoginId the user login ID used for audit trail
* @param linkedCase the updated linked case
@@ -252,29 +277,141 @@ public ResponseEntity addApplicationLinkedCase(
*/
@Override
public ResponseEntity updateApplicationLinkedCase(
- final Long applicationId, final Long linkedCaseId,
+ final Long linkedCaseId,
final String caabUserLoginId,
final LinkedCase linkedCase) {
- applicationService.updateLinkedCaseForApplication(applicationId, linkedCaseId, linkedCase);
-
+ linkedCaseService.updateLinkedCase(linkedCaseId, linkedCase);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
/**
* Removes a linked case from a specific application.
*
- * @param applicationId the unique identifier of the application
* @param linkedCaseId the unique identifier of the linked case
* @param caabUserLoginId the user login ID used for audit trail
* @return a ResponseEntity indicating the case was successfully removed
*/
@Override
public ResponseEntity removeApplicationLinkedCase(
- final Long applicationId,
final Long linkedCaseId,
final String caabUserLoginId) {
- applicationService.removeLinkedCaseFromApplication(applicationId, linkedCaseId);
+ linkedCaseService.removeLinkedCase(linkedCaseId);
+ return new ResponseEntity<>(HttpStatus.NO_CONTENT);
+ }
+
+ //proceedings
+
+ @Override
+ public ResponseEntity addApplicationProceeding(
+ final Long applicationId,
+ final String caabUserLoginId,
+ final Proceeding proceeding) {
+ applicationService.createProceedingForApplication(applicationId, proceeding);
+ return new ResponseEntity<>(HttpStatus.CREATED);
+ }
+
+ @Override
+ public ResponseEntity> getApplicationProceedings(
+ final Long applicationId) {
+ List proceedings = applicationService.getProceedingsForApplication(applicationId);
+ return new ResponseEntity<>(proceedings, HttpStatus.OK);
+ }
+
+ @Override
+ public ResponseEntity removeProceeding(
+ final Long proceedingId,
+ final String caabUserLoginId) {
+ proceedingService.removeProceeding(proceedingId);
+ return new ResponseEntity<>(HttpStatus.NO_CONTENT);
+ }
+
+ @Override
+ public ResponseEntity updateProceeding(
+ final Long proceedingId,
+ final String caabUserLoginId,
+ final Proceeding proceeding) {
+ proceedingService.updateProceeding(proceedingId, proceeding);
+ return new ResponseEntity<>(HttpStatus.NO_CONTENT);
+ }
+
+ //scope limitations
+
+ @Override
+ public ResponseEntity addProceedingScopeLimitation(
+ final Long proceedingId,
+ final String caabUserLoginId,
+ final ScopeLimitation scopeLimitation) {
+ proceedingService.createScopeLimitationForProceeding(proceedingId, scopeLimitation);
+ return new ResponseEntity<>(HttpStatus.CREATED);
+ }
+
+ @Override
+ public ResponseEntity> getApplicationScopeLimitations(
+ final Long proceedingId) {
+ List scopeLimitations =
+ proceedingService.getScopeLimitationsForProceeding(proceedingId);
+ return new ResponseEntity<>(scopeLimitations, HttpStatus.OK);
+ }
+
+ @Override
+ public ResponseEntity removeScopeLimitation(
+ final Long scopeLimitationId,
+ final String caabUserLoginId) {
+ scopeLimitationService.removeScopeLimitation(scopeLimitationId);
+ return new ResponseEntity<>(HttpStatus.NO_CONTENT);
+ }
+ @Override
+ public ResponseEntity updateScopeLimitation(
+ final Long scopeLimitationId,
+ final String caabUserLoginId,
+ final ScopeLimitation scopeLimitation) {
+ scopeLimitationService.updateScopeLimitation(scopeLimitationId, scopeLimitation);
+ return new ResponseEntity<>(HttpStatus.NO_CONTENT);
+ }
+
+ //prior authorities
+
+ @Override
+ public ResponseEntity addApplicationPriorAuthority(
+ final Long id,
+ final String caabUserLoginId,
+ final PriorAuthority priorAuthority) {
+ applicationService.createPriorAuthorityForApplication(id, priorAuthority);
+ return new ResponseEntity<>(HttpStatus.CREATED);
+ }
+
+ @Override
+ public ResponseEntity> getApplicationPriorAuthorities(
+ final Long id) {
+ List priorAuthorities =
+ applicationService.getPriorAuthoritiesForApplication(id);
+ return new ResponseEntity<>(priorAuthorities, HttpStatus.OK);
+ }
+
+ @Override
+ public ResponseEntity removePriorAuthority(
+ final Long priorAuthorityId,
+ final String caabUserLoginId) {
+ priorAuthorityService.removePriorAuthority(priorAuthorityId);
+ return new ResponseEntity<>(HttpStatus.NO_CONTENT);
+ }
+
+ @Override
+ public ResponseEntity updatePriorAuthority(
+ final Long priorAuthorityId,
+ final String caabUserLoginId,
+ final PriorAuthority priorAuthority) {
+ priorAuthorityService.updatePriorAuthority(priorAuthorityId, priorAuthority);
+ return new ResponseEntity<>(HttpStatus.NO_CONTENT);
+ }
+
+ //clients
+ @Override
+ public ResponseEntity updateApplicationClient(final String clientReferenceId,
+ final String caabUserLoginId,
+ final BaseClient baseClient) {
+ applicationService.updateClient(baseClient, clientReferenceId);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
diff --git a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/entity/Application.java b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/entity/Application.java
index 6650cef..90ab118 100644
--- a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/entity/Application.java
+++ b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/entity/Application.java
@@ -159,15 +159,15 @@ public class Application implements Serializable {
@JoinColumn(name = "FK_CORRESPONDENCE_ADDRESS")
private Address correspondenceAddress;
- @OneToMany(mappedBy = "application", cascade = CascadeType.ALL)
+ @OneToMany(mappedBy = "application", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("id asc")
private List proceedings;
- @OneToMany(mappedBy = "application", cascade = CascadeType.ALL)
+ @OneToMany(mappedBy = "application", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("id asc")
private List priorAuthorities;
- @OneToMany(mappedBy = "application", cascade = CascadeType.ALL)
+ @OneToMany(mappedBy = "application", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("id asc")
private List opponents;
diff --git a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/entity/PriorAuthority.java b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/entity/PriorAuthority.java
index 1975d22..cee8a2b 100644
--- a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/entity/PriorAuthority.java
+++ b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/entity/PriorAuthority.java
@@ -51,6 +51,9 @@ public class PriorAuthority implements Serializable {
@Embedded
private AuditTrail auditTrail = new AuditTrail();
+ /**
+ * Application, the prior authority is associated with.
+ */
@ManyToOne
@JoinColumn(name = "FK_APPLICATION", nullable = false)
private Application application;
diff --git a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/mapper/ApplicationMapper.java b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/mapper/ApplicationMapper.java
index 437a534..44d600d 100644
--- a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/mapper/ApplicationMapper.java
+++ b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/mapper/ApplicationMapper.java
@@ -2,8 +2,6 @@
import java.util.List;
-import lombok.Generated;
-import org.mapstruct.AfterMapping;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
@@ -134,7 +132,7 @@ default void setParentInChildEntities(@MappingTarget Application application) {
@Mapping(target = "typeOfOrder", source = "typeOfOrder.id")
Proceeding toProceeding(uk.gov.laa.ccms.caab.model.Proceeding proceeding);
- @InheritInverseConfiguration
+ @InheritInverseConfiguration(name = "toProceeding")
uk.gov.laa.ccms.caab.model.Proceeding toProceedingModel(Proceeding proceeding);
@Mapping(target = "auditTrail", ignore = true)
@@ -142,7 +140,7 @@ default void setParentInChildEntities(@MappingTarget Application application) {
@Mapping(target = "typeDisplayValue", source = "type.displayValue")
PriorAuthority toPriorAuthority(uk.gov.laa.ccms.caab.model.PriorAuthority priorAuthority);
- @InheritInverseConfiguration
+ @InheritInverseConfiguration(name = "toPriorAuthority")
uk.gov.laa.ccms.caab.model.PriorAuthority toPriorAuthorityModel(PriorAuthority priorAuthority);
@Mapping(target = "code", source = "code.id")
@@ -162,7 +160,7 @@ uk.gov.laa.ccms.caab.model.ReferenceDataItem toReferenceDataItemModel(
@Mapping(target = "delegatedFuncApplyInd", source = "delegatedFuncApplyInd.flag")
ScopeLimitation toScopeLimitation(uk.gov.laa.ccms.caab.model.ScopeLimitation scopeLimitation);
- @InheritInverseConfiguration
+ @InheritInverseConfiguration(name = "toScopeLimitation")
uk.gov.laa.ccms.caab.model.ScopeLimitation toScopeLimitationModel(
ScopeLimitation scopeLimitation);
@@ -204,7 +202,7 @@ uk.gov.laa.ccms.caab.model.ScopeLimitation toScopeLimitationModel(
CostStructure toCostStructure(uk.gov.laa.ccms.caab.model.CostStructure costs);
@Named("toCostStructureModel")
- @InheritInverseConfiguration
+ @InheritInverseConfiguration(name = "toCostStructure")
uk.gov.laa.ccms.caab.model.CostStructure toCostStructureModel(CostStructure costs);
@Mapping(target = "auditTrail", ignore = true)
@@ -283,6 +281,23 @@ void updateAddress(
@MappingTarget Address address,
uk.gov.laa.ccms.caab.model.Address addressModel);
+ /**
+ * Adds/Updates an application with a new cost structure.
+ */
+ default void addCostStructureToApplication(
+ @MappingTarget Application application,
+ uk.gov.laa.ccms.caab.model.CostStructure costStructureModel) {
+ if (application.getCosts() == null) {
+ application.setCosts(new CostStructure());
+ }
+ updateCostStructure(application.getCosts(), costStructureModel);
+ }
+
+ @Mapping(target = "id", ignore = true)
+ @Mapping(target = "auditTrail", ignore = true)
+ void updateCostStructure(
+ @MappingTarget CostStructure costStructure,
+ uk.gov.laa.ccms.caab.model.CostStructure costStructureModel);
@Mapping(target = "auditTrail", ignore = true)
@Mapping(target = "id", ignore = true)
@@ -293,6 +308,40 @@ void updateLinkedCase(
@MappingTarget LinkedCase linkedCase,
uk.gov.laa.ccms.caab.model.LinkedCase linkedCaseModel);
+ @Mapping(target = "auditTrail", ignore = true)
+ @Mapping(target = "id", ignore = true)
+ @Mapping(target = "type", source = "type.id")
+ @Mapping(target = "typeDisplayValue", source = "type.displayValue")
+ void updatePriorAuthority(
+ @MappingTarget PriorAuthority priorAuthority,
+ uk.gov.laa.ccms.caab.model.PriorAuthority priorAuthorityModel);
+
+ @Mapping(target = "auditTrail", ignore = true)
+ @Mapping(target = "id", ignore = true)
+ @Mapping(target = "matterType", source = "matterType.id")
+ @Mapping(target = "matterTypeDisplayValue", source = "matterType.displayValue")
+ @Mapping(target = "proceedingType", source = "proceedingType.id")
+ @Mapping(target = "proceedingTypeDisplayValue", source = "proceedingType.displayValue")
+ @Mapping(target = "levelOfService", source = "levelOfService.id")
+ @Mapping(target = "levelOfServiceDisplayValue", source = "levelOfService.displayValue")
+ @Mapping(target = "clientInvolvement", source = "clientInvolvement.id")
+ @Mapping(target = "clientInvolvementDisplayValue", source = "clientInvolvement.displayValue")
+ @Mapping(target = "status", source = "status.id")
+ @Mapping(target = "displayStatus", source = "status.displayValue")
+ @Mapping(target = "typeOfOrder", source = "typeOfOrder.id")
+ void updateProceeding(
+ @MappingTarget Proceeding proceeding,
+ uk.gov.laa.ccms.caab.model.Proceeding proceedingModel);
+
+ @Mapping(target = "auditTrail", ignore = true)
+ @Mapping(target = "id", ignore = true)
+ @Mapping(target = "scopeLimitation", source = "scopeLimitation.id")
+ @Mapping(target = "scopeLimitationDisplayValue", source = "scopeLimitation.displayValue")
+ @Mapping(target = "delegatedFuncApplyInd", source = "delegatedFuncApplyInd.flag")
+ void updateScopeLimitation(
+ @MappingTarget ScopeLimitation scopeLimitation,
+ uk.gov.laa.ccms.caab.model.ScopeLimitation scopeLimitationModel);
+
@Mapping(target = "providerDetails", source = ".")
@Mapping(target = "caseReferenceNumber", source = "lscCaseReference")
@Mapping(target = "categoryOfLaw.id", source = "categoryOfLaw")
diff --git a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/ApplicationRepository.java b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/ApplicationRepository.java
index 8589e57..7f4520f 100644
--- a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/ApplicationRepository.java
+++ b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/ApplicationRepository.java
@@ -1,6 +1,10 @@
package uk.gov.laa.ccms.caab.api.repository;
+import java.time.LocalDate;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
import uk.gov.laa.ccms.caab.api.entity.Application;
/**
@@ -12,5 +16,15 @@
* amongst other common operations found within {@link JpaRepository}.
*/
public interface ApplicationRepository extends JpaRepository {
-
+
+ @Modifying
+ @Query(
+ "update Application a "
+ + "set a.clientFirstName = :firstName, a.clientSurname = :surname "
+ + "where a.clientReference = :reference")
+ void updateClient(
+ @Param("firstName") String firstName,
+ @Param("surname") String surname,
+ @Param("reference") String reference
+ );
}
diff --git a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/LinkedCaseRepository.java b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/LinkedCaseRepository.java
new file mode 100644
index 0000000..26576b4
--- /dev/null
+++ b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/LinkedCaseRepository.java
@@ -0,0 +1,17 @@
+package uk.gov.laa.ccms.caab.api.repository;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import uk.gov.laa.ccms.caab.api.entity.LinkedCase;
+
+/**
+ * Repository interface for managing {@link uk.gov.laa.ccms.caab.api.entity.Application} entities.
+ *
+ * This interface provides CRUD (Create, Read, Update, Delete) operations
+ * for the {@link uk.gov.laa.ccms.caab.api.entity.LinkedCase} entity, leveraging the power of
+ * Spring Data JPA.It automatically provides methods to save, find, and delete applications,
+ * amongst other common operations found within
+ * {@link org.springframework.data.jpa.repository.JpaRepository}.
+ */
+public interface LinkedCaseRepository extends JpaRepository {
+
+}
diff --git a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/PriorAuthorityRepository.java b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/PriorAuthorityRepository.java
new file mode 100644
index 0000000..e34bc05
--- /dev/null
+++ b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/PriorAuthorityRepository.java
@@ -0,0 +1,18 @@
+package uk.gov.laa.ccms.caab.api.repository;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import uk.gov.laa.ccms.caab.api.entity.PriorAuthority;
+import uk.gov.laa.ccms.caab.api.entity.Proceeding;
+
+/**
+ * Repository interface for managing {@link uk.gov.laa.ccms.caab.api.entity.Application} entities.
+ *
+ * This interface provides CRUD (Create, Read, Update, Delete) operations
+ * for the {@link uk.gov.laa.ccms.caab.api.entity.PriorAuthority} entity, leveraging the power of
+ * Spring Data JPA. It automatically provides methods to save, find, and delete applications,
+ * amongst other common operations found within
+ * {@link org.springframework.data.jpa.repository.JpaRepository}.
+ */
+public interface PriorAuthorityRepository extends JpaRepository {
+
+}
diff --git a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/ProceedingRepository.java b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/ProceedingRepository.java
new file mode 100644
index 0000000..8b0e512
--- /dev/null
+++ b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/ProceedingRepository.java
@@ -0,0 +1,18 @@
+package uk.gov.laa.ccms.caab.api.repository;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import uk.gov.laa.ccms.caab.api.entity.LinkedCase;
+import uk.gov.laa.ccms.caab.api.entity.Proceeding;
+
+/**
+ * Repository interface for managing {@link uk.gov.laa.ccms.caab.api.entity.Application} entities.
+ *
+ * This interface provides CRUD (Create, Read, Update, Delete) operations
+ * for the {@link uk.gov.laa.ccms.caab.api.entity.Proceeding} entity, leveraging the power of
+ * Spring Data JPA. It automatically provides methods to save, find, and delete applications,
+ * amongst other common operations found within
+ * {@link org.springframework.data.jpa.repository.JpaRepository}.
+ */
+public interface ProceedingRepository extends JpaRepository {
+
+}
diff --git a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/ScopeLimitationRepository.java b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/ScopeLimitationRepository.java
new file mode 100644
index 0000000..1970f6d
--- /dev/null
+++ b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/repository/ScopeLimitationRepository.java
@@ -0,0 +1,18 @@
+package uk.gov.laa.ccms.caab.api.repository;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import uk.gov.laa.ccms.caab.api.entity.PriorAuthority;
+import uk.gov.laa.ccms.caab.api.entity.ScopeLimitation;
+
+/**
+ * Repository interface for managing {@link uk.gov.laa.ccms.caab.api.entity.Application} entities.
+ *
+ * This interface provides CRUD (Create, Read, Update, Delete) operations
+ * for the {@link uk.gov.laa.ccms.caab.api.entity.ScopeLimitation} entity, leveraging the power of
+ * Spring Data JPA. It automatically provides methods to save, find, and delete applications,
+ * amongst other common operations found within
+ * {@link org.springframework.data.jpa.repository.JpaRepository}.
+ */
+public interface ScopeLimitationRepository extends JpaRepository {
+
+}
diff --git a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/ApplicationService.java b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/ApplicationService.java
index 1a26c2b..8148989 100644
--- a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/ApplicationService.java
+++ b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/ApplicationService.java
@@ -2,6 +2,7 @@
import jakarta.transaction.Transactional;
import java.util.List;
+import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
@@ -9,6 +10,8 @@
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import uk.gov.laa.ccms.caab.api.entity.Application;
+import uk.gov.laa.ccms.caab.api.entity.ReferenceDataItem;
+import uk.gov.laa.ccms.caab.api.entity.ScopeLimitation;
import uk.gov.laa.ccms.caab.api.exception.CaabApiException;
import uk.gov.laa.ccms.caab.api.mapper.ApplicationMapper;
import uk.gov.laa.ccms.caab.api.repository.ApplicationRepository;
@@ -16,7 +19,10 @@
import uk.gov.laa.ccms.caab.model.ApplicationDetails;
import uk.gov.laa.ccms.caab.model.ApplicationProviderDetails;
import uk.gov.laa.ccms.caab.model.ApplicationType;
+import uk.gov.laa.ccms.caab.model.BaseClient;
import uk.gov.laa.ccms.caab.model.LinkedCase;
+import uk.gov.laa.ccms.caab.model.PriorAuthority;
+import uk.gov.laa.ccms.caab.model.Proceeding;
/**
* Service responsible for handling application-related operations.
@@ -102,6 +108,22 @@ public ApplicationDetail getApplication(final Long applicationId) {
HttpStatus.NOT_FOUND));
}
+ /**
+ * Updates a client's information in the application repository.
+ *
+ * @param baseClient The client object containing updated information.
+ * @param reference A unique reference number for the client.
+ */
+ @Transactional
+ public void updateClient(
+ final BaseClient baseClient,
+ final String reference) {
+ applicationRepository.updateClient(
+ baseClient.getFirstName(),
+ baseClient.getSurname(),
+ reference);
+ }
+
/**
* Gets an application's linked cases.
*
@@ -138,71 +160,106 @@ public void createLinkedCaseForApplication(
uk.gov.laa.ccms.caab.api.entity.LinkedCase linkedCaseEntity =
applicationMapper.toLinkedCase(linkedCase);
application.getLinkedCases().add(linkedCaseEntity);
+
linkedCaseEntity.setApplication(application);
applicationRepository.save(application);
}
/**
- * Removes a linked case from the specified application.
- * If either the application or the linked case is not found, a CaabApiException is thrown.
+ * Gets an application's proceedings.
+ *
+ * @param id the TDS id for the application.
+ * @return the application's proceedings.
+ */
+ @Transactional
+ public List getProceedingsForApplication(final Long id) {
+ return applicationRepository.findById(id)
+ .map(Application::getProceedings)
+ .orElseThrow(() -> new CaabApiException(
+ String.format("Application with id %s not found", id),
+ HttpStatus.NOT_FOUND))
+ .stream()
+ .map(applicationMapper::toProceedingModel)
+ .collect(Collectors.toList());
+ }
+
+ /**
+ * Creates and associates a new proceeding with a specified application.
+ * If the application is not found, a CaabApiException is thrown.
*
* @param applicationId The unique identifier of the application.
- * @param linkedCaseId The unique identifier of the linked case to be removed.
- * @throws CaabApiException If the application or the linked case with the specified IDs are
- * not found.
+ * @param proceeding The Proceeding object.
+ * @throws CaabApiException If the application with the specified ID is not found.
*/
@Transactional
- public void removeLinkedCaseFromApplication(final Long applicationId, final Long linkedCaseId) {
+ public void createProceedingForApplication(
+ final Long applicationId,
+ final Proceeding proceeding) {
Application application = applicationRepository.findById(applicationId)
.orElseThrow(() -> new CaabApiException(
String.format("Application with id %s not found", applicationId),
HttpStatus.NOT_FOUND));
- uk.gov.laa.ccms.caab.api.entity.LinkedCase linkedCaseEntity =
- application.getLinkedCases().stream()
- .filter(linkedCase -> linkedCase.getId().equals(linkedCaseId))
- .findFirst()
- .orElseThrow(() -> new CaabApiException(
- String.format("Linked case with id %s not found", linkedCaseId),
- HttpStatus.NOT_FOUND));
+ uk.gov.laa.ccms.caab.api.entity.Proceeding proceedingEntity =
+ applicationMapper.toProceeding(proceeding);
+ application.getProceedings().add(proceedingEntity);
+
+ proceedingEntity.setApplication(application);
+ for (ScopeLimitation scopeLimitation : proceedingEntity.getScopeLimitations()) {
+ scopeLimitation.setProceeding(proceedingEntity);
+ }
- application.getLinkedCases().remove(linkedCaseEntity);
applicationRepository.save(application);
}
/**
- * Updates a linked case of a specified application.
- * If either the application or the linked case is not found, a CaabApiException is thrown.
+ * Gets an application's prior authorities.
+ *
+ * @param id the TDS id for the application.
+ * @return the application's prior authorities.
+ */
+ @Transactional
+ public List getPriorAuthoritiesForApplication(final Long id) {
+ return applicationRepository.findById(id)
+ .map(Application::getPriorAuthorities)
+ .orElseThrow(() -> new CaabApiException(
+ String.format("Application with id %s not found", id),
+ HttpStatus.NOT_FOUND))
+ .stream()
+ .map(applicationMapper::toPriorAuthorityModel)
+ .collect(Collectors.toList());
+ }
+
+ /**
+ * Creates and associates a new prior authority with a specified application.
+ * If the application is not found, a CaabApiException is thrown.
*
* @param applicationId The unique identifier of the application.
- * @param linkedCaseId The unique identifier of the linked case to be updated.
- * @param linkedCaseModel The LinkedCase object containing the details of the case to be updated.
- * @throws CaabApiException If the application or the linked case with the specified IDs are not
- * found.
+ * @param priorAuthority The PriorAuthority object.
+ * @throws CaabApiException If the application with the specified ID is not found.
*/
@Transactional
- public void updateLinkedCaseForApplication(
- final Long applicationId, final Long linkedCaseId,
- final LinkedCase linkedCaseModel) {
+ public void createPriorAuthorityForApplication(
+ final Long applicationId,
+ final PriorAuthority priorAuthority) {
Application application = applicationRepository.findById(applicationId)
.orElseThrow(() -> new CaabApiException(
String.format("Application with id %s not found", applicationId),
HttpStatus.NOT_FOUND));
- uk.gov.laa.ccms.caab.api.entity.LinkedCase linkedCaseEntity =
- application.getLinkedCases().stream()
- .filter(linkedCase -> linkedCase.getId().equals(linkedCaseId))
- .findFirst()
- .orElseThrow(() -> new CaabApiException(
- String.format("Linked case with id %s not found", linkedCaseId),
- HttpStatus.NOT_FOUND));
+ uk.gov.laa.ccms.caab.api.entity.PriorAuthority priorAuthorityEntity =
+ applicationMapper.toPriorAuthority(priorAuthority);
+ application.getPriorAuthorities().add(priorAuthorityEntity);
+
+ priorAuthorityEntity.setApplication(application);
+ for (ReferenceDataItem item : priorAuthorityEntity.getItems()) {
+ item.setPriorAuthority(priorAuthorityEntity);
+ }
- applicationMapper.updateLinkedCase(linkedCaseEntity, linkedCaseModel);
applicationRepository.save(application);
}
-
/**
* Gets an application's correspondence address.
*
@@ -221,6 +278,25 @@ public uk.gov.laa.ccms.caab.model.Address getApplicationCorrespondenceAddress(
HttpStatus.NOT_FOUND));
}
+
+ /**
+ * Gets an application's cost structure.
+ *
+ * @param applicationId the TDS id for the application.
+ * @return the application's cost structure.
+ */
+ @Transactional
+ public uk.gov.laa.ccms.caab.model.CostStructure getApplicationCostStructure(
+ final Long applicationId) {
+ return applicationRepository.findById(applicationId)
+ .map(Application::getCosts)
+ .map(applicationMapper::toCostStructureModel)
+ .orElseThrow(() -> new CaabApiException(
+ String.format("Cost structure for application with id %s not found",
+ applicationId),
+ HttpStatus.NOT_FOUND));
+ }
+
/**
* Gets an applications provider details.
*
@@ -269,6 +345,26 @@ public void putCorrespondenceAddress(
applicationRepository.save(application);
}
+ /**
+ * Adds/Updates an application with a new cost structure.
+ *
+ * @param applicationId the TDS id for the application.
+ * @param costStructure the applications updated cost structure
+ */
+ @Transactional
+ public void putCostStructure(
+ final Long applicationId,
+ final uk.gov.laa.ccms.caab.model.CostStructure costStructure) {
+
+ Application application = applicationRepository.findById(applicationId)
+ .orElseThrow(() -> new CaabApiException(
+ String.format("Application with id %s not found", applicationId),
+ HttpStatus.NOT_FOUND));
+
+ applicationMapper.addCostStructureToApplication(application, costStructure);
+ applicationRepository.save(application);
+ }
+
/**
* Amends an application with new provider details.
*
diff --git a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/LinkedCaseService.java b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/LinkedCaseService.java
new file mode 100644
index 0000000..11009aa
--- /dev/null
+++ b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/LinkedCaseService.java
@@ -0,0 +1,70 @@
+package uk.gov.laa.ccms.caab.api.service;
+
+import jakarta.transaction.Transactional;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Service;
+import uk.gov.laa.ccms.caab.api.exception.CaabApiException;
+import uk.gov.laa.ccms.caab.api.mapper.ApplicationMapper;
+import uk.gov.laa.ccms.caab.api.repository.LinkedCaseRepository;
+import uk.gov.laa.ccms.caab.model.LinkedCase;
+
+/**
+ * Service responsible for handling linked-case operations.
+ *
+ * @see uk.gov.laa.ccms.caab.api.repository.LinkedCaseRepository
+ * @see ApplicationMapper
+ */
+@Service
+@RequiredArgsConstructor
+@Slf4j
+public class LinkedCaseService {
+
+ private final LinkedCaseRepository repository;
+
+ private final ApplicationMapper mapper;
+
+ /**
+ * Removes a linked case.
+ * If the linked case is not found, a CaabApiException is thrown.
+ *
+ * @param linkedCaseId The unique identifier of the linked case to be removed.
+ * @throws uk.gov.laa.ccms.caab.api.exception.CaabApiException If the application or the
+ * linked case with the specified IDs are not found.
+ */
+ @Transactional
+ public void removeLinkedCase(final Long linkedCaseId) {
+ if (repository.existsById(linkedCaseId)) {
+ repository.deleteById(linkedCaseId);
+ } else {
+ throw new CaabApiException(
+ String.format("Linked case with id: %s not found", linkedCaseId),
+ HttpStatus.NOT_FOUND);
+ }
+ }
+
+ /**
+ * Updates a linked case of an application.
+ * If either the application or the linked case is not found, a CaabApiException is thrown.
+ *
+ * @param linkedCaseId The unique identifier of the linked case to be updated.
+ * @param linkedCaseModel The LinkedCase object containing the details of the case to be updated.
+ * @throws CaabApiException If the application or the linked case with the specified IDs are not
+ * found.
+ */
+ @Transactional
+ public void updateLinkedCase(
+ final Long linkedCaseId,
+ final LinkedCase linkedCaseModel) {
+
+ uk.gov.laa.ccms.caab.api.entity.LinkedCase linkedCaseEntity =
+ repository.findById(linkedCaseId)
+ .orElseThrow(() -> new CaabApiException(
+ String.format("Linked case with id %s not found", linkedCaseId),
+ HttpStatus.NOT_FOUND));
+
+ mapper.updateLinkedCase(linkedCaseEntity, linkedCaseModel);
+ repository.save(linkedCaseEntity);
+ }
+}
diff --git a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/PriorAuthorityService.java b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/PriorAuthorityService.java
new file mode 100644
index 0000000..b17146d
--- /dev/null
+++ b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/PriorAuthorityService.java
@@ -0,0 +1,70 @@
+package uk.gov.laa.ccms.caab.api.service;
+
+import jakarta.transaction.Transactional;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Service;
+import uk.gov.laa.ccms.caab.api.exception.CaabApiException;
+import uk.gov.laa.ccms.caab.api.mapper.ApplicationMapper;
+import uk.gov.laa.ccms.caab.api.repository.PriorAuthorityRepository;
+import uk.gov.laa.ccms.caab.model.PriorAuthority;
+
+/**
+ * Service responsible for handling prior-authorities operations.
+ *
+ * @see uk.gov.laa.ccms.caab.api.repository.PriorAuthorityRepository
+ * @see ApplicationMapper
+ */
+@Service
+@RequiredArgsConstructor
+@Slf4j
+public class PriorAuthorityService {
+
+ private final PriorAuthorityRepository repository;
+ private final ApplicationMapper mapper;
+
+ /**
+ * Removes a prior authority.
+ * If the prior authority is not found, a CaabApiException is thrown.
+ *
+ * @param priorAuthorityId The unique identifier of the prior authority to be removed.
+ * @throws uk.gov.laa.ccms.caab.api.exception.CaabApiException If the prior authority with the
+ * specified ID is not found.
+ */
+ @Transactional
+ public void removePriorAuthority(final Long priorAuthorityId) {
+ if (repository.existsById(priorAuthorityId)) {
+ repository.deleteById(priorAuthorityId);
+ } else {
+ throw new CaabApiException(
+ String.format("Prior Authority with id: %s not found", priorAuthorityId),
+ HttpStatus.NOT_FOUND);
+ }
+ }
+
+ /**
+ * Updates a prior authority.
+ * If the prior authority is not found, a CaabApiException is thrown.
+ *
+ * @param priorAuthorityId The unique identifier of the prior authority to be updated.
+ * @param priorAuthorityModel The PriorAuthority object containing the details of the prior
+ * authority to be updated.
+ * @throws uk.gov.laa.ccms.caab.api.exception.CaabApiException If the prior authority with the
+ * specified ID is not found.
+ */
+ @Transactional
+ public void updatePriorAuthority(
+ final Long priorAuthorityId,
+ final PriorAuthority priorAuthorityModel) {
+
+ uk.gov.laa.ccms.caab.api.entity.PriorAuthority priorAuthorityEntity =
+ repository.findById(priorAuthorityId)
+ .orElseThrow(() -> new CaabApiException(
+ String.format("Prior Authority with id %s not found", priorAuthorityId),
+ HttpStatus.NOT_FOUND));
+
+ mapper.updatePriorAuthority(priorAuthorityEntity, priorAuthorityModel);
+ repository.save(priorAuthorityEntity);
+ }
+}
diff --git a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/ProceedingService.java b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/ProceedingService.java
new file mode 100644
index 0000000..84734d4
--- /dev/null
+++ b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/ProceedingService.java
@@ -0,0 +1,122 @@
+package uk.gov.laa.ccms.caab.api.service;
+
+import jakarta.transaction.Transactional;
+import java.util.List;
+import java.util.stream.Collectors;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Service;
+import uk.gov.laa.ccms.caab.api.entity.Application;
+import uk.gov.laa.ccms.caab.api.exception.CaabApiException;
+import uk.gov.laa.ccms.caab.api.mapper.ApplicationMapper;
+import uk.gov.laa.ccms.caab.api.repository.ProceedingRepository;
+import uk.gov.laa.ccms.caab.model.Proceeding;
+import uk.gov.laa.ccms.caab.model.ScopeLimitation;
+
+/**
+ * Service responsible for handling proceedings operations.
+ *
+ * @see uk.gov.laa.ccms.caab.api.repository.ProceedingRepository
+ * @see ApplicationMapper
+ */
+@Service
+@RequiredArgsConstructor
+@Slf4j
+public class ProceedingService {
+
+ private final ProceedingRepository repository;
+ private final ApplicationMapper mapper;
+
+ /**
+ * Removes a proceeding.
+ * If the proceeding is not found, a CaabApiException is thrown.
+ *
+ * @param proceedingId The unique identifier of the proceeding to be removed.
+ * @throws uk.gov.laa.ccms.caab.api.exception.CaabApiException If the application or the
+ * proceeding with the specified IDs are not found.
+ */
+ @Transactional
+ public void removeProceeding(final Long proceedingId) {
+ if (repository.existsById(proceedingId)) {
+ repository.deleteById(proceedingId);
+ } else {
+ throw new CaabApiException(
+ String.format("Proceeding with id: %s not found", proceedingId),
+ HttpStatus.NOT_FOUND);
+ }
+ }
+
+ /**
+ * Updates a proceeding of an application.
+ * If either the application or the proceeding is not found, a CaabApiException is thrown.
+ *
+ * @param proceedingId The unique identifier of the proceeding to be updated.
+ * @param proceedingModel The Proceeding object containing the details of the proceeding to be
+ * updated.
+ * @throws uk.gov.laa.ccms.caab.api.exception.CaabApiException If the application or the
+ * proceeding with the specified IDs are not found.
+ */
+ @Transactional
+ public void updateProceeding(
+ final Long proceedingId,
+ final Proceeding proceedingModel) {
+
+ uk.gov.laa.ccms.caab.api.entity.Proceeding proceedingEntity =
+ repository.findById(proceedingId)
+ .orElseThrow(() -> new CaabApiException(
+ String.format("Proceeding with id %s not found", proceedingId),
+ HttpStatus.NOT_FOUND));
+
+ mapper.updateProceeding(proceedingEntity, proceedingModel);
+ for (uk.gov.laa.ccms.caab.api.entity.ScopeLimitation scopeLimitationEntity :
+ proceedingEntity.getScopeLimitations()) {
+ scopeLimitationEntity.setProceeding(proceedingEntity);
+ }
+ repository.save(proceedingEntity);
+ }
+
+ /**
+ * Gets a proceeding's scope limitations.
+ *
+ * @param id the TDS id for the proceeding.
+ * @return the proceeding's scope limitations.
+ */
+ @Transactional
+ public List getScopeLimitationsForProceeding(final Long id) {
+ return repository.findById(id)
+ .map(uk.gov.laa.ccms.caab.api.entity.Proceeding::getScopeLimitations)
+ .orElseThrow(() -> new CaabApiException(
+ String.format("Application with id %s not found", id),
+ HttpStatus.NOT_FOUND))
+ .stream()
+ .map(mapper::toScopeLimitationModel)
+ .collect(Collectors.toList());
+ }
+
+ /**
+ * Creates and associates a new scope limitation with a specified proceeding.
+ * If the proceeding is not found, a CaabApiException is thrown.
+ *
+ * @param proceedingId The unique identifier of the proceeding.
+ * @param scopeLimitation The Scope Limitation object.
+ * @throws CaabApiException If the proceeding with the specified ID is not found.
+ */
+ @Transactional
+ public void createScopeLimitationForProceeding(
+ final Long proceedingId,
+ final ScopeLimitation scopeLimitation) {
+
+ uk.gov.laa.ccms.caab.api.entity.Proceeding proceeding = repository.findById(proceedingId)
+ .orElseThrow(() -> new CaabApiException(
+ String.format("Proceeding with id %s not found", proceedingId),
+ HttpStatus.NOT_FOUND));
+
+ uk.gov.laa.ccms.caab.api.entity.ScopeLimitation scopeLimitationEntity =
+ mapper.toScopeLimitation(scopeLimitation);
+ scopeLimitationEntity.setProceeding(proceeding);
+ proceeding.getScopeLimitations().add(scopeLimitationEntity);
+
+ repository.save(proceeding);
+ }
+}
diff --git a/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/ScopeLimitationService.java b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/ScopeLimitationService.java
new file mode 100644
index 0000000..b4f0e42
--- /dev/null
+++ b/caab-service/src/main/java/uk/gov/laa/ccms/caab/api/service/ScopeLimitationService.java
@@ -0,0 +1,70 @@
+package uk.gov.laa.ccms.caab.api.service;
+
+import jakarta.transaction.Transactional;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Service;
+import uk.gov.laa.ccms.caab.api.exception.CaabApiException;
+import uk.gov.laa.ccms.caab.api.mapper.ApplicationMapper;
+import uk.gov.laa.ccms.caab.api.repository.ScopeLimitationRepository;
+import uk.gov.laa.ccms.caab.model.ScopeLimitation;
+
+/**
+ * Service responsible for handling scope-limitations operations.
+ *
+ * @see uk.gov.laa.ccms.caab.api.repository.ScopeLimitationRepository
+ * @see ApplicationMapper
+ */
+@Service
+@RequiredArgsConstructor
+@Slf4j
+public class ScopeLimitationService {
+
+ private final ScopeLimitationRepository repository;
+ private final ApplicationMapper mapper;
+
+ /**
+ * Removes a scope limitation.
+ * If the scope limitation is not found, a CaabApiException is thrown.
+ *
+ * @param scopeLimitationId The unique identifier of the scope limitation to be removed.
+ * @throws uk.gov.laa.ccms.caab.api.exception.CaabApiException If the scope limitation with the
+ * specified ID is not found.
+ */
+ @Transactional
+ public void removeScopeLimitation(final Long scopeLimitationId) {
+ if (repository.existsById(scopeLimitationId)) {
+ repository.deleteById(scopeLimitationId);
+ } else {
+ throw new CaabApiException(
+ String.format("Scope Limitation with id: %s not found", scopeLimitationId),
+ HttpStatus.NOT_FOUND);
+ }
+ }
+
+ /**
+ * Updates a scope limitation.
+ * If the scope limitation is not found, a CaabApiException is thrown.
+ *
+ * @param scopeLimitationId The unique identifier of the scope limitation to be updated.
+ * @param scopeLimitationModel The ScopeLimitation object containing the details of the scope
+ * limitation to be updated.
+ * @throws uk.gov.laa.ccms.caab.api.exception.CaabApiException If the scope limitation with the
+ * specified ID is not found.
+ */
+ @Transactional
+ public void updateScopeLimitation(
+ final Long scopeLimitationId,
+ final ScopeLimitation scopeLimitationModel) {
+
+ uk.gov.laa.ccms.caab.api.entity.ScopeLimitation scopeLimitationEntity =
+ repository.findById(scopeLimitationId)
+ .orElseThrow(() -> new CaabApiException(
+ String.format("Scope Limitation with id %s not found", scopeLimitationId),
+ HttpStatus.NOT_FOUND));
+
+ mapper.updateScopeLimitation(scopeLimitationEntity, scopeLimitationModel);
+ repository.save(scopeLimitationEntity);
+ }
+}
diff --git a/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/controller/ApplicationControllerTest.java b/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/controller/ApplicationControllerTest.java
index 0559e44..307a661 100644
--- a/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/controller/ApplicationControllerTest.java
+++ b/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/controller/ApplicationControllerTest.java
@@ -25,19 +25,29 @@
import org.mockito.Mock;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
+import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
+import uk.gov.laa.ccms.caab.api.exception.CaabApiException;
import uk.gov.laa.ccms.caab.api.service.ApplicationService;
+import uk.gov.laa.ccms.caab.api.service.LinkedCaseService;
+import uk.gov.laa.ccms.caab.api.service.PriorAuthorityService;
+import uk.gov.laa.ccms.caab.api.service.ProceedingService;
+import uk.gov.laa.ccms.caab.api.service.ScopeLimitationService;
import uk.gov.laa.ccms.caab.model.Address;
import uk.gov.laa.ccms.caab.model.ApplicationDetail;
import uk.gov.laa.ccms.caab.model.ApplicationDetails;
import uk.gov.laa.ccms.caab.model.ApplicationProviderDetails;
import uk.gov.laa.ccms.caab.model.ApplicationType;
import uk.gov.laa.ccms.caab.model.Client;
+import uk.gov.laa.ccms.caab.model.CostStructure;
import uk.gov.laa.ccms.caab.model.IntDisplayValue;
import uk.gov.laa.ccms.caab.model.LinkedCase;
+import uk.gov.laa.ccms.caab.model.PriorAuthority;
+import uk.gov.laa.ccms.caab.model.Proceeding;
+import uk.gov.laa.ccms.caab.model.ScopeLimitation;
import uk.gov.laa.ccms.caab.model.StringDisplayValue;
@ExtendWith(SpringExtension.class)
@@ -47,6 +57,16 @@ class ApplicationControllerTest {
@Mock
private ApplicationService applicationService;
+ @Mock
+ private LinkedCaseService linkedCaseService;
+ @Mock
+ private ProceedingService proceedingService;
+ @Mock
+ private PriorAuthorityService priorAuthorityService;
+ @Mock
+ private ScopeLimitationService scopeLimitationService;
+
+
@InjectMocks
private ApplicationController applicationController;
@@ -54,6 +74,8 @@ class ApplicationControllerTest {
private ObjectMapper objectMapper;
+ private String caabUserLoginId = "userLoginId";
+
@BeforeEach
public void setup() {
mockMvc = standaloneSetup(applicationController)
@@ -88,11 +110,11 @@ public void createApplication_isCreated() throws Exception {
when(applicationService.createApplication(applicationDetail)).thenReturn(id);
this.mockMvc.perform(post("/applications")
- .header("Caab-User-Login-Id", loginId)
- .contentType(MediaType.APPLICATION_JSON)
- .content(objectMapper.writeValueAsString(applicationDetail)))
- .andExpect(status().isCreated())
- .andExpect(header().string("Location", "http://localhost/applications/" + id));
+ .header("Caab-User-Login-Id", loginId)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(applicationDetail)))
+ .andExpect(status().isCreated())
+ .andExpect(header().string("Location", "http://localhost/applications/" + id));
}
@Test
@@ -102,8 +124,8 @@ public void getApplication() throws Exception {
when(applicationService.getApplication(id)).thenReturn(new ApplicationDetail());
this.mockMvc.perform(get("/applications/{id}", id))
- .andDo(print())
- .andExpect(status().isOk());
+ .andDo(print())
+ .andExpect(status().isOk());
}
@Test
@@ -221,37 +243,35 @@ public void addApplicationLinkedCase_isCreated() throws Exception {
verify(applicationService).createLinkedCaseForApplication(id, linkedCase);
}
- @Test
- public void updateApplicationLinkedCase_noContent() throws Exception {
- Long id = 1L;
- Long linkedCaseId = 2L;
- String caabUserLoginId = "userLoginId";
- LinkedCase linkedCase = new LinkedCase(); // Set up updated linked case details as required
+ @Test
+ public void updateApplicationLinkedCase_noContent() throws Exception {
+ Long linkedCaseId = 2L;
+ String caabUserLoginId = "userLoginId";
+ LinkedCase linkedCase = new LinkedCase(); // Set up updated linked case details as required
- doNothing().when(applicationService).updateLinkedCaseForApplication(id, linkedCaseId, linkedCase);
+ doNothing().when(linkedCaseService).updateLinkedCase(linkedCaseId, linkedCase);
- this.mockMvc.perform(patch("/applications/{id}/linked-cases/{linkedCaseId}", id, linkedCaseId)
- .header("Caab-User-Login-Id", caabUserLoginId)
- .contentType(MediaType.APPLICATION_JSON)
- .content(objectMapper.writeValueAsString(linkedCase)))
- .andExpect(status().isNoContent());
+ this.mockMvc.perform(patch("/linked-cases/{linkedCaseId}", linkedCaseId)
+ .header("Caab-User-Login-Id", caabUserLoginId)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(linkedCase)))
+ .andExpect(status().isNoContent());
- verify(applicationService).updateLinkedCaseForApplication(id, linkedCaseId, linkedCase);
- }
+ verify(linkedCaseService).updateLinkedCase(linkedCaseId, linkedCase);
+ }
@Test
- public void removeApplicationLinkedCase_noContent() throws Exception {
- Long id = 1L;
+ public void removeLinkedCase_noContent() throws Exception {
Long linkedCaseId = 2L;
String caabUserLoginId = "userLoginId";
- doNothing().when(applicationService).removeLinkedCaseFromApplication(id, linkedCaseId);
+ doNothing().when(linkedCaseService).removeLinkedCase(linkedCaseId);
- this.mockMvc.perform(delete("/applications/{id}/linked-cases/{linkedCaseId}", id, linkedCaseId)
+ this.mockMvc.perform(delete("/linked-cases/{linkedCaseId}", linkedCaseId)
.header("Caab-User-Login-Id", caabUserLoginId))
.andExpect(status().isNoContent());
- verify(applicationService).removeLinkedCaseFromApplication(id, linkedCaseId);
+ verify(linkedCaseService).removeLinkedCase(linkedCaseId);
}
@Test
@@ -275,14 +295,218 @@ public void getApplications() throws Exception {
any(Pageable.class))).thenReturn(new ApplicationDetails());
this.mockMvc.perform(get("/applications")
- .param("case-reference-number", caseRef)
- .param("provider-case-ref", providerRef)
- .param("client-surname", clientSurname)
- .param("client-reference", clientRef)
- .param("fee-earner", feeEarner)
- .param("office-id", officeId)
- .param("status", status))
+ .param("case-reference-number", caseRef)
+ .param("provider-case-ref", providerRef)
+ .param("client-surname", clientSurname)
+ .param("client-reference", clientRef)
+ .param("fee-earner", feeEarner)
+ .param("office-id", officeId)
+ .param("status", status))
.andDo(print())
.andExpect(status().isOk());
}
+
+ @Test
+ public void getApplicationCostStructure_ReturnsCostStructure() throws Exception {
+ Long applicationId = 1L;
+ CostStructure costStructure = new CostStructure();
+
+ when(applicationService.getApplicationCostStructure(applicationId)).thenReturn(costStructure);
+
+ this.mockMvc.perform(get("/applications/{id}/cost-structure", applicationId))
+ .andExpect(status().isOk());
+
+ verify(applicationService).getApplicationCostStructure(applicationId);
+ }
+
+ @Test
+ public void updateApplicationCostStructure_UpdatesSuccessfully() throws Exception {
+ Long applicationId = 1L;
+ CostStructure costStructure = new CostStructure();
+
+ doNothing().when(applicationService).putCostStructure(applicationId, costStructure);
+
+ this.mockMvc.perform(put("/applications/{id}/cost-structure", applicationId)
+ .header("Caab-User-Login-Id", caabUserLoginId)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(costStructure)))
+ .andExpect(status().isNoContent());
+
+ verify(applicationService).putCostStructure(applicationId, costStructure);
+ }
+
+ @Test
+ public void addApplicationProceeding_CreatesProceeding() throws Exception {
+ Long applicationId = 1L;
+ Proceeding proceeding = new Proceeding();
+
+ doNothing().when(applicationService).createProceedingForApplication(applicationId, proceeding);
+
+ this.mockMvc.perform(post("/applications/{id}/proceedings", applicationId)
+ .header("Caab-User-Login-Id", caabUserLoginId)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(proceeding)))
+ .andExpect(status().isCreated());
+
+ verify(applicationService).createProceedingForApplication(applicationId, proceeding);
+ }
+
+ @Test
+ public void getApplicationProceedings_ReturnsProceedingsList() throws Exception {
+ Long applicationId = 1L;
+ List proceedings = List.of(new Proceeding());
+
+ when(applicationService.getProceedingsForApplication(applicationId)).thenReturn(proceedings);
+
+ this.mockMvc.perform(get("/applications/{id}/proceedings", applicationId))
+ .andExpect(status().isOk());
+
+ verify(applicationService).getProceedingsForApplication(applicationId);
+ }
+
+ @Test
+ public void removeProceeding_RemovesProceeding() throws Exception {
+ Long proceedingId = 2L;
+
+ doNothing().when(proceedingService).removeProceeding(proceedingId);
+
+ this.mockMvc.perform(delete("/proceedings/{proceedingId}", proceedingId)
+ .header("Caab-User-Login-Id", caabUserLoginId))
+ .andExpect(status().isNoContent());
+
+ verify(proceedingService).removeProceeding(proceedingId);
+ }
+
+ @Test
+ public void updateProceeding_UpdatesProceeding() throws Exception {
+ Long proceedingId = 2L;
+ Proceeding proceeding = new Proceeding();
+
+
+ doNothing().when(proceedingService).updateProceeding(proceedingId, proceeding);
+
+ this.mockMvc.perform(patch("/proceedings/{proceeding-id}", proceedingId)
+ .contentType(MediaType.APPLICATION_JSON)
+ .header("Caab-User-Login-Id", caabUserLoginId)
+ .content(objectMapper.writeValueAsString(proceeding)))
+ .andExpect(status().isNoContent());
+
+ verify(proceedingService).updateProceeding(proceedingId, proceeding);
+ }
+
+ @Test
+ public void addApplicationPriorAuthority_CreatesPriorAuthority() throws Exception {
+ Long id = 1L;
+ PriorAuthority priorAuthority = new PriorAuthority();
+
+ doNothing().when(applicationService).createPriorAuthorityForApplication(id, priorAuthority);
+
+ this.mockMvc.perform(post("/applications/{id}/prior-authorities", id)
+ .header("Caab-User-Login-Id", caabUserLoginId)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(priorAuthority)))
+ .andExpect(status().isCreated());
+
+ verify(applicationService).createPriorAuthorityForApplication(id, priorAuthority);
+ }
+
+ @Test
+ public void getApplicationPriorAuthorities_ReturnsPriorAuthoritiesList() throws Exception {
+ Long id = 1L;
+ List priorAuthorities = List.of(new PriorAuthority());
+
+ when(applicationService.getPriorAuthoritiesForApplication(id)).thenReturn(priorAuthorities);
+
+ this.mockMvc.perform(get("/applications/{id}/prior-authorities", id))
+ .andExpect(status().isOk());
+
+ verify(applicationService).getPriorAuthoritiesForApplication(id);
+ }
+
+ @Test
+ public void removePriorAuthority_RemovesPriorAuthority() throws Exception {
+ Long priorAuthorityId = 2L;
+
+ doNothing().when(priorAuthorityService).removePriorAuthority(priorAuthorityId);
+
+ this.mockMvc.perform(delete("/prior-authorities/{priorAuthorityId}", priorAuthorityId)
+ .header("Caab-User-Login-Id", caabUserLoginId))
+ .andExpect(status().isNoContent());
+
+ verify(priorAuthorityService).removePriorAuthority(priorAuthorityId);
+ }
+
+ @Test
+ public void updatePriorAuthority_UpdatesPriorAuthority() throws Exception {
+ Long priorAuthorityId = 2L;
+ PriorAuthority priorAuthority = new PriorAuthority();
+
+ doNothing().when(priorAuthorityService).updatePriorAuthority(priorAuthorityId, priorAuthority);
+
+ this.mockMvc.perform(patch("/prior-authorities/{priorAuthorityId}", priorAuthorityId)
+ .header("Caab-User-Login-Id", caabUserLoginId)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(priorAuthority)))
+ .andExpect(status().isNoContent());
+
+ verify(priorAuthorityService).updatePriorAuthority(priorAuthorityId, priorAuthority);
+ }
+
+ @Test
+ public void addProceedingScopeLimitation_CreatesScopeLimitation() throws Exception {
+ Long proceedingId = 1L;
+ ScopeLimitation scopeLimitation = new ScopeLimitation();
+
+ doNothing().when(proceedingService).createScopeLimitationForProceeding(proceedingId, scopeLimitation);
+
+ this.mockMvc.perform(post("/proceedings/{proceedingId}/scope-limitations", proceedingId)
+ .header("Caab-User-Login-Id", caabUserLoginId)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(scopeLimitation)))
+ .andExpect(status().isCreated());
+
+ verify(proceedingService).createScopeLimitationForProceeding(proceedingId, scopeLimitation);
+ }
+
+ @Test
+ public void getApplicationScopeLimitations_ReturnsScopeLimitations() throws Exception {
+ Long proceedingId = 1L;
+ List scopeLimitations = Arrays.asList(new ScopeLimitation());
+
+ when(proceedingService.getScopeLimitationsForProceeding(proceedingId)).thenReturn(scopeLimitations);
+
+ this.mockMvc.perform(get("/proceedings/{proceedingId}/scope-limitations", proceedingId))
+ .andExpect(status().isOk());
+
+ verify(proceedingService).getScopeLimitationsForProceeding(proceedingId);
+ }
+
+ @Test
+ public void removeScopeLimitation_RemovesScopeLimitation() throws Exception {
+ Long scopeLimitationId = 2L;
+
+ doNothing().when(scopeLimitationService).removeScopeLimitation(scopeLimitationId);
+
+ this.mockMvc.perform(delete("/scope-limitations/{scopeLimitationId}", scopeLimitationId)
+ .header("Caab-User-Login-Id", caabUserLoginId))
+ .andExpect(status().isNoContent());
+
+ verify(scopeLimitationService).removeScopeLimitation(scopeLimitationId);
+ }
+
+ @Test
+ public void updateScopeLimitation_UpdatesScopeLimitation() throws Exception {
+ Long scopeLimitationId = 2L;
+ ScopeLimitation scopeLimitation = new ScopeLimitation();
+
+ doNothing().when(scopeLimitationService).updateScopeLimitation(scopeLimitationId, scopeLimitation);
+
+ this.mockMvc.perform(patch("/scope-limitations/{scopeLimitationId}", scopeLimitationId)
+ .header("Caab-User-Login-Id", caabUserLoginId)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(objectMapper.writeValueAsString(scopeLimitation)))
+ .andExpect(status().isNoContent());
+
+ verify(scopeLimitationService).updateScopeLimitation(scopeLimitationId, scopeLimitation);
+ }
}
\ No newline at end of file
diff --git a/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/mapper/ApplicationMapperTest.java b/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/mapper/ApplicationMapperTest.java
index 0021494..caf4759 100644
--- a/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/mapper/ApplicationMapperTest.java
+++ b/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/mapper/ApplicationMapperTest.java
@@ -1189,6 +1189,93 @@ void updateAddress_doesNothingWhenModelIsNull() {
assertEquals("InitialPreferredAddress", address.getPreferredAddress());
}
+ @Test
+ void updateCostStructure_updatesFieldsWhenModelIsNotNull() {
+ CostStructure costStructure = new CostStructure();
+ uk.gov.laa.ccms.caab.model.CostStructure costStructureModel = new uk.gov.laa.ccms.caab.model.CostStructure()
+ .defaultCostLimitation(new BigDecimal("100.00"))
+ .requestedCostLimitation(new BigDecimal("200.00"))
+ .grantedCostLimitation(new BigDecimal("300.00"));
+
+ mapper.updateCostStructure(costStructure, costStructureModel);
+
+ assertEquals(new BigDecimal("100.00"), costStructure.getDefaultCostLimitation());
+ assertEquals(new BigDecimal("200.00"), costStructure.getRequestedCostLimitation());
+ assertEquals(new BigDecimal("300.00"), costStructure.getGrantedCostLimitation());
+ }
+
+ @Test
+ void updateCostStructure_doesNothingWhenModelIsNull() {
+ CostStructure costStructure = new CostStructure();
+
+ mapper.updateCostStructure(costStructure, null);
+
+ assertEquals(new BigDecimal("0"),costStructure.getDefaultCostLimitation());
+ assertEquals(new BigDecimal("0"), costStructure.getRequestedCostLimitation());
+ assertEquals(new BigDecimal("0"), costStructure.getGrantedCostLimitation());
+ }
+
+ @Test
+ void updateLinkedCase_updatesFieldsWhenModelIsNotNull() {
+ LinkedCase linkedCase = new LinkedCase();
+ uk.gov.laa.ccms.caab.model.LinkedCase linkedCaseModel = new uk.gov.laa.ccms.caab.model.LinkedCase()
+ .lscCaseReference("LSC123")
+ .relationToCase("Relation1")
+ .providerCaseReference("Provider123")
+ .feeEarner("FeeEarner1")
+ .status("Active");
+
+ mapper.updateLinkedCase(linkedCase, linkedCaseModel);
+
+ assertEquals("LSC123", linkedCase.getLscCaseReference());
+ assertEquals("Relation1", linkedCase.getRelationToCase());
+ assertEquals("Provider123", linkedCase.getProviderCaseReference());
+ assertEquals("FeeEarner1", linkedCase.getFeeEarner());
+ assertEquals("Active", linkedCase.getStatus());
+ }
+
+ @Test
+ void updateLinkedCase_doesNothingWhenModelIsNull() {
+ LinkedCase linkedCase = new LinkedCase();
+
+ mapper.updateLinkedCase(linkedCase, null);
+
+ assertNull(linkedCase.getLscCaseReference());
+ assertNull(linkedCase.getRelationToCase());
+ assertNull(linkedCase.getProviderCaseReference());
+ assertNull(linkedCase.getFeeEarner());
+ assertNull(linkedCase.getStatus());
+ }
+
+ @Test
+ void updatePriorAuthority_updatesFieldsWhenModelIsNotNull() {
+ PriorAuthority priorAuthority = new PriorAuthority();
+ uk.gov.laa.ccms.caab.model.PriorAuthority priorAuthorityModel = new uk.gov.laa.ccms.caab.model.PriorAuthority()
+ .ebsId("EBSID")
+ .status("Status")
+ .summary("Summary")
+ .justification("Justification");
+
+ mapper.updatePriorAuthority(priorAuthority, priorAuthorityModel);
+
+ assertEquals("EBSID", priorAuthority.getEbsId());
+ assertEquals("Status", priorAuthority.getStatus());
+ assertEquals("Summary", priorAuthority.getSummary());
+ assertEquals("Justification", priorAuthority.getJustification());
+ }
+
+ @Test
+ void updatePriorAuthority_doesNothingWhenModelIsNull() {
+ PriorAuthority priorAuthority = new PriorAuthority();
+
+ mapper.updatePriorAuthority(priorAuthority, null);
+
+ assertNull(priorAuthority.getEbsId());
+ assertNull(priorAuthority.getStatus());
+ assertNull(priorAuthority.getSummary());
+ assertNull(priorAuthority.getJustification());
+ }
+
@NotNull
private static Address buildAddress() {
Address address = new Address();
diff --git a/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/ApplicationServiceTest.java b/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/ApplicationServiceTest.java
index cb9aa26..a2a01b8 100644
--- a/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/ApplicationServiceTest.java
+++ b/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/ApplicationServiceTest.java
@@ -6,6 +6,7 @@
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -25,7 +26,6 @@
import org.springframework.http.HttpStatus;
import uk.gov.laa.ccms.caab.api.entity.Address;
import uk.gov.laa.ccms.caab.api.entity.Application;
-import uk.gov.laa.ccms.caab.api.entity.AuditTrail;
import uk.gov.laa.ccms.caab.api.entity.CostStructure;
import uk.gov.laa.ccms.caab.api.exception.CaabApiException;
import uk.gov.laa.ccms.caab.api.mapper.ApplicationMapper;
@@ -35,6 +35,8 @@
import uk.gov.laa.ccms.caab.model.ApplicationProviderDetails;
import uk.gov.laa.ccms.caab.model.ApplicationType;
import uk.gov.laa.ccms.caab.model.LinkedCase;
+import uk.gov.laa.ccms.caab.model.PriorAuthority;
+import uk.gov.laa.ccms.caab.model.Proceeding;
@ExtendWith(MockitoExtension.class)
class ApplicationServiceTest {
@@ -394,145 +396,237 @@ void createLinkedCaseForApplication_whenApplicationNotExists_throwsException() {
assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
}
+ /**
+ * Test case get applications returns data.
+ */
+ @Test
+ void getApplications_returnsData() {
+ Application application = new Application();
+ application.setLscCaseReference("caseref");
+ application.setProviderCaseReference("provref");
+ application.setClientSurname("surname");
+ application.setClientReference("clientref");
+ application.setFeeEarner("feeearner");
+ application.setOfficeId(100);
+ application.setActualStatus("stat");
+
+ Pageable pageable = Pageable.unpaged();
+
+ Page applicationPage = new PageImpl<>(List.of(application));
+ ApplicationDetails expectedResponse = new ApplicationDetails();
+
+ when(applicationMapper.toApplicationDetails(applicationPage)).thenReturn(expectedResponse);
+ when(applicationRepository.findAll(any(Example.class), eq(pageable))).thenReturn(applicationPage);
+
+ ApplicationDetails response = applicationService.getApplications(
+ application.getLscCaseReference(),
+ application.getProviderCaseReference(),
+ application.getClientSurname(),
+ application.getClientReference(),
+ application.getFeeEarner(),
+ application.getOfficeId(),
+ application.getActualStatus(),
+ pageable
+ );
+
+ verify(applicationMapper).toApplicationDetails(applicationPage);
+ verify(applicationRepository).findAll(any(Example.class), eq(pageable));
+
+ assertEquals(response, expectedResponse);
+ }
+
@Test
- void removeLinkedCaseFromApplication_whenApplicationNotExists_throwsException() {
+ void getProceedingsForApplication_WhenExists_ReturnsProceedings() {
+ Long applicationId = 1L;
+ Application application = new Application();
+ application.setProceedings(new ArrayList<>());
+ Proceeding proceedingModel = new Proceeding();
+ application.getProceedings().add(new uk.gov.laa.ccms.caab.api.entity.Proceeding());
+
+ when(applicationRepository.findById(applicationId)).thenReturn(Optional.of(application));
+ when(applicationMapper.toProceedingModel(any())).thenReturn(proceedingModel);
+
+ List result = applicationService.getProceedingsForApplication(applicationId);
+
+ verify(applicationRepository).findById(applicationId);
+ verify(applicationMapper, times(application.getProceedings().size())).toProceedingModel(any());
+
+ assertFalse(result.isEmpty());
+ assertEquals(proceedingModel, result.get(0));
+ }
+
+ @Test
+ void getProceedingsForApplication_WhenNotExists_ThrowsException() {
Long applicationId = 1L;
- Long linkedCaseId = 2L;
when(applicationRepository.findById(applicationId)).thenReturn(Optional.empty());
CaabApiException exception = assertThrows(CaabApiException.class, () ->
- applicationService.removeLinkedCaseFromApplication(applicationId, linkedCaseId));
+ applicationService.getProceedingsForApplication(applicationId));
assertEquals("Application with id 1 not found", exception.getMessage());
assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
}
-
@Test
- void removeLinkedCaseFromApplication_whenCaseExists_removesLinkedCase() {
+ void createProceedingForApplication_WhenApplicationExists_CreatesProceeding() {
Long applicationId = 1L;
- Long linkedCaseId = 2L;
+ Proceeding proceeding = new Proceeding();
Application application = new Application();
- uk.gov.laa.ccms.caab.api.entity.LinkedCase linkedCaseEntity = new uk.gov.laa.ccms.caab.api.entity.LinkedCase();
- linkedCaseEntity.setId(linkedCaseId);
- application.setLinkedCases(new ArrayList<>(Arrays.asList(linkedCaseEntity)));
+ uk.gov.laa.ccms.caab.api.entity.Proceeding proceedingEntity = new uk.gov.laa.ccms.caab.api.entity.Proceeding();
+ application.setProceedings(new ArrayList<>());
+ proceedingEntity.setScopeLimitations(new ArrayList<>());
when(applicationRepository.findById(applicationId)).thenReturn(Optional.of(application));
+ when(applicationMapper.toProceeding(proceeding)).thenReturn(proceedingEntity);
- applicationService.removeLinkedCaseFromApplication(applicationId, linkedCaseId);
+ applicationService.createProceedingForApplication(applicationId, proceeding);
verify(applicationRepository).findById(applicationId);
+ verify(applicationMapper).toProceeding(proceeding);
verify(applicationRepository).save(application);
- assertFalse(application.getLinkedCases().contains(linkedCaseEntity));
+ assertTrue(application.getProceedings().contains(proceedingEntity));
}
@Test
- void removeLinkedCaseFromApplication_whenCaseNotExists_throwsException() {
+ void createProceedingForApplication_WhenApplicationNotExists_ThrowsException() {
Long applicationId = 1L;
- Long linkedCaseId = 2L;
- Application application = new Application();
- application.setLinkedCases(new ArrayList<>());
+ Proceeding proceeding = new Proceeding();
- when(applicationRepository.findById(applicationId)).thenReturn(Optional.of(application));
+ when(applicationRepository.findById(applicationId)).thenReturn(Optional.empty());
CaabApiException exception = assertThrows(CaabApiException.class, () ->
- applicationService.removeLinkedCaseFromApplication(applicationId, linkedCaseId));
+ applicationService.createProceedingForApplication(applicationId, proceeding));
- assertEquals("Linked case with id 2 not found", exception.getMessage());
+ assertEquals("Application with id 1 not found", exception.getMessage());
assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
}
@Test
- void updateLinkedCaseForApplication_whenApplicationNotExists_throwsException() {
+ void getPriorAuthoritiesForApplication_WhenExists_ReturnsPriorAuthorities() {
+ Long applicationId = 1L;
+ Application application = new Application();
+ application.setPriorAuthorities(new ArrayList<>());
+ PriorAuthority priorAuthorityModel = new PriorAuthority();
+ application.getPriorAuthorities().add(new uk.gov.laa.ccms.caab.api.entity.PriorAuthority());
+
+ when(applicationRepository.findById(applicationId)).thenReturn(Optional.of(application));
+ when(applicationMapper.toPriorAuthorityModel(any())).thenReturn(priorAuthorityModel);
+
+ List result = applicationService.getPriorAuthoritiesForApplication(applicationId);
+
+ verify(applicationRepository).findById(applicationId);
+ verify(applicationMapper, times(application.getPriorAuthorities().size())).toPriorAuthorityModel(any());
+
+ assertFalse(result.isEmpty());
+ assertEquals(priorAuthorityModel, result.get(0));
+ }
+
+ @Test
+ void getPriorAuthoritiesForApplication_WhenNotExists_ThrowsException() {
Long applicationId = 1L;
- Long linkedCaseId = 2L;
- LinkedCase linkedCaseModel = new LinkedCase();
when(applicationRepository.findById(applicationId)).thenReturn(Optional.empty());
CaabApiException exception = assertThrows(CaabApiException.class, () ->
- applicationService.updateLinkedCaseForApplication(applicationId, linkedCaseId, linkedCaseModel));
+ applicationService.getPriorAuthoritiesForApplication(applicationId));
assertEquals("Application with id 1 not found", exception.getMessage());
assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
}
@Test
- void updateLinkedCaseForApplication_whenCaseExists_updatesLinkedCase() {
+ void createPriorAuthorityForApplication_WhenApplicationExists_CreatesPriorAuthority() {
Long applicationId = 1L;
- Long linkedCaseId = 2L;
- LinkedCase linkedCaseModel = new LinkedCase();
+ PriorAuthority priorAuthority = new PriorAuthority();
Application application = new Application();
- application.setLinkedCases(new ArrayList<>());
-
- uk.gov.laa.ccms.caab.api.entity.LinkedCase linkedCaseEntity = new uk.gov.laa.ccms.caab.api.entity.LinkedCase();
- linkedCaseEntity.setId(linkedCaseId);
- application.setLinkedCases(new ArrayList<>(Arrays.asList(linkedCaseEntity)));
+ uk.gov.laa.ccms.caab.api.entity.PriorAuthority priorAuthorityEntity = new uk.gov.laa.ccms.caab.api.entity.PriorAuthority();
+ application.setPriorAuthorities(new ArrayList<>());
+ priorAuthorityEntity.setItems(new ArrayList<>());
when(applicationRepository.findById(applicationId)).thenReturn(Optional.of(application));
+ when(applicationMapper.toPriorAuthority(priorAuthority)).thenReturn(priorAuthorityEntity);
- applicationService.updateLinkedCaseForApplication(applicationId, linkedCaseId, linkedCaseModel);
+ applicationService.createPriorAuthorityForApplication(applicationId, priorAuthority);
verify(applicationRepository).findById(applicationId);
- verify(applicationMapper).updateLinkedCase(linkedCaseEntity, linkedCaseModel);
+ verify(applicationMapper).toPriorAuthority(priorAuthority);
verify(applicationRepository).save(application);
+ assertTrue(application.getPriorAuthorities().contains(priorAuthorityEntity));
}
@Test
- void updateLinkedCaseForApplication_whenCaseNotExists_throwsException() {
+ void createPriorAuthorityForApplication_WhenApplicationNotExists_ThrowsException() {
+ Long applicationId = 1L;
+ PriorAuthority priorAuthority = new PriorAuthority();
+
+ when(applicationRepository.findById(applicationId)).thenReturn(Optional.empty());
+
+ CaabApiException exception = assertThrows(CaabApiException.class, () ->
+ applicationService.createPriorAuthorityForApplication(applicationId, priorAuthority));
+
+ assertEquals("Application with id 1 not found", exception.getMessage());
+ assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
+ }
+
+ @Test
+ void getApplicationCostStructure_WhenExists_ReturnsCostStructure() {
Long applicationId = 1L;
- Long linkedCaseId = 2L;
- LinkedCase linkedCaseModel = new LinkedCase();
Application application = new Application();
- application.setLinkedCases(new ArrayList<>());
+ application.setCosts(new CostStructure());
+ uk.gov.laa.ccms.caab.model.CostStructure expectedCostStructure = new uk.gov.laa.ccms.caab.model.CostStructure();
when(applicationRepository.findById(applicationId)).thenReturn(Optional.of(application));
+ when(applicationMapper.toCostStructureModel(application.getCosts())).thenReturn(expectedCostStructure);
+
+ uk.gov.laa.ccms.caab.model.CostStructure result = applicationService.getApplicationCostStructure(applicationId);
+
+ verify(applicationRepository).findById(applicationId);
+ verify(applicationMapper).toCostStructureModel(application.getCosts());
+
+ assertEquals(expectedCostStructure, result);
+ }
+
+ @Test
+ void getApplicationCostStructure_WhenNotExists_ThrowsException() {
+ Long applicationId = 1L;
+
+ when(applicationRepository.findById(applicationId)).thenReturn(Optional.empty());
CaabApiException exception = assertThrows(CaabApiException.class, () ->
- applicationService.updateLinkedCaseForApplication(applicationId, linkedCaseId, linkedCaseModel));
+ applicationService.getApplicationCostStructure(applicationId));
- assertEquals("Linked case with id 2 not found", exception.getMessage());
+ assertEquals("Cost structure for application with id 1 not found", exception.getMessage());
assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
}
- /**
- * Test case get applications returns data.
- */
@Test
- void getApplications_returnsData() {
+ void putCostStructure_WhenExists_UpdatesCostStructure() {
+ Long applicationId = 1L;
+ uk.gov.laa.ccms.caab.model.CostStructure costStructure = new uk.gov.laa.ccms.caab.model.CostStructure();
Application application = new Application();
- application.setLscCaseReference("caseref");
- application.setProviderCaseReference("provref");
- application.setClientSurname("surname");
- application.setClientReference("clientref");
- application.setFeeEarner("feeearner");
- application.setOfficeId(100);
- application.setActualStatus("stat");
- Pageable pageable = Pageable.unpaged();
+ when(applicationRepository.findById(applicationId)).thenReturn(Optional.of(application));
- Page applicationPage = new PageImpl<>(List.of(application));
- ApplicationDetails expectedResponse = new ApplicationDetails();
+ applicationService.putCostStructure(applicationId, costStructure);
- when(applicationMapper.toApplicationDetails(applicationPage)).thenReturn(expectedResponse);
- when(applicationRepository.findAll(any(Example.class), eq(pageable))).thenReturn(applicationPage);
+ verify(applicationRepository).findById(applicationId);
+ verify(applicationMapper).addCostStructureToApplication(application, costStructure);
+ verify(applicationRepository).save(application);
+ }
- ApplicationDetails response = applicationService.getApplications(
- application.getLscCaseReference(),
- application.getProviderCaseReference(),
- application.getClientSurname(),
- application.getClientReference(),
- application.getFeeEarner(),
- application.getOfficeId(),
- application.getActualStatus(),
- pageable
- );
+ @Test
+ void putCostStructure_WhenNotExists_ThrowsException() {
+ Long applicationId = 1L;
+ uk.gov.laa.ccms.caab.model.CostStructure costStructure = new uk.gov.laa.ccms.caab.model.CostStructure();
- verify(applicationMapper).toApplicationDetails(applicationPage);
- verify(applicationRepository).findAll(any(Example.class), eq(pageable));
+ when(applicationRepository.findById(applicationId)).thenReturn(Optional.empty());
- assertEquals(response, expectedResponse);
+ CaabApiException exception = assertThrows(CaabApiException.class, () ->
+ applicationService.putCostStructure(applicationId, costStructure));
+
+ assertEquals("Application with id 1 not found", exception.getMessage());
+ assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
}
/**
@@ -564,5 +658,7 @@ private Application createApplicationWithExistingAddressAndCosts() {
return application;
}
+
+
}
diff --git a/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/LinkedCaseServiceTest.java b/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/LinkedCaseServiceTest.java
new file mode 100644
index 0000000..c079304
--- /dev/null
+++ b/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/LinkedCaseServiceTest.java
@@ -0,0 +1,95 @@
+package uk.gov.laa.ccms.caab.api.service;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.Optional;
+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 org.springframework.http.HttpStatus;
+import uk.gov.laa.ccms.caab.api.exception.CaabApiException;
+import uk.gov.laa.ccms.caab.api.mapper.ApplicationMapper;
+import uk.gov.laa.ccms.caab.api.repository.LinkedCaseRepository;
+import uk.gov.laa.ccms.caab.model.LinkedCase;
+
+@ExtendWith(MockitoExtension.class)
+class LinkedCaseServiceTest {
+
+ @Mock
+ private LinkedCaseRepository linkedCaseRepository;
+
+ @Mock
+ private ApplicationMapper applicationMapper;
+
+ @InjectMocks
+ private LinkedCaseService linkedCaseService;
+
+ @Test
+ void removeLinkedCaseFromApplication_whenCaseExists_removesLinkedCase() {
+ Long linkedCaseId = 2L;
+
+ when(linkedCaseRepository.existsById(linkedCaseId)).thenReturn(true);
+ doNothing().when(linkedCaseRepository).deleteById(linkedCaseId);
+
+ linkedCaseService.removeLinkedCase(linkedCaseId);
+
+ verify(linkedCaseRepository).existsById(linkedCaseId);
+ verify(linkedCaseRepository).deleteById(linkedCaseId);
+ }
+
+ @Test
+ void removeLinkedCaseFromApplication_whenCaseNotExists_throwsException() {
+ Long linkedCaseId = 2L;
+
+ when(linkedCaseRepository.existsById(linkedCaseId)).thenReturn(false);
+
+ CaabApiException exception = assertThrows(CaabApiException.class, () ->
+ linkedCaseService.removeLinkedCase(linkedCaseId));
+
+ assertEquals("Linked case with id: 2 not found", exception.getMessage());
+ assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
+ }
+
+
+ @Test
+ void updateLinkedCaseForApplication_whenCaseExists_updatesLinkedCase() {
+ Long linkedCaseId = 2L;
+ LinkedCase linkedCaseModel = new LinkedCase();
+
+ uk.gov.laa.ccms.caab.api.entity.LinkedCase linkedCaseEntity = new uk.gov.laa.ccms.caab.api.entity.LinkedCase();
+ linkedCaseEntity.setId(linkedCaseId);
+
+ when(linkedCaseRepository.findById(linkedCaseId)).thenReturn(Optional.of(linkedCaseEntity));
+ when(linkedCaseRepository.save(linkedCaseEntity)).thenReturn(linkedCaseEntity);
+
+ linkedCaseService.updateLinkedCase(linkedCaseId, linkedCaseModel);
+
+ verify(applicationMapper).updateLinkedCase(linkedCaseEntity, linkedCaseModel);
+ verify(linkedCaseRepository).findById(linkedCaseId);
+ verify(linkedCaseRepository).save(linkedCaseEntity);
+ }
+
+ @Test
+ void updateLinkedCaseForApplication_whenCaseNotExists_throwsException() {
+ Long linkedCaseId = 2L;
+ LinkedCase linkedCaseModel = new LinkedCase();
+
+ uk.gov.laa.ccms.caab.api.entity.LinkedCase linkedCaseEntity = new uk.gov.laa.ccms.caab.api.entity.LinkedCase();
+ linkedCaseEntity.setId(linkedCaseId);
+
+ when(linkedCaseRepository.findById(linkedCaseId)).thenReturn(Optional.empty());
+
+ CaabApiException exception = assertThrows(CaabApiException.class, () ->
+ linkedCaseService.updateLinkedCase(linkedCaseId, linkedCaseModel));
+
+ assertEquals("Linked case with id 2 not found", exception.getMessage());
+ assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
+ }
+
+}
\ No newline at end of file
diff --git a/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/PriorAuthorityServiceTest.java b/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/PriorAuthorityServiceTest.java
new file mode 100644
index 0000000..98722be
--- /dev/null
+++ b/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/PriorAuthorityServiceTest.java
@@ -0,0 +1,89 @@
+package uk.gov.laa.ccms.caab.api.service;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.*;
+
+import java.util.Optional;
+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 org.springframework.http.HttpStatus;
+import uk.gov.laa.ccms.caab.api.exception.CaabApiException;
+import uk.gov.laa.ccms.caab.api.mapper.ApplicationMapper;
+import uk.gov.laa.ccms.caab.api.repository.PriorAuthorityRepository;
+import uk.gov.laa.ccms.caab.model.PriorAuthority;
+
+@ExtendWith(MockitoExtension.class)
+class PriorAuthorityServiceTest {
+
+ @Mock
+ private PriorAuthorityRepository priorAuthorityRepository;
+
+ @Mock
+ private ApplicationMapper applicationMapper;
+
+ @InjectMocks
+ private PriorAuthorityService priorAuthorityService;
+
+ @Test
+ void removePriorAuthority_whenAuthorityExists_removesPriorAuthority() {
+ Long priorAuthorityId = 1L;
+
+ when(priorAuthorityRepository.existsById(priorAuthorityId)).thenReturn(true);
+ doNothing().when(priorAuthorityRepository).deleteById(priorAuthorityId);
+
+ priorAuthorityService.removePriorAuthority(priorAuthorityId);
+
+ verify(priorAuthorityRepository).existsById(priorAuthorityId);
+ verify(priorAuthorityRepository).deleteById(priorAuthorityId);
+ }
+
+ @Test
+ void removePriorAuthority_whenAuthorityNotExists_throwsException() {
+ Long priorAuthorityId = 1L;
+
+ when(priorAuthorityRepository.existsById(priorAuthorityId)).thenReturn(false);
+
+ CaabApiException exception = assertThrows(CaabApiException.class, () ->
+ priorAuthorityService.removePriorAuthority(priorAuthorityId));
+
+ assertEquals("Prior Authority with id: 1 not found", exception.getMessage());
+ assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
+ }
+
+ @Test
+ void updatePriorAuthority_whenAuthorityExists_updatesPriorAuthority() {
+ Long priorAuthorityId = 1L;
+ PriorAuthority priorAuthorityModel = new PriorAuthority();
+
+ uk.gov.laa.ccms.caab.api.entity.PriorAuthority priorAuthorityEntity = new uk.gov.laa.ccms.caab.api.entity.PriorAuthority();
+ priorAuthorityEntity.setId(priorAuthorityId);
+
+ when(priorAuthorityRepository.findById(priorAuthorityId)).thenReturn(Optional.of(priorAuthorityEntity));
+ when(priorAuthorityRepository.save(priorAuthorityEntity)).thenReturn(priorAuthorityEntity);
+
+ priorAuthorityService.updatePriorAuthority(priorAuthorityId, priorAuthorityModel);
+
+ verify(applicationMapper).updatePriorAuthority(priorAuthorityEntity, priorAuthorityModel);
+ verify(priorAuthorityRepository).findById(priorAuthorityId);
+ verify(priorAuthorityRepository).save(priorAuthorityEntity);
+ }
+
+ @Test
+ void updatePriorAuthority_whenAuthorityNotExists_throwsException() {
+ Long priorAuthorityId = 1L;
+ PriorAuthority priorAuthorityModel = new PriorAuthority();
+
+ when(priorAuthorityRepository.findById(priorAuthorityId)).thenReturn(Optional.empty());
+
+ CaabApiException exception = assertThrows(CaabApiException.class, () ->
+ priorAuthorityService.updatePriorAuthority(priorAuthorityId, priorAuthorityModel));
+
+ assertEquals("Prior Authority with id 1 not found", exception.getMessage());
+ assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
+ }
+
+}
diff --git a/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/ProceedingServiceTest.java b/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/ProceedingServiceTest.java
new file mode 100644
index 0000000..8b978d3
--- /dev/null
+++ b/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/ProceedingServiceTest.java
@@ -0,0 +1,158 @@
+package uk.gov.laa.ccms.caab.api.service;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+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 org.springframework.http.HttpStatus;
+import uk.gov.laa.ccms.caab.api.exception.CaabApiException;
+import uk.gov.laa.ccms.caab.api.mapper.ApplicationMapper;
+import uk.gov.laa.ccms.caab.api.repository.ProceedingRepository;
+import uk.gov.laa.ccms.caab.model.Proceeding;
+import uk.gov.laa.ccms.caab.model.ScopeLimitation;
+
+
+@ExtendWith(MockitoExtension.class)
+class ProceedingServiceTest {
+
+ @Mock
+ private ProceedingRepository proceedingRepository;
+
+ @Mock
+ private ApplicationMapper applicationMapper;
+
+ @InjectMocks
+ private ProceedingService proceedingService;
+
+ @Test
+ void removeProceeding_whenExists_removesProceeding() {
+ Long proceedingId = 1L;
+ when(proceedingRepository.existsById(proceedingId)).thenReturn(true);
+ doNothing().when(proceedingRepository).deleteById(proceedingId);
+
+ proceedingService.removeProceeding(proceedingId);
+
+ verify(proceedingRepository).existsById(proceedingId);
+ verify(proceedingRepository).deleteById(proceedingId);
+ }
+
+ @Test
+ void removeProceeding_whenNotExists_throwsException() {
+ Long proceedingId = 1L;
+ when(proceedingRepository.existsById(proceedingId)).thenReturn(false);
+
+ CaabApiException exception = assertThrows(CaabApiException.class, () ->
+ proceedingService.removeProceeding(proceedingId));
+
+ assertEquals("Proceeding with id: 1 not found", exception.getMessage());
+ assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
+ }
+
+ @Test
+ void updateProceeding_whenExists_updatesProceeding() {
+ Long proceedingId = 1L;
+ Proceeding proceedingModel = new Proceeding();
+ uk.gov.laa.ccms.caab.api.entity.Proceeding proceedingEntity = new uk.gov.laa.ccms.caab.api.entity.Proceeding();
+ proceedingEntity.setId(proceedingId);
+ uk.gov.laa.ccms.caab.api.entity.ScopeLimitation scopeLimitationEntity = new uk.gov.laa.ccms.caab.api.entity.ScopeLimitation();
+ proceedingEntity.setScopeLimitations(List.of(scopeLimitationEntity));
+
+ when(proceedingRepository.findById(proceedingId)).thenReturn(Optional.of(proceedingEntity));
+ when(proceedingRepository.save(proceedingEntity)).thenReturn(proceedingEntity);
+
+ proceedingService.updateProceeding(proceedingId, proceedingModel);
+
+ verify(applicationMapper).updateProceeding(proceedingEntity, proceedingModel);
+ verify(proceedingRepository).findById(proceedingId);
+ verify(proceedingRepository).save(proceedingEntity);
+ }
+
+ @Test
+ void updateProceeding_whenNotExists_throwsException() {
+ Long proceedingId = 1L;
+ Proceeding proceedingModel = new Proceeding();
+
+ when(proceedingRepository.findById(proceedingId)).thenReturn(Optional.empty());
+
+ CaabApiException exception = assertThrows(CaabApiException.class, () ->
+ proceedingService.updateProceeding(proceedingId, proceedingModel));
+
+ assertEquals("Proceeding with id 1 not found", exception.getMessage());
+ assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
+ }
+
+ @Test
+ void getScopeLimitationsForProceeding_whenExists_returnsScopeLimitations() {
+ Long proceedingId = 1L;
+ uk.gov.laa.ccms.caab.api.entity.Proceeding proceedingEntity = new uk.gov.laa.ccms.caab.api.entity.Proceeding();
+ uk.gov.laa.ccms.caab.api.entity.ScopeLimitation scopeLimitationEntity = new uk.gov.laa.ccms.caab.api.entity.ScopeLimitation();
+ proceedingEntity.setScopeLimitations(List.of(scopeLimitationEntity));
+
+ when(proceedingRepository.findById(proceedingId)).thenReturn(Optional.of(proceedingEntity));
+ when(applicationMapper.toScopeLimitationModel(any())).thenAnswer(i -> new ScopeLimitation());
+
+ List result = proceedingService.getScopeLimitationsForProceeding(proceedingId);
+
+ assertFalse(result.isEmpty());
+ verify(proceedingRepository).findById(proceedingId);
+ }
+
+ @Test
+ void getScopeLimitationsForProceeding_whenNotExists_throwsException() {
+ Long proceedingId = 1L;
+
+ when(proceedingRepository.findById(proceedingId)).thenReturn(Optional.empty());
+
+ CaabApiException exception = assertThrows(CaabApiException.class, () ->
+ proceedingService.getScopeLimitationsForProceeding(proceedingId));
+
+ assertEquals("Application with id 1 not found", exception.getMessage());
+ assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
+ }
+
+ @Test
+ void createScopeLimitationForProceeding_whenProceedingExists_createsScopeLimitation() {
+ Long proceedingId = 1L;
+ ScopeLimitation scopeLimitation = new ScopeLimitation();
+ uk.gov.laa.ccms.caab.api.entity.Proceeding proceedingEntity = new uk.gov.laa.ccms.caab.api.entity.Proceeding();
+ uk.gov.laa.ccms.caab.api.entity.ScopeLimitation scopeLimitationEntity = new uk.gov.laa.ccms.caab.api.entity.ScopeLimitation();
+ List scopeLimitationEntities = new ArrayList<>();
+ scopeLimitationEntities.add(scopeLimitationEntity);
+ proceedingEntity.setScopeLimitations(scopeLimitationEntities);
+
+ when(proceedingRepository.findById(proceedingId)).thenReturn(Optional.of(proceedingEntity));
+ when(proceedingRepository.save(proceedingEntity)).thenReturn(proceedingEntity);
+ when(applicationMapper.toScopeLimitation(scopeLimitation)).thenReturn(scopeLimitationEntity);
+
+ proceedingService.createScopeLimitationForProceeding(proceedingId, scopeLimitation);
+
+ verify(proceedingRepository).findById(proceedingId);
+ verify(proceedingRepository).save(any(uk.gov.laa.ccms.caab.api.entity.Proceeding.class));
+ }
+
+ @Test
+ void createScopeLimitationForProceeding_whenProceedingNotExists_throwsException() {
+ Long proceedingId = 1L;
+ ScopeLimitation scopeLimitation = new ScopeLimitation();
+
+ when(proceedingRepository.findById(proceedingId)).thenReturn(Optional.empty());
+
+ CaabApiException exception = assertThrows(CaabApiException.class, () ->
+ proceedingService.createScopeLimitationForProceeding(proceedingId, scopeLimitation));
+
+ assertEquals("Proceeding with id 1 not found", exception.getMessage());
+ assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
+ }
+}
diff --git a/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/ScopeLimitationServiceTest.java b/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/ScopeLimitationServiceTest.java
new file mode 100644
index 0000000..41608a3
--- /dev/null
+++ b/caab-service/src/test/java/uk/gov/laa/ccms/caab/api/service/ScopeLimitationServiceTest.java
@@ -0,0 +1,84 @@
+package uk.gov.laa.ccms.caab.api.service;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.util.Optional;
+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 org.springframework.http.HttpStatus;
+import uk.gov.laa.ccms.caab.api.exception.CaabApiException;
+import uk.gov.laa.ccms.caab.api.mapper.ApplicationMapper;
+import uk.gov.laa.ccms.caab.api.repository.ScopeLimitationRepository;
+import uk.gov.laa.ccms.caab.model.ScopeLimitation;
+
+@ExtendWith(MockitoExtension.class)
+class ScopeLimitationServiceTest {
+
+ @Mock
+ private ScopeLimitationRepository scopeLimitationRepository;
+
+ @Mock
+ private ApplicationMapper applicationMapper;
+
+ @InjectMocks
+ private ScopeLimitationService scopeLimitationService;
+
+ @Test
+ void removeScopeLimitation_whenExists_removesScopeLimitation() {
+ Long scopeLimitationId = 1L;
+ when(scopeLimitationRepository.existsById(scopeLimitationId)).thenReturn(true);
+ doNothing().when(scopeLimitationRepository).deleteById(scopeLimitationId);
+
+ scopeLimitationService.removeScopeLimitation(scopeLimitationId);
+
+ verify(scopeLimitationRepository).existsById(scopeLimitationId);
+ verify(scopeLimitationRepository).deleteById(scopeLimitationId);
+ }
+
+ @Test
+ void removeScopeLimitation_whenNotExists_throwsException() {
+ Long scopeLimitationId = 1L;
+ when(scopeLimitationRepository.existsById(scopeLimitationId)).thenReturn(false);
+
+ CaabApiException exception = assertThrows(CaabApiException.class, () ->
+ scopeLimitationService.removeScopeLimitation(scopeLimitationId));
+
+ assertEquals("Scope Limitation with id: 1 not found", exception.getMessage());
+ assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
+ }
+
+ @Test
+ void updateScopeLimitation_whenExists_updatesScopeLimitation() {
+ Long scopeLimitationId = 1L;
+ ScopeLimitation scopeLimitationModel = new ScopeLimitation();
+ uk.gov.laa.ccms.caab.api.entity.ScopeLimitation scopeLimitationEntity = new uk.gov.laa.ccms.caab.api.entity.ScopeLimitation();
+ scopeLimitationEntity.setId(scopeLimitationId);
+
+ when(scopeLimitationRepository.findById(scopeLimitationId)).thenReturn(Optional.of(scopeLimitationEntity));
+ when(scopeLimitationRepository.save(scopeLimitationEntity)).thenReturn(scopeLimitationEntity);
+
+ scopeLimitationService.updateScopeLimitation(scopeLimitationId, scopeLimitationModel);
+
+ verify(applicationMapper).updateScopeLimitation(scopeLimitationEntity, scopeLimitationModel);
+ verify(scopeLimitationRepository).findById(scopeLimitationId);
+ verify(scopeLimitationRepository).save(scopeLimitationEntity);
+ }
+
+ @Test
+ void updateScopeLimitation_whenNotExists_throwsException() {
+ Long scopeLimitationId = 1L;
+ ScopeLimitation scopeLimitationModel = new ScopeLimitation();
+
+ when(scopeLimitationRepository.findById(scopeLimitationId)).thenReturn(Optional.empty());
+
+ CaabApiException exception = assertThrows(CaabApiException.class, () ->
+ scopeLimitationService.updateScopeLimitation(scopeLimitationId, scopeLimitationModel));
+
+ assertEquals("Scope Limitation with id 1 not found", exception.getMessage());
+ assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus());
+ }
+}