diff --git a/.codeclimate.yml b/.codeclimate.yml index 1891493f0d..af9d856f0d 100644 --- a/.codeclimate.yml +++ b/.codeclimate.yml @@ -22,15 +22,14 @@ exclude_patterns: - "src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/SubmissionMapper.java" - "src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionService.java" - "src/backend/efiling-backend-demo/src/main/java/ca/bc/gov/open/jag/efilingbackenddemo/EfilingBackendDemoApplication.java" - - "src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/EfilingWorkerApplication.java" - - "src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/service/DocumentStoreService.java" - "src/backend/libs/efiling-lookup-client/src/main/java/ca/bc/gov/open/jag/efilinglookupclient/EfilingLookupService.java" - "src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/EfilingStatusService.java" - "src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/EfilingSubmissionService.java" + - "src/backend/**/test/**" # Frontend Pattern Excludes - "src/frontend/*/src/*.js" + - "src/frontend/*/src/components/hoc/*.js" - "src/frontend/efiling-frontend/src/modules/confirmationPopupTestData.js" - - "src/frontend/shared-components/src/modules/termsOfUseTestData.js" - "src/frontend/*/public/" - "src/frontend/*/.storybook/" diff --git a/.env.template b/.env.template index d36f8fa712..2fdda5001d 100644 --- a/.env.template +++ b/.env.template @@ -1,4 +1,15 @@ -MVN_PROFILE=demo +DEMO_MODE= +MVN_PROFILE= +SERVER_PORT=8080 + +# KEYCLOAK CONFIG +KEYCLOAK_SSL_REQUIRED=none +KEYCLOAK_RESOURCE=efiling-api +KEYCLOAK_URL=http://localhost:8081/auth +KEYCLOAK_REALM=Efiling-Hub +KEYCLOAK_CREDENTIALS_SECRET= +KEYCLOAK_AUTH_SERVER_URL= + CSO_ACCOUNTFACADE_URI= CSO_ACCOUNTFACADE_USERNAME= CSO_ACCOUNTFACADE_PASSWORD= @@ -8,6 +19,43 @@ CSO_ROLEREGISTRY_URI= CSO_LOOKUPFACADE_USERNAME= CSO_LOOKUPFACADE_PASSWORD= CSO_LOOKUPFACADE_URI= -BCEID_LOOKUP_USERNAME= -BCEID_LOOKUP_PASSWORD= -BCEID_LOOKUP_URI= +CSO_BCEIDSERVICE_URI= +CSO_BCEIDSERVICE_USERNAME= +CSO_BCEIDSERVICE_PASSWORD= +CSO_FILINGSTATSFACADE_URI= +CSO_FILINGSTATSFACADE_USERNAME= +CSO_FILINGSTATSFACADE_PASSWORD= +CSOWS_USERNAME= +CSOWS_PASSWORD= +CSOWS_URI= +CSO_FILINGFACADE_URI= +CSO_FILINGFACADE_PASSWORD= +CSO_FILINGFACADE_USERNAME= +CSO_SERVICEFACADE_URI= +CSO_SERVICEFACADE_USERNAME= +CSO_SERVICEFACADE_PASSWORD= +CSO_FILE_SERVER_HOST= +CSO_DEBUG_ENABLED=true + +CEIS_BASE_PATH= +CEIS_USERNAME=BLANK? +CEIS_PASSWORD=BLANK? + +BAMBORA_APIPASSCODE= +BAMBORA_APIBASEPATH= +BAMBORA_MERCHANTID= +BAMBORA_PROFILE_URL= +BAMBORA_HASHKEY= +BAMBORA_PROFILE_SERVICE_VERSION= +BAMBORA_URL_EXPIRY= + +MAIL_SEND_BASE_URL= + +SFTP_KNOWNHOSTS= +SFTP_REMOTELOCATION= +SFTP_PRIVATE_KEY= + +BCEID_SERVICE_URI= +BCEID_SERVICE_USERNAME= +BCEID_SERVICE_PASSWORD= +BCEID_SERVICE_ONLINE_SERVICE_ID= diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..8cd5aff5be --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.sh text eol=lf diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000000..dd84ea7824 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,38 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Smartphone (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + - Browser [e.g. stock browser, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000000..bbcbbe7d61 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/onboarding-request.md b/.github/ISSUE_TEMPLATE/onboarding-request.md new file mode 100644 index 0000000000..cdbd8d031b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/onboarding-request.md @@ -0,0 +1,15 @@ +--- +name: Onboarding Request +about: Request for access to Efiling Hub API and Frontend +title: "[ONBOARDING]" +labels: Onboarding +assignees: akroon3r, alexjoybc + +--- + +After this issue has been opened, please provide the following information: + +- contact email that admins can reach you at +- a brief description of what you're looking to accomplish by integrating with the efiling-hub +- a link to github repository of the application that is requesting access to the efiling-hub +- a list of the types of documents you're looking to upload to the efiling-hub diff --git a/.github/dependabot.yml b/.github/dependabot.yml index c6abd64c51..bf3d702442 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,10 +5,16 @@ updates: directory: "/src/backend" schedule: interval: "daily" - time: "18:00" - # npm dependencies + time: "05:00" + # npm dependencies - frontend - package-ecosystem: "npm" - directory: "/src/frontend" + directory: "/src/frontend/efiling-frontend" schedule: interval: "daily" - time: "18:00" + time: "05:00" + # npm dependencies - demo + - package-ecosystem: "npm" + directory: "/src/frontend/efiling-demo" + schedule: + interval: "daily" + time: "05:00" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 7573b2a19d..e3477f936c 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -9,6 +9,7 @@ This PR includes the following proposed change(s): - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Refactoring / Documentation +- [ ] Version change if your change is a breaking change, please add `breaking change` label to this PR @@ -16,6 +17,16 @@ if your change is a breaking change, please add `breaking change` label to this Please describe the tests that you ran to verify your changes. +## Does the change impact or break the Docker build? + +- [ ] Yes +- [ ] No + +If Yes: Has Docker been updated accordingly? + +- [ ] Yes +- [ ] No + ## Checklist: - [ ] My code follows the style guidelines of this project diff --git a/.github/workflows/code-climate-coverage-aggregation.yml b/.github/workflows/code-climate-coverage-aggregation.yml index 9fed1b0124..2e7ce1b7c7 100644 --- a/.github/workflows/code-climate-coverage-aggregation.yml +++ b/.github/workflows/code-climate-coverage-aggregation.yml @@ -10,90 +10,30 @@ jobs: yarn: env: FILE_COUNTER: 0 - CC_TEST_REPORTER_ID: 9ada3133fe9babf91a222009998b3545b7eae897a05900930bfa8a27fd82f385 ACTION_DEBUG: true - name: Create, format and upload Javascript coverage artifact + name: Build and Test React Apps runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - # Get Code Climate binary - - name: Download Code Climate Binary - run: curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter - - # Permissions applied to the Code Climate Executable - - name: Apply executable perms to Code Climate Binary - run: chmod +x ./cc-test-reporter - - # Before build - - name: Before build - run: ./cc-test-reporter before-build - - # Set required Git env vars for either pull request - - name: Set ENV for codeclimate (pull_request) - run: | - echo "::set-env name=GIT_BRANCH::${{ github.event.pull_request.head.ref }}" - echo "::set-env name=GIT_COMMIT_SHA::${{ github.event.pull_request.head.sha }}" - if: github.event_name == 'pull_request' - - # Set required Git env vars for a push to master - - name: Set ENV for codeclimate (push) - run: | - echo "::set-env name=GIT_BRANCH::$GITHUB_REF" - echo "::set-env name=GIT_COMMIT_SHA::$GITHUB_SHA" - if: github.event_name == 'push' - - # Trimming the ref to master in order to publish correct report (paambaati) - - name: Set ref/head/master to master - run: | - echo "::set-env name=GIT_BRANCH::master" - if: env.GIT_BRANCH == 'refs/heads/master' + - uses: actions/checkout@v4 + - name: Printing node and yarn versions + run: node --version && yarn --version # Figure out where yarn is caching things - name: Yarn Cache run: yarn cache dir - # Implement Caching Action for Yarn Project - - name: Cache node modules - uses: actions/cache@v2 - env: - cache-name: cache-node-modules - with: - # YARN cache files are stored in `/home/runner/.cache/yarn/v6` on git actions - path: /home/runner/.cache/yarn/v6 - key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} - restore-keys: | - ${{ runner.os }}-build-${{ env.cache-name }}- - ${{ runner.os }}-build- - ${{ runner.os }}- - - # Run Yarn Install - Shared Components - - name: Run Yarn Install - Shared components - run: yarn --cwd src/frontend/shared-components install - - # Yarn Coverage - Shared Components - - name: Run Yarn Coverage - Shared components - run: yarn --cwd /home/runner/work/jag-file-submission/jag-file-submission/src/frontend/shared-components coverage - # Run Yarn Install - eFiling Frontend - name: Run Yarn Install - eFiling Frontend run: yarn --cwd src/frontend/efiling-frontend install - # Install link local globally - - name: Install linklocal - run: sudo npm install -g --unsafe-perm linklocal + # Check lint version + - name: Check lint - eFiling Frontend + run: yarn --cwd src/frontend/efiling-frontend run lint -v - # Link react versions between apps - - name: Run npm link - run: | - npm --prefix ${{ github.workspace }}/src/frontend/shared-components link ${{ github.workspace }}/src/frontend/efiling-frontend/node_modules/react - - # Run linklocal - - name: Run linklocal - run: | - cd ${{ github.workspace }}/src/frontend/efiling-frontend - linklocal + # Run lint - eFiling Frontend + - name: Run lint - eFiling Frontend + run: yarn --cwd src/frontend/efiling-frontend run lint # Yarn Coverage - eFiling Frontend - name: Run Yarn Coverage - eFiling Frontend @@ -103,248 +43,87 @@ jobs: - name: Run Yarn Install - eFiling Demo run: yarn --cwd src/frontend/efiling-demo install + # Run lint - eFiling Demo + - name: Run lint - eFiling Demo + run: yarn --cwd src/frontend/efiling-demo run lint + # Yarn Coverage - eFiling Demo - name: Run Yarn Coverage - eFiling Demo run: yarn --cwd /home/runner/work/jag-file-submission/jag-file-submission/src/frontend/efiling-demo coverage - # Formatting the FRONTEND coverage report - - name: Format the FRONTEND coverage report - run: | - ./cc-test-reporter format-coverage -t lcov -o coverage/frontend-codeclimate.json ${{github.workspace}}/src/frontend/efiling-frontend/coverage/lcov.info - # Formatting the FRONTEND DEMO coverage report - - name: Format the FRONTEND DEMO coverage report - run: | - ./cc-test-reporter format-coverage -t lcov -o coverage/frontend-demo-codeclimate.json ${{github.workspace}}/src/frontend/efiling-demo/coverage/lcov.info - - # Formatting the SHARED COMPONENTS coverage report - - name: Format the SHARED COMPONENTS coverage report - run: | - ./cc-test-reporter format-coverage -t lcov -o coverage/shared-components-codeclimate.json ${{github.workspace}}/src/frontend/shared-components/coverage/lcov.info - - # List all formatted files in coverage directory - - name: WHERE AM I - FORMATTED? - run: | - ls ${{ github.workspace }}/coverage - if: ${{ env.ACTION_DEBUG }} + #- name: Format the FRONTEND DEMO coverage report + # run: | + # pushd . + # cd ${{github.workspace}}/src/frontend/efiling-demo/ + # ${{github.workspace}}/cc-test-reporter format-coverage -t lcov -o ${{github.workspace}}/coverage/frontend-demo-codeclimate.json coverage/lcov.info + # popd + # Implement Caching Action for Yarn Project + - name: Cache node modules + uses: actions/cache@v4 + env: + cache-name: cache-node-modules + with: + # YARN cache files are stored in `/home/runner/.cache/yarn/v6` on git actions + path: /home/runner/.cache/yarn/v6 + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- - # Count of all total coverage files available - - name: Count files present - run: | - echo "::set-env name=FILE_COUNTER::$(ls -1q ./coverage | wc -l )" - # Sum the coverage reports - - name: Summing the coverage reports generated - run: ./cc-test-reporter sum-coverage coverage/*-codeclimate.json -p ${{ env.FILE_COUNTER }} -o coverage/total-codeclimate.json - # Upload JSON for debugging purposes - - name: Upload JSON for debugging purposes - uses: actions/upload-artifact@v2 - with: - name: summed-yarn-coverage-report - path: coverage/total-codeclimate.json spring-boot: - name: Create, format and upload Java coverage artifact + name: Build and Test Java runs-on: ubuntu-latest env: FILE_COUNTER: 0 - CC_TEST_REPORTER_ID: 9ada3133fe9babf91a222009998b3545b7eae897a05900930bfa8a27fd82f385 ACTION_DEBUG: true steps: - - uses: actions/checkout@v2 - - # Get Code Climate binary - - name: Download Code Climate Binary - run: curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter - - # Permissions applied to the Code Climate Executable - - name: Apply executable perms to Code Climate Binary - run: chmod +x ./cc-test-reporter - - # Before build - - name: Before build - run: ./cc-test-reporter before-build - - # Set required Git env vars for either pull request - - name: Set ENV for codeclimate (pull_request) - run: | - echo "::set-env name=GIT_BRANCH::${{ github.event.pull_request.head.ref }}" - echo "::set-env name=GIT_COMMIT_SHA::${{ github.event.pull_request.head.sha }}" - if: github.event_name == 'pull_request' - - # Set required Git env vars for a push to master - - name: Set ENV for codeclimate (push) - run: | - echo "::set-env name=GIT_BRANCH::$GITHUB_REF" - echo "::set-env name=GIT_COMMIT_SHA::$GITHUB_SHA" - if: github.event_name == 'push' - - # Trimming the ref to master in order to publish correct report (paambaati) - - name: Set ref/head/master to master - run: | - echo "::set-env name=GIT_BRANCH::master" - if: env.GIT_BRANCH == 'refs/heads/master' - + - name: Checkout Spring Starters Repository + uses: actions/checkout@v4 + with: + repository: bcgov/spring-boot-starters + path: spring-boot-starters + ref: v1.0.5 + # Setup Java Environment - - name: Set up JDK 1.8 + - name: Set up JDK 17 uses: actions/setup-java@v1 with: - java-version: 1.8 - - uses: actions/cache@v1 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven- + java-version: 17 - # Run Maven Verify to generate all jacoco reports - - name: Build with Maven - run: mvn -B verify -P all --file src/backend/pom.xml + # TODO REMOVE AFTER SFTP IS IN MAVEN CENTRAL + - name: Build Spring Starters + run: mvn install -P all --file ./spring-boot-starters/src/pom.xml - # Loop through all BACKEND services to show that jacoco reports have been generated - - name: WHERE AM I - BACKEND? - run: | - for s in efiling-backend-demo efiling-api - do - ls ${{ github.workspace }}/src/backend/$s/target/site/jacoco; - done - if: ${{ env.ACTION_DEBUG }} + - name: Checkout File Submission Repository + uses: actions/checkout@v2 - # Formatting the BACKEND coverage reports generated (dynamically) - - name: Format BACKEND coverage reports - run: | - projectRelRegex="^\.\/src\/backend\/(.*)\/target\/site\/jacoco\/jacoco\.xml$" - for file in $(find . -name "jacoco.xml") - do - echo $file - echo $projectRelRegex - if [[ $file =~ $projectRelRegex ]] - then - projectRel="${BASH_REMATCH[1]}" - echo "analyzing project: " $projectRel - projectName="${projectRel//\//-}" - JACOCO_SOURCE_PATH=${{ github.workspace }}/src/backend/$projectRel/src/main/java ./cc-test-reporter format-coverage ${{github.workspace}}/src/backend/$projectRel/target/site/jacoco/jacoco.xml --input-type jacoco --output coverage/$projectName-codeclimate.json; - echo "coverage generated: coverage/$projectName-codeclimate.json;" - else - echo $file does not match - fi - done - - # List all formatted files in coverage directory - - name: WHERE AM I - FORMATTED? - run: | - ls ${{ github.workspace }}/coverage - if: ${{ env.ACTION_DEBUG }} - - # Count of all total coverage files available - - name: Count files present - run: | - echo "::set-env name=FILE_COUNTER::$(ls -1q ./coverage | wc -l )" - - # Sum the coverage reports - - name: Summing the coverage reports generated - run: ./cc-test-reporter sum-coverage coverage/*-codeclimate.json -p ${{ env.FILE_COUNTER }} -o coverage/total-codeclimate.json - - # Upload JSON for debugging purposes - - name: Upload JSON for debugging purposes - uses: actions/upload-artifact@v2 - with: - name: summed-java-coverage-report - path: coverage/total-codeclimate.json - - aggregation: - name: Aggregate Spring Boot and Javascript reports - needs: [yarn, spring-boot] - env: - CC_TEST_REPORTER_ID: 9ada3133fe9babf91a222009998b3545b7eae897a05900930bfa8a27fd82f385 - runs-on: ubuntu-latest - steps: - # Get Code Climate binary - - name: Download Code Climate Binary - run: curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter - - # Permissions applied to the Code Climate Executable - - name: Apply executable perms to Code Climate Binary - run: chmod +x ./cc-test-reporter - - # Before build - - name: Before build - run: ./cc-test-reporter before-build - - # Set required Git env vars for either pull request - - name: Set ENV for codeclimate (pull_request) - run: | - echo "::set-env name=GIT_BRANCH::${{ github.event.pull_request.head.ref }}" - echo "::set-env name=GIT_COMMIT_SHA::${{ github.event.pull_request.head.sha }}" - if: github.event_name == 'pull_request' - - # Set required Git env vars for a push to master - - name: Set ENV for codeclimate (push) - run: | - echo "::set-env name=GIT_BRANCH::$GITHUB_REF" - echo "::set-env name=GIT_COMMIT_SHA::$GITHUB_SHA" - if: github.event_name == 'push' # Trimming the ref to master in order to publish correct report (paambaati) - name: Set ref/head/master to master run: | - echo "::set-env name=GIT_BRANCH::master" + echo "GIT_BRANCH=master" >> $GITHUB_ENV + #echo "::set-env name=GIT_BRANCH::master" if: env.GIT_BRANCH == 'refs/heads/master' - # Make Directory for downloaded files - - name: Make directory - run: mkdir coverage-reports - - # Download Spring-boot coverage report - - name: Download spring-boot coverage report - uses: actions/download-artifact@v1 - with: - name: summed-java-coverage-report - - # See what is inside - - name: List items inside java coverage report object - run: | - ls summed-java-coverage-report - - # Copy total java to outside directory - - name: Copy Java Coverage to directory - run: | - cp summed-java-coverage-report/total-codeclimate.json coverage-reports/total-java-codeclimate.json - - # Download Yarn coverage report - - name: Download javascript coverage report - uses: actions/download-artifact@v1 - with: - name: summed-yarn-coverage-report - - # See what is inside - - name: List items inside java coverage report object - run: | - ls summed-yarn-coverage-report - - # Copy total Yarn to outside directory - - name: Copy Yarn Coverage to directory - run: | - cp summed-yarn-coverage-report/total-codeclimate.json coverage-reports/total-yarn-codeclimate.json + #- uses: actions/cache@v1 + # with: + # path: ~/.m2/repository + # key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + # restore-keys: | + # ${{ runner.os }}-maven- - # See what is inside coverage - - name: List items inside java coverage report object - run: | - ls coverage-reports - - # Sum the coverage reports - - name: Summing the coverage reports generated - run: ./cc-test-reporter sum-coverage coverage-reports/*-codeclimate.json -p 2 -o coverage-reports/total-codeclimate.json - - # Upload JSON for debugging purposes - - name: Upload JSON for debugging purposes - uses: actions/upload-artifact@v2 + #Set env again?? + - name: Set up JDK 17 + uses: actions/setup-java@v1 with: - name: summed-total-coverage-report - path: coverage-reports/total-codeclimate.json + java-version: 17 - # Upload total coverage report to Code Climate - - name: Upload coverage report to Code Climate - run: ./cc-test-reporter upload-coverage -i coverage-reports/total-codeclimate.json + # Run Maven Verify to generate all jacoco reports + - name: Build with Maven + run: mvn -B verify -P all --file src/backend/pom.xml diff --git a/.github/workflows/cucumber-tests.yml b/.github/workflows/cucumber-tests.yml new file mode 100644 index 0000000000..14b21ccd87 --- /dev/null +++ b/.github/workflows/cucumber-tests.yml @@ -0,0 +1,215 @@ +name: Cucumber Tests + +on: + pull_request: + branches: [ master ] + push: + branches: [ master ] + workflow_dispatch: + +jobs: + + efiling-api-gcr: + name: Efiling Api GCR + runs-on: ubuntu-latest + steps: + - name: Pull Git repo. + uses: actions/checkout@v2 + + - name: Login to Docker Hub + uses: docker/login-action@v1 + with: + registry: docker.pkg.github.com + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Pull efiling-api-builder + run: docker pull docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-api:builder || true + + - name: build efiling-api-builder + run: docker build ./src/backend + -f ./src/backend/Dockerfile.efiling-api + --target build + -t efiling-api:builder + --build-arg SERVICE_NAME=efiling-api + --build-arg MVN_PROFILE=efiling-api-demo + --build-arg STARTERS_V=v1.0.5 + --cache-from=docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-api:builder + + - name: tag & push efiling-api to git container registry + if: github.event.pull_request.head.repo.full_name == github.repository + run: docker tag efiling-api:builder docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-api:builder && docker push docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-api:builder + + - name: Pull efiling-api-demo + run: docker pull docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-api:demo || true + + - name: build efiling-api-demo + run: docker build ./src/backend + -f ./src/backend/Dockerfile.efiling-api + -t efiling-api:demo + --build-arg SERVICE_NAME=efiling-api + --build-arg MVN_PROFILE=efiling-api-demo + --build-arg STARTERS_V=v1.0.5 + --cache-from=docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-api:builder + --cache-from=docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-api:demo + + # Optional only for branch on repo + - name: tag & push efiling-api to git container registry + if: github.event.pull_request.head.repo.full_name == github.repository + run: docker tag efiling-api:demo docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-api:demo && docker push docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-api:demo + + efiling-frontend-gcr: + name: Efiling Frontend GCR + runs-on: ubuntu-latest + steps: + - name: Pull Git repo. + uses: actions/checkout@v2 + + - name: Login to Docker Hub + uses: docker/login-action@v1 + with: + registry: docker.pkg.github.com + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Pull efiling-frontend-builder + run: docker pull docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-frontend:builder || true + + - name: build efiling-frontend-builder + run: docker build ./src/frontend/efiling-frontend + --target build + -t efiling-frontend:builder + --cache-from=docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-frontend:builder + + - name: tag & push efiling-frontend to git container registry + if: github.event.pull_request.head.repo.full_name == github.repository + run: docker tag efiling-frontend:builder docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-frontend:builder && docker push docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-frontend:builder + + - name: Pull efiling-frontend-demo + run: docker pull docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-frontend:demo || true + + - name: build efiling-frontend-demo + run: docker build ./src/frontend/efiling-frontend + -t efiling-frontend:demo + --cache-from=docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-frontend:builder + --cache-from=docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-frontend:demo + + - name: tag & push efiling-frontend to git container registry + if: github.event.pull_request.head.repo.full_name == github.repository + run: docker tag efiling-frontend:demo docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-frontend:demo && docker push docker.pkg.github.com/$GITHUB_REPOSITORY/efiling-frontend:demo + + keycloak-config-gcr: + name: Keycloack Config GCR + runs-on: ubuntu-latest + steps: + - name: Pull Git repo. + uses: actions/checkout@v2 + + - name: Login to Docker Hub + uses: docker/login-action@v1 + with: + registry: docker.pkg.github.com + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Pull efiling-frontend-builder + run: docker pull docker.pkg.github.com/$GITHUB_REPOSITORY/keycloak-config:demo || true + + - name: build efiling-frontend-builder + run: docker build ./infrastructure/keycloak + -t keycloak-config:demo + --build-arg KEYCLOAK_URL=http://keycloak:8080 + --cache-from=docker.pkg.github.com/$GITHUB_REPOSITORY/keycloak-config:demo + + - name: tag & push keycloak-config to git container registry + if: github.event.pull_request.head.repo.full_name == github.repository + run: docker tag keycloak-config:demo docker.pkg.github.com/$GITHUB_REPOSITORY/keycloak-config:demo && docker push docker.pkg.github.com/$GITHUB_REPOSITORY/keycloak-config:demo + + cucumber-tests: + name: Runs cucumber-tests + runs-on: ubuntu-latest + needs: [ efiling-api-gcr, efiling-frontend-gcr, keycloak-config-gcr ] + steps: + - name: Pull Git repo. + uses: actions/checkout@v2 + + # pulling images is faster than caching in most of the case + - name: pull available docker images first + run: docker compose pull -q --parallel redis clamav keycloak + + - name: Standup Infra + run: docker compose up -d redis clamav keycloak + + - name: Login to Docker Hub + uses: docker/login-action@v1 + with: + registry: docker.pkg.github.com + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Cache local Maven repository + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + + - name: Pull images (Local REPO only) + if: github.event.pull_request.head.repo.full_name == github.repository + run: docker compose -f docker-compose.yml -f tests/docker-compose-integration.yml pull --parallel -q efiling-api efiling-frontend keycloak-config + + - name: Standup Docker Pods (Local REPO only) + if: github.event.pull_request.head.repo.full_name == github.repository + run: docker compose -f docker-compose.yml -f tests/docker-compose-integration.yml up -d efiling-api efiling-frontend + + + - name: Standup Docker Pods (FORK only) + if: github.event.pull_request.head.repo.full_name != github.repository + run: docker compose up -d efiling-api efiling-frontend + + - name: Configure keycloak (Local REPO only) + if: github.event.pull_request.head.repo.full_name == github.repository + run: | + docker compose -f docker-compose.yml -f tests/docker-compose-integration.yml up keycloak-config + + - name: Configure keycloak (FORK only) + if: github.event.pull_request.head.repo.full_name != github.repository + run: | + docker compose up keycloak-config + + - name: Running Integration Tests + env: + DOCKERIZE_VERSION: v0.6.1 + continue-on-error: true + id: cucumber-test + run: | + + # Maven requires chrome driver. + wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb + sudo apt-get -qq -y install ./google-chrome-stable_current_amd64.deb + + # We need to test if efiling-api pod and service is running before we can proceed. Using dockerize to proceed only after efiling-demo:8080 can be reached. + wget -q https://github.com/jwilder/dockerize/releases/download/$DOCKERIZE_VERSION/dockerize-linux-amd64-$DOCKERIZE_VERSION.tar.gz + tar -xzvf dockerize-linux-amd64-$DOCKERIZE_VERSION.tar.gz + + ./dockerize -wait http://127.0.0.1:8080/actuator/health -timeout 120s + mvn verify -ntp -f tests/pom.xml + + # Upload Spark report for debugging purposes + - name: Upload Spark report for debugging purposes + uses: actions/upload-artifact@v4 + with: + name: cucumber-spark-report + path: ./tests/test-output/extent/Spark/Index.html + + # Upload Cucumber JSON for debugging purposes + - name: Upload Cucumber JSON for debugging purposes + uses: actions/upload-artifact@v4 + with: + name: cucumber-json-report + path: ./tests/target/cucumber-reports/CucumberTestReport.json + + - name: Set action status + if: steps.cucumber-test.outcome != 'success' + run: exit 1 diff --git a/.github/workflows/dev-efiling-admin-build.yaml b/.github/workflows/dev-efiling-admin-build.yaml new file mode 100644 index 0000000000..793a760053 --- /dev/null +++ b/.github/workflows/dev-efiling-admin-build.yaml @@ -0,0 +1,104 @@ +name: Build Efiling Admin Docker Image and Push to Openshift Image Registry + +on: + schedule: + - cron: "0 0 * */3 *" + push: + branches: [master] + paths: + - "src/frontend/efiling-demo/**" + - ".github/workflows/dev-efiling-admin-build.yaml" + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Login to Artifactory + uses: docker/login-action@v1 + with: + registry: artifacts.developer.gov.bc.ca + username: ${{ secrets.EFILING_ARTIFACTORY_USERNAME }} + password: ${{ secrets.EFILING_ARTIFACTORY_PASSWORD }} + + - name: Build Image + run: | + docker compose build efiling-demo + docker tag jag-file-submission-efiling-demo artifacts.developer.gov.bc.ca/efc7-efiling-admin/efiling-admin:dev + + #Run Vulnerability Scan usinig Trivy scanner + - name: Run Trivy vulnerability scanner + uses: aquasecurity/trivy-action@master + with: + scan-type: image + image-ref: jag-file-submission-efiling-demo + format: sarif + output: trivy-results.sarif + exit-code: 1 + ignore-unfixed: true + limit-severities-for-sarif: true + severity: HIGH,CRITICAL + + #Upload results to the Github security tab. + - name: Upload Trivy scan results to GitHub Security tab + uses: github/codeql-action/upload-sarif@v3 + if: always() + with: + sarif_file: trivy-results.sarif + + - name: Docker Push to Artifactory + run: | + docker push artifacts.developer.gov.bc.ca/efc7-efiling-admin/efiling-admin:dev + + # Get SHORT_SHA for the version + - name: Get short SHA + id: short_sha + run: | + echo "::set-output name=SHORT_SHA::$(git rev-parse --short HEAD)" + echo "Short SHA: $SHORT_SHA" + + - name: Checkout ArgoCD Repo + id: gitops + uses: actions/checkout@v4 + with: + repository: bcgov-c/tenant-gitops-fc726a + ref: develop + token: ${{ secrets.ARGO_PAT }} # `ARGO_PAT` is a secret that contains your PAT + path: gitops + + - name: Update Helm Values and Commit + id: helm + if: steps.gitops.outcome == 'success' # Only run if the previous step (publish) was successful + run: | + # Clone the GitOps deployment configuration repository + # Navigate to the directory containing your Helm values file for the environment develop -> DEV, test -> test and + cd gitops/charts + + # Update the Helm values file with the new image tag and version + DATETIME=$(date +'%Y-%m-%d %H:%M:%S') # Get current date and time + + sed -i "s/admintag: .*/admintag: dev # Image Updated on $DATETIME/" ../deploy/dev_values.yaml + sed -i "s/adminVersion: .*/adminVersion: ${{ steps.short_sha.outputs.SHORT_SHA }} # Version Updated on $DATETIME/" ../deploy/dev_values.yaml + + # Commit and push the changes + git config --global user.email "actions@github.com" + git config --global user.name "GitHub Actions" + + git add . + + git add ../deploy/dev_values.yaml + + # Repackage Helm Chart + + cd efiling-gitops + + helm dependency build + + cd charts + + git add . + + git commit -m "Update Dev Admin image tag" + git push origin develop # Update the branch name as needed \ No newline at end of file diff --git a/.github/workflows/dev-efiling-api-build.yaml b/.github/workflows/dev-efiling-api-build.yaml new file mode 100644 index 0000000000..c13434ffdd --- /dev/null +++ b/.github/workflows/dev-efiling-api-build.yaml @@ -0,0 +1,108 @@ +name: Build Efiling API Image and Push to Openshift 4 Registry + +on: + schedule: + - cron: "0 0 * */3 *" + push: + branches: [master] + paths: + - "src/backend/**" + - ".github/workflows/dev-efiling-api-build.yaml" + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - name: Login to Artifactory + uses: docker/login-action@v1 + with: + registry: artifacts.developer.gov.bc.ca + username: ${{ secrets.EFILING_ARTIFACTORY_USERNAME }} + password: ${{ secrets.EFILING_ARTIFACTORY_PASSWORD }} + + - name: Build Image + env: + MVN_PROFILE: efiling-api,splunk + STARTERS_V: v1.0.5 + run: | + docker compose build efiling-api + docker tag jag-file-submission-efiling-api artifacts.developer.gov.bc.ca/efc7-efiling-api/efiling-api:dev + + #Run Vulnerability Scan usinig Trivy scanner + - name: Run Trivy vulnerability scanner + uses: aquasecurity/trivy-action@master + with: + scan-type: image + image-ref: jag-file-submission-efiling-api + format: sarif + output: trivy-results.sarif + exit-code: 1 + ignore-unfixed: true + limit-severities-for-sarif: true + severity: HIGH,CRITICAL + + #Upload results to the Github security tab. + - name: Upload Trivy scan results to GitHub Security tab + uses: github/codeql-action/upload-sarif@v3 + if: always() + with: + sarif_file: trivy-results.sarif + + - name: Docker Push to Artifactory + run: | + docker push artifacts.developer.gov.bc.ca/efc7-efiling-api/efiling-api:dev + + # Get SHORT_SHA for the version + - name: Get short SHA + id: short_sha + run: | + echo "::set-output name=SHORT_SHA::$(git rev-parse --short HEAD)" + echo "Short SHA: $SHORT_SHA" + + - name: Checkout ArgoCD Repo + id: gitops + uses: actions/checkout@v4 + with: + repository: bcgov-c/tenant-gitops-fc726a + ref: develop + token: ${{ secrets.ARGO_PAT }} # `ARGO_PAT` is a secret that contains your PAT + path: gitops + + - name: Update Helm Values and Commit + id: helm + if: steps.gitops.outcome == 'success' # Only run if the previous step (publish) was successful + run: | + # Clone the GitOps deployment configuration repository + # Navigate to the directory containing your Helm values file for the environment develop -> DEV, test -> test and + cd gitops/charts + + # Update the Helm values file with the new image tag and version + DATETIME=$(date +'%Y-%m-%d %H:%M:%S') # Get current date and time + + sed -i "s/apitag: .*/apitag: dev # Image Updated on $DATETIME/" ../deploy/dev_values.yaml + sed -i "s/apiVersion: .*/apiVersion: ${{ steps.short_sha.outputs.SHORT_SHA }} # Version Updated on $DATETIME/" ../deploy/dev_values.yaml + + # Commit and push the changes + git config --global user.email "actions@github.com" + git config --global user.name "GitHub Actions" + + git add . + + git add ../deploy/dev_values.yaml + + # Repackage Helm Chart + + cd efiling-gitops + + helm dependency build + + cd charts + + git add . + + git commit -m "Update Dev API image tag" + git push origin develop # Update the branch name as needed diff --git a/.github/workflows/dev-efiling-frontend-build.yaml b/.github/workflows/dev-efiling-frontend-build.yaml new file mode 100644 index 0000000000..961b929d5b --- /dev/null +++ b/.github/workflows/dev-efiling-frontend-build.yaml @@ -0,0 +1,103 @@ +name: Build Efiling Frontend Image and Push to Openshift Registry + +on: + push: + branches: [master] + paths: + - "src/frontend/efiling-frontend/**" + - ".github/workflows/dev-efiling-frontend-build.yaml" + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - name: Login to Artifactory + uses: docker/login-action@v1 + with: + registry: artifacts.developer.gov.bc.ca + username: ${{ secrets.EFILING_ARTIFACTORY_USERNAME }} + password: ${{ secrets.EFILING_ARTIFACTORY_PASSWORD }} + + - name: Build Image + run: | + docker compose build efiling-frontend + docker tag jag-file-submission-efiling-frontend artifacts.developer.gov.bc.ca/efc7-efiling-frontend/efiling-frontend:dev + + #Run Vulnerability Scan usinig Trivy scanner + - name: Run Trivy vulnerability scanner + uses: aquasecurity/trivy-action@master + with: + scan-type: image + image-ref: jag-file-submission-efiling-frontend + format: sarif + output: trivy-results.sarif + exit-code: 1 + ignore-unfixed: true + limit-severities-for-sarif: true + severity: HIGH,CRITICAL + + #Upload results to the Github security tab. + - name: Upload Trivy scan results to GitHub Security tab + uses: github/codeql-action/upload-sarif@v3 + if: always() + with: + sarif_file: trivy-results.sarif + + - name: Docker Push to Artifactory + run: | + docker push artifacts.developer.gov.bc.ca/efc7-efiling-frontend/efiling-frontend:dev + + # Get SHORT_SHA for the version + - name: Get short SHA + id: short_sha + run: | + echo "::set-output name=SHORT_SHA::$(git rev-parse --short HEAD)" + echo "Short SHA: $SHORT_SHA" + + - name: Checkout ArgoCD Repo + id: gitops + uses: actions/checkout@v4 + with: + repository: bcgov-c/tenant-gitops-fc726a + ref: develop + token: ${{ secrets.ARGO_PAT }} # `ARGO_PAT` is a secret that contains your PAT + path: gitops + + - name: Update Helm Values and Commit + id: helm + if: steps.gitops.outcome == 'success' # Only run if the previous step (publish) was successful + run: | + # Clone the GitOps deployment configuration repository + # Navigate to the directory containing your Helm values file for the environment develop -> DEV, test -> test and + cd gitops/charts + + # Update the Helm values file with the new image tag and version + DATETIME=$(date +'%Y-%m-%d %H:%M:%S') # Get current date and time + + sed -i "s/frontendtag: .*/frontendtag: dev # Image Updated on $DATETIME/" ../deploy/dev_values.yaml + sed -i "s/frontendVersion: .*/frontendVersion: ${{ steps.short_sha.outputs.SHORT_SHA }} # Version Updated on $DATETIME/" ../deploy/dev_values.yaml + + # Commit and push the changes + git config --global user.email "actions@github.com" + git config --global user.name "GitHub Actions" + + git add . + + git add ../deploy/dev_values.yaml + + # Repackage Helm Chart + + cd efiling-gitops + + helm dependency build + + cd charts + + git add . + + git commit -m "Update Dev Frontend image tag" + git push origin develop # Update the branch name as needed \ No newline at end of file diff --git a/.github/workflows/prod-promote.yaml b/.github/workflows/prod-promote.yaml new file mode 100644 index 0000000000..439307f4c5 --- /dev/null +++ b/.github/workflows/prod-promote.yaml @@ -0,0 +1,170 @@ +# Deploy an artifact onto Prod +name: Promote to Prod + +on: + workflow_dispatch: + inputs: + application: + required: true + description: What application you want to promote? + type: choice + options: + - efiling-api + - efiling-frontend + - efiling-admin + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Login to Artifactory + uses: docker/login-action@v1 + with: + registry: artifacts.developer.gov.bc.ca + username: ${{ secrets.EFILING_ARTIFACTORY_USERNAME }} + password: ${{ secrets.EFILING_ARTIFACTORY_PASSWORD }} + + - name: Backup Prod Image from Artifactory + working-directory: ${{env.WORKING_DIRECTORY}} + run: | + docker pull artifacts.developer.gov.bc.ca/efc7-${{ github.event.inputs.application }}/${{ github.event.inputs.application }}:prod + docker tag artifacts.developer.gov.bc.ca/efc7-${{ github.event.inputs.application }}/${{ github.event.inputs.application }}:prod artifacts.developer.gov.bc.ca/efc7-${{ github.event.inputs.application }}/${{ github.event.inputs.application }}:prod-backup + docker push artifacts.developer.gov.bc.ca/efc7-${{ github.event.inputs.application }}/${{ github.event.inputs.application }}:prod-backup + + - name: Docker Pull Test Image from Artifactory + working-directory: ${{env.WORKING_DIRECTORY}} + run: | + docker pull artifacts.developer.gov.bc.ca/efc7-${{ github.event.inputs.application }}/${{ github.event.inputs.application }}:test + docker tag artifacts.developer.gov.bc.ca/efc7-${{ github.event.inputs.application }}/${{ github.event.inputs.application }}:test artifacts.developer.gov.bc.ca/efc7-${{ github.event.inputs.application }}/${{ github.event.inputs.application }}:prod + + + - name: Docker Push Prod Image To Artifactory + working-directory: ${{env.WORKING_DIRECTORY}} + run: | + docker push artifacts.developer.gov.bc.ca/efc7-${{ github.event.inputs.application }}/${{ github.event.inputs.application }}:prod + + # Get SHORT_SHA for the version + - name: Get short SHA + id: short_sha + run: | + echo "::set-output name=SHORT_SHA::$(git rev-parse --short HEAD)" + echo "Short SHA: $SHORT_SHA" + + - name: Checkout ArgoCD Repo + id: gitops + uses: actions/checkout@v4 + with: + repository: bcgov-c/tenant-gitops-fc726a + ref: main + token: ${{ secrets.ARGO_PAT }} + path: gitops + + - name: Update ADMIN Helm Values and Commit + id: helm-admin + if: ${{ github.event.inputs.application == 'efiling-admin' }} + run: | + # Clone the GitOps deployment configuration repository + # Navigate to the directory containing your Helm values file for the environment develop -> DEV, test -> test and + cd gitops/charts + + # Update the Helm values file with the new image tag and version + DATETIME=$(date +'%Y-%m-%d %H:%M:%S') # Get current date and time + + sed -i "s/admintag: .*/admintag: prod # Image Updated on $DATETIME/" ../deploy/prod_values.yaml + sed -i "s/adminVersion: .*/adminVersion: ${{ steps.short_sha.outputs.SHORT_SHA }} # Version Updated on $DATETIME/" ../deploy/prod_values.yaml + + # Commit and push the changes + git config --global user.email "actions@github.com" + git config --global user.name "GitHub Actions" + + git add . + + git add ../deploy/prod_values.yaml + + # Repackage Helm Chart + + cd efiling-gitops + + helm dependency build + + cd charts + + git add . + + git commit -m "Update Prod Admin image tag" + git push origin main # Update the branch name as needed + + - name: Update API Helm Values and Commit + id: helm-api + if: ${{ github.event.inputs.application == 'efiling-api' }} + run: | + # Clone the GitOps deployment configuration repository + # Navigate to the directory containing your Helm values file for the environment develop -> DEV, test -> test and + cd gitops/charts + + # Update the Helm values file with the new image tag and version + DATETIME=$(date +'%Y-%m-%d %H:%M:%S') # Get current date and time + + sed -i "s/apitag: .*/apitag: prod # Image Updated on $DATETIME/" ../deploy/prod_values.yaml + sed -i "s/apiVersion: .*/apiVersion: ${{ steps.short_sha.outputs.SHORT_SHA }} # Version Updated on $DATETIME/" ../deploy/prod_values.yaml + + # Commit and push the changes + git config --global user.email "actions@github.com" + git config --global user.name "GitHub Actions" + + git add . + + git add ../deploy/prod_values.yaml + + # Repackage Helm Chart + + cd efiling-gitops + + helm dependency build + + cd charts + + git add . + + git commit -m "Update Prod API image tag" + git push origin main # Update the branch name as needed + + - name: Update FRONTEND Helm Values and Commit + id: helm-frontend + if: ${{ github.event.inputs.application == 'efiling-frontend' }} + run: | + # Clone the GitOps deployment configuration repository + # Navigate to the directory containing your Helm values file for the environment develop -> DEV, test -> test and + cd gitops/charts + + # Update the Helm values file with the new image tag and version + DATETIME=$(date +'%Y-%m-%d %H:%M:%S') # Get current date and time + + sed -i "s/frontendtag: .*/frontendtag: prod # Image Updated on $DATETIME/" ../deploy/prod_values.yaml + sed -i "s/frontendVersion: .*/frontendVersion: ${{ steps.short_sha.outputs.SHORT_SHA }} # Version Updated on $DATETIME/" ../deploy/prod_values.yaml + + # Commit and push the changes + git config --global user.email "actions@github.com" + git config --global user.name "GitHub Actions" + + git add . + + git add ../deploy/prod_values.yaml + + # Repackage Helm Chart + + cd efiling-gitops + + helm dependency build + + cd charts + + git add . + + git commit -m "Update Prod FRONTEND image tag" + git push origin main # Update the branch name as needed + + + diff --git a/.github/workflows/test-promote.yaml b/.github/workflows/test-promote.yaml new file mode 100644 index 0000000000..b5c923dc46 --- /dev/null +++ b/.github/workflows/test-promote.yaml @@ -0,0 +1,158 @@ +# Deploy an artifact onto Test +name: Promote to Test +on: + workflow_dispatch: + inputs: + application: + required: true + description: What application you want to promote? + type: choice + options: + - efiling-api + - efiling-frontend + - efiling-admin + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Login to Artifactory + uses: docker/login-action@v1 + with: + registry: artifacts.developer.gov.bc.ca + username: ${{ secrets.EFILING_ARTIFACTORY_USERNAME }} + password: ${{ secrets.EFILING_ARTIFACTORY_PASSWORD }} + + - name: Docker Pull Dev Image from Artifactory + working-directory: ${{env.WORKING_DIRECTORY}} + run: | + docker pull artifacts.developer.gov.bc.ca/efc7-${{ github.event.inputs.application }}/${{ github.event.inputs.application }}:dev + docker tag artifacts.developer.gov.bc.ca/efc7-${{ github.event.inputs.application }}/${{ github.event.inputs.application }}:dev artifacts.developer.gov.bc.ca/efc7-${{ github.event.inputs.application }}/${{ github.event.inputs.application }}:test + + - name: Docker Push Test Image To Artifactory + working-directory: ${{env.WORKING_DIRECTORY}} + run: | + docker push artifacts.developer.gov.bc.ca/efc7-${{ github.event.inputs.application }}/${{ github.event.inputs.application }}:test + + # Get SHORT_SHA for the version + - name: Get short SHA + id: short_sha + run: | + echo "::set-output name=SHORT_SHA::$(git rev-parse --short HEAD)" + echo "Short SHA: $SHORT_SHA" + + - name: Checkout ArgoCD Repo + id: gitops + uses: actions/checkout@v4 + with: + repository: bcgov-c/tenant-gitops-fc726a + ref: test + token: ${{ secrets.ARGO_PAT }} + path: gitops + + - name: Update ADMIN Helm Values and Commit + id: helm-admin + if: ${{ github.event.inputs.application == 'efiling-admin' }} + run: | + # Clone the GitOps deployment configuration repository + # Navigate to the directory containing your Helm values file for the environment develop -> DEV, test -> test and + cd gitops/charts + + # Update the Helm values file with the new image tag and version + DATETIME=$(date +'%Y-%m-%d %H:%M:%S') # Get current date and time + + sed -i "s/admintag: .*/admintag: test # Image Updated on $DATETIME/" ../deploy/test_values.yaml + sed -i "s/adminVersion: .*/adminVersion: ${{ steps.short_sha.outputs.SHORT_SHA }} # Version Updated on $DATETIME/" ../deploy/test_values.yaml + + # Commit and push the changes + git config --global user.email "actions@github.com" + git config --global user.name "GitHub Actions" + + git add . + + git add ../deploy/test_values.yaml + + # Repackage Helm Chart + + cd efiling-gitops + + helm dependency build + + cd charts + + git add . + + git commit -m "Update Test Admin image tag" + git push origin test # Update the branch name as needed + + - name: Update API Helm Values and Commit + id: helm-api + if: ${{ github.event.inputs.application == 'efiling-api' }} + run: | + # Clone the GitOps deployment configuration repository + # Navigate to the directory containing your Helm values file for the environment develop -> DEV, test -> test and + cd gitops/charts + + # Update the Helm values file with the new image tag and version + DATETIME=$(date +'%Y-%m-%d %H:%M:%S') # Get current date and time + + sed -i "s/apitag: .*/apitag: test # Image Updated on $DATETIME/" ../deploy/test_values.yaml + sed -i "s/apiVersion: .*/apiVersion: ${{ steps.short_sha.outputs.SHORT_SHA }} # Version Updated on $DATETIME/" ../deploy/test_values.yaml + + # Commit and push the changes + git config --global user.email "actions@github.com" + git config --global user.name "GitHub Actions" + + git add . + + git add ../deploy/test_values.yaml + + # Repackage Helm Chart + + cd efiling-gitops + + helm dependency build + + cd charts + + git add . + + git commit -m "Update Test API image tag" + git push origin test # Update the branch name as needed + + - name: Update FRONTEND Helm Values and Commit + id: helm-frontend + if: ${{ github.event.inputs.application == 'efiling-frontend' }} + run: | + # Clone the GitOps deployment configuration repository + # Navigate to the directory containing your Helm values file for the environment develop -> DEV, test -> test and + cd gitops/charts + + # Update the Helm values file with the new image tag and version + DATETIME=$(date +'%Y-%m-%d %H:%M:%S') # Get current date and time + + sed -i "s/frontendtag: .*/frontendtag: test # Image Updated on $DATETIME/" ../deploy/test_values.yaml + sed -i "s/frontendVersion: .*/frontendVersion: ${{ steps.short_sha.outputs.SHORT_SHA }} # Version Updated on $DATETIME/" ../deploy/test_values.yaml + + # Commit and push the changes + git config --global user.email "actions@github.com" + git config --global user.name "GitHub Actions" + + git add . + + git add ../deploy/test_values.yaml + + # Repackage Helm Chart + + cd efiling-gitops + + helm dependency build + + cd charts + + git add . + + git commit -m "Update Test FRONTEND image tag" + git push origin test # Update the branch name as needed \ No newline at end of file diff --git a/.github/workflows/zap-baseline.yaml b/.github/workflows/zap-baseline.yaml new file mode 100644 index 0000000000..e16f63d74e --- /dev/null +++ b/.github/workflows/zap-baseline.yaml @@ -0,0 +1,21 @@ +name: Zap Baseline Scan + +on: [workflow_dispatch] + +jobs: + zap_scan: + runs-on: ubuntu-latest + name: Scan the eFiling Frontend Web Application + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + ref: master + - name: ZAP Scan + uses: zaproxy/action-baseline@v0.4.0 + with: + token: ${{ secrets.GITHUB_TOKEN }} + docker_name: 'owasp/zap2docker-stable' + target: 'https://test.justice.gov.bc.ca/efilinghub' + rules_file_name: '.zap/rules.tsv' + cmd_options: '-a' diff --git a/.gitignore b/.gitignore index a9500bfdc4..d9f78b7768 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,12 @@ tests/logs *.log .idea tests/test-output +tests/src/test/resources/application.properties .env +src/frontend/.vscode/ +src/frontend/efiling-frontend/.vscode/ +src/frontend/efiling-frontend/node_modules +*.lock +node_modules +.metadata +/TestAutomation/target diff --git a/.mdlrc b/.mdlrc new file mode 100644 index 0000000000..1fa2ca3703 --- /dev/null +++ b/.mdlrc @@ -0,0 +1 @@ +style ".settings/mdl/ruleset.rb" diff --git a/.settings/mdl/ruleset.rb b/.settings/mdl/ruleset.rb new file mode 100644 index 0000000000..18f0d8408e --- /dev/null +++ b/.settings/mdl/ruleset.rb @@ -0,0 +1,2 @@ +all +rule 'MD013', :code_blocks => false, :tables => false diff --git a/.settings/nginx.conf b/.settings/nginx.conf new file mode 100644 index 0000000000..d2120549a9 --- /dev/null +++ b/.settings/nginx.conf @@ -0,0 +1,18 @@ +worker_processes 1; +worker_rlimit_nofile 8192; + +events { + worker_connections 4096; ## Default: 1024 +} + +http { + + server { # simple reverse-proxy + listen 80; + + # pass requests for dynamic content to rails/turbogears/zope, et al + location / { + proxy_pass http://keycloak:8080; + } + } +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000000..af9a6adae9 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "java.configuration.updateBuildConfiguration": "disabled" +} diff --git a/Jenkinsfile b/Jenkinsfile deleted file mode 100644 index 8b13789179..0000000000 --- a/Jenkinsfile +++ /dev/null @@ -1 +0,0 @@ - diff --git a/README.md b/README.md index 2ad9325295..8329668fd9 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,12 @@ -[![Maintainability](https://api.codeclimate.com/v1/badges/4078a74ee2bb4d400fd9/maintainability)](https://codeclimate.com/github/bcgov/jag-file-submission/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/4078a74ee2bb4d400fd9/test_coverage)](https://codeclimate.com/github/bcgov/jag-file-submission/test_coverage) +# EFiling Hub -# jag-file-submission +[![img](https://img.shields.io/badge/Lifecycle-Maturing-007EC6)](https://github.com/bcgov/repomountie/blob/master/doc/lifecycle-badges.md) [![Maintainability](https://api.codeclimate.com/v1/badges/4078a74ee2bb4d400fd9/maintainability)](https://codeclimate.com/github/bcgov/jag-file-submission/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/4078a74ee2bb4d400fd9/test_coverage)](https://codeclimate.com/github/bcgov/jag-file-submission/test_coverage) ![Cucumber Tests](https://github.com/bcgov/jag-file-submission/workflows/Cucumber%20Tests/badge.svg) [![img](https://img.shields.io/badge/Chat-on%20RocketChat-%230f95d0.svg)](https://chat.developer.gov.bc.ca/group/efiling-hub-integration) -Generic File Submission API (to be used by the Family Law Act Application at first) +## Summary + +As a component of the Court Digital Transformation Strategy (CDTS), the eFiling hub uses modern, secure, scalable, microservice architecture and API first design to facilitate easy integration of other applications (i.e. Family Law Act application, Online Divorce Assistant, Representation Agreement app) with the current electronic filing services that are provisioned by the Court Services Online application. + +The eFiling hub is a foundational component to enhance citizen experiences for the submission of court documents electronically, while streamlining backend court registry processes. ## Project Structure @@ -12,16 +16,15 @@ Generic File Submission API (to be used by the Family Law Act Application at fir ├── src/ # application source files │ ├── backend # backend applications │ │ ├── efiling-api # efiling api - │ │ ├── efiling-worker # file submission worker │ │ ├── libs # backend libraries - │ │ | ├── efiling-account-client # efiling soap client that checks CSO account, FILE role, BCeID account info - │ │ | ├── efiling-submission-client # efiling soap client that submits packages to CSO - │ │ | ├── efiling-lookup-client # efiling soap client that looksup required info for submission - │ │ | └── efiling-status-client # efiling soap client for checking status of a submitted package + │ │ | ├── efiling-bambora-api-client # bamabora swagger for client generation + │ │ | ├── efiling-bom # pom Bill Of Materials + │ │ | ├── efiling-commons # efiling soap client that submits packages to CSO + │ │ | ├── efiling-cso-starter # efiling soap client that contains all soap implementations + │ │ | └── efiling-demo-starter # efiling demo app that mocks all soap implementations │ └── frontend # frontend applications │ ├── efiling-frontend # efiling frontend │ └── efiling-demo # efiling demo app frontend - │ └── shared-components # shared bcgov themed component library ├── COMPLIANCE.yaml # ├── CONTRIBUTING.md # ├── LICENSE # Apache License @@ -29,52 +32,33 @@ Generic File Submission API (to be used by the Family Law Act Application at fir ## Apps -| Name | description | doc | -| -------------------- | -------------------------------------------- | ---------------------------------------------------- | -| backend | all server side services | [README](src/backend/README.md) | -| efiling-api | the main api for interating with the service | [README](src/backend/efiling-api/README.md) | -| efiling-demo-backend | a demo backend that emulates a client | [README](src/backend/efiling-backend-demo/README.md) | -| efiling-worker | process submitted documents | [README](src/backend/efiling-worker/README.md) | -| frontend | all client side applications | [README](src/frontend/README.md) | -| efiling-frontend | the frontend for uploading documents | [README](src/frontend/efiling-frontend/README.md) | -| efiling-demo | the frontend for demo application | [README](src/frontend/efiling-demo/README.md) | -| shared-components | shared bcgov themed component library | [README](src/frontend/shared-components/README.md) | -| cucumber-tests | automated tests for frontend and backend | [README](tests/README.md) | +| Name | Description | Doc | +| ------------------- | -------------------------------------------- | -------------------------------------------------------- | +| backend | all server side services | [README](src/backend/README.md) | +| efiling-api | the main api for interating with the service | [README](src/backend/efiling-api/README.md) | +| efiling-cso-starter | soap client implementations | [README](src/backend/libs/efiling-cso-starter/README.md) | +| frontend | all client side applications | [README](src/frontend/README.md) | +| efiling-frontend | the frontend for uploading documents | [README](src/frontend/efiling-frontend/README.md) | +| efiling-demo | the frontend for demo application | [README](src/frontend/efiling-demo/README.md) | +| cucumber-tests | automated tests for frontend and backend | [README](tests/README.md) | ## Running the App By default a demo mode is enabled. -if you want to integrate with the CSO application, first create a local `.env` at the root of the repository based off `.env.template`. - -Change the `MVN_PROFILE` to `default` -Set the following environement variables: +First create a local `.env` at the root of the repository based off [.env.template](.env.template). Below are the variables that need to be configured to get the application running in demo mode. -``` -MVN_PROFILE=default -CSO_ACCOUNTFACADE_URI= -CSO_ACCOUNTFACADE_USERNAME= -CSO_ACCOUNTFACADE_PASSWORD= -CSO_ROLEREGISTRY_USERNAME= -CSO_ROLEREGISTRY_PASSWORD= -CSO_ROLEREGISTRY_URI= -CSO_LOOKUPFACADE_USERNAME= -CSO_LOOKUPFACADE_PASSWORD= -CSO_LOOKUPFACADE_URI= -BCEID_LOOKUP_USERNAME= -BCEID_LOOKUP_PASSWORD= -BCEID_LOOKUP_URI= -``` +Configure Keycloak run ```bash -docker-compose up -d --build +docker-compose up -d ``` -to get started, access the front end application [here](http://localhost:3001) and enter a user account and you will get redirected to the file upload. +login at [http://localhost:3001](http://localhost:3001) with `bobross` and `changeme` -You can get test accounts [here](https://bcgov.github.io/jag-file-submission/#/gettingStarted?id=test-accounts) when the app is running in demo mode. +To get started, access the front end application [here](http://localhost:3001) use the following username `bobross` and password `changeme` ![screen](docs/media/demoApp.png) @@ -96,14 +80,21 @@ Efiling Api check health at [http://localhost:8080/actuator/health](http://local A [redis](https://redis.io/) instance exposed on port 6379 -#### rabbitmq +#### redis commander -A [rabbitmq](https://www.rabbitmq.com/) access the management console at [http://localhost:15672](http://localhost:15672) +A [redis-commander](http://joeferner.github.io/redis-commander/) instance to query redis accessible at [http://localhost:8082](http://localhost:8082) -#### postgres: +#### keycloak -A [postgresql](https://www.postgresql.org/) to support keycloak +A [keycloak](https://www.keycloak.org/) instance accessible at [http://localhost:8081/auth](http://localhost:8081/auth) -#### keycloak: +#### Spring starter update + +When updating the spring starter ensure all hardcoded references are updated. +[Code Climate] (https://github.com/bcgov/jag-file-submission/blob/master/.github/workflows/code-climate-coverage-aggregation.yml) +[Docker File] (https://github.com/bcgov/jag-file-submission/blob/master/docker-compose.override.yml) +[Cucumber] (https://github.com/bcgov/jag-file-submission/blob/master/.github/workflows/cucumber-tests.yml) + + +## Github action -A [keycloak](https://www.keycloak.org/) instance accessible at [http://localhost:8081/auth](http://localhost:8081/auth) diff --git a/TestAutomation/.gitignore b/TestAutomation/.gitignore new file mode 100644 index 0000000000..f089b48b8b --- /dev/null +++ b/TestAutomation/.gitignore @@ -0,0 +1,16 @@ +### IntelliJ IDEA ### +tests/target +tests/.idea +tests/logs +*.iml +*.log +.idea +tests/test-output +tests/src/test/resources/application.properties +.env +src/frontend/.vscode/ +src/frontend/efiling-frontend/.vscode/ +src/frontend/efiling-frontend/node_modules +*.lock +node_modules + diff --git a/TestAutomation/bin/.gitignore b/TestAutomation/bin/.gitignore new file mode 100644 index 0000000000..6013929ddf --- /dev/null +++ b/TestAutomation/bin/.gitignore @@ -0,0 +1,14 @@ +/target/ +.classpath +.idea/ +.metadata/ +.project +.settings/ +/bin/chromedriver.exe +/bin/sqljdbc4-4.0.jar +/src/main/resources/jdbc.properties +/src/test/resources/jdbc.properties +debug.log +src/main/java/ca/epbc/ui/Config.java +src/test/java/ca/epbc/ui/LoginAccountRecoveryEnv.java +/src/ diff --git a/TestAutomation/bin/README.md b/TestAutomation/bin/README.md new file mode 100644 index 0000000000..b9cf4fbb3a Binary files /dev/null and b/TestAutomation/bin/README.md differ diff --git a/TestAutomation/bin/chr.ab b/TestAutomation/bin/chr.ab new file mode 100644 index 0000000000..c0efae8059 Binary files /dev/null and b/TestAutomation/bin/chr.ab differ diff --git a/TestAutomation/bin/chromedriver.exe b/TestAutomation/bin/chromedriver.exe new file mode 100644 index 0000000000..454b1809fa Binary files /dev/null and b/TestAutomation/bin/chromedriver.exe differ diff --git a/TestAutomation/bin/geckodriver.exe b/TestAutomation/bin/geckodriver.exe new file mode 100644 index 0000000000..dd2daa9001 Binary files /dev/null and b/TestAutomation/bin/geckodriver.exe differ diff --git a/TestAutomation/bin/sqljdbc4-4.0.jar b/TestAutomation/bin/sqljdbc4-4.0.jar new file mode 100644 index 0000000000..d6b7f6daf4 Binary files /dev/null and b/TestAutomation/bin/sqljdbc4-4.0.jar differ diff --git a/TestAutomation/pom.xml b/TestAutomation/pom.xml new file mode 100644 index 0000000000..ef3fbf8d6d --- /dev/null +++ b/TestAutomation/pom.xml @@ -0,0 +1,157 @@ + + + 4.0.0 + + ca.bc.gov.open.jagFileSubmission + TestAutomation + 1.0-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-parent + 3.0.0 + + + + eFilling-TesAutomation + + + UTF-8 + 1.8 + 4.7.2 + 2.0.26 + 1.18.20 + 4.13.1 + 3.7.0 + 3.1.0 + + + + + + org.seleniumhq.selenium + selenium-java + ${org.seleniumhq.selenium.version} + + + + junit + junit + ${junit.version} + jar + + + + org.apache.pdfbox + pdfbox + ${org.apache.pdfbox.version} + + + org.projectlombok + lombok + ${org.projectlombok.version} + test + + + + org.projectlombok + lombok + ${org.projectlombok.version} + provided + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + + + + + src/main/resources + true + + **/*.properties + **/*.bat + **/*.sh + **/.keystore + + + + + + maven-assembly-plugin + + + package + + single + + + + + + + ca.epbc.ui.Atest + + + + jar-with-dependencies + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + ${java.version} + ${java.version} + ${java.version} + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + + ${project.build.directory}/libs + + + + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven-jar-plugin.version} + + + + test-jar + + + + + + + + + \ No newline at end of file diff --git a/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/Atest.java b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/Atest.java new file mode 100644 index 0000000000..21707b9ca7 --- /dev/null +++ b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/Atest.java @@ -0,0 +1,42 @@ +package ca.bc.gov.open.jagFileSubmission; + +import org.junit.Test; +import org.junit.runner.JUnitCore; +import org.junit.runner.RunWith; + +import java.util.Random; + +public class Atest { + + @RunWith(ConcurrentJunitRunner.class) + @Concurent.Concurrent(threads = 6) + public final class ATest { + + @Test + public void test0() throws Throwable { printAndWait(); } + @Test public void test1() throws Throwable { printAndWait(); } + @Test public void test2() throws Throwable { printAndWait(); } + @Test public void test3() throws Throwable { printAndWait(); } + @Test public void test4() throws Throwable { printAndWait(); } + @Test public void test5() throws Throwable { printAndWait(); } + @Test public void test6() throws Throwable { printAndWait(); } + @Test public void test7() throws Throwable { printAndWait(); } + @Test public void test8() throws Throwable { printAndWait(); } + @Test public void test9() throws Throwable { printAndWait(); } + + void printAndWait() throws Throwable { + int w = new Random().nextInt(1000); + System.out.println(String.format("[%s] %s %s %s", + Thread.currentThread().getName(), + getClass().getName(), + new Throwable().getStackTrace()[1].getMethodName(), + w)); + Thread.sleep(w); + } + + public void main(String[] args) { + JUnitCore.main("ca.epbc.ATest"); + } + } + +} diff --git a/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/CommonUtils.java b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/CommonUtils.java new file mode 100644 index 0000000000..63b77360fe --- /dev/null +++ b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/CommonUtils.java @@ -0,0 +1,30 @@ +package ca.bc.gov.open.jagFileSubmission; + +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; + +import java.util.logging.Logger; + +public class CommonUtils { + + private static Logger log = Logger.getLogger("CommonUtils.class"); + + public static void login() throws Exception { + + WebDriver driver = WebDriverManager.getDriver(); + WebElement element = WebDriverManager.getElement(); + + if (Config.ENVIROMENT.equals(Constants.DEV)) { + driver.get("https://court-of-appeal-dev.apps.silver.devops.gov.bc.ca/court-of-appeal/"); + driver.navigate().to("https://court-of-appeal-dev.apps.silver.devops.gov.bc.ca/court-of-appeal/"); + driver.navigate().refresh(); + + } else if (Config.ENVIROMENT.equals(Constants.TST)) { + driver.get(""); + driver.navigate().to(""); + driver.navigate().refresh(); + + } + } + +} diff --git a/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/Concurent.java b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/Concurent.java new file mode 100644 index 0000000000..3ea6a92e3a --- /dev/null +++ b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/Concurent.java @@ -0,0 +1,16 @@ +package ca.bc.gov.open.jagFileSubmission; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +public class Concurent { + + @Retention(RetentionPolicy.RUNTIME) + @Target({ElementType.TYPE}) + public @interface Concurrent { + int threads() default 5; + } + +} diff --git a/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/ConcurrentJunitRunner.java b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/ConcurrentJunitRunner.java new file mode 100644 index 0000000000..d386624794 --- /dev/null +++ b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/ConcurrentJunitRunner.java @@ -0,0 +1,58 @@ +package ca.bc.gov.open.jagFileSubmission; + +import io.netty.util.concurrent.Future; +import org.junit.runners.BlockJUnit4ClassRunner; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.RunnerScheduler; + +import java.lang.annotation.Annotation; +import java.util.LinkedList; +import java.util.Queue; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +public class ConcurrentJunitRunner extends BlockJUnit4ClassRunner { + public ConcurrentJunitRunner(final Class klass) throws InitializationError { + super(klass); + setScheduler(new RunnerScheduler() { + ExecutorService executorService = Executors.newFixedThreadPool( + klass.isAnnotationPresent((Class) Concurent.Concurrent.class) ? + klass.getAnnotation(Concurent.Concurrent.class).threads() : + (int) (Runtime.getRuntime().availableProcessors() * 1.5), + new NamedThreadFactory(klass.getSimpleName())); + CompletionService completionService = new ExecutorCompletionService(executorService); + Queue> tasks = new LinkedList>(); + + public void schedule(Runnable childStatement) { + tasks.offer((Future) completionService.submit(childStatement, null)); + } + + public void finished() { + try { + while (!tasks.isEmpty()) + tasks.remove(completionService.take()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + while (!tasks.isEmpty()) + tasks.poll().cancel(true); + executorService.shutdownNow(); + } + } + }); + } + + static final class NamedThreadFactory implements ThreadFactory { + static final AtomicInteger poolNumber = new AtomicInteger(1); + final AtomicInteger threadNumber = new AtomicInteger(1); + final ThreadGroup group; + + NamedThreadFactory(String poolName) { + group = new ThreadGroup(poolName + "-" + poolNumber.getAndIncrement()); + } + + public Thread newThread(Runnable r) { + return new Thread(group, r, group.getName() + "-thread-" + threadNumber.getAndIncrement(), 0); + } + }} + diff --git a/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/ConcurrentSuite.java b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/ConcurrentSuite.java new file mode 100644 index 0000000000..44a91e672e --- /dev/null +++ b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/ConcurrentSuite.java @@ -0,0 +1,88 @@ +package ca.bc.gov.open.jagFileSubmission; + +import org.junit.internal.builders.AllDefaultPossibilitiesBuilder; +import org.junit.runner.Runner; +import org.junit.runners.Suite; +import org.junit.runners.model.InitializationError; +import org.junit.runners.model.RunnerBuilder; +import org.junit.runners.model.RunnerScheduler; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +public class ConcurrentSuite extends Suite { + public ConcurrentSuite(final Class klass) throws InitializationError { + super(klass, new AllDefaultPossibilitiesBuilder(true) { + @Override + public Runner runnerForClass(Class testClass) throws Throwable { + List builders = Arrays.asList( + new RunnerBuilder() { + @Override + public Runner runnerForClass(Class testClass) throws Throwable { + Concurent.Concurrent annotation = testClass.getAnnotation(Concurent.Concurrent.class); + if (annotation != null) + return new ConcurrentJunitRunner(testClass); + return null; + } + }, + ignoredBuilder(), + annotatedBuilder(), + suiteMethodBuilder(), + junit3Builder(), + junit4Builder()); + for (RunnerBuilder each : builders) { + Runner runner = each.safeRunnerForClass(testClass); + if (runner != null) + return runner; + } + return null; + } + }); + setScheduler(new RunnerScheduler() { + ExecutorService executorService = Executors.newFixedThreadPool( + klass.isAnnotationPresent(Concurent.Concurrent.class) ? + klass.getAnnotation(Concurent.Concurrent.class).threads() : + (int) (Runtime.getRuntime().availableProcessors() * 1.5), + new NamedThreadFactory(klass.getSimpleName())); + CompletionService completionService = new ExecutorCompletionService(executorService); + Queue> tasks = new LinkedList>(); + + public void schedule(Runnable childStatement) { + tasks.offer(completionService.submit(childStatement, null)); + } + + public void finished() { + try { + while (!tasks.isEmpty()) + tasks.remove(completionService.take()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + while (!tasks.isEmpty()) + tasks.poll().cancel(true); + executorService.shutdownNow(); + } + } + }); + } + + static final class NamedThreadFactory implements ThreadFactory { + static final AtomicInteger poolNumber = new AtomicInteger(1); + final AtomicInteger threadNumber = new AtomicInteger(1); + final ThreadGroup group; + + NamedThreadFactory(String poolName) { + group = new ThreadGroup(poolName + "-" + poolNumber.getAndIncrement()); + } + + public Thread newThread(Runnable r) { + return new Thread(group, r, group.getName() + "-thread-" + threadNumber.getAndIncrement(), 0); + } + } + +} + diff --git a/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/Config.java b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/Config.java new file mode 100644 index 0000000000..7116dedfa5 --- /dev/null +++ b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/Config.java @@ -0,0 +1,25 @@ +package ca.bc.gov.open.jagFileSubmission; + +import java.math.BigDecimal; + +public class Config { + + public static final String SELECTED_DRIVER = Constants.CHROME_DRIVER; + //public static final String SELECTED_DRIVER = Constants.FIREFOX_DRIVER; + //public static final String SELECTED_DRIVER = Constants.EDGE_DRIVER; + //public static final String ENVIROMENT = Constants.DEV; + public static final String ENVIROMENT = Constants.DEV; + + + public static String TEST_SCENARIO = Constants.NOT_SET; + public static boolean SKIP_SCREENSHOTS_OF_SHOPPING_CART = false; //not implemented yet + + public static final int TIMEOUT = 30; //the time webdriver waits before giving up (in seconds) + public static final int SLEEP_TIME_FULL_REFRESH = 3500; //time used in Thread.sleep() in milliseconds + public static final int SLEEP_TIME_PART_REFRESH = SLEEP_TIME_FULL_REFRESH/2; //time used in Thread.sleep() in milliseconds + + //app constants + public static BigDecimal CLAIM_CREDITS_PER_AREA = new BigDecimal("25"); + public static String CLIENT_ID = Constants.NOT_SET; + +} diff --git a/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/Constants.java b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/Constants.java new file mode 100644 index 0000000000..91a943bf16 --- /dev/null +++ b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/Constants.java @@ -0,0 +1,20 @@ +package ca.bc.gov.open.jagFileSubmission; + +public class Constants { + + //drivers + public static final String CHROME_DRIVER = "CHROME_DRIVER"; + public static final String FIREFOX_DRIVER = "FIREFOX_DRIVER"; + public static final String IE_DRIVER = "IE_DRIVER"; + public static final String EDGE_DRIVER = "EDGE_DRIVER"; + + //enviroments + public static final String DEV = "DEV"; + public static final String TST = "TST"; + + + //others + public static final String NOT_SET = "NOT_SET"; + public static final String JDBCURL = "JDBCURL"; + +} diff --git a/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/WaitTool.java b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/WaitTool.java new file mode 100644 index 0000000000..50f46f04bc --- /dev/null +++ b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/WaitTool.java @@ -0,0 +1,54 @@ +package ca.bc.gov.open.jagFileSubmission; + +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; + +import java.time.Duration; +import java.util.concurrent.TimeUnit; + +public class WaitTool { + + /** Default wait time for an element. 7 seconds. */ + public static final int DEFAULT_WAIT_4_ELEMENT = 7; + /** Default wait time for a page to be displayed. 12 seconds. + * The average webpage load time is 6 seconds in 2012. + * Based on your tests, please set this value. + * "0" will nullify implicitlyWait and speed up a test. */ + public static final int DEFAULT_WAIT_4_PAGE = 12; + + + + + /** + * Wait for the element to be present in the DOM, and displayed on the page. + * And returns the first WebElement using the given method. + * + * @param driver The driver object to be used + * @param by selector to find the element + * @param timeOutInSeconds The time in seconds to wait until returning a failure + * + * @return WebElement the first WebElement using the given method, or null (if the timeout is reached) + */ + public static WebElement waitForElement(WebDriver driver, final By by, Duration timeOutInSeconds) { + WebElement element; + try { + //To use WebDriverWait(), we would have to nullify implicitlyWait(). + //Because implicitlyWait time also set "driver.findElement()" wait time. + //info from: https://groups.google.com/forum/?fromgroups=#!topic/selenium-users/6VO_7IXylgY + driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //nullify implicitlyWait() + + WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds); + element = wait.until(ExpectedConditions.visibilityOfElementLocated(by)); + + driver.manage().timeouts().implicitlyWait(DEFAULT_WAIT_4_PAGE, TimeUnit.SECONDS); //reset implicitlyWait + return element; //return the element + } catch (Exception e) { + e.printStackTrace(); + } + return null; + + } + } diff --git a/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/WebDriverManager.java b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/WebDriverManager.java new file mode 100644 index 0000000000..b7b30fbc08 --- /dev/null +++ b/TestAutomation/src/main/java/ca/bc/gov/open/jagFileSubmission/WebDriverManager.java @@ -0,0 +1,150 @@ +package ca.bc.gov.open.jagFileSubmission; + +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.chrome.ChromeOptions; +import org.openqa.selenium.edge.EdgeDriver; +import org.openqa.selenium.edge.EdgeOptions; +import org.openqa.selenium.firefox.FirefoxBinary; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.firefox.FirefoxOptions; +import org.openqa.selenium.ie.InternetExplorerDriver; +import org.openqa.selenium.remote.DesiredCapabilities; +import org.openqa.selenium.support.ui.Select; +import org.openqa.selenium.support.ui.WebDriverWait; + +import java.io.File; +import java.time.Duration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class WebDriverManager { + + public static WebDriverManager instance = null; + + // web driver objects + private static WebDriver driver = null; + private static WebDriverWait driverWait = null; + private static WebElement element = null; + private static List elements = null; + private static Select select = null; + + /** + * private ctor - initialize everything + */ + private WebDriverManager() { + driver = initDriver(); + Duration duration4 = Duration.ofSeconds(10); + driverWait = (new WebDriverWait(driver,duration4)); + element = null; + elements = null; + select = null; + } + + public static WebDriverManager getInstance() { + if (instance == null) { + instance = new WebDriverManager(); + } + return instance; + } + + @SuppressWarnings("deprecation") + private static WebDriver initDriver() { + + if (Config.SELECTED_DRIVER.equals(Constants.CHROME_DRIVER)) { + + File file = new File("bin/chromedriver.exe"); + + System.setProperty("webdriver.chrome.driver", file.getAbsolutePath()); + + DesiredCapabilities capabilities = new DesiredCapabilities(); + + Map prefs = new HashMap<>(); + prefs.put("safebrowsing.enabled", "false"); // Bypass warning message, keep file anyway (for .exe, .jar, etc.) + + ChromeOptions options = new ChromeOptions(); + + options.addArguments("test-type"); + options.setExperimentalOption("prefs", prefs); + options.addArguments("start-maximized"); + options.addArguments("--remote-allow-origins=*"); + options.addArguments("--headless", "--disable-gpu", "--window-size=1920,1080","--ignore-certificate-errors","--no-sandbox", "--disable-dev-shm-usage"); + + capabilities.setCapability("chrome.binary", file.getAbsolutePath()); + + capabilities.setCapability(ChromeOptions.CAPABILITY, options); + + driver = new ChromeDriver(options); + + } else if (Config.SELECTED_DRIVER.equals(Constants.FIREFOX_DRIVER)) { + + FirefoxBinary firefoxBinary = new FirefoxBinary(); + firefoxBinary.addCommandLineOptions("--headless"); + File file = new File("bin/geckodriver.exe"); + System.setProperty("webdriver.gecko.driver", file.getAbsolutePath()); + FirefoxOptions firefoxOptions = new FirefoxOptions(); + firefoxOptions.setBinary(firefoxBinary); + driver = new FirefoxDriver(firefoxOptions); + driver.manage().window().maximize(); + + } else if (Config.SELECTED_DRIVER.equals(Constants.IE_DRIVER)) { + + // driver = new InternetExplorerDriver(); + + String service = "C:\\repo\\epbc-ui-test\\TestProject\\lib\\IEDriverServer.exe"; + System.setProperty("webdriver.ie.driver", service); + + // Create the DesiredCapability object of InternetExplorer + //DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer(); + + // Settings to Accept the SSL Certificate in the Capability object + //capabilities.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true); + + InternetExplorerDriver driver = new InternetExplorerDriver(); + // driver.get("URL for which certificate error is coming"); + driver.get("https://tst-apply.educationplannerbc.ca/account/create" + "/account/login"); + + } else if (Config.SELECTED_DRIVER.equals(Constants.EDGE_DRIVER)) { + + // Defining System Property for Edge + File file = new File("bin/msedgedriver.exe"); + System.setProperty("webdriver.edge.driver", file.getAbsolutePath()); + + driver = new EdgeDriver(); + driver.manage().window().maximize(); + + // Initialize the EdgeOptions class + EdgeOptions edgeOptions = new EdgeOptions(); + + // Use the addArguments method for configuring headless + // edgeOptions.addArguments("headless"); + + } + + return driver; + + } + + public static WebDriver getDriver() { + return getInstance().driver; + } + + public static WebDriverWait getDriverWait() { + return getInstance().driverWait; + } + + public static WebElement getElement() { + return getInstance().element; + } + + public static List getElements() { + return getInstance().elements; + } + + public static Select getSelect() { + return getInstance().select; + } + +} diff --git a/TestAutomation/src/test/java/ca/bc/gov/open/ui/LoginBCID.java b/TestAutomation/src/test/java/ca/bc/gov/open/ui/LoginBCID.java new file mode 100644 index 0000000000..691e500cdc --- /dev/null +++ b/TestAutomation/src/test/java/ca/bc/gov/open/ui/LoginBCID.java @@ -0,0 +1,60 @@ +package ca.bc.gov.open.ui; + +import ca.bc.gov.open.jagFileSubmission.CommonUtils; +import ca.bc.gov.open.jagFileSubmission.WebDriverManager; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Test; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.springframework.stereotype.Component; + + +import java.time.Duration; +@Component +public class LoginBCID { + + private WebDriver driver; + + @After + public void tearDown() { + driver.close(); + driver.quit(); + } + + @AfterClass + public static void afterClass() { + WebDriverManager.instance = null; + } + + @Test + public void test() throws Exception { + driver = WebDriverManager.getDriver(); + WebDriverWait driverWait = WebDriverManager.getDriverWait(); + WebElement element = WebDriverManager.getElement(); + WebDriverManager.getElements(); + String bceidUSERNAME = System.getenv("USERNAME_BCEID"); + String bceidPASSWORD = System.getenv("PASSWORD_BCEID"); + CommonUtils.login(); + + new WebDriverWait(driver, Duration.ofSeconds(10)).until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), ' Login with my ')]"))).click(); + System.out.println("Login with BCID page loaded successfully"); + + element = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.id("user"))); + element.sendKeys(bceidUSERNAME); + element = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.id("password"))); + element.sendKeys(bceidPASSWORD); + element = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.name("btnSubmit"))); + element.click(); + //Login successfully + new WebDriverWait(driver, Duration.ofSeconds(50)).until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), ' New Form ')]"))); + System.out.println("Login successfully"); + + + } +} diff --git a/TestAutomation/src/test/java/ca/bc/gov/open/ui/NoticeOfAppearance.java b/TestAutomation/src/test/java/ca/bc/gov/open/ui/NoticeOfAppearance.java new file mode 100644 index 0000000000..8533c86df9 --- /dev/null +++ b/TestAutomation/src/test/java/ca/bc/gov/open/ui/NoticeOfAppearance.java @@ -0,0 +1,107 @@ +package ca.bc.gov.open.ui; + +import ca.bc.gov.open.jagFileSubmission.WebDriverManager; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Test; +import org.openqa.selenium.By; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; + +import java.time.Duration; + +public class NoticeOfAppearance { + + private WebDriver driver; + + @After + public void tearDown() { + driver.close(); + driver.quit(); + } + + @AfterClass + public static void afterClass() { + WebDriverManager.instance = null; + } + + @Test + public void test() throws Exception { + driver = WebDriverManager.getDriver(); + WebDriverWait driverWait = WebDriverManager.getDriverWait(); + WebElement element = WebDriverManager.getElement(); + WebDriverManager.getElements(); + + LoginBCID notice = new LoginBCID(); + notice.test(); + + new WebDriverWait(driver, Duration.ofSeconds(10)).until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), ' Notice of Appearance (Form 2) ')]"))).click(); + + element = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.id("court-of-appeal-file-no"))); + element.sendKeys("CA46532"); + + driverWait.until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"respondent\"]/div[1]/label/span"))).click(); + + element = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.id("first-name"))); + element.sendKeys("Blair"); + element = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.id("last-name"))); + element.sendKeys("Greenwood"); + Thread.sleep(1000); + // Scroll down till the bottom of the page + JavascriptExecutor js = (JavascriptExecutor) driver; + js.executeScript("window.scrollBy(0,document.body.scrollHeight)"); + driver.findElement(By.xpath("//html")).click(); + new WebDriverWait(driver, Duration.ofSeconds(10)).until( + ExpectedConditions.presenceOfElementLocated(By.className("btn-success"))).click(); + Thread.sleep(1000); + element = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/div/main/div/div/div[4]/div/div/div/div[1]/div[2]/div[1]/select"))); + element.sendKeys("4 Pillars Consulting Group Inc."); + Thread.sleep(1000); + element = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/div/main/div/div/div[4]/div/div/div/div[1]/div[2]/div[2]/select"))); + element.sendKeys("Blair Greenwood"); + driver.findElement(By.cssSelector(".custom-control:nth-child(7) > .custom-control-label")).click(); + //text with address + element = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/div/main/div/div/div[4]/div/div/div/div[2]/div[2]/div[2]/div/textarea"))); + element.sendKeys("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vi"); + //phone no + element = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/div/main/div/div/div[4]/div/div/div/div[2]/div[3]/div[2]/div[1]/input"))); + element.sendKeys("999-999-9999"); + //email + element = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/div/main/div/div/div[4]/div/div/div/div[2]/div[4]/div[2]/div/input"))); + element.sendKeys("test@test.ca"); + //name + element = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/div/main/div/div/div[4]/div/div/div/div[2]/div[5]/div[2]/input"))); + element.sendKeys("Blair Greenwood"); + //Click Continue + new WebDriverWait(driver, Duration.ofSeconds(10)).until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), 'Continue ')]"))).click(); + new WebDriverWait(driver, Duration.ofSeconds(10)).until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), 'OK')]"))).click(); + new WebDriverWait(driver, Duration.ofSeconds(10)).until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), 'Blair Greenwood')]"))); + new WebDriverWait(driver, Duration.ofSeconds(10)).until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), 'Lorem ipsum dolor sit amet, consectetuer adipiscing')]"))); + Thread.sleep(1500); + new WebDriverWait(driver, Duration.ofSeconds(10)).until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), 'Proceed ')]"))).click(); + Thread.sleep(1500); + new WebDriverWait(driver, Duration.ofSeconds(50)).until( + ExpectedConditions.presenceOfElementLocated(By.className("btn-success"))).click(); + Thread.sleep(1000); + new WebDriverWait(driver, Duration.ofSeconds(50)).until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), 'Continue')]"))).click(); + element = driverWait.until(ExpectedConditions.presenceOfElementLocated(By.id("agreeCallout"))); + element.click(); + new WebDriverWait(driver, Duration.ofSeconds(50)).until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), 'Submit')]"))).click(); + new WebDriverWait(driver, Duration.ofSeconds(50)).until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), ' Done ')]"))); + + } +} diff --git a/TestAutomation/src/test/java/ca/bc/gov/open/ui/VerifyNoticeSubmitted.java b/TestAutomation/src/test/java/ca/bc/gov/open/ui/VerifyNoticeSubmitted.java new file mode 100644 index 0000000000..25c1518a67 --- /dev/null +++ b/TestAutomation/src/test/java/ca/bc/gov/open/ui/VerifyNoticeSubmitted.java @@ -0,0 +1,56 @@ +package ca.bc.gov.open.ui; + +import ca.bc.gov.open.jagFileSubmission.WebDriverManager; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Test; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; + +import java.time.Duration; + +public class VerifyNoticeSubmitted { + + private WebDriver driver; + + @After + public void tearDown() { + driver.close(); + driver.quit(); + } + + @AfterClass + public static void afterClass() { + WebDriverManager.instance = null; + } + + @Test + public void test() throws Exception { + driver = WebDriverManager.getDriver(); + WebDriverWait driverWait = WebDriverManager.getDriverWait(); + WebElement element = WebDriverManager.getElement(); + WebDriverManager.getElements(); + + NoticeOfAppearance packageNo = new NoticeOfAppearance(); + packageNo.test(); + + + WebElement e = driver.findElement( + By.xpath("/html/body/div/main/div/div/div/div[2]/div[2]/div[3]/div[2]/span")); + String actualpackageID = e.getText(); + + System.out.println("packageID: " + actualpackageID); + + //Click Done + new WebDriverWait(driver, Duration.ofSeconds(10)).until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), ' Done ')]"))).click(); + new WebDriverWait(driver, Duration.ofSeconds(50)).until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), ' New Form ')]"))); + new WebDriverWait(driver, Duration.ofSeconds(50)).until( + ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(text(), '" + actualpackageID + "')]"))); + + } +} diff --git a/TestAutomation/src/test/resources/application.properties b/TestAutomation/src/test/resources/application.properties new file mode 100644 index 0000000000..20bf908e68 --- /dev/null +++ b/TestAutomation/src/test/resources/application.properties @@ -0,0 +1,4 @@ + +#BCEIDCREDS +USERNAME_BCEID=${USERNAME_BCEID} +PASSWORD_BCEID=${PASSWORD_BCEID} diff --git a/docker-compose.override.yml b/docker-compose.override.yml new file mode 100644 index 0000000000..244e7acb46 --- /dev/null +++ b/docker-compose.override.yml @@ -0,0 +1,30 @@ +version: "3.7" +services: + + ############################################################################################# + ### EFILING FRONTEND ### + ############################################################################################# + efiling-frontend: + build: + context: ./src/frontend/efiling-frontend + + ############################################################################################# + ### Efiling api backend app ### + ############################################################################################# + efiling-api: + build: + context: ./src/backend + dockerfile: Dockerfile.efiling-api + args: + - MVN_PROFILE=${MVN_PROFILE:-efiling-api-demo} + - SKIP_TESTS=true + - STARTERS_V=v1.0.5 + + # ############################################################################################# + # ### KEYCLOAK Config ### + # ############################################################################################# + keycloak-config: + build: + context: ./infrastructure/keycloak + args: + - KEYCLOAK_URL=http://keycloak:8080 diff --git a/docker-compose.yml b/docker-compose.yml index 77819b6780..aa21b77d25 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -4,60 +4,101 @@ services: ### EFILING FRONTEND ### ############################################################################################# efiling-frontend: - # need stdin_open:true because there is an issue with container being auto exited after startup with react-scripts 3.4.1 - stdin_open: true container_name: efiling-frontend - build: - context: ./src/frontend - args: - - SERVICE_NAME=efiling-frontend ports: - - 3000:3000 + - 3000:8080 + environment: + - REACT_APP_KEYCLOAK_REALM=${KEYCLOAK_REALM:-Efiling-Hub} + - REACT_APP_KEYCLOAK_CLIENT_ID=efiling-frontend + - REACT_APP_KEYCLOAK_URL=${KEYCLOAK_URL:-http://localhost:8081/auth} + - REACT_APP_API_BASE_URL=http://localhost:8080 + - REACT_APP_BAMBORA_REDIRECT_URL=http://localhost:3000/efilinghub + - REACT_APP_CSO_BASE_URL=http://localhost/cso + - REACT_APP_RUSH_TAB_FEATURE_FLAG=true ############################################################################################# ### EFILING DEMO ### ############################################################################################# efiling-demo: - # need stdin_open:true because there is an issue with container being auto exited after startup with react-scripts 3.4.1 - stdin_open: true container_name: efiling-demo build: - context: ./src/frontend - args: - - SERVICE_NAME=efiling-demo + context: ./src/frontend/efiling-demo + environment: + - REACT_APP_KEYCLOAK_REALM=Efiling-Hub + - REACT_APP_KEYCLOAK_CLIENT_ID=efiling-admin + - REACT_APP_KEYCLOAK_URL=http://localhost:8081/auth + - REACT_APP_API_BASE_URL=http://localhost:8080 + - REACT_APP_BAMBORA_REDIRECT_URL=http://localhost:3000/efilinghub ports: - - 3001:3000 + - 3001:8080 ############################################################################################# ### Efiling api backend app ### ############################################################################################# efiling-api: - build: - context: ./src/backend - args: - - SERVICE_NAME=efiling-api - - MVN_PROFILE=${MVN_PROFILE} + container_name: efiling-api + hostname: efiling-api ports: - "8080:8080" environment: - - REDIS_HOST=redis - - REDIS_PORT=6379 - - REDIS_PASSWORD=admin - - NAVIGATION_BASE_URL=http://localhost:3000/efiling - - NAVIGATION_EXPIRYTIME=10 - - DEMO_MODE=${DEMO_MODE:-true} + - BAMBORA_APIPASSCODE=${BAMBORA_APIPASSCODE:-passcode} + - BAMBORA_MERCHANTID=${BAMBORA_MERCHANTID-merchantid} + - BAMBORA_PROFILE_URL=${BAMBORA_PROFILE_URL:-http://localhost:3001/updatecard} + - BAMBORA_HASHKEY=${BAMBORA_HASHKEY:-key} + - BAMBORA_PROFILE_SERVICE_VERSION=${BAMBORA_PROFILE_SERVICE_VERSION} + - BAMBORA_URL_EXPIRY=10 + + - KEYCLOAK_AUTH_SERVER_URL=${KEYCLOAK_AUTH_SERVER_URL:-http://localhost:8081/auth/realms/Efiling-Hub} + - KEYCLOAK_JWK_SERVER_URL=${KEYCLOAK_JWK_SERVER_URL:-http://keycloak:8080/auth/realms/Efiling-Hub} + - KEYCLOAK_REALM=${KEYCLOAK_RESOURCE:-efiling-api} + + - CSO_ACCOUNTFACADE_URI=${CSO_ACCOUNTFACADE_URI} - CSO_ACCOUNTFACADE_USERNAME=${CSO_ACCOUNTFACADE_USERNAME} - CSO_ACCOUNTFACADE_PASSWORD=${CSO_ACCOUNTFACADE_PASSWORD} - - CSO_ACCOUNTFACADE_URI=${CSO_ACCOUNTFACADE_URI} - CSO_ROLEREGISTRY_USERNAME=${CSO_ROLEREGISTRY_USERNAME} - CSO_ROLEREGISTRY_PASSWORD=${CSO_ROLEREGISTRY_PASSWORD} - CSO_ROLEREGISTRY_URI=${CSO_ROLEREGISTRY_URI} - CSO_LOOKUPFACADE_USERNAME=${CSO_LOOKUPFACADE_USERNAME} - CSO_LOOKUPFACADE_PASSWORD=${CSO_LOOKUPFACADE_PASSWORD} - CSO_LOOKUPFACADE_URI=${CSO_LOOKUPFACADE_URI} - - BCEID_LOOKUP_USERNAME=${BCEID_LOOKUP_USERNAME} - - BCEID_LOOKUP_PASSWORD=${BCEID_LOOKUP_PASSWORD} - - BCEID_LOOKUP_URI=${BCEID_LOOKUP_URI} + - CSO_BCEIDSERVICE_URI=${CSO_BCEIDSERVICE_URI} + - CSO_FILINGSTATSFACADE_URI=${CSO_FILINGSTATSFACADE_URI} + - CSO_FILINGSTATSFACADE_USERNAME=${CSO_FILINGSTATSFACADE_USERNAME} + - CSO_FILINGSTATSFACADE_PASSWORD=${CSO_FILINGSTATSFACADE_PASSWORD} + - CSO_BCEIDSERVICE_USERNAME=${CSO_BCEIDSERVICE_USERNAME} + - CSO_BCEIDSERVICE_PASSWORD=${CSO_BCEIDSERVICE_PASSWORD} + - CSOWS_USERNAME=${CSOWS_USERNAME} + - CSOWS_PASSWORD=${CSOWS_PASSWORD} + - CSOWS_URI=${CSOWS_URI} + - CSO_FILINGFACADE_URI=${CSO_FILINGFACADE_URI} + - CSO_FILINGFACADE_PASSWORD=${CSO_FILINGFACADE_PASSWORD} + - CSO_FILINGFACADE_USERNAME=${CSO_FILINGFACADE_USERNAME} + - CSO_SERVICEFACADE_URI=${CSO_SERVICEFACADE_URI} + - CSO_SERVICEFACADE_USERNAME=${CSO_SERVICEFACADE_USERNAME} + - CSO_SERVICEFACADE_PASSWORD=${CSO_SERVICEFACADE_PASSWORD} + + - SFTP_KNOWNHOSTS=${SFTP_KNOWNHOSTS} + - SFTP_REMOTELOCATION=${SFTP_REMOTELOCATION} + - SFTP_PRIVATE_KEY=${SFTP_PRIVATE_KEY} + + - BCEID_SERVICE_URI=${BCEID_SERVICE_URI} + - BCEID_SERVICE_USERNAME=${BCEID_SERVICE_USERNAME} + - BCEID_SERVICE_PASSWORD=${BCEID_SERVICE_PASSWORD} + - BCEID_SERVICE_ONLINE_SERVICE_ID=${BCEID_SERVICE_ONLINE_SERVICE_ID} + + - REDIS_HOST=redis + - REDIS_PORT=6379 + - REDIS_PASSWORD=admin + + - NAVIGATION_BASE_URL=http://localhost:3000/efilinghub + - NAVIGATION_EXPIRYTIME=10 + + - CLAMAV_HOST=clamav + - CLAMAV_TIMEOUT=150000 + + - MVN_PROFILE=${MVN_PROFILE} + - STARTERS_V=${STARTERS_V} + networks: - fisu-net @@ -65,7 +106,7 @@ services: ### REDIS SERVER ### ############################################################################################# redis: - container_name: redis + container_name: efiling_redis image: redis command: redis-server --requirepass admin ports: @@ -77,61 +118,75 @@ services: - fisu-net ############################################################################################# - ### RABBIT MQ SERVER ### + ### REDIS COMMANDER ### ############################################################################################# - rabbitmq: - image: rabbitmq:3.7.15-management - container_name: rabbitmq - hostname: rabbitmq + redis-commander: + container_name: efiling_redis-commander + hostname: redis-commander + image: rediscommander/redis-commander:latest + restart: always + environment: + - REDIS_PORT=6379 + - REDIS_HOST=redis + - REDIS_PASSWORD=admin ports: - - 5672:5672 - - 15672:15672 + - "8082:8081" + networks: + - fisu-net + + # ############################################################################################# + # ### KEYCLOAK ### + # ############################################################################################# + keycloak: + image: quay.io/keycloak/keycloak:26.1.3 + environment: + - KC_HEALTH_ENABLED=true + - KC_METRICS_ENABLED=true + - KC_HTTP_ENABLED=true + - KC_HOSTNAME_STRICT_HTTPS=false + - KEYCLOAK_SSL_REQUIRED=none + - KC_HOSTNAME_STRICT_BACKCHANNEL=false + - KC_PROXY_HEADERS=xforwarded + - KC_HOSTNAME=localhost + - KC_HTTP_RELATIVE_PATH=/auth + - KC_HOSTNAME_PORT=8080 + - DB_VENDOR=H2 + - KC_BOOTSTRAP_ADMIN_USERNAME=admin + - KC_BOOTSTRAP_ADMIN_PASSWORD=admin + - KC_DIR=/opt/keycloak/data/import volumes: - - data-rabbit:/var/lib/rabbitmq/mnesia/rabbit@app-rabbitmq:cached + - ./infrastructure/keycloak/realm-export.json:/opt/keycloak/data/import/realm-export.json + ports: + - 8081:8080 restart: always + command: start --import-realm networks: - fisu-net - ############################################################################################# - ### KEYCLOAK POSTGRES ### - ############################################################################################# - - postgres: - image: postgres - volumes: - - postgres_data:/var/lib/postgresql/data - environment: - POSTGRES_DB: keycloak - POSTGRES_USER: keycloak - POSTGRES_PASSWORD: password + # ############################################################################################# + # ### KEYCLOAK Config ### + # ############################################################################################# + keycloak-config: + command: sh -c "dockerize -timeout 300s /tmp/createuser.sh" + networks: + - fisu-net ############################################################################################# - ### KEYCLOAK ### + ### CLAMAV ### ############################################################################################# - - keycloak: - image: quay.io/keycloak/keycloak:latest - environment: - DB_VENDOR: POSTGRES - DB_ADDR: postgres - DB_DATABASE: keycloak - DB_USER: keycloak - DB_SCHEMA: public - DB_PASSWORD: password - KEYCLOAK_USER: admin - KEYCLOAK_PASSWORD: Pa55w0rd - # Uncomment the line below if you want to specify JDBC parameters. The parameter below is just an example, and it shouldn't be used in production without knowledge. It is highly recommended that you read the PostgreSQL JDBC driver documentation in order to use it. - #JDBC_PARAMS: "ssl=true" + clamav: + image: mk0x/docker-clamav ports: - - 8081:8080 - depends_on: - - postgres + - "3310:3310" + networks: + - fisu-net volumes: data-redis: - data-rabbit: - postgres_data: driver: local + data01: + driver: local + mongo-volume: networks: fisu-net: diff --git a/docs/README.md b/docs/README.md index e1c788064f..cabac54691 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,2 +1,239 @@ # jag-file-submission + Generic File Submission API (to be used by the Family Law Act Application at first) + +## Introduction + +Are you ready to integrate your application with the BC Gov E-filing Hub in order to allow your users to e-file documents? + +This guide will provide you with all the required information you need to get started. + +### Request a profile + +> Follow the following instructions in [Getting started - Onboarding](onboarding.md) + +### Start Integrating + +Get an oauth token from our Keycloak Server using the following curl command: + +```bash +curl --location --request POST 'keycloak_url' \ +--header 'Content-Type: application/x-www-form-urlencoded' \ +--data-urlencode 'client_id=[your client id]' \ +--data-urlencode 'grant_type=client_credentials' \ +--data-urlencode 'client_secret=[your client secret]' +``` + +> the secret should be kept safe and not exposed to the public + +Start by uploading document(s) to the **eFiling Hub** API: + +```bash +curl --location --request POST '[filing-hub-url]/submission/documents' \ +--header 'X-Transaction-Id: ca09e538-d34e-11ea-87d0-0242ac130003' \ +--header 'X-User-Id: [X-User-Id]' \ +--header 'Content-Type: multipart/form-data' \ +--header 'Authorization: Bearer [bearer_token]' \ +--form 'files=test.pdf' +``` + +the response includes a submission id that you will use to generate a redirect url + +```json +{ + "submissionId": "5e9492cf-e87e-48b5-ba55-0c198d8edde5", + "received": 1 +} +``` + +Then generate a unique url to redirect the users to the **eFiling Hub** + +```bash +curl --location --request POST '[filing-hub-url]/submission/5e9492cf-e87e-48b5-ba55-0c198d8edde5/generateUrl' \ +--header 'X-Transaction-Id: ca09e538-d34e-11ea-87d0-0242ac130003' \ +--header 'X-User-Id: [X-User-Id]' \ +--header 'Content-Type: application/json' \ +--header 'Authorization: Bearer [bearer_token]' \ +--data-raw 'the json payload bellow' +``` + +payload: + +```json +{ + "clientAppName": "string", + "filingPackage": { + "court": { + "location": "string", + "level": "P", + "courtClass": "F", + "division": "I", + "fileNumber": "string" + }, + "documents": [ + { + "name": "string", + "type": "ABP", + "isAmendment": true, + "isSupremeCourtScheduling": true, + "data": {}, + "md5": "string" + } + ], + "parties": [ + { + "roleType": "ABC", + "firstName": "string", + "middleName": "string", + "lastName": "string" + } + ], + "organizationParties": [ + { + "roleType": "ABC", + "name": "string" + } + ] + }, + "navigationUrls": { + "success": "string", + "error": "string", + "cancel": "string" + } +} +``` + +### Generate URL Payload Details + +#### navigation + +The `navigation` object represents a list of possible returns to your application based on the status of the document e-filing. + +#### clientApplication + +The `clientApplication` object represents how your application is labelled in **efiling hub**. + +#### filingPackage + +The `filingPackage` object represents the court information about the submitted package along with the document(s) info. + +##### court + +The `court` object represents the court details. + +##### Properties + +| name | type | required | description | +| ---------- | ------ | -------- | ----------------------------------------------------------------------------- | +| location | string | true | Court House where the package is submitted to | +| level | string | true | Court level, can be `Supreme` of `Provincial` | +| courtClass | string | true | Court Classification see [Court Classification](data.md#Court-Classification) | +| division | string | true | R for Criminal, I for Civil see [Court Division](data.md#Court-Division) | +| fileNumber | string | false | The court file number, leave blank for new Package Submission | + +##### Documents + +The `documents` array represents the previously uploaded documents. + +###### Properties + +| name | type | required | description | +| ------------------------ | ------- | -------- | ------------------------------------------------------------------------------------------ | +| name | string | true | the document name, must be the same name as uploaded previously | +| type | string | true | the type of document see [Document Type Codes](data.md#Document-Type-Codes) | +| isAmendment | boolean | true | if the document is an amendment | +| isSupremeCourtScheduling | boolean | true | if the document is directed to Supreme Court Scheduling | +| data | object | false | A non defined json object representing the form data of the document | +| md5 | string | false | The md5 hash value of the document content, used to validate the integrity of the document | + +##### parties + +The `parties` array represents a list of individual parties for the submission + +##### Properties + + +| name | type | required | description | +| ---------- | ------ | -------- | ----------------------------------------------------------------------------------------------- | +| roleType | string | true | the party role, see [Party Role](data.md#Party-Role) | +| firstName | string | true | the party first name | +| middleName | string | false | the party middle name | +| lastName | string | true | the party last name | + +##### organizationParties + +The `organizationParties` array represents a list of organization parties for the submission + +##### Properties + + +| name | type | required | description | +| ---------- | ------ | -------- | ----------------------------------------------------------------------------------------------- | +| roleType | string | true | the party role, see [Party Role](data.md#Party-Role) | +| name | string | true | the organization name | + +### Package Review + +The efiling Package Review screen shows the details of a submitted package. + +https://dev.justice.gov.bc.ca/efilinghub/packagereview/:packageId?returnUrl=&returnAppName=&defaultTab= + +The returnUrl parameter is optional, but if an encoded URL is supplied, the +page will render with a button that will return the user to the given URL +(i.e., parent application). + +The returnAppName parameter is optional, but if an encoded name of the Parent Application +is specified, the "Return to Parent App" button will be named accordingly. + +The defaultTab parameter is optional, but if an encoded defaultTab +is specified, the Package Review will display that tab by default. + +### Api Documentation + +eFiling API is documented using [openapi](http://editor.swagger.io/?url=https://raw.githubusercontent.com/bcgov/jag-file-submission/master/src/backend/efiling-api/jag-efiling-api.yaml) and we have a [postman collection](https://raw.githubusercontent.com/bcgov/jag-file-submission/master/src/backend/jag-efiling-api/src/test/jag-efiling-api.postman_collection.json) that you can use to test the eFiling API + +#### Answers to FAQ: + +##### What should be used for `roleType` and `partyType` in parties? + +The default values to be used for `roleType` is CLA and for `partyType` it is IND. Can refer to the roles in the code tables for more details. + +#### Are the various types of documents the ones present in this list? - https://bcgov.github.io/jag-file-submission/#/data? + +Yes. This is our list of various document types that can be submitted. +For FLA, the document types are as follows: Application to Obtain an Order (APO) , Notice of Motion (NM), Affidavit (AFF), and Electronic Filing Statement (EFS- Provincial). + +##### For the parties info, would this be the applicant and respondent? + +Yes. Applicant and respondent is correct for the parties. + +##### For documents, what kind of information should/can be included in the following fields? + +`Data`: A copy of the data collected on parent app side. JSON object containing the party info, potential issue, acts, things associated with divorce, etc. + +`MD5`: Computed hash value of the document content, it is used as a checksum to validate the document integrity. + +`isAmendment`: This marks if the document is an amendment. + +`isSupremeCourtScheduling`: This marks if the document is for supreme court scheduling. The Supreme Court Scheduling will not apply initially as we are dealing with Provincial Court, but in the future Supreme Court will be applicable. + +##### What should the value of `clientAppName` be? + +This field signifies the name of the parent application integrating with the eFiling hub and will show up on the eFiling hub, so please use a full form name such as `Family Law Act Application`. + +##### For the court information, how should the fields be determined for this section? + +Parent app should know level and class. Court location can be provided through the code tables. + +#### Response + +on submission you will receive the following response: + +```json +{ + "expiryDate": 1597944879789, + "efilingUrl": "a link where the user should be redirected" +} +``` + +Redirect the user to `efilingUrl` and we will handle the rest for you. diff --git a/docs/_sidebar.md b/docs/_sidebar.md index 8ea4d22da6..c2bb1f305a 100644 --- a/docs/_sidebar.md +++ b/docs/_sidebar.md @@ -1,5 +1,7 @@ -* [Home](/) -* [Getting started](gettingStarted.md) -* [Integration](integration.md) -* [Dictionary](dictionary.md) -* [Timeline](timeline.md) +- [Home](/) +- [Onboarding](onboarding.md) +- [Error Handling](errorHandling.md) +- [Data](data.md) +- [Integration](integration.md) +- [Dictionary](dictionary.md) +- [Timeline](timeline.md) diff --git a/docs/data.md b/docs/data.md new file mode 100644 index 0000000000..d00976309b --- /dev/null +++ b/docs/data.md @@ -0,0 +1,240 @@ +# Data + +In this section you can find values to use for efling packages to Court Services Online + +## Document Type Codes + +| documentTypeCd | documentTypeDesc | +| -------------- | --------------------------------------------------------------------------------------- | +| AFF | Affidavit | +| AFJ | Affidavit Section 51 | +| AAS | Affidavit of Attempted Service | +| APS | Affidavit of Personal Service | +| AMM | Agreement Made In a Facilitated Planning Meeting or Mediation | +| AEO | Application Respecting Existing Orders or Agreements | +| AFO | Application for an Order - CFCSA | +| APC | Application to Change/Cancel Order | +| AEC | Application to Enforce a Custody Order | +| APO | Application to Obtain an Order | +| ARC | Application to Recognize a Custody or Access Order made by an Extra-Provincial Tribunal | +| AEA | Application to Recognize an Extraprovincial Order | +| ARE | Application to Renew, Change or Cancel an Order (Adult Guardianship) | +| ARD | Application to re-set Court date | +| CCB | Case Conference Brief | +| CCR | Case Conference Record | +| CRDF | Certificate - Notice of Default Fee | +| CRA | Certificate of Attempted Service | +| COEA | Certificate of Enforceability and Arrears | +| CRF | Certificate of Fitness | +| COI | Certificate of Incapability (Form 2 AGA) | +| COJ | Certificate of Judgment | +| CSV | Certificate of Service | +| COT | Consent (Form 19) | +| COR | Consent Order | +| CPR | Consent for Child Protection Record Check | +| CCA | Consent to Court Date | +| CRP | Correspondence | +| CUR | Currency Certificate | +| CAR | Custody and Access Report | +| DPO | Default Payment Order | +| DOR | Desk Order | +| DET | Determination | +| EFSP | Electronic Filing Statement - Provincial | +| FRCC | FMEP Request for Certified Copies | +| FCR | Family Case Conference Record (FLA) | +| FLC | Family Law Matter Claim (Victoria only) | +| FSUM | File Summary (Victoria only - ERP Project) | +| FS | Financial Statement/Statement of Finances | +| FAC | Form A - Circumstances that caused removal | +| FBW | Form B - Withdrawal by Director | +| FFS | Form F - Section 29.1 Application for Supervision Order Report | +| ORNA | Form J Order without Notice/Appearance | +| FULL | Full Report - FLA s.211 | +| GOA | Garnishing Order After Judgment | +| GOB | Garnishing Order Before Judgment | +| HCL | Hague Convention Article 16 Letter | +| IPR | Internal Pre-Trial Conference Record | +| LOD | List of Documents | +| NID | NOI to Dispute Monies Pd into Court | +| NOA | Notice of Appeal | +| NA | Notice of Attachment | +| NCD | Notice of Change of Address For Delivery | +| NCS | Notice of Change of Solicitor | +| NFC | Notice of Family Claim | +| NFMC | Notice of Family Management Case Conference | +| NOF | Notice of Filing | +| NOH | Notice of Hearing or Conference | +| NIAP | Notice of Intention to Act in Person | +| NPR | Notice of Intention to Proceed | +| NM | Notice of Motion | +| NME | Notice of Motion in Maintenance Enforcement Proceedings | +| NPO | Notice of Payment Out | +| NRP | Notice of Protection or Restraining Order | +| NRG | Notice of Registration | +| NRO | Notice of Restraining Order (PFA 806) | +| NWD | Notice of Withdrawal | +| NWS | Notice of Withdrawal of Solicitor | +| NTR | Notice to Appear (Adult Guardianship Act) | +| NTD | Notice to Debtor - FMEP | +| ORD | Order | +| ODT | Order (Form 7) | +| ORO | Order (opens file) | +| ORP | Order for Attendance of a Prisoner in a Civil or Family Matter | +| OA | Order for Attendence of a Prisoner | +| OTH | Other Document | +| PAS | Parenting After Separation Certificate | +| PASE | Parenting After Separation Exemption | +| PAR | Parenting Arrangement Report | +| POC | Plan of Care | +| REP | Presentation Report | +| PPL | Proposal | +| PTS | Proposed terms of supervision (CFCSA) | +| POR | Protection Order | +| PIO | Protective Intervention Order | +| PVO | Provisional Order | +| RFJ | Reasons For Judgment | +| RCF | Record Check Results - s.51 Child Protection (MCFD) | +| RCR | Record Check Results - s.51 Protection Order Registry | +| REF | Referal Request | +| RO | Release (FRA) | +| RPL | Reply | +| RTC | Reply to a Counterclaim | +| RPC | Reply with Counterclaim | +| RQT | Request (Form 18) | +| RCE | Request for Court Enforcement | +| RPS | Request for Protection Order Registry Search | +| RFS | Request for Service of Documents | +| RFT | Request for Teleconference | +| RFR | Request for s.211 Report - FLA | +| RGW | Request to Adjourn Generally or Withdraw Application | +| REQ | Requisition | +| RSA | Respondent's Answer to Application - ISO Form N | +| RSO | Restraining Order | +| ROR | Restraining Order under Family Maintenance Enforcement Act | +| SNR | Scheduling Instructions - No Reply | +| SWR | Scheduling Instructions - With Reply | +| SR | Search Request | +| SRR | Search Request Response from Locate Services | +| SA | Separation Agreement | +| SOA | Statement of Arrears | +| SRO | Statement of Recalculation | +| SUB | Submissions | +| STW | Subpoena to a Witness | +| SUM | Summons | +| SCH | Summons to a Committal Hearing | +| SDH | Summons to a Default Hearing | +| SAP | Support Application | +| SVA | Support Variation Application | +| TRN | Transcript | +| TC | Transfer Consent | +| VOC | Views of the Child Report - FLA s.211 | +| WAV | Waiver (Notification period CFCSA) | +| WCL | Warrant Cancellation | +| WFA | Warrant for Arrest | +| WAW | Warrant for Witness | +| WOC | Warrant of Committal | +| WAE | Warrant of Execution | +| WEX | Warrant of Execution | +| WAA | Warrant to Arrest | +| HCLW | Withdrawal of Hague Convention Letter - Article 16 | +| WNC | Without Notice Application Checklist | +| WRT | Writ of Summons | +| WAG | Written Agreement | +| WCT | Written Consent | + +## Court Classification + +| Level | Level Description | Classification | Classification Description | +| ----- | ----------------- | -------------- | ------------------------------ | +| A | Appeal | O | Appeal Civil | +| P | Provincial | C | Small Claims | +| P | Provincial | F | Family | +| P | Provincial | L | Enforcement/Legislated Statute | +| P | Provincial | M | Motor Vehicle Accidents | +| S | Supreme | B | Bankruptcy | +| S | Supreme | D | Divorce | +| S | Supreme | E | Family Law Proceedings | +| S | Supreme | H | Foreclosure | +| S | Supreme | L | Enforcement/Legislated Statute | +| S | Supreme | M | Motor Vehicle Accidents | +| S | Supreme | N | Adoption | +| S | Supreme | P | Probate | +| S | Supreme | S | Supreme Civil (General) | +| S | Supreme | V | Caveat | + +## Court Division + +| Code | Description | +| R | Criminal Court | +| C | Civil Court | + +## Party Role + +| Code | Description | +| ---- | --------------------------------- | +| ABC | Aboriginal Community | +| ADJ | Adjudicator | +| ADP | Adoptee | +| APL | Appellant | +| APP | Applicant | +| ANT | Aunt | +| AUT | Authority | +| BKP | Bankrupt | +| BKS | Bankrupts (Spouse) | +| CAV | Caveator | +| CHD | Child | +| COF | Child on File | +| CIT | Citator | +| CLA | Claimant | +| CLA1 | Claimant 1 | +| CLA2 | Claimant 2 | +| CLI | Client | +| CI | Court Issued | +| CRD | Creditor | +| DBT | Debtor | +| DEC | Deceased | +| DEF | Defendant | +| DEO | Defendant by Counterclaim | +| DIS | Disputant | +| FTH | Father | +| FNA | First Nation | +| GRF | Grandfather | +| GRM | Grandmother | +| GUA | Guardian | +| HSB | Husband - Divorce | +| INB | Indian Band | +| INC | Indigenous Community | +| ITV | Intervener | +| MOT | Mother | +| NIS | Nisga'a Lisims Government | +| PAR1 | Party 1 | +| PA1 | Party 1 Joint Divorce Form127A | +| PAR2 | Party 2 | +| PA2 | Party 2 Joint Divorce Form127A | +| PAR3 | Party 3 | +| PAR4 | Party 4 | +| PAR5 | Party 5 | +| PET | Petitioner | +| PLA | Plaintiff | +| RES | Respondent | +| REO | Respondent by way of Counterclaim | +| SOL | Solicitor | +| SP1 | Spouse 1- Divorce | +| SP2 | Spouse 2 - Divorce | +| SFH | Step-Father | +| SMH | Step-Mother | +| TST | Testator | +| TSX | Testatrix | +| THR | Third Party | +| TFN | Treaty First Nation | +| TRU | Trustee | +| UNC | Uncle | +| WIF | Wife - Divorce | +| WIT | Witness | + +## Party type + +| Code | Description | +| ---- | ------------ | +| IND | Individual | +| ORG | Organization | diff --git a/docs/errorHandling.md b/docs/errorHandling.md new file mode 100644 index 0000000000..84a3161e0e --- /dev/null +++ b/docs/errorHandling.md @@ -0,0 +1,87 @@ +# Error Handling + +This documentation defines how errors may be handled by the eFiling Hub; it is based on the User Flow diagram. + +## Incorrect Navigation + +1. Navigating to the site without a submission ID or with an invalid submission ID will result in rendering an error message. + +## Initial Package Verification + +1. Package information from Parent App is not sufficient - does not include document descriptions, valid Parent App return link etc. + - System returns error to Parent App + - Parent App action TDB + +## User Account Verification/Setup + +1. User does not have an eFiling role + + - Parent app may hide button/option to use eFiling (Check for eFiling role on authentication?) + - Parent app may display error message. E.g. "You do not have a valid CSO account and are unable to use the eFiling Hub to file documents at this time" + +2. User does not authorize creation of CSO account (Does not tick the "I Accept" checkbox) + + - "Create CSO Account" button is in disabled state with roll-over/tap text "Please accept the Service Agreement to continue" + +3. CSO Account cannot be created (may be multiple reasons) + - User is returned to Parent App with error message. E.g. "CSO Account required for eFiling could not be created at this time. Please try again later" + +## Package Confirmation + +- No known error potential at this step. Initial Package Verification error handling should catch error states. + +## Document Upload + +1. Document fails upload because size is over 10mb + + - eFiling Hub displays error message. E.g. “Document size is limited to 10mb. Please reduce the size of your documents (_tips on how to reduce size?_) or visit (_information on process?_) to learn how to file larger documents” + +2. Document fails to upload because extention type is not supported + + - eFiling Hub displays error message. E.g. "Documents with the following extension type are not supported: exe" + +3. Document fails to upload to staging area + + - eFiling Hub displays error message. E.g. "Document upload failed. Please try again" + +4. Document fails to upload to staging area more than 3 times + - TBD + +## Payment Review + +1. Registering a new card with Bambora fails + + - Bambora app handles validation failure. User stays on Bambora until they cancel. + +2. If user cancels on Bambora + + - eFiling Hub displays the alert "You do not have a valid Credit Card registered with your CSO Account. Register a card now to continue. + +3. If a user tries to "Register a card now" more than 5 times + - (_do we want to treat this an card validation attempt security event?_) TBD + +## Package Submission + +1. User does not accept the "I have reviewed the information" prompt (Does not tick the "I Agree" checkbox) + + - "Submit" button is in disabled state with roll-over/tap text "Please review your submission and Agree to continue" + +2. Submit documents to CSO failed because CSO is down + + - System tried again with loading indicator displayed in eFiling Hub + +3. Submit documents to CSO failed more than 3 times + + - User is returned to Parent App with error message. E.g. "Package filing failed. Please try again later" + +4. CSO fee processing failed + - TBD + +## Rush/Urgent Submission + +- TBD + +## Cancel + +1. User clicks "Cancel" button + - User is prompted to confirm, and if yes, is returned to Parent App with message. E.g. "Your eFiling submission has been cancelled" diff --git a/docs/gettingStarted.md b/docs/gettingStarted.md deleted file mode 100644 index bf010c427e..0000000000 --- a/docs/gettingStarted.md +++ /dev/null @@ -1,62 +0,0 @@ -# Getting started - -## Introduction - -Ready for integrating your application with bcgov efiling service and allow your users to efile document ? - -This guide will provide you with all information you need to get started. - -## Test accounts - -Use the following accounts to test the application - -| Account Guid | Description | -| --- | --- | -| 77da92db-0791-491e-8c58-1a969e67d2fa | An account with a linked CSO account and an efiling role | -| 77da92db-0791-491e-8c58-1a969e67d2fb | An account with a linked CSO account and no efiling role | -| 88da92db-0791-491e-8c58-1a969e67d2fb | An account without CSO account but a fake bceid profile | - -## Quick start - -Generate a secure url by calling the generateUrl endpoint - -```bash - -curl --location --request POST 'http://localhost:8080/document/generateUrl' \ ---header 'Content-Type: application/json' \ ---data-raw '{ - "documentMetadata": { - "type": "string", - "subType": "string", - "documentAccess": { - "url": "string", - "verb": "GET", - "headers": { - "additionalProp1": "string", - "additionalProp2": "string", - "additionalProp3": "string" - } - } - }, - "navigation": { - "success": { - "url": "string" - }, - "error": { - "url": "string" - }, - "cancel": { - "url": "string" - } - } -}' - -``` - -## Api Documentation - -E-filing-api is documented using [openapi](http://editor.swagger.io/?url=https://raw.githubusercontent.com/bcgov/jag-file-submission/master/src/backend/efiling-api/jag-efiling-api.yaml) and we have a [postman collection](https://raw.githubusercontent.com/bcgov/jag-file-submission/master/src/backend/jag-efiling-api/src/test/jag-efiling-api.postman_collection.json) that you can use to test the e-filing-api - -## Diagram flow - -
diff --git a/docs/integration.md b/docs/integration.md index c8988a7aef..41ceb03177 100644 --- a/docs/integration.md +++ b/docs/integration.md @@ -1,8 +1,8 @@ # JAG File Submission Continuous Integration -## Git Action Workflow +## CI/CD Workflow -
+
## Code Climate diff --git a/docs/media/demoApp.png b/docs/media/demoApp.png index ce372958ea..068e83b22e 100644 Binary files a/docs/media/demoApp.png and b/docs/media/demoApp.png differ diff --git a/docs/onboarding.md b/docs/onboarding.md new file mode 100644 index 0000000000..061bb4e0ce --- /dev/null +++ b/docs/onboarding.md @@ -0,0 +1,34 @@ +# Getting Started - Onboarding + +## Request Keycloak Client + +Create a Github [issue](https://github.com/bcgov/jag-file-submission/issues/new?assignees=akroon3r%2C+alexjoybc&labels=Onboarding&template=onboarding-request.md&title=%5BONBOARDING%5D) to begin the onboarding process to our application. + +On completion of the Github issue, the user will be provided [OpenId Connect](https://openid.net/connect/) information such as *client_id*, *realm*, *client_secret*. All of which are required to be kept secured at all times. + +## Request Keycloak Token + +First, users will want to POST against the following URL: ${keycloakBaseUrl}/realms/${keycloakRealm}/protocol/openid-connect/token + +- ${keycloakBaseUrl} will be the value https://sso-${ENVIRONMENT}.pathfinder.gov.bc.ca/auth, where ${ENVIRONMENT} is either dev, test or prod +- ${keycloakRealm} will be provided to you by the admin after the keycloak client request has been fufilled + +In the request body, the following information will be required + +Example body: client_id=${keycloakClientId}&grant_type=client_credentials&client_secret=${keycloakClientSecret} + +- client_id : Provided to the user by the admin after the keycloak client request has been fufilled +- grant_type : value will always be `client_credentials` +- client_secret : Provided to the user by the admin after the keycloak client request has been fufilled + +Once the request for the keycloak token has been completed successfully, the user can begin to interface with the Efiling Hub [API](https://editor.swagger.io/?url=https://raw.githubusercontent.com/bcgov/jag-file-submission/master/src/backend/efiling-api/jag-efiling-api.yaml) and Frontend Applications. The two API endpoints that a parent application will interface with are the `/submission/documents` and `/submission/${submissionId}/generateUrl`. + +The following is a sample curl command for generating a token from any keycloak environment: + +``` bash +curl --location --request POST 'https://[keycloak auth endpoint]/auth/realms/[keycloak-realm]/protocol/openid-connect/token' \ +--header 'Content-Type: application/x-www-form-urlencoded' \ +--data-urlencode 'client_id=[your client id]' \ +--data-urlencode 'grant_type=client_credentials' \ +--data-urlencode 'client_secret=[your client secret]' +``` diff --git a/infrastructure/keycloak/Dockerfile b/infrastructure/keycloak/Dockerfile new file mode 100644 index 0000000000..4442b201d2 --- /dev/null +++ b/infrastructure/keycloak/Dockerfile @@ -0,0 +1,23 @@ +FROM ubuntu:18.04 + +ARG KEYCLOAK_URL +ARG DOCKERIZE_VERSION=v0.6.1 + +ENV KEYCLOAK_URL=$KEYCLOAK_URL + +# Temp fix for maching have clock issue. see https://stackoverflow.com/questions/63526272/release-file-is-not-valid-yet-docker +RUN echo "Acquire::Check-Valid-Until \"false\";\nAcquire::Check-Date \"false\";" | cat > /etc/apt/apt.conf.d/10no--check-valid-until + +RUN apt-get update && \ + apt-get install -y curl jq wget && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists + +RUN wget https://github.com/jwilder/dockerize/releases/download/$DOCKERIZE_VERSION/dockerize-alpine-linux-amd64-$DOCKERIZE_VERSION.tar.gz && \ + tar -C /usr/local/bin -xzvf dockerize-alpine-linux-amd64-$DOCKERIZE_VERSION.tar.gz && \ + rm dockerize-alpine-linux-amd64-$DOCKERIZE_VERSION.tar.gz + +COPY createuser.sh /tmp/createuser.sh +RUN chmod +x /tmp/createuser.sh + +CMD ["/tmp/createuser.sh"] diff --git a/infrastructure/keycloak/createuser.sh b/infrastructure/keycloak/createuser.sh new file mode 100755 index 0000000000..b83780632d --- /dev/null +++ b/infrastructure/keycloak/createuser.sh @@ -0,0 +1,112 @@ +#!/bin/bash + +sleep 1m + +KEYCLOAK_REALM_URL="$KEYCLOAK_URL/auth/admin/realms/Efiling-Hub" +USERNAME="bobross" +ADMIN_GROUP="efiling-admin" +EARLY_GROUP="efiling-early-adopters" + +# Get admin user token +ADMIN_TOKEN=$(curl -s --location --request POST "$KEYCLOAK_URL/auth/realms/master/protocol/openid-connect/token" \ + --header 'Content-Type: application/x-www-form-urlencoded' \ + --header 'Cookie: 8a49b93d4f41531bc1d1ef85f2b65254=2fb8f4c2fe6843d186204f21cc45dd4b' \ + --data-urlencode 'client_id=admin-cli' \ + --data-urlencode 'grant_type=password' \ + --data-urlencode 'username=admin' \ + --data-urlencode 'password=admin' | jq -r '.access_token') + +if [ -z "$ADMIN_TOKEN" ] +then + echo "Error connecting to keycloak" + exit 1 +fi + +echo "Successfully connected to keycloak" + +# Create efiling-hub user +CREATE_USER_STATUS=$(curl -s -o /dev/null -w '%{http_code}' \ + --request POST "$KEYCLOAK_REALM_URL/users" \ + --header "Authorization: Bearer $ADMIN_TOKEN" \ + --header 'Content-Type: application/json' \ + --data-raw '{ + "firstName": "bob", + "lastName": "ross", + "email": "bobross@paintit.com", + "enabled": "true", + "username": "bobross", + "attributes": { + "universal-id": ["77da92db-0791-491e-8c58-1a969e67d2fa"] + }, + "credentials": [ + { + "type": "password", + "temporary": false, + "value": "changeme" + } + ]}') + +if [ $CREATE_USER_STATUS -eq 201 ]; then + echo "user created" +elif [ $CREATE_USER_STATUS -eq 409 ]; then + echo "user already exists" +else + echo "Error connecting to keycloak" + exit 2 +fi + + +# Get user id +USER_ID=$(curl -s --location --request GET "$KEYCLOAK_REALM_URL/users?username=$USERNAME" \ +--header "Authorization: Bearer $ADMIN_TOKEN" | jq -r '.[0].id') + +if [ -z "$USER_ID" ]; then + echo "user bob ross does not exists" + exit 3 +fi + +# Get group id +ADMIN_GROUP_ID=$(curl -s --location --request GET "$KEYCLOAK_REALM_URL/groups?search=$ADMIN_GROUP" \ +--header "Authorization: Bearer $ADMIN_TOKEN" | jq -r '.[0].id') + +if [ -z "$ADMIN_GROUP_ID" ]; then + echo "admin group id does not exist" + exit 4 +fi + +# Add user to efiling-admin group +ADD_TO_ADMIN_STATUS=$(curl -s -o /dev/null -w '%{http_code}' \ + --request PUT "$KEYCLOAK_REALM_URL/users/$USER_ID/groups/$ADMIN_GROUP_ID" \ + --header "Authorization: Bearer $ADMIN_TOKEN" \ + --header 'Content-Type: application/json') + +if [ $ADD_TO_ADMIN_STATUS -eq 204 ]; then + echo "user added to admin group" +else + echo "Error adding user to admin group" + exit 5 +fi + +# Get early-adopters id +EARLY_GROUP_ID=$(curl -s --location --request GET "$KEYCLOAK_REALM_URL/groups?search=$EARLY_GROUP" \ +--header "Authorization: Bearer $ADMIN_TOKEN" | jq -r '.[0].id') + +if [ -z "$EARLY_GROUP_ID" ]; then + echo "early adopters group id does not exist" + exit 4 +fi + +# Add user to efiling-early-adopters group +ADD_TO_EARLY_STATUS=$(curl -s -o /dev/null -w '%{http_code}' \ + --request PUT "$KEYCLOAK_REALM_URL/users/$USER_ID/groups/$EARLY_GROUP_ID" \ + --header "Authorization: Bearer $ADMIN_TOKEN" \ + --header 'Content-Type: application/json') + +if [ $ADD_TO_EARLY_STATUS -eq 204 ]; then + echo "user added to efiling-early-adopters group" +else + echo "Error adding user to efiling-early-adopters group" + exit 5 +fi + +exit 0 diff --git a/infrastructure/keycloak/realm-export.json b/infrastructure/keycloak/realm-export.json new file mode 100644 index 0000000000..1eb889d10b --- /dev/null +++ b/infrastructure/keycloak/realm-export.json @@ -0,0 +1,2263 @@ +{ + "id": "test", + "realm": "Efiling-Hub", + "displayName": "Efiling Hub", + "notBefore": 0, + "revokeRefreshToken": false, + "refreshTokenMaxReuse": 0, + "accessTokenLifespan": 300, + "accessTokenLifespanForImplicitFlow": 900, + "ssoSessionIdleTimeout": 1800, + "ssoSessionMaxLifespan": 36000, + "ssoSessionIdleTimeoutRememberMe": 0, + "ssoSessionMaxLifespanRememberMe": 0, + "offlineSessionIdleTimeout": 2592000, + "offlineSessionMaxLifespanEnabled": false, + "offlineSessionMaxLifespan": 5184000, + "clientSessionIdleTimeout": 0, + "clientSessionMaxLifespan": 0, + "clientOfflineSessionIdleTimeout": 0, + "clientOfflineSessionMaxLifespan": 0, + "accessCodeLifespan": 60, + "accessCodeLifespanUserAction": 300, + "accessCodeLifespanLogin": 1800, + "actionTokenGeneratedByAdminLifespan": 43200, + "actionTokenGeneratedByUserLifespan": 300, + "enabled": true, + "sslRequired": "external", + "registrationAllowed": false, + "registrationEmailAsUsername": false, + "rememberMe": false, + "verifyEmail": false, + "loginWithEmailAllowed": true, + "duplicateEmailsAllowed": false, + "resetPasswordAllowed": false, + "editUsernameAllowed": false, + "bruteForceProtected": false, + "permanentLockout": false, + "maxFailureWaitSeconds": 900, + "minimumQuickLoginWaitSeconds": 60, + "waitIncrementSeconds": 60, + "quickLoginCheckMilliSeconds": 1000, + "maxDeltaTimeSeconds": 43200, + "failureFactor": 30, + "roles": { + "realm": [ + { + "id": "88016b52-2916-41a2-9d15-33723dc31551", + "name": "offline_access", + "description": "${role_offline-access}", + "composite": false, + "clientRole": false, + "containerId": "test", + "attributes": {} + }, + { + "id": "29b5ee13-d47f-4eb6-b6f7-448bdf6c458c", + "name": "uma_authorization", + "description": "${role_uma_authorization}", + "composite": false, + "clientRole": false, + "containerId": "test", + "attributes": {} + } + ], + "client": { + "realm-management": [ + { + "id": "109a1138-953d-4b75-8873-388ec21dc1f1", + "name": "view-events", + "description": "${role_view-events}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "26e3489a-6993-4f76-a341-bc223b5c092e", + "name": "impersonation", + "description": "${role_impersonation}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "2751d2fb-3368-46ce-bf95-f9e257aeb2de", + "name": "manage-authorization", + "description": "${role_manage-authorization}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "bbf3ca94-a057-44ba-a160-7df37bc54c21", + "name": "query-groups", + "description": "${role_query-groups}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "b8adf8df-b633-4cb3-a606-ad0d094e1577", + "name": "realm-admin", + "description": "${role_realm-admin}", + "composite": true, + "composites": { + "client": { + "realm-management": [ + "view-events", + "impersonation", + "manage-authorization", + "query-groups", + "view-realm", + "query-clients", + "view-clients", + "view-users", + "manage-events", + "query-users", + "manage-realm", + "view-identity-providers", + "query-realms", + "manage-identity-providers", + "manage-users", + "create-client", + "view-authorization", + "manage-clients" + ] + } + }, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "fb02f4e9-a444-4579-9be7-c3e813f547f8", + "name": "query-clients", + "description": "${role_query-clients}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "a104b612-c1cb-46b6-ad46-29565c6b5e0f", + "name": "view-realm", + "description": "${role_view-realm}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "6e02b81b-466c-4d98-98ea-a4576c8f8abb", + "name": "view-clients", + "description": "${role_view-clients}", + "composite": true, + "composites": { + "client": { + "realm-management": ["query-clients"] + } + }, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "bc2ad235-53e1-49c3-871a-6e34922897fc", + "name": "manage-events", + "description": "${role_manage-events}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "e6039dcc-669c-4435-8344-ae4a2c41fb00", + "name": "query-users", + "description": "${role_query-users}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "46cbbf73-c504-490c-b647-e979aee6a032", + "name": "view-users", + "description": "${role_view-users}", + "composite": true, + "composites": { + "client": { + "realm-management": ["query-groups", "query-users"] + } + }, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "19a3779d-0694-4201-a8f5-27c086cb05e5", + "name": "manage-realm", + "description": "${role_manage-realm}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "6ff82c7e-0713-4c4e-8a6a-e285cb1cd3d0", + "name": "query-realms", + "description": "${role_query-realms}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "055db674-6963-41c7-9a55-9df1f09094bc", + "name": "view-identity-providers", + "description": "${role_view-identity-providers}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "9610a238-c19b-4041-a949-73848d4527b1", + "name": "manage-identity-providers", + "description": "${role_manage-identity-providers}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "d5b7c513-bce5-4b77-a224-0819febaba68", + "name": "create-client", + "description": "${role_create-client}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "7a4bb1d2-c8ba-43b4-ba83-5b7348e5634f", + "name": "manage-users", + "description": "${role_manage-users}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "bc8d5c3e-7738-4d81-896a-8ba66433383f", + "name": "view-authorization", + "description": "${role_view-authorization}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + }, + { + "id": "079deeb5-b344-47e2-ada5-b5cb2af3ad56", + "name": "manage-clients", + "description": "${role_manage-clients}", + "composite": false, + "clientRole": true, + "containerId": "67b85937-008d-414c-9ee9-5f0fc5950254", + "attributes": {} + } + ], + "security-admin-console": [], + "efiling-admin": [], + "efiling-frontend": [], + "admin-cli": [], + "efiling-api": [ + { + "id": "102cf99b-8b2c-4568-b447-a5c0d6d21c27", + "name": "efiling-admin", + "description": "controls - access to admin features", + "composite": false, + "clientRole": true, + "containerId": "972b79de-44ab-4b64-8bf3-9c1794bfbbbe", + "attributes": {} + }, + { + "id": "4689e81c-0c72-4a4d-bb5c-660eee970540", + "name": "early-adopters", + "description": "group for early adopters", + "composite": false, + "clientRole": true, + "containerId": "972b79de-44ab-4b64-8bf3-9c1794bfbbbe", + "attributes": {} + }, + { + "id": "0f0d19fb-3ee1-4881-a1f6-3bff60386d4c", + "name": "efiling-rush", + "description": "This role allow user to submit rushed submissions", + "composite": false, + "clientRole": true, + "containerId": "972b79de-44ab-4b64-8bf3-9c1794bfbbbe", + "attributes": {} + }, + { + "id": "baeb0a13-43ee-4f43-a6b6-e3125009b875", + "name": "efiling-user", + "description": "default efiling user role", + "composite": false, + "clientRole": true, + "containerId": "972b79de-44ab-4b64-8bf3-9c1794bfbbbe", + "attributes": {} + }, + { + "id": "f47cddc6-9f88-4aea-82f5-a7a0244b372b", + "name": "efiling-client", + "description": "Role for client application, allows client to interact with dedicated endpoints", + "composite": false, + "clientRole": true, + "containerId": "972b79de-44ab-4b64-8bf3-9c1794bfbbbe", + "attributes": {} + } + ], + "account-console": [], + "broker": [ + { + "id": "acf420c6-8aeb-46a3-9fd7-eaa6e8df4a9d", + "name": "read-token", + "description": "${role_read-token}", + "composite": false, + "clientRole": true, + "containerId": "a0f4b6ca-76b6-4a43-919d-8e7decb308d1", + "attributes": {} + } + ], + "account": [ + { + "id": "e9033b04-7d86-448f-b45a-7aaa3200075c", + "name": "view-consent", + "description": "${role_view-consent}", + "composite": false, + "clientRole": true, + "containerId": "924c2240-577c-4737-9279-9febbb800a1b", + "attributes": {} + }, + { + "id": "84586445-80c7-4c43-8e33-7e286ab999dd", + "name": "manage-account-links", + "description": "${role_manage-account-links}", + "composite": false, + "clientRole": true, + "containerId": "924c2240-577c-4737-9279-9febbb800a1b", + "attributes": {} + }, + { + "id": "08de3662-56e8-48ff-a6b7-e12299943a22", + "name": "delete-account", + "description": "${role_delete-account}", + "composite": false, + "clientRole": true, + "containerId": "924c2240-577c-4737-9279-9febbb800a1b", + "attributes": {} + }, + { + "id": "2e48fd0e-5036-451d-af6e-34cc114c5b1f", + "name": "view-profile", + "description": "${role_view-profile}", + "composite": false, + "clientRole": true, + "containerId": "924c2240-577c-4737-9279-9febbb800a1b", + "attributes": {} + }, + { + "id": "bc8f543c-6d1d-462c-b731-9a695fc8467a", + "name": "view-applications", + "description": "${role_view-applications}", + "composite": false, + "clientRole": true, + "containerId": "924c2240-577c-4737-9279-9febbb800a1b", + "attributes": {} + }, + { + "id": "e650447d-63e0-4ced-bf44-cecf9ecc15d4", + "name": "manage-consent", + "description": "${role_manage-consent}", + "composite": true, + "composites": { + "client": { + "account": ["view-consent"] + } + }, + "clientRole": true, + "containerId": "924c2240-577c-4737-9279-9febbb800a1b", + "attributes": {} + }, + { + "id": "a77f02a4-4de5-465b-b64c-617644d8b19e", + "name": "manage-account", + "description": "${role_manage-account}", + "composite": true, + "composites": { + "client": { + "account": ["manage-account-links"] + } + }, + "clientRole": true, + "containerId": "924c2240-577c-4737-9279-9febbb800a1b", + "attributes": {} + } + ] + } + }, + "groups": [ + { + "id": "53514a5a-cbac-41c3-9942-881f1a2c0798", + "name": "efiling-admin", + "path": "/efiling-admin", + "attributes": {}, + "realmRoles": [], + "clientRoles": { + "efiling-api": ["efiling-admin"] + }, + "subGroups": [] + }, + { + "id": "92a7b5e7-c246-4eff-856d-80b7500df3f0", + "name": "efiling-early-adopters", + "path": "/efiling-early-adopters", + "attributes": {}, + "realmRoles": [], + "clientRoles": { + "efiling-api": ["early-adopters"] + }, + "subGroups": [] + }, + { + "id": "4dbc7648-1055-4838-ba10-6a5d91cc1c00", + "name": "efiling-user", + "path": "/efiling-user", + "attributes": {}, + "realmRoles": [], + "clientRoles": { + "efiling-api": ["efiling-user"] + }, + "subGroups": [] + } + ], + "defaultRoles": ["offline_access", "uma_authorization"], + "defaultGroups": ["/efiling-user"], + "requiredCredentials": ["password"], + "otpPolicyType": "totp", + "otpPolicyAlgorithm": "HmacSHA1", + "otpPolicyInitialCounter": 0, + "otpPolicyDigits": 6, + "otpPolicyLookAheadWindow": 1, + "otpPolicyPeriod": 30, + "otpSupportedApplications": ["FreeOTP", "Google Authenticator"], + "webAuthnPolicyRpEntityName": "keycloak", + "webAuthnPolicySignatureAlgorithms": ["ES256"], + "webAuthnPolicyRpId": "", + "webAuthnPolicyAttestationConveyancePreference": "not specified", + "webAuthnPolicyAuthenticatorAttachment": "not specified", + "webAuthnPolicyRequireResidentKey": "not specified", + "webAuthnPolicyUserVerificationRequirement": "not specified", + "webAuthnPolicyCreateTimeout": 0, + "webAuthnPolicyAvoidSameAuthenticatorRegister": false, + "webAuthnPolicyAcceptableAaguids": [], + "webAuthnPolicyPasswordlessRpEntityName": "keycloak", + "webAuthnPolicyPasswordlessSignatureAlgorithms": ["ES256"], + "webAuthnPolicyPasswordlessRpId": "", + "webAuthnPolicyPasswordlessAttestationConveyancePreference": "not specified", + "webAuthnPolicyPasswordlessAuthenticatorAttachment": "not specified", + "webAuthnPolicyPasswordlessRequireResidentKey": "not specified", + "webAuthnPolicyPasswordlessUserVerificationRequirement": "not specified", + "webAuthnPolicyPasswordlessCreateTimeout": 0, + "webAuthnPolicyPasswordlessAvoidSameAuthenticatorRegister": false, + "webAuthnPolicyPasswordlessAcceptableAaguids": [], + "scopeMappings": [ + { + "clientScope": "offline_access", + "roles": ["offline_access"] + } + ], + "clientScopeMappings": { + "account": [ + { + "client": "account-console", + "roles": ["manage-account"] + } + ] + }, + "clients": [ + { + "id": "924c2240-577c-4737-9279-9febbb800a1b", + "clientId": "account", + "name": "${client_account}", + "rootUrl": "${authBaseUrl}", + "baseUrl": "/realms/Efiling-Hub/account/", + "surrogateAuthRequired": false, + "enabled": true, + "alwaysDisplayInConsole": false, + "clientAuthenticatorType": "client-secret", + "secret": "**********", + "defaultRoles": ["view-profile", "manage-account"], + "redirectUris": ["/realms/Efiling-Hub/account/*"], + "webOrigins": [], + "notBefore": 0, + "bearerOnly": false, + "consentRequired": false, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "publicClient": false, + "frontchannelLogout": false, + "protocol": "openid-connect", + "attributes": {}, + "authenticationFlowBindingOverrides": {}, + "fullScopeAllowed": false, + "nodeReRegistrationTimeout": 0, + "defaultClientScopes": [ + "web-origins", + "role_list", + "roles", + "profile", + "email" + ], + "optionalClientScopes": [ + "address", + "phone", + "offline_access", + "microprofile-jwt" + ] + }, + { + "id": "d5d11c5e-72db-4436-9701-b3c17f10de3d", + "clientId": "account-console", + "name": "${client_account-console}", + "rootUrl": "${authBaseUrl}", + "baseUrl": "/realms/test/account/", + "surrogateAuthRequired": false, + "enabled": true, + "alwaysDisplayInConsole": false, + "clientAuthenticatorType": "client-secret", + "secret": "**********", + "redirectUris": ["/realms/test/account/*"], + "webOrigins": [], + "notBefore": 0, + "bearerOnly": false, + "consentRequired": false, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "publicClient": true, + "frontchannelLogout": false, + "protocol": "openid-connect", + "attributes": { + "pkce.code.challenge.method": "S256" + }, + "authenticationFlowBindingOverrides": {}, + "fullScopeAllowed": false, + "nodeReRegistrationTimeout": 0, + "protocolMappers": [ + { + "id": "388ef7e2-9edf-4e4e-8591-d182df18484c", + "name": "audience resolve", + "protocol": "openid-connect", + "protocolMapper": "oidc-audience-resolve-mapper", + "consentRequired": false, + "config": {} + } + ], + "defaultClientScopes": [ + "web-origins", + "role_list", + "roles", + "profile", + "email" + ], + "optionalClientScopes": [ + "address", + "phone", + "offline_access", + "microprofile-jwt" + ] + }, + { + "id": "25785dc8-7a99-4019-9f37-b75f1b0f0c94", + "clientId": "admin-cli", + "name": "${client_admin-cli}", + "surrogateAuthRequired": false, + "enabled": true, + "alwaysDisplayInConsole": false, + "clientAuthenticatorType": "client-secret", + "secret": "**********", + "redirectUris": [], + "webOrigins": [], + "notBefore": 0, + "bearerOnly": false, + "consentRequired": false, + "standardFlowEnabled": false, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": true, + "serviceAccountsEnabled": false, + "publicClient": true, + "frontchannelLogout": false, + "protocol": "openid-connect", + "attributes": {}, + "authenticationFlowBindingOverrides": {}, + "fullScopeAllowed": false, + "nodeReRegistrationTimeout": 0, + "defaultClientScopes": [ + "web-origins", + "role_list", + "roles", + "profile", + "email" + ], + "optionalClientScopes": [ + "address", + "phone", + "offline_access", + "microprofile-jwt" + ] + }, + { + "id": "a0f4b6ca-76b6-4a43-919d-8e7decb308d1", + "clientId": "broker", + "name": "${client_broker}", + "surrogateAuthRequired": false, + "enabled": true, + "alwaysDisplayInConsole": false, + "clientAuthenticatorType": "client-secret", + "secret": "**********", + "redirectUris": [], + "webOrigins": [], + "notBefore": 0, + "bearerOnly": false, + "consentRequired": false, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "publicClient": false, + "frontchannelLogout": false, + "protocol": "openid-connect", + "attributes": {}, + "authenticationFlowBindingOverrides": {}, + "fullScopeAllowed": false, + "nodeReRegistrationTimeout": 0, + "defaultClientScopes": [ + "web-origins", + "role_list", + "roles", + "profile", + "email" + ], + "optionalClientScopes": [ + "address", + "phone", + "offline_access", + "microprofile-jwt" + ] + }, + { + "id": "68deda16-9566-4b12-ac89-84b11e09780c", + "clientId": "efiling-admin", + "rootUrl": "http://localhost:3001", + "surrogateAuthRequired": false, + "enabled": true, + "alwaysDisplayInConsole": false, + "clientAuthenticatorType": "client-secret", + "secret": "**********", + "redirectUris": ["http://localhost:3001/*"], + "webOrigins": ["*"], + "notBefore": 0, + "bearerOnly": false, + "consentRequired": false, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": true, + "serviceAccountsEnabled": false, + "publicClient": true, + "frontchannelLogout": false, + "protocol": "openid-connect", + "attributes": { + "saml.assertion.signature": "false", + "saml.force.post.binding": "false", + "saml.multivalued.roles": "false", + "saml.encrypt": "false", + "backchannel.logout.revoke.offline.tokens": "false", + "saml.server.signature": "false", + "saml.server.signature.keyinfo.ext": "false", + "exclude.session.state.from.auth.response": "false", + "backchannel.logout.session.required": "true", + "client_credentials.use_refresh_token": "false", + "saml_force_name_id_format": "false", + "saml.client.signature": "false", + "tls.client.certificate.bound.access.tokens": "false", + "saml.authnstatement": "false", + "display.on.consent.screen": "false", + "saml.onetimeuse.condition": "false" + }, + "authenticationFlowBindingOverrides": {}, + "fullScopeAllowed": true, + "nodeReRegistrationTimeout": -1, + "protocolMappers": [ + { + "id": "0db5d028-403a-4566-b415-1218fc135925", + "name": "universal-id", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "universal-id", + "id.token.claim": "false", + "access.token.claim": "true", + "claim.name": "universal-id", + "jsonType.label": "String" + } + }, + { + "id": "8a7e052f-99ea-4e02-a570-4f1391c01a2a", + "name": "Efiling App Code", + "protocol": "openid-connect", + "protocolMapper": "oidc-hardcoded-claim-mapper", + "consentRequired": false, + "config": { + "claim.value": "DEMO", + "userinfo.token.claim": "true", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "cso-application-code", + "jsonType.label": "String", + "access.tokenResponse.claim": "false" + } + } + ], + "defaultClientScopes": [ + "web-origins", + "role_list", + "roles", + "profile", + "email" + ], + "optionalClientScopes": [ + "address", + "phone", + "offline_access", + "microprofile-jwt" + ] + }, + { + "id": "972b79de-44ab-4b64-8bf3-9c1794bfbbbe", + "clientId": "efiling-api", + "rootUrl": "http://localhost:8080", + "surrogateAuthRequired": false, + "enabled": true, + "alwaysDisplayInConsole": false, + "clientAuthenticatorType": "client-secret", + "secret": "**********", + "redirectUris": ["http://localhost:8080/*"], + "webOrigins": [], + "notBefore": 0, + "bearerOnly": false, + "consentRequired": false, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": true, + "serviceAccountsEnabled": false, + "publicClient": false, + "frontchannelLogout": false, + "protocol": "openid-connect", + "attributes": { + "saml.assertion.signature": "false", + "saml.force.post.binding": "false", + "saml.multivalued.roles": "false", + "saml.encrypt": "false", + "backchannel.logout.revoke.offline.tokens": "false", + "saml.server.signature": "false", + "saml.server.signature.keyinfo.ext": "false", + "exclude.session.state.from.auth.response": "false", + "backchannel.logout.session.required": "true", + "client_credentials.use_refresh_token": "false", + "saml_force_name_id_format": "false", + "saml.client.signature": "false", + "tls.client.certificate.bound.access.tokens": "false", + "saml.authnstatement": "false", + "display.on.consent.screen": "false", + "saml.onetimeuse.condition": "false" + }, + "authenticationFlowBindingOverrides": {}, + "fullScopeAllowed": true, + "nodeReRegistrationTimeout": -1, + "defaultClientScopes": [ + "web-origins", + "role_list", + "roles", + "profile", + "email" + ], + "optionalClientScopes": [ + "address", + "phone", + "offline_access", + "microprofile-jwt" + ] + }, + { + "id": "4afbfd92-0fe6-4801-a2eb-19b5852d5e13", + "clientId": "efiling-frontend", + "rootUrl": "http://localhost:3000", + "adminUrl": "http://localhost:3000", + "surrogateAuthRequired": false, + "enabled": true, + "alwaysDisplayInConsole": false, + "clientAuthenticatorType": "client-secret", + "secret": "**********", + "redirectUris": ["http://localhost:3000/*"], + "webOrigins": ["http://localhost:3000"], + "notBefore": 0, + "bearerOnly": false, + "consentRequired": false, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": true, + "serviceAccountsEnabled": false, + "publicClient": true, + "frontchannelLogout": false, + "protocol": "openid-connect", + "attributes": { + "backchannel.logout.session.required": "true", + "backchannel.logout.revoke.offline.tokens": "false" + }, + "authenticationFlowBindingOverrides": {}, + "fullScopeAllowed": true, + "nodeReRegistrationTimeout": -1, + "protocolMappers": [ + { + "id": "33c4c1a3-5701-41e2-b986-9249395aac44", + "name": "universal-id", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "universal-id", + "id.token.claim": "false", + "access.token.claim": "true", + "claim.name": "universal-id", + "jsonType.label": "String" + } + }, + { + "id": "4ca6d182-e816-469d-8933-ab81814625ac", + "name": "application-code", + "protocol": "openid-connect", + "protocolMapper": "oidc-hardcoded-claim-mapper", + "consentRequired": false, + "config": { + "claim.value": "DEMO", + "userinfo.token.claim": "true", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "cso-application-code", + "jsonType.label": "String", + "access.tokenResponse.claim": "false" + } + } + ], + "defaultClientScopes": [ + "web-origins", + "role_list", + "roles", + "profile", + "email" + ], + "optionalClientScopes": [ + "address", + "phone", + "offline_access", + "microprofile-jwt" + ] + }, + { + "id": "67b85937-008d-414c-9ee9-5f0fc5950254", + "clientId": "realm-management", + "name": "${client_realm-management}", + "surrogateAuthRequired": false, + "enabled": true, + "alwaysDisplayInConsole": false, + "clientAuthenticatorType": "client-secret", + "secret": "**********", + "redirectUris": [], + "webOrigins": [], + "notBefore": 0, + "bearerOnly": true, + "consentRequired": false, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "publicClient": false, + "frontchannelLogout": false, + "protocol": "openid-connect", + "attributes": {}, + "authenticationFlowBindingOverrides": {}, + "fullScopeAllowed": false, + "nodeReRegistrationTimeout": 0, + "defaultClientScopes": [ + "web-origins", + "role_list", + "roles", + "profile", + "email" + ], + "optionalClientScopes": [ + "address", + "phone", + "offline_access", + "microprofile-jwt" + ] + }, + { + "id": "ab0aae54-b778-4251-870d-aef6143369dc", + "clientId": "security-admin-console", + "name": "${client_security-admin-console}", + "rootUrl": "${authAdminUrl}", + "baseUrl": "/admin/Efiling-Hub/console/", + "surrogateAuthRequired": false, + "enabled": true, + "alwaysDisplayInConsole": false, + "clientAuthenticatorType": "client-secret", + "secret": "**********", + "redirectUris": ["/admin/Efiling-Hub/console/*"], + "webOrigins": ["+"], + "notBefore": 0, + "bearerOnly": false, + "consentRequired": false, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "publicClient": true, + "frontchannelLogout": false, + "protocol": "openid-connect", + "attributes": { + "pkce.code.challenge.method": "S256" + }, + "authenticationFlowBindingOverrides": {}, + "fullScopeAllowed": false, + "nodeReRegistrationTimeout": 0, + "protocolMappers": [ + { + "id": "a5579394-34b8-48c1-81a3-66c4fc03bece", + "name": "locale", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "locale", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "locale", + "jsonType.label": "String" + } + } + ], + "defaultClientScopes": [ + "web-origins", + "role_list", + "roles", + "profile", + "email" + ], + "optionalClientScopes": [ + "address", + "phone", + "offline_access", + "microprofile-jwt" + ] + } + ], + "clientScopes": [ + { + "id": "725470de-8981-4c81-98bd-3509261adf24", + "name": "address", + "description": "OpenID Connect built-in scope: address", + "protocol": "openid-connect", + "attributes": { + "include.in.token.scope": "true", + "display.on.consent.screen": "true", + "consent.screen.text": "${addressScopeConsentText}" + }, + "protocolMappers": [ + { + "id": "615ca1ef-f157-4dd1-b695-3c815aeb9aa2", + "name": "address", + "protocol": "openid-connect", + "protocolMapper": "oidc-address-mapper", + "consentRequired": false, + "config": { + "user.attribute.formatted": "formatted", + "user.attribute.country": "country", + "user.attribute.postal_code": "postal_code", + "userinfo.token.claim": "true", + "user.attribute.street": "street", + "id.token.claim": "true", + "user.attribute.region": "region", + "access.token.claim": "true", + "user.attribute.locality": "locality" + } + } + ] + }, + { + "id": "52b9840a-9717-4f09-b80b-1f02a8ff74c9", + "name": "email", + "description": "OpenID Connect built-in scope: email", + "protocol": "openid-connect", + "attributes": { + "include.in.token.scope": "true", + "display.on.consent.screen": "true", + "consent.screen.text": "${emailScopeConsentText}" + }, + "protocolMappers": [ + { + "id": "de4aa464-c83e-4685-80e5-42651e25a062", + "name": "email", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-property-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "email", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "email", + "jsonType.label": "String" + } + }, + { + "id": "471922f2-ca12-4bf9-8a36-bf8e26e8a707", + "name": "email verified", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-property-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "emailVerified", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "email_verified", + "jsonType.label": "boolean" + } + } + ] + }, + { + "id": "94fd8806-be94-430c-9eef-38d38be37139", + "name": "microprofile-jwt", + "description": "Microprofile - JWT built-in scope", + "protocol": "openid-connect", + "attributes": { + "include.in.token.scope": "true", + "display.on.consent.screen": "false" + }, + "protocolMappers": [ + { + "id": "84d81c56-2d5b-4853-9500-c14b02b00b8e", + "name": "upn", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-property-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "username", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "upn", + "jsonType.label": "String" + } + }, + { + "id": "01a28e74-339a-409f-8a56-5482a405ba74", + "name": "groups", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-realm-role-mapper", + "consentRequired": false, + "config": { + "multivalued": "true", + "userinfo.token.claim": "true", + "user.attribute": "foo", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "groups", + "jsonType.label": "String" + } + } + ] + }, + { + "id": "005a0de9-1ca4-4e76-8567-724e3b0be5e3", + "name": "offline_access", + "description": "OpenID Connect built-in scope: offline_access", + "protocol": "openid-connect", + "attributes": { + "consent.screen.text": "${offlineAccessScopeConsentText}", + "display.on.consent.screen": "true" + } + }, + { + "id": "0ff3d639-7bea-407a-ba30-38d9e33641ae", + "name": "phone", + "description": "OpenID Connect built-in scope: phone", + "protocol": "openid-connect", + "attributes": { + "include.in.token.scope": "true", + "display.on.consent.screen": "true", + "consent.screen.text": "${phoneScopeConsentText}" + }, + "protocolMappers": [ + { + "id": "ae6e7e67-1a52-47f8-a795-6472bfafb74e", + "name": "phone number", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "phoneNumber", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "phone_number", + "jsonType.label": "String" + } + }, + { + "id": "c75256c2-7fc5-41ac-9ef7-caab7b031591", + "name": "phone number verified", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "phoneNumberVerified", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "phone_number_verified", + "jsonType.label": "boolean" + } + } + ] + }, + { + "id": "777bdfd5-8889-4d38-94fd-a95340cea829", + "name": "profile", + "description": "OpenID Connect built-in scope: profile", + "protocol": "openid-connect", + "attributes": { + "include.in.token.scope": "true", + "display.on.consent.screen": "true", + "consent.screen.text": "${profileScopeConsentText}" + }, + "protocolMappers": [ + { + "id": "476826c3-c240-4bfc-b366-0c295b1a20e3", + "name": "website", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "website", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "website", + "jsonType.label": "String" + } + }, + { + "id": "1626e94f-31a3-49ac-845d-252823e61ac2", + "name": "full name", + "protocol": "openid-connect", + "protocolMapper": "oidc-full-name-mapper", + "consentRequired": false, + "config": { + "id.token.claim": "true", + "access.token.claim": "true", + "userinfo.token.claim": "true" + } + }, + { + "id": "968fe49b-3a14-4d71-b6dc-6cc584b34ed0", + "name": "zoneinfo", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "zoneinfo", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "zoneinfo", + "jsonType.label": "String" + } + }, + { + "id": "7700d3ed-f183-492f-bb4f-328f6ceb0490", + "name": "picture", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "picture", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "picture", + "jsonType.label": "String" + } + }, + { + "id": "8a330d1d-1049-4e55-94f1-fbc0444c8941", + "name": "updated at", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "updatedAt", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "updated_at", + "jsonType.label": "String" + } + }, + { + "id": "91a76d6e-13b5-4782-b0d8-6decfc60b431", + "name": "middle name", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "middleName", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "middle_name", + "jsonType.label": "String" + } + }, + { + "id": "25e87355-e714-41b3-a6bf-e8de18639ccb", + "name": "username", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-property-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "username", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "preferred_username", + "jsonType.label": "String" + } + }, + { + "id": "4647c894-f950-4b17-8892-ce46f3382e87", + "name": "gender", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "gender", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "gender", + "jsonType.label": "String" + } + }, + { + "id": "4f1af02c-c8a5-463b-8c20-a698078f9cc3", + "name": "family name", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-property-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "lastName", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "family_name", + "jsonType.label": "String" + } + }, + { + "id": "198612dd-56cf-4a76-bc2c-007c3302ac72", + "name": "nickname", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "nickname", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "nickname", + "jsonType.label": "String" + } + }, + { + "id": "c51cb373-42ad-4a2a-b845-1dbf3e369a3b", + "name": "profile", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "profile", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "profile", + "jsonType.label": "String" + } + }, + { + "id": "9f52ec0c-3e39-472f-a80b-6dc7a807d0ca", + "name": "locale", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "locale", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "locale", + "jsonType.label": "String" + } + }, + { + "id": "6740e9c8-0f93-4de3-aac8-84c9927621ba", + "name": "given name", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-property-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "firstName", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "given_name", + "jsonType.label": "String" + } + }, + { + "id": "e3350022-e59d-40b2-8e99-a04f1b8b6bb9", + "name": "birthdate", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-attribute-mapper", + "consentRequired": false, + "config": { + "userinfo.token.claim": "true", + "user.attribute": "birthdate", + "id.token.claim": "true", + "access.token.claim": "true", + "claim.name": "birthdate", + "jsonType.label": "String" + } + } + ] + }, + { + "id": "ce13a215-ee3f-4ea3-8ce9-3f0663ebaa83", + "name": "role_list", + "description": "SAML role list", + "protocol": "saml", + "attributes": { + "consent.screen.text": "${samlRoleListScopeConsentText}", + "display.on.consent.screen": "true" + }, + "protocolMappers": [ + { + "id": "a6a3a862-b822-4907-9211-f728fd73954f", + "name": "role list", + "protocol": "saml", + "protocolMapper": "saml-role-list-mapper", + "consentRequired": false, + "config": { + "single": "false", + "attribute.nameformat": "Basic", + "attribute.name": "Role" + } + } + ] + }, + { + "id": "206f88ef-2770-43e3-a0a1-bf84d0daa573", + "name": "roles", + "description": "OpenID Connect scope for add user roles to the access token", + "protocol": "openid-connect", + "attributes": { + "include.in.token.scope": "false", + "display.on.consent.screen": "true", + "consent.screen.text": "${rolesScopeConsentText}" + }, + "protocolMappers": [ + { + "id": "85c71801-edf2-4a3b-987a-9823de69f351", + "name": "audience resolve", + "protocol": "openid-connect", + "protocolMapper": "oidc-audience-resolve-mapper", + "consentRequired": false, + "config": {} + }, + { + "id": "5d7b30e9-4db8-497b-be92-2cc564cd388b", + "name": "realm roles", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-realm-role-mapper", + "consentRequired": false, + "config": { + "user.attribute": "foo", + "access.token.claim": "true", + "claim.name": "realm_access.roles", + "jsonType.label": "String", + "multivalued": "true" + } + }, + { + "id": "fa5097f5-70b5-4e98-a3f5-040d4fb79d39", + "name": "client roles", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-client-role-mapper", + "consentRequired": false, + "config": { + "user.attribute": "foo", + "access.token.claim": "true", + "claim.name": "resource_access.${client_id}.roles", + "jsonType.label": "String", + "multivalued": "true" + } + } + ] + }, + { + "id": "2d289740-f863-4be0-9031-8ca6b00b3d4c", + "name": "web-origins", + "description": "OpenID Connect scope for add allowed web origins to the access token", + "protocol": "openid-connect", + "attributes": { + "include.in.token.scope": "false", + "display.on.consent.screen": "false", + "consent.screen.text": "" + }, + "protocolMappers": [ + { + "id": "e35dafca-1611-4f90-bb79-a0007e53a9d5", + "name": "allowed web origins", + "protocol": "openid-connect", + "protocolMapper": "oidc-allowed-origins-mapper", + "consentRequired": false, + "config": {} + } + ] + } + ], + "defaultDefaultClientScopes": [ + "roles", + "web-origins", + "email", + "profile", + "role_list" + ], + "defaultOptionalClientScopes": [ + "offline_access", + "phone", + "address", + "microprofile-jwt" + ], + "browserSecurityHeaders": { + "contentSecurityPolicyReportOnly": "", + "xContentTypeOptions": "nosniff", + "xRobotsTag": "none", + "xFrameOptions": "SAMEORIGIN", + "contentSecurityPolicy": "frame-src 'self'; frame-ancestors 'self'; object-src 'none';", + "xXSSProtection": "1; mode=block", + "strictTransportSecurity": "max-age=31536000; includeSubDomains" + }, + "smtpServer": {}, + "eventsEnabled": false, + "eventsListeners": ["jboss-logging"], + "enabledEventTypes": [], + "adminEventsEnabled": false, + "adminEventsDetailsEnabled": false, + "identityProviders": [], + "identityProviderMappers": [], + "components": { + "org.keycloak.services.clientregistration.policy.ClientRegistrationPolicy": [ + { + "id": "87012b33-af56-4f4a-992e-913d219540e8", + "name": "Allowed Protocol Mapper Types", + "providerId": "allowed-protocol-mappers", + "subType": "authenticated", + "subComponents": {}, + "config": { + "allowed-protocol-mapper-types": [ + "oidc-full-name-mapper", + "oidc-address-mapper", + "oidc-usermodel-attribute-mapper", + "saml-role-list-mapper", + "oidc-usermodel-property-mapper", + "oidc-sha256-pairwise-sub-mapper", + "saml-user-attribute-mapper", + "saml-user-property-mapper" + ] + } + }, + { + "id": "3ae64f88-567e-452b-8652-e738badf57c8", + "name": "Consent Required", + "providerId": "consent-required", + "subType": "anonymous", + "subComponents": {}, + "config": {} + }, + { + "id": "d860bc28-c059-4e6e-810d-1dbe6d60c238", + "name": "Allowed Protocol Mapper Types", + "providerId": "allowed-protocol-mappers", + "subType": "anonymous", + "subComponents": {}, + "config": { + "allowed-protocol-mapper-types": [ + "oidc-address-mapper", + "saml-role-list-mapper", + "oidc-sha256-pairwise-sub-mapper", + "oidc-usermodel-attribute-mapper", + "saml-user-property-mapper", + "oidc-full-name-mapper", + "saml-user-attribute-mapper", + "oidc-usermodel-property-mapper" + ] + } + }, + { + "id": "03678af3-eeec-4f38-a986-cc2ccdcab37c", + "name": "Allowed Client Scopes", + "providerId": "allowed-client-templates", + "subType": "authenticated", + "subComponents": {}, + "config": { + "allow-default-scopes": ["true"] + } + }, + { + "id": "41063432-8717-47f9-bab8-b8a9e4c62322", + "name": "Allowed Client Scopes", + "providerId": "allowed-client-templates", + "subType": "anonymous", + "subComponents": {}, + "config": { + "allow-default-scopes": ["true"] + } + }, + { + "id": "85e7c066-bcf4-4fdf-ac81-0e9626701884", + "name": "Trusted Hosts", + "providerId": "trusted-hosts", + "subType": "anonymous", + "subComponents": {}, + "config": { + "host-sending-registration-request-must-match": ["true"], + "client-uris-must-match": ["true"] + } + }, + { + "id": "44d0b688-4f7f-4475-b62f-c5733454129d", + "name": "Full Scope Disabled", + "providerId": "scope", + "subType": "anonymous", + "subComponents": {}, + "config": {} + }, + { + "id": "80f2b705-a7f0-4e56-94b6-f150992b9c78", + "name": "Max Clients Limit", + "providerId": "max-clients", + "subType": "anonymous", + "subComponents": {}, + "config": { + "max-clients": ["200"] + } + } + ], + "org.keycloak.keys.KeyProvider": [ + { + "id": "4f57a139-24eb-4b6f-9d9a-ace7c2565c92", + "name": "aes-generated", + "providerId": "aes-generated", + "subComponents": {}, + "config": { + "priority": ["100"] + } + }, + { + "id": "7b70a240-9ab5-4f88-bee2-52cb7cb44823", + "name": "hmac-generated", + "providerId": "hmac-generated", + "subComponents": {}, + "config": { + "priority": ["100"], + "algorithm": ["HS256"] + } + }, + { + "id": "2d911441-12b7-487e-9063-494de95028bc", + "name": "rsa-generated", + "providerId": "rsa-generated", + "subComponents": {}, + "config": { + "priority": ["100"] + } + } + ] + }, + "internationalizationEnabled": false, + "supportedLocales": [], + "authenticationFlows": [ + { + "id": "0184ff58-7984-4821-86f7-598430d9084e", + "alias": "Account verification options", + "description": "Method with which to verity the existing account", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "idp-email-verification", + "requirement": "ALTERNATIVE", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "requirement": "ALTERNATIVE", + "priority": 20, + "flowAlias": "Verify Existing Account by Re-authentication", + "userSetupAllowed": false, + "autheticatorFlow": true + } + ] + }, + { + "id": "20d5739d-5321-4a38-b94c-be975f8d98b9", + "alias": "Authentication Options", + "description": "Authentication options.", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "basic-auth", + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "basic-auth-otp", + "requirement": "DISABLED", + "priority": 20, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "auth-spnego", + "requirement": "DISABLED", + "priority": 30, + "userSetupAllowed": false, + "autheticatorFlow": false + } + ] + }, + { + "id": "03e731f1-2678-4ca8-9a65-26cfdc7199ed", + "alias": "Browser - Conditional OTP", + "description": "Flow to determine if the OTP is required for the authentication", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "conditional-user-configured", + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "auth-otp-form", + "requirement": "REQUIRED", + "priority": 20, + "userSetupAllowed": false, + "autheticatorFlow": false + } + ] + }, + { + "id": "e817fbc7-a8bd-4e6a-8833-a62e7e44ae00", + "alias": "Direct Grant - Conditional OTP", + "description": "Flow to determine if the OTP is required for the authentication", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "conditional-user-configured", + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "direct-grant-validate-otp", + "requirement": "REQUIRED", + "priority": 20, + "userSetupAllowed": false, + "autheticatorFlow": false + } + ] + }, + { + "id": "337a3d15-0441-4cf7-acf4-8c71232d0ccc", + "alias": "First broker login - Conditional OTP", + "description": "Flow to determine if the OTP is required for the authentication", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "conditional-user-configured", + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "auth-otp-form", + "requirement": "REQUIRED", + "priority": 20, + "userSetupAllowed": false, + "autheticatorFlow": false + } + ] + }, + { + "id": "3de8f1d8-f0bd-4f0f-89af-18835e8312a0", + "alias": "Handle Existing Account", + "description": "Handle what to do if there is existing account with same email/username like authenticated identity provider", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "idp-confirm-link", + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "requirement": "REQUIRED", + "priority": 20, + "flowAlias": "Account verification options", + "userSetupAllowed": false, + "autheticatorFlow": true + } + ] + }, + { + "id": "92176992-8993-4f58-93ee-6e63749dfbfd", + "alias": "Reset - Conditional OTP", + "description": "Flow to determine if the OTP should be reset or not. Set to REQUIRED to force.", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "conditional-user-configured", + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "reset-otp", + "requirement": "REQUIRED", + "priority": 20, + "userSetupAllowed": false, + "autheticatorFlow": false + } + ] + }, + { + "id": "87e82fdd-76ba-47e5-8102-af2c88d2f2fb", + "alias": "User creation or linking", + "description": "Flow for the existing/non-existing user alternatives", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticatorConfig": "create unique user config", + "authenticator": "idp-create-user-if-unique", + "requirement": "ALTERNATIVE", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "requirement": "ALTERNATIVE", + "priority": 20, + "flowAlias": "Handle Existing Account", + "userSetupAllowed": false, + "autheticatorFlow": true + } + ] + }, + { + "id": "2798ef9e-55b6-40bf-8d3e-1e9bbef72359", + "alias": "Verify Existing Account by Re-authentication", + "description": "Reauthentication of existing account", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "idp-username-password-form", + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "requirement": "CONDITIONAL", + "priority": 20, + "flowAlias": "First broker login - Conditional OTP", + "userSetupAllowed": false, + "autheticatorFlow": true + } + ] + }, + { + "id": "d914e3f1-57ae-49a1-a80a-faa7c99ec389", + "alias": "browser", + "description": "browser based authentication", + "providerId": "basic-flow", + "topLevel": true, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "auth-cookie", + "requirement": "ALTERNATIVE", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "auth-spnego", + "requirement": "DISABLED", + "priority": 20, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "identity-provider-redirector", + "requirement": "ALTERNATIVE", + "priority": 25, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "requirement": "ALTERNATIVE", + "priority": 30, + "flowAlias": "forms", + "userSetupAllowed": false, + "autheticatorFlow": true + } + ] + }, + { + "id": "a9cc0bc8-8277-45a1-8199-c313667637db", + "alias": "clients", + "description": "Base authentication for clients", + "providerId": "client-flow", + "topLevel": true, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "client-secret", + "requirement": "ALTERNATIVE", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "client-jwt", + "requirement": "ALTERNATIVE", + "priority": 20, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "client-secret-jwt", + "requirement": "ALTERNATIVE", + "priority": 30, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "client-x509", + "requirement": "ALTERNATIVE", + "priority": 40, + "userSetupAllowed": false, + "autheticatorFlow": false + } + ] + }, + { + "id": "93632cc9-6a8c-4acb-afa2-a21df781aa49", + "alias": "direct grant", + "description": "OpenID Connect Resource Owner Grant", + "providerId": "basic-flow", + "topLevel": true, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "direct-grant-validate-username", + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "direct-grant-validate-password", + "requirement": "REQUIRED", + "priority": 20, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "requirement": "CONDITIONAL", + "priority": 30, + "flowAlias": "Direct Grant - Conditional OTP", + "userSetupAllowed": false, + "autheticatorFlow": true + } + ] + }, + { + "id": "48bee5d3-397c-488b-94a7-d29ff24762c0", + "alias": "docker auth", + "description": "Used by Docker clients to authenticate against the IDP", + "providerId": "basic-flow", + "topLevel": true, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "docker-http-basic-authenticator", + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + } + ] + }, + { + "id": "d4596dec-91c4-4a65-8113-336ad6b47028", + "alias": "first broker login", + "description": "Actions taken after first broker login with identity provider account, which is not yet linked to any Keycloak account", + "providerId": "basic-flow", + "topLevel": true, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticatorConfig": "review profile config", + "authenticator": "idp-review-profile", + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "requirement": "REQUIRED", + "priority": 20, + "flowAlias": "User creation or linking", + "userSetupAllowed": false, + "autheticatorFlow": true + } + ] + }, + { + "id": "97e3cb3b-310d-445f-8c9a-ceabf1063724", + "alias": "forms", + "description": "Username, password, otp and other auth forms.", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "auth-username-password-form", + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "requirement": "CONDITIONAL", + "priority": 20, + "flowAlias": "Browser - Conditional OTP", + "userSetupAllowed": false, + "autheticatorFlow": true + } + ] + }, + { + "id": "cbc568bb-79e4-4808-b486-f9eab24cc576", + "alias": "http challenge", + "description": "An authentication flow based on challenge-response HTTP Authentication Schemes", + "providerId": "basic-flow", + "topLevel": true, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "no-cookie-redirect", + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "requirement": "REQUIRED", + "priority": 20, + "flowAlias": "Authentication Options", + "userSetupAllowed": false, + "autheticatorFlow": true + } + ] + }, + { + "id": "c1356b41-5b0e-4eff-946c-331473144b1b", + "alias": "registration", + "description": "registration flow", + "providerId": "basic-flow", + "topLevel": true, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "registration-page-form", + "requirement": "REQUIRED", + "priority": 10, + "flowAlias": "registration form", + "userSetupAllowed": false, + "autheticatorFlow": true + } + ] + }, + { + "id": "4fa24705-10dc-47e1-a163-0bfc9b317645", + "alias": "registration form", + "description": "registration form", + "providerId": "form-flow", + "topLevel": false, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "registration-user-creation", + "requirement": "REQUIRED", + "priority": 20, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "registration-profile-action", + "requirement": "REQUIRED", + "priority": 40, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "registration-password-action", + "requirement": "REQUIRED", + "priority": 50, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "registration-recaptcha-action", + "requirement": "DISABLED", + "priority": 60, + "userSetupAllowed": false, + "autheticatorFlow": false + } + ] + }, + { + "id": "8e462f4c-da9f-4aa1-b337-139a7591c504", + "alias": "reset credentials", + "description": "Reset credentials for a user if they forgot their password or something", + "providerId": "basic-flow", + "topLevel": true, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "reset-credentials-choose-user", + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "reset-credential-email", + "requirement": "REQUIRED", + "priority": 20, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "authenticator": "reset-password", + "requirement": "REQUIRED", + "priority": 30, + "userSetupAllowed": false, + "autheticatorFlow": false + }, + { + "requirement": "CONDITIONAL", + "priority": 40, + "flowAlias": "Reset - Conditional OTP", + "userSetupAllowed": false, + "autheticatorFlow": true + } + ] + }, + { + "id": "c6a772cb-7a8c-45f6-9cc8-7f065a5dd0ff", + "alias": "saml ecp", + "description": "SAML ECP Profile Authentication Flow", + "providerId": "basic-flow", + "topLevel": true, + "builtIn": true, + "authenticationExecutions": [ + { + "authenticator": "http-basic-authenticator", + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false, + "autheticatorFlow": false + } + ] + } + ], + "authenticatorConfig": [ + { + "id": "b6348bec-eeb1-468b-813e-de7461b41a0b", + "alias": "create unique user config", + "config": { + "require.password.update.after.registration": "false" + } + }, + { + "id": "252fcbb0-d67e-4121-8445-bac8132989ca", + "alias": "review profile config", + "config": { + "update.profile.on.first.login": "missing" + } + } + ], + "requiredActions": [ + { + "alias": "CONFIGURE_TOTP", + "name": "Configure OTP", + "providerId": "CONFIGURE_TOTP", + "enabled": true, + "defaultAction": false, + "priority": 10, + "config": {} + }, + { + "alias": "terms_and_conditions", + "name": "Terms and Conditions", + "providerId": "terms_and_conditions", + "enabled": false, + "defaultAction": false, + "priority": 20, + "config": {} + }, + { + "alias": "UPDATE_PASSWORD", + "name": "Update Password", + "providerId": "UPDATE_PASSWORD", + "enabled": true, + "defaultAction": false, + "priority": 30, + "config": {} + }, + { + "alias": "UPDATE_PROFILE", + "name": "Update Profile", + "providerId": "UPDATE_PROFILE", + "enabled": true, + "defaultAction": false, + "priority": 40, + "config": {} + }, + { + "alias": "VERIFY_EMAIL", + "name": "Verify Email", + "providerId": "VERIFY_EMAIL", + "enabled": true, + "defaultAction": false, + "priority": 50, + "config": {} + }, + { + "alias": "delete_account", + "name": "Delete Account", + "providerId": "delete_account", + "enabled": false, + "defaultAction": false, + "priority": 60, + "config": {} + }, + { + "alias": "update_user_locale", + "name": "Update User Locale", + "providerId": "update_user_locale", + "enabled": true, + "defaultAction": false, + "priority": 1000, + "config": {} + } + ], + "browserFlow": "browser", + "registrationFlow": "registration", + "directGrantFlow": "direct grant", + "resetCredentialsFlow": "reset credentials", + "clientAuthenticationFlow": "clients", + "dockerAuthenticationFlow": "docker auth", + "attributes": { + "clientOfflineSessionMaxLifespan": "0", + "clientSessionIdleTimeout": "0", + "clientSessionMaxLifespan": "0", + "clientOfflineSessionIdleTimeout": "0" + }, + "keycloakVersion": "12.0.1", + "userManagedAccessAllowed": false +} diff --git a/node_modules/.yarn-integrity b/node_modules/.yarn-integrity new file mode 100644 index 0000000000..74953049ef --- /dev/null +++ b/node_modules/.yarn-integrity @@ -0,0 +1,12 @@ +{ + "systemParams": "linux-x64-83", + "modulesFolders": [ + "node_modules" + ], + "flags": [], + "linkedModules": [], + "topLevelPatterns": [], + "lockfileEntries": {}, + "files": [], + "artifacts": {} +} \ No newline at end of file diff --git a/openshift/zap/zap-scan.conf b/openshift/zap/zap-scan.conf new file mode 100644 index 0000000000..6a7acbfdd1 --- /dev/null +++ b/openshift/zap/zap-scan.conf @@ -0,0 +1,57 @@ +# zap-baseline rule configuration file +# Change WARN to IGNORE to ignore rule or FAIL to fail if rule matches +# Only the rule identifiers are used - the names are just for info +# You can add your own messages to each rule by appending them after a tab on each line. +* OUTOFSCOPE .*\.svg +* OUTOFSCOPE .*\.png +10010 WARN (Cookie No HttpOnly Flag) +10011 WARN (Cookie Without Secure Flag) +10015 WARN (Incomplete or No Cache-control and Pragma HTTP Header Set) +10016 IGNORE (Web Browser XSS Protection Not Enabled) +10017 WARN (Cross-Domain JavaScript Source File Inclusion) +10019 WARN (Content-Type Header Missing) +10020 WARN (X-Frame-Options Header Scanner) +10021 IGNORE (X-Content-Type-Options Header Missing) +10023 WARN (Information Disclosure - Debug Error Messages) +10024 WARN (Information Disclosure - Sensitive Information in URL) +10025 WARN (Information Disclosure - Sensitive Information in HTTP Referrer Header) +10026 WARN (HTTP Parameter Override) +10027 WARN (Information Disclosure - Suspicious Comments) +10028 WARN (Open Redirect) +10029 WARN (Cookie Poisoning) +10030 WARN (User Controllable Charset) +10031 WARN (User Controllable HTML Element Attribute (Potential XSS)) +10032 WARN (Viewstate Scanner) +10033 WARN (Directory Browsing) +10034 WARN (Heartbleed OpenSSL Vulnerability (Indicative)) +10035 WARN (Strict-Transport-Security Header Scanner) +10036 WARN (HTTP Server Response Header Scanner) +10037 WARN (Server Leaks Information via "X-Powered-By" HTTP Response Header Field(s)) +10038 WARN (Content Security Policy (CSP) Header Not Set) +10039 WARN (X-Backend-Server Header Information Leak) +10040 WARN (Secure Pages Include Mixed Content) +10041 WARN (HTTP to HTTPS Insecure Transition in Form Post) +10042 WARN (HTTPS to HTTP Insecure Transition in Form Post) +10043 WARN (User Controllable JavaScript Event (XSS)) +10044 WARN (Big Redirect Detected (Potential Sensitive Information Leak)) +10050 WARN (Retrieved from Cache) +10052 WARN (X-ChromeLogger-Data (XCOLD) Header Information Leak) +10054 WARN (Cookie Without SameSite Attribute) +10055 WARN (CSP Scanner) +10056 WARN (X-Debug-Token Information Leak) +10057 WARN (Username Hash Found) +10061 WARN (X-AspNet-Version Response Header Scanner) +10062 WARN (PII Scanner) +10096 WARN (Timestamp Disclosure) +10097 WARN (Hash Disclosure) +10098 WARN (Cross-Domain Misconfiguration) +10105 WARN (Weak Authentication Method) +10108 WARN (Reverse Tabnabbing) +10202 WARN (Absence of Anti-CSRF Tokens) +2 WARN (Private IP Disclosure) +3 WARN (Session ID in URL Rewrite) +50001 WARN (Script Passive Scan Rules) +90001 WARN (Insecure JSF ViewState) +90011 WARN (Charset Mismatch) +90022 WARN (Application Error Disclosure) +90033 WARN (Loosely Scoped Cookie) diff --git a/src/backend/.dockerignore b/src/backend/.dockerignore new file mode 100644 index 0000000000..f4ceea7856 --- /dev/null +++ b/src/backend/.dockerignore @@ -0,0 +1 @@ +**/target/ diff --git a/src/backend/.gitignore b/src/backend/.gitignore index a2a3040aa8..501e312805 100644 --- a/src/backend/.gitignore +++ b/src/backend/.gitignore @@ -29,3 +29,6 @@ build/ ### VS Code ### .vscode/ + +*.versionsBackup +/libs/spring-boot-starters/ diff --git a/src/backend/Dockerfile b/src/backend/Dockerfile.efiling-api similarity index 54% rename from src/backend/Dockerfile rename to src/backend/Dockerfile.efiling-api index b9a697b0c8..d5f82319b9 100644 --- a/src/backend/Dockerfile +++ b/src/backend/Dockerfile.efiling-api @@ -1,32 +1,50 @@ ############################################################################################# ### Stage where Docker is building spring boot app using maven ### ############################################################################################# -FROM maven:3.6.3-jdk-8 as build +FROM maven:3.8.3-openjdk-17 as build ARG MVN_PROFILE -ARG SERVICE_NAME +ARG SERVICE_NAME=efiling-api +ARG SKIP_TESTS=false +ARG STARTERS_V ENV SERVICE_NAME=${SERVICE_NAME} +ENV STARTERS_V=${STARTERS_V} -COPY . . +#Temporary removal. +#RUN mkdir /root/.ssh && \ +# chmod 0700 /root/.ssh && \ +# ssh-keyscan -t rsa localhost >> ~/.ssh/known_hosts && \ +# apt-get update && \ +# apt-get -y install git -RUN mvn -B clean install \ - -P libs +WORKDIR /libs -WORKDIR ${SERVICE_NAME} +RUN git clone https://github.com/bcgov/spring-boot-starters.git -RUN mvn -B clean package \ - -P ${MVN_PROFILE} +WORKDIR /libs/spring-boot-starters + +RUN git checkout $STARTERS_V && \ + mvn install -P all -f src/pom.xml + +WORKDIR / + +COPY . . + +RUN mvn -B clean install \ + -P ${MVN_PROFILE} \ + -Dmaven.test.skip=${SKIP_TESTS} -############################################################################################# ############################################################################################# ### Stage where Docker is running a java process to run a service built in previous stage ### ############################################################################################# -FROM openjdk:8-jdk-slim +FROM eclipse-temurin:17-jre-alpine + +RUN apk update && apk add --upgrade --no-cache libexpat # fix CVE-2024-8176 # ARG MVN_PROFILES -ARG SERVICE_NAME +ARG SERVICE_NAME=efiling-api COPY --from=build ./${SERVICE_NAME}/target/${SERVICE_NAME}-*.jar /app/service.jar diff --git a/src/backend/README.md b/src/backend/README.md index 12a0866f55..e69fa3733b 100644 --- a/src/backend/README.md +++ b/src/backend/README.md @@ -25,3 +25,15 @@ mvn clean install -P libs ``` mvn clean verify -P all ``` + +### Update Version + +Run + +``` +mvn -f src/backend/pom.xml versions:set -DartifactId=* -DgroupId=* +``` + +## caching + +Currently lookups are cached using redis. In the event of a code table change redis should be restarted. Check the api for activity beore doing so. \ No newline at end of file diff --git a/src/backend/efiling-api/README.md b/src/backend/efiling-api/README.md index a8d427397e..f0615aafe1 100644 --- a/src/backend/efiling-api/README.md +++ b/src/backend/efiling-api/README.md @@ -13,34 +13,74 @@ mvn install -P openshift ### Demo -This profile self isolate the application from any third party dependencies +This profile self isolate the application from any third individual dependencies ```bash mvn install -P demo ``` +### Dev + +This profile is required to pull the soap services + +```bash +mvn install -P efiling-api +``` + ## Configuration You should use environment variables to configure the jag efiling api -| Environment Variable | Type | Description | Notes | -| --- | --- | --- | --- | -| SERVER_PORT | Integer | web application server port | defaulted to `8080` | -| DEMO_MODE | Boolean | A flag to turn on/off demo mode | defaulted to `false` | -| REDIS_HOST | String | Redis storage host | defaulted to `localhost` | -| REDIS_PORT | Integer | Redis storage port | defaulted to `6379` | -| REDIS_PASSWORD | String | Redis storage password | Defaulted to `admin` | -| NAVIGATION_BASE_URL | String | The base path of the secure file upload | not set by default | -| CACHE_TTL | Integer | The default time to live for the cache in ms | Defaulted to `600000` (10 min) | -| CSO_ACCOUNTFACADE_USERNAME | String | CSO account facade username | not set by default | -| CSO_ACCOUNTFACADE_PASSWORD | String | CSO account facade password | not set by default | -| CSO_ACCOUNTFACADE_URI | String | CSO account facade URI | not set by default | -| CSO_ROLEREGISTRY_USERNAME | String | role registry username | not set by default | -| CSO_ROLEREGISTRY_PASSWORD | String | role registry password | not set by default | -| CSO_ROLEREGISTRY_URI | String | role registry URI | not set by default | -| BCEID_LOOKUP_USERNAME | String | bceid lookup username | not set by default | -| BCEID_LOOKUP_PASSWORD | String | bceid lookup password | not set by default | -| BCEID_LOOKUP_URI | String | bceid lookup URI | not set by default | +| Environment Variable | Type | Description | Notes | +| ------------------------------- | ------- | -------------------------------------------- | ------------------------------ | +| SERVER_PORT | Integer | web application server port | defaulted to `8080` | +| DEMO_MODE | Boolean | A flag to turn on/off demo mode | defaulted to `false` | +| REDIS_HOST | String | Redis storage host | defaulted to `localhost` | +| REDIS_PORT | Integer | Redis storage port | defaulted to `6379` | +| REDIS_PASSWORD | String | Redis storage password | Defaulted to `admin` | +| NAVIGATION_BASE_URL | String | The base path of the secure file upload | not set by default | +| CSO_BASE_URL | String | The cso application base URL | not set by default | +| CACHE_TTL | Integer | The default time to live for the cache in ms | Defaulted to `600000` (10 min) | +| CSO_ACCOUNTFACADE_USERNAME | String | CSO account facade username | not set by default | +| CSO_ACCOUNTFACADE_PASSWORD | String | CSO account facade password | not set by default | +| CSO_ACCOUNTFACADE_URI | String | CSO account facade URI | not set by default | +| CSO_ROLEREGISTRY_USERNAME | String | role registry username | not set by default | +| CSO_ROLEREGISTRY_PASSWORD | String | role registry password | not set by default | +| CSO_ROLEREGISTRY_URI | String | role registry URI | not set by default | +| CSO_FILINGSTATSFACADE_USERNAME | String | status facade username | not set by default | +| CSO_FILINGSTATSFACADE_PASSWORD | String | status facade password | not set by default | +| CSO_FILINGSTATSFACADE_URI | String | status facade URI | not set by default | +| CSOWS_USERNAME | String | csows username | not set by default | +| CSOWS_PASSWORD | String | csows password | not set by default | +| CSOWS_URI | String | csows URI | not set by default | +| CSO_FILINGFACADE_USERNAME | String | filing facade username | not set by default | +| CSO_FILINGFACADE_PASSWORD | String | filing facade password | not set by default | +| CSO_FILINGFACADE_URI | String | filing facade URI | not set by default | +| CSO_SERVICEFACADE_USERNAME | String | service facade username | not set by default | +| CSO_SERVICEFACADE_PASSWORD | String | service facade password | not set by default | +| CSO_SERVICEFACADE_URI | String | service facade URI | not set by default | +| KEYCLOAK_AUTH_SERVER_URL | String | The keycloak auth server URL | not set by default | +| KEYCLOAK_REALM | String | The keycloak realm name | not set by default | +| KEYCLOAK_RESOURCE | String | The keycloak resource name | not set by default | +| KEYCLOAK_CREDENTIALS_SECRET | String | The keycloak Credentials Secrets | not set by default | +| BAMBORA_APIBASEPATH | String | API base path | not set by default | +| BAMBORA_APIPASSCODE | String | API passcode for bambora auth | not set by default | +| BAMBORA_MERCHANTID | String | merchant id for bambora auth | not set by default | +| MAIL_SEND_BASE_URL | String | API base path | not set by default | +| SFTP_HOST | String | sftp host | defaulted to `localhost` | +| SFTP_PORT | Integer | sftp port | defaulted to `22` | +| SFTP_USERNAME | String | sftp username | Defaulted to `admin` | +| SFTP_PASSWORD | String | sftp password | Defaulted to `admin` | +| SFTP_REMOTELOCATION | String | remote directory | not set by default | +| SFTP_KNOWNHOSTS | String | location of known hosts file | not set by default | +| SFTP_ALLOWUNKNOWN | Boolean | allow unkown hosts | not set by default | +| CEIS_BASE_PATH | String | Base path for ords | not set by default | +| CEIS_USERNAME | String | Basic auth username | not set by default | +| CEIS_PASSWORD | String | Basic auth password | not set by default | +| BCEID_SERVICE_URI | String | BCEID uri | not set by default | +| BCEID_SERVICE_USERNAME | String | BCEID username | not set by default | +| BCEID_SERVICE_PASSWORD | String | BCEID password | not set by default | +| BCEID_SERVICE_ONLINE_SERVICE_ID | String | BCEID online service id | not set by default | ## Backend Folder Structure diff --git a/src/backend/efiling-api/jag-efiling-api.yaml b/src/backend/efiling-api/jag-efiling-api.yaml index 41fcacdf2a..d5251bc33e 100644 --- a/src/backend/efiling-api/jag-efiling-api.yaml +++ b/src/backend/efiling-api/jag-efiling-api.yaml @@ -1,100 +1,854 @@ openapi: 3.0.0 info: - version: 0.3.0 + version: 0.7.0 title: jag-efiling-api description: Efiling api servers: - - url: 'http://localhost:8080' + - url: "http://localhost:8080" tags: + - name: clientEndpoints + description: Endpoints that are exposed to external client - name: submission description: Submission Api + - name: courts + description: Courts + - name: filingPackages + description: File Packages +security: + - bearerAuth: [] paths: - '/submission/generateUrl': + "/submission/documents": + post: + summary: Initial documents upload + operationId: UploadSubmissionDocuments + tags: + - submission + - clientEndpoints + parameters: + - $ref: "#/components/parameters/xTransactionId" + - $ref: "#/components/parameters/xUserId" + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + files: + type: array + items: + type: string + format: binary + responses: + "200": + description: File successfully received + content: + application/json: + schema: + $ref: "#/components/schemas/UploadSubmissionDocumentsResponse" + "/submission/{submissionId}": + parameters: + - $ref: "#/components/parameters/submissionId" + - $ref: "#/components/parameters/xTransactionId" + delete: + summary: Delete a submission by id + operationId: DeleteSubmission + tags: + - submission + responses: + "200": + description: submission deleted + "/submission/{submissionId}/documents": + post: + summary: Additional documents upload + operationId: UploadAdditionalSubmissionDocuments + tags: + - submission + parameters: + - $ref: "#/components/parameters/submissionId" + - $ref: "#/components/parameters/xTransactionId" + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + files: + type: array + items: + type: string + format: binary + responses: + "200": + description: File successfully received + content: + application/json: + schema: + $ref: "#/components/schemas/UploadSubmissionDocumentsResponse" + "404": + description: Submission not found + "/submission/{submissionId}/rushDocuments": + post: + summary: Rush documents upload + operationId: UploadRushDocuments + tags: + - submission + parameters: + - $ref: "#/components/parameters/submissionId" + - $ref: "#/components/parameters/xTransactionId" + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + files: + type: array + items: + type: string + format: binary + responses: + "200": + description: File successfully received + content: + application/json: + schema: + $ref: "#/components/schemas/UploadSubmissionDocumentsResponse" + "404": + description: Submission not found + "/submission/{submissionId}/update-documents": + post: + summary: Additional documents properties + operationId: UpdateDocumentProperties + tags: + - submission + parameters: + - $ref: "#/components/parameters/submissionId" + - $ref: "#/components/parameters/xTransactionId" + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateDocumentRequest" + responses: + "200": + description: Document properties updated + content: + application/json: + schema: + $ref: "#/components/schemas/UpdateDocumentResponse" + "404": + description: Submission not found + "/submission/{submissionId}/config": + parameters: + - $ref: "#/components/parameters/submissionId" + - $ref: "#/components/parameters/xTransactionId" + get: + summary: Get configuration for a given submission + operationId: GetSubmissionConfig + tags: + - submission + responses: + "200": + description: Config found + content: + application/json: + schema: + $ref: "#/components/schemas/GetSubmissionConfigResponse" + "404": + description: Config not found + "/submission/{submissionId}/generateUrl": post: summary: Generates a secure URL for e-filing submission operationId: GenerateUrl tags: - submission + - clientEndpoints parameters: - - in: header - name: X-Auth-UserId - schema: - type: string - format: uuid - required: true - description: Authenticated user id + - $ref: "#/components/parameters/xTransactionId" + - $ref: "#/components/parameters/xUserId" + - $ref: "#/components/parameters/submissionId" requestBody: description: requested parameters to generate a url required: true content: application/json: schema: - $ref: '#/components/schemas/GenerateUrlRequest' + $ref: "#/components/schemas/GenerateUrlRequest" responses: - '200': + "200": description: File successfully received content: application/json: schema: - $ref: '#/components/schemas/GenerateUrlResponse' - '403': + $ref: "#/components/schemas/GenerateUrlResponse" + "403": description: Request does not meet the required criteria content: application/json: schema: - $ref: '#/components/schemas/EfilingError' - '/submission/{id}': + $ref: "#/components/schemas/EfilingError" + "/submission/{submissionId}/submit": + post: + summary: Create service for payment processing + operationId: submit + tags: + - submission + parameters: + - $ref: "#/components/parameters/xTransactionId" + - $ref: "#/components/parameters/submissionId" + requestBody: + description: filing submit parameters + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/SubmitRequest" + responses: + "201": + description: Service created + content: + application/json: + schema: + $ref: "#/components/schemas/SubmitResponse" + "403": + description: Request does not meet the required criteria + content: + application/json: + schema: + $ref: "#/components/schemas/EfilingError" + "/submission/{submissionId}/filing-package": get: - summary: Get user detail for a given submission - operationId: GetSubmission + summary: Get filing package information + operationId: GetSubmissionFilingPackage tags: - submission parameters: - - name: id + - $ref: "#/components/parameters/xTransactionId" + - $ref: "#/components/parameters/submissionId" + responses: + "200": + description: Filing Package Information found + content: + application/json: + schema: + $ref: "#/components/schemas/SubmissionFilingPackage" + "404": + description: Filing Package Information not found + "/submission/{submissionId}/document/{filename}": + get: + summary: Get document by name + operationId: GetSubmissionDocument + tags: + - submission + parameters: + - $ref: "#/components/parameters/xTransactionId" + - $ref: "#/components/parameters/submissionId" + - name: filename in: path - description: A submission id + description: A document name required: true schema: type: string - format: uuid responses: - '200': - description: Config found + "200": + description: Filing Package Information found + content: + application/octet-stream: + schema: + type: string + format: binary + "404": + description: Document not found + "/submission/{submissionId}/rushProcessing": + post: + summary: add rush processing to package + operationId: PostRushProcessing + tags: + - submission + parameters: + - $ref: "#/components/parameters/xTransactionId" + - $ref: "#/components/parameters/submissionId" + requestBody: + description: filing submit parameters + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/Rush" + responses: + "201": + description: Rush created + "404": + description: Submission not found + "/csoAccount": + post: + summary: Create a CSO account + operationId: CreateAccount + description: In order to create an account, an item with type BCeID is required in the accounts field. + tags: + - account + parameters: + - $ref: "#/components/parameters/xTransactionId" + requestBody: + description: cso account details + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CreateCsoAccountRequest" + responses: + "201": + description: Account Created content: application/json: schema: - $ref: '#/components/schemas/GetSubmissionResponse' - '404': - description: Config not found + $ref: "#/components/schemas/CsoAccount" + get: + summary: Get user CSO account + operationId: GetCsoAccount + description: Get a user cso account. + tags: + - account + parameters: + - $ref: "#/components/parameters/xTransactionId" + responses: + "200": + description: A CSO Account + content: + application/json: + schema: + $ref: "#/components/schemas/CsoAccount" + "404": + description: Cso Account not found + put: + summary: Update CSO account internal client number + operationId: updateCsoAccount + tags: + - account + parameters: + - $ref: "#/components/parameters/xTransactionId" + requestBody: + description: update client details parameters + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/CsoAccountUpdateRequest" + responses: + "200": + description: Client updated + content: + application/json: + schema: + $ref: "#/components/schemas/CsoAccount" + "403": + description: Request does not meet the required criteria + content: + application/json: + schema: + $ref: "#/components/schemas/EfilingError" + "/bceidAccount": + get: + summary: Get a BCeID account + operationId: GetBceidAccount + description: Retrieve BCeID user account information + tags: + - account + parameters: + - $ref: "#/components/parameters/xTransactionId" + responses: + "200": + description: Account Created + content: + application/json: + schema: + $ref: "#/components/schemas/BceidAccount" + "404": + description: Account not found + "/documents/types": + get: + summary: Get document types + operationId: GetDocumentTypes + description: A list of document types + tags: + - lookup + - clientEndpoints + parameters: + - name: courtLevel + in: query + description: court level + required: true + schema: + $ref: "#/components/schemas/CourtLevel" + - name: courtClassification + in: query + description: court classification + required: true + schema: + $ref: "#/components/schemas/CourtClassification" + responses: + "200": + description: List of document types + content: + application/json: + schema: + $ref: "#/components/schemas/DocumentTypes" + "/countries": + get: + summary: Get countries + operationId: GetCountries + description: A list of countries + tags: + - lookup + responses: + "200": + description: List of countries + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/CountryCode" + "/courts": + get: + summary: Get court locations + operationId: GetCourtLocations + description: get court information by court name + tags: + - courts + parameters: + - name: courtLevel + in: query + description: court type filter + required: false + schema: + type: string + responses: + "200": + description: Information of a court + content: + application/json: + schema: + $ref: "#/components/schemas/CourtLocations" + "/payment/generate-update-card": + post: + summary: Update card on bambora + operationId: UpdateCreditCard + description: For expired credit card get url to update + tags: + - payment + parameters: + - $ref: "#/components/parameters/xTransactionId" + requestBody: + description: card update params + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/GenerateCardUrlRequest" + responses: + "200": + description: Card url generated + content: + application/json: + schema: + $ref: "#/components/schemas/GenerateCardUrlResponse" + "/filingpackages": + get: + summary: Get filing packages + operationId: GetFilingPackages + description: get filing packages from cso + tags: + - filingPackages + parameters: + - name: parentApplication + in: query + description: parent application + required: false + schema: + type: string + responses: + "200": + description: All filing package details + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/FilingPackage" + "/filingpackages/{packageIdentifier}": + get: + summary: Get filing package + operationId: GetFilingPackage + description: get filing package details from cso + tags: + - filingPackages + - clientEndpoints + parameters: + - $ref: "#/components/parameters/packageIdentifier" + responses: + "200": + description: All filing package details + content: + application/json: + schema: + $ref: "#/components/schemas/FilingPackage" + "/filingpackages/{packageIdentifier}/actionRequiredDetails": + get: + summary: Get details for documents that require action + operationId: GetActionRequiredDetails + description: get action required details from cso + tags: + - filingPackages + - clientEndpoints + parameters: + - $ref: "#/components/parameters/packageIdentifier" + responses: + "200": + description: All filing package details + content: + application/json: + schema: + $ref: "#/components/schemas/ActionRequiredDetails" + "404": + description: Package not found + "403": + description: Request does not meet the required criteria + content: + application/json: + schema: + $ref: "#/components/schemas/EfilingError" + "/filingpackages/{packageIdentifier}/submissionSheet": + get: + summary: Get submission sheet for package + operationId: GetSubmissionSheet + description: get submission sheet file from cso + tags: + - filingPackages + parameters: + - $ref: "#/components/parameters/packageIdentifier" + responses: + "200": + description: File was returned + content: + application/pdf: + schema: + type: string + format: binary + "404": + description: file not found + "/filingpackages/{packageIdentifier}/paymentReceipt": + get: + summary: Get submission payment receipt + operationId: GetPaymentReceipt + description: get payment receipt file from cso + tags: + - filingPackages + parameters: + - $ref: "#/components/parameters/packageIdentifier" + responses: + "200": + description: File was returned + content: + application/pdf: + schema: + type: string + format: binary + "404": + description: file not found + "/filingpackages/{packageIdentifier}/registryNotice": + get: + summary: Get submission registry notice + operationId: GetRegistryNotice + description: get registry notice file from cso + tags: + - filingPackages + - clientEndpoints + parameters: + - $ref: "#/components/parameters/packageIdentifier" + responses: + "200": + description: File was returned + content: + application/pdf: + schema: + type: string + format: binary + "404": + description: file not found + "/filingpackages/{packageIdentifier}/document/{documentIdentifier}": + get: + summary: Get submitted document + operationId: GetSubmittedDocument + description: get submitted document + tags: + - filingPackages + parameters: + - $ref: "#/components/parameters/packageIdentifier" + - name: documentIdentifier + in: path + description: document identifier + required: true + schema: + type: number + format: int + responses: + "200": + description: File was returned + content: + application/pdf: + schema: + type: string + format: binary + "404": + description: file not found + delete: + summary: delete(withdraw) submitted document + operationId: DeleteSubmittedDocument + description: Delete submitted document + tags: + - filingPackages + parameters: + - $ref: "#/components/parameters/packageIdentifier" + - name: documentIdentifier + in: path + description: document identifier + required: true + schema: + type: string + responses: + "200": + description: Document was deleted + "/filingpackages/{packageIdentifier}/rushDocument/{fileName}": + get: + summary: Get rush document + operationId: GetRushDocument + description: get rush document + tags: + - filingPackages + parameters: + - $ref: "#/components/parameters/packageIdentifier" + - name: fileName + in: path + description: document file name + required: true + schema: + type: string + responses: + "200": + description: File was returned + content: + application/pdf: + schema: + type: string + format: binary + "404": + description: file not found + "/filingpackages/{packageIdentifier}/parentDetails": + get: + summary: Get rush document + operationId: GetParentDetails + description: get parent app details for package + tags: + - filingPackages + parameters: + - $ref: "#/components/parameters/packageIdentifier" + responses: + "200": + description: parent app details + content: + application/json: + schema: + $ref: "#/components/schemas/ParentAppDetails" + "404": + description: Package not found components: + securitySchemes: + bearerAuth: # arbitrary name for the security scheme + type: http + scheme: bearer + bearerFormat: JWT + parameters: + xTransactionId: + name: X-Transaction-Id + in: header + schema: + type: string + format: uuid + required: true + description: A unique Transaction Id generated by FilingHub clients + xUserId: + name: X-User-Id + in: header + schema: + type: string + format: string + required: true + description: A unique BCeID universal id passed to initial calls + submissionId: + name: submissionId + in: path + description: A submission id + required: true + schema: + type: string + format: uuid + packageIdentifier: + name: packageIdentifier + in: path + description: package identifier + required: true + schema: + type: number schemas: - Account: + BceidAccount: type: object - description: represents a user account + description: BCeID account details properties: + firstName: + type: string + lastName: + type: string + middleName: + type: string + CourtClassification: + type: string + enum: [B, C, D, E, F, H, L, M, N, O, P, S, V] + description: > + court classification: + * `B` - Bankruptcy + * `C` - Small Claims + * `D` - Divorce + * `E` - Family Law Proceedings + * `F` - Family + * `H` - Foreclosure + * `L` - Enforcement/Legislated Statute + * `M` - Motor Vehicle Accidents + * `N` - Adoption + * `O` - Appeal Civil + * `P` - Probate + * `S` - Supreme Civil (General) + * `V` - Caveat + CourtLevel: + type: string + enum: [A, P, S] + description: > + court level: + * `A` - Appeal + * `P` - Provincial + * `S` - Supreme + InitialDocument: + type: object + description: Submission Metadata used to describe the submission that will be e-filled + required: + - type + - name + - isAmendment + - isSupremeCourtScheduling + - data + - md5 + properties: + name: + type: string + description: the name of the document type: type: string - enum: [BCEID, CSO] - description: the account type + description: cso document type + isAmendment: + type: boolean + description: is the document an amendment to another + isSupremeCourtScheduling: + type: boolean + description: supreme court scheduling required + data: + type: object + description: store additional details + documentId: + type: string + description: identifier of document from parent application + md5: + type: string + description: Computed hash value of the document content, it is used as a checksum to validate the document integrity. + actionDocument: + $ref: "#/components/schemas/ActionDocument" + Document: + required: + - identifier + - description + - status + - paymentProcessed + - filingDate + type: object + description: A Efiling Document + properties: identifier: type: string - description: the account identifier + description: document identifier + filingDate: + type: string + description: date of document filing + description: + type: string + description: document description + paymentProcessed: + type: boolean + description: Has the payment been processed + rushRequired: + type: boolean + description: Does the document require rush + documentId: + type: string + description: identifier of document from parent application + documentProperties: + $ref: "#/components/schemas/DocumentProperties" + status: + $ref: "#/components/schemas/Status" DocumentProperties: - type: object - description: Submission Metadata used to describe the submission that will be e-filled required: + - name - type - - subType - - documentAccess + description: common document properties. properties: + name: + type: string + description: the name of the document type: type: string - description: the submission type - subType: + description: Court Service Online document type + isAmendment: + type: boolean + description: is the document an amendment to another + isSupremeCourtScheduling: + type: boolean + description: supreme court scheduling required + SubmissionDocument: + required: + - description + - statutoryFeeAmount + type: object + description: A Efiling Document + allOf: + - $ref: "#/components/schemas/InitialDocument" + properties: + documentProperties: + $ref: "#/components/schemas/DocumentProperties" + description: + type: string + description: the description of the document + statutoryFeeAmount: + type: number + description: statutory fee amount + mimeType: type: string - description: the submission sub type - submissionAccess: - $ref: '#/components/schemas/EndpointAccess' + description: File mime type + status: + $ref: "#/components/schemas/Status" + paymentProcessed: + type: boolean + description: Has the payment been processed + rushRequired: + type: boolean + description: Does the document require rush EfilingError: required: - error @@ -104,29 +858,24 @@ components: type: string message: type: string - EndpointAccess: - type: object - description: Represent an http endpoint - properties: - url: - type: string - verb: - type: string - enum: [GET, POST] - headers: - type: object - additionalProperties: + details: + type: array + items: type: string GenerateUrlRequest: description: details about the required transaction required: - - navigation - - documentProperties + - clientApplication + - filingPackage + - navigationUrls properties: - documentProperties: - $ref: '#/components/schemas/DocumentProperties' - navigation: - $ref: '#/components/schemas/Navigation' + clientAppName: + type: string + description: Name of the application to be displayed + filingPackage: + $ref: "#/components/schemas/InitialPackage" + navigationUrls: + $ref: "#/components/schemas/NavigationUrls" GenerateUrlResponse: description: A temporary url for uploading submission properties: @@ -135,37 +884,489 @@ components: format: int64 efilingUrl: type: string - GetSubmissionResponse: + GetSubmissionConfigResponse: type: object required: - - userDetails - navigation + - clientAppName + - csoBaseUrl properties: - userDetails: - $ref: '#/components/schemas/UserDetails' - navigation: - $ref: '#/components/schemas/Navigation' - Navigation: + navigationUrls: + $ref: "#/components/schemas/NavigationUrls" + clientAppName: + type: string + description: the client app name + csoBaseUrl: + type: string + description: the CSO base Url + NavigationUrls: required: - success - error - cancel properties: success: - $ref: '#/components/schemas/Redirect' + type: string + description: where user should be redirected on success error: - $ref: '#/components/schemas/Redirect' + type: string + description: where user should be redirected on error cancel: - $ref: '#/components/schemas/Redirect' - Redirect: + type: string + description: where user should be redirected on cancel + InitialPackage: + type: object + description: A filing package can contain one or multiple documents that have or are being submitted electronically for new or existing court file. + required: + - documents + - court + properties: + packageNumber: + type: number + description: Identifer of package that is being modified + court: + $ref: "#/components/schemas/CourtBase" + documents: + type: array + items: + $ref: "#/components/schemas/InitialDocument" + parties: + type: array + items: + $ref: "#/components/schemas/Individual" + organizationParties: + type: array + items: + $ref: "#/components/schemas/Organization" + FilingPackage: + type: object + description: A filing package can contain one or multiple documents that have or are being submitted electronically for new or existing court file. + required: + - packageNumber + - documents + - submittedBy + - submittedDate + - links + - court + - hasRegistryNotice + properties: + packageNumber: + type: number + description: Submitted package number + status: + type: string + description: Calculated status of package + filingComments: + type: string + description: Filing comments + submittedBy: + $ref: "#/components/schemas/Account" + submittedDate: + type: string + description: Submitted date + court: + $ref: "#/components/schemas/Court" + documents: + type: array + items: + $ref: "#/components/schemas/Document" + parties: + type: array + items: + $ref: "#/components/schemas/Individual" + organizationParties: + type: array + items: + $ref: "#/components/schemas/Organization" + payments: + type: array + items: + $ref: "#/components/schemas/Payment" + links: + type: object + properties: + packageHistoryUrl: + type: string + description: a link to view all submitted package + hasRegistryNotice: + type: boolean + description: this filing package has a registry notice + rush: + $ref: "#/components/schemas/Rush" + SubmissionFilingPackage: + type: object + description: Submitted + required: + - submissionFeeAmount + - documents + properties: + submissionFeeAmount: + type: number + description: Package submission fee. + packageNumber: + type: number + description: Submitted package number + filingComments: + type: string + description: Filing comments + submittedBy: + $ref: "#/components/schemas/Account" + submittedDate: + type: string + description: Submitted date + court: + $ref: "#/components/schemas/Court" + documents: + type: array + items: + $ref: "#/components/schemas/SubmissionDocument" + parties: + type: array + items: + $ref: "#/components/schemas/Individual" + organizationParties: + type: array + items: + $ref: "#/components/schemas/Organization" + payments: + type: array + items: + $ref: "#/components/schemas/Payment" + rush: + $ref: "#/components/schemas/Rush" + CourtBase: + type: object + description: "Court related information" + required: + - location + - level + - courtClass + - division + properties: + location: + type: string + description: the court location + level: + type: string + description: the court level + courtClass: + type: string + description: the court class + division: + type: string + description: the court division + fileNumber: + type: string + description: the file number if case already exists + participatingClass: + type: string + Court: + type: object + description: "Court related information" + allOf: + - $ref: "#/components/schemas/CourtBase" + required: + - locationDescription + properties: + agencyId: + type: number + description: the agancy identifier + locationDescription: + type: string + description: the court location description + levelDescription: + type: string + description: the court location description + classDescription: + type: string + description: the court location description + Rush: + type: object + required: + - rushType + - firstName + - lastName + properties: + rushType: + type: string + description: > + rush type code + * `rule` - Application is made under rule 8-5 (1) SCR + * `court` - The court directed that the order be processeed on an urgent basis + * `pro` - This is based on a document type + * `other` - Other + enum: + [ + rule, + court, + pro, + other + ] + firstName: + type: string + description: first name of rush party + lastName: + type: string + description: last name of rush party + organization: + type: string + description: organization + phoneNumber: + type: string + description: phone number + email: + type: string + description: email address + courtDate: + type: string + description: court directed date + country: + type: string + description: country + countryCode: + type: string + description: code value for country + reason: + type: string + description: clear and detailed reason + status: + type: string + description: current status of the rush request + statusReason: + type: string + description: current registry reason text + supportingDocuments: + type: array + items: + $ref: "#/components/schemas/RushDocument" + RushDocument: + type: object + properties: + fileName: + type: string + description: file name of document + identifier: + type: string + description: guid of file + CsoAccount: + type: object + description: a CsoAccount required: - - url + - clientId + - accountId + - internalClientNumber + - fileRolePresent properties: - url: + clientId: type: string - UserDetails: - description: represents a user submitting a package + description: the user cso clientId + accountId: + type: string + description: the user cso accountId + internalClientNumber: + type: string + description: the user cso internal client number + fileRolePresent: + type: boolean + description: if the user as file role + DocumentType: type: object + required: + - type + - description + properties: + type: + type: string + description: code value + description: + type: string + description: human readable value + DocumentTypes: + type: array + items: + $ref: "#/components/schemas/DocumentType" + UploadSubmissionDocumentsResponse: + description: represents upload document response + type: object + required: + - submissionId + properties: + submissionId: + type: string + format: uuid + description: a unique identifier for the submission + received: + type: number + description: the number of document received + Party: + description: party related to filing package + required: + - roleType + properties: + roleType: + type: string + description: > + role type code + * `ABC` - Aboriginal Community + * `ADJ` - Adjudicator + * `ADP` - Adoptee + * `APL` - Appellant + * `APP` - Applicant + * `ANT` - Aunt + * `AUT` - Authority + * `BKP` - Bankrupt + * `BKS` - Bankrupts (Spouse) + * `CAV` - Caveator + * `CHD` - Child + * `COF` - Child on File + * `CIT` - Citator + * `CLA` - Claimant + * `CLA1` - Claimant 1 + * `CLA2` - Claimant 2 + * `CLI` - Client + * `CI` - Court Issued + * `CRD` - Creditor + * `DBT` - Debtor + * `DEC` - Deceased + * `DEF` - Defendant + * `DEO` - Defendant by Counterclaim + * `DIS` - Disputant + * `FTH` - Father + * `FNA` - First Nation + * `GRF` - Grandfather + * `GRM` - Grandmother + * `GUA` - Guardian + * `HSB` - Husband - Divorce + * `INB` - Indian Band + * `INC` - Indigenous Community + * `ITV` - Intervener + * `MOT` - Mother + * `NIS` - Nisga'a Lisims Government + * `OPAR` - Other Party + * `PAR` - Party + * `PAR1` - Party 1 + * `PA1` - Party 1 Joint Divorce Form127A + * `PAR2` - Party 2 + * `PA2` - Party 2 Joint Divorce Form127A + * `PAR3` - Party 3 + * `PAR4` - Party 4 + * `PAR5` - Party 5 + * `PET` - Petitioner + * `PLA` - Plaintiff + * `RES` - Respondent + * `REO` - Respondent by way of Counterclaim + * `SOL` - Solicitor + * `SP1` - Spouse 1- Divorce + * `SP2` - Spouse 2 - Divorce + * `SFH` - Step-Father + * `SMH` - Step-Mother + * `TST` - Testator + * `TSX` - Testatrix + * `THR` - Third Party + * `TFN` - Treaty First Nation + * `TRU` - Trustee + * `UNC` - Uncle + * `WIF` - Wife - Divorce + * `WIT` - Witness + enum: + [ + ABC, + ADJ, + ADP, + APL, + APP, + ANT, + AUT, + BKP, + BKS, + CAV, + CHD, + COF, + CIT, + CLA, + CLA1, + CLA2, + CLI, + CI, + CRD, + DBT, + DEC, + DEF, + DEO, + DIS, + FTH, + FNA, + GRF, + GRM, + GUA, + HSB, + INB, + INC, + ITV, + MOT, + NIS, + OPAR, + PAR, + PAR1, + PA1, + PAR2, + PA2, + PAR3, + PAR4, + PAR5, + PET, + PLA, + RES, + REO, + SOL, + SP1, + SP2, + SFH, + SMH, + TST, + TSX, + THR, + TFN, + TRU, + UNC, + WIF, + WIT, + ] + roleDescription: + type: string + description: description of role + partyDescription: + type: string + description: description of party + Individual: + description: Individual party type + allOf: + - $ref: "#/components/schemas/Party" + required: + - firstName + - lastName + properties: + firstName: + type: string + description: first name + middleName: + type: string + description: middle name + lastName: + type: string + description: last name + Organization: + description: Organization party type + allOf: + - $ref: "#/components/schemas/Party" + required: + - name + properties: + name: + type: string + description: organization name + CreateCsoAccountRequest: + description: represents a request to create a user required: - firstName - lastName @@ -184,7 +1385,238 @@ components: email: type: string description: the user email address - accounts: + UpdateDocumentRequest: + description: request body for update documents + type: object + properties: + documents: + type: array + items: + $ref: "#/components/schemas/DocumentProperties" + UpdateDocumentResponse: + description: response body for update documents + type: object + properties: + documents: + type: array + items: + $ref: "#/components/schemas/SubmissionDocument" + SubmitRequest: + description: create service request + type: object + SubmitResponse: + description: result of submit filing package + type: object + required: + - packageRef + properties: + packageRef: + type: string + description: base64 encoded package reference url + GenerateCardUrlRequest: + description: create service request + type: object + required: + - internalClientNumber + - redirectUrl + properties: + internalClientNumber: + type: string + description: client id for request to bambora + redirectUrl: + type: string + description: url bambora return from + GenerateCardUrlResponse: + description: result generate url + type: object + required: + - bamboraUrl + properties: + bamboraUrl: + type: string + description: redirect url + CsoAccountUpdateRequest: + description: update client details + type: object + required: + - internalClientNumber + properties: + internalClientNumber: + type: string + description: internal client number for request to bambora + CourtLocation: + type: object + description: "Court related information" + required: + - id + - name + - code + - identifierCode + - isSupremeCourt + - address + properties: + id: + type: number + description: the court id + identifierCode: + type: string + description: the court id code + name: + type: string + description: the court name + code: + type: string + description: the court code + isSupremeCourt: + type: boolean + description: the court supreme + address: + $ref: "#/components/schemas/Address" + CourtLocations: + description: resposne body for courtlocations + type: object + properties: + courts: type: array items: - $ref: '#/components/schemas/Account' + $ref: "#/components/schemas/CourtLocation" + Address: + description: address object + type: object + required: + - addressLine1 + - cityName + - provinceName + - countryName + properties: + addressLine1: + type: string + description: the court address line one + addressLine2: + type: string + description: the court address line two + addressLine3: + type: string + description: the court address line three + postalCode: + type: string + description: the court postal code + cityName: + description: the court city name + type: string + provinceName: + type: string + description: the court province name + countryName: + description: the address country name + type: string + Payment: + description: payment object + type: object + properties: + feeExempt: + type: boolean + description: Is the fee exempt + paymentCategory: + type: number + description: Category for fee + paymentDescription: + type: string + description: a description of the payment + processedAmount: + type: number + description: Amount + submittedAmount: + type: number + description: Amount + serviceIdentifier: + type: number + description: Id of payment + transactionDate: + type: string + description: date time of transaction + Status: + description: document status + type: object + properties: + description: + type: string + description: description of status + code: + type: string + description: status identifier + changeDate: + type: string + description: date changed + Account: + description: account object + type: object + properties: + firstName: + type: string + description: first name + lastName: + type: string + description: last name + CountryCode: + description: Country Code Table Entry + type: object + properties: + code: + type: string + description: code value + description: + type: string + description: country name + ActionRequiredDetails: + description: Action required details + type: object + properties: + clientId: + type: number + description: user identifier + packageIdentifier: + type: number + description: package identifier + documents: + type: array + description: any document that requires action + items: + $ref: "#/components/schemas/ActionDocument" + ActionDocument: + description: Document that requires action + type: object + properties: + id: + type: number + description: document identifier + status: + type: string + description: > + document status: + * `SUB` - Submitted + * `RSUB` - Resubmitted + * `REF` - Referred + * `REJ` - Reject + * `CCOR` - Courtesy Correction + enum: + [ + SUB, + RSUB, + REF, + REJ, + CCOR + ] + type: + type: string + description: document type + ParentAppDetails: + description: Action required details + type: object + properties: + returnUrl: + type: string + description: the url that users will return to + rejectedDocumentFeature: + type: boolean + description: the feature is enabled or disabled for this parent diff --git a/src/backend/efiling-api/pom.xml b/src/backend/efiling-api/pom.xml index 940f0eab8c..56427427c1 100644 --- a/src/backend/efiling-api/pom.xml +++ b/src/backend/efiling-api/pom.xml @@ -1,317 +1,473 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.3.1.RELEASE - - - ca.bc.gov.open.jag - efiling-api - 0.0.1-SNAPSHOT - efiling-api - Demo project for Spring Boot - - - 1.8 - 1.3.1.Final - ca.bc.gov.open.jag.efilingapi - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - - - - org.springframework.boot - spring-boot-starter-actuator - - - - org.springframework.boot - spring-boot-starter-cache - - - - ca.bc.gov.open.jag - efiling-commons - 0.0.1-SNAPSHOT - - - - ca.bc.gov.open.jag - efiling-account-client - 0.0.1-SNAPSHOT - - - - ca.bc.gov.open.jag - efiling-lookup-client - 0.0.1-SNAPSHOT - compile - - - - commons-codec - commons-codec - - - - org.apache.commons - commons-lang3 - - - - joda-time - joda-time - - - - javax.validation - validation-api - - - - - io.opentracing.contrib - opentracing-spring-jaeger-web-starter - - - io.github.openfeign.opentracing - feign-opentracing - - - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - - - ch.qos.logback - logback-access - - - - net.rakugakibox.spring.boot - logback-access-spring-boot-starter - - - - - io.swagger - swagger-annotations - - - org.springdoc - springdoc-openapi-ui - - - io.springfox - springfox-swagger2 - - - io.springfox - springfox-swagger-ui - - - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.springframework.data - spring-data-redis - - - redis.clients - jedis - - - - - org.mapstruct - mapstruct - - - - org.openapitools - jackson-databind-nullable - - - - - - - - ca.bc.gov.open.jag - efiling-bom - 0.0.1-SNAPSHOT - pom - import - - - - - - - - default - - - - - openshift - - - - splunk-artifactory - Splunk Releases - https://splunk.jfrog.io/artifactory/ext-releases-local/ - - - - - - com.splunk.logging - splunk-library-javalogging - - - - - - - demo - - - ca.bc.gov.open.jag - efiling-demo-starter - 0.0.1-SNAPSHOT - - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - ca.bc.gov.open.jag.efilingapi.EfilingApiApplication - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - - - org.apache.maven.plugins - maven-failsafe-plugin - 2.22.2 - - - - - org.openapitools - openapi-generator-maven-plugin - 4.3.1 - - - spring-boot-api - - generate - - - ${project.basedir}/jag-efiling-api.yaml - spring - - joda - true - - spring-boot - ${default-package}.api - ${default-package}.api.model - ${default-package}.api.handler - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - ${java.version} - ${java.version} - - - org.mapstruct - mapstruct-processor - ${org.mapstruct.version} - - - - - - - - org.jacoco - jacoco-maven-plugin - 0.8.4 - - - - **/*/mappers/*Impl.java - **/*/efilingapi/api/**/* - org/openapitools/configuration/**/* - - - - - - - prepare-agent - - - - - - report - test - - report - - - - - - - - - + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.4 + + + + ca.bc.gov.open.jag + efiling-api + 2.0.12-SNAPSHOT + efiling-api + Demo project for Spring Boot + + + 17 + 1.5.5.Final + ca.bc.gov.open.jag.efilingapi + 2.17.1 + 2.0 + + jdt_apt + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-cache + + + + org.springframework.boot + spring-boot-starter-security + + + + org.springframework.boot + spring-boot-starter-oauth2-resource-server + + + + ca.bc.gov.open.jag + efiling-commons + 2.0.12-SNAPSHOT + + + + ca.bc.gov.open + spring-sftp-starter + + + + ca.bc.gov.open + spring-bceid-starter + + + org.mapstruct + mapstruct-processor + + + + + + ca.bc.gov.open + spring-clamav-starter + + + + ca.bc.gov.open + bambora-payment-starter + + + + commons-codec + commons-codec + + + + org.apache.commons + commons-lang3 + + + + org.apache.tika + tika-core + + + + joda-time + joda-time + + + + javax.validation + validation-api + + + + + ch.qos.logback + logback-classic + + + ch.qos.logback + logback-core + + + ch.qos.logback.access + logback-access-common + + + + net.rakugakibox.spring.boot + logback-access-spring-boot-starter + + + + + io.swagger.core.v3 + swagger-annotations + + + org.springdoc + springdoc-openapi-ui + + + + io.springfox + springfox-swagger-ui + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.data + spring-data-redis + + + redis.clients + jedis + 6.0.0 + + + + org.mapstruct + mapstruct + + + org.openapitools + jackson-databind-nullable + + + org.apache.commons + commons-collections4 + + + org.springframework.boot + spring-boot-test + + + org.testng + testng + 7.8.0 + compile + + + org.junit.jupiter + junit-jupiter-api + compile + + + org.springframework.security + spring-security-test + test + + + org.mockito + mockito-inline + 3.11.2 + test + + + org.apache.tomcat.embed + tomcat-embed-core + 11.0.10 + + + org.json + json + + + org.springframework.security + spring-security-core + + + org.springframework.security + spring-security-web + + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + io.netty + netty-common + + + io.netty + netty-handler + 4.1.118.Final + + + org.apache.cxf + cxf-core + 4.1.3 + + + org.springframework.security + spring-security-crypto + 6.5.3 + + + + + + + + ca.bc.gov.open.jag + efiling-bom + 2.0.12-SNAPSHOT + pom + import + + + + + + + + + default + + + + + efiling-api + + + + + ca.bc.gov.open.jag + efiling-cso-starter + 2.0.12-SNAPSHOT + + + + ca.bc.gov.open.jag + efiling-bambora-api-client + 2.0.12-SNAPSHOT + + + + ca.bc.gov.open.jag + efiling-ceis-api-client + 2.0.12-SNAPSHOT + + + + + com.github.java-json-tools + jackson-coreutils + 2.0 + + + + + + + + + splunk + + + + splunk-artifactory + Splunk Releases + https://splunk.jfrog.io/splunk/ext-releases-local + + + + + + com.splunk.logging + splunk-library-javalogging + 1.11.8 + + + + + + + + efiling-api-demo + + + ca.bc.gov.open.jag + efiling-demo-starter + 2.0.12-SNAPSHOT + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + ca.bc.gov.open.jag.efilingapi.EfilingApiApplication + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + + org.openapitools + openapi-generator-maven-plugin + 6.2.1 + + + spring-boot-api + + generate + + + ${project.basedir}/jag-efiling-api.yaml + spring + + joda + true + + + true + true + + + spring-boot + ${default-package}.api + ${default-package}.api.model + ${default-package}.api.handler + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + -parameters + + true + ${java.version} + ${java.version} + + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + + + + + + + + org.jacoco + jacoco-maven-plugin + 0.8.8 + + + + **/*/mappers/*Impl.java + **/*/efilingapi/api/**/* + org/openapitools/configuration/**/* + + + + + + + prepare-agent + + + + + + report + test + + report + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-source + generate-sources + + add-source + + + + ${project.build.directory}/generated-sources/annotations + + + + + + + + + diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/Keys.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/Keys.java index c10dc6e49a..3e9dcd2ecf 100644 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/Keys.java +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/Keys.java @@ -4,6 +4,32 @@ public class Keys { protected Keys() {} - public static final String SECURE_URL_CACHE_NAME = "SECURE_URL_CACHE"; + public static final String EFILING_APP = "efiling"; + + public static final String EFILING_API_NAME = "efiling-api"; + + public static final String MDC_EFILING_REQUEST_HEADERS = EFILING_APP + ".headers"; + + public static final String MDC_EFILING_JWT = EFILING_APP + ".jwt"; + + public static final String MDC_EFILING_SUBMISSION_ID = EFILING_APP + ".submissionId"; + + public static final String UNIVERSAL_ID_CLAIM_KEY = "universal-id"; + + public static final String CSO_APPLICATION_CLAIM_KEY = "cso-application-code"; + + public static final String IDENTITY_PROVIDER_CLAIM_KEY = "identityProviderAlias"; + + public static final String EFILING_CLIENT_ROLE = "efiling-client"; + + public static final String EFILING_USER_ROLE = "efiling-user"; + + public static final String EFILING_PAYMENT_RECEIPT_FILENAME = "payment-receipt.pdf"; + + public static final String EFILING_SUBMISSION_SHEET_FILENAME = "submission-sheet.pdf"; + + public static final String EFILING_REGISTRY_NOTICE_FILENAME = "registry-notice.pdf"; + + public static final String REJECTED_DOCUMENT_CODE = "REJ"; } diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/AccountConfig.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/AccountConfig.java new file mode 100644 index 0000000000..7e79c369d3 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/AccountConfig.java @@ -0,0 +1,31 @@ +package ca.bc.gov.open.jag.efilingapi.account; + +import ca.bc.gov.open.jag.efilingapi.account.mappers.*; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountServiceImpl; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class AccountConfig { + + @Bean + public CreateAccountRequestMapper createAccountRequestMapper() { + return new CreateAccountRequestMapperImpl(); + } + + @Bean + public AccountService accountService(EfilingAccountService efilingAccountService, CreateAccountRequestMapper createAccountRequestMapper) { + return new AccountServiceImpl(efilingAccountService, createAccountRequestMapper); + } + + @Bean + public BceidAccountMapper bceidAccountMapper() { + return new BceidAccountMapperImpl(); + } + + @Bean + public CsoAccountMapper csoAccountMapper() { return new CsoAccountMapperImpl(); } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/BceidAccountApiDelagateImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/BceidAccountApiDelagateImpl.java new file mode 100644 index 0000000000..d12a0e4996 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/BceidAccountApiDelagateImpl.java @@ -0,0 +1,48 @@ +package ca.bc.gov.open.jag.efilingapi.account; + +import ca.bc.gov.open.bceid.starter.account.BCeIDAccountService; +import ca.bc.gov.open.bceid.starter.account.GetAccountRequest; +import ca.bc.gov.open.bceid.starter.account.models.IndividualIdentity; +import ca.bc.gov.open.jag.efilingapi.account.mappers.BceidAccountMapper; +import ca.bc.gov.open.jag.efilingapi.api.BceidAccountApiDelegate; +import ca.bc.gov.open.jag.efilingapi.api.model.BceidAccount; +import ca.bc.gov.open.jag.efilingapi.core.security.SecurityUtils; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; + +import java.util.Optional; +import java.util.UUID; + +@Service +public class BceidAccountApiDelagateImpl implements BceidAccountApiDelegate { + + + private final BCeIDAccountService bCeIDAccountService; + private final BceidAccountMapper bceidAccountMapper; + + public BceidAccountApiDelagateImpl(BCeIDAccountService bCeIDAccountService, BceidAccountMapper bceidAccountMapper) { + this.bCeIDAccountService = bCeIDAccountService; + this.bceidAccountMapper = bceidAccountMapper; + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity getBceidAccount(UUID xTransactionId) { + + Optional userId = SecurityUtils.getUniversalIdFromContext(); + + if(!userId.isPresent()) + return new ResponseEntity(HttpStatus.FORBIDDEN); + + Optional individualIdentity = bCeIDAccountService.getIndividualIdentity( + GetAccountRequest.IndividualSelfRequest(userId.get().toString().replace("-", "").toUpperCase())); + + if(!individualIdentity.isPresent()) + return new ResponseEntity(HttpStatus.NOT_FOUND); + + return ResponseEntity.ok(bceidAccountMapper.toBceidAccount(individualIdentity.get())); + + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/CsoAccountApiDelegateImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/CsoAccountApiDelegateImpl.java new file mode 100644 index 0000000000..31de5d754c --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/CsoAccountApiDelegateImpl.java @@ -0,0 +1,128 @@ +package ca.bc.gov.open.jag.efilingapi.account; + +import ca.bc.gov.open.jag.efilingapi.account.mappers.CsoAccountMapper; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.CsoAccountApiDelegate; +import ca.bc.gov.open.jag.efilingapi.api.model.CreateCsoAccountRequest; +import ca.bc.gov.open.jag.efilingapi.api.model.CsoAccount; +import ca.bc.gov.open.jag.efilingapi.api.model.CsoAccountUpdateRequest; +import ca.bc.gov.open.jag.efilingapi.core.security.SecurityUtils; +import ca.bc.gov.open.jag.efilingapi.error.*; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingAccountServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; + +import java.util.Optional; +import java.util.UUID; + +/** + * Suite of services to manage cso account + */ +@Service +public class CsoAccountApiDelegateImpl implements CsoAccountApiDelegate { + + private static final String CREATE_ACCOUNT_EXCEPTION = "Error Creating CSO account."; + private static final String INVALID_UNIVERSAL_ID = "Invalid universal id."; + private static final String MISSING_IDENTITY_PROVIDER = "identityProviderAlias claim missing in jwt token."; + private static final String MISSING_UNIVERSAL_ID = "universal-id claim missing in jwt token."; + private static final String UPDATE_CLIENT_EXCEPTION = "Error Updating CSO client account."; + + Logger logger = LoggerFactory.getLogger(CsoAccountApiDelegateImpl.class); + + private final AccountService accountService; + private final CsoAccountMapper csoAccountMapper; + + + public CsoAccountApiDelegateImpl(AccountService accountService, CsoAccountMapper csoAccountMapper) { + this.accountService = accountService; + this.csoAccountMapper = csoAccountMapper; + } + + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity createAccount(UUID xTransactionId, CreateCsoAccountRequest createAccountRequest) { + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) + throw new MissingUniversalIdException(MISSING_UNIVERSAL_ID); + + Optional identityProvider = SecurityUtils.getIdentityProvider(); + + if(!identityProvider.isPresent()) + throw new MissingIdentityProviderException(MISSING_IDENTITY_PROVIDER); + + try { + + logger.debug("attempting to create a cso account"); + + AccountDetails accountDetails = accountService.createAccount(universalId.get(), identityProvider.get(),createAccountRequest); + + logger.info("Account successfully created"); + + return new ResponseEntity<>(csoAccountMapper.toCsoAccount(accountDetails), HttpStatus.CREATED); + + } catch (EfilingAccountServiceException e) { + + logger.error("Exception while trying to create a CSO Account", e); + throw new CreateAccountException(CREATE_ACCOUNT_EXCEPTION); + } + + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity getCsoAccount(UUID xTransactionId) { + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) return new ResponseEntity(HttpStatus.FORBIDDEN); + + AccountDetails accountDetails = accountService.getCsoAccountDetails(universalId.get()); + + if(accountDetails == null) return new ResponseEntity(HttpStatus.NOT_FOUND); + + return ResponseEntity.ok(csoAccountMapper.toCsoAccount(accountDetails)); + + } + + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity updateCsoAccount(UUID xTransactionId, CsoAccountUpdateRequest clientUpdateRequest) { + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) + throw new InvalidUniversalException(INVALID_UNIVERSAL_ID); + + ResponseEntity response; + + try { + + AccountDetails accountDetails = accountService.getCsoAccountDetails(universalId.get()); + + if(accountDetails == null) { + throw new InvalidUniversalException(INVALID_UNIVERSAL_ID); + } + + accountDetails.updateInternalClientNumber(clientUpdateRequest.getInternalClientNumber()); + + accountService.updateClient(accountDetails); + + response = ResponseEntity.ok(csoAccountMapper.toCsoAccount(accountDetails)); + } catch (EfilingAccountServiceException e) { + logger.warn(e.getMessage(), e); + throw new UpdateClientException(UPDATE_CLIENT_EXCEPTION); + } + + return response; + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/mappers/BceidAccountMapper.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/mappers/BceidAccountMapper.java new file mode 100644 index 0000000000..d3f9150566 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/mappers/BceidAccountMapper.java @@ -0,0 +1,16 @@ +package ca.bc.gov.open.jag.efilingapi.account.mappers; + +import ca.bc.gov.open.bceid.starter.account.models.IndividualIdentity; +import ca.bc.gov.open.jag.efilingapi.api.model.BceidAccount; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper +public interface BceidAccountMapper { + + @Mapping(target = "firstName", source = "name.firstName") + @Mapping(target = "lastName", source = "name.surname") + @Mapping(target = "middleName", source = "name.middleName") + BceidAccount toBceidAccount(IndividualIdentity individualIdentity); + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/mappers/CreateAccountRequestMapper.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/mappers/CreateAccountRequestMapper.java new file mode 100644 index 0000000000..426985d5b6 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/mappers/CreateAccountRequestMapper.java @@ -0,0 +1,12 @@ +package ca.bc.gov.open.jag.efilingapi.account.mappers; + +import ca.bc.gov.open.jag.efilingapi.api.model.CreateCsoAccountRequest; +import ca.bc.gov.open.jag.efilingcommons.model.CreateAccountRequest; +import org.mapstruct.Mapper; + +@Mapper +public interface CreateAccountRequestMapper { + + CreateAccountRequest toCreateAccountRequest(String universalId, String identityProvider,CreateCsoAccountRequest createCsoAccountRequest); + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/mappers/CsoAccountMapper.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/mappers/CsoAccountMapper.java new file mode 100644 index 0000000000..117fd8591c --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/mappers/CsoAccountMapper.java @@ -0,0 +1,12 @@ +package ca.bc.gov.open.jag.efilingapi.account.mappers; + +import ca.bc.gov.open.jag.efilingapi.api.model.CsoAccount; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import org.mapstruct.Mapper; + +@Mapper +public interface CsoAccountMapper { + + CsoAccount toCsoAccount(AccountDetails accountDetails); + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/service/AccountService.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/service/AccountService.java new file mode 100644 index 0000000000..78f0c5ff8d --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/service/AccountService.java @@ -0,0 +1,14 @@ +package ca.bc.gov.open.jag.efilingapi.account.service; + +import ca.bc.gov.open.jag.efilingapi.api.model.CreateCsoAccountRequest; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; + +public interface AccountService { + + AccountDetails getCsoAccountDetails(String universalId); + + void updateClient(AccountDetails accountDetails); + + AccountDetails createAccount(String universalId, String identityProvider,CreateCsoAccountRequest createAccountRequest); + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/service/AccountServiceImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/service/AccountServiceImpl.java new file mode 100644 index 0000000000..9858dfa7c9 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/account/service/AccountServiceImpl.java @@ -0,0 +1,36 @@ +package ca.bc.gov.open.jag.efilingapi.account.service; + +import ca.bc.gov.open.jag.efilingapi.account.mappers.CreateAccountRequestMapper; +import ca.bc.gov.open.jag.efilingapi.api.model.CreateCsoAccountRequest; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; +import org.springframework.cache.annotation.Cacheable; + +public class AccountServiceImpl implements AccountService { + + private final EfilingAccountService efilingAccountService; + private final CreateAccountRequestMapper createAccountRequestMapper; + + public AccountServiceImpl(EfilingAccountService efilingAccountService, CreateAccountRequestMapper createAccountRequestMapper) { + this.efilingAccountService = efilingAccountService; + this.createAccountRequestMapper = createAccountRequestMapper; + } + + @Override + @Cacheable(cacheNames = "accountDetails", key = "#universalId", cacheManager = "accountDetailsCacheManager", unless = "#result == null || #result.getInternalClientNumber() == null") + public AccountDetails getCsoAccountDetails(String universalId) { + return efilingAccountService.getAccountDetails(universalId); + } + + @Override + public void updateClient(AccountDetails accountDetails) { + efilingAccountService.updateClient(accountDetails); + } + + @Override + @Cacheable(cacheNames = "accountDetails", key = "#universalId", cacheManager = "accountDetailsCacheManager", unless = "#result == null || #result.getInternalClientNumber() == null") + public AccountDetails createAccount(String universalId, String identityProvider, CreateCsoAccountRequest createAccountRequest) { + return efilingAccountService.createAccount(createAccountRequestMapper.toCreateAccountRequest(universalId, identityProvider, createAccountRequest)); + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/cache/CacheConfiguration.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/cache/CacheConfiguration.java index e0f3705d90..a93411ef59 100644 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/cache/CacheConfiguration.java +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/cache/CacheConfiguration.java @@ -2,6 +2,9 @@ import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.cache.CacheProperties; import org.springframework.boot.autoconfigure.data.redis.RedisProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -10,6 +13,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisClusterConfiguration; @@ -20,6 +24,7 @@ import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; +import java.time.Duration; import java.util.ArrayList; import java.util.List; @@ -89,7 +94,10 @@ private List createSentinels(RedisProperties.Sentinel sentinel) { * @return */ @Bean(name = "submissionCacheManager") - public CacheManager submissionCacheManager(JedisConnectionFactory jedisConnectionFactory, Jackson2JsonRedisSerializer jackson2JsonRedisSerializer) { + @Primary + public CacheManager submissionCacheManager( + JedisConnectionFactory jedisConnectionFactory, + @Qualifier("submissionSerializer") Jackson2JsonRedisSerializer jackson2JsonRedisSerializer) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .disableCachingNullValues() @@ -103,10 +111,83 @@ public CacheManager submissionCacheManager(JedisConnectionFactory jedisConnectio .cacheDefaults(redisCacheConfiguration).build(); } - @Bean + @Bean(name = "submissionSerializer") + @Primary public Jackson2JsonRedisSerializer jackson2JsonRedisSerializer() { return new Jackson2JsonRedisSerializer(Submission.class); } + /** + * Configures the cache manager + * @param jedisConnectionFactory A jedisConnectionFactory + * @return + */ + @Bean(name = "documentCacheManager") + public CacheManager documentCacheManager( + JedisConnectionFactory jedisConnectionFactory) { + + RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() + .disableCachingNullValues() + .entryTtl(Duration.ofHours(24)); + + redisCacheConfiguration.usePrefix(); + + return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(jedisConnectionFactory) + .cacheDefaults(redisCacheConfiguration).build(); + } + + /** + * Configures the cache manager + * @param jedisConnectionFactory A jedisConnectionFactory + * @return + */ + @Bean(name = "documentTypeDetailsCacheManager") + public CacheManager documentTypeDetailsCacheManager( + JedisConnectionFactory jedisConnectionFactory, + @Qualifier("documentTypeDetailsSerializer") Jackson2JsonRedisSerializer documentTypeDetailsSerializer) { + + RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() + .disableCachingNullValues() + .entryTtl(Duration.ofHours(24)) + .serializeValuesWith(RedisSerializationContext + .SerializationPair.fromSerializer(documentTypeDetailsSerializer)); + + redisCacheConfiguration.usePrefix(); + + return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(jedisConnectionFactory) + .cacheDefaults(redisCacheConfiguration).build(); + } + + @Bean(name = "documentTypeDetailsSerializer") + public Jackson2JsonRedisSerializer documentTypeDetailsSerializer() { + return new Jackson2JsonRedisSerializer(DocumentTypeDetails.class); + } + + /** + * Configures the cache manager + * @param jedisConnectionFactory A jedisConnectionFactory + * @return + */ + @Bean(name = "accountDetailsCacheManager") + public CacheManager accountDetailsCacheManager( + JedisConnectionFactory jedisConnectionFactory, + @Qualifier("accountDetailsSerializer") Jackson2JsonRedisSerializer accountDetailsSerializer) { + + RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() + .disableCachingNullValues() + .entryTtl(Duration.ofMinutes(15)) + .serializeValuesWith(RedisSerializationContext + .SerializationPair.fromSerializer(accountDetailsSerializer));; + + redisCacheConfiguration.usePrefix(); + + return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(jedisConnectionFactory) + .cacheDefaults(redisCacheConfiguration).build(); + } + + @Bean(name = "accountDetailsSerializer") + public Jackson2JsonRedisSerializer accountDetailsSerializer() { + return new Jackson2JsonRedisSerializer(AccountDetails.class); + } } diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/config/ApplicationConfiguration.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/config/ApplicationConfiguration.java deleted file mode 100644 index 7e09f370d5..0000000000 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/config/ApplicationConfiguration.java +++ /dev/null @@ -1,37 +0,0 @@ -package ca.bc.gov.open.jag.efilingapi.config; - -import io.opentracing.Tracer; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -/** - * Global Application Configuration - */ -@Configuration -public class ApplicationConfiguration { - - /** - * Configures CORS for enabling javascript applications to connect. - */ - @Bean - public WebMvcConfigurer corsConfigurer() { - return new WebMvcConfigurer() { - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**").allowedMethods("*").allowedOrigins("*"); - } - }; - } - - /** - * Configures Jeager tracer. - */ - @Bean - public Tracer jaegerTracer() { - return new io.jaegertracing.Configuration("spring-boot") - .getTracer(); - } - -} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/config/KeycloakJwtAuthConverter.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/config/KeycloakJwtAuthConverter.java new file mode 100644 index 0000000000..516a7c25d8 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/config/KeycloakJwtAuthConverter.java @@ -0,0 +1,79 @@ +package ca.bc.gov.open.jag.efilingapi.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.convert.converter.Converter; +import org.springframework.lang.NonNull; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; +import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; +import org.springframework.stereotype.Component; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * A Converter implementation (specific to Keycloak) that can convert a Keycloak + * JWT into a AbstractAuthenticationToken that can be used by Spring Security. + */ +@Component +public class KeycloakJwtAuthConverter implements Converter { + + public static final String KEYCLOAK_PRINCIPLE_ATTRIBUTE = "preferred_username"; + public static final String KEYCLOAK_RESOURCE_ATTRIBUTE = "resource_access"; + public static final String KEYCLOAK_ROLE_ATTRIBUTE = "roles"; + + private String resourceId; + + public KeycloakJwtAuthConverter(@Value("${jwt.auth.converter.resource-id}") String resourceId) { + this.resourceId = resourceId; + } + + @Override + public AbstractAuthenticationToken convert(@NonNull Jwt jwt) { + JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); + + Collection authorities = Stream + .concat(jwtGrantedAuthoritiesConverter.convert(jwt).stream(), extractResourceRoles(jwt).stream()) + .collect(Collectors.toSet()); + + return new JwtAuthenticationToken(jwt, authorities, getPrincipleClaimName(jwt)); + } + + /** + * Extract the principle claim name (preferred_username) from the JWT. + */ + public static String getPrincipleClaimName(Jwt jwt) { + return jwt.getClaim(KEYCLOAK_PRINCIPLE_ATTRIBUTE); + } + + /** + * Extracts the resource roles from the JWT. + */ + @SuppressWarnings("unchecked") + private Collection extractResourceRoles(Jwt jwt) { + Map resourceAccess = jwt.getClaim(KEYCLOAK_RESOURCE_ATTRIBUTE); + if (resourceAccess == null) { + return Set.of(); + } + + Map resource = (Map) resourceAccess.get(resourceId); + if (resource == null) { + return Set.of(); + } + + Collection resourceRoles = (Collection) resource.get(KEYCLOAK_ROLE_ATTRIBUTE); + if (resourceRoles == null) { + return Set.of(); + } + + return resourceRoles.stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role)) + .collect(Collectors.toSet()); + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/config/NavigationProperties.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/config/NavigationProperties.java index ae90e32078..900f736527 100644 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/config/NavigationProperties.java +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/config/NavigationProperties.java @@ -9,6 +9,9 @@ public class NavigationProperties { private String baseUrl; + + private String csoBaseUrl; + /** * Returns the base url to create a secure upload url * @return @@ -21,4 +24,11 @@ public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } + public String getCsoBaseUrl() { + return csoBaseUrl; + } + + public void setCsoBaseUrl(String csoBaseUrl) { + this.csoBaseUrl = csoBaseUrl; + } } diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/config/SecurityConfig.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/config/SecurityConfig.java new file mode 100644 index 0000000000..feb582b875 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/config/SecurityConfig.java @@ -0,0 +1,68 @@ +package ca.bc.gov.open.jag.efilingapi.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.session.SessionRegistryImpl; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy; +import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; + +@Configuration +@EnableWebSecurity +@EnableMethodSecurity +class SecurityConfig { + + private final KeycloakJwtAuthConverter keycloakJwtAuthConverter; + + public SecurityConfig(KeycloakJwtAuthConverter keycloakJwtAuthConverter) { + this.keycloakJwtAuthConverter = keycloakJwtAuthConverter; + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + + http.cors(cors -> cors.configurationSource(corsConfigurationSource())); + + http.csrf(AbstractHttpConfigurer::disable); + + http.authorizeHttpRequests(requests -> requests + .requestMatchers(antMatcher("/actuator/**")).permitAll() + .anyRequest().authenticated()); + + http.oauth2ResourceServer((oauth2) -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(keycloakJwtAuthConverter))); + + http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); + + return http.build(); + } + + protected CorsConfigurationSource corsConfigurationSource() { + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + CorsConfiguration corsConfiguration = new CorsConfiguration(); + corsConfiguration.applyPermitDefaultValues(); + corsConfiguration.addAllowedMethod(HttpMethod.GET); + corsConfiguration.addAllowedMethod(HttpMethod.POST); + corsConfiguration.addAllowedMethod(HttpMethod.PUT); + corsConfiguration.addAllowedMethod(HttpMethod.DELETE); + corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS); + source.registerCorsConfiguration("/**", corsConfiguration); + return source; + } + + @Bean + protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { + return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()); + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/core/mdc/MdcFilter.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/core/mdc/MdcFilter.java new file mode 100644 index 0000000000..91554bc8c9 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/core/mdc/MdcFilter.java @@ -0,0 +1,89 @@ +package ca.bc.gov.open.jag.efilingapi.core.mdc; + +import ca.bc.gov.open.jag.efilingapi.Keys; +import ca.bc.gov.open.jag.efilingapi.core.security.SecurityUtils; +import jakarta.servlet.*; +import jakarta.servlet.http.HttpServletRequest; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; + +/** + * The MdcFilter class sets the context for any http request handled by the efiling api + * It adds all the header (except authorization) and value of interest from the jwt token + */ +@Component +public class MdcFilter implements Filter { + + private Logger logger = LoggerFactory.getLogger(MdcFilter.class); + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + + List mdcKeys = new ArrayList<>(); + + mdcKeys.addAll(setMDCHeaders((HttpServletRequest) servletRequest)); + + mdcKeys.addAll(setMDCToken()); + + filterChain.doFilter(servletRequest, servletResponse); + + mdcKeys.stream().forEach(MDC::remove); + + } + + private List setMDCHeaders(HttpServletRequest httpRequest) { + + List result = new ArrayList<>(); + + Enumeration headerNames = httpRequest.getHeaderNames(); + + if (headerNames == null) return result; + + while (headerNames.hasMoreElements()) { + + String header = headerNames.nextElement(); + + if (StringUtils.equalsIgnoreCase("authorization", header)) continue; + + String mdcKey = MessageFormat.format("{0}.{1}", Keys.MDC_EFILING_REQUEST_HEADERS, header); + result.add(mdcKey); + + logger.debug("{}:{}", mdcKey, httpRequest.getHeader(header)); + MDC.put(mdcKey, httpRequest.getHeader(header)); + + } + + return result; + } + + private List setMDCToken() { + + List result = new ArrayList<>(); + + SecurityUtils.getClientId().ifPresent(value -> result.add(setJwtValue("clientId", value))); + SecurityUtils.getUniversalIdFromContext().ifPresent(value -> result.add(setJwtValue("universalId", value))); + SecurityUtils.getApplicationCode().ifPresent(value -> result.add(setJwtValue("applicationCode", value))); + SecurityUtils.getIdentityProvider().ifPresent(value -> result.add(setJwtValue("identityProvider", value))); + + return result; + + } + + private String setJwtValue( String key, String value) { + String mdcKey = MessageFormat.format("{0}.{1}", Keys.MDC_EFILING_JWT, key); + logger.debug("{}:{}", key, value); + MDC.put(mdcKey, value); + return mdcKey; + } + + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/core/security/SecurityUtils.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/core/security/SecurityUtils.java new file mode 100644 index 0000000000..d769fb246c --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/core/security/SecurityUtils.java @@ -0,0 +1,60 @@ +package ca.bc.gov.open.jag.efilingapi.core.security; + +import ca.bc.gov.open.jag.efilingapi.Keys; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.util.Optional; + +public class SecurityUtils { + + private SecurityUtils() { + } + + public static Optional getClientId() { + try { + Jwt jwt = (Jwt) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + + return Optional.of(jwt.getId()); + } catch (Exception e) { + return Optional.empty(); + } + } + + public static Optional getUniversalIdFromContext() { + return getOtherClaim(Keys.UNIVERSAL_ID_CLAIM_KEY); + } + + public static Optional getApplicationCode() { + return getOtherClaim(Keys.CSO_APPLICATION_CLAIM_KEY); + } + + public static Optional getIdentityProvider() { + return getOtherClaim(Keys.IDENTITY_PROVIDER_CLAIM_KEY); + } + + private static Optional getOtherClaim(String claim) { + try { + Jwt jwt = (Jwt) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + return Optional.of(jwt.getClaim(claim)); + } catch (Exception e) { + return Optional.empty(); + } + } + + public static boolean isEarlyAdopter() { + return isInRole("ROLE_early-adopters"); + } + + public static boolean isInRole(String role) { + try { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + + return authentication.getAuthorities().stream() + .anyMatch(r -> r.getAuthority().equals(role)); + } catch (Exception e) { + return false; + } + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/CourtConfig.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/CourtConfig.java new file mode 100644 index 0000000000..7a36c64311 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/CourtConfig.java @@ -0,0 +1,18 @@ +package ca.bc.gov.open.jag.efilingapi.court; + +import ca.bc.gov.open.jag.efilingapi.court.services.CourtService; +import ca.bc.gov.open.jag.efilingapi.court.services.CourtServiceImpl; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingCourtService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSearchService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class CourtConfig { + + @Bean + public CourtService courtService(EfilingCourtService efilingCourtService, EfilingSearchService efilingSearchService) { + return new CourtServiceImpl(efilingCourtService, efilingSearchService); + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/models/GetCourtDetailsRequest.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/models/GetCourtDetailsRequest.java new file mode 100644 index 0000000000..85bb840b07 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/models/GetCourtDetailsRequest.java @@ -0,0 +1,59 @@ +package ca.bc.gov.open.jag.efilingapi.court.models; + +public class GetCourtDetailsRequest { + + private String courtLocation; + private String courtLevel; + private String courtClassification; + + public String getCourtLocation() { + return courtLocation; + } + + public String getCourtLevel() { + return courtLevel; + } + + public String getCourtClassification() { + return courtClassification; + } + + public GetCourtDetailsRequest(Builder builder) { + this.courtClassification = builder.courtClassification; + this.courtLevel = builder.courtLevel; + this.courtLocation = builder.courtLocation; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private String courtLocation; + private String courtClassification; + private String courtLevel; + + public Builder courtLocation(String courtLocation) { + this.courtLocation = courtLocation; + return this; + } + + public Builder courtClassification(String courtClassification) { + this.courtClassification = courtClassification; + return this; + } + + public Builder courtLevel(String courtLevel) { + this.courtLevel = courtLevel; + return this; + } + + public GetCourtDetailsRequest create() { + return new GetCourtDetailsRequest(this); + } + + } + + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/models/IsValidCourtFileNumberRequest.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/models/IsValidCourtFileNumberRequest.java new file mode 100644 index 0000000000..8ae14af0c6 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/models/IsValidCourtFileNumberRequest.java @@ -0,0 +1,84 @@ +package ca.bc.gov.open.jag.efilingapi.court.models; + +import java.math.BigDecimal; + +public class IsValidCourtFileNumberRequest { + + private String fileNumber; + private BigDecimal courtId; + private String courtLevel; + private String courtClassification; + private String applicationCode; + + public String getFileNumber() { + return fileNumber; + } + + public BigDecimal getCourtId() { + return courtId; + } + + public String getCourtLevel() { + return courtLevel; + } + + public String getCourtClassification() { + return courtClassification; + } + + public String getApplicationCode() { + return applicationCode; + } + + public IsValidCourtFileNumberRequest(Builder builder) { + this.fileNumber = builder.fileNumber; + this.courtId = builder.courtId; + this.courtLevel = builder.courtLevel; + this.courtClassification = builder.courtClassification; + this.applicationCode = builder.applicationCode; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private String fileNumber; + private BigDecimal courtId; + private String courtLevel; + private String courtClassification; + private String applicationCode; + + public Builder applicationCode(String applicationCode) { + this.applicationCode = applicationCode; + return this; + } + + public Builder fileNumber(String fileNumber) { + this.fileNumber = fileNumber; + return this; + } + + public Builder courtId(BigDecimal courtId) { + this.courtId = courtId; + return this; + } + + public Builder courtLevel(String courtLevel) { + this.courtLevel = courtLevel; + return this; + } + + public Builder courtClassification(String courtClassification) { + this.courtClassification = courtClassification; + return this; + } + + public IsValidCourtFileNumberRequest create() { + return new IsValidCourtFileNumberRequest(this); + } + + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/models/IsValidCourtRequest.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/models/IsValidCourtRequest.java new file mode 100644 index 0000000000..8e26ba8fbd --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/models/IsValidCourtRequest.java @@ -0,0 +1,72 @@ +package ca.bc.gov.open.jag.efilingapi.court.models; + +import java.math.BigDecimal; + +public class IsValidCourtRequest { + + private BigDecimal courtId; + private String courtLevel; + private String courtClassification; + private String applicationCode; + + public BigDecimal getCourtId() { + return courtId; + } + + public String getCourtLevel() { + return courtLevel; + } + + public String getCourtClassification() { + return courtClassification; + } + + public String getApplicationCode() { + return applicationCode; + } + + public IsValidCourtRequest(Builder builder) { + this.applicationCode = builder.applicationCode; + this.courtId = builder.courtId; + this.courtClassification = builder.courtClassification; + this.courtLevel = builder.courtLevel; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private BigDecimal courtId; + private String courtLevel; + private String courtClassification; + private String applicationCode; + + public Builder courtId(BigDecimal courtId) { + this.courtId = courtId; + return this; + } + + public Builder courtLevel(String courtLevel) { + this.courtLevel = courtLevel; + return this; + } + + public Builder courtClassification(String courtClassification) { + this.courtClassification = courtClassification; + return this; + } + + public Builder applicationCode(String applicationCode) { + this.applicationCode = applicationCode; + return this; + } + + public IsValidCourtRequest create() { + return new IsValidCourtRequest(this); + } + + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/services/CourtService.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/services/CourtService.java new file mode 100644 index 0000000000..01f842f6d3 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/services/CourtService.java @@ -0,0 +1,17 @@ +package ca.bc.gov.open.jag.efilingapi.court.services; + +import ca.bc.gov.open.jag.efilingapi.court.models.GetCourtDetailsRequest; +import ca.bc.gov.open.jag.efilingapi.court.models.IsValidCourtFileNumberRequest; +import ca.bc.gov.open.jag.efilingapi.court.models.IsValidCourtRequest; +import ca.bc.gov.open.jag.efilingcommons.model.CourtDetails; + +import java.util.Optional; + +public interface CourtService { + + boolean isValidCourt(IsValidCourtRequest isValidCourtRequest); + + Optional getCourtDetails(GetCourtDetailsRequest getCourtDetailsRequest); + + boolean isValidCourtFileNumber(IsValidCourtFileNumberRequest isValidCourtFileNumberRequest); +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/services/CourtServiceImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/services/CourtServiceImpl.java new file mode 100644 index 0000000000..6aaf3125d1 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/court/services/CourtServiceImpl.java @@ -0,0 +1,61 @@ +package ca.bc.gov.open.jag.efilingapi.court.services; + +import ca.bc.gov.open.jag.efilingapi.court.models.GetCourtDetailsRequest; +import ca.bc.gov.open.jag.efilingapi.court.models.IsValidCourtFileNumberRequest; +import ca.bc.gov.open.jag.efilingapi.court.models.IsValidCourtRequest; +import ca.bc.gov.open.jag.efilingcommons.model.CourtDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingCourtService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSearchService; +import org.apache.commons.lang3.StringUtils; + +import java.util.Optional; + +public class CourtServiceImpl implements CourtService { + + private final EfilingCourtService efilingCourtService; + private final EfilingSearchService efilingSearchService; + + public CourtServiceImpl(EfilingCourtService efilingCourtService, EfilingSearchService efilingSearchService) { + this.efilingCourtService = efilingCourtService; + this.efilingSearchService = efilingSearchService; + } + + @Override + public boolean isValidCourt(IsValidCourtRequest isValidCourtRequest) { + return this.efilingCourtService.checkValidLevelClassLocation( + isValidCourtRequest.getCourtId(), + isValidCourtRequest.getCourtLevel(), + isValidCourtRequest.getCourtClassification(), + isValidCourtRequest.getApplicationCode() + ); + } + + @Override + public Optional getCourtDetails(GetCourtDetailsRequest getCourtDetailsRequest) { + + return this.efilingCourtService.getCourtDescription( + getCourtDetailsRequest.getCourtLocation(), + getCourtDetailsRequest.getCourtLevel(), + getCourtDetailsRequest.getCourtClassification()); + + } + + @Override + public boolean isValidCourtFileNumber(IsValidCourtFileNumberRequest isValidCourtFileNumberRequest){ + + if (StringUtils.equalsIgnoreCase("A", isValidCourtFileNumberRequest.getCourtLevel())) { + return this.efilingSearchService.caseNumberExists(isValidCourtFileNumberRequest.getFileNumber()); + } else { + return efilingCourtService.checkValidCourtFileNumber( + isValidCourtFileNumberRequest.getFileNumber(), + isValidCourtFileNumberRequest.getCourtId(), + isValidCourtFileNumberRequest.getCourtLevel(), + isValidCourtFileNumberRequest.getCourtClassification(), + isValidCourtFileNumberRequest.getApplicationCode() + ); + } + + + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/courts/CourtsApiDelegateImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/courts/CourtsApiDelegateImpl.java new file mode 100644 index 0000000000..d727008f0c --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/courts/CourtsApiDelegateImpl.java @@ -0,0 +1,51 @@ +package ca.bc.gov.open.jag.efilingapi.courts; + +import ca.bc.gov.open.jag.efilingapi.api.CourtsApiDelegate; +import ca.bc.gov.open.jag.efilingapi.api.model.CourtLocation; +import ca.bc.gov.open.jag.efilingapi.api.model.CourtLocations; +import ca.bc.gov.open.jag.efilingapi.courts.mappers.CourtLocationMapper; +import ca.bc.gov.open.jag.efilingapi.error.CourtLocationException; +import ca.bc.gov.open.jag.efilingcommons.court.EfilingCourtLocationService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; + +import java.util.List; + + +@Service +public class CourtsApiDelegateImpl implements CourtsApiDelegate { + + private static final String COURT_LOCATION_ERROR = "Error while retrieving court locations."; + + Logger logger = LoggerFactory.getLogger(CourtsApiDelegateImpl.class); + + private final EfilingCourtLocationService efilingCourtLocationService; + + private final CourtLocationMapper courtLocationMapper; + + public CourtsApiDelegateImpl(EfilingCourtLocationService efilingCourtLocationService, CourtLocationMapper courtLocationMapper) { + this.efilingCourtLocationService = efilingCourtLocationService; + this.courtLocationMapper = courtLocationMapper; + } + + @Override + @PreAuthorize("hasRole('efiling-client') || hasRole('efiling-admin')") + public ResponseEntity getCourtLocations(String courtLevel) { + + logger.info("Request for court level received {}", courtLevel); + List courtLocationsList = courtLocationMapper.toCourtLocationList(efilingCourtLocationService.getCourtLocations(courtLevel)); + if (courtLocationsList == null) + throw new CourtLocationException(COURT_LOCATION_ERROR); + + CourtLocations courtLocations = new CourtLocations(); + courtLocations.setCourts(courtLocationsList); + return ResponseEntity.ok(courtLocations); + + } + + + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/courts/CourtsConfiguration.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/courts/CourtsConfiguration.java new file mode 100644 index 0000000000..9253775c3d --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/courts/CourtsConfiguration.java @@ -0,0 +1,17 @@ +package ca.bc.gov.open.jag.efilingapi.courts; + + +import ca.bc.gov.open.jag.efilingapi.courts.mappers.CourtLocationMapper; +import ca.bc.gov.open.jag.efilingapi.courts.mappers.CourtLocationMapperImpl; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class CourtsConfiguration { + + @Bean + public CourtLocationMapper courtLocationMapper() { + return new CourtLocationMapperImpl(); + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/courts/mappers/CourtLocationMapper.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/courts/mappers/CourtLocationMapper.java new file mode 100644 index 0000000000..9fa60c5472 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/courts/mappers/CourtLocationMapper.java @@ -0,0 +1,13 @@ +package ca.bc.gov.open.jag.efilingapi.courts.mappers; + +import ca.bc.gov.open.jag.efilingapi.api.model.CourtLocation; +import ca.bc.gov.open.jag.efilingcommons.model.InternalCourtLocation; +import org.mapstruct.Mapper; + +import java.util.List; + +@Mapper +public interface CourtLocationMapper { + + List toCourtLocationList(List courtLocations); +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentApiDelegateImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentApiDelegateImpl.java new file mode 100644 index 0000000000..c429e0cc77 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentApiDelegateImpl.java @@ -0,0 +1,51 @@ +package ca.bc.gov.open.jag.efilingapi.document; + +import ca.bc.gov.open.jag.efilingapi.Keys; +import ca.bc.gov.open.jag.efilingapi.api.DocumentsApiDelegate; +import ca.bc.gov.open.jag.efilingapi.api.model.CourtClassification; +import ca.bc.gov.open.jag.efilingapi.api.model.CourtLevel; +import ca.bc.gov.open.jag.efilingapi.api.model.DocumentType; +import ca.bc.gov.open.jag.efilingapi.error.DocumentTypeException; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingDocumentServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class DocumentApiDelegateImpl implements DocumentsApiDelegate { + Logger logger = LoggerFactory.getLogger(DocumentApiDelegateImpl.class); + + private static final String DOCUMENT_TYPE_ERROR = "Error while retrieving documents"; + private final DocumentStore documentStore; + + public DocumentApiDelegateImpl(DocumentStore documentStore) { + this.documentStore = documentStore; + } + + @Override + @PreAuthorize("hasRole('" + Keys.EFILING_USER_ROLE + "') || hasRole('"+ Keys.EFILING_CLIENT_ROLE +"')") + public ResponseEntity> getDocumentTypes(@NotNull @Valid CourtLevel courtLevel, @NotNull @Valid CourtClassification courtClassification) { + try { + return ResponseEntity.ok(documentStore.getDocumentTypes(courtLevel.getValue(), courtClassification.getValue()).stream() + .map(this::toDocumentType).collect(Collectors.toList())); + } catch (EfilingDocumentServiceException e) { + logger.warn(e.getMessage(), e); + throw new DocumentTypeException(DOCUMENT_TYPE_ERROR); + } + } + + private DocumentType toDocumentType(DocumentTypeDetails documentTypeDetails) { + DocumentType outDocumentType = new DocumentType(); + outDocumentType.setType(documentTypeDetails.getType()); + outDocumentType.setDescription(documentTypeDetails.getDescription()); + return outDocumentType; + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentConfiguration.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentConfiguration.java new file mode 100644 index 0000000000..b95713e8ca --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentConfiguration.java @@ -0,0 +1,20 @@ +package ca.bc.gov.open.jag.efilingapi.document; + +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class DocumentConfiguration { + + @Bean + public DocumentStore documentStore(EfilingDocumentService efilingDocumentService) { + return new DocumentStoreImpl(efilingDocumentService); + } + + @Bean + public DocumentService documentService(EfilingDocumentService efilingDocumentService) { + return new DocumentServiceImpl(efilingDocumentService); + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentService.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentService.java new file mode 100644 index 0000000000..31890cc76a --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentService.java @@ -0,0 +1,17 @@ +package ca.bc.gov.open.jag.efilingapi.document; + +import ca.bc.gov.open.jag.efilingapi.document.models.GetValidDocumentTypesRequest; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; + +import java.util.List; + +public interface DocumentService { + + /** + * Returns a list of valid document types + * @param getValidDocumentTypesRequest + * @return + */ + List getValidDocumentTypes(GetValidDocumentTypesRequest getValidDocumentTypesRequest); + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentServiceImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentServiceImpl.java new file mode 100644 index 0000000000..420deedbe7 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentServiceImpl.java @@ -0,0 +1,22 @@ +package ca.bc.gov.open.jag.efilingapi.document; + +import ca.bc.gov.open.jag.efilingapi.document.models.GetValidDocumentTypesRequest; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; + +import java.util.List; + +public class DocumentServiceImpl implements DocumentService { + + private final EfilingDocumentService efilingDocumentService; + + public DocumentServiceImpl(EfilingDocumentService efilingDocumentService) { + this.efilingDocumentService = efilingDocumentService; + } + + @Override + public List getValidDocumentTypes(GetValidDocumentTypesRequest getValidDocumentTypesRequest) { + return efilingDocumentService.getDocumentTypes(getValidDocumentTypesRequest.getCourtLevel(), getValidDocumentTypesRequest.getCourtClassification()); + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentStore.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentStore.java new file mode 100644 index 0000000000..972c6302dd --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentStore.java @@ -0,0 +1,26 @@ +package ca.bc.gov.open.jag.efilingapi.document; + +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionKey; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; + +import java.util.List; + +public interface DocumentStore { + + byte[] put(SubmissionKey submissionKey, String fileName, byte[] content); + + byte[] get(SubmissionKey submissionKey, String fileName); + + void evict(SubmissionKey submissionKey, String fileName); + + DocumentTypeDetails getDocumentDetails(String courtLevel, String courtClass, String documentType); + + List getDocumentTypes(String courtLevel, String courtClass); + + byte[] putRushDocument(SubmissionKey submissionKey, String fileName, byte[] content); + + byte[] getRushDocument(SubmissionKey submissionKey, String fileName); + + void evictRushDocument(SubmissionKey submissionKey, String fileName); + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentStoreImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentStoreImpl.java new file mode 100644 index 0000000000..de1ed81b96 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/DocumentStoreImpl.java @@ -0,0 +1,68 @@ +package ca.bc.gov.open.jag.efilingapi.document; + +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionKey; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; + +import java.util.List; + +public class DocumentStoreImpl implements DocumentStore { + + private final EfilingDocumentService efilingDocumentService; + + public DocumentStoreImpl(EfilingDocumentService efilingDocumentService) { + this.efilingDocumentService = efilingDocumentService; + } + + @Override + @CachePut(cacheNames = "document", key = "{ #submissionKey.universalId, #submissionKey.submissionId, #submissionKey.transactionId, #fileName }", cacheManager = "documentCacheManager") + public byte[] put(SubmissionKey submissionKey, String fileName, byte[] content) { + return content; + } + + @Override + @Cacheable(cacheNames = "document", key = "{ #submissionKey.universalId, #submissionKey.submissionId, #submissionKey.transactionId, #fileName }", cacheManager = "documentCacheManager", unless = "#result == null") + public byte[] get(SubmissionKey submissionKey, String fileName) { + return null; + } + + @Override + @CacheEvict(cacheNames = "document", key = "{ #submissionKey.universalId, #submissionKey.submissionId, #submissionKey.transactionId, #fileName }", cacheManager = "documentCacheManager") + public void evict(SubmissionKey submissionKey, String fileName) { + //This implements Redis delete no code required + } + + @Override + @Cacheable(cacheNames = "documentDetails", cacheManager = "documentTypeDetailsCacheManager", unless = "#result == null") + public DocumentTypeDetails getDocumentDetails(String courtLevel, String courtClass, String documentType) { + return this.efilingDocumentService.getDocumentTypeDetails(courtLevel, courtClass, documentType); + } + + @Override + public List getDocumentTypes(String courtLevel, String courtClass) { + return this.efilingDocumentService.getDocumentTypes(courtLevel, courtClass); + } + + @Override + @CachePut(cacheNames = "rushDocument", key = "{ #submissionKey.universalId, #submissionKey.submissionId, #submissionKey.transactionId, #fileName }", cacheManager = "documentCacheManager") + public byte[] putRushDocument(SubmissionKey submissionKey, String fileName, byte[] content) { + return content; + } + + @Override + @Cacheable(cacheNames = "rushDocument", key = "{ #submissionKey.universalId, #submissionKey.submissionId, #submissionKey.transactionId, #fileName }", cacheManager = "documentCacheManager", unless = "#result == null") + public byte[] getRushDocument(SubmissionKey submissionKey, String fileName) { + return null; + } + + @Override + @CacheEvict(cacheNames = "rushDocument", key = "{ #submissionKey.universalId, #submissionKey.submissionId, #submissionKey.transactionId, #fileName }", cacheManager = "documentCacheManager") + public void evictRushDocument(SubmissionKey submissionKey, String fileName) { + //This implements Redis delete no code required + } + + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/models/GetValidDocumentTypesRequest.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/models/GetValidDocumentTypesRequest.java new file mode 100644 index 0000000000..9cd879cc06 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/document/models/GetValidDocumentTypesRequest.java @@ -0,0 +1,45 @@ +package ca.bc.gov.open.jag.efilingapi.document.models; + +public class GetValidDocumentTypesRequest { + private String courtLevel; + private String courtClassification; + + public String getCourtLevel() { + return courtLevel; + } + + public String getCourtClassification() { + return courtClassification; + } + + public GetValidDocumentTypesRequest(Builder builder) { + this.courtLevel = builder.courtLevel; + this.courtClassification = builder.courtClassification; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private String courtLevel; + private String courtClassification; + + public Builder courtClassification(String courtClassification) { + this.courtClassification = courtClassification; + return this; + } + + public Builder courtLevel(String courtLevel) { + this.courtLevel = courtLevel; + return this; + } + + public GetValidDocumentTypesRequest create() { + return new GetValidDocumentTypesRequest(this); + } + + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/AccountException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/AccountException.java new file mode 100644 index 0000000000..3c3c2a077d --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/AccountException.java @@ -0,0 +1,9 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class AccountException extends EfilingException { + private static final long serialVersionUID = 1L; + + public AccountException(String message) { + super(message, ErrorCode.ACCOUNTEXCEPTION); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/CacheException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/CacheException.java new file mode 100644 index 0000000000..7ce7916b56 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/CacheException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class CacheException extends EfilingException { + public CacheException(String message) { + super(message, ErrorCode.CACHE_ERROR); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/CourtLocationException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/CourtLocationException.java new file mode 100644 index 0000000000..dbd9d0d0b2 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/CourtLocationException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class CourtLocationException extends EfilingException { + public CourtLocationException(String message) { + super(message,ErrorCode.COURT_LOCATION_ERROR); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/CreateAccountException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/CreateAccountException.java new file mode 100644 index 0000000000..d88986de4a --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/CreateAccountException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class CreateAccountException extends EfilingException { + public CreateAccountException(String message) { + super(message, ErrorCode.CREATE_ACCOUNT_EXCEPTION); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/DeleteDocumentException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/DeleteDocumentException.java new file mode 100644 index 0000000000..cb6e74488c --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/DeleteDocumentException.java @@ -0,0 +1,18 @@ +package ca.bc.gov.open.jag.efilingapi.error; + + +import org.springframework.http.HttpStatus; + +public class DeleteDocumentException extends EfilingException { + + private final HttpStatus httpStatus; + + public DeleteDocumentException(String message, HttpStatus httpStatus) { + super(message, ErrorCode.DELETE_DOCUMENT_ERROR); + this.httpStatus = httpStatus; + } + + public HttpStatus getHttpStatus() { + return httpStatus; + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/DocumentRequiredException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/DocumentRequiredException.java new file mode 100644 index 0000000000..aa45eb8dcd --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/DocumentRequiredException.java @@ -0,0 +1,8 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class DocumentRequiredException extends EfilingException { + + public DocumentRequiredException(String message) { + super(message, ErrorCode.DOCUMENT_REQUIRED); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/DocumentStorageException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/DocumentStorageException.java new file mode 100644 index 0000000000..16449c1aa6 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/DocumentStorageException.java @@ -0,0 +1,8 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class DocumentStorageException extends EfilingException { + + public DocumentStorageException(String message) { + super(message, ErrorCode.DOCUMENT_STORAGE_FAILURE); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/DocumentTypeException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/DocumentTypeException.java new file mode 100644 index 0000000000..23ac01a2e5 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/DocumentTypeException.java @@ -0,0 +1,8 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class DocumentTypeException extends EfilingException { + + public DocumentTypeException(String message) { + super(message, ErrorCode.DOCUMENT_TYPE_ERROR); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/EfilingException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/EfilingException.java new file mode 100644 index 0000000000..87c431ce7d --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/EfilingException.java @@ -0,0 +1,17 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class EfilingException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + private final ErrorCode errorCode; + + public EfilingException(String message, ErrorCode errorCode) { + super(message); + this.errorCode = errorCode; + } + + public String getErrorCode() { + return errorCode.name(); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/ErrorCode.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/ErrorCode.java new file mode 100644 index 0000000000..f5cbf85252 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/ErrorCode.java @@ -0,0 +1,25 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public enum ErrorCode { + ACCOUNTEXCEPTION, + CACHE_ERROR, + CREATE_ACCOUNT_EXCEPTION, + COURT_LOCATION_ERROR, + DELETE_DOCUMENT_ERROR, + DOCUMENT_REQUIRED, + DOCUMENT_STORAGE_FAILURE, + DOCUMENT_TYPE_ERROR, + FILE_TYPE_ERROR, + FILING_PACKAGE_NOT_FOUND, + INVALIDROLE, + INVALIDUNIVERSAL, + INVALID_INITIAL_SUBMISSION_PAYLOAD, + MISSING_APPLICATION_CODE, + MISSING_UNIVERSAL_ID, + MISSING_REGISTRY_NOTICE, + MISSING_IDENTITY_PROVIDER, + PAYMENT_FAILURE, + SUBMISSION_FAILURE, + UPDATE_CLIENT_EXCEPTION, + URL_GENERATION_FAILURE +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/ErrorResponse.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/ErrorResponse.java deleted file mode 100644 index 6de9285371..0000000000 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/ErrorResponse.java +++ /dev/null @@ -1,20 +0,0 @@ -package ca.bc.gov.open.jag.efilingapi.error; - -public enum ErrorResponse { - INVALIDROLE("User does not have a valid role for this request."), - ACCOUNTEXCEPTION("Client has multiple CSO profiles."), - GETPROFILESEXCEPTION("Calling CSO accountFacade.getProfiles caused an exception."), - CACHE_ERROR("Cache related error."); - - private final String errorMessage; - - ErrorResponse(String errorMessage) { - this.errorMessage = errorMessage; - } - - public String getErrorCode() { - return this.toString(); - } - - public String getErrorMessage() { return errorMessage; } -} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/ExceptionControllerAdvisor.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/ExceptionControllerAdvisor.java new file mode 100644 index 0000000000..9a337b4e36 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/ExceptionControllerAdvisor.java @@ -0,0 +1,127 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +import ca.bc.gov.open.jag.efilingapi.api.model.EfilingError; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +@ControllerAdvice +public class ExceptionControllerAdvisor { + + @ExceptionHandler(AccountException.class) + public ResponseEntity handleAccountException(AccountException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(CacheException.class) + public ResponseEntity handleCacheException(CacheException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler(CourtLocationException.class) + public ResponseEntity handleCourtLocationException(CourtLocationException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler(CreateAccountException.class) + public ResponseEntity handleCreateAccountException(CreateAccountException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler(DeleteDocumentException.class) + public ResponseEntity handleDeleteDocumentException(DeleteDocumentException ex) { + return new ResponseEntity<>(getEfilingError(ex), ex.getHttpStatus()); + } + + @ExceptionHandler(DocumentRequiredException.class) + public ResponseEntity handleDocumentRequiredException(DocumentRequiredException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(DocumentStorageException.class) + public ResponseEntity handleDocumentStorageException(DocumentStorageException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.BAD_GATEWAY); + } + + @ExceptionHandler(DocumentTypeException.class) + public ResponseEntity handleDocumentTypeException(DocumentTypeException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler(FileTypeException.class) + public ResponseEntity handleFileTypeException(FileTypeException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(InvalidInitialSubmissionPayloadException.class) + public ResponseEntity handleInvalidInitialSubmissionPayloadException(InvalidInitialSubmissionPayloadException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(InvalidRoleException.class) + public ResponseEntity handleInvalidRoleException(InvalidRoleException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.FORBIDDEN); + } + + @ExceptionHandler(InvalidUniversalException.class) + public ResponseEntity handleInvalidUniversalException(InvalidUniversalException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.FORBIDDEN); + } + + @ExceptionHandler(MissingApplicationCodeException.class) + public ResponseEntity handleMissingApplicationCodeException(MissingApplicationCodeException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.FORBIDDEN); + } + + @ExceptionHandler(MissingIdentityProviderException.class) + public ResponseEntity handleMissingIdentityProviderException(MissingIdentityProviderException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.FORBIDDEN); + } + + @ExceptionHandler(MissingUniversalIdException.class) + public ResponseEntity handleMissingUniversalIdException(MissingUniversalIdException ex) { + return new ResponseEntity<>(getEfilingError(ex) , HttpStatus.FORBIDDEN); + } + + @ExceptionHandler(PaymentException.class) + public ResponseEntity handlePaymentException(PaymentException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(SubmissionException.class) + public ResponseEntity handleSubmissionException(SubmissionException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler(UpdateClientException.class) + public ResponseEntity handleUpdateClientException(UpdateClientException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler(UrlGenerationException.class) + public ResponseEntity handleUrlGenerationException(UrlGenerationException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler(FilingPackageNotFoundException.class) + public ResponseEntity handleFilingPackageNotFoundException(FilingPackageNotFoundException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.NOT_FOUND); + } + + @ExceptionHandler(NoRegistryNoticeException.class) + public ResponseEntity handleNoRegistryNoticeException(NoRegistryNoticeException ex) { + return new ResponseEntity<>(getEfilingError(ex), HttpStatus.BAD_REQUEST); + } + + private EfilingError getEfilingError(EfilingException ex) { + EfilingError efilingError = new EfilingError(); + efilingError.setError(ex.getErrorCode()); + efilingError.setMessage(ex.getMessage()); + + if (ex instanceof InvalidInitialSubmissionPayloadException) { + efilingError.setDetails(((InvalidInitialSubmissionPayloadException) ex).getDetails()); + } + return efilingError; + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/FileTypeException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/FileTypeException.java new file mode 100644 index 0000000000..47742f0973 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/FileTypeException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class FileTypeException extends EfilingException { + public FileTypeException(String message) { + super(message, ErrorCode.FILE_TYPE_ERROR); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/FilingPackageNotFoundException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/FilingPackageNotFoundException.java new file mode 100644 index 0000000000..d083a7b5bf --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/FilingPackageNotFoundException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class FilingPackageNotFoundException extends EfilingException { + public FilingPackageNotFoundException(String message) { + super(message,ErrorCode.FILING_PACKAGE_NOT_FOUND); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/InvalidInitialSubmissionPayloadException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/InvalidInitialSubmissionPayloadException.java new file mode 100644 index 0000000000..74462e986f --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/InvalidInitialSubmissionPayloadException.java @@ -0,0 +1,17 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +import java.util.List; + +public class InvalidInitialSubmissionPayloadException extends EfilingException { + + private final List details; + + public InvalidInitialSubmissionPayloadException(String message, List details) { + super(message, ErrorCode.INVALID_INITIAL_SUBMISSION_PAYLOAD); + this.details = details; + } + + public List getDetails() { + return details; + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/InvalidRoleException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/InvalidRoleException.java new file mode 100644 index 0000000000..885a124860 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/InvalidRoleException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class InvalidRoleException extends EfilingException { + public InvalidRoleException(String message) { + super(message, ErrorCode.INVALIDROLE); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/InvalidUniversalException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/InvalidUniversalException.java new file mode 100644 index 0000000000..fd87401b90 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/InvalidUniversalException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class InvalidUniversalException extends EfilingException { + public InvalidUniversalException(String message) { + super(message, ErrorCode.INVALIDUNIVERSAL); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/MissingApplicationCodeException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/MissingApplicationCodeException.java new file mode 100644 index 0000000000..297a87232e --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/MissingApplicationCodeException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class MissingApplicationCodeException extends EfilingException { + public MissingApplicationCodeException(String message) { + super(message, ErrorCode.MISSING_APPLICATION_CODE); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/MissingIdentityProviderException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/MissingIdentityProviderException.java new file mode 100644 index 0000000000..a922b3eb2e --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/MissingIdentityProviderException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class MissingIdentityProviderException extends EfilingException { + public MissingIdentityProviderException(String message) { + super(message, ErrorCode.MISSING_IDENTITY_PROVIDER); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/MissingUniversalIdException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/MissingUniversalIdException.java new file mode 100644 index 0000000000..89027dfcbb --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/MissingUniversalIdException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class MissingUniversalIdException extends EfilingException { + public MissingUniversalIdException(String message) { + super(message, ErrorCode.MISSING_UNIVERSAL_ID); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/NoRegistryNoticeException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/NoRegistryNoticeException.java new file mode 100644 index 0000000000..fdb219562f --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/NoRegistryNoticeException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class NoRegistryNoticeException extends EfilingException { + public NoRegistryNoticeException(String message) { + super(message, ErrorCode.MISSING_REGISTRY_NOTICE); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/PaymentException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/PaymentException.java new file mode 100644 index 0000000000..4fc0284b28 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/PaymentException.java @@ -0,0 +1,8 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class PaymentException extends EfilingException { + + public PaymentException(String message) { + super(message, ErrorCode.PAYMENT_FAILURE); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/SubmissionException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/SubmissionException.java new file mode 100644 index 0000000000..9c74037745 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/SubmissionException.java @@ -0,0 +1,8 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class SubmissionException extends EfilingException { + + public SubmissionException(String message) { + super(message, ErrorCode.SUBMISSION_FAILURE); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/UpdateClientException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/UpdateClientException.java new file mode 100644 index 0000000000..b99fbb6134 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/UpdateClientException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class UpdateClientException extends EfilingException { + public UpdateClientException(String message) { + super(message, ErrorCode.UPDATE_CLIENT_EXCEPTION); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/UrlGenerationException.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/UrlGenerationException.java new file mode 100644 index 0000000000..eb4246cfd2 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/error/UrlGenerationException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +public class UrlGenerationException extends EfilingException { + public UrlGenerationException(String message) { + super(message, ErrorCode.URL_GENERATION_FAILURE); + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/FeeService.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/FeeService.java deleted file mode 100644 index 0753ccfd66..0000000000 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/FeeService.java +++ /dev/null @@ -1,13 +0,0 @@ -package ca.bc.gov.open.jag.efilingapi.fee; - -import ca.bc.gov.open.jag.efilingapi.fee.models.Fee; -import ca.bc.gov.open.jag.efilingapi.fee.models.FeeRequest; - -/** - * A FeeService interface that provides services - */ -public interface FeeService { - - Fee getFee(FeeRequest feeRequest); - -} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/MockFeeService.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/MockFeeService.java deleted file mode 100644 index d1dd841a9b..0000000000 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/MockFeeService.java +++ /dev/null @@ -1,15 +0,0 @@ -package ca.bc.gov.open.jag.efilingapi.fee; - -import ca.bc.gov.open.jag.efilingapi.fee.models.Fee; -import ca.bc.gov.open.jag.efilingapi.fee.models.FeeRequest; - -import java.math.BigDecimal; - -public class MockFeeService implements FeeService { - - @Override - public Fee getFee(FeeRequest feeRequest) { - return new Fee(new BigDecimal(7)); - } - -} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/models/Config.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/models/Config.java deleted file mode 100644 index 4440d8574b..0000000000 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/models/Config.java +++ /dev/null @@ -1,16 +0,0 @@ -package ca.bc.gov.open.jag.efilingapi.fee.models; - -import ca.bc.gov.open.jag.efilingapi.fee.FeeService; -import ca.bc.gov.open.jag.efilingapi.fee.MockFeeService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class Config { - - @Bean - public FeeService feeService() { - return new MockFeeService(); - } - -} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/models/Fee.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/models/Fee.java deleted file mode 100644 index 5259e27f43..0000000000 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/models/Fee.java +++ /dev/null @@ -1,24 +0,0 @@ -package ca.bc.gov.open.jag.efilingapi.fee.models; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.math.BigDecimal; - -/** - * Represents a fee structure - */ -public class Fee { - - private BigDecimal amount; - - @JsonCreator - public Fee(@JsonProperty("amount") BigDecimal amount) { - this.amount = amount; - } - - public BigDecimal getAmount() { - return amount; - } - -} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/models/FeeRequest.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/models/FeeRequest.java deleted file mode 100644 index 8ab8b4f6f3..0000000000 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/fee/models/FeeRequest.java +++ /dev/null @@ -1,24 +0,0 @@ -package ca.bc.gov.open.jag.efilingapi.fee.models; - -/** - * Represent a request to get a fee - */ -public class FeeRequest { - - private String documentType; - private String documentSubType; - - public FeeRequest(String documentType, String documentSubType) { - this.documentType = documentType; - this.documentSubType = documentSubType; - } - - public String getDocumentType() { - return documentType; - } - - public String getDocumentSubType() { - return documentSubType; - } - -} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/FilingPackageConfig.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/FilingPackageConfig.java new file mode 100644 index 0000000000..4786a227f0 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/FilingPackageConfig.java @@ -0,0 +1,31 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage; + + +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.filingpackage.mapper.ActionRequiredDetailsMapperImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.mapper.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.properties.ParentProperties; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageServiceImpl; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties({ParentProperties.class}) +public class FilingPackageConfig { + + private final ParentProperties parentProperties; + + public FilingPackageConfig(ParentProperties parentProperties) { + this.parentProperties = parentProperties; + } + + @Bean + public FilingPackageService filePackageService(EfilingReviewService efilingReviewService, EfilingDocumentService efilingDocumentService, AccountService accountService) { + return new FilingPackageServiceImpl(efilingReviewService, efilingDocumentService, accountService, new FilingPackageMapperImpl(), new ActionRequiredDetailsMapperImpl(), parentProperties); + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/FilingpackageApiDelegateImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/FilingpackageApiDelegateImpl.java new file mode 100644 index 0000000000..18a3bdb1ab --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/FilingpackageApiDelegateImpl.java @@ -0,0 +1,241 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage; + +import ca.bc.gov.open.jag.efilingapi.Keys; +import ca.bc.gov.open.jag.efilingapi.api.FilingpackagesApiDelegate; +import ca.bc.gov.open.jag.efilingapi.api.model.ActionRequiredDetails; +import ca.bc.gov.open.jag.efilingapi.api.model.FilingPackage; +import ca.bc.gov.open.jag.efilingapi.api.model.ParentAppDetails; +import ca.bc.gov.open.jag.efilingapi.core.security.SecurityUtils; +import ca.bc.gov.open.jag.efilingapi.error.DeleteDocumentException; +import ca.bc.gov.open.jag.efilingapi.error.FilingPackageNotFoundException; +import ca.bc.gov.open.jag.efilingapi.error.MissingUniversalIdException; +import ca.bc.gov.open.jag.efilingapi.filingpackage.model.SubmittedDocument; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingAccountServiceException; +import ca.bc.gov.open.jag.efilingcommons.submission.models.ReportRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.ReportsTypes; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.text.MessageFormat; +import java.util.List; +import java.util.Optional; + +@Service +public class FilingpackageApiDelegateImpl implements FilingpackagesApiDelegate { + + private static final String DELETE_DOCUMENT_ERROR = "Document deletion failed."; + private static final String FILING_PACKAGE_NOT_FOUND = "Requested filing package was not found."; + private static final String MISSING_UNIVERSAL_ID = "universal-id claim missing in jwt token."; + + private final FilingPackageService filingPackageService; + Logger logger = LoggerFactory.getLogger(FilingpackageApiDelegateImpl.class); + + public FilingpackageApiDelegateImpl(FilingPackageService filingPackageService) { + this.filingPackageService = filingPackageService; + } + + + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity getFilingPackage(BigDecimal packageIdentifier) { + + logger.info("get filing package request received"); + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) + throw new MissingUniversalIdException(MISSING_UNIVERSAL_ID); + + Optional result = filingPackageService.getCSOFilingPackage(universalId.get(), packageIdentifier); + + return result.map(ResponseEntity::ok).orElseThrow(() -> new FilingPackageNotFoundException(FILING_PACKAGE_NOT_FOUND)); + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity> getFilingPackages(String parentApplication) { + + logger.info("get filing packages request received"); + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) + throw new MissingUniversalIdException(MISSING_UNIVERSAL_ID); + + Optional> result = filingPackageService.getFilingPackages(universalId.get(), parentApplication); + + return result.map(ResponseEntity::ok).orElseThrow(() -> new FilingPackageNotFoundException(FILING_PACKAGE_NOT_FOUND)); + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity getSubmissionSheet(BigDecimal packageIdentifier) { + + logger.info("get submission sheet request received"); + + return getReport(ReportRequest.builder() + .report(ReportsTypes.SUBMISSION_SHEET) + .packageId(packageIdentifier) + .fileName(Keys.EFILING_SUBMISSION_SHEET_FILENAME).create()); + + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity getPaymentReceipt(BigDecimal packageIdentifier) { + + logger.info("get payment receipt request received"); + + return getReport(ReportRequest.builder() + .report(ReportsTypes.PAYMENT_RECEIPT) + .packageId(packageIdentifier) + .fileName(Keys.EFILING_PAYMENT_RECEIPT_FILENAME).create()); + + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity getRegistryNotice(BigDecimal packageIdentifier) { + + logger.info("get registry notice request received"); + + return getReport(ReportRequest.builder() + .report(ReportsTypes.REGISTRY_NOTICE) + .packageId(packageIdentifier) + .fileName(Keys.EFILING_REGISTRY_NOTICE_FILENAME).create()); + + } + + private ResponseEntity getReport(ReportRequest reportRequest) { + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) return new ResponseEntity<>(HttpStatus.FORBIDDEN); + + //Add a universal id + reportRequest.setUniversalId(universalId.get()); + + Optional result = filingPackageService.getReport(reportRequest); + + if(!result.isPresent()) return new ResponseEntity<>(HttpStatus.NOT_FOUND); + + HttpHeaders header = new HttpHeaders(); + header.add(HttpHeaders.CONTENT_DISPOSITION, MessageFormat.format("attachment; filename={0}", result.get().getFilename())); + + return ResponseEntity.ok() + .headers(header) + .body(result.get()); + + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity getSubmittedDocument(BigDecimal packageIdentifier, + BigDecimal documentIdentifier) { + + logger.info("get document request received"); + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) return new ResponseEntity<>(HttpStatus.FORBIDDEN); + + Optional result = filingPackageService.getSubmittedDocument(universalId.get(), packageIdentifier, documentIdentifier); + + if(!result.isPresent()) return new ResponseEntity<>(HttpStatus.NOT_FOUND); + + HttpHeaders header = new HttpHeaders(); + header.add(HttpHeaders.CONTENT_DISPOSITION, MessageFormat.format("attachment; filename={0}",result.get().getName())); + + return ResponseEntity.ok() + .headers(header) + .body(result.get().getData()); + + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity deleteSubmittedDocument(BigDecimal packageIdentifier, String documentIdentifier) { + + logger.info("delete document request received"); + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) + throw new MissingUniversalIdException(MISSING_UNIVERSAL_ID); + + try { + filingPackageService.deleteSubmittedDocument(universalId.get(), packageIdentifier, documentIdentifier); + return ResponseEntity.ok().build(); + } catch (EfilingAccountServiceException e) { + throw new DeleteDocumentException(DELETE_DOCUMENT_ERROR, HttpStatus.NOT_FOUND); + } catch (Exception e) { + throw new DeleteDocumentException(DELETE_DOCUMENT_ERROR, HttpStatus.BAD_REQUEST); + } + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity getRushDocument(BigDecimal packageIdentifier, String fileName) { + + logger.info("get rush document request received"); + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) return new ResponseEntity<>(HttpStatus.FORBIDDEN); + + Optional result = filingPackageService.getRushDocument(universalId.get(), packageIdentifier, fileName); + + if(!result.isPresent()) return new ResponseEntity<>(HttpStatus.NOT_FOUND); + + HttpHeaders header = new HttpHeaders(); + header.add(HttpHeaders.CONTENT_DISPOSITION, MessageFormat.format("attachment; filename={0}",result.get().getName())); + + return ResponseEntity.ok() + .headers(header) + .body(result.get().getData()); + + } + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity getActionRequiredDetails(BigDecimal packageIdentifier) { + + logger.info("get action required details request received"); + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) + throw new MissingUniversalIdException(MISSING_UNIVERSAL_ID); + + Optional result = filingPackageService.getActionRequiredDetails(universalId.get(), packageIdentifier); + + return result.map(ResponseEntity::ok).orElseThrow(() -> new FilingPackageNotFoundException(FILING_PACKAGE_NOT_FOUND)); + + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity getParentDetails(BigDecimal packageIdentifier) { + + logger.info("get parent details request"); + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) + throw new MissingUniversalIdException(MISSING_UNIVERSAL_ID); + + Optional result = filingPackageService.getParentDetails(universalId.get(), packageIdentifier); + + return result.map(ResponseEntity::ok).orElseThrow(() -> new FilingPackageNotFoundException(FILING_PACKAGE_NOT_FOUND)); + + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/mapper/ActionRequiredDetailsMapper.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/mapper/ActionRequiredDetailsMapper.java new file mode 100644 index 0000000000..ba33de845a --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/mapper/ActionRequiredDetailsMapper.java @@ -0,0 +1,26 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.mapper; + +import ca.bc.gov.open.jag.efilingapi.api.model.ActionDocument; +import ca.bc.gov.open.jag.efilingapi.api.model.ActionRequiredDetails; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewDocument; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewFilingPackage; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +import java.math.BigDecimal; +import java.util.List; + +@Mapper +public interface ActionRequiredDetailsMapper { + + @Mapping(target = "clientId", source = "clientId") + @Mapping(target = "documents", source = "actionDocuments") + @Mapping(target = "packageIdentifier", source = "filingPackage.packageNo") + ActionRequiredDetails toActionRequiredDetails(ReviewFilingPackage filingPackage, BigDecimal clientId, List actionDocuments); + + @Mapping(target = "id", source = "documentId") + @Mapping(target = "type", source = "documentTypeCd") + @Mapping(target = "status", source = "statusCode") + ActionDocument toActionDocument(ReviewDocument file); + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/mapper/FilingPackageMapper.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/mapper/FilingPackageMapper.java new file mode 100644 index 0000000000..dcfbb9e866 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/mapper/FilingPackageMapper.java @@ -0,0 +1,97 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.mapper; + +import ca.bc.gov.open.jag.efilingapi.api.model.*; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.PackagePayment; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewDocument; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewFilingPackage; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewRushOrder; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +import java.util.List; + + +@Mapper +public interface FilingPackageMapper { + + @Mapping(target = "court.fileNumber", source = "court.fileNumber") + @Mapping(target = "court.courtClass", source = "court.courtClass") + @Mapping(target = "court.level", source = "court.level") + @Mapping(target = "court.levelDescription", source = "court.levelDescription") + @Mapping(target = "court.division", source = "court.division") + @Mapping(target = "court.participatingClass", source = "court.participatingClass") + @Mapping(target = "court.location", source = "court.locationName") + @Mapping(target = "court.agencyId", source = "court.locationId") + @Mapping(target = "court.locationDescription", source = "court.locationDescription") + @Mapping(target = "court.classDescription", source = "court.classDescription") + @Mapping(target = "submittedBy.firstName", source = "firstName") + @Mapping(target = "submittedBy.lastName", source = "lastName") + @Mapping(target = "submittedDate", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.toIsoDate(filingPackage.getSubmittedDate()))") + @Mapping(target = "packageNumber", source = "packageNo") + @Mapping(target = "filingComments", source = "filingCommentsTxt") + @Mapping(target = "status", source = "status") + @Mapping(target = "links.packageHistoryUrl", source = "packageLinks.packageHistoryUrl") + @Mapping(target = "organizationParties", source = "organizations") + @Mapping(target = "rush", source = "rushOrder") + FilingPackage toResponseFilingPackage(ReviewFilingPackage filingPackage); + + List toDocuments(List file); + + @Mapping(target = "identifier", source = "documentId") + @Mapping(target = "documentId", source = "parentDocumentId") + @Mapping(target = "documentProperties.name", source = "fileName") + @Mapping(target = "documentProperties.type", source = "documentTypeCd") + @Mapping(target = "description", source = "documentType") + @Mapping(target = "filingDate", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.toIsoDate(file.getDateFiled()))") + @Mapping(target = "status.description", source = "status") + @Mapping(target = "status.code", source = "statusCode") + @Mapping(target = "status.changeDate", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.toIsoDate(reviewDocument.getStatusDate()))") + @Mapping(target = "paymentProcessed", source = "paymentProcessed") + @Mapping(target = "rushRequired", source = "rushRequired") + Document toDocument(ReviewDocument file); + + List toParties(List parties); + + @Mapping(target = "partyDescription", source = "partyTypeDesc") + @Mapping(target = "roleType", source = "roleTypeCd") + @Mapping(target = "roleDescription", source = "roleTypeDesc") + Individual toParty(ca.bc.gov.open.jag.efilingcommons.model.Individual individual); + + List toOrganizationParties(List organizations); + + @Mapping(target = "partyDescription", source = "partyTypeDesc") + @Mapping(target = "roleType", source = "roleTypeCd") + @Mapping(target = "roleDescription", source = "roleTypeDesc") + Organization toOrganization(ca.bc.gov.open.jag.efilingcommons.model.Organization organization); + + List toPayments(List payments); + + @Mapping(target = "feeExempt", source = "feeExmpt") + @Mapping(target = "paymentCategory", source = "paymentCategory") + @Mapping(target = "paymentDescription", source = "transactionDesc") + @Mapping(target = "processedAmount", source = "processedAmt") + @Mapping(target = "submittedAmount", source = "submittedAmt") + @Mapping(target = "serviceIdentifier", source = "serviceId") + @Mapping(target = "transactionDate", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.toIsoDate(payment.getTransactionDtm()))") + Payment toPayment(PackagePayment payment); + + @Mapping(target = "reason", source = "rushFilingReasonTxt") + @Mapping(target = "rushType", expression = "java(ca.bc.gov.open.jag.efilingapi.filingpackage.util.RushMappingUtils.getRushType(reviewRushOrder.getProcessReasonCd()))") + @Mapping(target = "status", source = "currentStatusDsc") + @Mapping(target = "email", source = "contactEmailTxt") + @Mapping(target = "firstName", source = "contactFirstGivenNm") + @Mapping(target = "organization", source = "contactOrganizationNm") + @Mapping(target = "phoneNumber", source = "contactPhoneNo") + @Mapping(target = "lastName", source = "contactSurnameNm") + @Mapping(target = "countryCode", source = "ctryId") + @Mapping(target = "country", source = "countryDsc") + @Mapping(target = "statusReason", source = "processingCommentTxt") + @Mapping(target = "courtDate", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.toIsoDate(reviewRushOrder.getCourtOrderDt()))") + @Mapping(target = "supportingDocuments", source = "supportDocs") + Rush toRush(ReviewRushOrder reviewRushOrder); + + @Mapping(target = "fileName", source = "clientFileNm") + @Mapping(target = "identifier", source = "objectGuid") + RushDocument toRushDocument(ca.bc.gov.open.jag.efilingcommons.submission.models.review.RushDocument rushDocument); + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/model/SubmittedDocument.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/model/SubmittedDocument.java new file mode 100644 index 0000000000..7c0cf080d4 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/model/SubmittedDocument.java @@ -0,0 +1,46 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.model; + +import org.springframework.core.io.Resource; + +public class SubmittedDocument { + private String name; + private Resource data; + + public String getName() { + return name; + } + + public Resource getData() { + return data; + } + + public SubmittedDocument(SubmittedDocument.Builder builder) { + this.name = builder.name; + this.data = builder.data; + } + + public static SubmittedDocument.Builder builder() { + return new SubmittedDocument.Builder(); + } + + public static class Builder { + + private String name; + private Resource data; + + + public SubmittedDocument.Builder name(String name) { + this.name = name; + return this; + } + + public SubmittedDocument.Builder data(Resource data) { + this.data = data; + return this; + } + + public SubmittedDocument create() { + return new SubmittedDocument(this); + } + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/properties/ParentAppProperties.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/properties/ParentAppProperties.java new file mode 100644 index 0000000000..12a5349e25 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/properties/ParentAppProperties.java @@ -0,0 +1,21 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.properties; + +public class ParentAppProperties { + + private String application; + private String returnUrl; + private Boolean rejectedDocuments; + + public String getApplication() { return application; } + + public void setApplication(String application) { this.application = application; } + + public String getReturnUrl() { return returnUrl; } + + public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } + + public Boolean getRejectedDocuments() { return rejectedDocuments; } + + public void setRejectedDocuments(Boolean rejectedDocuments) { this.rejectedDocuments = rejectedDocuments; } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/properties/ParentProperties.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/properties/ParentProperties.java new file mode 100644 index 0000000000..90221c1c59 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/properties/ParentProperties.java @@ -0,0 +1,16 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.List; + +@ConfigurationProperties(prefix = "parents") +public class ParentProperties { + + private List parents; + + public List getParents() { return parents; } + + public void setParents(List parents) { this.parents = parents; } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/FilingPackageService.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/FilingPackageService.java new file mode 100644 index 0000000000..f92ab5bac1 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/FilingPackageService.java @@ -0,0 +1,51 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.service; + +import ca.bc.gov.open.jag.efilingapi.api.model.ActionRequiredDetails; +import ca.bc.gov.open.jag.efilingapi.api.model.FilingPackage; +import ca.bc.gov.open.jag.efilingapi.api.model.ParentAppDetails; +import ca.bc.gov.open.jag.efilingapi.filingpackage.model.SubmittedDocument; +import ca.bc.gov.open.jag.efilingcommons.submission.models.ReportRequest; +import org.springframework.core.io.Resource; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Optional; + +public interface FilingPackageService { + + Optional getCSOFilingPackage(String universalId, BigDecimal packageNumber); + + Optional> getFilingPackages(String universalId, String parentApplication); + + Optional getReport(ReportRequest reportRequest); + + Optional getSubmittedDocument(String universalId, BigDecimal packageNumber, BigDecimal documentIdentifier); + + void deleteSubmittedDocument(String universalId, BigDecimal packageNumber, String documentIdentifier); + + /** + * Get the required details for a package that requires action + * @param universalId authorized users universal id + * @param packageNumber requested package identifier + * @return the action details for given user and package + */ + Optional getActionRequiredDetails(String universalId, BigDecimal packageNumber); + + /** + * Get the file related to the record + * @param universalId authorized users universal id + * @param packageNumber requested package identifier + * @param fileName required fileName + * @return the byte array and meta associated with the document + */ + Optional getRushDocument(String universalId, BigDecimal packageNumber, String fileName); + + /** + * Get the parent app features for a package + * @param universalId authorized users universal id + * @param packageNumber requested package identifier + * @return feature for the packages parent application + */ + Optional getParentDetails(String universalId, BigDecimal packageNumber); + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/FilingPackageServiceImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/FilingPackageServiceImpl.java new file mode 100644 index 0000000000..3c7fdde85d --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/FilingPackageServiceImpl.java @@ -0,0 +1,234 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.service; + +import ca.bc.gov.open.jag.efilingapi.Keys; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.ActionRequiredDetails; +import ca.bc.gov.open.jag.efilingapi.api.model.FilingPackage; +import ca.bc.gov.open.jag.efilingapi.api.model.ParentAppDetails; +import ca.bc.gov.open.jag.efilingapi.error.NoRegistryNoticeException; +import ca.bc.gov.open.jag.efilingapi.filingpackage.mapper.ActionRequiredDetailsMapper; +import ca.bc.gov.open.jag.efilingapi.filingpackage.mapper.FilingPackageMapper; +import ca.bc.gov.open.jag.efilingapi.filingpackage.model.SubmittedDocument; +import ca.bc.gov.open.jag.efilingapi.filingpackage.properties.ParentAppProperties; +import ca.bc.gov.open.jag.efilingapi.filingpackage.properties.ParentProperties; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingAccountServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.RushDocumentRequest; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.DeleteSubmissionDocumentRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackageRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.ReportRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewDocument; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewFilingPackage; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.RushDocument; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.Resource; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +public class FilingPackageServiceImpl implements FilingPackageService { + + private final EfilingReviewService efilingReviewService; + + private final EfilingDocumentService efilingDocumentService; + + private final AccountService accountService; + + private final FilingPackageMapper filingPackageMapper; + + private final ActionRequiredDetailsMapper actionRequiredDetailsMapper; + + private final ParentProperties parentProperties; + + public FilingPackageServiceImpl(EfilingReviewService efilingReviewService, EfilingDocumentService efilingDocumentService, AccountService accountService, FilingPackageMapper filingPackageMapper, ActionRequiredDetailsMapper actionRequiredDetailsMapper, ParentProperties parentProperties) { + this.efilingReviewService = efilingReviewService; + this.efilingDocumentService = efilingDocumentService; + this.accountService = accountService; + this.filingPackageMapper = filingPackageMapper; + this.actionRequiredDetailsMapper = actionRequiredDetailsMapper; + this.parentProperties = parentProperties; + } + + + @Override + public Optional getCSOFilingPackage(String universalId, BigDecimal packageNumber) { + + Optional request = buildFilingPackageRequest(universalId, packageNumber, null); + + if (!request.isPresent()) return Optional.empty(); + + Optional filingPackage = efilingReviewService.findStatusByPackage(request.get()); + + if (!filingPackage.isPresent()) return Optional.empty(); + + filingPackage.get().getDocuments().forEach( + reviewDocument -> reviewDocument.setRushRequired(efilingDocumentService.getDocumentTypeDetails(filingPackage.get().getCourt().getLevel(),filingPackage.get().getCourt().getCourtClass(), reviewDocument.getDocumentTypeCd()).isRushRequired()) + ); + + return filingPackage.map(filingPackageMapper::toResponseFilingPackage); + + } + + @Override + public Optional> getFilingPackages(String universalId, String parentApplication) { + + Optional request = buildFilingPackageRequest(universalId, null, parentApplication); + + if (!request.isPresent()) return Optional.empty(); + + List result = efilingReviewService.findStatusByClient(request.get()); + + if (result == null || result.isEmpty()) return Optional.empty(); + + return Optional.of(result.stream() + .map(filingPackageMapper::toResponseFilingPackage) + .collect(Collectors.toList())); + + } + + @Override + public Optional getReport(ReportRequest reportRequest) { + + Optional filingPackage = getFilingPackage(reportRequest.getUniversalId(), reportRequest.getPackageId()); + + if (!filingPackage.isPresent()) return Optional.empty(); + + Optional result = efilingReviewService.getReport(reportRequest); + + if (!result.isPresent()) return Optional.empty(); + + Resource resource = new ByteArrayResource(result.get()) { + @Override + public String getFilename() { + return reportRequest.getFileName(); + } + }; + + return Optional.of(resource); + + } + + @Override + public Optional getSubmittedDocument(String universalId, BigDecimal packageNumber, BigDecimal documentIdentifier) { + + Optional filingPackage = getFilingPackage(universalId, packageNumber); + + if (!filingPackage.isPresent()) return Optional.empty(); + + Optional reviewDocument = filingPackage.get().getDocuments().stream().filter(document -> document.getDocumentId().equals(documentIdentifier.toString())).findFirst(); + + if (!reviewDocument.isPresent()) return Optional.empty(); + + Optional document = efilingReviewService.getSubmittedDocument(documentIdentifier); + + return document.map(bytes -> SubmittedDocument.builder() + .name(reviewDocument.get().getFileName()) + .data(new ByteArrayResource(bytes)) + .create()); + + } + + @Override + public void deleteSubmittedDocument(String universalId, BigDecimal packageNumber, String documentIdentifier) { + + AccountDetails accountDetails = accountService.getCsoAccountDetails(universalId); + + if (accountDetails.getClientId() == null) throw new EfilingAccountServiceException("Account not found"); + + efilingReviewService.deleteSubmittedDocument(new DeleteSubmissionDocumentRequest(accountDetails.getClientId(), packageNumber, null, documentIdentifier)); + + } + + @Override + public Optional getActionRequiredDetails(String universalId, BigDecimal packageNumber) { + + Optional request = buildFilingPackageRequest(universalId, packageNumber, null); + + if (!request.isPresent()) return Optional.empty(); + + Optional filingPackage = efilingReviewService.findStatusByPackage(request.get()); + + if (!filingPackage.isPresent()) return Optional.empty(); + + if (Boolean.FALSE.equals(filingPackage.get().getHasRegistryNotice())) throw new NoRegistryNoticeException("This package does not have a registry notice"); + + //For phase one of enhancements rejected document are the only ones included. + return Optional.of(actionRequiredDetailsMapper.toActionRequiredDetails(filingPackage.get(), + request.get().getClientId(), + filingPackage.get().getDocuments().stream() + .filter(reviewDocument -> reviewDocument.getStatusCode().equalsIgnoreCase(Keys.REJECTED_DOCUMENT_CODE)) + .map(actionRequiredDetailsMapper::toActionDocument) + .collect(Collectors.toList()))); + + } + + @Override + public Optional getRushDocument(String universalId, BigDecimal packageNumber, String fileName) { + + Optional filingPackage = getFilingPackage(universalId, packageNumber); + + if (!filingPackage.isPresent()) return Optional.empty(); + + Optional reviewDocument = filingPackage.get().getRushOrder().getSupportDocs().stream().filter(document -> document.getClientFileNm().equals(fileName)).findFirst(); + + if (!reviewDocument.isPresent()) return Optional.empty(); + + Optional document = efilingReviewService.getRushDocument(RushDocumentRequest.builder() + .procReqId(reviewDocument.get().getProcessRequestId()) + .docSeqNo(reviewDocument.get().getProcessSupportDocSeqNo()) + .procItemSeqNo(reviewDocument.get().getProcessItemSeqNo()) + .create()); + + return document.map(bytes -> SubmittedDocument.builder() + .name(reviewDocument.get().getClientFileNm()) + .data(new ByteArrayResource(bytes)) + .create()); + + } + + @Override + public Optional getParentDetails(String universalId, BigDecimal packageNumber) { + + Optional filingPackage = getFilingPackage(universalId, packageNumber); + + if (!filingPackage.isPresent()) return Optional.empty(); + + Optional parentAppProperties = parentProperties.getParents().stream() + .filter(parentApp -> parentApp.getApplication().equalsIgnoreCase(filingPackage.get().getApplicationCode())) + .findFirst(); + + if (!parentAppProperties.isPresent()) return Optional.empty(); + + ParentAppDetails parentAppDetails = new ParentAppDetails(); + + parentAppDetails.setRejectedDocumentFeature(parentAppProperties.get().getRejectedDocuments()); + parentAppDetails.setReturnUrl(parentAppProperties.get().getReturnUrl()); + + return Optional.of(parentAppDetails); + + } + + private Optional buildFilingPackageRequest(String universalId, BigDecimal packageNumber, String parentApplication) { + + AccountDetails accountDetails = accountService.getCsoAccountDetails(universalId); + + if (accountDetails.getClientId() == null) return Optional.empty(); + + return Optional.of(new FilingPackageRequest(accountDetails.getClientId(), accountDetails.getAccountId(), packageNumber, parentApplication)); + + } + + private Optional getFilingPackage(String universalId, BigDecimal packageNumber) { + Optional request = buildFilingPackageRequest(universalId, packageNumber, null); + + if (!request.isPresent()) return Optional.empty(); + + return efilingReviewService.findStatusByPackage(request.get()); + + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/util/RushMappingUtils.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/util/RushMappingUtils.java new file mode 100644 index 0000000000..c92f2c7a7a --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/filingpackage/util/RushMappingUtils.java @@ -0,0 +1,28 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.util; + +import ca.bc.gov.open.jag.efilingapi.api.model.Rush; + +public class RushMappingUtils { + + private RushMappingUtils() {} + + public static Rush.RushTypeEnum getRushType(String code) { + + if (code == null) return null; + + switch (code.toUpperCase()) { + case "CRTD": + return Rush.RushTypeEnum.COURT; + case "CRTR": + return Rush.RushTypeEnum.RULE; + case "OTHR": + return Rush.RushTypeEnum.OTHER; + case "PRO": + return Rush.RushTypeEnum.PRO; + default: + return null; + } + + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/lookup/CountriesApiDelegateImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/lookup/CountriesApiDelegateImpl.java new file mode 100644 index 0000000000..4ac11feda3 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/lookup/CountriesApiDelegateImpl.java @@ -0,0 +1,44 @@ +package ca.bc.gov.open.jag.efilingapi.lookup; + +import ca.bc.gov.open.jag.efilingapi.api.CountriesApiDelegate; +import ca.bc.gov.open.jag.efilingapi.api.model.CountryCode; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.LookupItem; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class CountriesApiDelegateImpl implements CountriesApiDelegate { + + Logger logger = LoggerFactory.getLogger(CountriesApiDelegateImpl.class); + + private final EfilingLookupService efilingLookupService; + + public CountriesApiDelegateImpl(EfilingLookupService efilingLookupService) { + this.efilingLookupService = efilingLookupService; + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity> getCountries() { + + logger.info("Get countries list request received"); + + return ResponseEntity.ok(efilingLookupService.getCountries().stream() + .map(this::createCountryCode) + .collect(Collectors.toList())); + } + + private CountryCode createCountryCode(LookupItem item) { + CountryCode countryCode = new CountryCode(); + countryCode.setCode(item.getCode()); + countryCode.setDescription(item.getDescription()); + return countryCode; + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/payment/PaymentApiDelegateImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/payment/PaymentApiDelegateImpl.java new file mode 100644 index 0000000000..bff48e13b5 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/payment/PaymentApiDelegateImpl.java @@ -0,0 +1,50 @@ +package ca.bc.gov.open.jag.efilingapi.payment; + +import ca.bc.gov.open.bambora.payment.starter.BamboraException; +import ca.bc.gov.open.bambora.payment.starter.managment.BamboraCardService; +import ca.bc.gov.open.bambora.payment.starter.managment.models.RecurringPaymentDetails; +import ca.bc.gov.open.jag.efilingapi.api.PaymentApiDelegate; +import ca.bc.gov.open.jag.efilingapi.api.model.GenerateCardUrlRequest; +import ca.bc.gov.open.jag.efilingapi.api.model.GenerateCardUrlResponse; +import ca.bc.gov.open.jag.efilingapi.error.UrlGenerationException; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; + +import java.text.MessageFormat; +import java.util.UUID; + +@Service +public class PaymentApiDelegateImpl implements PaymentApiDelegate { + + private static final String URL_GENERATION_FAILURE = "failed to generate bambora card update url."; + + private final BamboraCardService bamboraCardService; + + private final EfilingAccountService efilingAccountService; + + public PaymentApiDelegateImpl(BamboraCardService bamboraCardService, EfilingAccountService efilingAccountService) { + this.bamboraCardService = bamboraCardService; + this.efilingAccountService = efilingAccountService; + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity updateCreditCard(UUID xTransactionId, GenerateCardUrlRequest generateCardUrlRequest) { + + GenerateCardUrlResponse generateCardUrlResponse = new GenerateCardUrlResponse(); + try { + generateCardUrlResponse.setBamboraUrl(bamboraCardService.setupRecurringPayment(RecurringPaymentDetails.builder() + .orderNumber(MessageFormat.format("C{0}", efilingAccountService.getOrderNumber())) + .echoData("customerCode") + .redirectURL(generateCardUrlRequest.getRedirectUrl()) + .endUserId(generateCardUrlRequest.getInternalClientNumber()) + .create()).toString()); + return ResponseEntity.ok(generateCardUrlResponse); + } catch (BamboraException e) { + throw new UrlGenerationException(URL_GENERATION_FAILURE); + } + + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/SubmissionApiDelegateImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/SubmissionApiDelegateImpl.java index 9251b39ca1..42d86856bc 100644 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/SubmissionApiDelegateImpl.java +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/SubmissionApiDelegateImpl.java @@ -1,23 +1,44 @@ package ca.bc.gov.open.jag.efilingapi.submission; +import ca.bc.gov.open.clamav.starter.ClamAvService; +import ca.bc.gov.open.clamav.starter.VirusDetectedException; +import ca.bc.gov.open.jag.efilingapi.Keys; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; import ca.bc.gov.open.jag.efilingapi.api.SubmissionApiDelegate; import ca.bc.gov.open.jag.efilingapi.api.model.*; import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; -import ca.bc.gov.open.jag.efilingapi.error.ErrorResponse; +import ca.bc.gov.open.jag.efilingapi.core.security.SecurityUtils; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.error.*; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapper; import ca.bc.gov.open.jag.efilingapi.submission.mappers.GenerateUrlResponseMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.RushProcessingMapper; import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; -import ca.bc.gov.open.jag.efilingcommons.exceptions.CSOHasMultipleAccountException; -import ca.bc.gov.open.jag.efilingcommons.exceptions.InvalidAccountStateException; -import ca.bc.gov.open.jag.efilingcommons.exceptions.StoreException; +import ca.bc.gov.open.jag.efilingapi.submission.validator.GenerateUrlRequestValidator; +import ca.bc.gov.open.jag.efilingapi.utils.Notification; +import ca.bc.gov.open.jag.efilingapi.utils.TikaAnalysis; +import ca.bc.gov.open.jag.efilingcommons.exceptions.*; +import ca.bc.gov.open.jag.efilingcommons.model.RushProcessing; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.MDC; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.Resource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.text.MessageFormat; +import java.util.List; import java.util.Optional; import java.util.UUID; @@ -25,53 +46,233 @@ @EnableConfigurationProperties(NavigationProperties.class) public class SubmissionApiDelegateImpl implements SubmissionApiDelegate { + private static final String ACCOUNT_EXCEPTION = "Client has multiple CSO profiles."; + private static final String CACHE_ERROR = "Cache related error."; + private static final String DOCUMENT_REQUIRED = "At least one document is required."; + private static final String DOCUMENT_STORAGE_FAILURE = "An unknown error happened while storing documents."; + private static final String DOCUMENT_TYPE_ERROR = "Error while retrieving documents."; + private static final String FILE_TYPE_EXCEPTION = "File is not a PDF."; + private static final String INVALID_INITIAL_SUBMISSION_PAYLOAD = "Initial Submission payload invalid, find more in the details array."; + private static final String INVALID_UNIVERSAL_ID = "Invalid universal id."; + private static final String INVALID_ROLE = "User does not have a valid role for this request."; + private static final String MISSING_APPLICATION_CODE = "Missing application code claim. Contact administrator."; + private static final String MISSING_UNIVERSAL_ID = "universal-id claim missing in jwt token."; + private static final String PAYMENT_FAILURE = "Error while making payment."; + private static final String SUBMISSION_FAILURE = "Error while submitting filing package."; + private static final String UNIVERSAL_ID_IS_REQUIRED = "universal Id is required."; + Logger logger = LoggerFactory.getLogger(SubmissionApiDelegateImpl.class); private final SubmissionService submissionService; - private final SubmissionStore submissionStore; - + private final AccountService accountService; private final GenerateUrlResponseMapper generateUrlResponseMapper; - private final NavigationProperties navigationProperties; - + private final DocumentStore documentStore; + private final ClamAvService clamAvService; + private final FilingPackageMapper filingPackageMapper; + private final GenerateUrlRequestValidator generateUrlRequestValidator; + private final RushProcessingMapper rushProcessingMapper; public SubmissionApiDelegateImpl( SubmissionService submissionService, + AccountService accountService, GenerateUrlResponseMapper generateUrlResponseMapper, NavigationProperties navigationProperties, - SubmissionStore submissionStore) { + SubmissionStore submissionStore, DocumentStore documentStore, ClamAvService clamAvService, FilingPackageMapper filingPackageMapper, GenerateUrlRequestValidator generateUrlRequestValidator, RushProcessingMapper rushProcessingMapper) { this.submissionService = submissionService; + this.accountService = accountService; this.generateUrlResponseMapper = generateUrlResponseMapper; this.navigationProperties = navigationProperties; this.submissionStore = submissionStore; + this.documentStore = documentStore; + this.clamAvService = clamAvService; + this.filingPackageMapper = filingPackageMapper; + this.generateUrlRequestValidator = generateUrlRequestValidator; + this.rushProcessingMapper = rushProcessingMapper; + } + + @Override + @PreAuthorize("hasRole('efiling-client') || hasRole('efiling-admin')") + public ResponseEntity uploadSubmissionDocuments(UUID xTransactionId, String xUserId, List files) { + + if(StringUtils.isBlank(xUserId)) { + logger.error(UNIVERSAL_ID_IS_REQUIRED); + throw new InvalidUniversalException(INVALID_UNIVERSAL_ID); + } + + SubmissionKey submissionKey = new SubmissionKey( + xUserId, + xTransactionId, + UUID.randomUUID()); + + logger.info("attempting to upload original document [{}]", submissionKey.getSubmissionId()); + + ResponseEntity response = storeDocuments(submissionKey, files, false); + + logger.info("successfully uploaded original document [{}]", submissionKey.getSubmissionId()); + + return response; + } @Override - public ResponseEntity generateUrl(UUID xAuthUserId, - GenerateUrlRequest generateUrlRequest) { - logger.info("Generate Url Request Received"); + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity uploadAdditionalSubmissionDocuments(UUID submissionId, UUID xTransactionId, List files) { + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) { + + logger.error(UNIVERSAL_ID_IS_REQUIRED); + throw new InvalidUniversalException(INVALID_UNIVERSAL_ID); + + } + + SubmissionKey submissionKey = new SubmissionKey(universalId.get(), xTransactionId, submissionId); + + Optional fromCacheSubmission = this.submissionStore.get(submissionKey); + + if (!fromCacheSubmission.isPresent()) + return ResponseEntity.notFound().build(); + + logger.info("attempting to upload new document for transaction [{}]", submissionId); + + ResponseEntity responseEntity = storeDocuments(submissionKey, files, false); + + logger.info("successfully uploaded new document for transaction [{}]", submissionId); + + return responseEntity; + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity updateDocumentProperties(UUID submissionId, UUID + xTransactionId, UpdateDocumentRequest updateDocumentRequest) { + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) { + + logger.error(UNIVERSAL_ID_IS_REQUIRED); + throw new InvalidUniversalException(INVALID_UNIVERSAL_ID); + + } + + logger.info("attempting to add new document for transaction [{}]", submissionId); + + if (updateDocumentRequest == null || updateDocumentRequest.getDocuments().isEmpty()) + throw new DocumentRequiredException(DOCUMENT_REQUIRED); + + SubmissionKey submissionKey = new SubmissionKey(universalId.get(), xTransactionId, submissionId); + + Optional fromCacheSubmission = this.submissionStore.get(submissionKey); + + if (!fromCacheSubmission.isPresent()) + return ResponseEntity.notFound().build(); + + try { + + Submission submission = submissionService.updateDocuments(fromCacheSubmission.get(), updateDocumentRequest, submissionKey); + UpdateDocumentResponse updateDocumentResponse = new UpdateDocumentResponse(); + SubmissionFilingPackage filingPackage = filingPackageMapper.toApiFilingPackage(submission.getFilingPackage()); + updateDocumentResponse.setDocuments(filingPackage.getDocuments()); + logger.info("successfully added new document for transaction [{}]", submissionId); + return ResponseEntity.ok(updateDocumentResponse); + + } catch (EfilingDocumentServiceException e) { + + logger.warn(e.getMessage(), e); + throw new DocumentTypeException(DOCUMENT_TYPE_ERROR); + + } + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity getSubmissionDocument(UUID xTransactionId, + UUID submissionId, + String filename) { + + + logger.info("getSubmission document for transaction [{}]", xTransactionId); + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) { + + logger.error(UNIVERSAL_ID_IS_REQUIRED); + throw new InvalidUniversalException(INVALID_UNIVERSAL_ID); + + } + + SubmissionKey submissionKey = new SubmissionKey(universalId.get(), xTransactionId, submissionId); + + byte[] bytes = documentStore.get(submissionKey, filename); + + if (bytes == null) return ResponseEntity.notFound().build(); + + logger.info("successfully retrieved document for transaction [{}]", xTransactionId); + + return ResponseEntity.ok(new ByteArrayResource(bytes)); + + } + + @Override + @PreAuthorize("hasRole('efiling-client') || hasRole('efiling-admin')") + public ResponseEntity generateUrl(UUID xTransactionId, String xUserId, UUID submissionId, GenerateUrlRequest generateUrlRequest) { + + logger.info("Attempting to generate Url Request Received"); + + logger.info("Message recieved from client App [{}]", generateUrlRequest.getClientAppName()); + + if (StringUtils.isBlank(xUserId)) { + + logger.error(UNIVERSAL_ID_IS_REQUIRED); + throw new InvalidUniversalException(INVALID_UNIVERSAL_ID); + + } + + Optional applicationCode = SecurityUtils.getApplicationCode(); + + if (!applicationCode.isPresent()) { + + logger.error("[{}]: {}", ErrorCode.MISSING_APPLICATION_CODE.toString(), MISSING_APPLICATION_CODE); + throw new MissingApplicationCodeException(MISSING_APPLICATION_CODE); + + } + + Notification validation = generateUrlRequestValidator.validate(generateUrlRequest, applicationCode.get(), xUserId); + + if (validation.hasError()) + throw new InvalidInitialSubmissionPayloadException(INVALID_INITIAL_SUBMISSION_PAYLOAD, validation.getErrors()); + + if (accountService.getCsoAccountDetails(xUserId) != null && + !accountService.getCsoAccountDetails(xUserId).isFileRolePresent()) + throw new InvalidRoleException(INVALID_ROLE); + + SubmissionKey submissionKey = new SubmissionKey(xUserId, xTransactionId, submissionId); ResponseEntity response; try { response = ResponseEntity.ok( generateUrlResponseMapper.toGenerateUrlResponse( - submissionService.generateFromRequest(xAuthUserId, generateUrlRequest), + submissionService.generateFromRequest(applicationCode.get(), submissionKey, generateUrlRequest), navigationProperties.getBaseUrl())); logger.info("successfully generated return url."); - } - catch (CSOHasMultipleAccountException e) { + } catch (CSOHasMultipleAccountException e) { logger.warn(e.getMessage(), e); - response = new ResponseEntity(buildEfilingError(ErrorResponse.ACCOUNTEXCEPTION), HttpStatus.BAD_REQUEST); - } - catch (InvalidAccountStateException e) { + throw new AccountException(ACCOUNT_EXCEPTION); + } catch (InvalidAccountStateException e) { logger.warn(e.getMessage(), e); - response = new ResponseEntity(buildEfilingError(ErrorResponse.INVALIDROLE), HttpStatus.FORBIDDEN); - } - catch (StoreException e) { + throw new InvalidRoleException(INVALID_ROLE); + } catch (EfilingDocumentServiceException e) { + logger.warn(e.getMessage(), e); + throw new DocumentTypeException(DOCUMENT_TYPE_ERROR); + } catch (StoreException e) { logger.warn(e.getMessage(), e); - response = new ResponseEntity(buildEfilingError(ErrorResponse.CACHE_ERROR), HttpStatus.INTERNAL_SERVER_ERROR); + throw new CacheException(CACHE_ERROR); } return response; @@ -79,60 +280,247 @@ public ResponseEntity generateUrl(UUID xAuthUserId, } @Override - public ResponseEntity getSubmission(UUID id) { + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity getSubmissionConfig(UUID submissionId, UUID xTransactionId) { - Optional fromCacheSubmission = this.submissionStore.getByKey(id); + Optional universalId = SecurityUtils.getUniversalIdFromContext(); - if(!fromCacheSubmission.isPresent()) + if (!universalId.isPresent()) { + + logger.error(UNIVERSAL_ID_IS_REQUIRED); + throw new MissingUniversalIdException(MISSING_UNIVERSAL_ID); + + } + + SubmissionKey submissionKey = new SubmissionKey(universalId.get(), xTransactionId, submissionId); + + logger.info("attempting to get Submission for transactionId [{}]", xTransactionId); + + Optional fromCacheSubmission = this.submissionStore.get(submissionKey); + + if (!fromCacheSubmission.isPresent()) return ResponseEntity.notFound().build(); - GetSubmissionResponse response = new GetSubmissionResponse(); + GetSubmissionConfigResponse response = new GetSubmissionConfigResponse(); + + response.setClientAppName(fromCacheSubmission.get().getClientAppName()); - response.setUserDetails(buildUserDetails(fromCacheSubmission.get())); + response.setNavigationUrls(fromCacheSubmission.get().getNavigationUrls()); - response.setNavigation(fromCacheSubmission.get().getNavigation()); + response.setCsoBaseUrl(navigationProperties.getCsoBaseUrl()); + + logger.info("Successfully retrieved submission for transactionId [{}]", xTransactionId); return ResponseEntity.ok(response); } - private UserDetails buildUserDetails(Submission submission) { + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity getSubmissionFilingPackage(UUID xTransactionId, UUID submissionId) { - UserDetails userDetails = new UserDetails(); + Optional universalId = SecurityUtils.getUniversalIdFromContext(); - if(submission.getAccountDetails() != null) { + if(!universalId.isPresent()) { - if(submission.getAccountDetails().isFileRolePresent()) { - Account account = new Account(); - account.setType(Account.TypeEnum.CSO); - account.setIdentifier(submission.getAccountDetails().getAccountId().toString()); - userDetails.addAccountsItem(account); - } + logger.error(UNIVERSAL_ID_IS_REQUIRED); + throw new InvalidUniversalException(INVALID_UNIVERSAL_ID); + + } + + SubmissionKey submissionKey = new SubmissionKey(universalId.get(), xTransactionId, submissionId); + + logger.info("attempting to get Submission Filing Package for transactionId [{}]", xTransactionId); + + Optional fromCacheSubmission = this.submissionStore.get(submissionKey); + + if (!fromCacheSubmission.isPresent()) + return ResponseEntity.notFound().build(); + + logger.info("successfully retrieved submission filing package for transactionId [{}]", xTransactionId); + + SubmissionFilingPackage submissionFilingPackage = filingPackageMapper.toApiFilingPackage(fromCacheSubmission.get().getFilingPackage()); + + submissionFilingPackage.getDocuments().forEach( + submissionDocument -> submissionDocument.setRushRequired(submissionService.isRushRequired(submissionDocument.getType(),submissionFilingPackage.getCourt().getLevel(),submissionFilingPackage.getCourt().getCourtClass())) + ); + + return ResponseEntity.ok(submissionFilingPackage); + + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity deleteSubmission(UUID submissionId, UUID xTransactionId) { - userDetails.setFirstName(submission.getAccountDetails().getFirstName()); - userDetails.setLastName(submission.getAccountDetails().getLastName()); - userDetails.setMiddleName(submission.getAccountDetails().getMiddleName()); - userDetails.setEmail(submission.getAccountDetails().getEmail()); + Optional universalId = SecurityUtils.getUniversalIdFromContext(); - } else { + if(!universalId.isPresent()) { - userDetails.setFirstName("firstName"); - userDetails.setLastName("lastName"); - userDetails.setMiddleName("middleName"); - userDetails.setEmail("email"); + logger.error(UNIVERSAL_ID_IS_REQUIRED); + throw new InvalidUniversalException(INVALID_UNIVERSAL_ID); } - return userDetails; + SubmissionKey submissionKey = new SubmissionKey(universalId.get(), xTransactionId, submissionId); + + Optional fromCacheSubmission = this.submissionStore.get(submissionKey); + if(!fromCacheSubmission.isPresent()) + return ResponseEntity.notFound().build(); + //Remove documents from cache + if (fromCacheSubmission.get().getFilingPackage() != null && fromCacheSubmission.get().getFilingPackage().getDocuments() != null) + fromCacheSubmission.get().getFilingPackage().getDocuments().forEach( + document -> documentStore.evict(submissionKey, document.getName())); + + //Remove submission from cache + submissionStore.evict(submissionKey); + return new ResponseEntity<>(HttpStatus.OK); } + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity submit(UUID xTransactionId, UUID submissionId, Object body) { + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) { + + logger.error(UNIVERSAL_ID_IS_REQUIRED); + throw new InvalidUniversalException(INVALID_UNIVERSAL_ID); + + } + + SubmissionKey submissionKey = new SubmissionKey(universalId.get(), xTransactionId, submissionId); + + logger.info("attempting to submit efiling package for transaction [{}]", xTransactionId); + + Optional fromCacheSubmission = this.submissionStore.get(submissionKey); + + if (!fromCacheSubmission.isPresent()) + return ResponseEntity.notFound().build(); + ResponseEntity response; + MDC.put(Keys.MDC_EFILING_SUBMISSION_ID, submissionId.toString()); + try { + + SubmitResponse result = submissionService.createSubmission(fromCacheSubmission.get(), accountService.getCsoAccountDetails(submissionKey.getUniversalId()), SecurityUtils.isEarlyAdopter()); + + response = new ResponseEntity(result, HttpStatus.CREATED); + logger.info("successfully submitted efiling package for transaction [{}], cso id {}", xTransactionId, result.getPackageRef()); + + } catch (EfilingSubmissionServiceException e) { + logger.error("failed package submission {}", xTransactionId); + throw new SubmissionException(SUBMISSION_FAILURE); + + } catch (EfilingPaymentException e) { + logger.error("payment failure during package submission {}", xTransactionId); + throw new PaymentException(PAYMENT_FAILURE); + + } finally { + this.submissionStore.evict(submissionKey); + } - public EfilingError buildEfilingError(ErrorResponse errorResponse) { - EfilingError response = new EfilingError(); - response.setError(errorResponse.getErrorCode()); - response.setMessage(errorResponse.getErrorMessage()); return response; } + private ResponseEntity storeDocuments(SubmissionKey submissionKey, List files, boolean rush) { + + if (files == null || files.isEmpty()) + throw new DocumentRequiredException(DOCUMENT_REQUIRED); + + try { + + for (MultipartFile file : files) { + try { + clamAvService.scan(new ByteArrayInputStream(file.getBytes())); + } catch (VirusDetectedException e) { + throw new DocumentStorageException(DOCUMENT_STORAGE_FAILURE); + } + + if (!TikaAnalysis.isPdf(file)) + throw new FileTypeException(FILE_TYPE_EXCEPTION); + } + for (MultipartFile file : files) { + if (!rush) { + documentStore.put(submissionKey, file.getResource().getFilename(), file.getBytes()); + } else { + documentStore.putRushDocument(submissionKey, file.getResource().getFilename(), file.getBytes()); + } + } + + } catch (IOException e) { + throw new DocumentStorageException(DOCUMENT_STORAGE_FAILURE); + } + + logger.info("{} stored in cache", files.size()); + + return ResponseEntity.ok(new UploadSubmissionDocumentsResponse().submissionId(submissionKey.getSubmissionId()).received(new BigDecimal(files.size()))); + + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity postRushProcessing(UUID xTransactionId, UUID submissionId, Rush rush) { + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) { + + logger.error(UNIVERSAL_ID_IS_REQUIRED); + throw new InvalidUniversalException(INVALID_UNIVERSAL_ID); + + } + + SubmissionKey submissionKey = new SubmissionKey(universalId.get(), xTransactionId, submissionId); + + logger.info("attempting to add rush processing to efiling package for transaction [{}]", xTransactionId); + + Optional fromCacheSubmission = this.submissionStore.get(submissionKey); + + if (!fromCacheSubmission.isPresent()) + return ResponseEntity.notFound().build(); + + MDC.put(Keys.MDC_EFILING_SUBMISSION_ID, submissionId.toString()); + + RushProcessing rushProcessing = rushProcessingMapper.toRushProcessing(rush); + //Set filenames here values not present in mapper + rushProcessing.getSupportingDocuments().forEach( + document -> document.setServerFileName(MessageFormat.format("fh_{0}_{1}_{2}", submissionKey.getSubmissionId(), submissionKey.getTransactionId(), document.getName()) + )); + + fromCacheSubmission.get().getFilingPackage().setRush(rushProcessing); + + submissionStore.put(fromCacheSubmission.get()); + + return ResponseEntity.created(null).build(); + + } + + @Override + @PreAuthorize("hasRole('efiling-user')") + public ResponseEntity uploadRushDocuments(UUID submissionId, UUID xTransactionId, List files) { + + Optional universalId = SecurityUtils.getUniversalIdFromContext(); + + if(!universalId.isPresent()) { + + logger.error(UNIVERSAL_ID_IS_REQUIRED); + throw new InvalidUniversalException(INVALID_UNIVERSAL_ID); + + } + + SubmissionKey submissionKey = new SubmissionKey( + universalId.get(), + xTransactionId, + submissionId); + + logger.info("attempting to upload rush document [{}]", submissionKey.getSubmissionId()); + + ResponseEntity response = storeDocuments(submissionKey, files, true); + + logger.info("successfully uploaded rush document [{}]", submissionKey.getSubmissionId()); + + return response; + + } } diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/SubmissionConfig.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/SubmissionConfig.java index 7df66cabf1..7b4b52d081 100644 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/SubmissionConfig.java +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/SubmissionConfig.java @@ -1,13 +1,23 @@ package ca.bc.gov.open.jag.efilingapi.submission; -import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; -import ca.bc.gov.open.jag.efilingapi.fee.FeeService; -import ca.bc.gov.open.jag.efilingapi.submission.mappers.SubmissionMapper; -import ca.bc.gov.open.jag.efilingapi.submission.mappers.SubmissionMapperImpl; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.court.services.CourtService; +import ca.bc.gov.open.jag.efilingapi.document.DocumentService; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.*; import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionServiceImpl; import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStoreImpl; +import ca.bc.gov.open.jag.efilingapi.submission.validator.GenerateUrlRequestValidator; +import ca.bc.gov.open.jag.efilingapi.submission.validator.GenerateUrlRequestValidatorImpl; +import ca.bc.gov.open.jag.efilingcommons.payment.PaymentAdapter; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingCourtService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSubmissionService; +import ca.bc.gov.open.sftp.starter.SftpService; import org.springframework.boot.autoconfigure.cache.CacheProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -16,9 +26,11 @@ public class SubmissionConfig { private final CacheProperties cacheProperties; + private final NavigationProperties navigationProperties; - public SubmissionConfig(CacheProperties cacheProperties) { + public SubmissionConfig(CacheProperties cacheProperties, NavigationProperties navigationProperties) { this.cacheProperties = cacheProperties; + this.navigationProperties = navigationProperties; } @Bean @@ -31,18 +43,42 @@ public SubmissionMapper submissionMapper() { return new SubmissionMapperImpl(); } + @Bean + public FilingPackageMapper filingPackageApiMapper() { return new FilingPackageMapperImpl(); } + + @Bean + public RushProcessingMapper rushProcessingMapper() { return new RushProcessingMapperImpl(); } + + @Bean + public PartyMapper partyMapper() { return new PartyMapperImpl(); } + @Bean public SubmissionService submissionService(SubmissionStore submissionStore, SubmissionMapper submissionMapper, - EfilingAccountService efilingAccountService, - FeeService feeService) { + EfilingLookupService efilingLookupService, + EfilingCourtService efilingCourtService, + EfilingSubmissionService efilingSubmissionService, + EfilingDocumentService efilingDocumentService, + DocumentStore documentStore, + PaymentAdapter paymentAdapter, + SftpService sftpService, PartyMapper partyMapper) { return new SubmissionServiceImpl(submissionStore, cacheProperties, submissionMapper, - efilingAccountService, - feeService); + partyMapper, + efilingLookupService, + efilingCourtService, + efilingSubmissionService, + efilingDocumentService, documentStore, + paymentAdapter, + sftpService, + navigationProperties); + } + @Bean + public GenerateUrlRequestValidator packageValidator(SubmissionService submissionService, CourtService courtService, DocumentService documentService, FilingPackageService filingPackageService) { + return new GenerateUrlRequestValidatorImpl(submissionService, courtService, documentService, filingPackageService); } } diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/SubmissionKey.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/SubmissionKey.java new file mode 100644 index 0000000000..2d153ff3a3 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/SubmissionKey.java @@ -0,0 +1,30 @@ +package ca.bc.gov.open.jag.efilingapi.submission; + +import ca.bc.gov.open.jag.efilingapi.utils.UniversalIdUtils; + +import java.util.UUID; + +public class SubmissionKey { + + private String universalId; + private UUID transactionId; + private UUID submissionId; + + public SubmissionKey(String universalId, UUID transactionId, UUID submissionId) { + this.universalId = UniversalIdUtils.sanitizeUniversalId(universalId); + this.transactionId = transactionId; + this.submissionId = submissionId; + } + + public String getUniversalId() { + return universalId; + } + + public UUID getTransactionId() { + return transactionId; + } + + public UUID getSubmissionId() { + return submissionId; + } +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/FilingPackageMapper.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/FilingPackageMapper.java new file mode 100644 index 0000000000..0c413e6ee8 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/FilingPackageMapper.java @@ -0,0 +1,27 @@ +package ca.bc.gov.open.jag.efilingapi.submission.mappers; + +import ca.bc.gov.open.jag.efilingapi.api.model.InitialPackage; +import ca.bc.gov.open.jag.efilingapi.api.model.RushDocument; +import ca.bc.gov.open.jag.efilingapi.api.model.SubmissionDocument; +import ca.bc.gov.open.jag.efilingcommons.model.Document; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper +public interface FilingPackageMapper { + + FilingPackage toFilingPackage(InitialPackage filingPackage); + + FilingPackage toFilingPackage(ca.bc.gov.open.jag.efilingapi.api.model.FilingPackage filingPackage); + + ca.bc.gov.open.jag.efilingapi.api.model.SubmissionFilingPackage toApiFilingPackage(FilingPackage filingPackage); + + @Mapping(target = "documentProperties.name", source = "name") + @Mapping(target = "documentProperties.type", source = "type") + SubmissionDocument documentToSubmissionDocument(Document file); + + @Mapping(target = "fileName", source = "name") + RushDocument documentToRushDocument(Document file); + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/GenerateUrlResponseMapper.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/GenerateUrlResponseMapper.java index 542c28f1c6..2a3a290d9e 100644 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/GenerateUrlResponseMapper.java +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/GenerateUrlResponseMapper.java @@ -5,22 +5,22 @@ import org.mapstruct.*; import java.text.MessageFormat; -import java.util.UUID; @Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR) public interface GenerateUrlResponseMapper { @Mapping(source = "expiryDate", target = "expiryDate") - @Mapping(target = "efilingUrl", source = "submission.id", qualifiedByName = "submissionIdToUrl") + @Mapping(target = "efilingUrl", source = "submission", qualifiedByName = "submissionIdToUrl") GenerateUrlResponse toGenerateUrlResponse(Submission submission, @Context String baseUrl); @Named("submissionIdToUrl") - static String submissionIdToUrl(UUID id, @Context String baseUrl) { + static String submissionIdToUrl(Submission submission, @Context String baseUrl) { return MessageFormat.format( - "{0}?submissionId={1}", + "{0}?submissionId={1}&transactionId={2}", baseUrl, - id); + submission.getId(), + submission.getTransactionId()); } } diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/PartyMapper.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/PartyMapper.java new file mode 100644 index 0000000000..92831faf24 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/PartyMapper.java @@ -0,0 +1,19 @@ +package ca.bc.gov.open.jag.efilingapi.submission.mappers; + +import ca.bc.gov.open.jag.efilingcommons.model.Individual; +import ca.bc.gov.open.jag.efilingcommons.model.Organization; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper +public interface PartyMapper { + + @Mapping(target = "roleTypeCd", source="roleType") + @Mapping(target = "nameTypeCd", constant="CUR") + Individual toIndividual(ca.bc.gov.open.jag.efilingapi.api.model.Individual individual); + + @Mapping(target = "roleTypeCd", source="roleType") + @Mapping(target = "nameTypeCd", constant="CUR") + Organization toOrganization(ca.bc.gov.open.jag.efilingapi.api.model.Organization organization); + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/RushProcessingMapper.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/RushProcessingMapper.java new file mode 100644 index 0000000000..8e97f412d6 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/RushProcessingMapper.java @@ -0,0 +1,25 @@ +package ca.bc.gov.open.jag.efilingapi.submission.mappers; + +import ca.bc.gov.open.jag.efilingapi.api.model.Rush; +import ca.bc.gov.open.jag.efilingapi.api.model.RushDocument; +import ca.bc.gov.open.jag.efilingcommons.model.Document; +import ca.bc.gov.open.jag.efilingcommons.model.RushProcessing; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper +public interface RushProcessingMapper { + + @Mapping(target="rushType", source="rushType", defaultValue = "") + @Mapping(target="phoneNumber", source="phoneNumber", defaultValue = "") + @Mapping(target="reason", source="reason", defaultValue = "") + @Mapping(target="organization", source="organization", defaultValue = "") + @Mapping(target="country", source="country", defaultValue = "") + @Mapping(target="countryCode", source="countryCode", defaultValue = "") + RushProcessing toRushProcessing(Rush rush); + + @Mapping(target = "name", source = "fileName") + @Mapping(target = "serverFileName", source = "fileName") + Document toDocument(RushDocument rushDocument); + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/SubmissionMapper.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/SubmissionMapper.java index 8a0067f1cf..ec1f19559f 100644 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/SubmissionMapper.java +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/mappers/SubmissionMapper.java @@ -1,21 +1,31 @@ package ca.bc.gov.open.jag.efilingapi.submission.mappers; -import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; -import ca.bc.gov.open.jag.efilingapi.fee.models.Fee; -import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; import ca.bc.gov.open.jag.efilingapi.api.model.GenerateUrlRequest; +import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; import org.mapstruct.InjectionStrategy; import org.mapstruct.Mapper; import org.mapstruct.Mapping; -@Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR) +import java.util.UUID; + +@Mapper(componentModel = "spring", + injectionStrategy = InjectionStrategy.CONSTRUCTOR, +uses = { FilingPackageMapper.class }) public interface SubmissionMapper { - @Mapping(source = "generateUrlRequest.documentProperties", target = "documentProperties") - @Mapping(source = "generateUrlRequest.navigation", target = "navigation") - @Mapping(source = "fee", target = "fee") - @Mapping(source = "accountDetails", target = "accountDetails") + @Mapping(source = "submissionId", target = "id") + @Mapping(source = "universalId", target = "universalId") + @Mapping(source = "transactionId", target = "transactionId") + @Mapping(source = "generateUrlRequest.navigationUrls", target = "navigationUrls") + @Mapping(source = "filingPackage", target = "filingPackage") @Mapping(source = "expiryDate", target = "expiryDate") - Submission toSubmission(GenerateUrlRequest generateUrlRequest, Fee fee, AccountDetails accountDetails, long expiryDate); + Submission toSubmission( + String universalId, + UUID submissionId, + UUID transactionId, + GenerateUrlRequest generateUrlRequest, + FilingPackage filingPackage, + long expiryDate); } diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/models/GetValidPartyRoleRequest.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/models/GetValidPartyRoleRequest.java new file mode 100644 index 0000000000..53e492da42 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/models/GetValidPartyRoleRequest.java @@ -0,0 +1,71 @@ +package ca.bc.gov.open.jag.efilingapi.submission.models; + + +import ca.bc.gov.open.jag.efilingapi.api.model.InitialDocument; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class GetValidPartyRoleRequest { + + private List initialDocuments = new ArrayList<>(); + private String courtLevel; + private String courtClassification; + + public List getInitialDocuments() { + return initialDocuments; + } + + public String getCourtLevel() { + return courtLevel; + } + + public String getCourtClassification() { + return courtClassification; + } + + public String getDocumentTypesAsString() { + return this.initialDocuments.stream().map(InitialDocument::getType).collect(Collectors.joining(",")); + } + + public GetValidPartyRoleRequest(Builder builder) { + this.initialDocuments = builder.documents; + this.courtLevel = builder.courtLevel; + this.courtClassification = builder.courtClassification; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + public GetValidPartyRoleRequest create() { + return new GetValidPartyRoleRequest(this); + } + + private String courtLevel; + + public Builder courtLevel(String courtLevel) { + this.courtLevel = courtLevel; + return this; + } + + private String courtClassification; + + public Builder courtClassification(String courtClassification) { + this.courtClassification = courtClassification; + return this; + } + + private List documents; + + public Builder documents(List documents) { + this.documents = documents; + return this; + } + + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/models/Submission.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/models/Submission.java index 6af8568d96..8e66e27b72 100644 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/models/Submission.java +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/models/Submission.java @@ -1,9 +1,7 @@ package ca.bc.gov.open.jag.efilingapi.submission.models; -import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; -import ca.bc.gov.open.jag.efilingapi.fee.models.Fee; -import ca.bc.gov.open.jag.efilingapi.api.model.DocumentProperties; -import ca.bc.gov.open.jag.efilingapi.api.model.Navigation; +import ca.bc.gov.open.jag.efilingapi.api.model.NavigationUrls; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -16,23 +14,26 @@ public class Submission { private UUID id; - private long expiryDate; + private UUID transactionId; + + private String universalId; - private DocumentProperties documentProperties; + private long expiryDate; - private Navigation navigation; + private NavigationUrls navigationUrls; - private Fee fee; + private FilingPackage filingPackage; - private AccountDetails accountDetails; + private String clientAppName; protected Submission(Submission.Builder builder) { - this.id = UUID.randomUUID(); - this.documentProperties = builder.documentProperties; - this.navigation = builder.navigation; - this.fee = builder.fee; - this.accountDetails = builder.accountDetails; + this.id = builder.id; + this.transactionId = builder.transactionId; + this.filingPackage = builder.filingPackage; + this.navigationUrls = builder.navigationUrls; this.expiryDate = builder.expiryDate; + this.universalId = builder.universalId; + this.clientAppName = builder.clientAppName; } public static Submission.Builder builder() { @@ -42,66 +43,78 @@ public static Submission.Builder builder() { @JsonCreator public Submission( @JsonProperty("id") UUID id, - @JsonProperty("submissionMetadata") DocumentProperties documentProperties, - @JsonProperty("navigation") Navigation navigation, - @JsonProperty("fee") Fee fee, - @JsonProperty("accountDetails") AccountDetails accountDetails, + @JsonProperty("transactionId") UUID transactionId, + @JsonProperty("universalId") String universalId, + @JsonProperty("clientAppName") String clientAppName, + @JsonProperty("filingPackage") FilingPackage filingPackage, + @JsonProperty("navigationUrls") NavigationUrls navigationUrls, @JsonProperty("expiryDate") long expiryDate) { this.id = id; - this.documentProperties = documentProperties; - this.navigation = navigation; - this.fee = fee; - this.accountDetails = accountDetails; + this.transactionId = transactionId; + this.universalId = universalId; + this.filingPackage = filingPackage; + this.navigationUrls = navigationUrls; this.expiryDate = expiryDate; + this.clientAppName = clientAppName; } public UUID getId() { return id; } - public DocumentProperties getDocumentProperties() { - return documentProperties; - } + public UUID getTransactionId() { return transactionId; } - public Navigation getNavigation() { - return navigation; - } + public String getUniversalId() { return universalId; } - public Fee getFee() { - return fee; - } + public String getClientAppName() { return clientAppName; } - public AccountDetails getAccountDetails() { - return accountDetails; + public FilingPackage getFilingPackage() { + return filingPackage; } + public NavigationUrls getNavigationUrls() { return navigationUrls; } + public long getExpiryDate() { return expiryDate; } - + public static class Builder { - private DocumentProperties documentProperties; - private Navigation navigation; - private Fee fee; - private AccountDetails accountDetails; + private UUID id; + private UUID transactionId; + private String universalId; + private FilingPackage filingPackage; + private NavigationUrls navigationUrls; private long expiryDate; + private String clientAppName; + - public Builder documentProperties(DocumentProperties documentProperties) { - this.documentProperties = documentProperties; + public Builder id (UUID id) { + this.id = id; return this; } - public Builder navigation(Navigation navigation) { - this.navigation = navigation; + public Builder clientAppName(String clientAppName) { + this.clientAppName = clientAppName; return this; } - public Builder fee(Fee fee) { - this.fee = fee; + + public Builder transactionId(UUID owner) { + this.transactionId = owner; + return this; + } + + public Builder universalId(String universalId) { + this.universalId = universalId; return this; } - public Builder accountDetails(AccountDetails accountDetails) { - this.accountDetails = accountDetails; + public Builder filingPackage(FilingPackage filingPackage) { + this.filingPackage = filingPackage; + return this; + } + + public Builder navigationUrls(NavigationUrls navigationUrls) { + this.navigationUrls = navigationUrls; return this; } @@ -115,5 +128,4 @@ public Submission create() { } } - } diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/models/SubmissionConstants.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/models/SubmissionConstants.java new file mode 100644 index 0000000000..bbe9213d17 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/models/SubmissionConstants.java @@ -0,0 +1,15 @@ +package ca.bc.gov.open.jag.efilingapi.submission.models; + +public class SubmissionConstants { + + + + private SubmissionConstants() { + + } + + public static final String SUBMISSION_FEE_TYPE = "DCFL"; + public static final String SUBMISSION_ORDR_DOCUMENT_SUB_TYPE_CD = "ORDR"; + public static final String SUBMISSION_ODOC_DOCUMENT_SUB_TYPE_CD = "ODOC"; + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionService.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionService.java index 54acce4674..688902c0d5 100644 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionService.java +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionService.java @@ -1,12 +1,25 @@ package ca.bc.gov.open.jag.efilingapi.submission.service; import ca.bc.gov.open.jag.efilingapi.api.model.GenerateUrlRequest; +import ca.bc.gov.open.jag.efilingapi.api.model.SubmitResponse; +import ca.bc.gov.open.jag.efilingapi.api.model.UpdateDocumentRequest; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionKey; +import ca.bc.gov.open.jag.efilingapi.submission.models.GetValidPartyRoleRequest; import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; -import java.util.UUID; +import java.util.List; public interface SubmissionService { - Submission generateFromRequest(UUID authUserId, GenerateUrlRequest generateUrlRequest); + Submission generateFromRequest(String applicationCode, SubmissionKey submissionKey, GenerateUrlRequest generateUrlRequest); + + SubmitResponse createSubmission(Submission submission, AccountDetails accountDetails, Boolean isEarlyAdopter); + + Submission updateDocuments(Submission submission, UpdateDocumentRequest updateDocumentRequest, SubmissionKey submissionKey); + + Boolean isRushRequired(String documentType, String courtLevel, String courtClass); + + List getValidPartyRoles(GetValidPartyRoleRequest getValidPartyRoleRequest); } diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionServiceImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionServiceImpl.java index 8148357a94..78c1fd0eed 100644 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionServiceImpl.java +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionServiceImpl.java @@ -1,91 +1,336 @@ package ca.bc.gov.open.jag.efilingapi.submission.service; -import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; -import ca.bc.gov.open.jag.efilingapi.api.model.GenerateUrlRequest; -import ca.bc.gov.open.jag.efilingapi.fee.FeeService; -import ca.bc.gov.open.jag.efilingapi.fee.models.FeeRequest; +import ca.bc.gov.open.jag.efilingapi.api.model.*; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionKey; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.PartyMapper; import ca.bc.gov.open.jag.efilingapi.submission.mappers.SubmissionMapper; +import ca.bc.gov.open.jag.efilingapi.submission.models.GetValidPartyRoleRequest; import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; -import ca.bc.gov.open.jag.efilingcommons.exceptions.InvalidAccountStateException; +import ca.bc.gov.open.jag.efilingapi.submission.models.SubmissionConstants; +import ca.bc.gov.open.jag.efilingapi.utils.FileUtils; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingCourtServiceException; import ca.bc.gov.open.jag.efilingcommons.exceptions.StoreException; -import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.ActionDocument; +import ca.bc.gov.open.jag.efilingcommons.model.Court; +import ca.bc.gov.open.jag.efilingcommons.model.Document; +import ca.bc.gov.open.jag.efilingcommons.model.*; +import ca.bc.gov.open.jag.efilingcommons.payment.PaymentAdapter; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingCourtService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSubmissionService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; +import ca.bc.gov.open.sftp.starter.SftpService; +import org.apache.commons.collections4.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.cache.CacheProperties; +import java.io.ByteArrayInputStream; import java.math.BigDecimal; +import java.text.MessageFormat; +import java.util.Base64; +import java.util.List; import java.util.Optional; -import java.util.UUID; +import java.util.stream.Collectors; public class SubmissionServiceImpl implements SubmissionService { Logger logger = LoggerFactory.getLogger(SubmissionServiceImpl.class); - public static final UUID FAKE_ACCOUNT = UUID.fromString("88da92db-0791-491e-8c58-1a969e67d2fb"); - private final SubmissionStore submissionStore; private final CacheProperties cacheProperties; private final SubmissionMapper submissionMapper; - private final EfilingAccountService efilingAccountService; + private final PartyMapper partyMapper; + + private final EfilingLookupService efilingLookupService; + + private final EfilingCourtService efilingCourtService; + + private final EfilingSubmissionService efilingSubmissionService; + + private final EfilingDocumentService efilingDocumentService; + + private final DocumentStore documentStore; - private final FeeService feeService; + private final PaymentAdapter paymentAdapter; + + private final SftpService sftpService; + + private final NavigationProperties navigationProperties; public SubmissionServiceImpl( SubmissionStore submissionStore, CacheProperties cacheProperties, SubmissionMapper submissionMapper, - EfilingAccountService efilingAccountService, - FeeService feeService) { + PartyMapper partyMapper, + EfilingLookupService efilingLookupService, + EfilingCourtService efilingCourtService, + EfilingSubmissionService efilingSubmissionService, + EfilingDocumentService efilingDocumentService, DocumentStore documentStore, + PaymentAdapter paymentAdapter, + SftpService sftpService, NavigationProperties navigationProperties) { this.submissionStore = submissionStore; this.cacheProperties = cacheProperties; this.submissionMapper = submissionMapper; - this.efilingAccountService = efilingAccountService; - this.feeService = feeService; + this.partyMapper = partyMapper; + this.efilingLookupService = efilingLookupService; + this.efilingCourtService = efilingCourtService; + this.efilingSubmissionService = efilingSubmissionService; + this.efilingDocumentService = efilingDocumentService; + this.documentStore = documentStore; + this.paymentAdapter = paymentAdapter; + this.sftpService = sftpService; + this.navigationProperties = navigationProperties; } + @Override - public Submission generateFromRequest(UUID authUserId, GenerateUrlRequest generateUrlRequest) { + public Submission generateFromRequest(String applicationCode, SubmissionKey submissionKey, GenerateUrlRequest generateUrlRequest) { - logger.debug("Attempting to get user cso account information"); - AccountDetails accountDetails = efilingAccountService.getAccountDetails(authUserId, ""); - logger.info("Successfully got cso account information"); + Optional cachedSubmission = submissionStore.put( + submissionMapper.toSubmission( + submissionKey.getUniversalId(), + submissionKey.getSubmissionId(), + submissionKey.getTransactionId(), + generateUrlRequest, + toFilingPackage(applicationCode, generateUrlRequest, submissionKey), + getExpiryDate())); - if (accountDetails != null && !accountDetails.isFileRolePresent()) { - throw new InvalidAccountStateException("Account does not have CSO FILE ROLE"); - } else if (accountDetails == null) { - accountDetails = fakeFromBceId(authUserId); + if (!cachedSubmission.isPresent()) throw new StoreException("exception while storing submission object"); + + return cachedSubmission.get(); + + } + + private boolean isRushedSubmission(GenerateUrlRequest generateUrlRequest) { + + for (InitialDocument initialDocument : generateUrlRequest.getFilingPackage().getDocuments()) { + DocumentTypeDetails documentTypeDetails = documentStore.getDocumentDetails(generateUrlRequest.getFilingPackage().getCourt().getLevel(), generateUrlRequest.getFilingPackage().getCourt().getCourtClass(), initialDocument.getType()); + if (documentTypeDetails.isRushRequired()) return true; } + return false; + + } - Optional cachedSubmission = submissionStore.put( - submissionMapper.toSubmission(generateUrlRequest, - feeService.getFee( - new FeeRequest( - generateUrlRequest.getDocumentProperties().getType(), - generateUrlRequest.getDocumentProperties().getSubType())), + @Override + public SubmitResponse createSubmission(Submission submission, AccountDetails accountDetails, Boolean isEarlyAdopter) { + + uploadFiles(submission); + + SubmitResponse result = new SubmitResponse(); + + SubmitPackageResponse submitPackageResponse = efilingSubmissionService + .submitFilingPackage( accountDetails, - getExpiryDate())); + submission.getFilingPackage(), + paymentAdapter::makePayment); - if(!cachedSubmission.isPresent()) - throw new StoreException("exception while storing submission object"); + if(isEarlyAdopter) { + // TODO: remove ?packageNo= from the url, this is a temp fix to accomodate client that are currently parsing the url to get the id back + result.setPackageRef( + Base64.getEncoder().encodeToString( + MessageFormat.format("{0}/packagereview/{1}?packageNo={1}", + navigationProperties.getBaseUrl(), + submitPackageResponse.getTransactionId().toPlainString()).getBytes())); + } else { + result.setPackageRef(Base64.getEncoder().encodeToString(submitPackageResponse.getPackageLink().getBytes())); + } - return cachedSubmission.get(); + logger.info("successfully submitted efiling package with cso id [{}]", submitPackageResponse.getTransactionId()); + + return result; + + } + + @Override + public Submission updateDocuments(Submission submission, UpdateDocumentRequest updateDocumentRequest, SubmissionKey submissionKey) { + + updateDocumentRequest.getDocuments().forEach(documentProperties -> { + submission.getFilingPackage().addDocument(toDocument( + submission.getFilingPackage().getCourt().getLevel(), + submission.getFilingPackage().getCourt().getCourtClass(), + documentProperties, submissionKey)); + }); + + submissionStore.put(submission); + + return submission; + + } + + @Override + public List getValidPartyRoles(GetValidPartyRoleRequest getValidPartyRoleRequest) { + + return efilingLookupService.getValidPartyRoles( + getValidPartyRoleRequest.getCourtLevel(), + getValidPartyRoleRequest.getCourtClassification(), + getValidPartyRoleRequest.getDocumentTypesAsString() + ); + + } + + @Override + public Boolean isRushRequired(String documentType, String courtLevel, String courtClass) { + + DocumentTypeDetails documentTypeDetails = efilingDocumentService.getDocumentTypeDetails(courtLevel, courtClass, documentType); + + return documentTypeDetails.isRushRequired(); + + } + + private FilingPackage toFilingPackage(String applicationCode, GenerateUrlRequest request, SubmissionKey submissionKey) { + + return FilingPackage.builder() + .packageNumber(request.getFilingPackage().getPackageNumber()) + .court(populateCourtDetails(request.getFilingPackage().getCourt())) + .submissionFeeAmount(getSubmissionFeeAmount(SubmissionFeeRequest.builder() + .serviceType(SubmissionConstants.SUBMISSION_FEE_TYPE) + .division(request.getFilingPackage().getCourt().getDivision()) + .classification(request.getFilingPackage().getCourt().getCourtClass()) + .level(request.getFilingPackage().getCourt().getLevel()) + .application(applicationCode).create())) + .documents(request.getFilingPackage() + .getDocuments() + .stream() + .map(documentProperties -> toDocument( + request.getFilingPackage().getCourt().getLevel(), + request.getFilingPackage().getCourt().getCourtClass(), + documentProperties, submissionKey)) + .collect(Collectors.toList())) + .parties(CollectionUtils.emptyIfNull(request.getFilingPackage() + .getParties()) + .stream() + .map(partyMapper::toIndividual) + .collect(Collectors.toList())) + .organizations(CollectionUtils.emptyIfNull(request.getFilingPackage() + .getOrganizationParties()) + .stream() + .map(partyMapper::toOrganization) + .collect(Collectors.toList())) + .rushedSubmission(isRushedSubmission(request)) + .applicationCode(applicationCode) + .autoProcessing(false) + .create(); + + } + + private Court populateCourtDetails(CourtBase courtBase) { + + Optional courtDetails = efilingCourtService.getCourtDescription(courtBase.getLocation(), courtBase.getLevel(), courtBase.getCourtClass()); + + if(!courtDetails.isPresent()) { + throw new EfilingCourtServiceException("Failed to retrieve Efiling exception"); + } + + return Court + .builder() + .location(courtBase.getLocation()) + .level(courtBase.getLevel()) + .courtClass(courtBase.getCourtClass()) + .division(courtBase.getDivision()) + .fileNumber(courtBase.getFileNumber()) + .agencyId(courtDetails.get().getCourtId()) + .locationDescription(courtDetails.get().getCourtDescription()) + .classDescription(courtDetails.get().getClassDescription()) + .levelDescription(courtDetails.get().getLevelDescription()) + .create(); + + } + + private Document toDocument(String courtLevel, String courtClass, InitialDocument initialDocument, SubmissionKey submissionKey) { + + DocumentTypeDetails details = documentStore.getDocumentDetails(courtLevel, courtClass, initialDocument.getType()); + + return + Document.builder() + .description(details.getDescription()) + .statutoryFeeAmount(details.getStatutoryFeeAmount()) + .type(initialDocument.getType()) + .name(initialDocument.getName()) + .serverFileName(MessageFormat.format("fh_{0}_{1}_{2}",submissionKey.getSubmissionId(), submissionKey.getTransactionId(), initialDocument.getName())) + .mimeType(FileUtils.guessContentTypeFromName(initialDocument.getName())) + .isAmendment(initialDocument.getIsAmendment()) + .documentId(initialDocument.getDocumentId()) + .isSupremeCourtScheduling(initialDocument.getIsSupremeCourtScheduling()) + .actionDocument( + setActionDocument(initialDocument.getActionDocument()) + ) + .subType(details.isOrderDocument() ? SubmissionConstants.SUBMISSION_ORDR_DOCUMENT_SUB_TYPE_CD : SubmissionConstants.SUBMISSION_ODOC_DOCUMENT_SUB_TYPE_CD) + .data(initialDocument.getData()) + .create(); + + } + + private Document toDocument(String courtLevel, String courtClass, DocumentProperties documentProperties, SubmissionKey submissionKey) { + + DocumentTypeDetails details = documentStore.getDocumentDetails(courtLevel, courtClass, documentProperties.getType()); + + return + Document.builder() + .description(details.getDescription()) + .statutoryFeeAmount(details.getStatutoryFeeAmount()) + .type(documentProperties.getType()) + .name(documentProperties.getName()) + .serverFileName(MessageFormat.format("fh_{0}_{1}_{2}", submissionKey.getSubmissionId(), submissionKey.getTransactionId(), documentProperties.getName())) + .mimeType(FileUtils.guessContentTypeFromName(documentProperties.getName())) + .isAmendment(documentProperties.getIsAmendment()) + .isSupremeCourtScheduling(documentProperties.getIsSupremeCourtScheduling()) + .subType(details.isOrderDocument() ? SubmissionConstants.SUBMISSION_ORDR_DOCUMENT_SUB_TYPE_CD : SubmissionConstants.SUBMISSION_ODOC_DOCUMENT_SUB_TYPE_CD) + .create(); } - private AccountDetails fakeFromBceId(UUID authUserId) { + private void uploadFiles(Submission submission) { + //Upload submission documents + logger.info("Uploading submission documents"); + submission.getFilingPackage().getDocuments().forEach( + document -> + redisStoreToSftpStore(document, submission)); + + //Upload supporting documents when there is a rush with documents + if (submission.getFilingPackage().getRush() != null && submission.getFilingPackage().getRush().getSupportingDocuments().size() > 0) { + logger.info("Uploading rush supporting documents"); + submission.getFilingPackage().getRush().getSupportingDocuments().forEach( + document -> + redisRushStoreToSftpStore(document, submission)); + } + } - // TODO: implement account details service + private void redisStoreToSftpStore(Document document, Submission submission) { + + SubmissionKey submissionKey = new SubmissionKey(submission.getUniversalId(), submission.getTransactionId(), submission.getId()); + + sftpService.put(new ByteArrayInputStream(documentStore.get(submissionKey, document.getName())), + document.getServerFileName()); + + //Delete file from cache + documentStore.evict(submissionKey, document.getName()); + + } - logger.error("THIS IS FOR TESTING ONLY"); + private void redisRushStoreToSftpStore(Document document, Submission submission) { - if(authUserId.equals(FAKE_ACCOUNT)) - return new AccountDetails(BigDecimal.ZERO, BigDecimal.ZERO, false, "Bob", "Ross", "Rob", "bross@paintit.com"); + SubmissionKey submissionKey = new SubmissionKey(submission.getUniversalId(), submission.getTransactionId(), submission.getId()); - return null; + sftpService.put(new ByteArrayInputStream(documentStore.getRushDocument(submissionKey, document.getName())), + document.getServerFileName()); + //Delete file from cache + documentStore.evictRushDocument(submissionKey, document.getName()); + + } + + + private BigDecimal getSubmissionFeeAmount(SubmissionFeeRequest submissionFeeRequest ) { + + ServiceFees fee = efilingLookupService.getServiceFee(submissionFeeRequest); + return fee == null ? BigDecimal.ZERO : fee.getFeeAmount(); } @@ -93,5 +338,18 @@ private long getExpiryDate() { return System.currentTimeMillis() + cacheProperties.getRedis().getTimeToLive().toMillis(); } + private ActionDocument setActionDocument(ca.bc.gov.open.jag.efilingapi.api.model.ActionDocument actionDocument) { + + if (actionDocument == null) return null; + + logger.info("setting action document"); + + return ActionDocument.builder() + .documentId(actionDocument.getId()) + .status(String.valueOf(actionDocument.getStatus())) + .type(actionDocument.getType()) + .create(); + + } } diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionStore.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionStore.java index 0cb59bb7ff..d7b2f9c93a 100644 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionStore.java +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionStore.java @@ -1,9 +1,9 @@ package ca.bc.gov.open.jag.efilingapi.submission.service; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionKey; import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; import java.util.Optional; -import java.util.UUID; /** * A service to manage persistence of submissions objects @@ -12,6 +12,8 @@ public interface SubmissionStore { Optional put(Submission submission); - Optional getByKey(UUID key); + Optional get(SubmissionKey submissionKey); + + void evict(SubmissionKey submissionKey); } diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionStoreImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionStoreImpl.java index 51e80a3aa9..63b38ef4fa 100644 --- a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionStoreImpl.java +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/service/SubmissionStoreImpl.java @@ -1,11 +1,12 @@ package ca.bc.gov.open.jag.efilingapi.submission.service; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionKey; import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import java.util.Optional; -import java.util.UUID; /** * Implementation of SubmissionStore using Submission StorageService @@ -14,15 +15,21 @@ public class SubmissionStoreImpl implements SubmissionStore { @Override - @CachePut(cacheNames = "submission", key = "#submission.id", cacheManager = "submissionCacheManager") + @CachePut(cacheNames = "submission", key = "{ #submission.universalId, #submission.id, #submission.transactionId }", cacheManager = "submissionCacheManager") public Optional put(Submission submission) { return Optional.of(submission); } @Override - @Cacheable(cacheNames = "submission", key = "#key", cacheManager = "submissionCacheManager", unless="#result == null") - public Optional getByKey(UUID key) { + @Cacheable(cacheNames = "submission", key = "{ #submissionKey.universalId, #submissionKey.submissionId, #submissionKey.transactionId }", cacheManager = "submissionCacheManager", unless="#result == null") + public Optional get(SubmissionKey submissionKey) { return Optional.empty(); } + @Override + @CacheEvict(cacheNames = "submission", key = "{ #submissionKey.universalId, #submissionKey.submissionId, #submissionKey.transactionId }", cacheManager = "submissionCacheManager") + public void evict(SubmissionKey submissionKey) { + //This implements Redis delete no code required + } + } diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/validator/GenerateUrlRequestValidator.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/validator/GenerateUrlRequestValidator.java new file mode 100644 index 0000000000..66dffb3b56 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/validator/GenerateUrlRequestValidator.java @@ -0,0 +1,10 @@ +package ca.bc.gov.open.jag.efilingapi.submission.validator; + +import ca.bc.gov.open.jag.efilingapi.api.model.GenerateUrlRequest; +import ca.bc.gov.open.jag.efilingapi.utils.Notification; + +public interface GenerateUrlRequestValidator { + + Notification validate(GenerateUrlRequest generateUrlRequest, String applicationCode, String universalId); + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/validator/GenerateUrlRequestValidatorImpl.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/validator/GenerateUrlRequestValidatorImpl.java new file mode 100644 index 0000000000..f4e5944c76 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/submission/validator/GenerateUrlRequestValidatorImpl.java @@ -0,0 +1,225 @@ +package ca.bc.gov.open.jag.efilingapi.submission.validator; + +import ca.bc.gov.open.jag.efilingapi.api.model.*; +import ca.bc.gov.open.jag.efilingapi.court.models.GetCourtDetailsRequest; +import ca.bc.gov.open.jag.efilingapi.court.models.IsValidCourtFileNumberRequest; +import ca.bc.gov.open.jag.efilingapi.court.models.IsValidCourtRequest; +import ca.bc.gov.open.jag.efilingapi.court.services.CourtService; +import ca.bc.gov.open.jag.efilingapi.document.DocumentService; +import ca.bc.gov.open.jag.efilingapi.document.models.GetValidDocumentTypesRequest; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import ca.bc.gov.open.jag.efilingapi.submission.models.GetValidPartyRoleRequest; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; +import ca.bc.gov.open.jag.efilingapi.utils.Notification; +import ca.bc.gov.open.jag.efilingcommons.model.CourtDetails; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +public class GenerateUrlRequestValidatorImpl implements GenerateUrlRequestValidator { + + private final SubmissionService submissionService; + private final CourtService courtService; + private final DocumentService documentService; + private final FilingPackageService filingPackageService; + + public GenerateUrlRequestValidatorImpl(SubmissionService submissionService, + CourtService courtService, + DocumentService documentService, + FilingPackageService filingPackageService) { + this.submissionService = submissionService; + this.courtService = courtService; + this.documentService = documentService; + this.filingPackageService = filingPackageService; + } + + @Override + public Notification validate(GenerateUrlRequest generateUrlRequest, String applicationCode, String universalId) { + + Notification notification = new Notification(); + + if (generateUrlRequest.getFilingPackage() == null) { + notification.addError("Initial Package is required."); + return notification; + } + + notification.addError(validateNavigationUrls(generateUrlRequest.getNavigationUrls())); + + Optional courtDetails = this.courtService.getCourtDetails(GetCourtDetailsRequest + .builder() + .courtLocation(generateUrlRequest.getFilingPackage().getCourt().getLocation()) + .courtLevel(generateUrlRequest.getFilingPackage().getCourt().getLevel()) + .courtClassification(generateUrlRequest.getFilingPackage().getCourt().getCourtClass()) + .create()); + + if(!courtDetails.isPresent()) { + notification.addError(MessageFormat.format("Court with Location: [{0}], Level: [{1}], Classification: [{2}] is not a valid court.", + generateUrlRequest.getFilingPackage().getCourt().getLocation(), generateUrlRequest.getFilingPackage().getCourt().getLevel(), generateUrlRequest.getFilingPackage().getCourt().getCourtClass())); + return notification; + } + + notification.addError(validateCourt(generateUrlRequest.getFilingPackage(), courtDetails.get(), applicationCode)); + + notification.addError(validateParties(generateUrlRequest.getFilingPackage())); + + if(!isNewSubmission(generateUrlRequest.getFilingPackage())) { + notification.addError(validateCourtFileNumber(generateUrlRequest.getFilingPackage(), courtDetails.get(), applicationCode)); + } + + notification.addError(validateDocumentTypes(generateUrlRequest.getFilingPackage())); + + //Validate package number and document ids + if (generateUrlRequest.getFilingPackage().getPackageNumber() != null) { + notification.addError(validateActionsRequired(generateUrlRequest, universalId)); + } + + + return notification; + + } + + private List validateNavigationUrls(NavigationUrls navigationUrls) { + + List result = new ArrayList<>(); + + if(navigationUrls == null) { + result.add("Navigation Urls are required."); + return result; + } + + if(StringUtils.isBlank(navigationUrls.getError())) result.add("Error url is required."); + if(StringUtils.isBlank(navigationUrls.getCancel())) result.add("Cancel url is required."); + if(StringUtils.isBlank(navigationUrls.getSuccess())) result.add("Success url is required."); + + return result; + + } + + private List validateCourt(InitialPackage initialPackage, CourtDetails courtDetails, String applicationCode) { + + if (!this.courtService.isValidCourt(IsValidCourtRequest + .builder() + .applicationCode(applicationCode) + .courtClassification(initialPackage.getCourt().getCourtClass()) + .courtLevel(initialPackage.getCourt().getLevel()) + .courtId(courtDetails.getCourtId()) + .create())) + return Arrays.asList(MessageFormat.format("Court with Location: [{0}], Level: [{1}], Classification: [{2}] is not a valid court.", + initialPackage.getCourt().getLocation(), initialPackage.getCourt().getLevel(), initialPackage.getCourt().getCourtClass())); + + return new ArrayList<>(); + + } + + private boolean isNewSubmission(InitialPackage initialPackage) { + return initialPackage.getCourt() != null && StringUtils.isBlank(initialPackage.getCourt().getFileNumber()); + } + + /** + * Validates parties + * + * if court file number is empty then at least 1 party is required + * + * Party(Organization or Individual) types must be valid based on the document types submitted + * + * @param initialPackage + */ + private List validateParties(InitialPackage initialPackage) { + + if (StringUtils.isBlank(initialPackage.getCourt().getFileNumber()) && (CollectionUtils.emptyIfNull(initialPackage.getParties()).isEmpty() && CollectionUtils.emptyIfNull(initialPackage.getOrganizationParties()).isEmpty())) { + return Arrays.asList("At least 1 party is required for new submission."); + } + + List validPartyRoles = submissionService.getValidPartyRoles(GetValidPartyRoleRequest + .builder() + .courtClassification(initialPackage.getCourt().getCourtClass()) + .courtLevel(initialPackage.getCourt().getLevel()) + .documents(initialPackage.getDocuments()) + .create()); + + List validationResult = new ArrayList<>(); + + for (Individual individual : CollectionUtils.emptyIfNull(initialPackage.getParties())) { + if (individual.getRoleType() == null || !validPartyRoles.contains(individual.getRoleType().toString())) { + validationResult.add(MessageFormat.format("Individual role type [{0}] is invalid.", individual.getRoleType())); + } + if (StringUtils.isBlank(individual.getLastName())) { + validationResult.add("Individual last name is required."); + } + } + + for (Organization organization : CollectionUtils.emptyIfNull(initialPackage.getOrganizationParties())) { + if (organization.getRoleType() == null || !validPartyRoles.contains(organization.getRoleType().toString())) { + validationResult.add(MessageFormat.format("Organization role type [{0}] is invalid.", organization.getRoleType())); + } + if (StringUtils.isBlank(organization.getName())) { + validationResult.add("Organization name is required."); + } + } + + return validationResult; + + } + + private List validateCourtFileNumber(InitialPackage initialPackage, CourtDetails courtDetails, String applicationCode) { + + List result = new ArrayList<>(); + + if(!this.courtService.isValidCourtFileNumber(IsValidCourtFileNumberRequest + .builder() + .fileNumber(initialPackage.getCourt().getFileNumber()) + .courtClassification(initialPackage.getCourt().getCourtClass()) + .courtLevel(initialPackage.getCourt().getLevel()) + .courtId(courtDetails.getCourtId()) + .applicationCode(applicationCode) + .create())) + result.add(MessageFormat.format("FileNumber [{0}] does not exists.", initialPackage.getCourt().getFileNumber())); + + return result; + + } + + public List validateDocumentTypes(InitialPackage initialPackage) { + + List validDocumentTypes = this.documentService.getValidDocumentTypes(GetValidDocumentTypesRequest.builder() + .courtClassification(initialPackage.getCourt().getCourtClass()) + .courtLevel(initialPackage.getCourt().getLevel()) + .create()).stream().map(DocumentTypeDetails::getType).collect(Collectors.toList()); + + return initialPackage.getDocuments() + .stream() + .map(InitialDocument::getType) + .filter(x -> !validDocumentTypes.contains(x)) + .map(invalidType -> MessageFormat.format("Document type [{0}] is invalid.", invalidType)) + .collect(Collectors.toList()); + } + + private List validateActionsRequired(GenerateUrlRequest generateUrlRequest, String universalId) { + + List result = new ArrayList<>(); + + Optional filingPackage = filingPackageService.getCSOFilingPackage(universalId, generateUrlRequest.getFilingPackage().getPackageNumber()); + + //Validate Package + if (!filingPackage.isPresent()) { + result.add("For given package number and universal id no record was found in cso"); + return result; + } + + //Validate Documents + if (generateUrlRequest.getFilingPackage().getDocuments().isEmpty()) { + result.add("For given package there are no documents present"); + } + + return result; + + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/utils/FileUtils.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/utils/FileUtils.java new file mode 100644 index 0000000000..a8e022ed05 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/utils/FileUtils.java @@ -0,0 +1,20 @@ +package ca.bc.gov.open.jag.efilingapi.utils; + +import java.io.File; +import java.net.URLConnection; + +public class FileUtils { + + private FileUtils() {} + + /** + * Guess the mime type from filename + * @param fileName + * @return + */ + public static String guessContentTypeFromName(String fileName){ + File file = new File(fileName); + return URLConnection.guessContentTypeFromName(file.getName()); + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/utils/Notification.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/utils/Notification.java new file mode 100644 index 0000000000..c97d5a88c8 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/utils/Notification.java @@ -0,0 +1,27 @@ +package ca.bc.gov.open.jag.efilingapi.utils; + +import java.util.ArrayList; +import java.util.List; + +public class Notification { + + private List errors = new ArrayList<>(); + + public Boolean hasError() { + return !this.errors.isEmpty(); + } + + public void addError(String error) { + errors.add(error); + } + + public void addError(List errors) { + this.errors.addAll(errors); + } + + public List getErrors() { + return this.errors; + } + + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/utils/TikaAnalysis.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/utils/TikaAnalysis.java new file mode 100644 index 0000000000..dd99aa1971 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/utils/TikaAnalysis.java @@ -0,0 +1,32 @@ +package ca.bc.gov.open.jag.efilingapi.utils; + +import org.apache.commons.lang3.StringUtils; +import org.apache.tika.detect.DefaultDetector; +import org.apache.tika.detect.Detector; +import org.apache.tika.metadata.Metadata; +import org.apache.tika.mime.MediaType; +import org.springframework.web.multipart.MultipartFile; + +import java.io.ByteArrayInputStream; +import java.io.IOException; + +public class TikaAnalysis { + + private TikaAnalysis() { } + + public static Boolean isPdf(MultipartFile multipartFile) { + + Detector detector = new DefaultDetector(); + Metadata metadata = new Metadata(); + + try { + MediaType mediaType = detector.detect(new ByteArrayInputStream(multipartFile.getBytes()), metadata); + return StringUtils.equals("application/pdf", mediaType.toString()); + } catch (IOException e) { + return false; + } + + + } + +} diff --git a/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/utils/UniversalIdUtils.java b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/utils/UniversalIdUtils.java new file mode 100644 index 0000000000..2463a5ca71 --- /dev/null +++ b/src/backend/efiling-api/src/main/java/ca/bc/gov/open/jag/efilingapi/utils/UniversalIdUtils.java @@ -0,0 +1,13 @@ +package ca.bc.gov.open.jag.efilingapi.utils; + +import org.apache.commons.lang3.StringUtils; + +public class UniversalIdUtils { + + private UniversalIdUtils() {} + + public static String sanitizeUniversalId(String universalId) { + return StringUtils.replace(universalId, "-", "").toUpperCase(); + } + +} diff --git a/src/backend/efiling-api/src/main/resources/application.yml b/src/backend/efiling-api/src/main/resources/application.yml index 3a09bfe85b..4c7fd9b8b1 100644 --- a/src/backend/efiling-api/src/main/resources/application.yml +++ b/src/backend/efiling-api/src/main/resources/application.yml @@ -1,20 +1,45 @@ server: port: ${SERVER_PORT:8080} + tomcat: + max-part-count: ${MAX_FILE_COUNT:15} + max-part-header-size: ${MAX_HEADER_SIZE:2048} spring: - redis: - host: ${REDIS_HOST:localhost} - port: ${REDIS_PORT:6379} - password: ${REDIS_PASSWORD:admin} + security: + oauth2: + resourceserver: + jwt: + issuer-uri: ${KEYCLOAK_AUTH_SERVER_URL:http://localhost:8081/auth/realms/Efiling-Hub} + jwk-set-uri: ${KEYCLOAK_JWK_SERVER_URL:http://localhost:8081/auth/realms/Efiling-Hub}/protocol/openid-connect/certs + data: + redis: + host: ${REDIS_HOST:localhost} + port: ${REDIS_PORT:6379} + password: ${REDIS_PASSWORD:admin} cache: redis: time-to-live: ${CACHE_TTL:600000} + servlet: + multipart: + max-file-size: ${MAX_FILE_SIZE:10MB} + max-request-size: ${MAX_REQUEST_SIZE:100MB} + +jwt: + auth: + converter: + resource-id: ${KEYCLOAK_RESOURCE:efiling-api} + jag: efiling: global: demo: ${DEMO_MODE:false} navigation: - baseUrl: ${NAVIGATION_BASE_URL:https://httpbin.org/} + baseUrl: ${NAVIGATION_BASE_URL:http://localhost:3000/efilinghub} + csoBaseUrl: ${CSO_BASE_URL:http://localhost/cso} soap: + proxy: + basePath: ${CSO_BASEPATH} + username: ${CSO_USERNAME} + password: ${CSO_PASSWORD} clients: - client: ACCOUNT userName: ${CSO_ACCOUNTFACADE_USERNAME} @@ -28,19 +53,102 @@ jag: userName: ${CSO_LOOKUPFACADE_USERNAME} password: ${CSO_LOOKUPFACADE_PASSWORD} uri: ${CSO_LOOKUPFACADE_URI:http://localhost:8091} - - client: BCEID - userName: ${BCEID_LOOKUP_USERNAME} - password: ${BCEID_LOOKUP_PASSWORD} - uri: ${BCEID_LOOKUP_URI:http://localhost:8091} + - client: STATUS + userName: ${CSO_FILINGSTATSFACADE_USERNAME} + password: ${CSO_FILINGSTATSFACADE_PASSWORD} + uri: ${CSO_FILINGSTATSFACADE_URI:http://localhost:8091} + - client: CSOWS + userName: ${CSOWS_USERNAME} + password: ${CSOWS_PASSWORD} + uri: ${CSOWS_URI:http://localhost:8091} + - client: FILING + userName: ${CSO_FILINGFACADE_USERNAME} + password: ${CSO_FILINGFACADE_PASSWORD} + uri: ${CSO_FILINGFACADE_URI:http://localhost:8091} + - client: SERVICE + userName: ${CSO_SERVICEFACADE_USERNAME} + password: ${CSO_SERVICEFACADE_PASSWORD} + uri: ${CSO_SERVICEFACADE_URI:http://localhost:8091} + - client: REPORT + userName: ${CSO_REPORTSERVICE_USERNAME} + password: ${CSO_REPORTSERVICE_PASSWORD} + uri: ${CSO_REPORTSERVICE_URI:http://localhost:8091} + - client: SEARCH + userName: ${CSO_SEARCH_USERNAME} + password: ${CSO_SEARCH_PASSWORD} + uri: ${CSO_SEARCH_URI:http://localhost:8091} + +ceis: + ceisBasePath: ${CEIS_BASE_PATH} + ceisUsername: ${CEIS_USERNAME} + ceisPassword: ${CEIS_PASSWORD} + +cso: + fileServerHost: ${CSO_FILE_SERVER_HOST} + csoBasePath: ${CSO_BASE_URL:http://localhost/cso} + csoPackagePath: ${CSO_PACKAGE_PATH:/accounts/bceidNotification.do?packageNo=} + debugEnabled: ${CSO_DEBUG_ENABLED:false} +bambora: + apiBasePath: ${BAMBORA_APIBASEPATH:http://localhost:8080} + apiPasscode: ${BAMBORA_APIPASSCODE} + merchantId: ${BAMBORA_MERCHANTID} + hostedProfileUrl: ${BAMBORA_PROFILE_URL} + hostedProfileServiceVersion: ${BAMBORA_PROFILE_SERVICE_VERSION} + hashKey: ${BAMBORA_HASHKEY} + minutesToExpiry: ${BAMBORA_URL_EXPIRY:10} +bcgov: + sftp: + host: ${SFTP_HOST:localhost} + port: ${SFTP_PORT:23} + username: ${SFTP_USERNAME:admin} + password: ${SFTP_PASSWORD:admin} + remoteLocation: ${SFTP_REMOTELOCATION} + knownHostsFileName: ${SFTP_KNOWNHOSTS} + allowUnknownKeys: ${SFTP_ALLOWUNKNOWN:true} + sshPrivateKey: ${SFTP_PRIVATE_KEY} + bceid: + service: + uri: ${BCEID_SERVICE_URI} + username: ${BCEID_SERVICE_USERNAME} + password: ${BCEID_SERVICE_PASSWORD} + onlineServiceId: ${BCEID_SERVICE_ONLINE_SERVICE_ID} + + clamav: + host: ${CLAMAV_HOST:localhost} + port: ${CLAMAV_PORT:3310} + timeout: ${CLAMAV_TIMEOUT:50000} info: app: - name: @project.name@ - description: @project.description@ - version: @project.version@ + name: "@project.name@" + description: "@project.description@" + version: "@project.version@" + +mailsend: + baseUrl: ${MAIL_SEND_BASE_URL:http://localhost:8090} + +parents: + - application: EFILING_ADMIN + returnUrl: ${EFILING_ADMIN_RETURN_URL:http://localhost:8080/rejected} + rejectedDocuments: ${EFILING_ADMIN_REJECTED_DOCUMENT:false} + - application: FLA + returnUrl: ${FLA_RETURN_URL:http://localhost:8080/rejected} + rejectedDocuments: ${FLA_REJECTED_DOCUMENT:false} + - application: BCCOA + returnUrl: ${BCCOA_RETURN_URL:http://localhost:8080/rejected} + rejectedDocuments: ${BCCOA_REJECTED_DOCUMENT:false} + - application: EDIVORCE + returnUrl: ${EDIVORCE_RETURN_URL:http://localhost:8080/rejected} + rejectedDocuments: ${EDIVORCE_REJECTED_DOCUMENT:false} + opentracing: jaeger: service-name: efilingApi enabled: TRUE udp-sender: host: localhost + +logging: + level: + root: INFO + ca.bc.gov.open.jag.aireviewerapi: ${LOGGING_LEVEL:INFO} diff --git a/src/backend/efiling-api/src/main/resources/logback-access.xml b/src/backend/efiling-api/src/main/resources/logback-access.xml index 6b72900908..0eb2526b9e 100644 --- a/src/backend/efiling-api/src/main/resources/logback-access.xml +++ b/src/backend/efiling-api/src/main/resources/logback-access.xml @@ -1,10 +1,17 @@ - combined + + + /health + + + NEUTRAL + DENY + diff --git a/src/backend/efiling-api/src/main/resources/logback-splunk.xml b/src/backend/efiling-api/src/main/resources/logback-splunk.xml index 7b41d26230..68affeb8e4 100644 --- a/src/backend/efiling-api/src/main/resources/logback-splunk.xml +++ b/src/backend/efiling-api/src/main/resources/logback-splunk.xml @@ -1,4 +1,4 @@ - + @@ -11,7 +11,7 @@ ${SPLUNK_URL} ${SPLUNK_TOKEN} jag-efiling-api - jag-efiling-access-logs + jag-efiling-logs HttpEventCollectorUnitTestMiddleware true 1 diff --git a/src/backend/efiling-api/src/test/efilling-api.postman_environment.json b/src/backend/efiling-api/src/test/efilling-api.postman_environment.json new file mode 100644 index 0000000000..c122de89f4 --- /dev/null +++ b/src/backend/efiling-api/src/test/efilling-api.postman_environment.json @@ -0,0 +1,44 @@ +{ + "id": "8a095ec6-e50b-4df6-8d02-3062c3b62770", + "name": "efilling-api", + "values": [ + { + "key": "baseUrl", + "value": "http://localhost:8080", + "enabled": true + }, + { + "key": "submissionId", + "value": "", + "enabled": true + }, + { + "key": "jwt", + "value": "", + "enabled": true + }, + { + "key": "client-secret", + "value": "", + "enabled": true + }, + { + "key": "X-Transaction-Id", + "value": "", + "enabled": true + }, + { + "key": "user-jwt", + "value": "", + "enabled": true + }, + { + "key": "keycloak-token-endpoint", + "value": "", + "enabled": true + } + ], + "_postman_variable_scope": "environment", + "_postman_exported_at": "2020-08-12T15:49:25.001Z", + "_postman_exported_using": "Postman/7.29.1" +} diff --git a/src/backend/efiling-api/src/test/jag-efiling-api.postman_collection.json b/src/backend/efiling-api/src/test/jag-efiling-api.postman_collection.json index 022de9e93c..00d487fd5c 100644 --- a/src/backend/efiling-api/src/test/jag-efiling-api.postman_collection.json +++ b/src/backend/efiling-api/src/test/jag-efiling-api.postman_collection.json @@ -1,83 +1,1676 @@ { "info": { - "_postman_id": "12584c3c-7c4d-4253-a3c2-96ca5fed2431", + "_postman_id": "1a173799-0b1d-42d8-9a83-5f0963d5907f", "name": "jag-efiling-api", + "description": "Efiling api", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, "item": [ { - "name": "generate url", - "request": { - "method": "POST", - "header": [ - { - "key": "X-Auth-UserId", - "value": "80AD31DA-0B8B-4E85-8F05-F693CF0B300D", - "type": "text" - } - ], - "body": { - "mode": "raw", - "raw": "{\r\n \"documentProperties\": {\r\n \"type\": \"DCFL\",\r\n \"subType\": \"string\",\r\n \"submissionAccess\": {\r\n \"url\": \"string\",\r\n \"verb\": \"GET\",\r\n \"headers\": {\r\n \"additionalProp1\": \"string\",\r\n \"additionalProp2\": \"string\",\r\n \"additionalProp3\": \"string\"\r\n }\r\n }\r\n },\r\n \"navigation\": {\r\n \"success\": {\r\n \"url\": \"string\"\r\n },\r\n \"error\": {\r\n \"url\": \"string\"\r\n },\r\n \"cancel\": {\r\n \"url\": \"string\"\r\n }\r\n }\r\n}", - "options": { - "raw": { - "language": "json" + "name": "Efiling-Clients", + "item": [ + { + "name": "1 - Get a JWT Token", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Get jwt\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.environment.set(\"jwt\", jsonData.access_token);\r", + "});" + ], + "type": "text/javascript" + } } - } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/x-www-form-urlencoded" + }, + { + "key": "Cookie", + "value": "8a49b93d4f41531bc1d1ef85f2b65254=2fb8f4c2fe6843d186204f21cc45dd4b" + } + ], + "body": { + "mode": "urlencoded", + "urlencoded": [ + { + "key": "client_id", + "value": "efiling-demo", + "type": "text" + }, + { + "key": "grant_type", + "value": "client_credentials", + "type": "text" + }, + { + "key": "client_secret", + "value": "{{client-secret}}", + "type": "text" + } + ] + }, + "url": { + "raw": "{{keycloak-token-endpoint}}", + "host": [ + "{{keycloak-token-endpoint}}" + ] + }, + "description": "To interact with the client endpoints, your Application needs to get a JWT from our Keycloak server." + }, + "response": [] }, - "url": { - "raw": "localhost:8080/submission/generateUrl", - "host": [ - "localhost" + { + "name": "2 - Upload Documents", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"submissionId\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.environment.set(\"submissionId\", jsonData.submissionId);\r", + "});" + ], + "type": "text/javascript" + } + } ], - "port": "8080", - "path": [ - "submission", - "generateUrl" + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "X-Transaction-Id", + "value": "{{X-Transaction-Id}}", + "description": "(Required) Authenticated user id" + }, + { + "key": "Content-Type", + "value": "multipart/form-data" + }, + { + "key": "X-User-Id", + "value": "{{X-User-Id}}", + "type": "text" + } + ], + "body": { + "mode": "formdata", + "formdata": [ + { + "key": "files", + "type": "file", + "src": "/C:/Users/177226/Desktop/test.pdf" + } + ] + }, + "url": { + "raw": "{{baseUrl}}/submission/documents", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + "documents" + ] + }, + "description": "Upload `one` or `many` documents to efling hub.\r\n\r\nTo Add multiple documents, add new document with the same key `files`" + }, + "response": [ + { + "name": "File successfully received", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "formdata", + "formdata": [ + { + "key": "files", + "value": "[\"\",\"\"]", + "type": "text" + } + ] + }, + "url": { + "raw": "{{baseUrl}}/submission/documents", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + "documents" + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"submissionId\": \"nisi\",\n \"received\": 29508064.475584164\n}" + } + ] + }, + { + "name": "3 - Generates a secure URL", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{jwt}}", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "X-Transaction-Id", + "value": "{{X-Transaction-Id}}", + "description": "(Required) Authenticated user id" + }, + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "X-User-Id", + "value": "{{X-User-Id}}", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigationUrls\": {\n \"success\": \"http//somewhere.com\",\n \"error\": \"http//somewhere.com\",\n \"cancel\": \"http//somewhere.com\"\n },\n \"clientAppName\": \"my app\",\n \"filingPackage\": {\n \"court\": {\n \"location\": \"1211\",\n \"level\": \"P\",\n \"courtClass\": \"F\"\n },\n \"documents\": [\n {\n \"name\": \"test.pdf\",\n \"type\": \"WNC\",\n \"statutoryFeeAmount\": 0,\n \"data\": {},\n \"md5\": \"string\"\n }\n ],\n \"parties\": [\n {\n \"partyType\": \"IND\",\n \"roleType\": \"CLA\",\n \"firstName\": \"first\",\n \"middleName\": \"middle\",\n \"lastName\": \"last\"\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/generateUrl", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "generateUrl" + ], + "variable": [ + { + "key": "id", + "value": "{{submissionId}}", + "description": "(Required) A submission id" + } + ] + }, + "description": "Generate a unique URL to rediect your users" + }, + "response": [ + { + "name": "File successfully received", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigation\": {\n \"success\": {\n \"url\": \"laboris adipisicing\"\n },\n \"error\": {\n \"url\": \"aliquip\"\n },\n \"cancel\": {\n \"url\": \"ad in\"\n }\n },\n \"clientApplication\": {\n \"displayName\": \"\",\n \"type\": \"\"\n },\n \"filingPackage\": {\n \"court\": {\n \"location\": \"\",\n \"level\": \"\",\n \"class\": \"\",\n \"division\": \"\",\n \"fileNumber\": \"\",\n \"participatingClass\": \"\"\n },\n \"documents\": [\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n },\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/generateUrl", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "generateUrl" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"expiryDate\": 65910561,\n \"efilingUrl\": \"exercitation officia pariatur magna i\"\n}" + }, + { + "name": "Request does not meet the required criteria", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigation\": {\n \"success\": {\n \"url\": \"laboris adipisicing\"\n },\n \"error\": {\n \"url\": \"aliquip\"\n },\n \"cancel\": {\n \"url\": \"ad in\"\n }\n },\n \"clientApplication\": {\n \"displayName\": \"\",\n \"type\": \"\"\n },\n \"filingPackage\": {\n \"court\": {\n \"location\": \"\",\n \"level\": \"\",\n \"class\": \"\",\n \"division\": \"\",\n \"fileNumber\": \"\",\n \"participatingClass\": \"\"\n },\n \"documents\": [\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n },\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/generateUrl", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "generateUrl" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "Forbidden", + "code": 403, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"error\": \"aliquip dolor\",\n \"message\": \"aliquip voluptate\"\n}" + } ] } - }, - "response": [] + ] }, { - "name": "userDetails", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "localhost:8080/submission/4fa58287-6f3b-471e-b0dd-7d30a1ab66df", - "host": [ - "localhost" - ], - "port": "8080", - "path": [ - "submission", - "4fa58287-6f3b-471e-b0dd-7d30a1ab66df" + "name": "Efling-Users", + "item": [ + { + "name": "submission", + "item": [ + { + "name": "{id}", + "item": [ + { + "name": "Get user detail for a given submission", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{user-jwt}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "X-Transaction-Id", + "value": "{{X-Transaction-Id}}", + "description": "(Required) Authenticated user id" + } + ], + "url": { + "raw": "{{baseUrl}}/submission/{{submissionId}}/config", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + "{{submissionId}}", + "config" + ] + } + }, + "response": [ + { + "name": "Config found", + "originalRequest": { + "method": "GET", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "url": { + "raw": "{{baseUrl}}/submission/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"userDetails\": {\n \"universalId\": \"amet velit\",\n \"firstName\": \"dolore qui commodo\",\n \"lastName\": \"id tempor quis enim Excepteur\",\n \"middleName\": \"ut magna occaecat\",\n \"email\": \"aute in\",\n \"accounts\": [\n {\n \"type\": \"BCEID\",\n \"identifier\": \"et elit dolor m\"\n },\n {\n \"type\": \"CSO\",\n \"identifier\": \"mollit reprehenderit adipisicing nulla\"\n }\n ]\n },\n \"navigation\": {\n \"success\": {\n \"url\": \"mollit dolore officia et adipisicing\"\n },\n \"error\": {\n \"url\": \"non reprehenderit laborum in laboris\"\n },\n \"cancel\": {\n \"url\": \"Ut s\"\n }\n },\n \"fees\": [\n {\n \"feeAmt\": -88520371.33262028,\n \"serviceTypeCd\": \"exercitation ipsum\"\n },\n {\n \"feeAmt\": 4171825.591308221,\n \"serviceTypeCd\": \"nisi\"\n }\n ]\n}" + }, + { + "name": "Config not found", + "originalRequest": { + "method": "GET", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "url": { + "raw": "{{baseUrl}}/submission/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "Not Found", + "code": 404, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "text/plain" + } + ], + "cookie": [], + "body": "" + } + ] + }, + { + "name": "Generates a secure URL for e-filing submission Copy", + "request": { + "auth": { + "type": "noauth" + }, + "method": "DELETE", + "header": [ + { + "key": "X-Transaction-Id", + "value": "{{X-Transaction-Id}}", + "description": "(Required) Authenticated user id" + }, + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "X-User-Id", + "value": "{{X-User-Id}}", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigation\": {\n \"success\": {\n \"url\": \"http//somewhere.com\"\n },\n \"error\": {\n \"url\": \"http//somewhere.com\"\n },\n \"cancel\": {\n \"url\": \"http//somewhere.com\"\n }\n },\n \"clientApplication\": {\n \"displayName\": \"my app\",\n \"type\": \"DCFL\"\n },\n \"filingPackage\": {\n \"court\": {\n \"location\": \"1211\",\n \"level\": \"P\",\n \"courtClass\": \"F\"\n },\n \"submissionFeeAmount\": 7.00,\n \"documents\": [\n {\n \"name\": \"test.pdf\",\n \"type\": \"WNC\",\n \"description\": \"Without Notice Application Checklist\",\n \"statutoryFeeAmount\": 0\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{submissionId}}", + "description": "(Required) A submission id" + } + ] + } + }, + "response": [ + { + "name": "File successfully received", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigation\": {\n \"success\": {\n \"url\": \"laboris adipisicing\"\n },\n \"error\": {\n \"url\": \"aliquip\"\n },\n \"cancel\": {\n \"url\": \"ad in\"\n }\n },\n \"clientApplication\": {\n \"displayName\": \"\",\n \"type\": \"\"\n },\n \"filingPackage\": {\n \"court\": {\n \"location\": \"\",\n \"level\": \"\",\n \"class\": \"\",\n \"division\": \"\",\n \"fileNumber\": \"\",\n \"participatingClass\": \"\"\n },\n \"documents\": [\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n },\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/generateUrl", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "generateUrl" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"expiryDate\": 65910561,\n \"efilingUrl\": \"exercitation officia pariatur magna i\"\n}" + }, + { + "name": "Request does not meet the required criteria", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigation\": {\n \"success\": {\n \"url\": \"laboris adipisicing\"\n },\n \"error\": {\n \"url\": \"aliquip\"\n },\n \"cancel\": {\n \"url\": \"ad in\"\n }\n },\n \"clientApplication\": {\n \"displayName\": \"\",\n \"type\": \"\"\n },\n \"filingPackage\": {\n \"court\": {\n \"location\": \"\",\n \"level\": \"\",\n \"class\": \"\",\n \"division\": \"\",\n \"fileNumber\": \"\",\n \"participatingClass\": \"\"\n },\n \"documents\": [\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n },\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/generateUrl", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "generateUrl" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "Forbidden", + "code": 403, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"error\": \"aliquip dolor\",\n \"message\": \"aliquip voluptate\"\n}" + } + ] + }, + { + "name": "update document list", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{user-jwt}}", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "X-Transaction-Id", + "value": "{{X-Transaction-Id}}", + "description": "(Required) Authenticated user id" + }, + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigation\": {\n \"success\": {\n \"url\": \"http//somewhere.com\"\n },\n \"error\": {\n \"url\": \"http//somewhere.com\"\n },\n \"cancel\": {\n \"url\": \"http//somewhere.com\"\n }\n },\n \"clientApplication\": {\n \"displayName\": \"my app\",\n \"type\": \"DCFL\"\n },\n \"filingPackage\": {\n \"court\": {\n \"location\": \"1211\",\n \"level\": \"P\",\n \"courtClass\": \"F\",\n \"division\": \"\",\n \"fileNumber\": \"\",\n \"participatingClass\": \"\"\n },\n \"submissionFeeAmount\": 7.00,\n \"documents\": [\n {\n \"name\": \"WAA-doc\",\n \"type\": \"WNC\",\n \"description\": \"Without Notice Application Checklist\",\n \"statutoryFeeAmount\": 0\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WRT\",\n \"description\": \"Writ of Summons\",\n \"statutoryFeeAmount\": null\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WRT\",\n \"description\": \"Writ of Summons\",\n \"statutoryFeeAmount\": null\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WRT\",\n \"description\": \"Writ of Summons\",\n \"statutoryFeeAmount\": null\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WRT\",\n \"description\": \"Writ of Summons\",\n \"statutoryFeeAmount\": null\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WRT\",\n \"description\": \"Writ of Summons\",\n \"statutoryFeeAmount\": null\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WRT\",\n \"description\": \"Writ of Summons\",\n \"statutoryFeeAmount\": null\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WRT\",\n \"description\": \"Writ of Summons\",\n \"statutoryFeeAmount\": null\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WAW\",\n \"description\": \"Warrant for Witness\",\n \"statutoryFeeAmount\": 0\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WRT\",\n \"description\": \"Writ of Summons\",\n \"statutoryFeeAmount\": null\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WRT\",\n \"description\": \"Writ of Summons\",\n \"statutoryFeeAmount\": null\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WAE\",\n \"description\": \"Warrant of Execution\",\n \"statutoryFeeAmount\": 0\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WEX\",\n \"description\": \"Warrant of Execution \",\n \"statutoryFeeAmount\": 0\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WAA\",\n \"description\": \"Warrant to Arrest\",\n \"statutoryFeeAmount\": 0\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WCT\",\n \"description\": \"Written Consent\",\n \"statutoryFeeAmount\": 0\n },\n {\n \"name\": \"WNC-doc\",\n \"type\": \"WAG\",\n \"description\": \"Written Agreement \",\n \"statutoryFeeAmount\": 0\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/generateUrl", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "generateUrl" + ], + "variable": [ + { + "key": "id", + "value": "{{submissionId}}", + "description": "(Required) A submission id" + } + ] + } + }, + "response": [ + { + "name": "Request does not meet the required criteria", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigation\": {\n \"success\": {\n \"url\": \"laboris adipisicing\"\n },\n \"error\": {\n \"url\": \"aliquip\"\n },\n \"cancel\": {\n \"url\": \"ad in\"\n }\n },\n \"clientApplication\": {\n \"displayName\": \"\",\n \"type\": \"\"\n },\n \"filingPackage\": {\n \"court\": {\n \"location\": \"\",\n \"level\": \"\",\n \"class\": \"\",\n \"division\": \"\",\n \"fileNumber\": \"\",\n \"participatingClass\": \"\"\n },\n \"documents\": [\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n },\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/generateUrl", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "generateUrl" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "Forbidden", + "code": 403, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"error\": \"aliquip dolor\",\n \"message\": \"aliquip voluptate\"\n}" + }, + { + "name": "File successfully received", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigation\": {\n \"success\": {\n \"url\": \"laboris adipisicing\"\n },\n \"error\": {\n \"url\": \"aliquip\"\n },\n \"cancel\": {\n \"url\": \"ad in\"\n }\n },\n \"clientApplication\": {\n \"displayName\": \"\",\n \"type\": \"\"\n },\n \"filingPackage\": {\n \"court\": {\n \"location\": \"\",\n \"level\": \"\",\n \"class\": \"\",\n \"division\": \"\",\n \"fileNumber\": \"\",\n \"participatingClass\": \"\"\n },\n \"documents\": [\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n },\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/generateUrl", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "generateUrl" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"expiryDate\": 65910561,\n \"efilingUrl\": \"exercitation officia pariatur magna i\"\n}" + } + ] + }, + { + "name": "rush processing", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{user-jwt}}", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "X-Transaction-Id", + "value": "{{X-Transaction-Id}}", + "description": "(Required) Authenticated user id" + }, + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"rushType\": \"rule\",\n \"firstName\": \"string\",\n \"lastName\": \"string\",\n \"organization\": \"string\",\n \"phoneNumber\": \"string\",\n \"email\": \"string\",\n \"country\": \"string\",\n \"countryCode\": \"string\",\n \"reason\": \"string\",\n \"status\": \"string\",\n \"supportingDocuments\": [\n {\n \"fileName\": \"string\",\n \"identifier\": \"string\"\n }\n ]\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/rushProcessing", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "rushProcessing" + ], + "variable": [ + { + "key": "id", + "value": "{{submissionId}}", + "description": "(Required) A submission id" + } + ] + } + }, + "response": [ + { + "name": "Request does not meet the required criteria", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigation\": {\n \"success\": {\n \"url\": \"laboris adipisicing\"\n },\n \"error\": {\n \"url\": \"aliquip\"\n },\n \"cancel\": {\n \"url\": \"ad in\"\n }\n },\n \"clientApplication\": {\n \"displayName\": \"\",\n \"type\": \"\"\n },\n \"filingPackage\": {\n \"court\": {\n \"location\": \"\",\n \"level\": \"\",\n \"class\": \"\",\n \"division\": \"\",\n \"fileNumber\": \"\",\n \"participatingClass\": \"\"\n },\n \"documents\": [\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n },\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/generateUrl", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "generateUrl" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "Forbidden", + "code": 403, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"error\": \"aliquip dolor\",\n \"message\": \"aliquip voluptate\"\n}" + }, + { + "name": "File successfully received", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigation\": {\n \"success\": {\n \"url\": \"laboris adipisicing\"\n },\n \"error\": {\n \"url\": \"aliquip\"\n },\n \"cancel\": {\n \"url\": \"ad in\"\n }\n },\n \"clientApplication\": {\n \"displayName\": \"\",\n \"type\": \"\"\n },\n \"filingPackage\": {\n \"court\": {\n \"location\": \"\",\n \"level\": \"\",\n \"class\": \"\",\n \"division\": \"\",\n \"fileNumber\": \"\",\n \"participatingClass\": \"\"\n },\n \"documents\": [\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n },\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/generateUrl", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "generateUrl" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"expiryDate\": 65910561,\n \"efilingUrl\": \"exercitation officia pariatur magna i\"\n}" + } + ] + }, + { + "name": "rush documents", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{user-jwt}}", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "key": "X-Transaction-Id", + "value": "{{X-Transaction-Id}}", + "description": "(Required) Authenticated user id" + }, + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "formdata", + "formdata": [ + { + "key": "", + "type": "file", + "src": [] + } + ] + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/rushDocuments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "rushDocuments" + ], + "variable": [ + { + "key": "id", + "value": "{{submissionId}}", + "description": "(Required) A submission id" + } + ] + } + }, + "response": [ + { + "name": "Request does not meet the required criteria", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigation\": {\n \"success\": {\n \"url\": \"laboris adipisicing\"\n },\n \"error\": {\n \"url\": \"aliquip\"\n },\n \"cancel\": {\n \"url\": \"ad in\"\n }\n },\n \"clientApplication\": {\n \"displayName\": \"\",\n \"type\": \"\"\n },\n \"filingPackage\": {\n \"court\": {\n \"location\": \"\",\n \"level\": \"\",\n \"class\": \"\",\n \"division\": \"\",\n \"fileNumber\": \"\",\n \"participatingClass\": \"\"\n },\n \"documents\": [\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n },\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/generateUrl", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "generateUrl" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "Forbidden", + "code": 403, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"error\": \"aliquip dolor\",\n \"message\": \"aliquip voluptate\"\n}" + }, + { + "name": "File successfully received", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigation\": {\n \"success\": {\n \"url\": \"laboris adipisicing\"\n },\n \"error\": {\n \"url\": \"aliquip\"\n },\n \"cancel\": {\n \"url\": \"ad in\"\n }\n },\n \"clientApplication\": {\n \"displayName\": \"\",\n \"type\": \"\"\n },\n \"filingPackage\": {\n \"court\": {\n \"location\": \"\",\n \"level\": \"\",\n \"class\": \"\",\n \"division\": \"\",\n \"fileNumber\": \"\",\n \"participatingClass\": \"\"\n },\n \"documents\": [\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n },\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/generateUrl", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "generateUrl" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"expiryDate\": 65910561,\n \"efilingUrl\": \"exercitation officia pariatur magna i\"\n}" + } + ] + }, + { + "name": "Submit filing", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{user-jwt}}", + "type": "string" + } + ] + }, + "method": "POST", + "header": [ + { + "description": "(Required) Authenticated user id", + "key": "X-Transaction-Id", + "value": "{{X-Transaction-Id}}" + }, + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/{{submissionId}}/submit", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + "{{submissionId}}", + "submit" + ] + } + }, + "response": [ + { + "name": "File successfully received", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigation\": {\n \"success\": {\n \"url\": \"laboris adipisicing\"\n },\n \"error\": {\n \"url\": \"aliquip\"\n },\n \"cancel\": {\n \"url\": \"ad in\"\n }\n },\n \"clientApplication\": {\n \"displayName\": \"\",\n \"type\": \"\"\n },\n \"filingPackage\": {\n \"court\": {\n \"location\": \"\",\n \"level\": \"\",\n \"class\": \"\",\n \"division\": \"\",\n \"fileNumber\": \"\",\n \"participatingClass\": \"\"\n },\n \"documents\": [\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n },\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/generateUrl", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "generateUrl" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"expiryDate\": 65910561,\n \"efilingUrl\": \"exercitation officia pariatur magna i\"\n}" + }, + { + "name": "Request does not meet the required criteria", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"navigation\": {\n \"success\": {\n \"url\": \"laboris adipisicing\"\n },\n \"error\": {\n \"url\": \"aliquip\"\n },\n \"cancel\": {\n \"url\": \"ad in\"\n }\n },\n \"clientApplication\": {\n \"displayName\": \"\",\n \"type\": \"\"\n },\n \"filingPackage\": {\n \"court\": {\n \"location\": \"\",\n \"level\": \"\",\n \"class\": \"\",\n \"division\": \"\",\n \"fileNumber\": \"\",\n \"participatingClass\": \"\"\n },\n \"documents\": [\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n },\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n }\n ]\n }\n}" + }, + "url": { + "raw": "{{baseUrl}}/submission/:id/generateUrl", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "generateUrl" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "Forbidden", + "code": 403, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"error\": \"aliquip dolor\",\n \"message\": \"aliquip voluptate\"\n}" + } + ] + }, + { + "name": "Get filing package information", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{user-jwt}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "X-Transaction-Id", + "value": "{{X-Transaction-Id}}", + "description": "(Required) Authenticated user id" + } + ], + "url": { + "raw": "{{baseUrl}}/submission/:id/filing-package", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "filing-package" + ], + "variable": [ + { + "key": "id", + "value": "{{submissionId}}", + "description": "(Required) A submission id" + } + ] + } + }, + "response": [ + { + "name": "Filing Package Information found", + "originalRequest": { + "method": "GET", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "url": { + "raw": "{{baseUrl}}/submission/:id/filing-package", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "filing-package" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"court\": {\n \"location\": \"\",\n \"level\": \"\",\n \"class\": \"\",\n \"division\": \"\",\n \"fileNumber\": \"\",\n \"participatingClass\": \"\"\n },\n \"documents\": [\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n },\n {\n \"type\": \"\",\n \"name\": \"\",\n \"description\": \"\"\n }\n ]\n}" + }, + { + "name": "Filing Package Information not found", + "originalRequest": { + "method": "GET", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "url": { + "raw": "{{baseUrl}}/submission/:id/filing-package", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "filing-package" + ], + "variable": [ + { + "key": "id" + } + ] + } + }, + "status": "Not Found", + "code": 404, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "text/plain" + } + ], + "cookie": [], + "body": "" + } + ] + }, + { + "name": "Get document by name", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{user-jwt}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "X-Transaction-Id", + "value": "{{X-Transaction-Id}}", + "description": "(Required) Authenticated user id" + } + ], + "url": { + "raw": "{{baseUrl}}/submission/:id/document/:filename", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "document", + ":filename" + ], + "variable": [ + { + "key": "id", + "value": "{{submissionId}}", + "description": "(Required) A submission id" + }, + { + "key": "filename", + "value": "test.pdf", + "description": "(Required) A document name" + } + ] + } + }, + "response": [ + { + "name": "Filing Package Information found", + "originalRequest": { + "method": "GET", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "url": { + "raw": "{{baseUrl}}/submission/:id/document/:filename", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "document", + ":filename" + ], + "variable": [ + { + "key": "id" + }, + { + "key": "filename" + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "application/octet-stream" + } + ], + "cookie": [], + "body": "ea" + }, + { + "name": "Document not found", + "originalRequest": { + "method": "GET", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "url": { + "raw": "{{baseUrl}}/submission/:id/document/:filename", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "submission", + ":id", + "document", + ":filename" + ], + "variable": [ + { + "key": "id" + }, + { + "key": "filename" + } + ] + } + }, + "status": "Not Found", + "code": 404, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "text/plain" + } + ], + "cookie": [], + "body": "" + } + ] + } + ] + } + ] + }, + { + "name": "payment", + "item": [ + { + "name": "GeneratePaymentUrl", + "request": { + "method": "POST", + "header": [ + { + "key": "X-Transaction-Id", + "value": "{{X-Transaction-Id}}", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\r\n \"clientId\": 123,\r\n \"redirectUrl\": \"localhost:3000/efiling\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/payment/generate-update-card", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "payment", + "generate-update-card" + ] + } + }, + "response": [] + } + ] + }, + { + "name": "account", + "item": [ + { + "name": "Create a CSO account", + "request": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "{{x-Auth-UserId}}", + "description": "(Required) Authenticated user id" + }, + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"firstName\": \"string\",\n \"lastName\": \"string\",\n \"middleName\": \"string\",\n \"email\": \"string\"\n}" + }, + "url": { + "raw": "{{baseUrl}}/csoAccount", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "csoAccount" + ] + }, + "description": "In order to create an account, an item with type BCeID is required in the accounts field." + }, + "response": [ + { + "name": "Account Created", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"universalId\": \"\",\n \"firstName\": \"\",\n \"lastName\": \"\",\n \"middleName\": \"\",\n \"email\": \"\",\n \"accounts\": [\n {\n \"type\": \"CSO\",\n \"identifier\": \"velit et cupidatat laborum eu\"\n },\n {\n \"type\": \"BCEID\",\n \"identifier\": \"in adipisicing tempor\"\n }\n ]\n}" + }, + "url": { + "raw": "{{baseUrl}}/csoAccount", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "csoAccount" + ] + } + }, + "status": "Created", + "code": 201, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"universalId\": \"\",\n \"firstName\": \"\",\n \"lastName\": \"\",\n \"middleName\": \"\",\n \"email\": \"\",\n \"accounts\": [\n {\n \"type\": \"CSO\",\n \"identifier\": \"velit et cupidatat laborum eu\"\n },\n {\n \"type\": \"BCEID\",\n \"identifier\": \"in adipisicing tempor\"\n }\n ]\n}" + } + ] + }, + { + "name": "Update Cso Account", + "request": { + "method": "PUT", + "header": [ + { + "description": "(Required) Authenticated user id", + "key": "X-Auth-UserId", + "value": "{{x-Auth-UserId}}" + }, + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"internalClientNumber\": \"string\"\n}" + }, + "url": { + "raw": "{{baseUrl}}/csoAccount", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "csoAccount" + ] + }, + "description": "In order to create an account, an item with type BCeID is required in the accounts field." + }, + "response": [ + { + "name": "Account Created", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "X-Auth-UserId", + "value": "", + "description": "(Required) Authenticated user id" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"universalId\": \"\",\n \"firstName\": \"\",\n \"lastName\": \"\",\n \"middleName\": \"\",\n \"email\": \"\",\n \"accounts\": [\n {\n \"type\": \"CSO\",\n \"identifier\": \"velit et cupidatat laborum eu\"\n },\n {\n \"type\": \"BCEID\",\n \"identifier\": \"in adipisicing tempor\"\n }\n ]\n}" + }, + "url": { + "raw": "{{baseUrl}}/csoAccount", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "csoAccount" + ] + } + }, + "status": "Created", + "code": 201, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\n \"universalId\": \"\",\n \"firstName\": \"\",\n \"lastName\": \"\",\n \"middleName\": \"\",\n \"email\": \"\",\n \"accounts\": [\n {\n \"type\": \"CSO\",\n \"identifier\": \"velit et cupidatat laborum eu\"\n },\n {\n \"type\": \"BCEID\",\n \"identifier\": \"in adipisicing tempor\"\n }\n ]\n}" + } + ] + }, + { + "name": "Get cso Account", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "" + } + }, + "response": [] + } + ] + }, + { + "name": "lookup", + "item": [ + { + "name": "get document types", + "request": { + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{user-jwt}}", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "X-Transaction-Id", + "value": "{{X-Transaction-Id}}", + "type": "text" + } + ], + "url": { + "raw": "{{baseUrl}}/lookup/documentTypes/P/F", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "lookup", + "documentTypes", + "P", + "F" + ] + } + }, + "response": [] + } ] } - }, - "response": [] + ] }, { - "name": "acutator", - "request": { - "method": "GET", - "header": [], - "url": { - "raw": "http://localhost:8080/actuator/info", - "protocol": "http", - "host": [ - "localhost" - ], - "port": "8080", - "path": [ - "actuator", - "info" - ] + "name": "System", + "item": [ + { + "name": "health", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/actuator/health", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "actuator", + "health" + ] + } + }, + "response": [] } - }, - "response": [] + ] } ], - "protocolProfileBehavior": {} + "variable": [ + { + "key": "baseUrl", + "value": "http://localhost:8080", + "type": "string" + } + ] } \ No newline at end of file diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/TestHelpers.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/TestHelpers.java index c61cedce83..3983addf02 100644 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/TestHelpers.java +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/TestHelpers.java @@ -1,12 +1,17 @@ package ca.bc.gov.open.jag.efilingapi; -import ca.bc.gov.open.jag.efilingapi.api.model.DocumentProperties; -import ca.bc.gov.open.jag.efilingapi.api.model.Redirect; -import ca.bc.gov.open.jag.efilingapi.api.model.EndpointAccess; -import ca.bc.gov.open.jag.efilingapi.api.model.Navigation; +import ca.bc.gov.open.jag.efilingapi.api.model.InitialDocument; +import ca.bc.gov.open.jag.efilingapi.api.model.InitialPackage; +import ca.bc.gov.open.jag.efilingapi.api.model.NavigationUrls; +import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingapi.submission.models.SubmissionConstants; +import ca.bc.gov.open.jag.efilingcommons.model.*; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.*; +import org.joda.time.DateTime; -import java.util.Collections; -import java.util.UUID; +import java.math.BigDecimal; +import java.util.*; public class TestHelpers { @@ -16,39 +21,383 @@ public class TestHelpers { public static final UUID CASE_4 = UUID.fromString("77da92db-0791-491e-8c58-1a969e67d2fc"); public static final UUID CASE_5 = UUID.fromString("77da92db-0791-491e-8c58-1a969e67d2fd"); + public static final String CASE_1_STRING = CASE_1.toString(); + public static final String CASE_2_STRING = CASE_2.toString(); + + public static final String IDENTITY_PROVIDER = "IDENTITY_PROVIDER"; + public static final String DIVISION = "DIVISION"; + public static final String FILENUMBER = "FILENUMBER"; + public static final String LEVEL = "LEVEL"; + public static final String LOCATION = "1211"; + public static final String PARTICIPATIONCLASS = "PARTICIPATIONCLASS"; + public static final String PROPERTYCLASS = "PROPERTYCLASS"; + public static final String DESCRIPTION = "DESCRIPTION"; + public static final String COURT_DESCRIPTION = "TESTCOURTDESC"; + public static final String LEVEL_DESCRIPTION = "TESTLEVELDESC"; + public static final String CLASS_DESCRIPTION = "TESTCLASSDESC"; + public static final String SUCCESS_URL = "http://success"; public static final String CANCEL_URL = "http://cancel"; public static final String ERROR_URL = "http://error"; - public static DocumentProperties createDocumentProperties(String header, String url, String subtype, String type) { - DocumentProperties documentProperties = new DocumentProperties(); - EndpointAccess documentAccess = new EndpointAccess(); - documentAccess.setHeaders(Collections.singletonMap(header, header)); - documentAccess.setUrl(url); - documentAccess.setVerb(EndpointAccess.VerbEnum.POST); - documentProperties.setSubmissionAccess(documentAccess); - documentProperties.setSubType(subtype); - documentProperties.setType(type); - return documentProperties; - } - - public static Navigation createNavigation(String success, String cancel, String error) { - Navigation navigation = new Navigation(); - Redirect successRedirect = new Redirect(); - successRedirect.setUrl(success); - navigation.setSuccess(successRedirect); - Redirect cancelRedirect = new Redirect(); - cancelRedirect.setUrl(cancel); - navigation.setCancel(cancelRedirect); - Redirect errorRedirect = new Redirect(); - errorRedirect.setUrl(error); - navigation.setError(errorRedirect); + public static final String FIRST_NAME = "FIRSTNAME"; + public static final String MIDDLE_NAME = "MIDDLENAME"; + public static final String LAST_NAME = "LASTNAME"; + public static final String NAME_TYPE_CD = "NAMECD"; + public static final String ROLE_TYPE_CD = "ABC"; + + public static final String COURT_CLASS = "COURT_CLASS"; + public static final String FILE_NUMBER = "FILE_NUMBER"; + public static final String LOCATION_DESCRIPTION = "LOCATION_DESCRIPTION"; + public static final String PARTICIPATING_CLASS = "PARTICIPATING_CLASS"; + public static final String NAME_TYPE = "NAME_TYPE"; + public static final String NAME = "NAME"; + public static final String STATUS = "STATUS"; + public static final String STATUS_CODE = "STATUSCODE"; + public static final String COMMENT = "COMMENT"; + public static final String PACKAGE_NO = "123"; + public static final String DOCUMENT_ID_ONE = "1"; + public static final String DOCUMENT_ID_TWO = "2"; + public static final BigDecimal DOCUMENT_ID_TWO_BD = new BigDecimal(2); + + public static final String TYPE = "AAB"; + public static final String PARTY_TYPE_DESC = "PARTY_TYPE_DESC"; + public static final String ROLE_TYPE_DESC = "ROLE_TYPE_DESC"; + public static final String TRANSACTION_DESC = "TRANSACTION_DESC"; + public static final String CONTACT_EMAIL_TXT = "hello@hello.com"; + public static final String ORGANIZATION_NM = "Paint It"; + public static final String CONTACT_PHONE_NO = "1231231234"; + public static final String CURRENT_STATUS_DSC = "Processing"; + public static final String COUNTRY_DSC = "Canada"; + public static final String PROCESS_REASON_CD = "OTHR"; + public static final String NOTICE_REASON_TEXT = "Registry notice reason text"; + public static final String RUSH_FILING_REASON_TXT = "This is a reason. This is a reason. This is a reason. This is a reason."; + public static final String CLIENT_FILE_NM = "Test.pdf"; + public static final String OBJECT_GUID = "9b35f5d6-50e9-4cd5-9d46-8ce1f9e484c8"; + public static final String APPLICATION_CODE = "TESTPARENT"; + + + public static InitialPackage createInitalPackage(ca.bc.gov.open.jag.efilingapi.api.model.CourtBase court, List initialDocuments) { + InitialPackage initialPackage = new InitialPackage(); + initialPackage.setCourt(court); + initialPackage.setDocuments(initialDocuments); + initialPackage.setParties(new ArrayList<>()); + initialPackage.setOrganizationParties(new ArrayList<>()); + return initialPackage; + } + + public static NavigationUrls createNavigation(String success, String cancel, String error) { + NavigationUrls navigation = new NavigationUrls(); + navigation.setSuccess(success); + navigation.setCancel(cancel); + navigation.setError(error); return navigation; } - public static Navigation createDefaultNavigation() { + public static ca.bc.gov.open.jag.efilingapi.api.model.CourtBase createApiCourtBase() { + ca.bc.gov.open.jag.efilingapi.api.model.CourtBase court = new ca.bc.gov.open.jag.efilingapi.api.model.CourtBase(); + court.setDivision(DIVISION); + court.setFileNumber(FILENUMBER); + court.setLevel(LEVEL); + court.setLocation(LOCATION); + court.setParticipatingClass(PARTICIPATIONCLASS); + court.setCourtClass(PROPERTYCLASS); + return court; + } + + public static ca.bc.gov.open.jag.efilingapi.api.model.CourtBase createApiCourtBase(String location) { + ca.bc.gov.open.jag.efilingapi.api.model.CourtBase court = new ca.bc.gov.open.jag.efilingapi.api.model.CourtBase(); + court.setDivision(DIVISION); + court.setFileNumber(FILENUMBER); + court.setLevel(LEVEL); + court.setLocation(location); + court.setParticipatingClass(PARTICIPATIONCLASS); + court.setCourtClass(PROPERTYCLASS); + return court; + } + + public static Court createCourt() { + return Court.builder() + .division(DIVISION) + .fileNumber(FILENUMBER) + .level(LEVEL) + .location(LOCATION) + .participatingClass(PARTICIPATIONCLASS) + .courtClass(PROPERTYCLASS) + .agencyId(BigDecimal.TEN) + .levelDescription(LEVEL_DESCRIPTION) + .classDescription(CLASS_DESCRIPTION) + .locationDescription(COURT_DESCRIPTION).create(); + } + + public static Submission buildSubmission() { + return Submission + .builder() + .filingPackage(createPackage(createCourt(), createDocumentList(), createPartyList(), createOrganizationList())) + .navigationUrls(createNavigation(SUCCESS_URL, CANCEL_URL, ERROR_URL)) + .create(); + } + + public static FilingPackage createPackage( + Court court, + List documents, + List parties, + List organizations) { + return FilingPackage.builder() + .packageNumber(BigDecimal.TEN) + .court(court) + .documents(documents) + .parties(parties) + .organizations(organizations) + .create(); + } + + public static List createInitialDocumentsList() { + InitialDocument initialDocument = new InitialDocument(); + initialDocument.setName("random.txt"); + initialDocument.setType("AAB"); + return Arrays.asList(initialDocument); + } + + public static List createValidDocumentTypesList() { + DocumentTypeDetails documentTypeDetails = new DocumentTypeDetails(DESCRIPTION, TYPE, BigDecimal.TEN, false, false, false); + return Arrays.asList(documentTypeDetails); + } + + public static List createInvalidDocumentTypesList() { + DocumentTypeDetails documentTypeDetails = new DocumentTypeDetails(DESCRIPTION, "ZZZ", BigDecimal.TEN, false, false, false); + return Arrays.asList(documentTypeDetails); + } + + public static List createInvalidPartyRoles() { + List invalidRoles = new ArrayList<>(); + invalidRoles.add(ROLE_TYPE_CD); + + return invalidRoles; + } + + public static List createValidPartyRoles() { + List validRoles = new ArrayList<>(); + validRoles.add("ABC"); + + return validRoles; + } + + public static List createDocumentList() { + return Arrays.asList(Document.builder() + .description(DESCRIPTION) + .statutoryFeeAmount(BigDecimal.TEN) + .name("random.txt") + .type(TYPE) + .subType(SubmissionConstants.SUBMISSION_ORDR_DOCUMENT_SUB_TYPE_CD) + .mimeType("application/txt") + .isSupremeCourtScheduling(true) + .isAmendment(true) + .actionDocument(ActionDocument.builder() + .documentId(BigDecimal.TEN) + .status("REJ") + .type("TEST") + .create()) + .data(new Object()).create()); + } + + public static List createPartyList() { + + Individual individualOne = buildParty(); + + Individual individualTwo = buildParty(); + return Arrays.asList(individualOne, individualTwo); + } + + public static List createOrganizationList() { + + Organization orgOne = buildOrganization(); + + Organization orgTwo = buildOrganization(); + return Arrays.asList(orgOne, orgTwo); + } + + private static Individual buildParty() { + return Individual.builder() + .firstName(FIRST_NAME) + .middleName(MIDDLE_NAME) + .lastName(LAST_NAME) + .nameTypeCd(NAME_TYPE_CD) + .roleTypeCd(ROLE_TYPE_CD) + .create(); + } + + private static Organization buildOrganization() { + return Organization.builder() + .name(NAME) + .nameTypeCd(NAME_TYPE_CD) + .roleTypeCd(ROLE_TYPE_CD) + .create(); + } + + public static AccountDetails createCSOAccountDetails(boolean isFileRolePresent) { + return AccountDetails.builder().fileRolePresent(isFileRolePresent).create(); + } + + public static NavigationUrls createDefaultNavigation() { return createNavigation(SUCCESS_URL, CANCEL_URL, ERROR_URL); } + public static AccountDetails createAccount(BigDecimal clientId) { + + return AccountDetails.builder() + .fileRolePresent(true) + .accountId(BigDecimal.ONE) + .clientId(clientId) + .cardRegistered(true) + .universalId(UUID.randomUUID().toString()) + .internalClientNumber(null) + .universalId(TestHelpers.CASE_1_STRING).create(); + + } + + public static ReviewFilingPackage createFilingPackage(Boolean hasRegistry) { + + ReviewFilingPackage reviewFilingPackage = new ReviewFilingPackage(); + reviewFilingPackage.setApplicationCode(APPLICATION_CODE); + reviewFilingPackage.setHasRegistryNotice(hasRegistry); + reviewFilingPackage.setClientFileNo("CLIENTFILENO"); + reviewFilingPackage.setFilingCommentsTxt(COMMENT); + reviewFilingPackage.setPackageNo(PACKAGE_NO); + reviewFilingPackage.setFirstName(FIRST_NAME); + reviewFilingPackage.setLastName(LAST_NAME); + reviewFilingPackage.setSubmittedDate(DateTime.parse("2020-05-05T00:00:00.000-07:00")); + reviewFilingPackage.setCourt(createReviewCourt()); + reviewFilingPackage.setDocuments(createDocuments()); + reviewFilingPackage.setParties(Collections.singletonList(createParty())); + reviewFilingPackage.setPayments(Collections.singletonList(createPayment())); + reviewFilingPackage.setPackageLinks(PackageLinks.builder().packageHistoryUrl("http://localhost:8080/showmustgoon").create()); + reviewFilingPackage.setRushOrder(createReviewRushOrder()); + return reviewFilingPackage; + + } + + public static ReviewCourt createReviewCourt() { + + ReviewCourt reviewCourt = new ReviewCourt(); + reviewCourt.setClassDescription(CLASS_DESCRIPTION); + reviewCourt.setCourtClass(COURT_CLASS); + reviewCourt.setDivision(DIVISION); + reviewCourt.setFileNumber(FILE_NUMBER); + reviewCourt.setLevel(LEVEL); + reviewCourt.setLevelDescription(LEVEL_DESCRIPTION); + reviewCourt.setLocationId(BigDecimal.ONE); + reviewCourt.setLocationName(LOCATION); + reviewCourt.setLocationDescription(LOCATION_DESCRIPTION); + reviewCourt.setParticipatingClass(PARTICIPATING_CLASS); + return reviewCourt; + + } + public static Individual createParty() { + return Individual.builder() + .firstName(FIRST_NAME) + .lastName(LAST_NAME) + .middleName(MIDDLE_NAME) + .nameTypeCd(NAME_TYPE) + .partyTypeDesc(PARTY_TYPE_DESC) + .roleTypeCd(ca.bc.gov.open.jag.efilingapi.api.model.Party.RoleTypeEnum.ABC.getValue()) + .roleTypeDesc(ROLE_TYPE_DESC) + .create(); + } + + public static List createDocuments() { + + ReviewDocument reviewDocumentOne = new ReviewDocument(); + reviewDocumentOne.setDocumentId(DOCUMENT_ID_ONE); + reviewDocumentOne.setFileName(NAME); + reviewDocumentOne.setDocumentTypeCd("AAB"); + reviewDocumentOne.setDocumentType(DESCRIPTION); + reviewDocumentOne.setStatus(STATUS); + reviewDocumentOne.setStatusCode(STATUS_CODE); + reviewDocumentOne.setDateFiled(DateTime.parse("2020-05-05T00:00:00.000-07:00")); + reviewDocumentOne.setStatusDate(DateTime.parse("2020-05-05T00:00:00.000-07:00")); + reviewDocumentOne.setPaymentProcessed(true); + + ReviewDocument reviewDocumentTwo = new ReviewDocument(); + reviewDocumentTwo.setDocumentId(DOCUMENT_ID_TWO); + reviewDocumentTwo.setFileName(NAME); + reviewDocumentTwo.setDocumentTypeCd("AAB"); + reviewDocumentTwo.setDocumentType(DESCRIPTION); + reviewDocumentTwo.setStatus(STATUS); + reviewDocumentTwo.setStatusCode(Keys.REJECTED_DOCUMENT_CODE); + reviewDocumentTwo.setDateFiled(DateTime.parse("2020-05-05T00:00:00.000-07:00")); + reviewDocumentTwo.setStatusDate(DateTime.parse("2020-05-05T00:00:00.000-07:00")); + reviewDocumentTwo.setPaymentProcessed(true); + + ArrayList documents = new ArrayList<>(); + documents.add(reviewDocumentOne); + documents.add(reviewDocumentTwo); + return documents; + + } + + public static PackagePayment createPayment() { + + PackagePayment packagePayment = new PackagePayment(); + packagePayment.setFeeExmpt(false); + packagePayment.setPaymentCategory(BigDecimal.ONE); + packagePayment.setProcessedAmt(BigDecimal.ONE); + packagePayment.setSubmittedAmt(BigDecimal.ONE); + packagePayment.setServiceId(BigDecimal.ONE); + packagePayment.setTransactionDesc(TRANSACTION_DESC); + packagePayment.setTransactionDtm(DateTime.parse("2020-05-05T00:00:00.000-07:00")); + return packagePayment; + + } + + public static ReviewRushOrder createReviewRushOrder() { + ReviewRushOrder reviewRushOrder = new ReviewRushOrder(); + reviewRushOrder.setContactEmailTxt(CONTACT_EMAIL_TXT); + reviewRushOrder.setContactFirstGivenNm(FIRST_NAME); + reviewRushOrder.setContactSurnameNm(LAST_NAME); + reviewRushOrder.setContactOrganizationNm(ORGANIZATION_NM); + reviewRushOrder.setContactPhoneNo(CONTACT_PHONE_NO); + reviewRushOrder.setCurrentStatusDsc(CURRENT_STATUS_DSC); + reviewRushOrder.setCtryId(BigDecimal.ONE); + reviewRushOrder.setCountryDsc(COUNTRY_DSC); + reviewRushOrder.setCourtOrderDt(DateTime.parse("2020-05-05T00:00:00.000-07:00")); + reviewRushOrder.setPackageId(BigDecimal.ONE); + reviewRushOrder.setProcessReasonCd(PROCESS_REASON_CD); + reviewRushOrder.setProcessingCommentTxt(NOTICE_REASON_TEXT); + reviewRushOrder.setRushFilingReasonTxt(RUSH_FILING_REASON_TXT); + reviewRushOrder.setSupportDocs(createRushDocuments()); + return reviewRushOrder; + } + + private static List createRushDocuments() { + RushDocument rushDocumentOne = new RushDocument(); + rushDocumentOne.setClientFileNm(CLIENT_FILE_NM); + rushDocumentOne.setEntDtm(new DateTime()); + rushDocumentOne.setEntUserId("1"); + rushDocumentOne.setFileServer("www.google.com"); + rushDocumentOne.setObjectGuid(OBJECT_GUID); + rushDocumentOne.setProcessItemSeqNo(BigDecimal.ONE); + rushDocumentOne.setProcessRequestId(BigDecimal.ONE); + rushDocumentOne.setProcessSupportDocSeqNo(BigDecimal.ONE); + rushDocumentOne.setTempFileName("Test.pdf"); + rushDocumentOne.setUpdUserId("1"); + rushDocumentOne.setUpdDtm(new DateTime()); + + RushDocument rushDocumentTwo = new RushDocument(); + rushDocumentTwo.setClientFileNm(CLIENT_FILE_NM); + rushDocumentTwo.setEntDtm(new DateTime()); + rushDocumentTwo.setEntUserId("1"); + rushDocumentTwo.setFileServer("www.google.com"); + rushDocumentTwo.setObjectGuid(OBJECT_GUID); + rushDocumentTwo.setProcessItemSeqNo(BigDecimal.ONE); + rushDocumentTwo.setProcessRequestId(BigDecimal.ONE); + rushDocumentTwo.setProcessSupportDocSeqNo(BigDecimal.ONE); + rushDocumentTwo.setTempFileName("Test.pdf"); + rushDocumentTwo.setUpdUserId("1"); + rushDocumentTwo.setUpdDtm(new DateTime()); + + return Arrays.asList(rushDocumentOne, rushDocumentTwo); + + } } diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/account/AccountConfigTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/account/AccountConfigTest.java new file mode 100644 index 0000000000..c58d1f0448 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/account/AccountConfigTest.java @@ -0,0 +1,69 @@ +package ca.bc.gov.open.jag.efilingapi.account; + +import ca.bc.gov.open.jag.efilingapi.account.mappers.CsoAccountMapper; +import ca.bc.gov.open.jag.efilingapi.account.mappers.CsoAccountMapperImpl; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.CreateAccountRequest; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import static org.assertj.core.api.Assertions.assertThat; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class AccountConfigTest { + + @Configuration + public static class TestConfig { + + @Bean + public EfilingAccountService efilingAccountService() { + return new EfilingAccountService() { + @Override + public AccountDetails getAccountDetails(String userGuid) { + return null; + } + + @Override + public AccountDetails createAccount(CreateAccountRequest createAccountRequest) { + return null; + } + + @Override + public void updateClient(AccountDetails accountDetails) { + + } + + @Override + public String getOrderNumber() { + return null; + } + }; + } + + } + + + ApplicationContextRunner context = new ApplicationContextRunner() + .withUserConfiguration(TestConfig.class) + .withUserConfiguration(AccountConfig.class); + + @Test + public void testConfigure() throws Exception { + + context.run(it -> { + assertThat(it).hasSingleBean(AccountService.class); + assertThat(it).hasSingleBean(CsoAccountMapper.class); + + Assertions.assertEquals(CsoAccountMapperImpl.class, it.getBean(CsoAccountMapper.class).getClass()); + + }); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/account/BceidAccountApiDelegateImplTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/account/BceidAccountApiDelegateImplTest.java new file mode 100644 index 0000000000..971556d3a4 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/account/BceidAccountApiDelegateImplTest.java @@ -0,0 +1,120 @@ +package ca.bc.gov.open.jag.efilingapi.account; + +import ca.bc.gov.open.bceid.starter.account.BCeIDAccountService; +import ca.bc.gov.open.bceid.starter.account.models.IndividualIdentity; +import ca.bc.gov.open.bceid.starter.account.models.Name; +import ca.bc.gov.open.jag.efilingapi.account.mappers.BceidAccountMapper; +import ca.bc.gov.open.jag.efilingapi.account.mappers.BceidAccountMapperImpl; +import ca.bc.gov.open.jag.efilingapi.api.model.BceidAccount; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.util.Optional; +import java.util.UUID; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class BceidAccountApiDelegateImplTest { + + public static final UUID CASE_1 = UUID.randomUUID(); + public static final UUID CASE_2 = UUID.randomUUID(); + + private BceidAccountApiDelagateImpl sut; + + @Mock + private BCeIDAccountService bCeIDAccountServiceMock; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwt; + + + @BeforeAll + public void setup() { + + Optional identity = Optional.of(new IndividualIdentity(new Name( + "firstName", + "middleName", + "otherMiddleName", + "surname", + "initials" + ), null, null, null)); + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + SecurityContextHolder.setContext(securityContextMock); + + + Mockito + .doReturn(identity) + .when(bCeIDAccountServiceMock) + .getIndividualIdentity(ArgumentMatchers.argThat(x -> x.getId().equals(CASE_1.toString().replace("-", "").toUpperCase()))); + + Mockito + .doReturn(Optional.empty()) + .when(bCeIDAccountServiceMock) + .getIndividualIdentity(ArgumentMatchers.argThat(x -> x.getId().equals(CASE_2.toString().replace("-", "").toUpperCase()))); + + BceidAccountMapper bceidAccountMapper = new BceidAccountMapperImpl(); + sut = new BceidAccountApiDelagateImpl(bCeIDAccountServiceMock, bceidAccountMapper); + + } + + @Test + @DisplayName("200: should return bceid account") + public void withAccountShouldReturnAccount() { + + + Mockito.when(jwt.getClaim(Mockito.any())).thenReturn(CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwt); + + ResponseEntity actual = sut.getBceidAccount(UUID.randomUUID()); + + Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); + Assertions.assertEquals("firstName", actual.getBody().getFirstName()); + Assertions.assertEquals("middleName", actual.getBody().getMiddleName()); + Assertions.assertEquals("surname", actual.getBody().getLastName()); + + } + + @Test + @DisplayName("403: when no universal id should return 403") + public void withNoUniversalIdShouldReturn403() { + + Mockito.when(jwt.getClaim(Mockito.any())).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwt); + + ResponseEntity actual = sut.getBceidAccount(UUID.randomUUID()); + + Assertions.assertEquals(HttpStatus.FORBIDDEN, actual.getStatusCode()); + + } + + @Test + @DisplayName("404: when user not found should return 404") + public void withNoUserShouldReturn404() { + + Mockito.when(jwt.getClaim(Mockito.any())).thenReturn(CASE_2.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwt); + + ResponseEntity actual = sut.getBceidAccount(UUID.randomUUID()); + + Assertions.assertEquals(HttpStatus.NOT_FOUND, actual.getStatusCode()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/account/CsoAccountApiDelegateImplTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/account/CsoAccountApiDelegateImplTest.java new file mode 100644 index 0000000000..073f160008 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/account/CsoAccountApiDelegateImplTest.java @@ -0,0 +1,278 @@ +package ca.bc.gov.open.jag.efilingapi.account; +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.mappers.CsoAccountMapper; +import ca.bc.gov.open.jag.efilingapi.account.mappers.CsoAccountMapperImpl; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.CreateCsoAccountRequest; +import ca.bc.gov.open.jag.efilingapi.api.model.CsoAccount; +import ca.bc.gov.open.jag.efilingapi.api.model.CsoAccountUpdateRequest; +import ca.bc.gov.open.jag.efilingapi.error.*; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingAccountServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.math.BigDecimal; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.IDENTITY_PROVIDER_CLAIM_KEY; +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("CsoAccountApiDelegateImpl Test Suite") +public class CsoAccountApiDelegateImplTest { + + private static final String LAST_NAME = "lastName"; + private static final String MIDDLE_NAME = "middleName"; + private static final String EMAIL = "email@email.com"; + private static final String FIRST_NAME = "firstName"; + private static final String INTERNAL_CLIENT_NUMBER = "123456"; + private static final String FAIL_INTERNAL_CLIENT_NUMBER = "23456"; + + private CsoAccountApiDelegateImpl sut; + + @Mock + private AccountService accountServiceMock; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @BeforeEach + public void setUp() { + + MockitoAnnotations.openMocks(this); + + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + SecurityContextHolder.setContext(securityContextMock); + + AccountDetails accountDetails = AccountDetails.builder() + .fileRolePresent(true) + .accountId(BigDecimal.ONE) + .clientId(BigDecimal.TEN) + .cardRegistered(true) + .internalClientNumber(INTERNAL_CLIENT_NUMBER) + .universalId(TestHelpers.CASE_1_STRING).create(); + + Mockito + .doReturn(accountDetails) + .when(accountServiceMock) + .createAccount(Mockito.eq(TestHelpers.CASE_1_STRING), Mockito.any(), Mockito.any()); + + Mockito + .doReturn(accountDetails) + .when(accountServiceMock) + .getCsoAccountDetails(Mockito.eq(TestHelpers.CASE_1_STRING)); + + Mockito + .doReturn(null) + .when(accountServiceMock) + .getCsoAccountDetails(Mockito.eq(TestHelpers.CASE_2_STRING)); + + Mockito + .doThrow(new EfilingAccountServiceException("random")) + .when(accountServiceMock) + .createAccount(Mockito.eq(TestHelpers.CASE_2_STRING), Mockito.any(), Mockito.any()); + + + Mockito.doNothing().when(accountServiceMock).updateClient( + ArgumentMatchers.argThat(x -> x.getInternalClientNumber().equals(INTERNAL_CLIENT_NUMBER)) + ); + + Mockito.doThrow(EfilingAccountServiceException.class).when(accountServiceMock).updateClient( + ArgumentMatchers.argThat(x -> x.getInternalClientNumber().equals(FAIL_INTERNAL_CLIENT_NUMBER)) + ); + + + // Testing mapper in this test + CsoAccountMapper csoAccountMapper = new CsoAccountMapperImpl(); + + sut = new CsoAccountApiDelegateImpl(accountServiceMock, csoAccountMapper); + } + + + @Test + @DisplayName("201: should return an account with cso") + public void whenAccountCreatedShouldReturn201() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(jwtMock.getClaim(Mockito.eq(IDENTITY_PROVIDER_CLAIM_KEY))).thenReturn(TestHelpers.IDENTITY_PROVIDER); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + CreateCsoAccountRequest request = new CreateCsoAccountRequest(); + request.setLastName(LAST_NAME); + request.setMiddleName(MIDDLE_NAME); + request.setEmail(EMAIL); + request.setFirstName(FIRST_NAME); + ResponseEntity actual = sut.createAccount(TestHelpers.CASE_1, request); + + Assertions.assertEquals(HttpStatus.CREATED, actual.getStatusCode()); + Assertions.assertEquals("1", actual.getBody().getAccountId()); + Assertions.assertEquals("10", actual.getBody().getClientId()); + Assertions.assertEquals(true, actual.getBody().getFileRolePresent()); + Assertions.assertEquals(INTERNAL_CLIENT_NUMBER, actual.getBody().getInternalClientNumber()); + + } + + @Test + @DisplayName("403: when universal id is missing should throw MissingUniversalIdException") + public void createAccountWithUserNotHavingUniversalIdShouldThrowMissingUniversalIdException() { + + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + CreateCsoAccountRequest request = new CreateCsoAccountRequest(); + request.setLastName(LAST_NAME); + request.setMiddleName(MIDDLE_NAME); + request.setEmail(EMAIL); + request.setFirstName(FIRST_NAME); + + MissingUniversalIdException exception = Assertions.assertThrows(MissingUniversalIdException.class, () -> sut.createAccount(TestHelpers.CASE_1, request)); + Assertions.assertEquals(ErrorCode.MISSING_UNIVERSAL_ID.toString(), exception.getErrorCode()); + } + + + @Test + @DisplayName("500: when exception should throw CreateAccountException") + public void createAccountWhenEfilingAccountServiceExceptionShouldThrowCreateAccountException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_2.toString()); + Mockito.when(jwtMock.getClaim(Mockito.eq(IDENTITY_PROVIDER_CLAIM_KEY))).thenReturn(TestHelpers.IDENTITY_PROVIDER); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + CreateCsoAccountRequest request = new CreateCsoAccountRequest(); + request.setLastName(LAST_NAME); + request.setMiddleName(MIDDLE_NAME); + request.setEmail(EMAIL); + request.setFirstName(FIRST_NAME); + + CreateAccountException exception = Assertions.assertThrows(CreateAccountException.class, () -> sut.createAccount(TestHelpers.CASE_2, request)); + Assertions.assertEquals(ErrorCode.CREATE_ACCOUNT_EXCEPTION.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("403: when creating account identity provider is missing should throw MissingIdentityProviderException") + public void createAccountWithUserNotHavingIdentityProviderShouldThrowMissingIdentityProviderException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_2.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + MissingIdentityProviderException exception = Assertions.assertThrows(MissingIdentityProviderException.class, () -> sut.createAccount(TestHelpers.CASE_3, null)); + Assertions.assertEquals(ErrorCode.MISSING_IDENTITY_PROVIDER.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("200: should return a cso account") + public void getAccountWithExistingAccountShouldReturnAccount() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(jwtMock.getClaim(Mockito.eq(IDENTITY_PROVIDER_CLAIM_KEY))).thenReturn(TestHelpers.IDENTITY_PROVIDER); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getCsoAccount(TestHelpers.CASE_1); + + Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); + + } + + @Test + @DisplayName("404: with account not found should return not found") + public void getAccountWithNoAccountShouldReturnNotFound() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_2.toString()); + Mockito.when(jwtMock.getClaim(Mockito.eq(IDENTITY_PROVIDER_CLAIM_KEY))).thenReturn(TestHelpers.IDENTITY_PROVIDER); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getCsoAccount(TestHelpers.CASE_1); + + Assertions.assertEquals(HttpStatus.NOT_FOUND, actual.getStatusCode()); + + } + + @Test + @DisplayName("403: when getting account universal id is missing should return 403") + public void getAccountWithUserNotHavingUniversalIdShouldReturn403() { + + ResponseEntity actual = sut.getCsoAccount(TestHelpers.CASE_3); + + Assertions.assertEquals(HttpStatus.FORBIDDEN, actual.getStatusCode()); + + } + + @Test + @DisplayName("200: With user having cso account and efiling role return submission details") + public void updateAccountWithUserHavingCsoAccountShouldReturnUserDetailsAndAccount() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(jwtMock.getClaim(Mockito.eq(IDENTITY_PROVIDER_CLAIM_KEY))).thenReturn(TestHelpers.IDENTITY_PROVIDER); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + CsoAccountUpdateRequest clientUpdateRequest = new CsoAccountUpdateRequest(); + clientUpdateRequest.setInternalClientNumber(INTERNAL_CLIENT_NUMBER); + + ResponseEntity actual = sut.updateCsoAccount(TestHelpers.CASE_1, clientUpdateRequest); + assertEquals(HttpStatus.OK, actual.getStatusCode()); + + } + + @Test + @DisplayName("403: With user not having cso account should throw InvalidUniversalException") + public void updateAccountWithUserHavingNoCsoAccountShouldThrowInvalidUniversalException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + CsoAccountUpdateRequest clientUpdateRequest = new CsoAccountUpdateRequest(); + clientUpdateRequest.setInternalClientNumber(INTERNAL_CLIENT_NUMBER); + + InvalidUniversalException exception = Assertions.assertThrows(InvalidUniversalException.class, () -> sut.updateCsoAccount(TestHelpers.CASE_2, clientUpdateRequest)); + Assertions.assertEquals(ErrorCode.INVALIDUNIVERSAL.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("500: with exception in soap service should throw UpdateClientException") + public void updateAccountWithExceptionShouldThrowUpdateClientException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + CsoAccountUpdateRequest clientUpdateRequest = new CsoAccountUpdateRequest(); + clientUpdateRequest.setInternalClientNumber(FAIL_INTERNAL_CLIENT_NUMBER); + + UpdateClientException exception = Assertions.assertThrows(UpdateClientException.class, () -> sut.updateCsoAccount(TestHelpers.CASE_2, clientUpdateRequest)); + Assertions.assertEquals(ErrorCode.UPDATE_CLIENT_EXCEPTION.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("403: with no universal id should throw InvalidUniversalException") + public void updateAccountWithUserNotHavingUniversalIdShouldThrowInvalidUniversalException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + CsoAccountUpdateRequest clientUpdateRequest = new CsoAccountUpdateRequest(); + clientUpdateRequest.setInternalClientNumber(INTERNAL_CLIENT_NUMBER); + + InvalidUniversalException exception = Assertions.assertThrows(InvalidUniversalException.class, () -> sut.updateCsoAccount(TestHelpers.CASE_2, clientUpdateRequest)); + Assertions.assertEquals(ErrorCode.INVALIDUNIVERSAL.toString(), exception.getErrorCode()); + } + + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/account/service/AccountServiceImplTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/account/service/AccountServiceImplTest.java new file mode 100644 index 0000000000..517aed81d3 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/account/service/AccountServiceImplTest.java @@ -0,0 +1,91 @@ +package ca.bc.gov.open.jag.efilingapi.account.service; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.mappers.CreateAccountRequestMapper; +import ca.bc.gov.open.jag.efilingapi.account.mappers.CreateAccountRequestMapperImpl; +import ca.bc.gov.open.jag.efilingapi.api.model.CreateCsoAccountRequest; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("AccountServiceImpl test suite") +public class AccountServiceImplTest { + + private static final String INTERNAL_CLIENT_NUMBER = "123456"; + private static final String FAIL_INTERNAL_CLIENT_NUMBER = "234567"; + public static final String BCEID = "BCEID"; + + private AccountServiceImpl sut; + + @Mock + private EfilingAccountService efilingAccountServiceMock; + + @BeforeAll + public void setup() { + + MockitoAnnotations.initMocks(this); + AccountDetails accountDetails = AccountDetails + .builder() + .accountId(BigDecimal.TEN) + .create(); + + + Mockito + .when(efilingAccountServiceMock.getAccountDetails(Mockito.eq(TestHelpers.CASE_1_STRING))) + .thenReturn(accountDetails); + + Mockito + .when(efilingAccountServiceMock.createAccount(Mockito.any())) + .thenReturn(accountDetails); + + + Mockito.doNothing().when(efilingAccountServiceMock).updateClient(any()); + + + // Testing mapper as part of the test + CreateAccountRequestMapper createAccountRequestMapper = new CreateAccountRequestMapperImpl(); + sut = new AccountServiceImpl(efilingAccountServiceMock, createAccountRequestMapper); + } + + @Test + @DisplayName("OK: should return an account") + public void withRequestShouldReturnAnAccount() { + + AccountDetails actual = sut.getCsoAccountDetails(TestHelpers.CASE_1_STRING); + Assertions.assertEquals(BigDecimal.TEN, actual.getAccountId()); + + } + + @Test + @DisplayName("OK: execute method") + public void withClientIdShouldExecuteMethod() { + + sut.updateClient(AccountDetails.builder() + .internalClientNumber("123") + .cardRegistered(true) + .clientId(BigDecimal.TEN) + .create()); + Mockito.verify(efilingAccountServiceMock,Mockito.times(1)).updateClient(any()); + + } + + @Test + @DisplayName("OK: should Create an account") + public void withRequestShouldCreateAnAccount() { + AccountDetails actual = sut.createAccount(UUID.randomUUID().toString(), BCEID, new CreateCsoAccountRequest()); + Mockito.verify(efilingAccountServiceMock,Mockito.times(1)).createAccount(any()); + + Assertions.assertEquals(BigDecimal.TEN, actual.getAccountId()); + } + + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/cache/AutoConfigurationTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/cache/AutoConfigurationTest.java index e04822abaf..1adf119f86 100644 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/cache/AutoConfigurationTest.java +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/cache/AutoConfigurationTest.java @@ -1,6 +1,7 @@ package ca.bc.gov.open.jag.efilingapi.cache; import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; import org.junit.jupiter.api.*; import org.mockito.Mock; import org.mockito.Mockito; @@ -17,19 +18,20 @@ @TestInstance(TestInstance.Lifecycle.PER_CLASS) @DisplayName("CacheConfiguration Test Suite") public class AutoConfigurationTest { + private static final String TEST_CRED = "notapassword"; private static final String HOST = "notip"; @Mock private RedisProperties redisProperties; - CacheConfiguration autoConfiguration; + private CacheConfiguration sut; @Mock - CacheProperties cachePropertiesMock; + private CacheProperties cachePropertiesMock; @Mock - CacheProperties.Redis redisPropertiesMock; + private CacheProperties.Redis redisPropertiesMock; @BeforeAll public void init() { @@ -38,10 +40,11 @@ public void init() { Mockito.when(redisPropertiesMock.getTimeToLive()).thenReturn(Duration.ofMillis(600000)); Mockito.when(cachePropertiesMock.getRedis()).thenReturn(redisPropertiesMock); - autoConfiguration = new CacheConfiguration(cachePropertiesMock); + sut = new CacheConfiguration(cachePropertiesMock); redisProperties = Mockito.mock(RedisProperties.class); } + @DisplayName("CASE1: stand alone input should generate jedisConnectionFactory") @Test public void standaloneInputShouldGenerateJedisConnectionFactory() { @@ -50,18 +53,20 @@ public void standaloneInputShouldGenerateJedisConnectionFactory() { Mockito.when(redisProperties.getHost()).thenReturn(HOST); Mockito.when(redisProperties.getPort()).thenReturn(6379); Mockito.when(redisProperties.getPassword()).thenReturn(TEST_CRED); - JedisConnectionFactory jedisConnectionFactory = autoConfiguration.jedisConnectionFactory(redisProperties); + JedisConnectionFactory jedisConnectionFactory = sut.jedisConnectionFactory(redisProperties); Assertions.assertNotNull(jedisConnectionFactory); } + @DisplayName("CASE2: cluster input should generate jedisConnectionFactory") @Test public void clusterInputshouldGenerateJedisConnectionFactory() { RedisProperties.Cluster cluster = Mockito.mock(RedisProperties.Cluster.class); Mockito.when(redisProperties.getCluster()).thenReturn(cluster); Mockito.when(redisProperties.getPassword()).thenReturn(TEST_CRED); - JedisConnectionFactory jedisConnectionFactory = autoConfiguration.jedisConnectionFactory(redisProperties); + JedisConnectionFactory jedisConnectionFactory = sut.jedisConnectionFactory(redisProperties); Assertions.assertNotNull(jedisConnectionFactory); } + @DisplayName("CASE3: sentinel input should generate jedisConnectionFactory") @Test public void sentinelInputShouldGenerateJedisConnectionFactory() { @@ -70,7 +75,7 @@ public void sentinelInputShouldGenerateJedisConnectionFactory() { Mockito.when(redisProperties.getSentinel()).thenReturn(sentinel); Mockito.when(redisProperties.getCluster()).thenReturn(null); Mockito.when(redisProperties.getPassword()).thenReturn(TEST_CRED); - JedisConnectionFactory jedisConnectionFactory = autoConfiguration.jedisConnectionFactory(redisProperties); + JedisConnectionFactory jedisConnectionFactory = sut.jedisConnectionFactory(redisProperties); Assertions.assertNotNull(jedisConnectionFactory); } @@ -84,22 +89,46 @@ public void sentinelInputShouldThrowIllegalState() { Mockito.when(redisProperties.getCluster()).thenReturn(null); Mockito.when(redisProperties.getPassword()).thenReturn(TEST_CRED); Assertions.assertThrows(IllegalStateException.class, () -> { - autoConfiguration.jedisConnectionFactory(redisProperties); + sut.jedisConnectionFactory(redisProperties); }); } - @DisplayName("CASE4: correct input should return cacheManager") + @DisplayName("CASE4: correct input should return submission cacheManager") @Test public void correctInputShouldReturnCacheManager() { JedisConnectionFactory jedisConnectionFactory = Mockito.mock(JedisConnectionFactory.class); - CacheManager cacheManager = autoConfiguration.submissionCacheManager(jedisConnectionFactory, new Jackson2JsonRedisSerializer(Submission.class)); + CacheManager cacheManager = sut.submissionCacheManager(jedisConnectionFactory, new Jackson2JsonRedisSerializer(Submission.class)); Assertions.assertNotNull(cacheManager); } @DisplayName("CASE5: Return correct class") @Test public void correctReturnJackson2JsonRedisSerializer() { - Jackson2JsonRedisSerializer result = autoConfiguration.jackson2JsonRedisSerializer(); - Assertions.assertNotNull(result); + Jackson2JsonRedisSerializer actual = sut.jackson2JsonRedisSerializer(); + Assertions.assertNotNull(actual); + } + + @DisplayName("OK: correct input should return document cacheManager") + @Test + public void correctInputShouldReturnDocumentCacheManager() { + JedisConnectionFactory jedisConnectionFactory = Mockito.mock(JedisConnectionFactory.class); + CacheManager cacheManager = sut.documentCacheManager(jedisConnectionFactory); + Assertions.assertNotNull(cacheManager); + } + + @DisplayName("OK: correct input should return documentTypeDetails cacheManager") + @Test + public void correctInputShouldReturnDocumentTypeDetailsCacheManager() { + JedisConnectionFactory jedisConnectionFactory = Mockito.mock(JedisConnectionFactory.class); + CacheManager cacheManager = sut.documentTypeDetailsCacheManager(jedisConnectionFactory, new Jackson2JsonRedisSerializer(DocumentTypeDetails.class)); + Assertions.assertNotNull(cacheManager); + } + + + @DisplayName("OK: should return DocumentTypeDetails Serializer") + @Test + public void correctReturnDocumentDetailsJackson2JsonRedisSerializer() { + Jackson2JsonRedisSerializer actual = sut.documentTypeDetailsSerializer(); + Assertions.assertNotNull(actual); } } diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/cache/CacheConfigurationTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/cache/CacheConfigurationTest.java new file mode 100644 index 0000000000..e29d6bfb74 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/cache/CacheConfigurationTest.java @@ -0,0 +1,76 @@ +package ca.bc.gov.open.jag.efilingapi.cache; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.boot.autoconfigure.data.redis.RedisProperties; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.data.redis.cache.RedisCacheManager; + +import java.time.Duration; + +import static org.assertj.core.api.Assertions.assertThat; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class CacheConfigurationTest { + + ApplicationContextRunner context = new ApplicationContextRunner() + .withPropertyValues( + "spring.redis.host=localhost", + "spring.redis.port=6379", + "spring.redis.password=admin", + "spring.cache.redis.time-to-live=600000" + ) + .withUserConfiguration(RedisProperties.class) + .withUserConfiguration(CacheConfiguration.class); + + @Test + @DisplayName("submissionCacheManager test") + public void testSubmissionCacheManager() { + context.run(it -> { + assertThat(it).hasBean("submissionCacheManager"); + assertThat(it).hasBean("submissionSerializer"); + RedisCacheManager actualCacheManager = ((RedisCacheManager)it.getBean("submissionCacheManager")); + actualCacheManager.getCache("redis"); + Assertions.assertEquals(Duration.ofSeconds(600), actualCacheManager.getCacheConfigurations().get("redis").getTtl()); + + }); + } + + @Test + @DisplayName("documentCacheManager test") + public void testDocumentCacheManager() { + context.run(it -> { + assertThat(it).hasBean("documentCacheManager"); + RedisCacheManager actualCacheManager = ((RedisCacheManager)it.getBean("documentCacheManager")); + actualCacheManager.getCache("redis"); + Assertions.assertEquals(Duration.ofHours(24), actualCacheManager.getCacheConfigurations().get("redis").getTtl()); + }); + } + + @Test + @DisplayName("documentDetailsCacheManager test") + public void testDocumentDetailsCacheManager() { + context.run(it -> { + assertThat(it).hasBean("documentTypeDetailsCacheManager"); + assertThat(it).hasBean("documentTypeDetailsSerializer"); + RedisCacheManager actualCacheManager = ((RedisCacheManager)it.getBean("documentTypeDetailsCacheManager")); + actualCacheManager.getCache("redis"); + Assertions.assertEquals(Duration.ofHours(24), actualCacheManager.getCacheConfigurations().get("redis").getTtl()); + }); + } + + @Test + @DisplayName("accountDetailsCacheManager test") + public void testAccountDetailsCacheManater() { + context.run(it -> { + assertThat(it).hasBean("accountDetailsCacheManager"); + assertThat(it).hasBean("accountDetailsSerializer"); + RedisCacheManager actualCacheManager = ((RedisCacheManager)it.getBean("accountDetailsCacheManager")); + actualCacheManager.getCache("redis"); + Assertions.assertEquals(Duration.ofMinutes(15), actualCacheManager.getCacheConfigurations().get("redis").getTtl()); + }); + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/GlobalCorsConfigurationTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/GlobalCorsConfigurationTest.java deleted file mode 100644 index de2cd60aae..0000000000 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/GlobalCorsConfigurationTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package ca.bc.gov.open.jag.efilingapi.config; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -@DisplayName("GlobalCorsConfiguration Test Suite") -public class GlobalCorsConfigurationTest { - ApplicationContextRunner context = new ApplicationContextRunner() - .withUserConfiguration(ApplicationConfiguration.class); - - @Test - @DisplayName("CASE1: Test that beans are created") - public void testBeansAreGenerated() { - context.run(it -> { - assertThat(it).hasSingleBean(ApplicationConfiguration.class); - }); - } -} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/JaegerConfigTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/JaegerConfigTest.java deleted file mode 100644 index b45095e841..0000000000 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/JaegerConfigTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package ca.bc.gov.open.jag.efilingapi.config; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -@DisplayName("JaegerConfig Test Suite") -public class JaegerConfigTest { - ApplicationContextRunner context = new ApplicationContextRunner() - .withUserConfiguration(ApplicationConfiguration.class); - - @Test - @DisplayName("CASE1: Test that beans are created") - public void testBeansAreGenerated() { - context.run(it -> { - assertThat(it).hasSingleBean(ApplicationConfiguration.class); - }); - } -} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/KeycloakJwtAuthConverterTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/KeycloakJwtAuthConverterTest.java new file mode 100644 index 0000000000..700f0bca10 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/KeycloakJwtAuthConverterTest.java @@ -0,0 +1,84 @@ +package ca.bc.gov.open.jag.efilingapi.config; + +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + +public class KeycloakJwtAuthConverterTest { + + @Test + void testNull() { + KeycloakJwtAuthConverter converter = new KeycloakJwtAuthConverter(null); + assertThrows(NullPointerException.class, () -> converter.convert(null)); + } + + @Test + void testJwtMissingResourceAccess() throws Exception { + Jwt jwt = Mockito.mock(Jwt.class); + + KeycloakJwtAuthConverter converter = new KeycloakJwtAuthConverter(null); + AbstractAuthenticationToken authenticationToken = converter.convert(jwt); + Collection authorities = authenticationToken.getAuthorities(); + assertEquals(0, authorities.size()); + } + + @Test + void testJwtMissingResource() throws Exception { + Jwt jwt = Mockito.mock(Jwt.class); + Map resourceAccess = new HashMap(); + when(jwt.getClaim(KeycloakJwtAuthConverter.KEYCLOAK_RESOURCE_ATTRIBUTE)).thenReturn(resourceAccess); + + KeycloakJwtAuthConverter converter = new KeycloakJwtAuthConverter(null); + AbstractAuthenticationToken authenticationToken = converter.convert(jwt); + Collection authorities = authenticationToken.getAuthorities(); + assertEquals(0, authorities.size()); + } + + @Test + void testJwtMissingRoles() throws Exception { + Jwt jwt = Mockito.mock(Jwt.class); + + Map resource = new HashMap(); + + Map resourceAccess = new HashMap(); + resourceAccess.put("efiling-hub", resource); + when(jwt.getClaim(KeycloakJwtAuthConverter.KEYCLOAK_RESOURCE_ATTRIBUTE)).thenReturn(resourceAccess); + + KeycloakJwtAuthConverter converter = new KeycloakJwtAuthConverter("efiling-hub"); + AbstractAuthenticationToken authenticationToken = converter.convert(jwt); + Collection authorities = authenticationToken.getAuthorities(); + assertEquals(0, authorities.size()); + } + + @Test + void testJwtValid() throws Exception { + Jwt jwt = Mockito.mock(Jwt.class); + + Collection resourceRoles = new ArrayList<>(); + resourceRoles.add("tester"); + + Map resource = new HashMap(); + resource.put(KeycloakJwtAuthConverter.KEYCLOAK_ROLE_ATTRIBUTE, resourceRoles); + + Map resourceAccess = new HashMap(); + resourceAccess.put("efiling-hub", resource); + when(jwt.getClaim(KeycloakJwtAuthConverter.KEYCLOAK_RESOURCE_ATTRIBUTE)).thenReturn(resourceAccess); + + KeycloakJwtAuthConverter converter = new KeycloakJwtAuthConverter("efiling-hub"); + AbstractAuthenticationToken authenticationToken = converter.convert(jwt); + Collection authorities = authenticationToken.getAuthorities(); + assertEquals(1, authorities.size()); + assertEquals("ROLE_tester", authorities.iterator().next().getAuthority()); + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/NavigationPropertiesTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/NavigationPropertiesTest.java index 2d80d6f58c..a3816aac1b 100644 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/NavigationPropertiesTest.java +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/NavigationPropertiesTest.java @@ -10,12 +10,15 @@ public class NavigationPropertiesTest { private static final String BASEURL = "BASEURL"; + private static final String CSO_BASEURL = "CSO_BASEURL"; @Test @DisplayName("CASE1: Test getters and setters") public void testGettSetter() { NavigationProperties testproperties = new NavigationProperties(); testproperties.setBaseUrl(BASEURL); + testproperties.setCsoBaseUrl(CSO_BASEURL); Assertions.assertEquals(BASEURL, testproperties.getBaseUrl()); + Assertions.assertEquals(CSO_BASEURL, testproperties.getCsoBaseUrl()); } } diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/SecurityConfigTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/SecurityConfigTest.java new file mode 100644 index 0000000000..32bad9fbf8 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/config/SecurityConfigTest.java @@ -0,0 +1,39 @@ +package ca.bc.gov.open.jag.efilingapi.config; + +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.web.DefaultSecurityFilterChain; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.when; + +class SecurityConfigTest { + + @Mock + KeycloakJwtAuthConverter jwtAuthConverter; + + @Mock + HttpSecurity http; + + @Test + void testFilterChain() throws Exception { + MockitoAnnotations.openMocks(this); + when(http.build()).thenReturn(Mockito.mock(DefaultSecurityFilterChain.class)); + SecurityConfig config = new SecurityConfig(jwtAuthConverter); + assertNotNull(config.filterChain(http)); + assertNotNull(config.corsConfigurationSource()); + } + + @Test + void testSessionAuthenticationStrategy() throws Exception { + KeycloakJwtAuthConverter jwtAuthConverter = Mockito.mock(KeycloakJwtAuthConverter.class); + HttpSecurity http = Mockito.mock(HttpSecurity.class); + + SecurityConfig config = new SecurityConfig(jwtAuthConverter); + assertNotNull(config.sessionAuthenticationStrategy()); + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/core/mdc/MdcFilterTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/core/mdc/MdcFilterTest.java new file mode 100644 index 0000000000..e8d7b2f42d --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/core/mdc/MdcFilterTest.java @@ -0,0 +1,72 @@ +package ca.bc.gov.open.jag.efilingapi.core.mdc; + +import jakarta.servlet.ServletException; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.io.IOException; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class MdcFilterTest { + + private MdcFilter sut; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + SecurityContextHolder.setContext(securityContextMock); + + + sut = new MdcFilter(); + + } + + @Test + @DisplayName("test that the MDCFilter does not throw exception while running with lambda request") + public void globalTestFilter() throws IOException, ServletException { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest("GET", "/efilinghub/submission"); + mockHttpServletRequest.addHeader("authorization", "token"); + mockHttpServletRequest.addHeader("random", "random"); + + MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); + MockFilterChain mockFilterChain = new MockFilterChain(); + + sut.doFilter(mockHttpServletRequest, mockHttpServletResponse, mockFilterChain); + + + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/court/CourtConfigTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/court/CourtConfigTest.java new file mode 100644 index 0000000000..29727ed00c --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/court/CourtConfigTest.java @@ -0,0 +1,36 @@ +package ca.bc.gov.open.jag.efilingapi.court; + +import ca.bc.gov.open.jag.efilingapi.court.services.CourtService; +import ca.bc.gov.open.jag.efilingapi.court.services.CourtServiceImpl; +import ca.bc.gov.open.jag.efilingapi.fakes.EfilingCourtServiceFake; +import ca.bc.gov.open.jag.efilingapi.fakes.EfilingSearchServiceFake; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class CourtConfigTest { + + ApplicationContextRunner context = new ApplicationContextRunner() + .withUserConfiguration(CourtConfig.class) + .withBean(EfilingCourtServiceFake.class) + .withBean(EfilingSearchServiceFake.class); + + @Test + @DisplayName("Test Court Configuration Beans") + public void testSubmissionBeans() { + + context.run(it -> { + + assertThat(it).hasSingleBean(CourtService.class); + Assertions.assertEquals(CourtServiceImpl.class, it.getBean(CourtService.class).getClass()); + + }); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/court/services/CourtServiceImplTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/court/services/CourtServiceImplTest.java new file mode 100644 index 0000000000..1925d2a957 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/court/services/CourtServiceImplTest.java @@ -0,0 +1,184 @@ +package ca.bc.gov.open.jag.efilingapi.court.services; + +import ca.bc.gov.open.jag.efilingapi.court.models.GetCourtDetailsRequest; +import ca.bc.gov.open.jag.efilingapi.court.models.IsValidCourtFileNumberRequest; +import ca.bc.gov.open.jag.efilingapi.court.models.IsValidCourtRequest; +import ca.bc.gov.open.jag.efilingcommons.model.CourtDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingCourtService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSearchService; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; +import java.util.Optional; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class CourtServiceImplTest { + + private static final String COURT_CLASSIFICATION = "classification"; + private static final String COURT_LEVEL = "level"; + private static final String COURT_OF_APPEAL_LEVEL = "a"; + private static final String COURT_LOCATION = "location"; + public static final String CLASS_DESCRIPTION = "classDescription"; + public static final String COURT_DESCRIPTION = "courtDescription"; + public static final String LEVEL_DESCRIPTION = "levelDescription"; + public static final BigDecimal COURT_ID = BigDecimal.TEN; + public static final String CASE_1 = "case1"; + public static final String CASE_2 = "case2"; + public static final String FILE_NUMBER = "123465"; + + private CourtServiceImpl sut; + + @Mock + private EfilingCourtService efilingCourtServiceMock; + @Mock + private EfilingSearchService efilingSearchServiceMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + CourtDetails courtDetails = new CourtDetails(COURT_ID, COURT_DESCRIPTION, CLASS_DESCRIPTION, LEVEL_DESCRIPTION); + Mockito.when(efilingCourtServiceMock.getCourtDescription( + Mockito.eq(COURT_LOCATION), + Mockito.eq(COURT_LEVEL), + Mockito.eq(COURT_CLASSIFICATION))).thenReturn(Optional.of(courtDetails)); + + Mockito.when(efilingCourtServiceMock + .checkValidLevelClassLocation( + Mockito.eq(COURT_ID), + Mockito.eq(COURT_LEVEL), + Mockito.eq(COURT_CLASSIFICATION), + Mockito.eq(CASE_1) + )).thenReturn(true); + + Mockito.when(efilingCourtServiceMock + .checkValidLevelClassLocation( + Mockito.eq(COURT_ID), + Mockito.eq(COURT_LEVEL), + Mockito.eq(COURT_CLASSIFICATION), + Mockito.eq(CASE_2) + )).thenReturn(false); + + Mockito.when(efilingCourtServiceMock + .checkValidCourtFileNumber( + Mockito.eq(FILE_NUMBER), + Mockito.eq(COURT_ID), + Mockito.eq(COURT_LEVEL), + Mockito.eq(COURT_CLASSIFICATION), + Mockito.eq(CASE_1) + )).thenReturn(true); + + Mockito.when(efilingCourtServiceMock + .checkValidCourtFileNumber( + Mockito.eq(FILE_NUMBER), + Mockito.eq(COURT_ID), + Mockito.eq(COURT_LEVEL), + Mockito.eq(COURT_CLASSIFICATION), + Mockito.eq(CASE_2) + )).thenReturn(false); + + Mockito.when(efilingSearchServiceMock.caseNumberExists(Mockito.eq(FILE_NUMBER))).thenReturn(true); + sut = new CourtServiceImpl(efilingCourtServiceMock, efilingSearchServiceMock); + + } + + + @Test + @DisplayName("ok: with valid request should return court description") + public void withValidRequestShouldReturnCourtDescription() { + + CourtDetails actual = sut.getCourtDetails(GetCourtDetailsRequest + .builder() + .courtClassification(COURT_CLASSIFICATION) + .courtLevel(COURT_LEVEL) + .courtLocation(COURT_LOCATION) + .create()).get(); + + Assertions.assertEquals(COURT_ID, actual.getCourtId()); + Assertions.assertEquals(CLASS_DESCRIPTION, actual.getClassDescription()); + Assertions.assertEquals(COURT_DESCRIPTION, actual.getCourtDescription()); + Assertions.assertEquals(LEVEL_DESCRIPTION, actual.getLevelDescription()); + + } + + @Test + @DisplayName("ok: should validate court classification and return true") + public void shouldValidateCourtClassificationAndReturnTrue() { + + boolean actual = sut.isValidCourt(IsValidCourtRequest.builder() + .applicationCode(CASE_1) + .courtClassification(COURT_CLASSIFICATION) + .courtId(COURT_ID) + .courtLevel(COURT_LEVEL) + .create()); + + Assertions.assertTrue(actual); + + } + + @Test + @DisplayName("ok: should validate court classification and return false") + public void shouldValidateCourtClassificationAndReturnFalse() { + + boolean actual = sut.isValidCourt(IsValidCourtRequest.builder() + .applicationCode(CASE_2) + .courtClassification(COURT_CLASSIFICATION) + .courtId(COURT_ID) + .courtLevel(COURT_LEVEL) + .create()); + + Assertions.assertFalse(actual); + + + } + + @Test + @DisplayName("ok: should validate a court file number and return true") + public void shouldValidateACourtFileNumberAndReturnTrue() { + + boolean actual = sut.isValidCourtFileNumber(IsValidCourtFileNumberRequest.builder() + .applicationCode(CASE_1) + .courtId(COURT_ID) + .courtLevel(COURT_LEVEL) + .courtClassification(COURT_CLASSIFICATION) + .fileNumber(FILE_NUMBER).create()); + + Assertions.assertTrue(actual); + + } + + @Test + @DisplayName("ok: with Court of Appeal should validate a court file number and return true") + public void withCourtOfAppealShouldValidateACourtFileNumberAndReturnTrue() { + + boolean actual = sut.isValidCourtFileNumber(IsValidCourtFileNumberRequest.builder() + .applicationCode(CASE_1) + .courtId(COURT_ID) + .courtLevel(COURT_OF_APPEAL_LEVEL) + .courtClassification(COURT_CLASSIFICATION) + .fileNumber(FILE_NUMBER).create()); + + Assertions.assertTrue(actual); + + } + + @Test + @DisplayName("ok: should validate a court file number and return false") + public void shouldValidateACourtFileNumberAndReturnFalse() { + + boolean actual = sut.isValidCourtFileNumber(IsValidCourtFileNumberRequest.builder() + .applicationCode(CASE_2) + .courtId(COURT_ID) + .courtLevel(COURT_LEVEL) + .courtClassification(COURT_CLASSIFICATION) + .fileNumber(FILE_NUMBER).create()); + + Assertions.assertFalse(actual); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/courts/GetCourtLocationsTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/courts/GetCourtLocationsTest.java new file mode 100644 index 0000000000..9b4afd7a9d --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/courts/GetCourtLocationsTest.java @@ -0,0 +1,118 @@ +package ca.bc.gov.open.jag.efilingapi.courts; + +import ca.bc.gov.open.jag.efilingapi.api.model.CourtLocations; +import ca.bc.gov.open.jag.efilingapi.courts.mappers.CourtLocationMapperImpl; +import ca.bc.gov.open.jag.efilingapi.error.CourtLocationException; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingcommons.court.EfilingCourtLocationService; +import ca.bc.gov.open.jag.efilingcommons.model.InternalCourtLocation; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("CourtsApiDelegateImpl test suite") +public class GetCourtLocationsTest { + + private final String COURTLEVEL = "COURTLEVEL"; + private final String COURTLEVELERROR = "COURTLEVELERROR"; + + CourtsApiDelegateImpl sut; + + + + @Mock + EfilingCourtLocationService efilingCourtLocationServiceMock; + + @BeforeAll + public void setUp() { + MockitoAnnotations.openMocks(this); + + Mockito.when(efilingCourtLocationServiceMock.getCourtLocations(COURTLEVEL)).thenReturn(buildMockData()); + + Mockito.when(efilingCourtLocationServiceMock.getCourtLocations(COURTLEVELERROR)).thenReturn(null); + + sut = new CourtsApiDelegateImpl(efilingCourtLocationServiceMock, new CourtLocationMapperImpl()); + } + + @Test + @DisplayName("200") + public void withValidCourtNameReturnCourtLocations() { + + ResponseEntity actual = sut.getCourtLocations(COURTLEVEL); + + Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); + Assertions.assertEquals(2, actual.getBody().getCourts().size()); + Assertions.assertEquals(BigDecimal.valueOf(1031), actual.getBody().getCourts().get(0).getId()); + Assertions.assertEquals("Campbell River",actual.getBody().getCourts().get(0).getName()); + Assertions.assertEquals("MockCode",actual.getBody().getCourts().get(0).getCode()); + Assertions.assertEquals(true,actual.getBody().getCourts().get(0).getIsSupremeCourt()); + Assertions.assertEquals("500 - 13th Avenue",actual.getBody().getCourts().get(0).getAddress().getAddressLine1()); + Assertions.assertEquals(null,actual.getBody().getCourts().get(0).getAddress().getAddressLine2()); + Assertions.assertEquals(null,actual.getBody().getCourts().get(0).getAddress().getAddressLine3()); + Assertions.assertEquals("V9W 6P1",actual.getBody().getCourts().get(0).getAddress().getPostalCode()); + Assertions.assertEquals("Campbell River",actual.getBody().getCourts().get(0).getAddress().getCityName()); + Assertions.assertEquals("British Columbia",actual.getBody().getCourts().get(0).getAddress().getProvinceName()); + Assertions.assertEquals("Canada",actual.getBody().getCourts().get(0).getAddress().getCountryName()); + + Assertions.assertEquals(BigDecimal.valueOf(3521), actual.getBody().getCourts().get(1).getId()); + Assertions.assertEquals("Chilliwack",actual.getBody().getCourts().get(1).getName()); + Assertions.assertEquals("MockCode",actual.getBody().getCourts().get(1).getCode()); + Assertions.assertEquals(true,actual.getBody().getCourts().get(1).getIsSupremeCourt()); + Assertions.assertEquals("46085 Yale Road",actual.getBody().getCourts().get(1).getAddress().getAddressLine1()); + Assertions.assertEquals(" ",actual.getBody().getCourts().get(1).getAddress().getAddressLine2()); + Assertions.assertEquals(" ",actual.getBody().getCourts().get(1).getAddress().getAddressLine3()); + Assertions.assertEquals("V2P 2L8",actual.getBody().getCourts().get(1).getAddress().getPostalCode()); + Assertions.assertEquals("Chilliwack",actual.getBody().getCourts().get(1).getAddress().getCityName()); + Assertions.assertEquals("British Columbia",actual.getBody().getCourts().get(1).getAddress().getProvinceName()); + Assertions.assertEquals("Canada",actual.getBody().getCourts().get(1).getAddress().getCountryName()); + + } + + @Test + @DisplayName("500: with invalid court name should throw CourtLocationException") + public void withInvalidCourtNameShouldThrowException() { + + CourtLocationException exception = Assertions.assertThrows(CourtLocationException.class, () -> sut.getCourtLocations(COURTLEVELERROR)); + Assertions.assertEquals(ErrorCode.COURT_LOCATION_ERROR.toString(), exception.getErrorCode()); + } + + private List buildMockData() { + InternalCourtLocation courtLocationOne = new InternalCourtLocation(); + courtLocationOne.setId(BigDecimal.valueOf(1031)); + courtLocationOne.setName("Campbell River"); + courtLocationOne.setCode("MockCode"); + courtLocationOne.setIsSupremeCourt(true); + ca.bc.gov.open.jag.efilingcommons.model.Address addressOne = new ca.bc.gov.open.jag.efilingcommons.model.Address(); + addressOne.setAddressLine1("500 - 13th Avenue"); + addressOne.setPostalCode("V9W 6P1"); + addressOne.setCityName("Campbell River"); + addressOne.setProvinceName("British Columbia"); + addressOne.setCountryName("Canada"); + courtLocationOne.setAddress(addressOne); + + InternalCourtLocation courtLocationTwo = new InternalCourtLocation(); + courtLocationTwo.setId(BigDecimal.valueOf(3521)); + courtLocationTwo.setName("Chilliwack"); + courtLocationTwo.setCode("MockCode"); + courtLocationTwo.setIsSupremeCourt(true); + ca.bc.gov.open.jag.efilingcommons.model.Address addressTwo = new ca.bc.gov.open.jag.efilingcommons.model.Address(); + addressTwo.setAddressLine1("46085 Yale Road"); + addressTwo.setAddressLine2(" "); + addressTwo.setAddressLine3(" "); + addressTwo.setPostalCode("V2P 2L8"); + addressTwo.setCityName("Chilliwack"); + addressTwo.setProvinceName("British Columbia"); + addressTwo.setCountryName("Canada"); + courtLocationTwo.setAddress(addressTwo); + + return Arrays.asList(courtLocationOne,courtLocationTwo); + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/courts/config/CourtsConfigurationTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/courts/config/CourtsConfigurationTest.java new file mode 100644 index 0000000000..87673ea083 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/courts/config/CourtsConfigurationTest.java @@ -0,0 +1,26 @@ +package ca.bc.gov.open.jag.efilingapi.courts.config; + +import ca.bc.gov.open.jag.efilingapi.courts.CourtsConfiguration; +import ca.bc.gov.open.jag.efilingapi.courts.mappers.CourtLocationMapper; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("CourtsConfiguration test suite") +public class CourtsConfigurationTest { + ApplicationContextRunner context = new ApplicationContextRunner() + .withUserConfiguration(CourtsConfiguration.class); + + @Test + public void testConfigure() { + + context.run(it -> { + assertThat(it).hasSingleBean(CourtLocationMapper.class); + }); + + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/document/DocumentConfigurationTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/document/DocumentConfigurationTest.java new file mode 100644 index 0000000000..5d86c4bad5 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/document/DocumentConfigurationTest.java @@ -0,0 +1,42 @@ +package ca.bc.gov.open.jag.efilingapi.document; + +import ca.bc.gov.open.jag.efilingapi.fakes.EfilingDocumentServiceFake; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("DocumentConfiguration") +public class DocumentConfigurationTest { + + private DocumentConfiguration sut; + + ApplicationContextRunner context = new ApplicationContextRunner() + .withUserConfiguration( + DocumentConfiguration.class) + .withBean(EfilingDocumentServiceFake.class); + + + @Test + public void checkRegisteredBeans() { + + + context.run(it -> { + assertThat(it).hasSingleBean(DocumentStore.class); + Assertions.assertEquals(DocumentStoreImpl.class, it.getBean(DocumentStore.class).getClass()); + + assertThat(it).hasSingleBean(DocumentService.class); + Assertions.assertEquals(DocumentServiceImpl.class, it.getBean(DocumentService.class).getClass()); + + + }); + + } + + + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/document/DocumentServiceImplTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/document/DocumentServiceImplTest.java new file mode 100644 index 0000000000..ccc4bdda0f --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/document/DocumentServiceImplTest.java @@ -0,0 +1,59 @@ +package ca.bc.gov.open.jag.efilingapi.document; + +import ca.bc.gov.open.jag.efilingapi.document.models.GetValidDocumentTypesRequest; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class DocumentServiceImplTest { + + private static final String COURT_LEVEL = "courtLevel"; + private static final String COURT_CLASSIFICATION = "court classification"; + + private DocumentServiceImpl sut; + + @Mock + private EfilingDocumentService efilingDocumentServiceMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + List documentList = new ArrayList<>(); + DocumentTypeDetails document = new DocumentTypeDetails("description", "type", BigDecimal.TEN,false, true, true); + documentList.add(document); + Mockito.when(efilingDocumentServiceMock.getDocumentTypes(Mockito.eq(COURT_LEVEL), Mockito.eq(COURT_CLASSIFICATION))).thenReturn(documentList); + + sut = new DocumentServiceImpl(efilingDocumentServiceMock); + + + } + + @Test + @DisplayName("ok: should return a list of documents") + public void shouldReturnAListOfDocuments() { + + List actual = sut.getValidDocumentTypes(GetValidDocumentTypesRequest + .builder() + .courtLevel(COURT_LEVEL) + .courtClassification(COURT_CLASSIFICATION) + .create()); + + Assertions.assertEquals(1, actual.size()); + Assertions.assertEquals("description", actual.get(0).getDescription()); + Assertions.assertEquals("type", actual.get(0).getType()); + + + } + + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/document/DocumentStoreImplTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/document/DocumentStoreImplTest.java new file mode 100644 index 0000000000..114b378dd9 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/document/DocumentStoreImplTest.java @@ -0,0 +1,115 @@ +package ca.bc.gov.open.jag.efilingapi.document; + +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionKey; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("DocumentStoreImpl test suite") +public class DocumentStoreImplTest { + + private static final String DUMMY_CONTENT = "test"; + private static final String DESCRIPTION = "description"; + private static final String TYPE = "TYPE"; + private DocumentStoreImpl sut; + + @Mock + private EfilingDocumentService efilingDocumentServiceMock; + + @BeforeAll + public void setUp() { + MockitoAnnotations.openMocks(this); + + DocumentTypeDetails docummentDetails = new DocumentTypeDetails(DESCRIPTION, TYPE, BigDecimal.TEN, true, true, true); + + Mockito + .when(efilingDocumentServiceMock.getDocumentTypeDetails(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(docummentDetails); + + + List documentTypeDetails = Arrays.asList(new DocumentTypeDetails(DESCRIPTION, TYPE, BigDecimal.TEN, true, true, true)); + + Mockito + .when(efilingDocumentServiceMock.getDocumentTypes(Mockito.anyString(), Mockito.anyString())) + .thenReturn(documentTypeDetails); + + sut = new DocumentStoreImpl(efilingDocumentServiceMock); + } + + @Test + @DisplayName("OK: put document should return byte array") + public void withoutCacheShouldReturnIt() { + + byte[] actual = sut.put(new SubmissionKey(UUID.randomUUID().toString(), UUID.randomUUID(), UUID.randomUUID()), "filename.txt", DUMMY_CONTENT.getBytes()); + + Assertions.assertEquals(DUMMY_CONTENT, new String(actual)); + } + + @Test + @DisplayName("OK: get document by Id should return null") + public void withoutCacheShouldReturnNull() { + Assertions.assertNull(sut.get(new SubmissionKey(UUID.randomUUID().toString(), UUID.randomUUID(), UUID.randomUUID()), "filename.txt")); + } + + @Test + @DisplayName("OK: evict should delete submission") + public void withoutCacheNotThrowException() { + Assertions.assertDoesNotThrow(() -> sut.evict(new SubmissionKey(UUID.randomUUID().toString(), UUID.randomUUID(), UUID.randomUUID()), "filename.txt")); + } + + @Test + @DisplayName("OK: put document should return byte array") + public void withRushCacheShouldReturnIt() { + + byte[] actual = sut.putRushDocument(new SubmissionKey(UUID.randomUUID().toString(), UUID.randomUUID(), UUID.randomUUID()), "filename.txt", DUMMY_CONTENT.getBytes()); + + Assertions.assertEquals(DUMMY_CONTENT, new String(actual)); + } + + @Test + @DisplayName("OK: get document by Id should return null") + public void withRushCacheShouldReturnNull() { + Assertions.assertNull(sut.getRushDocument(new SubmissionKey(UUID.randomUUID().toString(), UUID.randomUUID(), UUID.randomUUID()), "filename.txt")); + } + + @Test + @DisplayName("OK: evict should delete submission") + public void withRushCacheNotThrowException() { + Assertions.assertDoesNotThrow(() -> sut.evictRushDocument(new SubmissionKey(UUID.randomUUID().toString(), UUID.randomUUID(), UUID.randomUUID()), "filename.txt")); + } + + @Test + @DisplayName("OK: get document details should cache result") + public void withCourtLevelCourtClassDocumentTypeShouldReturnDocumentDetails() { + + + DocumentTypeDetails actual = sut.getDocumentDetails("courtLevel", "courtClass", "documentType"); + + Assertions.assertEquals(DESCRIPTION, actual.getDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getStatutoryFeeAmount()); + + } + + @Test + @DisplayName("OK: get document types should cache result") + public void withCourtLevelCourtClassShouldReturnDocumentTypes() { + + + List actual = sut.getDocumentTypes("courtLevel", "courtClass"); + + Assertions.assertEquals(1, actual.size()); + Assertions.assertEquals(DESCRIPTION, actual.get(0).getDescription()); + Assertions.assertEquals(TYPE, actual.get(0).getType()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/document/documentApiDelegateImpl/GetDocumentTypesTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/document/documentApiDelegateImpl/GetDocumentTypesTest.java new file mode 100644 index 0000000000..0da1e81479 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/document/documentApiDelegateImpl/GetDocumentTypesTest.java @@ -0,0 +1,68 @@ +package ca.bc.gov.open.jag.efilingapi.document.documentApiDelegateImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.api.model.CourtClassification; +import ca.bc.gov.open.jag.efilingapi.api.model.CourtLevel; +import ca.bc.gov.open.jag.efilingapi.document.DocumentApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.error.DocumentTypeException; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingDocumentServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; + + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("LookupApiDelegateImpl test suite") +public class GetDocumentTypesTest { + + private static final String CLASS_STRING = "S"; + private static final String LEVEL_STRING = "A"; + private static final String CLASS_STRING_ERROR = "M"; + DocumentApiDelegateImpl sut; + + @Mock + private DocumentStore documentStoreMock; + + + @BeforeAll + public void beforeAll() throws IOException { + MockitoAnnotations.openMocks(this); + List documentTypeDetails = Arrays.asList(new DocumentTypeDetails(TestHelpers.DESCRIPTION, TestHelpers.TYPE, BigDecimal.TEN, false, false, false)); + + Mockito.when(documentStoreMock.getDocumentTypes(LEVEL_STRING, CLASS_STRING)).thenReturn(documentTypeDetails); + Mockito.when(documentStoreMock.getDocumentTypes(LEVEL_STRING, CLASS_STRING_ERROR)).thenThrow(new EfilingDocumentServiceException("NOOOOOOO")); + sut = new DocumentApiDelegateImpl(documentStoreMock); + } + + @Test + @DisplayName("200") + public void withValidParametersReturnDocumentProperties() { + + ResponseEntity> actual = sut.getDocumentTypes(CourtLevel.A, CourtClassification.S); + + Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); + Assertions.assertEquals(1, actual.getBody().size()); + Assertions.assertEquals(TestHelpers.DESCRIPTION, actual.getBody().get(0).getDescription()); + Assertions.assertEquals(TestHelpers.TYPE, actual.getBody().get(0).getType()); + + } + + @Test + @DisplayName("500: exception thrown from SOAP should throw DocumentTypeException") + public void withExceptionThrownFromSoapShouldThrowDocumentTypeException() { + + DocumentTypeException exception = Assertions.assertThrows(DocumentTypeException.class, () -> sut.getDocumentTypes(CourtLevel.A, CourtClassification.M)); + Assertions.assertEquals(ErrorCode.DOCUMENT_TYPE_ERROR.toString(), exception.getErrorCode()); + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/error/ExceptionControllerAdvisorTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/error/ExceptionControllerAdvisorTest.java new file mode 100644 index 0000000000..914e753fff --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/error/ExceptionControllerAdvisorTest.java @@ -0,0 +1,474 @@ +package ca.bc.gov.open.jag.efilingapi.error; + +import ca.bc.gov.open.jag.efilingapi.api.model.EfilingError; +import org.junit.jupiter.api.*; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("ExceptionControllerAdvisor test suite") +public class ExceptionControllerAdvisorTest { + + public ExceptionControllerAdvisor sut; + + @BeforeEach + public void beforeEach() { + + MockitoAnnotations.openMocks(this); + sut = new ExceptionControllerAdvisor(); + + } + + @Test + @DisplayName("500: Assert Cache Exception") + public void testCacheException() { + + String expected = "Something went wrong"; + + //arrange + CacheException exception = new CacheException(expected); + + //act + ResponseEntity result = sut.handleCacheException(exception); + + //assert + Assertions.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.CACHE_ERROR.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("500: Assert Court Location Exception") + public void testCourtLocationException() { + + String expected = "Something went wrong"; + + //arrange + CourtLocationException exception = new CourtLocationException(expected); + + //act + ResponseEntity result = sut.handleCourtLocationException(exception); + + //assert + Assertions.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.COURT_LOCATION_ERROR.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("500: Assert Create Account Exception") + public void testCreateAccountException() { + + String expected = "Something went wrong"; + + //arrange + CreateAccountException exception = new CreateAccountException(expected); + + //act + ResponseEntity result = sut.handleCreateAccountException(exception); + + //assert + Assertions.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.CREATE_ACCOUNT_EXCEPTION.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("404: Assert Delete Document Exception Returns Not Found") + public void testDeleteDocumentExceptionReturnNotFound() { + + String expected = "Something went wrong"; + + //arrange + DeleteDocumentException exception = new DeleteDocumentException(expected, HttpStatus.NOT_FOUND); + + //act + ResponseEntity result = sut.handleDeleteDocumentException(exception); + + //assert + Assertions.assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.DELETE_DOCUMENT_ERROR.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("400: Assert Delete Document Exception Returns Bad Request") + public void testDeleteDocumentExceptionReturnsBadRequest() { + + String expected = "Something went wrong"; + + //arrange + DeleteDocumentException exception = new DeleteDocumentException(expected, HttpStatus.BAD_REQUEST); + + //act + ResponseEntity result = sut.handleDeleteDocumentException(exception); + + //assert + Assertions.assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.DELETE_DOCUMENT_ERROR.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("400: Assert Document Required Exception") + public void testDocumentRequiredException() { + + String expected = "Something went wrong"; + + //arrange + DocumentRequiredException exception = new DocumentRequiredException(expected); + + //act + ResponseEntity result = sut.handleDocumentRequiredException(exception); + + //assert + Assertions.assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.DOCUMENT_REQUIRED.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("502: Assert Document Storage Exception") + public void testDocumentStorageException() { + + String expected = "Something went wrong"; + + //arrange + DocumentStorageException exception = new DocumentStorageException(expected); + + //act + ResponseEntity result = sut.handleDocumentStorageException(exception); + + //assert + Assertions.assertEquals(HttpStatus.BAD_GATEWAY, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.DOCUMENT_STORAGE_FAILURE.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("500: Assert Document Type Exception") + public void testDocumentTypeException() { + + String expected = "Something went wrong"; + + //arrange + DocumentTypeException exception = new DocumentTypeException(expected); + + //act + ResponseEntity result = sut.handleDocumentTypeException(exception); + + //assert + Assertions.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.DOCUMENT_TYPE_ERROR.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("400: Assert File Type Exception") + public void testFileTypeException() { + + String expected = "Something went wrong"; + + //arrange + FileTypeException exception = new FileTypeException(expected); + + //act + ResponseEntity result = sut.handleFileTypeException(exception); + + //assert + Assertions.assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.FILE_TYPE_ERROR.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + + @Test + @DisplayName("404: Assert Filing Package Not Found Exception") + public void testFilingPackageNotFoundException() { + + String expected = "Something went wrong"; + + //arrange + FilingPackageNotFoundException exception = new FilingPackageNotFoundException(expected); + + //act + ResponseEntity result = sut.handleFilingPackageNotFoundException(exception); + + //assert + Assertions.assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.FILING_PACKAGE_NOT_FOUND.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("400: Assert Invalid Initial Submission Payload Exception") + public void testInvalidInitialSubmissionPayloadException() { + + String expected = "Something went wrong"; + String expectedDetail1 = "Detail 1 - FileNumber [3] does not exists."; + String expectedDetail2 = "Detail 2 - FileNumber [3] does not exists."; + List expectedDetails = Arrays.asList(expectedDetail1, expectedDetail2); + + //arrange + InvalidInitialSubmissionPayloadException exception = new InvalidInitialSubmissionPayloadException(expected, expectedDetails); + + //act + ResponseEntity result = sut.handleInvalidInitialSubmissionPayloadException(exception); + + //assert + Assertions.assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.INVALID_INITIAL_SUBMISSION_PAYLOAD.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + Assertions.assertEquals(expectedDetails, ((EfilingError) result.getBody()).getDetails()); + Assertions.assertEquals(expectedDetail1, ((EfilingError) result.getBody()).getDetails().get(0)); + Assertions.assertEquals(expectedDetail2, ((EfilingError) result.getBody()).getDetails().get(1)); + + } + + @Test + @DisplayName("403: Assert Invalid Role Exception") + public void testInvalidRoleException() { + + String expected = "Something went wrong"; + + //arrange + InvalidRoleException exception = new InvalidRoleException(expected); + + //act + ResponseEntity result = sut.handleInvalidRoleException(exception); + + //assert + Assertions.assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.INVALIDROLE.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("403: Assert Invalid Universal Exception") + public void testInvalidUniversalException() { + + String expected = "Something went wrong"; + + //arrange + InvalidUniversalException exception = new InvalidUniversalException(expected); + + //act + ResponseEntity result = sut.handleInvalidUniversalException(exception); + + //assert + Assertions.assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.INVALIDUNIVERSAL.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("403: Assert Missing Application Code Exception") + public void testMissingApplicationCodeException() { + + String expected = "Something went wrong"; + + //arrange + MissingApplicationCodeException exception = new MissingApplicationCodeException(expected); + + //act + ResponseEntity result = sut.handleMissingApplicationCodeException(exception); + + //assert + Assertions.assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.MISSING_APPLICATION_CODE.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("403: Assert Missing Identity Provider Exception") + public void testMissingIdentityProviderException() { + + String expected = "Something went wrong"; + + //arrange + MissingIdentityProviderException exception = new MissingIdentityProviderException(expected); + + //act + ResponseEntity result = sut.handleMissingIdentityProviderException(exception); + + //assert + Assertions.assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.MISSING_IDENTITY_PROVIDER.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("403: Assert Missing Universal Id Exception") + public void testMissingUniversalIdException() { + + String expected = "Something went wrong"; + + //arrange + MissingUniversalIdException exception = new MissingUniversalIdException(expected); + + //act + ResponseEntity result = sut.handleMissingUniversalIdException(exception); + + //assert + Assertions.assertEquals(HttpStatus.FORBIDDEN, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.MISSING_UNIVERSAL_ID.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("400: Assert Multiple Accounts Exception") + public void testMultipleAccountsException() { + + String expected = "Something went wrong"; + + //arrange + AccountException exception = new AccountException(expected); + + //act + ResponseEntity result = sut.handleAccountException(exception); + + //assert + Assertions.assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.ACCOUNTEXCEPTION.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("400: Assert Payment Exception") + public void testPaymentException() { + + String expected = "Something went wrong"; + + //arrange + PaymentException exception = new PaymentException(expected); + + //act + ResponseEntity result = sut.handlePaymentException(exception); + + //assert + Assertions.assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.PAYMENT_FAILURE.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("500: Assert Submission Exception") + public void testSubmissionException() { + + String expected = "Something went wrong"; + + //arrange + SubmissionException exception = new SubmissionException(expected); + + //act + ResponseEntity result = sut.handleSubmissionException(exception); + + //assert + Assertions.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.SUBMISSION_FAILURE.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("500: Assert Update Client Exception") + public void testUpdateClientException() { + + String expected = "Something went wrong"; + + //arrange + UpdateClientException exception = new UpdateClientException(expected); + + //act + ResponseEntity result = sut.handleUpdateClientException(exception); + + //assert + Assertions.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.UPDATE_CLIENT_EXCEPTION.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("500: Assert Url Generation Exception") + public void testUrlGenerationException() { + + String expected = "Something went wrong"; + + //arrange + UrlGenerationException exception = new UrlGenerationException(expected); + + //act + ResponseEntity result = sut.handleUrlGenerationException(exception); + + //assert + Assertions.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.URL_GENERATION_FAILURE.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + + @Test + @DisplayName("400: Assert No Registry Notice Exception") + public void testNoRegistryNoticeException() { + + String expected = "Something went wrong"; + + //arrange + NoRegistryNoticeException exception = new NoRegistryNoticeException(expected); + + //act + ResponseEntity result = sut.handleNoRegistryNoticeException(exception); + + //assert + Assertions.assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); + Assertions.assertEquals(ErrorCode.MISSING_REGISTRY_NOTICE.toString(), + ((EfilingError) Objects.requireNonNull(result.getBody())).getError()); + Assertions.assertEquals(expected, ((EfilingError) result.getBody()).getMessage()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/CourtServiceFake.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/CourtServiceFake.java new file mode 100644 index 0000000000..dbeea469e4 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/CourtServiceFake.java @@ -0,0 +1,26 @@ +package ca.bc.gov.open.jag.efilingapi.fakes; + +import ca.bc.gov.open.jag.efilingapi.court.models.GetCourtDetailsRequest; +import ca.bc.gov.open.jag.efilingapi.court.models.IsValidCourtFileNumberRequest; +import ca.bc.gov.open.jag.efilingapi.court.models.IsValidCourtRequest; +import ca.bc.gov.open.jag.efilingapi.court.services.CourtService; +import ca.bc.gov.open.jag.efilingcommons.model.CourtDetails; + +import java.util.Optional; + +public class CourtServiceFake implements CourtService { + @Override + public boolean isValidCourt(IsValidCourtRequest isValidCourtRequest) { + return false; + } + + @Override + public Optional getCourtDetails(GetCourtDetailsRequest getCourtDetailsRequest) { + return Optional.empty(); + } + + @Override + public boolean isValidCourtFileNumber(IsValidCourtFileNumberRequest isValidCourtFileNumberRequest) { + return false; + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/DocumentServiceFake.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/DocumentServiceFake.java new file mode 100644 index 0000000000..775b4743e0 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/DocumentServiceFake.java @@ -0,0 +1,14 @@ +package ca.bc.gov.open.jag.efilingapi.fakes; + +import ca.bc.gov.open.jag.efilingapi.document.DocumentService; +import ca.bc.gov.open.jag.efilingapi.document.models.GetValidDocumentTypesRequest; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; + +import java.util.List; + +public class DocumentServiceFake implements DocumentService { + @Override + public List getValidDocumentTypes(GetValidDocumentTypesRequest getValidDocumentTypesRequest) { + return null; + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/EfilingCourtServiceFake.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/EfilingCourtServiceFake.java new file mode 100644 index 0000000000..ef8f64097f --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/EfilingCourtServiceFake.java @@ -0,0 +1,25 @@ +package ca.bc.gov.open.jag.efilingapi.fakes; + +import ca.bc.gov.open.jag.efilingcommons.model.CourtDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingCourtService; + +import java.math.BigDecimal; +import java.util.Optional; + +public class EfilingCourtServiceFake implements EfilingCourtService { + + @Override + public Optional getCourtDescription(String agencyIdentifierCd, String courtLevel, String courtClass) { + return Optional.empty(); + } + + @Override + public boolean checkValidLevelClassLocation(BigDecimal agencyId, String courtLevel, String courtClass, String applicationCode) { + return false; + } + + @Override + public boolean checkValidCourtFileNumber(String fileNumber, BigDecimal agencyId, String courtLevel, String courtClass, String applicationCode) { + return false; + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/EfilingDocumentServiceFake.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/EfilingDocumentServiceFake.java new file mode 100644 index 0000000000..d44e067a8d --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/EfilingDocumentServiceFake.java @@ -0,0 +1,18 @@ +package ca.bc.gov.open.jag.efilingapi.fakes; + +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; + +import java.util.List; + +public class EfilingDocumentServiceFake implements EfilingDocumentService { + @Override + public DocumentTypeDetails getDocumentTypeDetails(String courtLevel, String courtClass, String documentType) { + return null; + } + + @Override + public List getDocumentTypes(String courtLevel, String courtClass) { + return null; + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/EfilingSearchServiceFake.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/EfilingSearchServiceFake.java new file mode 100644 index 0000000000..7170fb6196 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fakes/EfilingSearchServiceFake.java @@ -0,0 +1,10 @@ +package ca.bc.gov.open.jag.efilingapi.fakes; + +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSearchService; + +public class EfilingSearchServiceFake implements EfilingSearchService { + @Override + public boolean caseNumberExists(String caseNumber) { + return false; + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fee/mockservice/GetFeeTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fee/mockservice/GetFeeTest.java deleted file mode 100644 index c4a1c9da51..0000000000 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fee/mockservice/GetFeeTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package ca.bc.gov.open.jag.efilingapi.fee.mockservice; - -import ca.bc.gov.open.jag.efilingapi.fee.MockFeeService; -import ca.bc.gov.open.jag.efilingapi.fee.models.Fee; -import ca.bc.gov.open.jag.efilingapi.fee.models.FeeRequest; -import org.junit.jupiter.api.*; - -import java.math.BigDecimal; - -@DisplayName("MockFeeService getFee Test Suite") -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -public class GetFeeTest { - - private MockFeeService sut; - - @BeforeAll - public void setUp() { - sut = new MockFeeService(); - } - - @Test - @DisplayName("CASE1: with any request should return 7") - public void withAnyRequestShouldReturnSeven() { - - Fee actual = sut.getFee(new FeeRequest("type", "subtype")); - - Assertions.assertEquals(new BigDecimal(7), actual.getAmount()); - - } - -} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fee/models/ConfigTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fee/models/ConfigTest.java deleted file mode 100644 index 70a4f5c4af..0000000000 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fee/models/ConfigTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package ca.bc.gov.open.jag.efilingapi.fee.models; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -@DisplayName("Config Test Suite") -public class ConfigTest { - ApplicationContextRunner context = new ApplicationContextRunner() - .withUserConfiguration(Config.class); - - @Test - @DisplayName("CASE1: Test that beans are created") - public void testBeansAreGenerated() { - context.run(it -> { - assertThat(it).hasSingleBean(Config.class); - }); - } -} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fee/models/FeeRequestTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fee/models/FeeRequestTest.java deleted file mode 100644 index 8aa5ca3bc8..0000000000 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/fee/models/FeeRequestTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package ca.bc.gov.open.jag.efilingapi.fee.models; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@DisplayName("FeeRequest Test Suite") -public class FeeRequestTest { - - private static final String DOCTYPE = "DOCTYPE"; - private static final String SUBDOCTYPE = "SUBDOCTYPE"; - - @Test - @DisplayName("CASE1: Test getters") - public void testGettSetter() { - FeeRequest testFee = new FeeRequest(DOCTYPE, SUBDOCTYPE); - Assertions.assertEquals(DOCTYPE, testFee.getDocumentType()); - Assertions.assertEquals(SUBDOCTYPE, testFee.getDocumentSubType()); - } -} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/FilingPackageConfigTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/FilingPackageConfigTest.java new file mode 100644 index 0000000000..1a67d0bcd1 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/FilingPackageConfigTest.java @@ -0,0 +1,128 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage; + +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.CreateCsoAccountRequest; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import ca.bc.gov.open.jag.efilingcommons.model.RushDocumentRequest; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.DeleteSubmissionDocumentRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackageRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.ReportRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewFilingPackage; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilePackageConfigTest") +public class FilingPackageConfigTest { + + + @Configuration + public static class TestConfig { + + @Bean + public AccountService accountService() { + return new AccountService() { + + @Override + public AccountDetails getCsoAccountDetails(String universalId) { + return null; + } + + @Override + public void updateClient(AccountDetails accountDetails) { + + } + + @Override + public AccountDetails createAccount(String universalId, String identityProvider ,CreateCsoAccountRequest createAccountRequest) { + return null; + } + }; + } + + @Bean + public EfilingDocumentService efilingDocumentService() { + return new EfilingDocumentService() { + @Override + public DocumentTypeDetails getDocumentTypeDetails(String courtLevel, String courtClass, String documentType) { + return null; + } + + @Override + public List getDocumentTypes(String courtLevel, String courtClass) { + return null; + } + }; + } + + @Bean + public EfilingReviewService efilingReviewService() { + return new EfilingReviewService() { + @Override + public Optional findStatusByPackage(FilingPackageRequest filingPackageRequest) { + return Optional.empty(); + } + + @Override + public List findStatusByClient(FilingPackageRequest filingPackageRequest) { + return new ArrayList<>(); + } + + @Override + public Optional getReport(ReportRequest reportRequest) { + return Optional.empty(); + } + + @Override + public Optional getSubmittedDocument(BigDecimal documentIdentifier) { + return Optional.empty(); + } + + @Override + public void deleteSubmittedDocument(DeleteSubmissionDocumentRequest deleteSubmissionDocumentRequest) { + //Do nothing + } + + @Override + public Optional getRushDocument(RushDocumentRequest rushDocumentRequest) { + return Optional.empty(); + } + }; + + } + + } + + ApplicationContextRunner context = new ApplicationContextRunner() + .withUserConfiguration(FilingPackageConfigTest.TestConfig.class) + .withUserConfiguration(FilingPackageConfig.class); + + @Test + public void testConfigure() { + + context.run(it -> { + assertThat(it).hasSingleBean(AccountService.class); + assertThat(it).hasSingleBean(FilingPackageService.class); + + }); + + } + + + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/DeleteSubmittedDocumentTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/DeleteSubmittedDocumentTest.java new file mode 100644 index 0000000000..5b8a21ba12 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/DeleteSubmittedDocumentTest.java @@ -0,0 +1,111 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.filingpackageApiDelegateImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.error.DeleteDocumentException; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingapi.error.MissingUniversalIdException; +import ca.bc.gov.open.jag.efilingapi.filingpackage.FilingpackageApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingAccountServiceException; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.math.BigDecimal; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilepackageApiDelegateImplTest") +public class DeleteSubmittedDocumentTest { + + FilingpackageApiDelegateImpl sut; + + @Mock + FilingPackageService filingPackageService; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + Mockito.doNothing().when(filingPackageService).deleteSubmittedDocument(any(), ArgumentMatchers.eq(BigDecimal.ONE), ArgumentMatchers.eq(TestHelpers.DOCUMENT_ID_ONE)); + + Mockito.doThrow(RuntimeException.class).when(filingPackageService).deleteSubmittedDocument(any(), ArgumentMatchers.eq(BigDecimal.ONE), ArgumentMatchers.eq(TestHelpers.DOCUMENT_ID_TWO)); + + Mockito.doThrow(EfilingAccountServiceException.class).when(filingPackageService).deleteSubmittedDocument(any(), ArgumentMatchers.eq(BigDecimal.TEN), ArgumentMatchers.eq(TestHelpers.DOCUMENT_ID_TWO)); + + sut = new FilingpackageApiDelegateImpl(filingPackageService); + } + + @Test + @DisplayName("200: ok document was deleted") + public void withValidRequestReturnFilingPackage() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity result = sut.deleteSubmittedDocument(BigDecimal.ONE, TestHelpers.DOCUMENT_ID_ONE); + + Assertions.assertEquals(HttpStatus.OK, result.getStatusCode()); + + } + + @Test + @DisplayName("403: when no universal id should throw MissingUniversalIdException") + public void withNoUniversalIdShouldThrowMissingUniversalIdException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + MissingUniversalIdException exception = Assertions.assertThrows(MissingUniversalIdException.class, () -> sut.deleteSubmittedDocument(BigDecimal.ONE, TestHelpers.DOCUMENT_ID_ONE)); + Assertions.assertEquals(ErrorCode.MISSING_UNIVERSAL_ID.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("400: when delete failed should throw DeleteDocumentException") + public void withDeleteFailedShouldThrowDeleteDocumentException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + DeleteDocumentException exception = Assertions.assertThrows(DeleteDocumentException.class, () -> sut.deleteSubmittedDocument(BigDecimal.ONE, TestHelpers.DOCUMENT_ID_TWO)); + Assertions.assertEquals(ErrorCode.DELETE_DOCUMENT_ERROR.toString(), exception.getErrorCode()); + Assertions.assertEquals(HttpStatus.BAD_REQUEST, exception.getHttpStatus()); + } + + @Test + @DisplayName("404: when delete failed should throw DeleteDocumentException") + public void withDeleteAccountNotFoundFailedShouldThrowDeleteDocumentException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + DeleteDocumentException exception = Assertions.assertThrows(DeleteDocumentException.class, () -> sut.deleteSubmittedDocument(BigDecimal.TEN, TestHelpers.DOCUMENT_ID_TWO)); + Assertions.assertEquals(ErrorCode.DELETE_DOCUMENT_ERROR.toString(), exception.getErrorCode()); + Assertions.assertEquals(HttpStatus.NOT_FOUND, exception.getHttpStatus()); + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetActionRequiredDetailsTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetActionRequiredDetailsTest.java new file mode 100644 index 0000000000..a00238205e --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetActionRequiredDetailsTest.java @@ -0,0 +1,100 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.filingpackageApiDelegateImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.api.model.ActionRequiredDetails; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingapi.error.FilingPackageNotFoundException; +import ca.bc.gov.open.jag.efilingapi.error.MissingUniversalIdException; +import ca.bc.gov.open.jag.efilingapi.filingpackage.FilingpackageApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.math.BigDecimal; +import java.util.Optional; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilepackageApiDelegateImplTest") +public class GetActionRequiredDetailsTest { + + FilingpackageApiDelegateImpl sut; + + @Mock + FilingPackageService filingPackageService; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + Mockito.when(filingPackageService.getActionRequiredDetails(ArgumentMatchers.eq(TestHelpers.CASE_1_STRING), ArgumentMatchers.eq(BigDecimal.ONE))).thenReturn(Optional.of(new ActionRequiredDetails())); + + + Mockito.when(filingPackageService.getActionRequiredDetails(ArgumentMatchers.eq(TestHelpers.CASE_2_STRING), ArgumentMatchers.eq(BigDecimal.TEN))).thenReturn(Optional.empty()); + + sut = new FilingpackageApiDelegateImpl(filingPackageService); + } + + @Test + @DisplayName("200: ok action required details returned") + public void withValidRequestReturnActionRequiredDetails() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity result = sut.getActionRequiredDetails(BigDecimal.ONE); + + Assertions.assertEquals(HttpStatus.OK, result.getStatusCode()); + + } + + @Test + @DisplayName("403: when no universal id should return 403") + public void withNoUniversalIdShouldReturn403() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + MissingUniversalIdException exception = Assertions.assertThrows(MissingUniversalIdException.class, () -> sut.getActionRequiredDetails(BigDecimal.ONE)); + Assertions.assertEquals(ErrorCode.MISSING_UNIVERSAL_ID.toString(), exception.getErrorCode()); + + } + + @Test + @DisplayName("404: when no filling package is found should throw FilingPackageNotFoundException") + public void withValidRequestNotFoundShouldThrowFilingPackageNotFoundException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_2.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + FilingPackageNotFoundException exception = Assertions.assertThrows(FilingPackageNotFoundException.class, () -> sut.getActionRequiredDetails(BigDecimal.ONE)); + Assertions.assertEquals(ErrorCode.FILING_PACKAGE_NOT_FOUND.toString(), exception.getErrorCode()); + + } + +} + diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetFilingPackageTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetFilingPackageTest.java new file mode 100644 index 0000000000..3783581aac --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetFilingPackageTest.java @@ -0,0 +1,100 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.filingpackageApiDelegateImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.api.model.FilingPackage; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingapi.error.FilingPackageNotFoundException; +import ca.bc.gov.open.jag.efilingapi.error.MissingUniversalIdException; +import ca.bc.gov.open.jag.efilingapi.filingpackage.FilingpackageApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.math.BigDecimal; +import java.util.Optional; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilepackageApiDelegateImplTest") +public class GetFilingPackageTest { + + + FilingpackageApiDelegateImpl sut; + + @Mock + FilingPackageService filingPackageService; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + Mockito.when(filingPackageService.getCSOFilingPackage(ArgumentMatchers.eq(TestHelpers.CASE_1_STRING), ArgumentMatchers.eq(BigDecimal.ONE))).thenReturn(Optional.of(new FilingPackage())); + + + Mockito.when(filingPackageService.getCSOFilingPackage(ArgumentMatchers.eq(TestHelpers.CASE_2_STRING), ArgumentMatchers.eq(BigDecimal.TEN))).thenReturn(Optional.empty()); + + sut = new FilingpackageApiDelegateImpl(filingPackageService); + } + + @Test + @DisplayName("200: ok url was generated") + public void withValidRequestReturnFilingPackage() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity result = sut.getFilingPackage(BigDecimal.ONE); + + Assertions.assertEquals(HttpStatus.OK, result.getStatusCode()); + + } + + @Test + @DisplayName("403: when no universal id should return 403") + public void withNoUniversalIdShouldReturn403() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + MissingUniversalIdException exception = Assertions.assertThrows(MissingUniversalIdException.class, () -> sut.getFilingPackage(BigDecimal.ONE)); + Assertions.assertEquals(ErrorCode.MISSING_UNIVERSAL_ID.toString(), exception.getErrorCode()); + + } + + @Test + @DisplayName("404: when no filling package is found should throw FilingPackageNotFoundException") + public void withValidRequestNotFoundShouldThrowFilingPackageNotFoundException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_2.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + FilingPackageNotFoundException exception = Assertions.assertThrows(FilingPackageNotFoundException.class, () -> sut.getFilingPackage(BigDecimal.ONE)); + Assertions.assertEquals(ErrorCode.FILING_PACKAGE_NOT_FOUND.toString(), exception.getErrorCode()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetFilingPackagesTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetFilingPackagesTest.java new file mode 100644 index 0000000000..8c905df0ab --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetFilingPackagesTest.java @@ -0,0 +1,104 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.filingpackageApiDelegateImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.api.model.FilingPackage; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingapi.error.FilingPackageNotFoundException; +import ca.bc.gov.open.jag.efilingapi.error.MissingUniversalIdException; +import ca.bc.gov.open.jag.efilingapi.filingpackage.FilingpackageApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilePackageServiceImplTest") + +public class GetFilingPackagesTest { + + public static final String PARENT_APPLICATION_FOUND = "FOUND"; + public static final String PARENT_APPLICATION_NOT_FOUND = "NOT_FOUND"; + FilingpackageApiDelegateImpl sut; + + @Mock + FilingPackageService filingPackageService; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + Mockito.when(filingPackageService.getFilingPackages(ArgumentMatchers.eq(TestHelpers.CASE_1_STRING), ArgumentMatchers.eq(PARENT_APPLICATION_FOUND))).thenReturn(Optional.of(new ArrayList<>())); + + Mockito.when(filingPackageService.getFilingPackages(ArgumentMatchers.eq(TestHelpers.CASE_2_STRING), ArgumentMatchers.eq(PARENT_APPLICATION_FOUND))).thenReturn(Optional.empty()); + + sut = new FilingpackageApiDelegateImpl(filingPackageService); + } + + @Test + @DisplayName("200: ok filingpackages returned") + public void withValidRequestReturnFilingPackages() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity> actual = sut.getFilingPackages(PARENT_APPLICATION_FOUND); + + Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); + + } + + @Test + @DisplayName("403: when no universal id should throw MissingUniversalIdException") + public void withNoUniversalIdShouldThrowMissingUniversalIdException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + + MissingUniversalIdException exception = Assertions.assertThrows(MissingUniversalIdException.class, () -> sut.getFilingPackages(PARENT_APPLICATION_FOUND)); + Assertions.assertEquals(ErrorCode.MISSING_UNIVERSAL_ID.toString(), exception.getErrorCode()); + + } + + @Test + @DisplayName("404: when no filling packages found should throw FilingPackageNotFoundException") + public void withValidRequestNotFoundShouldThrowFilingPackageNotFoundException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_2.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + + FilingPackageNotFoundException exception = Assertions.assertThrows(FilingPackageNotFoundException.class, () -> sut.getFilingPackages(PARENT_APPLICATION_NOT_FOUND)); + Assertions.assertEquals(ErrorCode.FILING_PACKAGE_NOT_FOUND.toString(), exception.getErrorCode()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetParentAppDetailsTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetParentAppDetailsTest.java new file mode 100644 index 0000000000..5e198e8a44 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetParentAppDetailsTest.java @@ -0,0 +1,110 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.filingpackageApiDelegateImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.api.model.ParentAppDetails; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingapi.error.FilingPackageNotFoundException; +import ca.bc.gov.open.jag.efilingapi.error.MissingUniversalIdException; +import ca.bc.gov.open.jag.efilingapi.filingpackage.FilingpackageApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.math.BigDecimal; +import java.util.Optional; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilepackageApiDelegateImplTest") +public class GetParentAppDetailsTest { + + public static final UUID CASE_1 = UUID.randomUUID(); + public static final UUID CASE_2 = UUID.randomUUID(); + + private static final String RETURN_URL = "http://localhost:8080/"; + + FilingpackageApiDelegateImpl sut; + + @Mock + FilingPackageService filingPackageService; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + sut = new FilingpackageApiDelegateImpl(filingPackageService); + } + + @Test + @DisplayName("200: ok url was generated") + public void withValidRequestReturnParentAppDetails() { + + ParentAppDetails parentAppDetails = new ParentAppDetails(); + + parentAppDetails.setReturnUrl(RETURN_URL); + parentAppDetails.setRejectedDocumentFeature(true); + + Mockito.when(filingPackageService.getParentDetails(Mockito.any(), Mockito.any())).thenReturn(Optional.of(parentAppDetails)); + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity result = sut.getParentDetails(BigDecimal.ONE); + + Assertions.assertEquals(HttpStatus.OK, result.getStatusCode()); + Assertions.assertEquals(RETURN_URL, result.getBody().getReturnUrl()); + Assertions.assertTrue(result.getBody().getRejectedDocumentFeature()); + + } + + @Test + @DisplayName("403: when no universal id should return 403") + public void withNoUniversalIdShouldReturn403() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + MissingUniversalIdException exception = Assertions.assertThrows(MissingUniversalIdException.class, () -> sut.getParentDetails(BigDecimal.ONE)); + Assertions.assertEquals(ErrorCode.MISSING_UNIVERSAL_ID.toString(), exception.getErrorCode()); + + } + + @Test + @DisplayName("404: when no filling package is found return 404") + public void withValidRequestFilingPackageNotFound() { + + Mockito.when(filingPackageService.getParentDetails(Mockito.any(), Mockito.any())).thenReturn(Optional.empty()); + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_2.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + FilingPackageNotFoundException exception = Assertions.assertThrows(FilingPackageNotFoundException.class, () -> sut.getParentDetails(BigDecimal.TEN)); + Assertions.assertEquals(ErrorCode.FILING_PACKAGE_NOT_FOUND.toString(), exception.getErrorCode()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetPaymentReceiptTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetPaymentReceiptTest.java new file mode 100644 index 0000000000..4c03b72c45 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetPaymentReceiptTest.java @@ -0,0 +1,103 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.filingpackageApiDelegateImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.filingpackage.FilingpackageApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.math.BigDecimal; +import java.util.Optional; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("GetPaymentReceiptTest") +public class GetPaymentReceiptTest { + public static final UUID CASE_1 = UUID.randomUUID(); + public static final UUID CASE_2 = UUID.randomUUID(); + + public static final byte[] BYTES = "TEST".getBytes(); + + FilingpackageApiDelegateImpl sut; + + @Mock + FilingPackageService filingPackageService; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + sut = new FilingpackageApiDelegateImpl(filingPackageService); + + } + + @Test + @DisplayName("200: ok url was generated") + public void withValidRequestReturnFilingPackage() { + + Mockito.when(filingPackageService.getReport(Mockito.any())).thenReturn(Optional.of(new ByteArrayResource(BYTES))); + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity result = sut.getPaymentReceipt(BigDecimal.ONE); + + Assertions.assertEquals(HttpStatus.OK, result.getStatusCode()); + + } + + @Test + @DisplayName("403: when no universal id should return 403") + public void withNoUniversalIdShouldReturn403() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getPaymentReceipt(BigDecimal.ONE); + + Assertions.assertEquals(HttpStatus.FORBIDDEN, actual.getStatusCode()); + + } + + @Test + @DisplayName("404: when no filling package is found return 404") + public void withValidRequestFilingPackageNotFound() { + + Mockito.when(filingPackageService.getReport(Mockito.any())).thenReturn(Optional.empty()); + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_2.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity result = sut.getPaymentReceipt(BigDecimal.TEN); + + Assertions.assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetRegistryNoticeTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetRegistryNoticeTest.java new file mode 100644 index 0000000000..8242e7ca17 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetRegistryNoticeTest.java @@ -0,0 +1,102 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.filingpackageApiDelegateImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.filingpackage.FilingpackageApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.math.BigDecimal; +import java.util.Optional; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("GetPaymentReceiptTest") +public class GetRegistryNoticeTest { + public static final UUID CASE_1 = UUID.randomUUID(); + public static final UUID CASE_2 = UUID.randomUUID(); + + public static final byte[] BYTES = "TEST".getBytes(); + + FilingpackageApiDelegateImpl sut; + + @Mock + FilingPackageService filingPackageService; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + sut = new FilingpackageApiDelegateImpl(filingPackageService); + + } + + @Test + @DisplayName("200: ok registry notice returned") + public void withValidRequestReturnRegistryNotice() { + + Mockito.when(filingPackageService.getReport(Mockito.any())).thenReturn(Optional.of(new ByteArrayResource(BYTES))); + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity result = sut.getRegistryNotice(BigDecimal.ONE); + + Assertions.assertEquals(HttpStatus.OK, result.getStatusCode()); + + } + + @Test + @DisplayName("403: when no universal id should return 403") + public void withNoUniversalIdShouldReturn403() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getRegistryNotice(BigDecimal.ONE); + + Assertions.assertEquals(HttpStatus.FORBIDDEN, actual.getStatusCode()); + + } + + @Test + @DisplayName("404: when no filling package is found return 404") + public void withValidRequestFilingPackageNotFound() { + + Mockito.when(filingPackageService.getReport(Mockito.any())).thenReturn(Optional.empty()); + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_2.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + ResponseEntity result = sut.getRegistryNotice(BigDecimal.TEN); + + Assertions.assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetRushDocumentTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetRushDocumentTest.java new file mode 100644 index 0000000000..685fceaa07 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetRushDocumentTest.java @@ -0,0 +1,114 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.filingpackageApiDelegateImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.filingpackage.FilingpackageApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.model.SubmittedDocument; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.math.BigDecimal; +import java.util.Optional; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilepackageApiDelegateImplTest") +public class GetRushDocumentTest { + public static final UUID CASE_1 = UUID.randomUUID(); + public static final UUID CASE_2 = UUID.randomUUID(); + + public static final String FOUND_DOCUMENT_IDENTIFIER = "1"; + + public static final String NOT_FOUND_DOCUMENT_IDENTIFIER = "10"; + + public static final byte[] BYTES = "TEST".getBytes(); + + FilingpackageApiDelegateImpl sut; + + @Mock + FilingPackageService filingPackageService; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + Mockito.when(filingPackageService.getRushDocument(Mockito.any(), ArgumentMatchers.eq(BigDecimal.ONE), Mockito.any())).thenReturn(Optional.of(SubmittedDocument.builder() + .data(new ByteArrayResource(BYTES)) + .name("TEST") + .create())); + + Mockito.when(filingPackageService.getRushDocument(Mockito.any(), ArgumentMatchers.eq(BigDecimal.TEN), Mockito.any())).thenReturn(Optional.empty()); + + sut = new FilingpackageApiDelegateImpl(filingPackageService); + + } + + @Test + @DisplayName("200: File is returned") + public void withValidRequestReturnFilingPackage() { + + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity result = sut.getRushDocument(BigDecimal.ONE, FOUND_DOCUMENT_IDENTIFIER); + + Assertions.assertEquals(HttpStatus.OK, result.getStatusCode()); + + } + + @Test + @DisplayName("403: when no universal id should return 403") + public void withNoUniversalIdShouldReturn403() { + + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getRushDocument(BigDecimal.ONE, NOT_FOUND_DOCUMENT_IDENTIFIER); + + Assertions.assertEquals(HttpStatus.FORBIDDEN, actual.getStatusCode()); + + } + + @Test + @DisplayName("404: when no document should return 404") + public void withNoDocumentShouldReturn404() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getRushDocument(BigDecimal.TEN, NOT_FOUND_DOCUMENT_IDENTIFIER); + + Assertions.assertEquals(HttpStatus.NOT_FOUND, actual.getStatusCode()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetSubmissionDocumentTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetSubmissionDocumentTest.java new file mode 100644 index 0000000000..f07727ccc5 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetSubmissionDocumentTest.java @@ -0,0 +1,112 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.filingpackageApiDelegateImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.filingpackage.FilingpackageApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.model.SubmittedDocument; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.math.BigDecimal; +import java.util.Optional; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilepackageApiDelegateImplTest") +public class GetSubmissionDocumentTest { + public static final UUID CASE_1 = UUID.randomUUID(); + public static final UUID CASE_2 = UUID.randomUUID(); + + public static final BigDecimal FOUND_DOCUMENT_IDENTIFIER = BigDecimal.ONE; + + public static final BigDecimal NOT_FOUND_DOCUMENT_IDENTIFIER = BigDecimal.TEN; + + public static final byte[] BYTES = "TEST".getBytes(); + + FilingpackageApiDelegateImpl sut; + + @Mock + FilingPackageService filingPackageService; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + Mockito.when(filingPackageService.getSubmittedDocument(Mockito.any(), ArgumentMatchers.eq(BigDecimal.ONE), Mockito.any())).thenReturn(Optional.of(SubmittedDocument.builder() + .data(new ByteArrayResource(BYTES)) + .name("TEST") + .create())); + + Mockito.when(filingPackageService.getSubmittedDocument(Mockito.any(), ArgumentMatchers.eq(BigDecimal.TEN), Mockito.any())).thenReturn(Optional.empty()); + + sut = new FilingpackageApiDelegateImpl(filingPackageService); + + } + + @Test + @DisplayName("200: File is returned") + public void withValidRequestReturnFilingPackage() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity result = sut.getSubmittedDocument(BigDecimal.ONE, FOUND_DOCUMENT_IDENTIFIER); + + Assertions.assertEquals(HttpStatus.OK, result.getStatusCode()); + + } + + @Test + @DisplayName("403: when no universal id should return 403") + public void withNoUniversalIdShouldReturn403() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getSubmittedDocument(BigDecimal.ONE, NOT_FOUND_DOCUMENT_IDENTIFIER); + + Assertions.assertEquals(HttpStatus.FORBIDDEN, actual.getStatusCode()); + + } + + @Test + @DisplayName("404: when no document should return 404") + public void withNoDocumentShouldReturn404() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getSubmittedDocument(BigDecimal.TEN, NOT_FOUND_DOCUMENT_IDENTIFIER); + + Assertions.assertEquals(HttpStatus.NOT_FOUND, actual.getStatusCode()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetSubmissionSheetTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetSubmissionSheetTest.java new file mode 100644 index 0000000000..c07f63df83 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/filingpackageApiDelegateImpl/GetSubmissionSheetTest.java @@ -0,0 +1,102 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.filingpackageApiDelegateImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.filingpackage.FilingpackageApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.math.BigDecimal; +import java.util.Optional; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilepackageApiDelegateImplTest") + +public class GetSubmissionSheetTest { + public static final UUID CASE_1 = UUID.randomUUID(); + public static final UUID CASE_2 = UUID.randomUUID(); + + public static final byte[] BYTES = "TEST".getBytes(); + + FilingpackageApiDelegateImpl sut; + + @Mock + FilingPackageService filingPackageService; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @BeforeAll + public void beforeEach() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + sut = new FilingpackageApiDelegateImpl(filingPackageService); + } + + @Test + @DisplayName("200: ok url was generated") + public void withValidRequestReturnFilingPackage() { + + Mockito.when(filingPackageService.getReport(Mockito.any())).thenReturn(Optional.of(new ByteArrayResource(BYTES))); + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity result = sut.getSubmissionSheet(BigDecimal.ONE); + + Assertions.assertEquals(HttpStatus.OK, result.getStatusCode()); + + } + + @Test + @DisplayName("403: when no universal id should return 403") + public void withNoUniversalIdShouldReturn403() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getSubmissionSheet(BigDecimal.ONE); + + Assertions.assertEquals(HttpStatus.FORBIDDEN, actual.getStatusCode()); + + } + + @Test + @DisplayName("404: when no filling package is found return 404") + public void withValidRequestFilingPackageNotFound() { + + Mockito.when(filingPackageService.getReport(Mockito.any())).thenReturn(Optional.empty()); + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_2.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity result = sut.getSubmissionSheet(BigDecimal.TEN); + + Assertions.assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode()); + + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/DeleteSubmittedDocumentTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/DeleteSubmittedDocumentTest.java new file mode 100644 index 0000000000..929a3b989d --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/DeleteSubmittedDocumentTest.java @@ -0,0 +1,73 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.service.filingPackageServiceImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.filingpackage.mapper.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageServiceImpl; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingAccountServiceException; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilePackageServiceImplTest") +public class DeleteSubmittedDocumentTest { + + FilingPackageServiceImpl sut; + + @Mock + EfilingReviewService efilingReviewServiceMock; + + @Mock + AccountService accountServiceMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_1_STRING))).thenReturn(TestHelpers.createAccount(BigDecimal.ONE)); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_2_STRING))).thenReturn(TestHelpers.createAccount(null)); + + sut = new FilingPackageServiceImpl(efilingReviewServiceMock, null, accountServiceMock, new FilingPackageMapperImpl(), null, null); + } + + + @Test + @DisplayName("Ok: a document was deleted") + public void withValidRequestReturnDocument() { + + Mockito.doNothing().when(efilingReviewServiceMock).deleteSubmittedDocument(any()); + + Assertions.assertDoesNotThrow(() -> sut.deleteSubmittedDocument(TestHelpers.CASE_1_STRING, BigDecimal.ONE, TestHelpers.DOCUMENT_ID_TWO)); + + } + + @Test + @DisplayName("failed: missing account") + public void withValidRequestButMissingAccountReturnEmpty() { + + Assertions.assertThrows(EfilingAccountServiceException.class, () -> sut.deleteSubmittedDocument(TestHelpers.CASE_2_STRING, BigDecimal.ONE, TestHelpers.DOCUMENT_ID_TWO)); + + + } + + + @Test + @DisplayName("failed: nothing was deleted") + public void withValidRequestButMissingPackageReturnEmpty() { + + Mockito.doThrow(RuntimeException.class).when(efilingReviewServiceMock).deleteSubmittedDocument(any()); + + Assertions.assertThrows(Exception.class, () ->sut.deleteSubmittedDocument(TestHelpers.CASE_1_STRING, BigDecimal.TEN, TestHelpers.DOCUMENT_ID_TWO)); + + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetActionRequiredDetailsTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetActionRequiredDetailsTest.java new file mode 100644 index 0000000000..d591e3c92f --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetActionRequiredDetailsTest.java @@ -0,0 +1,101 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.service.filingPackageServiceImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.ActionDocument; +import ca.bc.gov.open.jag.efilingapi.api.model.ActionRequiredDetails; +import ca.bc.gov.open.jag.efilingapi.error.NoRegistryNoticeException; +import ca.bc.gov.open.jag.efilingapi.filingpackage.mapper.ActionRequiredDetailsMapperImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.mapper.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageServiceImpl; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; +import java.util.Optional; + +import static ca.bc.gov.open.jag.efilingapi.TestHelpers.DOCUMENT_ID_TWO; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilePackageServiceImplTest") +public class GetActionRequiredDetailsTest { + public static final String EXPECTED_ISO = "2020-05-05T00:00:00.000-07:00"; + + FilingPackageServiceImpl sut; + + @Mock + EfilingReviewService efilingReviewServiceMock; + + @Mock + AccountService accountServiceMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_1_STRING))).thenReturn(TestHelpers.createAccount(BigDecimal.ONE)); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_2_STRING))).thenReturn(TestHelpers.createAccount(null)); + + sut = new FilingPackageServiceImpl(efilingReviewServiceMock, null, accountServiceMock, new FilingPackageMapperImpl(), new ActionRequiredDetailsMapperImpl(), null); + } + + @Test + @DisplayName("Ok: action details returned was returned") + public void withValidRequestReturnActionRequiredDetails() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.of(TestHelpers.createFilingPackage(true))); + + Optional result = sut.getActionRequiredDetails(TestHelpers.CASE_1_STRING, BigDecimal.ONE); + + Assertions.assertTrue(result.isPresent()); + + Assertions.assertEquals(BigDecimal.ONE, result.get().getClientId()); + Assertions.assertEquals(BigDecimal.valueOf(123), result.get().getPackageIdentifier()); + //Assert Documents + Assertions.assertEquals(1, result.get().getDocuments().size()); + Assertions.assertEquals(new BigDecimal(DOCUMENT_ID_TWO), result.get().getDocuments().get(0).getId()); + Assertions.assertEquals(ActionDocument.StatusEnum.REJ, result.get().getDocuments().get(0).getStatus()); + Assertions.assertEquals("AAB", result.get().getDocuments().get(0).getType()); + } + + @Test + @DisplayName("Not found: missing account") + public void withValidRequestButMissingAccountReturnEmpty() { + + Optional result = sut.getActionRequiredDetails(TestHelpers.CASE_2_STRING, BigDecimal.ONE); + + Assertions.assertFalse(result.isPresent()); + + } + + + @Test + @DisplayName("Not found: no filing package") + public void withValidRequestButMissingPackageReturnEmpty() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.empty()); + + Optional result = sut.getActionRequiredDetails(TestHelpers.CASE_1_STRING, BigDecimal.TEN); + + Assertions.assertFalse(result.isPresent()); + + } + + @Test + @DisplayName("No Registry Notice: throws exception") + public void withValidRequestButNoRegistryNoticeEmpty() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.of(TestHelpers.createFilingPackage(false))); + + Assertions.assertThrows(NoRegistryNoticeException.class, () -> sut.getActionRequiredDetails(TestHelpers.CASE_1_STRING, BigDecimal.TEN)); + + } + +} + diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetCSOFilingPackageTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetCSOFilingPackageTest.java new file mode 100644 index 0000000000..b9f7d9d28e --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetCSOFilingPackageTest.java @@ -0,0 +1,196 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.service.filingPackageServiceImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.FilingPackage; +import ca.bc.gov.open.jag.efilingapi.api.model.Rush; +import ca.bc.gov.open.jag.efilingapi.filingpackage.mapper.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageServiceImpl; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewDocument; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewFilingPackage; +import org.joda.time.DateTime; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilePackageServiceImplTest") +public class GetCSOFilingPackageTest { + + public static final String EXPECTED_ISO = "2020-05-05T00:00:00.000-07:00"; + + FilingPackageServiceImpl sut; + + @Mock + EfilingReviewService efilingReviewServiceMock; + + + @Mock + EfilingDocumentService efilingDocumentServiceMock; + + @Mock + AccountService accountServiceMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_1_STRING))).thenReturn(TestHelpers.createAccount(BigDecimal.ONE)); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_2_STRING))).thenReturn(TestHelpers.createAccount(null)); + + sut = new FilingPackageServiceImpl(efilingReviewServiceMock, efilingDocumentServiceMock, accountServiceMock, new FilingPackageMapperImpl(), null, null); + } + + @Test + @DisplayName("Ok: a filing package was returned") + public void withValidRequestReturnFilingPackage() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.of(TestHelpers.createFilingPackage(true))); + + Mockito.when(efilingDocumentServiceMock.getDocumentTypeDetails(any(), any(), any())).thenReturn(new DocumentTypeDetails("description", + "type", + BigDecimal.TEN, + true, + true, + true)); + + Optional result = sut.getCSOFilingPackage(TestHelpers.CASE_1_STRING, BigDecimal.ONE); + + Assertions.assertTrue(result.isPresent()); + //FilingPackage + Assertions.assertEquals(TestHelpers.COMMENT, result.get().getFilingComments()); + Assertions.assertEquals(new BigDecimal(TestHelpers.PACKAGE_NO), result.get().getPackageNumber()); + Assertions.assertNotNull(result.get().getSubmittedDate()); + Assertions.assertEquals(TestHelpers.FIRST_NAME, result.get().getSubmittedBy().getFirstName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, result.get().getSubmittedBy().getLastName()); + Assertions.assertEquals(EXPECTED_ISO, result.get().getSubmittedDate()); + + //Court + Assertions.assertEquals(TestHelpers.CLASS_DESCRIPTION, result.get().getCourt().getClassDescription()); + Assertions.assertEquals(TestHelpers.COURT_CLASS, result.get().getCourt().getCourtClass()); + Assertions.assertEquals(TestHelpers.DIVISION, result.get().getCourt().getDivision()); + Assertions.assertEquals(TestHelpers.FILE_NUMBER, result.get().getCourt().getFileNumber()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getCourt().getAgencyId()); + Assertions.assertEquals(TestHelpers.LOCATION, result.get().getCourt().getLocation()); + Assertions.assertEquals(TestHelpers.LEVEL, result.get().getCourt().getLevel()); + Assertions.assertEquals(TestHelpers.LEVEL_DESCRIPTION, result.get().getCourt().getLevelDescription()); + Assertions.assertEquals(TestHelpers.LOCATION_DESCRIPTION, result.get().getCourt().getLocationDescription()); + Assertions.assertEquals(TestHelpers.PARTICIPATING_CLASS, result.get().getCourt().getParticipatingClass()); + //Party + Assertions.assertEquals(1, result.get().getParties().size()); + Assertions.assertEquals(TestHelpers.PARTY_TYPE_DESC, result.get().getParties().get(0).getPartyDescription()); + Assertions.assertEquals(ca.bc.gov.open.jag.efilingapi.api.model.Individual.RoleTypeEnum.ABC, result.get().getParties().get(0).getRoleType()); + Assertions.assertEquals(TestHelpers.ROLE_TYPE_DESC, result.get().getParties().get(0).getRoleDescription()); + Assertions.assertEquals(TestHelpers.FIRST_NAME, result.get().getParties().get(0).getFirstName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, result.get().getParties().get(0).getLastName()); + Assertions.assertEquals(TestHelpers.MIDDLE_NAME, result.get().getParties().get(0).getMiddleName()); + //Document + Assertions.assertEquals(2, result.get().getDocuments().size()); + Assertions.assertEquals("AAB", result.get().getDocuments().get(0).getDocumentProperties().getType()); + Assertions.assertEquals(TestHelpers.DESCRIPTION, result.get().getDocuments().get(0).getDescription()); + Assertions.assertEquals(TestHelpers.NAME, result.get().getDocuments().get(0).getDocumentProperties().getName()); + Assertions.assertEquals(TestHelpers.STATUS, result.get().getDocuments().get(0).getStatus().getDescription()); + Assertions.assertEquals(TestHelpers.STATUS_CODE, result.get().getDocuments().get(0).getStatus().getCode()); + Assertions.assertTrue( result.get().getDocuments().get(0).getRushRequired()); + Assertions.assertNotNull(result.get().getDocuments().get(0).getStatus().getChangeDate()); + Assertions.assertEquals(EXPECTED_ISO, result.get().getDocuments().get(0).getStatus().getChangeDate()); + Assertions.assertEquals(EXPECTED_ISO, result.get().getDocuments().get(0).getFilingDate()); + //Payments + Assertions.assertEquals(1, result.get().getPayments().size()); + Assertions.assertEquals(false, result.get().getPayments().get(0).getFeeExempt()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getPayments().get(0).getProcessedAmount()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getPayments().get(0).getProcessedAmount()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getPayments().get(0).getServiceIdentifier()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getPayments().get(0).getPaymentCategory()); + Assertions.assertEquals(TestHelpers.TRANSACTION_DESC, result.get().getPayments().get(0).getPaymentDescription()); + Assertions.assertEquals(EXPECTED_ISO, result.get().getPayments().get(0).getTransactionDate()); + //Rush + Assertions.assertEquals(Rush.RushTypeEnum.OTHER, result.get().getRush().getRushType()); + Assertions.assertEquals(TestHelpers.CONTACT_EMAIL_TXT, result.get().getRush().getEmail()); + Assertions.assertEquals(TestHelpers.FIRST_NAME, result.get().getRush().getFirstName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, result.get().getRush().getLastName()); + Assertions.assertEquals(TestHelpers.ORGANIZATION_NM, result.get().getRush().getOrganization()); + Assertions.assertEquals(TestHelpers.CONTACT_PHONE_NO, result.get().getRush().getPhoneNumber()); + Assertions.assertEquals(TestHelpers.CURRENT_STATUS_DSC, result.get().getRush().getStatus()); + Assertions.assertEquals(BigDecimal.ONE.toEngineeringString(), result.get().getRush().getCountryCode()); + Assertions.assertEquals(TestHelpers.COUNTRY_DSC, result.get().getRush().getCountry()); + Assertions.assertEquals(EXPECTED_ISO, result.get().getRush().getCourtDate()); + Assertions.assertEquals(TestHelpers.NOTICE_REASON_TEXT, result.get().getRush().getStatusReason()); + Assertions.assertEquals(TestHelpers.RUSH_FILING_REASON_TXT, result.get().getRush().getReason()); + + //Rush Documents + Assertions.assertEquals(2, result.get().getRush().getSupportingDocuments().size()); + + Assertions.assertEquals(TestHelpers.CLIENT_FILE_NM, result.get().getRush().getSupportingDocuments().get(0).getFileName()); + Assertions.assertEquals(TestHelpers.OBJECT_GUID, result.get().getRush().getSupportingDocuments().get(0).getIdentifier()); + + Assertions.assertEquals(TestHelpers.CLIENT_FILE_NM, result.get().getRush().getSupportingDocuments().get(1).getFileName()); + Assertions.assertEquals(TestHelpers.OBJECT_GUID, result.get().getRush().getSupportingDocuments().get(1).getIdentifier()); + + Assertions.assertEquals("http://localhost:8080/showmustgoon", result.get().getLinks().getPackageHistoryUrl()); + + } + + @Test + @DisplayName("Ok: a filing package was returned ensure withdrawn included") + public void withValidRequestReturnFilingPackageWithWithdrawnExcluded() { + + ReviewFilingPackage reviewFilingPackage = TestHelpers.createFilingPackage(true); + + ReviewDocument withdrawnDocument = new ReviewDocument(); + withdrawnDocument.setDocumentId("TEST"); + withdrawnDocument.setFileName("TEST"); + withdrawnDocument.setDocumentTypeCd("AAB"); + withdrawnDocument.setDocumentType("TEST"); + withdrawnDocument.setStatus("TEST"); + withdrawnDocument.setStatusCode(ca.bc.gov.open.jag.efilingcommons.Keys.WITHDRAWN_STATUS_CD); + withdrawnDocument.setStatusDate(DateTime.parse("2020-05-05T00:00:00.000-07:00")); + withdrawnDocument.setPaymentProcessed(true); + + reviewFilingPackage.getDocuments().add(withdrawnDocument); + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.of(reviewFilingPackage)); + + Optional result = sut.getCSOFilingPackage(TestHelpers.CASE_1_STRING, BigDecimal.ONE); + + Assertions.assertTrue(result.isPresent()); + //FilingPackage + //Document + Assertions.assertEquals(3, result.get().getDocuments().size()); + + } + + + @Test + @DisplayName("Not found: missing account") + public void withValidRequestButMissingAccountReturnEmpty() { + Optional result = sut.getCSOFilingPackage(TestHelpers.CASE_2_STRING, BigDecimal.ONE); + + Assertions.assertFalse(result.isPresent()); + } + + + @Test + @DisplayName("Not found: no filing package") + public void withValidRequestButMissingPackageReturnEmpty() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.empty()); + + Optional result = sut.getCSOFilingPackage(TestHelpers.CASE_1_STRING, BigDecimal.TEN); + + Assertions.assertFalse(result.isPresent()); + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetFilingPackagesTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetFilingPackagesTest.java new file mode 100644 index 0000000000..dbb9766b4e --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetFilingPackagesTest.java @@ -0,0 +1,131 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.service.filingPackageServiceImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.FilingPackage; +import ca.bc.gov.open.jag.efilingapi.filingpackage.mapper.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageServiceImpl; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilePackageServiceImplTest") +public class GetFilingPackagesTest { + + public static final String EXPECTED_ISO = "2020-05-05T00:00:00.000-07:00"; + public static final String PARENT_APPLICATION = "PARENT_APPLICATION"; + public static final String PARENT_APPLICATION_NOT_FOUND = "PARENT_APPLICATION_NOT_FOUND"; + + FilingPackageServiceImpl sut; + + @Mock + EfilingReviewService efilingReviewServiceMock; + + @Mock + AccountService accountServiceMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_1_STRING))).thenReturn(TestHelpers.createAccount(BigDecimal.ONE)); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_2_STRING))).thenReturn(TestHelpers.createAccount(null)); + + sut = new FilingPackageServiceImpl(efilingReviewServiceMock, null, accountServiceMock, new FilingPackageMapperImpl(), null, null); + + } + + @Test + @DisplayName("Ok: a filing package was returned") + public void withValidRequestReturnFilingPackage() { + + Mockito.when(efilingReviewServiceMock.findStatusByClient(ArgumentMatchers.any())).thenReturn(Collections.singletonList(TestHelpers.createFilingPackage(true))); + + Optional> actual = sut.getFilingPackages(TestHelpers.CASE_1_STRING, PARENT_APPLICATION); + + Assertions.assertTrue(actual.isPresent()); + //FilingPackage + Assertions.assertEquals(TestHelpers.COMMENT, actual.get().get(0).getFilingComments()); + Assertions.assertEquals(new BigDecimal(TestHelpers.PACKAGE_NO), actual.get().get(0).getPackageNumber()); + Assertions.assertNotNull(actual.get().get(0).getSubmittedDate()); + Assertions.assertEquals(TestHelpers.FIRST_NAME, actual.get().get(0).getSubmittedBy().getFirstName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, actual.get().get(0).getSubmittedBy().getLastName()); + Assertions.assertEquals(EXPECTED_ISO, actual.get().get(0).getSubmittedDate()); + + //Court + Assertions.assertEquals(TestHelpers.CLASS_DESCRIPTION, actual.get().get(0).getCourt().getClassDescription()); + Assertions.assertEquals(TestHelpers.COURT_CLASS, actual.get().get(0).getCourt().getCourtClass()); + Assertions.assertEquals(TestHelpers.DIVISION, actual.get().get(0).getCourt().getDivision()); + Assertions.assertEquals(TestHelpers.FILE_NUMBER, actual.get().get(0).getCourt().getFileNumber()); + Assertions.assertEquals(BigDecimal.ONE, actual.get().get(0).getCourt().getAgencyId()); + Assertions.assertEquals(TestHelpers.LOCATION, actual.get().get(0).getCourt().getLocation()); + Assertions.assertEquals(TestHelpers.LEVEL, actual.get().get(0).getCourt().getLevel()); + Assertions.assertEquals(TestHelpers.LEVEL_DESCRIPTION, actual.get().get(0).getCourt().getLevelDescription()); + Assertions.assertEquals(TestHelpers.LOCATION_DESCRIPTION, actual.get().get(0).getCourt().getLocationDescription()); + Assertions.assertEquals(TestHelpers.PARTICIPATING_CLASS, actual.get().get(0).getCourt().getParticipatingClass()); + //Party + Assertions.assertEquals(1, actual.get().get(0).getParties().size()); + Assertions.assertEquals(TestHelpers.PARTY_TYPE_DESC, actual.get().get(0).getParties().get(0).getPartyDescription()); + Assertions.assertEquals(ca.bc.gov.open.jag.efilingapi.api.model.Individual.RoleTypeEnum.ABC, actual.get().get(0).getParties().get(0).getRoleType()); + Assertions.assertEquals(TestHelpers.ROLE_TYPE_DESC, actual.get().get(0).getParties().get(0).getRoleDescription()); + Assertions.assertEquals(TestHelpers.FIRST_NAME, actual.get().get(0).getParties().get(0).getFirstName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, actual.get().get(0).getParties().get(0).getLastName()); + Assertions.assertEquals(TestHelpers.MIDDLE_NAME, actual.get().get(0).getParties().get(0).getMiddleName()); + //Document + Assertions.assertEquals(2, actual.get().get(0).getDocuments().size()); + Assertions.assertEquals("AAB", actual.get().get(0).getDocuments().get(0).getDocumentProperties().getType()); + Assertions.assertEquals(TestHelpers.DESCRIPTION, actual.get().get(0).getDocuments().get(0).getDescription()); + Assertions.assertEquals(TestHelpers.NAME, actual.get().get(0).getDocuments().get(0).getDocumentProperties().getName()); + Assertions.assertEquals(TestHelpers.STATUS, actual.get().get(0).getDocuments().get(0).getStatus().getDescription()); + Assertions.assertEquals(TestHelpers.STATUS_CODE, actual.get().get(0).getDocuments().get(0).getStatus().getCode()); + Assertions.assertNotNull(actual.get().get(0).getDocuments().get(0).getStatus().getChangeDate()); + Assertions.assertEquals(EXPECTED_ISO, actual.get().get(0).getDocuments().get(0).getStatus().getChangeDate()); + Assertions.assertEquals(EXPECTED_ISO, actual.get().get(0).getDocuments().get(0).getFilingDate()); + //Payments + Assertions.assertEquals(1, actual.get().get(0).getPayments().size()); + Assertions.assertEquals(false, actual.get().get(0).getPayments().get(0).getFeeExempt()); + Assertions.assertEquals(BigDecimal.ONE, actual.get().get(0).getPayments().get(0).getProcessedAmount()); + Assertions.assertEquals(BigDecimal.ONE, actual.get().get(0).getPayments().get(0).getProcessedAmount()); + Assertions.assertEquals(BigDecimal.ONE, actual.get().get(0).getPayments().get(0).getServiceIdentifier()); + Assertions.assertEquals(BigDecimal.ONE, actual.get().get(0).getPayments().get(0).getPaymentCategory()); + Assertions.assertEquals(TestHelpers.TRANSACTION_DESC, actual.get().get(0).getPayments().get(0).getPaymentDescription()); + Assertions.assertEquals(EXPECTED_ISO, actual.get().get(0).getPayments().get(0).getTransactionDate()); + + Assertions.assertEquals("http://localhost:8080/showmustgoon", actual.get().get(0).getLinks().getPackageHistoryUrl()); + + } + + @Test + @DisplayName("Not found: missing account") + public void withValidRequestButMissingAccountReturnEmpty() { + Optional> actual = sut.getFilingPackages(TestHelpers.CASE_2_STRING, PARENT_APPLICATION_NOT_FOUND); + + Assertions.assertFalse(actual.isPresent()); + + } + + @Test + @DisplayName("Not found: no filing packages") + public void withValidRequestButMissingPackageReturnEmpty() { + + Mockito.when(efilingReviewServiceMock.findStatusByClient(ArgumentMatchers.any())).thenReturn(new ArrayList<>()); + + Optional> actual = sut.getFilingPackages(TestHelpers.CASE_1_STRING, PARENT_APPLICATION_NOT_FOUND); + + Assertions.assertFalse(actual.isPresent()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetParentAppDetailsTestTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetParentAppDetailsTestTest.java new file mode 100644 index 0000000000..9ac51adaf3 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetParentAppDetailsTestTest.java @@ -0,0 +1,107 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.service.filingPackageServiceImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.ParentAppDetails; +import ca.bc.gov.open.jag.efilingapi.filingpackage.mapper.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.properties.ParentAppProperties; +import ca.bc.gov.open.jag.efilingapi.filingpackage.properties.ParentProperties; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageServiceImpl; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewFilingPackage; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.Optional; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilePackageServiceImplTest") +public class GetParentAppDetailsTestTest { + + private static final String RETURN_URL = "http://localhost:8080"; + FilingPackageServiceImpl sut; + + @Mock + EfilingReviewService efilingReviewServiceMock; + + @Mock + AccountService accountServiceMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_1_STRING))).thenReturn(TestHelpers.createAccount(BigDecimal.ONE)); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_2_STRING))).thenReturn(TestHelpers.createAccount(null)); + + ParentAppProperties parentAppProperties = new ParentAppProperties(); + parentAppProperties.setApplication(TestHelpers.APPLICATION_CODE); + parentAppProperties.setRejectedDocuments(true); + parentAppProperties.setReturnUrl(RETURN_URL); + + ParentProperties parentProperties = new ParentProperties(); + + parentProperties.setParents(Arrays.asList(parentAppProperties)); + + sut = new FilingPackageServiceImpl(efilingReviewServiceMock, null, accountServiceMock, new FilingPackageMapperImpl(), null, parentProperties); + } + + + @Test + @DisplayName("Ok: parent app details returned") + public void withValidRequestReturnDocument() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.of(TestHelpers.createFilingPackage(true))); + + Optional result = sut.getParentDetails(TestHelpers.CASE_1_STRING, BigDecimal.ONE); + + Assertions.assertTrue(result.isPresent()); + Assertions.assertEquals(RETURN_URL, result.get().getReturnUrl()); + Assertions.assertTrue(result.get().getRejectedDocumentFeature()); + + } + + @Test + @DisplayName("Not found: missing parent ") + public void withValidRequestButMissingParentReturnEmpty() { + + ReviewFilingPackage reviewFilingPackage = TestHelpers.createFilingPackage(true); + + reviewFilingPackage.setApplicationCode("MISSING"); + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.of(reviewFilingPackage)); + + Optional result = sut.getParentDetails(TestHelpers.CASE_1_STRING, BigDecimal.ONE); + Assertions.assertFalse(result.isPresent()); + + } + + @Test + @DisplayName("Not found: missing account") + public void withValidRequestButMissingAccountReturnEmpty() { + + Optional result = sut.getParentDetails(TestHelpers.CASE_2_STRING, BigDecimal.ONE); + Assertions.assertFalse(result.isPresent()); + + } + + @Test + @DisplayName("Not found: no filing package") + public void withValidRequestButMissingPackageReturnEmpty() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.empty()); + + Optional result = sut.getParentDetails(TestHelpers.CASE_1_STRING, BigDecimal.TEN); + + Assertions.assertFalse(result.isPresent()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetReportTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetReportTest.java new file mode 100644 index 0000000000..ddb11cd6f5 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetReportTest.java @@ -0,0 +1,73 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.service.filingPackageServiceImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.filingpackage.mapper.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageServiceImpl; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.ReportRequest; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.Resource; + +import java.math.BigDecimal; +import java.util.Optional; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilePackageServiceImplTest") +public class GetReportTest { + public static final byte[] BYTES = "TEST".getBytes(); + FilingPackageServiceImpl sut; + + @Mock + EfilingReviewService efilingReviewServiceMock; + + @Mock + AccountService accountServiceMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_1_STRING))).thenReturn(TestHelpers.createAccount(BigDecimal.ONE)); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_2_STRING))).thenReturn(TestHelpers.createAccount(null)); + + sut = new FilingPackageServiceImpl(efilingReviewServiceMock, null, accountServiceMock, new FilingPackageMapperImpl(), null, null); + } + + @Test + @DisplayName("Ok: a filing package was returned") + public void withValidRequestReturnFilingPackage() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.of(TestHelpers.createFilingPackage(true))); + + Mockito.when(efilingReviewServiceMock.getReport(ArgumentMatchers.any())).thenReturn(Optional.of(BYTES)); + + Optional result = sut.getReport(ReportRequest.builder() + .packageId(BigDecimal.ONE) + .universalId(TestHelpers.CASE_1_STRING).create()); + + Assertions.assertTrue(result.isPresent()); + Assertions.assertEquals(new ByteArrayResource(BYTES), result.get()); + + } + + @Test + @DisplayName("Not found: no filing package") + public void withValidRequestButMissingPackageReturnEmpty() { + + Mockito.when(efilingReviewServiceMock.getReport(ArgumentMatchers.any())).thenReturn(Optional.empty()); + + Optional result = sut.getReport(ReportRequest.builder().packageId(BigDecimal.ONE) + .universalId(TestHelpers.CASE_1_STRING).create()); + + Assertions.assertFalse(result.isPresent()); + + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetRushDocumentTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetRushDocumentTest.java new file mode 100644 index 0000000000..49405b197a --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetRushDocumentTest.java @@ -0,0 +1,113 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.service.filingPackageServiceImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.filingpackage.mapper.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.model.SubmittedDocument; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageServiceImpl; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.ByteArrayResource; + +import java.math.BigDecimal; +import java.util.Optional; +import java.util.UUID; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilePackageServiceImplTest") +public class GetRushDocumentTest { + + private static final byte[] DOC_DATA = "TEST".getBytes(); + private static final String DOCUMENT_NOT_FOUND = UUID.randomUUID().toString(); + + + FilingPackageServiceImpl sut; + + @Mock + EfilingReviewService efilingReviewServiceMock; + + @Mock + AccountService accountServiceMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_1_STRING))).thenReturn(TestHelpers.createAccount(BigDecimal.ONE)); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_2_STRING))).thenReturn(TestHelpers.createAccount(null)); + + sut = new FilingPackageServiceImpl(efilingReviewServiceMock, null, accountServiceMock, new FilingPackageMapperImpl(), null, null); + } + + + @Test + @DisplayName("Ok: a rush document was returned") + public void withValidRequestReturnDocument() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.of(TestHelpers.createFilingPackage(true))); + + Mockito.when(efilingReviewServiceMock.getRushDocument(ArgumentMatchers.any())).thenReturn(Optional.of(DOC_DATA)); + + Optional result = sut.getRushDocument(TestHelpers.CASE_1_STRING, BigDecimal.ONE, TestHelpers.CLIENT_FILE_NM); + + Assertions.assertTrue(result.isPresent()); + Assertions.assertEquals("Test.pdf", result.get().getName()); + Assertions.assertEquals(new ByteArrayResource(DOC_DATA), result.get().getData()); + + } + + @Test + @DisplayName("Not found: missing account") + public void withValidRequestButMissingAccountReturnEmpty() { + + Optional result = sut.getRushDocument(TestHelpers.CASE_2_STRING, BigDecimal.ONE, UUID.randomUUID().toString()); + Assertions.assertFalse(result.isPresent()); + + } + + + @Test + @DisplayName("Not found: no filing package") + public void withValidRequestButMissingPackageReturnEmpty() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.empty()); + + Optional result = sut.getRushDocument(TestHelpers.CASE_1_STRING, BigDecimal.TEN, UUID.randomUUID().toString()); + + Assertions.assertFalse(result.isPresent()); + + } + + @Test + @DisplayName("Not found: document not in filing package") + public void withValidRequestButMissingDocumentInPackageReturnEmpty() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.of(TestHelpers.createFilingPackage(true))); + + Optional result = sut.getRushDocument(TestHelpers.CASE_1_STRING, BigDecimal.ONE, UUID.randomUUID().toString()); + + Assertions.assertFalse(result.isPresent()); + + } + + @Test + @DisplayName("Not found: no document") + public void withValidRequestButMissingDocumentReturnEmpty() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.of(TestHelpers.createFilingPackage(true))); + + Mockito.when(efilingReviewServiceMock.getRushDocument(ArgumentMatchers.any())).thenReturn(Optional.empty()); + + Optional result = sut.getRushDocument(TestHelpers.CASE_1_STRING, BigDecimal.TEN, DOCUMENT_NOT_FOUND); + + Assertions.assertFalse(result.isPresent()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetSubmissionDocumentTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetSubmissionDocumentTest.java new file mode 100644 index 0000000000..096cc5a1ab --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/service/filingPackageServiceImpl/GetSubmissionDocumentTest.java @@ -0,0 +1,110 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.service.filingPackageServiceImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.filingpackage.mapper.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.filingpackage.model.SubmittedDocument; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageServiceImpl; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.ByteArrayResource; + +import java.math.BigDecimal; +import java.util.Optional; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("FilePackageServiceImplTest") +public class GetSubmissionDocumentTest { + + private static final byte[] DOC_DATA = "TEST".getBytes(); + private static final BigDecimal DOCUMENT_NOT_FOUND = new BigDecimal(50); + + FilingPackageServiceImpl sut; + + @Mock + EfilingReviewService efilingReviewServiceMock; + + @Mock + AccountService accountServiceMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_1_STRING))).thenReturn(TestHelpers.createAccount(BigDecimal.ONE)); + + Mockito.when(accountServiceMock.getCsoAccountDetails(ArgumentMatchers.eq(TestHelpers.CASE_2_STRING))).thenReturn(TestHelpers.createAccount(null)); + + sut = new FilingPackageServiceImpl(efilingReviewServiceMock, null, accountServiceMock, new FilingPackageMapperImpl(), null, null); + } + + + @Test + @DisplayName("Ok: a submitted document was returned") + public void withValidRequestReturnDocument() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.of(TestHelpers.createFilingPackage(true))); + + Mockito.when(efilingReviewServiceMock.getSubmittedDocument(Mockito.eq(TestHelpers.DOCUMENT_ID_TWO_BD))).thenReturn(Optional.of(DOC_DATA)); + + Optional result = sut.getSubmittedDocument(TestHelpers.CASE_1_STRING, BigDecimal.ONE, TestHelpers.DOCUMENT_ID_TWO_BD); + + Assertions.assertTrue(result.isPresent()); + Assertions.assertEquals(TestHelpers.NAME, result.get().getName()); + Assertions.assertEquals(new ByteArrayResource(DOC_DATA), result.get().getData()); + + } + + @Test + @DisplayName("Not found: missing account") + public void withValidRequestButMissingAccountReturnEmpty() { + + Optional result = sut.getSubmittedDocument(TestHelpers.CASE_2_STRING, BigDecimal.ONE, TestHelpers.DOCUMENT_ID_TWO_BD); + Assertions.assertFalse(result.isPresent()); + + } + + + @Test + @DisplayName("Not found: no filing package") + public void withValidRequestButMissingPackageReturnEmpty() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.empty()); + + Optional result = sut.getSubmittedDocument(TestHelpers.CASE_1_STRING, BigDecimal.TEN, TestHelpers.DOCUMENT_ID_TWO_BD); + + Assertions.assertFalse(result.isPresent()); + + } + + @Test + @DisplayName("Not found: document not in filing package") + public void withValidRequestButMissingDocumentInPackageReturnEmpty() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.of(TestHelpers.createFilingPackage(true))); + + Optional result = sut.getSubmittedDocument(TestHelpers.CASE_1_STRING, BigDecimal.ONE, DOCUMENT_NOT_FOUND); + + Assertions.assertFalse(result.isPresent()); + + } + + @Test + @DisplayName("Not found: no document") + public void withValidRequestButMissingDocumentReturnEmpty() { + + Mockito.when(efilingReviewServiceMock.findStatusByPackage(ArgumentMatchers.any())).thenReturn(Optional.of(TestHelpers.createFilingPackage(true))); + + Mockito.when(efilingReviewServiceMock.getSubmittedDocument(Mockito.eq(TestHelpers.DOCUMENT_ID_TWO_BD))).thenReturn(Optional.empty()); + + Optional result = sut.getSubmittedDocument(TestHelpers.CASE_1_STRING, BigDecimal.TEN, TestHelpers.DOCUMENT_ID_TWO_BD); + + Assertions.assertFalse(result.isPresent()); + + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/util/GetRushTypeTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/util/GetRushTypeTest.java new file mode 100644 index 0000000000..57a47aae69 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/filingpackage/util/GetRushTypeTest.java @@ -0,0 +1,63 @@ +package ca.bc.gov.open.jag.efilingapi.filingpackage.util; + +import ca.bc.gov.open.jag.efilingapi.api.model.Rush; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("GetRushTypeTest") +public class GetRushTypeTest { + + @Test + @DisplayName("CRTD maps to Court") + public void testMappingCourt() { + + Assertions.assertEquals(Rush.RushTypeEnum.COURT, RushMappingUtils.getRushType("CRTD")); + + } + + @Test + @DisplayName("CRTR maps to Rule") + public void testMappingRule() { + + Assertions.assertEquals(Rush.RushTypeEnum.RULE, RushMappingUtils.getRushType("CRTR")); + + } + + @Test + @DisplayName("OTHR maps to Other") + public void testMappingOther() { + + Assertions.assertEquals(Rush.RushTypeEnum.OTHER, RushMappingUtils.getRushType("OTHR")); + + } + + @Test + @DisplayName("PRO maps to PRO") + public void testMappingPro() { + + Assertions.assertEquals(Rush.RushTypeEnum.PRO, RushMappingUtils.getRushType("PRO")); + + } + + + @Test + @DisplayName("Unknown maps to null") + public void testMappingUnknown() { + + Assertions.assertNull(RushMappingUtils.getRushType("UNKOWN")); + + } + + + @Test + @DisplayName("null maps to null") + public void testMappingNull() { + + Assertions.assertNull(RushMappingUtils.getRushType(null)); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/lookup/GetCountriesTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/lookup/GetCountriesTest.java new file mode 100644 index 0000000000..6cc33f68fc --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/lookup/GetCountriesTest.java @@ -0,0 +1,64 @@ +package ca.bc.gov.open.jag.efilingapi.lookup; + +import ca.bc.gov.open.jag.efilingapi.api.model.CountryCode; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.LookupItem; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.util.Arrays; +import java.util.List; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class GetCountriesTest { + + private static final String TEST = "TEST"; + private static final String TEST_1 = "TEST_1"; + private static final String TEST_2 = "TEST_2"; + + CountriesApiDelegateImpl sut; + + @Mock + EfilingLookupService efilingLookupServiceMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(efilingLookupServiceMock.getCountries()).thenReturn(createLookupList()); + + sut = new CountriesApiDelegateImpl(efilingLookupServiceMock); + + } + + @Test + @DisplayName("200: File is returned") + public void withValidRequestReturnFilingPackage() { + + ResponseEntity> result = sut.getCountries(); + + Assertions.assertEquals(HttpStatus.OK, result.getStatusCode()); + Assertions.assertEquals(2, result.getBody().size()); + + Assertions.assertEquals(TEST_1, result.getBody().get(0).getCode()); + Assertions.assertEquals(TEST, result.getBody().get(0).getDescription()); + + Assertions.assertEquals(TEST_2, result.getBody().get(1).getCode()); + Assertions.assertEquals(TEST, result.getBody().get(1).getDescription()); + + } + + private List createLookupList() { + + return Arrays.asList( + LookupItem.builder().code(TEST_1).description(TEST).create(), + LookupItem.builder().code(TEST_2).description(TEST).create()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/payment/PaymentApiDelegateImplTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/payment/PaymentApiDelegateImplTest.java new file mode 100644 index 0000000000..a21e8dabc0 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/payment/PaymentApiDelegateImplTest.java @@ -0,0 +1,74 @@ +package ca.bc.gov.open.jag.efilingapi.payment; + +import ca.bc.gov.open.bambora.payment.starter.BamboraException; +import ca.bc.gov.open.bambora.payment.starter.managment.BamboraCardService; +import ca.bc.gov.open.jag.efilingapi.api.model.GenerateCardUrlRequest; +import ca.bc.gov.open.jag.efilingapi.api.model.GenerateCardUrlResponse; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingapi.error.UrlGenerationException; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.UUID; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("PaymentApiDelegateImpl") +public class PaymentApiDelegateImplTest { + + private static final String REDIRECT_URL = "SOMEURL"; + private static final String REDIRECTED_URL = "http://www.google.com/bambora"; + private static final String INTERNAL_CLIENT_NUMBER = "123"; + private static final String FAIL_INTERNAL_CLIENT_NUMBER = "1234"; + private PaymentApiDelegateImpl sut; + + @Mock + BamboraCardService bamboraCardServiceMock; + + @Mock + EfilingAccountService efilingAccountServiceMock; + + @BeforeAll + public void setUp() throws MalformedURLException, URISyntaxException { + MockitoAnnotations.openMocks(this); + + Mockito.doReturn(new URI(REDIRECTED_URL)).when(bamboraCardServiceMock).setupRecurringPayment( + ArgumentMatchers.argThat(request -> request.getEndUserId().equals(INTERNAL_CLIENT_NUMBER))); + + Mockito.doThrow(BamboraException.class).when(bamboraCardServiceMock).setupRecurringPayment( + ArgumentMatchers.argThat(request -> request.getEndUserId().equals(FAIL_INTERNAL_CLIENT_NUMBER))); + + sut = new PaymentApiDelegateImpl(bamboraCardServiceMock, efilingAccountServiceMock); + } + + @Test + @DisplayName("200: ok url was generated") + public void withCorrectVariableReturnGeneratedUrl() { + GenerateCardUrlRequest request = new GenerateCardUrlRequest(); + request.setInternalClientNumber(INTERNAL_CLIENT_NUMBER); + request.setRedirectUrl(REDIRECT_URL); + ResponseEntity actual = sut.updateCreditCard(UUID.randomUUID(),request); + + Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); + Assertions.assertEquals(REDIRECTED_URL, actual.getBody().getBamboraUrl()); + } + + @Test + @DisplayName("500: bambora exception caught should throw UrlGenerationException") + public void withBamboraExceptionCaughtShouldThrowUrlGenerationException() { + GenerateCardUrlRequest request = new GenerateCardUrlRequest(); + request.setInternalClientNumber(FAIL_INTERNAL_CLIENT_NUMBER); + request.setRedirectUrl(REDIRECT_URL); + + UrlGenerationException exception = Assertions.assertThrows(UrlGenerationException.class, () -> sut.updateCreditCard(UUID.randomUUID(),request)); + Assertions.assertEquals(ErrorCode.URL_GENERATION_FAILURE.toString(), exception.getErrorCode()); + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/ConfigTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/ConfigTest.java deleted file mode 100644 index 5da41ded72..0000000000 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/ConfigTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package ca.bc.gov.open.jag.efilingapi.submission; - -import ca.bc.gov.open.jag.efilingapi.submission.mappers.SubmissionMapper; -import ca.bc.gov.open.jag.efilingapi.submission.mappers.SubmissionMapperImpl; -import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; -import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionServiceImpl; -import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; -import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStoreImpl; -import org.junit.jupiter.api.*; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.springframework.cache.CacheManager; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -public class ConfigTest { - - private SubmissionConfig sut; - - @Mock - CacheManager cacheManagerMock; - - @BeforeAll - public void setUp() { - - MockitoAnnotations.initMocks(this); - - sut = new SubmissionConfig(null); - } - - @Test - @DisplayName("get SubmissionStoreImpl test") - public void testGetSubmissionStore() { - - SubmissionStore actual = sut.submissionStore(); - Assertions.assertEquals(SubmissionStoreImpl.class, actual.getClass()); - - } - - @Test - @DisplayName("get SubmissionServiceImpl test") - public void testGetSubmissionService() { - - SubmissionService actual = sut.submissionService(null, null, null, null); - Assertions.assertEquals(SubmissionServiceImpl.class, actual.getClass()); - - } - - @Test - @DisplayName("get SubmissionMapperImpl test") - public void testGetSubmissionMapper() { - - SubmissionMapper actual = sut.submissionMapper(); - Assertions.assertEquals(SubmissionMapperImpl.class, actual.getClass()); - - } - - -} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/SubmissionConfigTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/SubmissionConfigTest.java new file mode 100644 index 0000000000..6044e29715 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/SubmissionConfigTest.java @@ -0,0 +1,250 @@ +package ca.bc.gov.open.jag.efilingapi.submission; + +import ca.bc.gov.open.jag.efilingapi.api.model.ActionRequiredDetails; +import ca.bc.gov.open.jag.efilingapi.api.model.ParentAppDetails; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.fakes.CourtServiceFake; +import ca.bc.gov.open.jag.efilingapi.fakes.DocumentServiceFake; +import ca.bc.gov.open.jag.efilingapi.fakes.EfilingCourtServiceFake; +import ca.bc.gov.open.jag.efilingapi.filingpackage.model.SubmittedDocument; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.SubmissionMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.SubmissionMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionServiceImpl; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStoreImpl; +import ca.bc.gov.open.jag.efilingcommons.model.*; +import ca.bc.gov.open.jag.efilingcommons.payment.PaymentAdapter; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingPaymentService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSubmissionService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; +import ca.bc.gov.open.jag.efilingcommons.submission.models.LookupItem; +import ca.bc.gov.open.jag.efilingcommons.submission.models.ReportRequest; +import ca.bc.gov.open.sftp.starter.SftpService; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.boot.autoconfigure.cache.CacheProperties; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.core.io.Resource; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.math.BigDecimal; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class SubmissionConfigTest { + + + ApplicationContextRunner context = new ApplicationContextRunner() + .withUserConfiguration( + SubmissionConfig.class, + CacheProperties.class) + .withBean(PaymentAdapterTest.class) + .withBean(SftpServiceTestImpl.class) + .withBean(EfilingLookupServiceTest.class) + .withBean(EfilingCourtServiceFake.class) + .withBean(EfilingDocumentServiceTest.class) + .withBean(EfilingSubmissionServiceTest.class) + .withBean(DocumentStoreTest.class) + .withBean(CourtServiceFake.class) + .withBean(NavigationProperties.class) + .withBean(DocumentServiceFake.class) + .withBean(FilingPackageServiceTest.class); + + @Test + @DisplayName("Test Submission Beans") + public void testSubmissionBeans() { + + context.run(it -> { + assertThat(it).hasSingleBean(SubmissionStore.class); + Assertions.assertEquals(SubmissionStoreImpl.class, it.getBean(SubmissionStore.class).getClass()); + + assertThat(it).hasSingleBean(SubmissionMapper.class); + Assertions.assertEquals(SubmissionMapperImpl.class, it.getBean(SubmissionMapper.class).getClass()); + + assertThat(it).hasSingleBean(FilingPackageMapper.class); + Assertions.assertEquals(FilingPackageMapperImpl.class, it.getBean(FilingPackageMapper.class).getClass()); + + assertThat(it).hasSingleBean(SubmissionService.class); + Assertions.assertEquals(SubmissionServiceImpl.class, it.getBean(SubmissionService.class).getClass()); + + + }); + + } + + + + public static class SftpServiceTestImpl implements SftpService { + + @Override + public ByteArrayInputStream getContent(String s) { + return null; + } + + @Override + public void moveFile(String s, String s1) { + } + + @Override + public void put(InputStream inputStream, String s) { + } + + @Override + public List listFiles(String s) { + return null; + } + } + + + public static class EfilingLookupServiceTest implements EfilingLookupService { + + @Override + public ServiceFees getServiceFee(SubmissionFeeRequest submissionFeeRequest) { + return null; + } + + @Override + public List getValidPartyRoles(String courtLevel, String courtClass, String documentTypes) { + return null; + } + + @Override + public List getCountries() { + return null; + } + } + + public static class EfilingSubmissionServiceTest implements EfilingSubmissionService { + + @Override + public SubmitPackageResponse submitFilingPackage(AccountDetails accountDetails, FilingPackage efilingPackage, EfilingPaymentService payment) { + return null; + } + } + + public static class EfilingDocumentServiceTest implements EfilingDocumentService { + + @Override + public DocumentTypeDetails getDocumentTypeDetails(String courtLevel, String courtClass, String documentType) { + return null; + } + + @Override + public List getDocumentTypes(String courtLevel, String courtClass) { + return null; + } + } + + public static class DocumentStoreTest implements DocumentStore { + + + @Override + public byte[] put(SubmissionKey submissionKey, String fileName, byte[] content) { + return new byte[0]; + } + + @Override + public byte[] get(SubmissionKey submissionKey, String fileName) { + return new byte[0]; + } + + @Override + public void evict(SubmissionKey submissionKey, String fileName) { + + } + + @Override + public DocumentTypeDetails getDocumentDetails(String courtLevel, String courtClass, String documentType) { + return null; + } + + @Override + public List getDocumentTypes(String courtLevel, String courtClass) { + return null; + } + + @Override + public byte[] putRushDocument(SubmissionKey submissionKey, String fileName, byte[] content) { + return new byte[0]; + } + + @Override + public byte[] getRushDocument(SubmissionKey submissionKey, String fileName) { + return new byte[0]; + } + + @Override + public void evictRushDocument(SubmissionKey submissionKey, String fileName) { + + } + + + } + + public static class PaymentAdapterTest implements PaymentAdapter { + + @Override + public PaymentTransaction makePayment(EfilingPayment efilingPayment) { + return null; + } + + } + + public static class FilingPackageServiceTest implements FilingPackageService { + + @Override + public Optional getCSOFilingPackage(String universalId, BigDecimal packageNumber) { + return Optional.empty(); + } + + @Override + public Optional> getFilingPackages(String universalId, String parentApplication) { + return Optional.empty(); + } + + @Override + public Optional getReport(ReportRequest reportRequest) { + return Optional.empty(); + } + + @Override + public Optional getSubmittedDocument(String universalId, BigDecimal packageNumber, BigDecimal documentIdentifier) { + return Optional.empty(); + } + + @Override + public void deleteSubmittedDocument(String universalId, BigDecimal packageNumber, String documentIdentifier) { + + } + + @Override + public Optional getActionRequiredDetails(String universalId, BigDecimal packageNumber) { + return Optional.empty(); + } + + @Override + public Optional getRushDocument(String universalId, BigDecimal packageNumber, String documentIdentifier) { + return Optional.empty(); + } + + @Override + public Optional getParentDetails(String universalId, BigDecimal packageNumber) { + return Optional.empty(); + } + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/models/FilingPakageTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/models/FilingPakageTest.java new file mode 100644 index 0000000000..e146d7d412 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/models/FilingPakageTest.java @@ -0,0 +1,167 @@ +package ca.bc.gov.open.jag.efilingapi.submission.models; + +import ca.bc.gov.open.jag.efilingcommons.model.*; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class FilingPakageTest { + + + public static final BigDecimal AGENCY_ID = BigDecimal.ONE; + public static final String LOCATION = "location"; + public static final String LOCATION_DESCRIPTION = "locationDescription"; + public static final String LEVEL = "level"; + public static final String LEVEL_DESCRIPTION = "levelDescription"; + public static final String COURT_CLASS = "courtClass"; + public static final String CLASS_DESCRIPTION = "classDescription"; + public static final String DIVISION = "division"; + public static final String FILE_NUMBER = "fileNumber"; + public static final String PARTICIPATING_CLASS = "participatingClass"; + public static final String NAME = "name"; + public static final String TYPE = "type"; + public static final String SUB_TYPE = "subType"; + public static final String DESCRIPTION = "description"; + public static final BigDecimal STATUTORY_FEE_AMOUNT = BigDecimal.TEN; + public static final String MIME_TYPE = "mimeType"; + public static final String ROLE_TYPE_CD = "roleTypeCd"; + public static final String PARTY_TYPE_DESC = "partyTypeDesc"; + public static final String ROLE_TYPE_DESC = "roleTypeDesc"; + public static final String FIRST_NAME = "firstName"; + public static final String MIDDLE_NAME = "middleName"; + public static final String LAST_NAME = "lastName"; + public static final String NAME_TYPE_CD = "nameTypeCd"; + public static final BigDecimal SUBMISSION_FEE_AMOUNT = BigDecimal.TEN; + public static final String SERVER_FILE_NAME = "SERVER.txt"; + + @Test + public void testConstructor() { + + + FilingPackage actual = new FilingPackage( + BigDecimal.TEN, + SUBMISSION_FEE_AMOUNT, + getCourt(), + getDocuments(), + getParties(), + getOrganization(), + null, + true, + true, + "TEST"); + + Assertions.assertEquals(STATUTORY_FEE_AMOUNT, actual.getSubmissionFeeAmount()); + assertCourt(actual); + assertDocuments(actual); + assertParties(actual); + assertOrganizations(actual); + } + + private void assertParties(FilingPackage actual) { + Assertions.assertEquals(ROLE_TYPE_CD, actual.getParties().get(0).getRoleTypeCd()); + Assertions.assertEquals(FIRST_NAME, actual.getParties().get(0).getFirstName()); + Assertions.assertEquals(MIDDLE_NAME, actual.getParties().get(0).getMiddleName()); + Assertions.assertEquals(LAST_NAME, actual.getParties().get(0).getLastName()); + Assertions.assertEquals(NAME_TYPE_CD, actual.getParties().get(0).getNameTypeCd()); + } + + private void assertOrganizations(FilingPackage actual) { + Assertions.assertEquals(ROLE_TYPE_CD, actual.getOrganizations().get(0).getRoleTypeCd()); + Assertions.assertEquals(NAME, actual.getOrganizations().get(0).getName()); + Assertions.assertEquals(NAME_TYPE_CD, actual.getOrganizations().get(0).getNameTypeCd()); + } + + private void assertDocuments(FilingPackage actual) { + Assertions.assertEquals(NAME, actual.getDocuments().get(0).getName()); + Assertions.assertEquals(TYPE, actual.getDocuments().get(0).getType()); + Assertions.assertEquals(SUB_TYPE, actual.getDocuments().get(0).getSubType()); + Assertions.assertEquals(true, actual.getDocuments().get(0).getIsAmendment()); + Assertions.assertEquals(false, actual.getDocuments().get(0).getIsSupremeCourtScheduling()); + Assertions.assertEquals("test", actual.getDocuments().get(0).getData()); + Assertions.assertEquals(DESCRIPTION, actual.getDocuments().get(0).getDescription()); + Assertions.assertEquals(STATUTORY_FEE_AMOUNT, actual.getDocuments().get(0).getStatutoryFeeAmount()); + Assertions.assertEquals(MIME_TYPE, actual.getDocuments().get(0).getMimeType()); + } + + private void assertCourt(FilingPackage actual) { + Assertions.assertEquals(AGENCY_ID, actual.getCourt().getAgencyId()); + Assertions.assertEquals(LOCATION, actual.getCourt().getLocation()); + Assertions.assertEquals(LOCATION_DESCRIPTION, actual.getCourt().getLocationDescription()); + Assertions.assertEquals(LEVEL, actual.getCourt().getLevel()); + Assertions.assertEquals(LEVEL_DESCRIPTION, actual.getCourt().getLevelDescription()); + Assertions.assertEquals(COURT_CLASS, actual.getCourt().getCourtClass()); + Assertions.assertEquals(CLASS_DESCRIPTION, actual.getCourt().getClassDescription()); + Assertions.assertEquals(DIVISION, actual.getCourt().getDivision()); + Assertions.assertEquals(FILE_NUMBER, actual.getCourt().getFileNumber()); + Assertions.assertEquals(PARTICIPATING_CLASS, actual.getCourt().getParticipatingClass()); + } + + private List getParties() { + List parties = new ArrayList<>(); + Individual individual = new Individual( + PARTY_TYPE_DESC, + ROLE_TYPE_CD, + ROLE_TYPE_DESC, + FIRST_NAME, + MIDDLE_NAME, + LAST_NAME, + NAME_TYPE_CD); + parties.add(individual); + return parties; + } + + private List getOrganization() { + List organizations = new ArrayList<>(); + Organization organization = new Organization( + PARTY_TYPE_DESC, + ROLE_TYPE_CD, + ROLE_TYPE_DESC, + NAME, + NAME_TYPE_CD); + organizations.add(organization); + return organizations; + } + + private List getDocuments() { + List documents = new ArrayList<>(); + Document document = new Document( + NAME, + TYPE, + SUB_TYPE, + true, + false, + "test", + DESCRIPTION, + STATUTORY_FEE_AMOUNT, + MIME_TYPE, + UUID.randomUUID().toString(), + SERVER_FILE_NAME, + ActionDocument.builder() + .documentId(BigDecimal.TEN) + .status("REJ") + .type("TEST") + .create()); + documents.add(document); + return documents; + } + + private Court getCourt() { + return new Court(AGENCY_ID, + LOCATION, + LOCATION_DESCRIPTION, + LEVEL, + LEVEL_DESCRIPTION, + COURT_CLASS, + CLASS_DESCRIPTION, + DIVISION, + FILE_NUMBER, + PARTICIPATING_CLASS); + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/models/SubmissionTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/models/SubmissionTest.java index d34745ac30..32c94b0bdd 100644 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/models/SubmissionTest.java +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/models/SubmissionTest.java @@ -1,15 +1,11 @@ package ca.bc.gov.open.jag.efilingapi.submission.models; -import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; import ca.bc.gov.open.jag.efilingapi.TestHelpers; -import ca.bc.gov.open.jag.efilingapi.api.model.EndpointAccess; -import ca.bc.gov.open.jag.efilingapi.fee.models.Fee; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; -import java.math.BigDecimal; import java.util.UUID; @TestInstance(TestInstance.Lifecycle.PER_CLASS) @@ -20,34 +16,39 @@ public class SubmissionTest { private static final String CASE_1 = "CASE1"; private static final String CANCEL = "CANCEL"; private static final String ERROR = "ERROR"; - private static final String TYPE = "TYPE"; - private static final String SUBTYPE = "SUBTYPE"; - private static final String URL = "http://doc.com"; - private static final String HEADER = "HEADER"; + private static final String CLIENT_APP_NAME = "appName"; @Test @DisplayName("CASE 1: testing constructor") public void testingConstructor() { - Fee fee = new Fee(BigDecimal.TEN); - AccountDetails accountDetails = new AccountDetails(BigDecimal.TEN, BigDecimal.TEN, true, "firstName", "lastName", "middleName", "email"); Submission actual = new Submission( UUID.randomUUID(), - TestHelpers.createDocumentProperties(HEADER, URL, SUBTYPE, TYPE), + UUID.randomUUID(), + UUID.randomUUID().toString(), + CLIENT_APP_NAME, + TestHelpers.createPackage(TestHelpers.createCourt(), TestHelpers.createDocumentList(), TestHelpers.createPartyList(), TestHelpers.createOrganizationList()), TestHelpers.createNavigation(CASE_1, CANCEL, ERROR), - fee, - accountDetails, 1); - Assertions.assertEquals(TYPE, actual.getDocumentProperties().getType()); - Assertions.assertEquals(SUBTYPE, actual.getDocumentProperties().getSubType()); - Assertions.assertEquals(URL, actual.getDocumentProperties().getSubmissionAccess().getUrl()); - Assertions.assertEquals(EndpointAccess.VerbEnum.POST, actual.getDocumentProperties().getSubmissionAccess().getVerb()); - Assertions.assertEquals(ERROR, actual.getNavigation().getError().getUrl()); - Assertions.assertEquals(CANCEL, actual.getNavigation().getCancel().getUrl()); - Assertions.assertEquals(CASE_1, actual.getNavigation().getSuccess().getUrl()); - Assertions.assertEquals(BigDecimal.TEN, actual.getFee().getAmount()); + Assertions.assertEquals(CLIENT_APP_NAME, actual.getClientAppName()); + Assertions.assertEquals(ERROR, actual.getNavigationUrls().getError()); + Assertions.assertEquals(CANCEL, actual.getNavigationUrls().getCancel()); + Assertions.assertEquals(CASE_1, actual.getNavigationUrls().getSuccess()); + Assertions.assertEquals(TestHelpers.DIVISION, actual.getFilingPackage().getCourt().getDivision()); + Assertions.assertEquals(TestHelpers.FILENUMBER, actual.getFilingPackage().getCourt().getFileNumber()); + Assertions.assertEquals(TestHelpers.LEVEL, actual.getFilingPackage().getCourt().getLevel()); + Assertions.assertEquals(TestHelpers.LOCATION, actual.getFilingPackage().getCourt().getLocation()); + Assertions.assertEquals(TestHelpers.PARTICIPATIONCLASS, actual.getFilingPackage().getCourt().getParticipatingClass()); + Assertions.assertEquals(TestHelpers.PROPERTYCLASS, actual.getFilingPackage().getCourt().getCourtClass()); + Assertions.assertEquals(TestHelpers.COURT_DESCRIPTION, actual.getFilingPackage().getCourt().getLocationDescription()); + Assertions.assertEquals(TestHelpers.CLASS_DESCRIPTION, actual.getFilingPackage().getCourt().getClassDescription()); + Assertions.assertEquals(TestHelpers.LEVEL_DESCRIPTION, actual.getFilingPackage().getCourt().getLevelDescription()); + Assertions.assertEquals(TestHelpers.TYPE, actual.getFilingPackage().getDocuments().get(0).getType()); + Assertions.assertEquals(TestHelpers.DESCRIPTION, actual.getFilingPackage().getDocuments().get(0).getDescription()); + Assertions.assertEquals(true, actual.getFilingPackage().getDocuments().get(0).getIsAmendment()); + Assertions.assertEquals(true, actual.getFilingPackage().getDocuments().get(0).getIsSupremeCourtScheduling()); } } diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/GetValidIndividualRoleRequestTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/GetValidIndividualRoleRequestTest.java new file mode 100644 index 0000000000..5a736040d4 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/GetValidIndividualRoleRequestTest.java @@ -0,0 +1,48 @@ +package ca.bc.gov.open.jag.efilingapi.submission.service; + +import ca.bc.gov.open.jag.efilingapi.api.model.InitialDocument; +import ca.bc.gov.open.jag.efilingapi.submission.models.GetValidPartyRoleRequest; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +import java.util.ArrayList; +import java.util.List; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class GetValidIndividualRoleRequestTest { + + public static final String COURT_CLASSIFICATION = "A"; + public static final String COURT_LEVEL = "B"; + + @Test + @DisplayName("ok: returns a comma separated list of document types") + public void shouldReturnAValidListOfDocumentTypes() { + + List initialDocumentList = new ArrayList<>(); + InitialDocument document1 = new InitialDocument(); + document1.setType("AAB"); + initialDocumentList.add(document1); + InitialDocument document2 = new InitialDocument(); + document2.setType("ACMW"); + initialDocumentList.add(document2); + InitialDocument document3 = new InitialDocument(); + document3.setType("TAX"); + initialDocumentList.add(document3); + + GetValidPartyRoleRequest actual = GetValidPartyRoleRequest.builder() + .courtClassification(COURT_CLASSIFICATION) + .courtLevel(COURT_LEVEL) + .documents(initialDocumentList).create(); + + Assertions.assertEquals(COURT_CLASSIFICATION, actual.getCourtClassification()); + Assertions.assertEquals(COURT_LEVEL, actual.getCourtLevel()); + Assertions.assertEquals(3, actual.getInitialDocuments().size()); + Assertions.assertEquals("AAB,ACMW,TAX", actual.getDocumentTypesAsString()); + + + } + + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/CreateSubmissionTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/CreateSubmissionTest.java new file mode 100644 index 0000000000..2c7fc04ab1 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/CreateSubmissionTest.java @@ -0,0 +1,177 @@ +package ca.bc.gov.open.jag.efilingapi.submission.service.submissionServiceImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.api.model.SubmitResponse; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.PartyMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionServiceImpl; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingcommons.model.*; +import ca.bc.gov.open.jag.efilingcommons.payment.PaymentAdapter; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingCourtService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSubmissionService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; +import ca.bc.gov.open.sftp.starter.SftpService; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.autoconfigure.cache.CacheProperties; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class CreateSubmissionTest { + + public static final String INTERNAL_CLIENT_NUMBER = "12345"; + public static final String CLIENT_APP_NAME = "clientAppName"; + private static final String FILE_PDF = "file.pdf"; + private static final String FILE_1_PDF = "file1.pdf"; + private SubmissionServiceImpl sut; + + @Mock + private SubmissionStore submissionStoreMock; + + @Mock + private CacheProperties cachePropertiesMock; + + @Mock + private EfilingLookupService efilingLookupService; + + @Mock + private EfilingCourtService efilingCourtService; + + @Mock + private DocumentStore documentStoreMock; + + @Mock + private EfilingSubmissionService efilingSubmissionServiceMock; + + @Mock + private PaymentAdapter paymentAdapterMock; + + @Mock + private SftpService sftpServiceMock; + + @BeforeAll + public void setUp(){ + MockitoAnnotations.initMocks(this); + Mockito.when(efilingSubmissionServiceMock.submitFilingPackage(any(), any(), any())).thenReturn(SubmitPackageResponse.builder().transactionId(BigDecimal.valueOf(11000)).packageLink("http://link").create()); + Mockito.when(paymentAdapterMock.makePayment(any())).thenReturn(new PaymentTransaction()); + Mockito.when(documentStoreMock.get(any(), any())).thenReturn(new byte[]{}); + Mockito.when(documentStoreMock.getRushDocument(any(), any())).thenReturn(new byte[]{}); + Mockito.doNothing().when(sftpServiceMock).put(any(), any()); + NavigationProperties navigationProperties = new NavigationProperties(); + sut = new SubmissionServiceImpl(submissionStoreMock, cachePropertiesMock, null, new PartyMapperImpl(), efilingLookupService, efilingCourtService, efilingSubmissionServiceMock, null, documentStoreMock, paymentAdapterMock, sftpServiceMock, navigationProperties); + + } + + + @Test + @DisplayName("OK: service is created without early adopter") + public void withValidSubmissionServiceIsCreatedNotEarlyAdopter() { + + SubmitResponse actual = sut.createSubmission(Submission + .builder() + .id(TestHelpers.CASE_1) + .universalId(UUID.randomUUID().toString()) + .transactionId(TestHelpers.CASE_1) + .navigationUrls(TestHelpers.createDefaultNavigation()) + .expiryDate(10) + .clientAppName(CLIENT_APP_NAME) + .filingPackage(TestHelpers.createPackage(TestHelpers.createCourt(), TestHelpers.createDocumentList(), TestHelpers.createPartyList(), TestHelpers.createOrganizationList())) + .create(), + AccountDetails.builder() + .fileRolePresent(true) + .accountId(BigDecimal.ONE) + .cardRegistered(true) + .universalId(UUID.randomUUID().toString()) + .clientId(BigDecimal.TEN) + .internalClientNumber(INTERNAL_CLIENT_NUMBER) + .create(), false); + assertEquals("aHR0cDovL2xpbms=", actual.getPackageRef()); + } + + @Test + @DisplayName("OK: service is created with early adopter") + public void withValidSubmissionServiceIsCreatedEarlyAdopter() { + + SubmitResponse actual = sut.createSubmission(Submission + .builder() + .id(TestHelpers.CASE_1) + .transactionId(TestHelpers.CASE_1) + .universalId(UUID.randomUUID().toString()) + .navigationUrls(TestHelpers.createDefaultNavigation()) + .expiryDate(10) + .clientAppName(CLIENT_APP_NAME) + .filingPackage(TestHelpers.createPackage(TestHelpers.createCourt(), TestHelpers.createDocumentList(), TestHelpers.createPartyList(), TestHelpers.createOrganizationList())) + .create(), + AccountDetails.builder() + .fileRolePresent(true) + .accountId(BigDecimal.ONE) + .cardRegistered(true) + .universalId(UUID.randomUUID().toString()) + .clientId(BigDecimal.TEN) + .internalClientNumber(INTERNAL_CLIENT_NUMBER) + .create(), true); + assertEquals("bnVsbC9wYWNrYWdlcmV2aWV3LzExMDAwP3BhY2thZ2VObz0xMTAwMA==", actual.getPackageRef()); + } + + @Test + @DisplayName("OK: service is created with rush") + public void withValidSubmissionServiceIsCreatedRush() { + + FilingPackage filingPackage = TestHelpers.createPackage(TestHelpers.createCourt(), TestHelpers.createDocumentList(), TestHelpers.createPartyList(), TestHelpers.createOrganizationList()); + filingPackage.setRush(createRush()); + + SubmitResponse actual = sut.createSubmission(Submission + .builder() + .id(TestHelpers.CASE_1) + .transactionId(TestHelpers.CASE_1) + .universalId(UUID.randomUUID().toString()) + .navigationUrls(TestHelpers.createDefaultNavigation()) + .expiryDate(10) + .clientAppName(CLIENT_APP_NAME) + .filingPackage(filingPackage) + .create(), + AccountDetails.builder() + .fileRolePresent(true) + .accountId(BigDecimal.ONE) + .cardRegistered(true) + .universalId(UUID.randomUUID().toString()) + .clientId(BigDecimal.TEN) + .internalClientNumber(INTERNAL_CLIENT_NUMBER) + .create(), true); + assertEquals("bnVsbC9wYWNrYWdlcmV2aWV3LzExMDAwP3BhY2thZ2VObz0xMTAwMA==", actual.getPackageRef()); + } + + private RushProcessing createRush() { + return RushProcessing.builder() + .courtDate("2001-11-26T12:00:00Z") + .supportingDocuments( + Arrays.asList( + Document.builder() + .serverFileName(FILE_PDF) + .name(FILE_PDF) + .create(), + Document.builder() + .serverFileName(FILE_1_PDF) + .name(FILE_1_PDF) + .create() + ) + ) + .create(); + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/GenerateFromRequestTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/GenerateFromRequestTest.java new file mode 100644 index 0000000000..a241cd8f71 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/GenerateFromRequestTest.java @@ -0,0 +1,488 @@ +package ca.bc.gov.open.jag.efilingapi.submission.service.submissionServiceImpl; + + +import ca.bc.gov.open.jag.efilingapi.Keys; +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.api.model.*; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionKey; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.PartyMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.SubmissionMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.SubmissionMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingapi.submission.models.SubmissionConstants; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionServiceImpl; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingCourtServiceException; +import ca.bc.gov.open.jag.efilingcommons.exceptions.StoreException; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.CourtDetails; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import ca.bc.gov.open.jag.efilingcommons.model.ServiceFees; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingCourtService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSubmissionService; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.autoconfigure.cache.CacheProperties; + +import javax.xml.datatype.DatatypeConfigurationException; +import java.math.BigDecimal; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class GenerateFromRequestTest { + + public static final String CLIENT_APP_NAME = "clientAppName"; + public static final String APP_CODE = "CODE"; + private static final BigDecimal PACKAGE_IDENTIFIER = BigDecimal.TEN; + private static final BigDecimal DOCUMENT_ID = BigDecimal.TEN; + private static final String DOCUMENT_COURTESY_CORRECTED = "CCOR"; + + private SubmissionServiceImpl sut; + + @Mock + private SubmissionStore submissionStoreMock; + + @Mock + private CacheProperties cachePropertiesMock; + + @Mock + private EfilingLookupService efilingLookupService; + + @Mock + private EfilingCourtService efilingCourtService; + + @Mock + private EfilingDocumentService efilingDocumentService; + + @Mock + private DocumentStore documentStoreMock; + + @Mock + private EfilingSubmissionService efilingSubmissionServiceMock; + + @BeforeAll + public void beforeAll() throws DatatypeConfigurationException { + + MockitoAnnotations.openMocks(this); + + ServiceFees fee = new ServiceFees( BigDecimal.valueOf(7.00), "DCFL"); + Mockito.doReturn(fee) + .when(efilingLookupService) + .getServiceFee(any()); + + Mockito.when(efilingCourtService.getCourtDescription(Mockito.eq("1211"), any(), any())) + .thenReturn(Optional.of(new CourtDetails(BigDecimal.TEN, TestHelpers.COURT_DESCRIPTION, TestHelpers.CLASS_DESCRIPTION, TestHelpers.LEVEL_DESCRIPTION))); + + Mockito.when(efilingCourtService.getCourtDescription(Mockito.eq("661"), any(), any())) + .thenReturn(Optional.empty()); + + + configureCase1(fee); + configureCase2(); + configureCase3(); + + CacheProperties.Redis redis = new CacheProperties.Redis(); + redis.setTimeToLive(Duration.ofMillis(100)); + Mockito.when(cachePropertiesMock.getRedis()).thenReturn(redis); + + // Testing mapper as part of this unit test + SubmissionMapper submissionMapper = new SubmissionMapperImpl(); + NavigationProperties navigationProperties = new NavigationProperties(); + sut = new SubmissionServiceImpl(submissionStoreMock, cachePropertiesMock, submissionMapper, new PartyMapperImpl(), efilingLookupService, efilingCourtService, efilingSubmissionServiceMock, efilingDocumentService, documentStoreMock, null, null, navigationProperties); + + } + + + @Test + @DisplayName("OK: with valid account with court file number and no parties should return submission") + public void withValidAccountWithCourtFileNumberAndNoPartiesShouldReturnSubmission() { + + GenerateUrlRequest request = new GenerateUrlRequest(); + request.setClientAppName(CLIENT_APP_NAME); + request.setNavigationUrls(TestHelpers.createDefaultNavigation()); + request.setFilingPackage(TestHelpers.createInitalPackage(TestHelpers.createApiCourtBase(), TestHelpers.createInitialDocumentsList())); + + Mockito.when(efilingCourtService.checkValidLevelClassLocation(any(), any(), any(), any())).thenReturn(true); + Mockito.when(efilingCourtService.checkValidCourtFileNumber(any(), any(), any(), any(), any())).thenReturn(true); + Mockito.when(efilingDocumentService.getDocumentTypes(any(), any())).thenReturn(TestHelpers.createValidDocumentTypesList()); + + Submission actual = sut.generateFromRequest(APP_CODE, new SubmissionKey(TestHelpers.CASE_1_STRING, TestHelpers.CASE_1, TestHelpers.CASE_1), request); + + Assertions.assertEquals(TestHelpers.ERROR_URL, actual.getNavigationUrls().getError()); + Assertions.assertEquals(TestHelpers.CANCEL_URL, actual.getNavigationUrls().getCancel()); + Assertions.assertEquals(TestHelpers.SUCCESS_URL, actual.getNavigationUrls().getSuccess()); + Assertions.assertEquals(10, actual.getExpiryDate()); + Assertions.assertNotNull(actual.getId()); + Assertions.assertEquals(TestHelpers.DIVISION, actual.getFilingPackage().getCourt().getDivision()); + Assertions.assertEquals(TestHelpers.FILENUMBER, actual.getFilingPackage().getCourt().getFileNumber()); + Assertions.assertEquals(TestHelpers.LEVEL, actual.getFilingPackage().getCourt().getLevel()); + Assertions.assertEquals(TestHelpers.LOCATION, actual.getFilingPackage().getCourt().getLocation()); + Assertions.assertEquals(TestHelpers.PARTICIPATIONCLASS, actual.getFilingPackage().getCourt().getParticipatingClass()); + Assertions.assertEquals(TestHelpers.PROPERTYCLASS, actual.getFilingPackage().getCourt().getCourtClass()); + Assertions.assertEquals(TestHelpers.TYPE, actual.getFilingPackage().getDocuments().get(0).getType()); + Assertions.assertEquals(TestHelpers.DESCRIPTION, actual.getFilingPackage().getDocuments().get(0).getDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getFilingPackage().getCourt().getAgencyId()); + Assertions.assertEquals(TestHelpers.COURT_DESCRIPTION, actual.getFilingPackage().getCourt().getLocationDescription()); + Assertions.assertEquals(TestHelpers.LEVEL_DESCRIPTION, actual.getFilingPackage().getCourt().getLevelDescription()); + Assertions.assertEquals(TestHelpers.CLASS_DESCRIPTION, actual.getFilingPackage().getCourt().getClassDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getFilingPackage().getDocuments().get(0).getStatutoryFeeAmount()); + Assertions.assertEquals(SubmissionConstants.SUBMISSION_ORDR_DOCUMENT_SUB_TYPE_CD, actual.getFilingPackage().getDocuments().get(0).getSubType()); + Assertions.assertEquals("application/txt", actual.getFilingPackage().getDocuments().get(0).getMimeType()); + Assertions.assertEquals(2, actual.getFilingPackage().getParties().size()); + Assertions.assertEquals(TestHelpers.FIRST_NAME, actual.getFilingPackage().getParties().get(0).getFirstName()); + Assertions.assertEquals(TestHelpers.MIDDLE_NAME, actual.getFilingPackage().getParties().get(0).getMiddleName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, actual.getFilingPackage().getParties().get(0).getLastName()); + Assertions.assertEquals(TestHelpers.NAME_TYPE_CD, actual.getFilingPackage().getParties().get(0).getNameTypeCd()); + Assertions.assertEquals(TestHelpers.ROLE_TYPE_CD, actual.getFilingPackage().getParties().get(0).getRoleTypeCd()); + + Assertions.assertEquals(TestHelpers.FIRST_NAME, actual.getFilingPackage().getParties().get(1).getFirstName()); + Assertions.assertEquals(TestHelpers.MIDDLE_NAME, actual.getFilingPackage().getParties().get(1).getMiddleName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, actual.getFilingPackage().getParties().get(1).getLastName()); + Assertions.assertEquals(TestHelpers.NAME_TYPE_CD, actual.getFilingPackage().getParties().get(1).getNameTypeCd()); + Assertions.assertEquals(TestHelpers.ROLE_TYPE_CD, actual.getFilingPackage().getParties().get(1).getRoleTypeCd()); + + + } + + @Test + @DisplayName("OK: with valid account with no court file number and valid parties should return submission") + public void withValidAccountWithNoCourtFileNumberAndValidPartiesShouldReturnSubmission() { + + GenerateUrlRequest request = new GenerateUrlRequest(); + request.setClientAppName(CLIENT_APP_NAME); + request.setNavigationUrls(TestHelpers.createDefaultNavigation()); + request.setFilingPackage(TestHelpers.createInitalPackage(TestHelpers.createApiCourtBase(), TestHelpers.createInitialDocumentsList())); + request.getFilingPackage().getCourt().setFileNumber(""); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setRoleType(Individual.RoleTypeEnum.ABC); + parties.add(party); + request.getFilingPackage().setParties(parties); + + Mockito.when(efilingCourtService.checkValidLevelClassLocation(any(), any(), any(), any())).thenReturn(true); + Mockito.when(efilingLookupService.getValidPartyRoles(any(), any(), any())).thenReturn(TestHelpers.createValidPartyRoles()); + Mockito.when(efilingDocumentService.getDocumentTypes(any(), any())).thenReturn(TestHelpers.createValidDocumentTypesList()); + + Submission actual = sut.generateFromRequest(APP_CODE, new SubmissionKey(TestHelpers.CASE_1_STRING, TestHelpers.CASE_1, TestHelpers.CASE_1), request); + + Assertions.assertEquals(TestHelpers.ERROR_URL, actual.getNavigationUrls().getError()); + Assertions.assertEquals(TestHelpers.CANCEL_URL, actual.getNavigationUrls().getCancel()); + Assertions.assertEquals(TestHelpers.SUCCESS_URL, actual.getNavigationUrls().getSuccess()); + Assertions.assertEquals(10, actual.getExpiryDate()); + Assertions.assertNotNull(actual.getId()); + Assertions.assertEquals(TestHelpers.DIVISION, actual.getFilingPackage().getCourt().getDivision()); + Assertions.assertEquals(TestHelpers.FILENUMBER, actual.getFilingPackage().getCourt().getFileNumber()); + Assertions.assertEquals(TestHelpers.LEVEL, actual.getFilingPackage().getCourt().getLevel()); + Assertions.assertEquals(TestHelpers.LOCATION, actual.getFilingPackage().getCourt().getLocation()); + Assertions.assertEquals(TestHelpers.PARTICIPATIONCLASS, actual.getFilingPackage().getCourt().getParticipatingClass()); + Assertions.assertEquals(TestHelpers.PROPERTYCLASS, actual.getFilingPackage().getCourt().getCourtClass()); + Assertions.assertEquals(TestHelpers.TYPE, actual.getFilingPackage().getDocuments().get(0).getType()); + Assertions.assertEquals(TestHelpers.DESCRIPTION, actual.getFilingPackage().getDocuments().get(0).getDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getFilingPackage().getCourt().getAgencyId()); + Assertions.assertEquals(TestHelpers.COURT_DESCRIPTION, actual.getFilingPackage().getCourt().getLocationDescription()); + Assertions.assertEquals(TestHelpers.LEVEL_DESCRIPTION, actual.getFilingPackage().getCourt().getLevelDescription()); + Assertions.assertEquals(TestHelpers.CLASS_DESCRIPTION, actual.getFilingPackage().getCourt().getClassDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getFilingPackage().getDocuments().get(0).getStatutoryFeeAmount()); + Assertions.assertEquals(SubmissionConstants.SUBMISSION_ORDR_DOCUMENT_SUB_TYPE_CD, actual.getFilingPackage().getDocuments().get(0).getSubType()); + Assertions.assertEquals("application/txt", actual.getFilingPackage().getDocuments().get(0).getMimeType()); + Assertions.assertEquals(2, actual.getFilingPackage().getParties().size()); + Assertions.assertEquals(TestHelpers.FIRST_NAME, actual.getFilingPackage().getParties().get(0).getFirstName()); + Assertions.assertEquals(TestHelpers.MIDDLE_NAME, actual.getFilingPackage().getParties().get(0).getMiddleName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, actual.getFilingPackage().getParties().get(0).getLastName()); + Assertions.assertEquals(TestHelpers.NAME_TYPE_CD, actual.getFilingPackage().getParties().get(0).getNameTypeCd()); + Assertions.assertEquals(TestHelpers.ROLE_TYPE_CD, actual.getFilingPackage().getParties().get(0).getRoleTypeCd()); + + Assertions.assertEquals(TestHelpers.FIRST_NAME, actual.getFilingPackage().getParties().get(1).getFirstName()); + Assertions.assertEquals(TestHelpers.MIDDLE_NAME, actual.getFilingPackage().getParties().get(1).getMiddleName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, actual.getFilingPackage().getParties().get(1).getLastName()); + Assertions.assertEquals(TestHelpers.NAME_TYPE_CD, actual.getFilingPackage().getParties().get(1).getNameTypeCd()); + Assertions.assertEquals(TestHelpers.ROLE_TYPE_CD, actual.getFilingPackage().getParties().get(1).getRoleTypeCd()); + + } + + @Test + @DisplayName("OK: with valid account no rushed should return submission") + public void withValidAccountNoRushedShouldReturnSubmission() { + + GenerateUrlRequest request = new GenerateUrlRequest(); + request.setClientAppName(CLIENT_APP_NAME); + request.setNavigationUrls(TestHelpers.createDefaultNavigation()); + + InitialPackage filingPackage = TestHelpers.createInitalPackage(TestHelpers.createApiCourtBase(), TestHelpers.createInitialDocumentsList()); + filingPackage.getCourt().setLevel("TEST2"); + request.setFilingPackage(filingPackage); + + Mockito.when(efilingCourtService.checkValidLevelClassLocation(any(), any(), any(), any())).thenReturn(true); + Mockito.when(efilingCourtService.checkValidCourtFileNumber(any(), any(), any(), any(), any())).thenReturn(true); + Mockito.when(efilingDocumentService.getDocumentTypes(any(), any())).thenReturn(TestHelpers.createValidDocumentTypesList()); + + Submission actual = sut.generateFromRequest(APP_CODE, new SubmissionKey(TestHelpers.CASE_1_STRING, TestHelpers.CASE_1, TestHelpers.CASE_1), request); + + Assertions.assertEquals(TestHelpers.ERROR_URL, actual.getNavigationUrls().getError()); + Assertions.assertEquals(TestHelpers.CANCEL_URL, actual.getNavigationUrls().getCancel()); + Assertions.assertEquals(TestHelpers.SUCCESS_URL, actual.getNavigationUrls().getSuccess()); + Assertions.assertEquals(10, actual.getExpiryDate()); + Assertions.assertNotNull(actual.getId()); + Assertions.assertEquals(TestHelpers.DIVISION, actual.getFilingPackage().getCourt().getDivision()); + Assertions.assertEquals(TestHelpers.FILENUMBER, actual.getFilingPackage().getCourt().getFileNumber()); + Assertions.assertEquals(TestHelpers.LEVEL, actual.getFilingPackage().getCourt().getLevel()); + Assertions.assertEquals(TestHelpers.LOCATION, actual.getFilingPackage().getCourt().getLocation()); + Assertions.assertEquals(TestHelpers.PARTICIPATIONCLASS, actual.getFilingPackage().getCourt().getParticipatingClass()); + Assertions.assertEquals(TestHelpers.PROPERTYCLASS, actual.getFilingPackage().getCourt().getCourtClass()); + Assertions.assertEquals(TestHelpers.TYPE, actual.getFilingPackage().getDocuments().get(0).getType()); + Assertions.assertEquals(TestHelpers.DESCRIPTION, actual.getFilingPackage().getDocuments().get(0).getDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getFilingPackage().getCourt().getAgencyId()); + Assertions.assertEquals(TestHelpers.COURT_DESCRIPTION, actual.getFilingPackage().getCourt().getLocationDescription()); + Assertions.assertEquals(TestHelpers.LEVEL_DESCRIPTION, actual.getFilingPackage().getCourt().getLevelDescription()); + Assertions.assertEquals(TestHelpers.CLASS_DESCRIPTION, actual.getFilingPackage().getCourt().getClassDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getFilingPackage().getDocuments().get(0).getStatutoryFeeAmount()); + Assertions.assertEquals(SubmissionConstants.SUBMISSION_ORDR_DOCUMENT_SUB_TYPE_CD, actual.getFilingPackage().getDocuments().get(0).getSubType()); + Assertions.assertEquals("application/txt", actual.getFilingPackage().getDocuments().get(0).getMimeType()); + Assertions.assertEquals(2, actual.getFilingPackage().getParties().size()); + Assertions.assertEquals(TestHelpers.FIRST_NAME, actual.getFilingPackage().getParties().get(0).getFirstName()); + Assertions.assertEquals(TestHelpers.MIDDLE_NAME, actual.getFilingPackage().getParties().get(0).getMiddleName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, actual.getFilingPackage().getParties().get(0).getLastName()); + Assertions.assertEquals(TestHelpers.NAME_TYPE_CD, actual.getFilingPackage().getParties().get(0).getNameTypeCd()); + Assertions.assertEquals(TestHelpers.ROLE_TYPE_CD, actual.getFilingPackage().getParties().get(0).getRoleTypeCd()); + + Assertions.assertEquals(TestHelpers.FIRST_NAME, actual.getFilingPackage().getParties().get(1).getFirstName()); + Assertions.assertEquals(TestHelpers.MIDDLE_NAME, actual.getFilingPackage().getParties().get(1).getMiddleName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, actual.getFilingPackage().getParties().get(1).getLastName()); + Assertions.assertEquals(TestHelpers.NAME_TYPE_CD, actual.getFilingPackage().getParties().get(1).getNameTypeCd()); + Assertions.assertEquals(TestHelpers.ROLE_TYPE_CD, actual.getFilingPackage().getParties().get(1).getRoleTypeCd()); + + } + + @Test + @DisplayName("OK: with packge id and rejected document should return submission") + public void withPackageAndRejectedDocumentShouldReturnSubmission() { + + GenerateUrlRequest request = new GenerateUrlRequest(); + request.setClientAppName(CLIENT_APP_NAME); + request.setNavigationUrls(TestHelpers.createDefaultNavigation()); + + InitialPackage filingPackage = TestHelpers.createInitalPackage(TestHelpers.createApiCourtBase(), TestHelpers.createInitialDocumentsList()); + filingPackage.setPackageNumber(PACKAGE_IDENTIFIER); + + ActionDocument actionDocument = new ActionDocument(); + actionDocument.setId(DOCUMENT_ID); + actionDocument.setType(Keys.REJECTED_DOCUMENT_CODE); + filingPackage.getDocuments().get(0).setActionDocument(actionDocument); + + filingPackage.getCourt().setLevel("TEST2"); + request.setFilingPackage(filingPackage); + + Mockito.when(efilingCourtService.checkValidLevelClassLocation(any(), any(), any(), any())).thenReturn(true); + Mockito.when(efilingCourtService.checkValidCourtFileNumber(any(), any(), any(), any(), any())).thenReturn(true); + Mockito.when(efilingDocumentService.getDocumentTypes(any(), any())).thenReturn(TestHelpers.createValidDocumentTypesList()); + + Submission actual = sut.generateFromRequest(APP_CODE, new SubmissionKey(TestHelpers.CASE_1_STRING, TestHelpers.CASE_1, TestHelpers.CASE_1), request); + + Assertions.assertEquals(TestHelpers.ERROR_URL, actual.getNavigationUrls().getError()); + Assertions.assertEquals(TestHelpers.CANCEL_URL, actual.getNavigationUrls().getCancel()); + Assertions.assertEquals(TestHelpers.SUCCESS_URL, actual.getNavigationUrls().getSuccess()); + Assertions.assertEquals(10, actual.getExpiryDate()); + Assertions.assertNotNull(actual.getId()); + Assertions.assertEquals(TestHelpers.DIVISION, actual.getFilingPackage().getCourt().getDivision()); + Assertions.assertEquals(TestHelpers.FILENUMBER, actual.getFilingPackage().getCourt().getFileNumber()); + Assertions.assertEquals(TestHelpers.LEVEL, actual.getFilingPackage().getCourt().getLevel()); + Assertions.assertEquals(TestHelpers.LOCATION, actual.getFilingPackage().getCourt().getLocation()); + Assertions.assertEquals(TestHelpers.PARTICIPATIONCLASS, actual.getFilingPackage().getCourt().getParticipatingClass()); + Assertions.assertEquals(TestHelpers.PROPERTYCLASS, actual.getFilingPackage().getCourt().getCourtClass()); + Assertions.assertEquals(TestHelpers.TYPE, actual.getFilingPackage().getDocuments().get(0).getType()); + Assertions.assertEquals(TestHelpers.DESCRIPTION, actual.getFilingPackage().getDocuments().get(0).getDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getFilingPackage().getCourt().getAgencyId()); + Assertions.assertEquals(TestHelpers.COURT_DESCRIPTION, actual.getFilingPackage().getCourt().getLocationDescription()); + Assertions.assertEquals(TestHelpers.LEVEL_DESCRIPTION, actual.getFilingPackage().getCourt().getLevelDescription()); + Assertions.assertEquals(TestHelpers.CLASS_DESCRIPTION, actual.getFilingPackage().getCourt().getClassDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getFilingPackage().getDocuments().get(0).getStatutoryFeeAmount()); + Assertions.assertEquals(SubmissionConstants.SUBMISSION_ORDR_DOCUMENT_SUB_TYPE_CD, actual.getFilingPackage().getDocuments().get(0).getSubType()); + Assertions.assertEquals("application/txt", actual.getFilingPackage().getDocuments().get(0).getMimeType()); + Assertions.assertEquals(2, actual.getFilingPackage().getParties().size()); + Assertions.assertEquals(TestHelpers.FIRST_NAME, actual.getFilingPackage().getParties().get(0).getFirstName()); + Assertions.assertEquals(TestHelpers.MIDDLE_NAME, actual.getFilingPackage().getParties().get(0).getMiddleName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, actual.getFilingPackage().getParties().get(0).getLastName()); + Assertions.assertEquals(TestHelpers.NAME_TYPE_CD, actual.getFilingPackage().getParties().get(0).getNameTypeCd()); + Assertions.assertEquals(TestHelpers.ROLE_TYPE_CD, actual.getFilingPackage().getParties().get(0).getRoleTypeCd()); + + Assertions.assertEquals(TestHelpers.FIRST_NAME, actual.getFilingPackage().getParties().get(1).getFirstName()); + Assertions.assertEquals(TestHelpers.MIDDLE_NAME, actual.getFilingPackage().getParties().get(1).getMiddleName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, actual.getFilingPackage().getParties().get(1).getLastName()); + Assertions.assertEquals(TestHelpers.NAME_TYPE_CD, actual.getFilingPackage().getParties().get(1).getNameTypeCd()); + Assertions.assertEquals(TestHelpers.ROLE_TYPE_CD, actual.getFilingPackage().getParties().get(1).getRoleTypeCd()); + + Assertions.assertEquals(PACKAGE_IDENTIFIER, actual.getFilingPackage().getPackageNumber()); + + } + + @Test + @DisplayName("OK: with packge id and non rejected document id should return submission") + public void withPackageAndDocumentShouldReturnSubmission() { + + GenerateUrlRequest request = new GenerateUrlRequest(); + request.setClientAppName(CLIENT_APP_NAME); + request.setNavigationUrls(TestHelpers.createDefaultNavigation()); + + InitialPackage filingPackage = TestHelpers.createInitalPackage(TestHelpers.createApiCourtBase(), TestHelpers.createInitialDocumentsList()); + filingPackage.setPackageNumber(PACKAGE_IDENTIFIER); + + ActionDocument actionDocument = new ActionDocument(); + actionDocument.setId(DOCUMENT_ID); + actionDocument.setType(DOCUMENT_COURTESY_CORRECTED); + filingPackage.getDocuments().get(0).setActionDocument(actionDocument); + + filingPackage.getCourt().setLevel("TEST2"); + request.setFilingPackage(filingPackage); + + Mockito.when(efilingCourtService.checkValidLevelClassLocation(any(), any(), any(), any())).thenReturn(true); + Mockito.when(efilingCourtService.checkValidCourtFileNumber(any(), any(), any(), any(), any())).thenReturn(true); + Mockito.when(efilingDocumentService.getDocumentTypes(any(), any())).thenReturn(TestHelpers.createValidDocumentTypesList()); + + Submission actual = sut.generateFromRequest(APP_CODE, new SubmissionKey(TestHelpers.CASE_1_STRING, TestHelpers.CASE_1, TestHelpers.CASE_1), request); + + Assertions.assertEquals(TestHelpers.ERROR_URL, actual.getNavigationUrls().getError()); + Assertions.assertEquals(TestHelpers.CANCEL_URL, actual.getNavigationUrls().getCancel()); + Assertions.assertEquals(TestHelpers.SUCCESS_URL, actual.getNavigationUrls().getSuccess()); + Assertions.assertEquals(10, actual.getExpiryDate()); + Assertions.assertNotNull(actual.getId()); + Assertions.assertEquals(TestHelpers.DIVISION, actual.getFilingPackage().getCourt().getDivision()); + Assertions.assertEquals(TestHelpers.FILENUMBER, actual.getFilingPackage().getCourt().getFileNumber()); + Assertions.assertEquals(TestHelpers.LEVEL, actual.getFilingPackage().getCourt().getLevel()); + Assertions.assertEquals(TestHelpers.LOCATION, actual.getFilingPackage().getCourt().getLocation()); + Assertions.assertEquals(TestHelpers.PARTICIPATIONCLASS, actual.getFilingPackage().getCourt().getParticipatingClass()); + Assertions.assertEquals(TestHelpers.PROPERTYCLASS, actual.getFilingPackage().getCourt().getCourtClass()); + Assertions.assertEquals(TestHelpers.TYPE, actual.getFilingPackage().getDocuments().get(0).getType()); + Assertions.assertEquals(TestHelpers.DESCRIPTION, actual.getFilingPackage().getDocuments().get(0).getDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getFilingPackage().getCourt().getAgencyId()); + Assertions.assertEquals(TestHelpers.COURT_DESCRIPTION, actual.getFilingPackage().getCourt().getLocationDescription()); + Assertions.assertEquals(TestHelpers.LEVEL_DESCRIPTION, actual.getFilingPackage().getCourt().getLevelDescription()); + Assertions.assertEquals(TestHelpers.CLASS_DESCRIPTION, actual.getFilingPackage().getCourt().getClassDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getFilingPackage().getDocuments().get(0).getStatutoryFeeAmount()); + Assertions.assertEquals(SubmissionConstants.SUBMISSION_ORDR_DOCUMENT_SUB_TYPE_CD, actual.getFilingPackage().getDocuments().get(0).getSubType()); + Assertions.assertEquals("application/txt", actual.getFilingPackage().getDocuments().get(0).getMimeType()); + Assertions.assertEquals(DOCUMENT_ID, actual.getFilingPackage().getDocuments().get(0).getActionDocument().getDocumentId()); + Assertions.assertEquals("REJ", actual.getFilingPackage().getDocuments().get(0).getActionDocument().getStatus()); + Assertions.assertEquals("TEST", actual.getFilingPackage().getDocuments().get(0).getActionDocument().getType()); + Assertions.assertEquals(2, actual.getFilingPackage().getParties().size()); + Assertions.assertEquals(TestHelpers.FIRST_NAME, actual.getFilingPackage().getParties().get(0).getFirstName()); + Assertions.assertEquals(TestHelpers.MIDDLE_NAME, actual.getFilingPackage().getParties().get(0).getMiddleName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, actual.getFilingPackage().getParties().get(0).getLastName()); + Assertions.assertEquals(TestHelpers.NAME_TYPE_CD, actual.getFilingPackage().getParties().get(0).getNameTypeCd()); + Assertions.assertEquals(TestHelpers.ROLE_TYPE_CD, actual.getFilingPackage().getParties().get(0).getRoleTypeCd()); + + Assertions.assertEquals(TestHelpers.FIRST_NAME, actual.getFilingPackage().getParties().get(1).getFirstName()); + Assertions.assertEquals(TestHelpers.MIDDLE_NAME, actual.getFilingPackage().getParties().get(1).getMiddleName()); + Assertions.assertEquals(TestHelpers.LAST_NAME, actual.getFilingPackage().getParties().get(1).getLastName()); + Assertions.assertEquals(TestHelpers.NAME_TYPE_CD, actual.getFilingPackage().getParties().get(1).getNameTypeCd()); + Assertions.assertEquals(TestHelpers.ROLE_TYPE_CD, actual.getFilingPackage().getParties().get(1).getRoleTypeCd()); + + Assertions.assertEquals(PACKAGE_IDENTIFIER, actual.getFilingPackage().getPackageNumber()); + + } + + @Test + @DisplayName("Exception: with empty submission from store should throw StoreException") + public void withEmptySubmissionShouldThrowStoreException() { + + GenerateUrlRequest request = new GenerateUrlRequest(); + request.setClientAppName(CLIENT_APP_NAME); + request.setNavigationUrls(TestHelpers.createDefaultNavigation()); + request.setFilingPackage(TestHelpers.createInitalPackage(TestHelpers.createApiCourtBase(), TestHelpers.createInitialDocumentsList())); + + Mockito.when(efilingCourtService.checkValidLevelClassLocation(any(), any(), any(), any())).thenReturn(true); + Mockito.when(efilingCourtService.checkValidCourtFileNumber(any(), any(), any(), any(), any())).thenReturn(true); + Mockito.when(efilingDocumentService.getDocumentTypes(any(), any())).thenReturn(TestHelpers.createValidDocumentTypesList()); + + Assertions.assertThrows(StoreException.class, () -> sut.generateFromRequest(APP_CODE, new SubmissionKey(TestHelpers.CASE_2_STRING, TestHelpers.CASE_2, TestHelpers.CASE_2), request)); + + } + + + @Test + @DisplayName("Exception: with null courtDetails should throw an exception") + public void withEmptyCourtDescriptionShouldThrowException() { + + GenerateUrlRequest request = new GenerateUrlRequest(); + request.setClientAppName(CLIENT_APP_NAME); + request.setNavigationUrls(TestHelpers.createDefaultNavigation()); + + CourtBase apiCourt = TestHelpers.createApiCourtBase("661"); + + request.setFilingPackage(TestHelpers.createInitalPackage(apiCourt, TestHelpers.createInitialDocumentsList())); + + Mockito.when(efilingCourtService.checkValidLevelClassLocation(any(), any(), any(), any())).thenReturn(true); + Mockito.when(efilingCourtService.checkValidCourtFileNumber(any(), any(), any(), any(), any())).thenReturn(true); + Mockito.when(efilingDocumentService.getDocumentTypes(any(), any())).thenReturn(TestHelpers.createValidDocumentTypesList()); + + + Assertions.assertThrows( + EfilingCourtServiceException.class, + () -> sut.generateFromRequest(APP_CODE, new SubmissionKey(TestHelpers.CASE_1_STRING, TestHelpers.CASE_1, TestHelpers.CASE_1), request)); + + + } + + private void configureCase1(ServiceFees fee) { + + AccountDetails accountDetails = getAccountDetails(true, TestHelpers.CASE_1.toString()); + + Mockito.when(documentStoreMock.getDocumentDetails(Mockito.eq("LEVEL"), any(), any())) + .thenReturn(new DocumentTypeDetails(TestHelpers.DESCRIPTION, TestHelpers.TYPE, BigDecimal.TEN, true, true, true)); + + Mockito.when(documentStoreMock.getDocumentDetails(Mockito.eq("TEST2"), any(), any())) + .thenReturn(new DocumentTypeDetails(TestHelpers.DESCRIPTION, TestHelpers.TYPE, BigDecimal.TEN, true, false, false)); + + Submission submissionCase1 = Submission + .builder() + .id(TestHelpers.CASE_1) + .transactionId(TestHelpers.CASE_1) + .navigationUrls(TestHelpers.createDefaultNavigation()) + .expiryDate(10) + .filingPackage(TestHelpers.createPackage(TestHelpers.createCourt(), TestHelpers.createDocumentList(), TestHelpers.createPartyList(), TestHelpers.createOrganizationList())) + .create(); + + Mockito + .doReturn(Optional.of(submissionCase1)) + .when(submissionStoreMock).put( + ArgumentMatchers.argThat(x -> x.getTransactionId() == TestHelpers.CASE_1)); + } + + private void configureCase2() { + + AccountDetails accountDetails = getAccountDetails(true, TestHelpers.CASE_2.toString()); + + Mockito + .doReturn(Optional.empty()) + .when(submissionStoreMock).put( + ArgumentMatchers.argThat(x -> x.getTransactionId() == TestHelpers.CASE_2)); + } + + private void configureCase3() { + + AccountDetails accountDetails = getAccountDetails(false, TestHelpers.CASE_3.toString()); + + } + + private AccountDetails getAccountDetails(boolean fileRolePresent, String _case) { + return AccountDetails + .builder() + .fileRolePresent(fileRolePresent) + .accountId(BigDecimal.TEN) + .clientId(BigDecimal.ONE) + .create(); + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/GetValidIndividualRolesTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/GetValidIndividualRolesTest.java new file mode 100644 index 0000000000..43711fb6c8 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/GetValidIndividualRolesTest.java @@ -0,0 +1,95 @@ +package ca.bc.gov.open.jag.efilingapi.submission.service.submissionServiceImpl; + +import ca.bc.gov.open.jag.efilingapi.api.model.InitialDocument; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.PartyMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.models.GetValidPartyRoleRequest; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionServiceImpl; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingcommons.payment.PaymentAdapter; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingCourtService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSubmissionService; +import ca.bc.gov.open.sftp.starter.SftpService; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.autoconfigure.cache.CacheProperties; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class GetValidIndividualRolesTest { + + private static String[] ROLE_TYPES = new String[] {"role1", "role2", "role3", "role4", "role5"}; + + private SubmissionServiceImpl sut; + + @Mock + private SubmissionStore submissionStoreMock; + + @Mock + private CacheProperties cachePropertiesMock; + + @Mock + private EfilingLookupService efilingLookupService; + + @Mock + private EfilingCourtService efilingCourtService; + + @Mock + private DocumentStore documentStoreMock; + + @Mock + private EfilingSubmissionService efilingSubmissionServiceMock; + + @Mock + private PaymentAdapter paymentAdapterMock; + + @Mock + private SftpService sftpServiceMock; + + + @BeforeAll + public void setUp(){ + MockitoAnnotations.initMocks(this); + + Mockito.when(efilingLookupService.getValidPartyRoles( + Mockito.eq("A"), + Mockito.eq("B"), + Mockito.eq("POR,ACMW"))).thenReturn(Arrays.asList(ROLE_TYPES)); + NavigationProperties navigationProperties = new NavigationProperties(); + sut = new SubmissionServiceImpl(submissionStoreMock, cachePropertiesMock, null, new PartyMapperImpl(), efilingLookupService, efilingCourtService, efilingSubmissionServiceMock, null, documentStoreMock, paymentAdapterMock, sftpServiceMock, navigationProperties); + } + + @Test + @DisplayName("ok: service will return a valid list of role types") + public void shouldReturnAValidListOfTypes() + { + + List documents = new ArrayList<>(); + InitialDocument document1 = new InitialDocument(); + document1.setType("POR"); + documents.add(document1); + InitialDocument document2 = new InitialDocument(); + document2.setType("ACMW"); + documents.add(document2); + GetValidPartyRoleRequest getValidPartyRoleRequest = GetValidPartyRoleRequest + .builder() + .courtLevel("A") + .courtClassification("B") + .documents(documents) + .create(); + + List actual = sut.getValidPartyRoles(getValidPartyRoleRequest); + + Assertions.assertEquals(5, actual.size()); + Assertions.assertTrue(Arrays.asList(ROLE_TYPES).containsAll(actual)); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/IsRushRequiredTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/IsRushRequiredTest.java new file mode 100644 index 0000000000..eeba9c4052 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/IsRushRequiredTest.java @@ -0,0 +1,87 @@ +package ca.bc.gov.open.jag.efilingapi.submission.service.submissionServiceImpl; + +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionServiceImpl; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingCourtService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSubmissionService; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.autoconfigure.cache.CacheProperties; + +import javax.xml.datatype.DatatypeConfigurationException; +import java.math.BigDecimal; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class IsRushRequiredTest { + + private SubmissionServiceImpl sut; + + @Mock + private SubmissionStore submissionStoreMock; + + @Mock + private CacheProperties cachePropertiesMock; + + @Mock + private EfilingLookupService efilingLookupService; + + @Mock + private EfilingCourtService efilingCourtService; + + @Mock + private EfilingDocumentService efilingDocumentService; + + @Mock + private DocumentStore documentStoreMock; + + @Mock + private EfilingSubmissionService efilingSubmissionServiceMock; + + @BeforeAll + public void beforeAll() throws DatatypeConfigurationException { + + MockitoAnnotations.openMocks(this); + + sut = new SubmissionServiceImpl(submissionStoreMock, cachePropertiesMock, null, null, efilingLookupService, efilingCourtService, efilingSubmissionServiceMock, efilingDocumentService, documentStoreMock, null, null, null); + + } + + @Test + @DisplayName("Test is rushRequired") + public void testRushRequired() { + + Mockito.when(efilingDocumentService.getDocumentTypeDetails(any(), any(), any())).thenReturn(new DocumentTypeDetails("description", + "type", + BigDecimal.TEN, + true, + true, + true)); + + Assertions.assertTrue(sut.isRushRequired("TEST","TEST","TEST")); + + } + + @Test + @DisplayName("Test is not rushRequired") + public void testRushNotRequired() { + + Mockito.when(efilingDocumentService.getDocumentTypeDetails(any(), any(), any())).thenReturn(new DocumentTypeDetails("description", + "type", + BigDecimal.TEN, + true, + false, + true)); + + Assertions.assertFalse(sut.isRushRequired("TEST","TEST","TEST")); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/UpdateDocumentsTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/UpdateDocumentsTest.java new file mode 100644 index 0000000000..e2462c82bb --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/UpdateDocumentsTest.java @@ -0,0 +1,100 @@ +package ca.bc.gov.open.jag.efilingapi.submission.service.submissionServiceImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.api.model.DocumentProperties; +import ca.bc.gov.open.jag.efilingapi.api.model.UpdateDocumentRequest; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionKey; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.PartyMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.SubmissionMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingapi.submission.models.SubmissionConstants; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionServiceImpl; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingCourtService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSubmissionService; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.autoconfigure.cache.CacheProperties; + +import java.math.BigDecimal; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class UpdateDocumentsTest { + private SubmissionServiceImpl sut; + + @Mock + private SubmissionStore submissionStoreMock; + + @Mock + private CacheProperties cachePropertiesMock; + + @Mock + private EfilingLookupService efilingLookupService; + + @Mock + private EfilingCourtService efilingCourtService; + + @Mock + private DocumentStore documentStoreMock; + + @Mock + private EfilingSubmissionService efilingSubmissionServiceMock; + + + @BeforeAll + public void setUp() { + + MockitoAnnotations.openMocks(this); + + DocumentTypeDetails documentDetails = new DocumentTypeDetails(TestHelpers.DESCRIPTION, "TYPE",BigDecimal.TEN, false, false,true); + + Mockito.when(documentStoreMock.getDocumentDetails(any(), any(), any())).thenReturn(documentDetails); + + NavigationProperties navigationProperties = new NavigationProperties(); + + sut = new SubmissionServiceImpl( + submissionStoreMock, + cachePropertiesMock, + new SubmissionMapperImpl(), + new PartyMapperImpl(), + efilingLookupService, + efilingCourtService, + efilingSubmissionServiceMock, + null, + documentStoreMock, + null, + null, navigationProperties); + + } + + @Test + @DisplayName("OK: with valid request should return submission") + public void withValidRequestShouldreturnSubmission() { + UpdateDocumentRequest updateDocumentRequest = new UpdateDocumentRequest(); + DocumentProperties initialDocument = new DocumentProperties(); + initialDocument.setType("AAB"); + initialDocument.setName("test.txt"); + updateDocumentRequest.addDocumentsItem(initialDocument); + + Submission submission = TestHelpers.buildSubmission(); + Submission actual = sut.updateDocuments(submission, updateDocumentRequest, new SubmissionKey(UUID.randomUUID().toString(), UUID.randomUUID(), UUID.randomUUID())); + + Assertions.assertEquals(2, actual.getFilingPackage().getDocuments().size()); + Assertions.assertEquals(TestHelpers.DESCRIPTION, actual.getFilingPackage().getDocuments().get(0).getDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getFilingPackage().getDocuments().get(0).getStatutoryFeeAmount()); + Assertions.assertEquals(SubmissionConstants.SUBMISSION_ORDR_DOCUMENT_SUB_TYPE_CD, actual.getFilingPackage().getDocuments().get(0).getSubType()); + Assertions.assertEquals(TestHelpers.DESCRIPTION, actual.getFilingPackage().getDocuments().get(1).getDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getFilingPackage().getDocuments().get(1).getStatutoryFeeAmount()); + Assertions.assertEquals(SubmissionConstants.SUBMISSION_ODOC_DOCUMENT_SUB_TYPE_CD, actual.getFilingPackage().getDocuments().get(1).getSubType()); + + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/generateFromRequestTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/generateFromRequestTest.java deleted file mode 100644 index 2dd1dcd4b0..0000000000 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionServiceImpl/generateFromRequestTest.java +++ /dev/null @@ -1,238 +0,0 @@ -package ca.bc.gov.open.jag.efilingapi.submission.service.submissionServiceImpl; - - -import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; -import ca.bc.gov.open.jag.efilingapi.TestHelpers; -import ca.bc.gov.open.jag.efilingapi.api.model.DocumentProperties; -import ca.bc.gov.open.jag.efilingapi.api.model.GenerateUrlRequest; -import ca.bc.gov.open.jag.efilingapi.fee.FeeService; -import ca.bc.gov.open.jag.efilingapi.fee.models.Fee; -import ca.bc.gov.open.jag.efilingapi.submission.mappers.SubmissionMapper; -import ca.bc.gov.open.jag.efilingapi.submission.mappers.SubmissionMapperImpl; -import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; -import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionServiceImpl; -import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; -import ca.bc.gov.open.jag.efilingcommons.exceptions.InvalidAccountStateException; -import ca.bc.gov.open.jag.efilingcommons.exceptions.StoreException; -import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; -import org.apache.commons.lang3.StringUtils; -import org.junit.jupiter.api.*; -import org.mockito.ArgumentMatchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.springframework.boot.autoconfigure.cache.CacheProperties; - -import java.math.BigDecimal; -import java.time.Duration; -import java.util.Optional; -import java.util.UUID; - -import static ca.bc.gov.open.jag.efilingapi.api.model.EndpointAccess.VerbEnum.POST; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -public class generateFromRequestTest { - - private static final String MIDDLE_NAME = "case1_middleName"; - private static final String LAST_NAME = "case1_lastName"; - private static final String FIRST_NAME = "case1_firstName"; - private static final String EMAIL = "case1_email"; - private static final DocumentProperties CASE1_DOCUMENT_PROPERTIES = TestHelpers.createDocumentProperties("header", "http://doc", "subtype", "case1_type"); - - - private SubmissionServiceImpl sut; - - @Mock - private SubmissionStore submissionStoreMock; - @Mock - private CacheProperties cachePropertiesMock; - @Mock - private FeeService feeServiceMock; - @Mock - private EfilingAccountService efilingAccountServiceMock; - - - @BeforeAll - public void setUp() { - - MockitoAnnotations.initMocks(this); - - Fee fee = new Fee(BigDecimal.valueOf(7.00)); - Mockito.doReturn(fee) - .when(feeServiceMock) - .getFee(Mockito.any()); - - configureCase1(fee); - configureCase2(); - configureCase3(); - - CacheProperties.Redis redis = new CacheProperties.Redis(); - redis.setTimeToLive(Duration.ofMillis(100)); - Mockito.when(cachePropertiesMock.getRedis()).thenReturn(redis); - - // Testing mapper as part of this unit test - SubmissionMapper submissionMapper = new SubmissionMapperImpl(); - sut = new SubmissionServiceImpl(submissionStoreMock, cachePropertiesMock, submissionMapper, efilingAccountServiceMock, feeServiceMock); - - } - - - - @Test - @DisplayName("OK: with valid account should retun submission") - public void withValidAccountShouldReturnSubmission() { - - GenerateUrlRequest request = new GenerateUrlRequest(); - request.setNavigation(TestHelpers.createDefaultNavigation()); - request.setDocumentProperties(CASE1_DOCUMENT_PROPERTIES); - - Submission actual = sut.generateFromRequest(TestHelpers.CASE_1, request); - - Assertions.assertEquals(TestHelpers.CASE_1.toString() + EMAIL, actual.getAccountDetails().getEmail()); - Assertions.assertEquals(TestHelpers.CASE_1.toString() + FIRST_NAME, actual.getAccountDetails().getFirstName()); - Assertions.assertEquals(TestHelpers.CASE_1.toString() + LAST_NAME, actual.getAccountDetails().getLastName()); - Assertions.assertEquals(TestHelpers.CASE_1.toString() + MIDDLE_NAME, actual.getAccountDetails().getMiddleName()); - Assertions.assertEquals(BigDecimal.TEN, actual.getAccountDetails().getAccountId()); - Assertions.assertEquals(BigDecimal.ONE, actual.getAccountDetails().getClientId()); - Assertions.assertEquals(TestHelpers.ERROR_URL, actual.getNavigation().getError().getUrl()); - Assertions.assertEquals(TestHelpers.CANCEL_URL, actual.getNavigation().getCancel().getUrl()); - Assertions.assertEquals(TestHelpers.SUCCESS_URL, actual.getNavigation().getSuccess().getUrl()); - Assertions.assertEquals(10, actual.getExpiryDate()); - Assertions.assertEquals("subtype", actual.getDocumentProperties().getSubType()); - Assertions.assertEquals("case1_type", actual.getDocumentProperties().getType()); - Assertions.assertEquals("http://doc", actual.getDocumentProperties().getSubmissionAccess().getUrl()); - Assertions.assertEquals("header", actual.getDocumentProperties().getSubmissionAccess().getHeaders().get("header")); - Assertions.assertEquals(POST, actual.getDocumentProperties().getSubmissionAccess().getVerb()); - Assertions.assertEquals(BigDecimal.valueOf(7.0), actual.getFee().getAmount()); - Assertions.assertNotNull(actual.getId()); - - } - - @Test - @DisplayName("Exception: with empty submission from store should throw StoreException") - public void withEmptySubmissionShouldThrowStoreException() { - - GenerateUrlRequest request = new GenerateUrlRequest(); - request.setNavigation(TestHelpers.createDefaultNavigation()); - request.setDocumentProperties(CASE1_DOCUMENT_PROPERTIES); - - Assertions.assertThrows(StoreException.class, () -> sut.generateFromRequest(TestHelpers.CASE_2, request)); - - } - - @Test - @DisplayName("Exception: with no file role should throw InvalidAccountStateException") - public void withNoFileRoleShouldThrowInvalidAccountStateException() { - - GenerateUrlRequest request = new GenerateUrlRequest(); - request.setNavigation(TestHelpers.createDefaultNavigation()); - request.setDocumentProperties(CASE1_DOCUMENT_PROPERTIES); - - Assertions.assertThrows(InvalidAccountStateException.class, () -> sut.generateFromRequest(TestHelpers.CASE_3, request)); - - } - - @Test - @DisplayName("TEMP: test demo acount") - public void testDemo() { - - UUID fakeaccount = UUID.fromString("88da92db-0791-491e-8c58-1a969e67d2fb"); - GenerateUrlRequest request = new GenerateUrlRequest(); - request.setNavigation(TestHelpers.createDefaultNavigation()); - request.setDocumentProperties(CASE1_DOCUMENT_PROPERTIES); - - - AccountDetails accountDetails = AccountDetails.builder().lastName("lastName").create(); - - Fee fee = new Fee(BigDecimal.TEN); - Submission submissionCase1 = Submission - .builder() - .accountDetails(accountDetails) - .navigation(TestHelpers.createDefaultNavigation()) - .expiryDate(10) - .documentProperties(CASE1_DOCUMENT_PROPERTIES) - .fee(fee) - .create(); - - Mockito - .doReturn(Optional.of(submissionCase1)) - .when(submissionStoreMock).put( - ArgumentMatchers.argThat(x -> StringUtils.equals("Ross", x.getAccountDetails().getLastName()))); - - Submission actual = sut.generateFromRequest(fakeaccount, request); - - Assertions.assertEquals("lastName", actual.getAccountDetails().getLastName()); - - - } - - private void configureCase1(Fee fee) { - - - AccountDetails accountDetails = getAccountDetails(true, TestHelpers.CASE_1.toString()); - - Mockito - .when(efilingAccountServiceMock.getAccountDetails( - Mockito.eq(TestHelpers.CASE_1), - Mockito.any())) - .thenReturn(accountDetails); - - Submission submissionCase1 = Submission - .builder() - .accountDetails(accountDetails) - .navigation(TestHelpers.createDefaultNavigation()) - .expiryDate(10) - .documentProperties(CASE1_DOCUMENT_PROPERTIES) - .fee(fee) - .create(); - - Mockito - .doReturn(Optional.of(submissionCase1)) - .when(submissionStoreMock).put( - ArgumentMatchers.argThat(x -> StringUtils.equals(TestHelpers.CASE_1.toString() + FIRST_NAME, x.getAccountDetails().getFirstName()))); - } - - private void configureCase2() { - - - AccountDetails accountDetails = getAccountDetails(true, TestHelpers.CASE_2.toString()); - - Mockito - .when(efilingAccountServiceMock.getAccountDetails( - Mockito.eq(TestHelpers.CASE_2), - Mockito.any())) - .thenReturn(accountDetails); - - Mockito - .doReturn(Optional.empty()) - .when(submissionStoreMock).put( - ArgumentMatchers.argThat(x -> StringUtils.equals(TestHelpers.CASE_2.toString() + FIRST_NAME, x.getAccountDetails().getFirstName()))); - } - - private void configureCase3() { - - AccountDetails accountDetails = getAccountDetails(false, TestHelpers.CASE_3.toString()); - - Mockito - .when(efilingAccountServiceMock.getAccountDetails( - Mockito.eq(TestHelpers.CASE_3), - Mockito.any())) - .thenReturn(accountDetails); - - } - - private AccountDetails getAccountDetails(boolean fileRolePresent, String _case) { - return AccountDetails - .builder() - .fileRolePresent(fileRolePresent) - .middleName(_case + MIDDLE_NAME) - .lastName(_case + LAST_NAME) - .firstName(_case + FIRST_NAME) - .email(_case + EMAIL) - .accountId(BigDecimal.TEN) - .clientId(BigDecimal.ONE) - .create(); - } - - -} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionStore/DeleteByKeyTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionStore/DeleteByKeyTest.java new file mode 100644 index 0000000000..0b9016c7ae --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionStore/DeleteByKeyTest.java @@ -0,0 +1,28 @@ +package ca.bc.gov.open.jag.efilingapi.submission.service.submissionStore; + +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionKey; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStoreImpl; +import org.junit.jupiter.api.*; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; + +import java.util.UUID; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class DeleteByKeyTest { + + @InjectMocks + private SubmissionStoreImpl sut; + + @BeforeAll + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + @DisplayName("OK: evict should do nothing") + public void testEvict() { + Assertions.assertDoesNotThrow(() -> sut.evict(new SubmissionKey( UUID.randomUUID().toString(), UUID.randomUUID(), UUID.randomUUID()))); + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionStore/GetByKeyTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionStore/GetByKeyTest.java index b830233596..11a9f06bb5 100644 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionStore/GetByKeyTest.java +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionStore/GetByKeyTest.java @@ -1,7 +1,8 @@ package ca.bc.gov.open.jag.efilingapi.submission.service.submissionStore; -import ca.bc.gov.open.jag.efilingapi.api.model.DocumentProperties; +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionKey; import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStoreImpl; import org.junit.jupiter.api.*; @@ -14,46 +15,24 @@ @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class GetByKeyTest { - private static final UUID ID = UUID.randomUUID(); - private static final String TYPE = "type"; - @InjectMocks private SubmissionStoreImpl sut; @BeforeAll public void setUp() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); - DocumentProperties documentMetadata = new DocumentProperties(); - documentMetadata.setType(TYPE); } @Test @DisplayName("CASE 1: without cache always return empty") public void withExistingIdShouldReturnSubmission() { - Optional actual = sut.getByKey(ID); + Optional actual = sut.get(new SubmissionKey(TestHelpers.CASE_1_STRING, UUID.randomUUID(), UUID.randomUUID())); Assertions.assertEquals(Optional.empty(), actual); } - @Test - @DisplayName("CASE 2: with put in cache should put return submission") - public void withSubmissionShouldReturnOptional() { - - DocumentProperties documentProperties = new DocumentProperties(); - documentProperties.setSubType("subtype"); - - Submission submission = Submission - .builder() - .documentProperties(documentProperties) - .create(); - Optional actual = sut.put(submission); - Assertions.assertTrue(actual.isPresent()); - Assertions.assertEquals("subtype", actual.get().getDocumentProperties().getSubType()); - - } - } diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionStore/PutTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionStore/PutTest.java index 2398a84c16..111ca1af51 100644 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionStore/PutTest.java +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/service/submissionStore/PutTest.java @@ -1,6 +1,5 @@ package ca.bc.gov.open.jag.efilingapi.submission.service.submissionStore; -import ca.bc.gov.open.jag.efilingapi.api.model.DocumentProperties; import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStoreImpl; import org.junit.jupiter.api.*; @@ -13,6 +12,8 @@ @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class PutTest { + private static final String CLIENT_APP_NAME = "appName"; + @InjectMocks private SubmissionStoreImpl sut; @@ -26,13 +27,12 @@ public void setUp() { @DisplayName("CASE 1: with valid submission should store submission") public void withValidObjectShouldPut() { - DocumentProperties documentMetadata = new DocumentProperties(); - documentMetadata.setType("type"); - Submission submission = new Submission.Builder().documentProperties(documentMetadata).create(); + + Submission submission = new Submission.Builder().clientAppName(CLIENT_APP_NAME).create(); Optional actual = sut.put(submission); Assertions.assertTrue(actual.isPresent()); - Assertions.assertEquals("type", actual.get().getDocumentProperties().getType()); + Assertions.assertEquals(CLIENT_APP_NAME, actual.get().getClientAppName()); } diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/DeleteSubmissionTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/DeleteSubmissionTest.java new file mode 100644 index 0000000000..0179a19f78 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/DeleteSubmissionTest.java @@ -0,0 +1,134 @@ +package ca.bc.gov.open.jag.efilingapi.submission.submissionApiDelegateImpl; + +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingapi.error.InvalidUniversalException; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.GenerateUrlResponseMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingapi.submission.validator.GenerateUrlRequestValidator; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.math.BigDecimal; +import java.util.Optional; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; +import static ca.bc.gov.open.jag.efilingapi.TestHelpers.createDocumentList; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class DeleteSubmissionTest { + + private SubmissionApiDelegateImpl sut; + + @Mock + private SubmissionService submissionServiceMock; + + @Mock + private SubmissionStore submissionStoreMock; + + @Mock + private DocumentStore documentStoreMock; + + @Mock + private AccountService accountServiceMock; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + + @Mock + private GenerateUrlRequestValidator generateUrlRequestValidator; + + @Mock + private Jwt jwtMock; + + @BeforeEach + public void setUp() { + + MockitoAnnotations.openMocks(this); + + Mockito.doNothing().when(documentStoreMock).evict(Mockito.any(), Mockito.any()); + Mockito.doNothing().when(submissionStoreMock).evict(Mockito.any()); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + Submission submission = Submission + .builder() + .universalId(UUID.randomUUID().toString()) + .filingPackage(TestHelpers.createPackage(TestHelpers.createCourt(), createDocumentList(), TestHelpers.createPartyList(), TestHelpers.createOrganizationList())) + .create(); + + Mockito.when(submissionStoreMock.get(ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_1)))).thenReturn(Optional.of(submission)); + + + NavigationProperties navigationProperties = new NavigationProperties(); + FilingPackageMapper filingPackageMapper = new FilingPackageMapperImpl(); + sut = new SubmissionApiDelegateImpl(submissionServiceMock, accountServiceMock, new GenerateUrlResponseMapperImpl(), navigationProperties, submissionStoreMock, documentStoreMock, null, filingPackageMapper, generateUrlRequestValidator, null); + + } + + @Test + @DisplayName("200: should delete from submission") + public void withSubmissionIdAndTransactionIdShouldDeleteSubmission() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.deleteSubmission(TestHelpers.CASE_1, UUID.randomUUID()); + + Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); + + } + + @Test + @DisplayName("404: without submission should return not found") + public void withoutSubmissionShouldDeleteSubmission() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.deleteSubmission(TestHelpers.CASE_2, UUID.randomUUID()); + + Assertions.assertEquals(HttpStatus.NOT_FOUND, actual.getStatusCode()); + + } + + @Test + @DisplayName("403: with no universal id should throw InvalidUniversalException") + public void withUserNotHavingUniversalIdShouldThrowInvalidUniversalException() { + + + BigDecimal test = new BigDecimal(100000000); + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + InvalidUniversalException exception = Assertions.assertThrows(InvalidUniversalException.class, () -> sut.deleteSubmission(TestHelpers.CASE_2, UUID.randomUUID())); + Assertions.assertEquals(ErrorCode.INVALIDUNIVERSAL.toString(), exception.getErrorCode()); + + } + + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/GenerateUrlTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/GenerateUrlTest.java index df5931a2be..a31c7c7b13 100644 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/GenerateUrlTest.java +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/GenerateUrlTest.java @@ -1,85 +1,149 @@ package ca.bc.gov.open.jag.efilingapi.submission.submissionApiDelegateImpl; +import ca.bc.gov.open.clamav.starter.ClamAvService; +import ca.bc.gov.open.jag.efilingapi.Keys; import ca.bc.gov.open.jag.efilingapi.TestHelpers; -import ca.bc.gov.open.jag.efilingapi.api.model.EfilingError; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.CourtBase; import ca.bc.gov.open.jag.efilingapi.api.model.GenerateUrlRequest; import ca.bc.gov.open.jag.efilingapi.api.model.GenerateUrlResponse; +import ca.bc.gov.open.jag.efilingapi.api.model.InitialPackage; import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; -import ca.bc.gov.open.jag.efilingapi.error.ErrorResponse; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.error.*; import ca.bc.gov.open.jag.efilingapi.submission.SubmissionApiDelegateImpl; -import ca.bc.gov.open.jag.efilingapi.submission.mappers.GenerateUrlResponseMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapperImpl; import ca.bc.gov.open.jag.efilingapi.submission.mappers.GenerateUrlResponseMapperImpl; import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingapi.submission.validator.GenerateUrlRequestValidator; +import ca.bc.gov.open.jag.efilingapi.utils.Notification; import ca.bc.gov.open.jag.efilingcommons.exceptions.CSOHasMultipleAccountException; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingDocumentServiceException; import ca.bc.gov.open.jag.efilingcommons.exceptions.InvalidAccountStateException; import ca.bc.gov.open.jag.efilingcommons.exceptions.StoreException; import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; import javax.validation.Valid; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; @TestInstance(TestInstance.Lifecycle.PER_CLASS) @DisplayName("SubmissionApiDelegateImpl test suite") public class GenerateUrlTest { - private static final String HEADER = "test"; - private static final String URL = "http://doc"; - private static final String SUBTYPE = "subtype"; - private static final String TYPE = "type"; - private static final String SUCCESSURL = "http://success"; - private static final String CANCELURL = "http://cancel"; - private static final String ERRORURL = "http://error"; - + private static final String CODE = "CODE"; + private static final String CLIENT_APP_NAME = "clientAppName"; + private static final String USER_WITH_CSO_ACCOUNT = "1593769b-ac4b-43d9-9e81-38877eefcca5"; + private static final String USER_WITH_NO_CSO_ACCOUNT = "1593769b-ac4b-43d9-9e81-38877eefcca6"; private SubmissionApiDelegateImpl sut; @Mock private SubmissionService submissionServiceMock; - private GenerateUrlResponseMapper generateUrlResponseMapperMock; - @Mock private SubmissionStore submissionStoreMock; - @BeforeAll - public void setUp() { + @Mock + private DocumentStore documentStoreMock; + + @Mock + private AccountService accountServiceMock; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @Mock + private ClamAvService clamAvServiceMock; + private UUID transactionId = UUID.randomUUID(); + + @Mock + private GenerateUrlRequestValidator generateUrlRequestValidatorMock; - MockitoAnnotations.initMocks(this); + @BeforeEach + public void beforeEach() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + SecurityContextHolder.setContext(securityContextMock); NavigationProperties navigationProperties = new NavigationProperties(); navigationProperties.setBaseUrl("http://localhost"); - Submission submission = Submission.builder().expiryDate(10).create(); + Submission submission = Submission.builder().id(TestHelpers.CASE_1).transactionId(transactionId).expiryDate(10).create(); - Mockito.when(submissionServiceMock.generateFromRequest( - Mockito.eq(TestHelpers.CASE_1), - Mockito.any())) + Mockito.when(accountServiceMock.getCsoAccountDetails(Mockito.eq(USER_WITH_CSO_ACCOUNT))).thenReturn(TestHelpers.createCSOAccountDetails(true)); + Mockito.when(accountServiceMock.getCsoAccountDetails(Mockito.eq(USER_WITH_NO_CSO_ACCOUNT))).thenReturn(null); + + Mockito + .when(submissionServiceMock.generateFromRequest( + Mockito.any(), + ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_1)), + Mockito.any())) .thenReturn(submission); Mockito.doThrow(new CSOHasMultipleAccountException("CSOHasMultipleAccountException message")) .when(submissionServiceMock).generateFromRequest( - Mockito.eq(TestHelpers.CASE_2), + Mockito.any(), + ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_2)), Mockito.any()); Mockito.doThrow(new InvalidAccountStateException("InvalidAccountStateException message")) .when(submissionServiceMock).generateFromRequest( - Mockito.eq(TestHelpers.CASE_3), + Mockito.any(), + ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_3)), Mockito.any()); Mockito.doThrow(new StoreException("StoreException message")) - .when(submissionServiceMock).generateFromRequest(Mockito.eq(TestHelpers.CASE_4), + .when(submissionServiceMock).generateFromRequest( + Mockito.any(), + ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_4)), Mockito.any()); - // Testing the mapper part of this test - generateUrlResponseMapperMock = new GenerateUrlResponseMapperImpl(); + Mockito.doThrow(new EfilingDocumentServiceException("EfilingDocumentServiceException message")) + .when(submissionServiceMock).generateFromRequest( + Mockito.any(), + ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_5)), + Mockito.any()); + + Notification notification = new Notification(); + Mockito.doReturn(notification).when(generateUrlRequestValidatorMock) + .validate( + ArgumentMatchers.argThat(x -> x.getFilingPackage().getCourt().getLocation().equals("valid")), + Mockito.anyString(), Mockito.anyString()); + + Notification invalidNotification = new Notification(); + invalidNotification.addError("a random error"); + Mockito.doReturn(invalidNotification).when(generateUrlRequestValidatorMock).validate( + ArgumentMatchers.argThat(x -> x.getFilingPackage().getCourt().getLocation().equals("invalid")), + Mockito.anyString(), Mockito.anyString()); - sut = new SubmissionApiDelegateImpl(submissionServiceMock, generateUrlResponseMapperMock, navigationProperties, submissionStoreMock); + FilingPackageMapper filingPackageMapper = new FilingPackageMapperImpl(); + sut = new SubmissionApiDelegateImpl(submissionServiceMock, accountServiceMock, new GenerateUrlResponseMapperImpl(), navigationProperties, submissionStoreMock, documentStoreMock, clamAvServiceMock, filingPackageMapper, generateUrlRequestValidatorMock, null); + + Mockito.when(jwtMock.getClaim(Mockito.eq(Keys.CSO_APPLICATION_CLAIM_KEY))).thenReturn(CODE); } @@ -90,67 +154,185 @@ public void withValidRequestShouldGenerateUrl() { @Valid GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); - generateUrlRequest.setDocumentProperties(TestHelpers.createDocumentProperties(HEADER, URL, SUBTYPE, TYPE)); - generateUrlRequest.setNavigation(TestHelpers.createNavigation(SUCCESSURL, CANCELURL, ERRORURL)); + generateUrlRequest.setClientAppName(CLIENT_APP_NAME); + generateUrlRequest.setNavigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)); + generateUrlRequest.setNavigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)); + InitialPackage initialPackage = new InitialPackage(); + CourtBase court = new CourtBase(); + court.setLocation("valid"); + initialPackage.setCourt(court); + generateUrlRequest.setFilingPackage(initialPackage); + + ResponseEntity actual = sut.generateUrl(transactionId, USER_WITH_CSO_ACCOUNT.toString().replace("-", ""), TestHelpers.CASE_1, generateUrlRequest); + + Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); + Assertions.assertEquals("http://localhost?submissionId=" + TestHelpers.CASE_1.toString() + "&transactionId=" + transactionId, actual.getBody().getEfilingUrl()); + Assertions.assertNotNull(actual.getBody().getExpiryDate()); + + } + + + @Test + @DisplayName("200: with user having no CSO account should return a valid url") + public void withUserHavingNoCSOAccountShouldReturnValidUrl() { + + @Valid GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + + generateUrlRequest.setClientAppName(CLIENT_APP_NAME); + generateUrlRequest.setNavigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)); + generateUrlRequest.setNavigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)); + InitialPackage initialPackage = new InitialPackage(); + CourtBase court = new CourtBase(); + court.setLocation("valid"); + initialPackage.setCourt(court); + generateUrlRequest.setFilingPackage(initialPackage); - ResponseEntity actual = sut.generateUrl(TestHelpers.CASE_1, generateUrlRequest); + ResponseEntity actual = sut.generateUrl(transactionId, USER_WITH_NO_CSO_ACCOUNT.toString().replace("-", ""), TestHelpers.CASE_1, generateUrlRequest); Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); - Assertions.assertTrue(actual.getBody().getEfilingUrl().matches("http:\\/\\/localhost\\?submissionId=[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}")); + Assertions.assertEquals("http://localhost?submissionId=" + TestHelpers.CASE_1.toString() + "&transactionId=" + transactionId, actual.getBody().getEfilingUrl()); Assertions.assertNotNull(actual.getBody().getExpiryDate()); } + @Test + @DisplayName("400: with initialPackage validation failure should throw InvalidInitialSubmissionPayloadException") + public void whenInitialPackageValidationFailureShouldThrowInvalidInitialSubmissionPayloadException() { + + @Valid GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + + generateUrlRequest.setClientAppName(CLIENT_APP_NAME); + generateUrlRequest.setNavigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)); + InitialPackage initialPackage = new InitialPackage(); + CourtBase court = new CourtBase(); + court.setLocation("invalid"); + initialPackage.setCourt(court); + generateUrlRequest.setFilingPackage(initialPackage); + + InvalidInitialSubmissionPayloadException exception = Assertions.assertThrows(InvalidInitialSubmissionPayloadException.class, () -> sut.generateUrl(transactionId, USER_WITH_NO_CSO_ACCOUNT.toString().replace("-", ""), TestHelpers.CASE_1, generateUrlRequest)); + Assertions.assertEquals(ErrorCode.INVALID_INITIAL_SUBMISSION_PAYLOAD.toString(), exception.getErrorCode()); + } @Test - @DisplayName("400: when CSOHasMultipleAccountException should return Bad Request") - public void whenCSOHasMultipleAccountExceptionShouldReturnBadRequest() { + @DisplayName("400: when CSOHasMultipleAccountException should throw AccountException") + public void whenCSOHasMultipleAccountExceptionShouldThrowAccountException() { @Valid GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); - generateUrlRequest.setDocumentProperties(TestHelpers.createDocumentProperties(HEADER, URL, SUBTYPE, TYPE)); - generateUrlRequest.setNavigation(TestHelpers.createNavigation(SUCCESSURL, CANCELURL, ERRORURL)); + generateUrlRequest.setClientAppName(CLIENT_APP_NAME); + generateUrlRequest.setNavigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)); + InitialPackage initialPackage = new InitialPackage(); + CourtBase court = new CourtBase(); + court.setLocation("valid"); + initialPackage.setCourt(court); + generateUrlRequest.setFilingPackage(initialPackage); - ResponseEntity actual = sut.generateUrl(TestHelpers.CASE_2, generateUrlRequest); + AccountException exception = Assertions.assertThrows(AccountException.class, () -> sut.generateUrl(UUID.randomUUID(), UUID.randomUUID().toString().replace("-", ""), TestHelpers.CASE_2, generateUrlRequest)); + Assertions.assertEquals(ErrorCode.ACCOUNTEXCEPTION.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("403: when InvalidAccountStateException should throw InvalidRoleException") + public void whenInvalidAccountStateExceptionShouldThrowInvalidRoleException() { + @Valid GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); - EfilingError actualError = (EfilingError) actual.getBody(); + generateUrlRequest.setClientAppName(CLIENT_APP_NAME); + generateUrlRequest.setNavigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)); + InitialPackage initialPackage = new InitialPackage(); + CourtBase court = new CourtBase(); + court.setLocation("valid"); + initialPackage.setCourt(court); + generateUrlRequest.setFilingPackage(initialPackage); - Assertions.assertEquals(HttpStatus.BAD_REQUEST, actual.getStatusCode()); - Assertions.assertEquals(ErrorResponse.ACCOUNTEXCEPTION.getErrorCode(), actualError.getError()); - Assertions.assertEquals(ErrorResponse.ACCOUNTEXCEPTION.getErrorMessage(), actualError.getMessage()); + InvalidRoleException exception = Assertions.assertThrows(InvalidRoleException.class, () -> sut.generateUrl(UUID.randomUUID(), UUID.randomUUID().toString().replace("-", ""), TestHelpers.CASE_3, generateUrlRequest)); + Assertions.assertEquals(ErrorCode.INVALIDROLE.toString(), exception.getErrorCode()); } @Test - @DisplayName("403: when InvalidAccountStateException should return FORBIDDEN") - public void whenInvalidAccountStateExceptionShouldReturnForbidden() { + @DisplayName("403: when EFileRole not present should throw InvalidRoleException") + public void whenEFileRoleNotPresentShouldThrowInvalidRoleException() { @Valid GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); - generateUrlRequest.setDocumentProperties(TestHelpers.createDocumentProperties(HEADER, URL, SUBTYPE, TYPE)); - generateUrlRequest.setNavigation(TestHelpers.createNavigation(SUCCESSURL, CANCELURL, ERRORURL)); + Mockito.when(accountServiceMock.getCsoAccountDetails(any())).thenReturn(TestHelpers.createCSOAccountDetails(false)); - ResponseEntity actual = sut.generateUrl(TestHelpers.CASE_3, generateUrlRequest); + generateUrlRequest.setClientAppName(CLIENT_APP_NAME); + generateUrlRequest.setNavigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)); + InitialPackage initialPackage = new InitialPackage(); + CourtBase court = new CourtBase(); + court.setLocation("valid"); + initialPackage.setCourt(court); + generateUrlRequest.setFilingPackage(initialPackage); - EfilingError actualError = (EfilingError) actual.getBody(); + InvalidRoleException exception = Assertions.assertThrows(InvalidRoleException.class, () -> sut.generateUrl(transactionId, UUID.randomUUID().toString().replace("-", ""), TestHelpers.CASE_1, generateUrlRequest)); + Assertions.assertEquals(ErrorCode.INVALIDROLE.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("403: when Application Code is not present should throw MissingApplicationCodeException") + public void whenApplicationCodeNotPresentShouldThrowMissingApplicationCodeException() { + @Valid GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); - Assertions.assertEquals(HttpStatus.FORBIDDEN, actual.getStatusCode()); - Assertions.assertEquals(ErrorResponse.INVALIDROLE.getErrorCode(), actualError.getError()); - Assertions.assertEquals(ErrorResponse.INVALIDROLE.getErrorMessage(), actualError.getMessage()); + Mockito.when(jwtMock.getClaim(Mockito.eq(Keys.CSO_APPLICATION_CLAIM_KEY))).thenReturn(null); + + generateUrlRequest.setClientAppName(CLIENT_APP_NAME); + generateUrlRequest.setNavigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)); + InitialPackage initialPackage = new InitialPackage(); + CourtBase court = new CourtBase(); + court.setLocation("valid"); + initialPackage.setCourt(court); + generateUrlRequest.setFilingPackage(initialPackage); + + MissingApplicationCodeException exception = Assertions.assertThrows(MissingApplicationCodeException.class, () -> sut.generateUrl(transactionId, UUID.randomUUID().toString().replace("-", ""), TestHelpers.CASE_1, generateUrlRequest)); + Assertions.assertEquals(ErrorCode.MISSING_APPLICATION_CODE.toString(), exception.getErrorCode()); } @Test - @DisplayName("500: when StoreException should return INTERNAL SERVER ERROR") - public void whenStoreExceptionShouldReturnInternalServerError() { + @DisplayName("500: when StoreException should throw CacheException") + public void whenStoreExceptionShouldThrowCacheException() { @Valid GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); - generateUrlRequest.setDocumentProperties(TestHelpers.createDocumentProperties(HEADER, URL, SUBTYPE, TYPE)); - generateUrlRequest.setNavigation(TestHelpers.createNavigation(SUCCESSURL, CANCELURL, ERRORURL)); + generateUrlRequest.setClientAppName(CLIENT_APP_NAME); + generateUrlRequest.setNavigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)); + InitialPackage initialPackage = new InitialPackage(); + CourtBase court = new CourtBase(); + court.setLocation("valid"); + initialPackage.setCourt(court); + generateUrlRequest.setFilingPackage(initialPackage); - ResponseEntity actual = sut.generateUrl(TestHelpers.CASE_4, generateUrlRequest); + CacheException exception = Assertions.assertThrows(CacheException.class, () -> sut.generateUrl(UUID.randomUUID(), UUID.randomUUID().toString().replace("-", ""), TestHelpers.CASE_4, generateUrlRequest)); + Assertions.assertEquals(ErrorCode.CACHE_ERROR.toString(), exception.getErrorCode()); + } - EfilingError actualError = (EfilingError) actual.getBody(); + @Test + @DisplayName("500: when DocumentException should throw DocumentTypeException") + public void whenDocumentExceptionShouldThrowDocumentTypeException() { + @Valid GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + + generateUrlRequest.setClientAppName(CLIENT_APP_NAME); + generateUrlRequest.setNavigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)); + InitialPackage initialPackage = new InitialPackage(); + CourtBase court = new CourtBase(); + court.setLocation("valid"); + initialPackage.setCourt(court); + generateUrlRequest.setFilingPackage(initialPackage); - Assertions.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, actual.getStatusCode()); - Assertions.assertEquals(ErrorResponse.CACHE_ERROR.getErrorCode(), actualError.getError()); - Assertions.assertEquals(ErrorResponse.CACHE_ERROR.getErrorMessage(), actualError.getMessage()); + DocumentTypeException exception = Assertions.assertThrows(DocumentTypeException.class, () -> sut.generateUrl(UUID.randomUUID(), UUID.randomUUID().toString().replace("-", ""), TestHelpers.CASE_5, generateUrlRequest)); + Assertions.assertEquals(ErrorCode.DOCUMENT_TYPE_ERROR.toString(), exception.getErrorCode()); } + @Test + @DisplayName("403: with no user id it should throw InvalidUniversalException") + public void withNoUserIdShouldThrowInvalidUniversalException() { + @Valid GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + + generateUrlRequest.setClientAppName(CLIENT_APP_NAME); + generateUrlRequest.setNavigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)); + InitialPackage initialPackage = new InitialPackage(); + CourtBase court = new CourtBase(); + court.setLocation("valid"); + initialPackage.setCourt(court); + generateUrlRequest.setFilingPackage(initialPackage); + + InvalidUniversalException exception = Assertions.assertThrows(InvalidUniversalException.class, () -> sut.generateUrl(UUID.randomUUID(), " ", TestHelpers.CASE_5, generateUrlRequest)); + Assertions.assertEquals(ErrorCode.INVALIDUNIVERSAL.toString(), exception.getErrorCode()); + } } diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/GetPackageInformationTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/GetPackageInformationTest.java new file mode 100644 index 0000000000..33fa79a682 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/GetPackageInformationTest.java @@ -0,0 +1,160 @@ +package ca.bc.gov.open.jag.efilingapi.submission.submissionApiDelegateImpl; + +import ca.bc.gov.open.clamav.starter.ClamAvService; +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.SubmissionFilingPackage; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingapi.error.InvalidUniversalException; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.GenerateUrlResponseMapper; +import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingapi.submission.models.SubmissionConstants; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingapi.submission.validator.GenerateUrlRequestValidator; +import ca.bc.gov.open.jag.efilingcommons.model.Document; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.math.BigDecimal; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("SubmissionApiDelegateImpl test suite") +public class GetPackageInformationTest { + + private SubmissionApiDelegateImpl sut; + + @Mock + private SubmissionService submissionServiceMock; + + @Mock + private GenerateUrlResponseMapper generateUrlResponseMapperMock; + + @Mock + private SubmissionStore submissionStoreMock; + + @Mock + private DocumentStore documentStoreMock; + + @Mock + private AccountService accountServiceMock; + + @Mock + private ClamAvService clamAvServiceMock; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private GenerateUrlRequestValidator generateUrlRequestValidator; + + @Mock + private Jwt jwtMock; + + @BeforeEach + public void setUp() { + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + NavigationProperties navigationProperties = new NavigationProperties(); + navigationProperties.setBaseUrl("http://localhost"); + + Submission submissionWithParentApplication = Submission + .builder() + .filingPackage(TestHelpers.createPackage(TestHelpers.createCourt(), createDocumentListWithNulls(), TestHelpers.createPartyList(), TestHelpers.createOrganizationList())) + .create(); + + Mockito.when(submissionStoreMock.get(ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_1)))).thenReturn(Optional.of(submissionWithParentApplication)); + + Mockito.when(submissionServiceMock.isRushRequired(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(true); + + FilingPackageMapper filingPackageMapper = new FilingPackageMapperImpl(); + sut = new SubmissionApiDelegateImpl(submissionServiceMock, accountServiceMock, generateUrlResponseMapperMock, navigationProperties, submissionStoreMock, documentStoreMock, clamAvServiceMock, filingPackageMapper, generateUrlRequestValidator, null); + } + + @Test + @DisplayName("200: pass id and get values") + public void withCorrectIDReturnResult() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_1.toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getSubmissionFilingPackage(UUID.randomUUID(), TestHelpers.CASE_1); + assertEquals(HttpStatus.OK, actual.getStatusCode()); + Assertions.assertEquals(TestHelpers.DIVISION, actual.getBody().getCourt().getDivision()); + Assertions.assertEquals(TestHelpers.FILENUMBER, actual.getBody().getCourt().getFileNumber()); + Assertions.assertEquals(TestHelpers.LEVEL, actual.getBody().getCourt().getLevel()); + Assertions.assertEquals(TestHelpers.LOCATION, actual.getBody().getCourt().getLocation()); + Assertions.assertEquals(TestHelpers.PARTICIPATIONCLASS, actual.getBody().getCourt().getParticipatingClass()); + Assertions.assertEquals(TestHelpers.PROPERTYCLASS, actual.getBody().getCourt().getCourtClass()); + Assertions.assertEquals(TestHelpers.TYPE, actual.getBody().getDocuments().get(0).getType()); + Assertions.assertTrue(actual.getBody().getDocuments().get(0).getRushRequired()); + Assertions.assertEquals(TestHelpers.DESCRIPTION, actual.getBody().getDocuments().get(0).getDescription()); + Assertions.assertNull(actual.getBody().getDocuments().get(0).getIsAmendment()); + Assertions.assertNull(actual.getBody().getDocuments().get(0).getIsSupremeCourtScheduling()); + + } + + @Test + @DisplayName("404: with incorrect id return 404") + public void withInCorrectIDReturnNotFound() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getSubmissionFilingPackage(UUID.randomUUID(), TestHelpers.CASE_2); + assertEquals(HttpStatus.NOT_FOUND, actual.getStatusCode()); + } + + @Test + @DisplayName("404: with no universal id should throw InvalidUniversalException") + public void withInCorrectIDThrowInvalidUniversalException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + InvalidUniversalException exception = Assertions.assertThrows(InvalidUniversalException.class, () -> sut.getSubmissionFilingPackage(UUID.randomUUID(), TestHelpers.CASE_2)); + Assertions.assertEquals(ErrorCode.INVALIDUNIVERSAL.toString(), exception.getErrorCode()); + + } + + private List createDocumentListWithNulls() { + return Collections.singletonList(Document.builder() + .description(TestHelpers.DESCRIPTION) + .statutoryFeeAmount(BigDecimal.TEN) + .name("random.txt") + .type(TestHelpers.TYPE) + .subType(SubmissionConstants.SUBMISSION_ORDR_DOCUMENT_SUB_TYPE_CD) + .mimeType("application/txt") + .isSupremeCourtScheduling(null) + .isAmendment(null) + .data(new Object()).create()); + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/GetSubmissionDocumentTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/GetSubmissionDocumentTest.java new file mode 100644 index 0000000000..558588920a --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/GetSubmissionDocumentTest.java @@ -0,0 +1,121 @@ +package ca.bc.gov.open.jag.efilingapi.submission.submissionApiDelegateImpl; + +import ca.bc.gov.open.clamav.starter.ClamAvService; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingapi.error.InvalidUniversalException; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.GenerateUrlResponseMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingapi.submission.validator.GenerateUrlRequestValidator; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class GetSubmissionDocumentTest { + + public static final String CONTENT = "content"; + private SubmissionApiDelegateImpl sut; + + @Mock + private SubmissionService submissionServiceMock; + + @Mock + private SubmissionStore submissionStoreMock; + + @Mock + private DocumentStore documentStoreMock; + + @Mock + private AccountService accountServiceMock; + + @Mock + private ClamAvService clamAvServiceMock; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private GenerateUrlRequestValidator generateUrlRequestValidator; + + @Mock + private Jwt jwtMock; + + @BeforeAll + public void setUp() { + + MockitoAnnotations.initMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + NavigationProperties navigationProperties = new NavigationProperties(); + navigationProperties.setBaseUrl("http://localhost"); + + Mockito.when(documentStoreMock.get(Mockito.any(), Mockito.endsWith("test.txt"))).thenReturn(CONTENT.getBytes()); + + FilingPackageMapper filingPackageMapper = new FilingPackageMapperImpl(); + sut = new SubmissionApiDelegateImpl(submissionServiceMock, accountServiceMock, new GenerateUrlResponseMapperImpl(), navigationProperties, submissionStoreMock, documentStoreMock, clamAvServiceMock, filingPackageMapper, generateUrlRequestValidator, null); + + } + + + @Test + @DisplayName("200: when document in cache should return 200") + public void withDocumentInCacheShouldReturn200() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getSubmissionDocument(UUID.randomUUID(), UUID.randomUUID(), "test.txt"); + + Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); + + } + + @Test + @DisplayName("404: when document is missing should return 404") + public void withNoDocumentShouldReturn404() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getSubmissionDocument(UUID.randomUUID(), UUID.randomUUID(), "test2.txt"); + + Assertions.assertEquals(HttpStatus.NOT_FOUND, actual.getStatusCode()); + } + + @Test + @DisplayName("403: without universal id should throw InvalidUniversalException") + public void withNoUniversalIdShouldThrowInvalidUniversalException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + InvalidUniversalException exception = Assertions.assertThrows(InvalidUniversalException.class, () -> sut.getSubmissionDocument(UUID.randomUUID(), UUID.randomUUID(), "test2.txt")); + Assertions.assertEquals(ErrorCode.INVALIDUNIVERSAL.toString(), exception.getErrorCode()); + + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/GetSubmissionTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/GetSubmissionTest.java index 5a3a133db4..b42bf0dd83 100644 --- a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/GetSubmissionTest.java +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/GetSubmissionTest.java @@ -1,46 +1,53 @@ package ca.bc.gov.open.jag.efilingapi.submission.submissionApiDelegateImpl; +import ca.bc.gov.open.clamav.starter.ClamAvService; import ca.bc.gov.open.jag.efilingapi.TestHelpers; -import ca.bc.gov.open.jag.efilingapi.api.model.Account; -import ca.bc.gov.open.jag.efilingapi.api.model.GetSubmissionResponse; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.GetSubmissionConfigResponse; import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingapi.error.MissingUniversalIdException; import ca.bc.gov.open.jag.efilingapi.submission.SubmissionApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapperImpl; import ca.bc.gov.open.jag.efilingapi.submission.mappers.GenerateUrlResponseMapper; import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingapi.submission.validator.GenerateUrlRequestValidator; import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; +import ca.bc.gov.open.jag.efilingcommons.model.ServiceFees; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; import java.util.Optional; import java.util.UUID; +import static ca.bc.gov.open.jag.efilingapi.Keys.IDENTITY_PROVIDER_CLAIM_KEY; +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; @TestInstance(TestInstance.Lifecycle.PER_CLASS) @DisplayName("SubmissionApiDelegateImpl test suite") public class GetSubmissionTest { - private static final String SUCCESSURL = "http://success"; - private static final String CANCELURL = "http://cancel"; - private static final String ERRORURL = "http://error"; - private static final UUID CASE_1 = UUID.fromString("77da92db-0791-491e-8c58-1a969e67d2fe"); - private static final UUID CASE_2 = UUID.fromString("77da92db-0791-491e-8c58-1a969e67d2fa"); - private static final UUID CASE_3 = UUID.fromString("77da92db-0791-491e-8c58-1a969e67d2fb"); - private static final String EMAIL = "email"; - private static final String FIRST_NAME = "firstName"; - private static final String LAST_NAME = "lastName"; - private static final String MIDDLE_NAME = "middleName"; + private static final String SERVICE_TYPE_CD = "DCFL"; + private static final String SERVICE_TYPE_CD1 = "NOTDCFL"; + private static final String INTERNAL_CLIENT_NUMBER = "123"; + private static final String IDENTITY_PROVIDER = "identity_provider_alias"; private SubmissionApiDelegateImpl sut; @@ -53,45 +60,92 @@ public class GetSubmissionTest { @Mock private SubmissionStore submissionStoreMock; + @Mock + private DocumentStore documentStoreMock; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @Mock + private AccountService accountServiceMock; + + @Mock + private ClamAvService clamAvServiceMock; + + @Mock + private GenerateUrlRequestValidator generateUrlRequestValidator; + @BeforeAll - public void setUp() { + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); - MockitoAnnotations.initMocks(this); + SecurityContextHolder.setContext(securityContextMock); NavigationProperties navigationProperties = new NavigationProperties(); navigationProperties.setBaseUrl("http://localhost"); - Submission submissionWithCsoAccount = Submission .builder() - .accountDetails( - AccountDetails - .builder() - .accountId(BigDecimal.TEN) - .firstName(FIRST_NAME + CASE_2) - .lastName(LAST_NAME + CASE_2) - .middleName(MIDDLE_NAME + CASE_2) - .fileRolePresent(true) - .email(EMAIL + CASE_2).create()) - .navigation(TestHelpers.createNavigation(SUCCESSURL, CANCELURL, ERRORURL)) + .clientAppName(TestHelpers.DESCRIPTION) + .navigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)) .create(); - Mockito.when(submissionStoreMock.getByKey(CASE_2)).thenReturn(Optional.of(submissionWithCsoAccount)); + Mockito + .doReturn(Optional.of(submissionWithCsoAccount)) + .when(submissionStoreMock) + .get(ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_2))); Submission submissionWithoutCsoAccount = Submission .builder() - .navigation(TestHelpers.createNavigation(SUCCESSURL, CANCELURL, ERRORURL)) + .navigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)) .create(); - Mockito.when(submissionStoreMock.getByKey(CASE_3)).thenReturn(Optional.of(submissionWithoutCsoAccount)); + Mockito + .doReturn(Optional.of(submissionWithoutCsoAccount)) + .when(submissionStoreMock) + .get(ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_3))); + + Mockito + .doReturn(Optional.of(submissionWithoutCsoAccount)) + .when(submissionStoreMock) + .get(ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_4))); + - sut = new SubmissionApiDelegateImpl(submissionServiceMock, generateUrlResponseMapperMock, navigationProperties, submissionStoreMock); + Mockito.when(accountServiceMock.getCsoAccountDetails(Mockito.eq(TestHelpers.CASE_2_STRING))) + .thenReturn(AccountDetails + .builder() + .clientId(BigDecimal.TEN) + .internalClientNumber(INTERNAL_CLIENT_NUMBER) + .universalId(TestHelpers.CASE_2_STRING) + .accountId(BigDecimal.TEN) + .fileRolePresent(true) + .cardRegistered(true) + .create()); + + FilingPackageMapper filingPackageMapper = new FilingPackageMapperImpl(); + sut = new SubmissionApiDelegateImpl(submissionServiceMock, accountServiceMock, generateUrlResponseMapperMock, navigationProperties, submissionStoreMock, documentStoreMock, clamAvServiceMock, filingPackageMapper, generateUrlRequestValidator, null); } @Test @DisplayName("404: With null redis storage response return NotFound") public void withNullRedisStorageResponseReturnNotFound() { - ResponseEntity actual = sut.getSubmission(CASE_1); + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + + ResponseEntity actual = sut.getSubmissionConfig( + UUID.randomUUID(), + TestHelpers.CASE_1); assertEquals(HttpStatus.NOT_FOUND, actual.getStatusCode()); } @@ -99,34 +153,72 @@ public void withNullRedisStorageResponseReturnNotFound() { @DisplayName("200: With user having cso account and efiling role return submission details") public void withUserHavingCsoAccountShouldReturnUserDetailsAndAccount() { - ResponseEntity actual = sut.getSubmission(CASE_2); + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(TestHelpers.CASE_2.toString()); + Mockito.when(jwtMock.getClaim(Mockito.eq(IDENTITY_PROVIDER_CLAIM_KEY))).thenReturn(IDENTITY_PROVIDER); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + + ResponseEntity actual = sut.getSubmissionConfig(UUID.fromString( + TestHelpers.CASE_2_STRING), + TestHelpers.CASE_2); assertEquals(HttpStatus.OK, actual.getStatusCode()); - assertEquals(EMAIL + CASE_2, actual.getBody().getUserDetails().getEmail()); - assertEquals(FIRST_NAME + CASE_2, actual.getBody().getUserDetails().getFirstName()); - assertEquals(LAST_NAME + CASE_2, actual.getBody().getUserDetails().getLastName()); - assertEquals(MIDDLE_NAME + CASE_2, actual.getBody().getUserDetails().getMiddleName()); - assertEquals(1, actual.getBody().getUserDetails().getAccounts().size()); - assertEquals(Account.TypeEnum.CSO, actual.getBody().getUserDetails().getAccounts().stream().findFirst().get().getType()); - assertEquals("10", actual.getBody().getUserDetails().getAccounts().stream().findFirst().get().getIdentifier()); - assertEquals(SUCCESSURL, actual.getBody().getNavigation().getSuccess().getUrl()); - assertEquals(CANCELURL, actual.getBody().getNavigation().getCancel().getUrl()); - assertEquals(ERRORURL, actual.getBody().getNavigation().getError().getUrl()); + assertEquals(TestHelpers.SUCCESS_URL, actual.getBody().getNavigationUrls().getSuccess()); + assertEquals(TestHelpers.CANCEL_URL, actual.getBody().getNavigationUrls().getCancel()); + assertEquals(TestHelpers.ERROR_URL, actual.getBody().getNavigationUrls().getError()); + assertEquals(TestHelpers.DESCRIPTION, actual.getBody().getClientAppName()); + } @Test @DisplayName("200: With user not having cso account") public void withUserHavingNoCsoAccountShouldReturnUserDetailsButNoAccount() { - ResponseEntity actual = sut.getSubmission(CASE_3); + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getSubmissionConfig( + TestHelpers.CASE_3, + UUID.randomUUID()); assertEquals(HttpStatus.OK, actual.getStatusCode()); - assertEquals(EMAIL, actual.getBody().getUserDetails().getEmail()); - assertEquals(FIRST_NAME, actual.getBody().getUserDetails().getFirstName()); - assertEquals(LAST_NAME, actual.getBody().getUserDetails().getLastName()); - assertEquals(MIDDLE_NAME, actual.getBody().getUserDetails().getMiddleName()); - assertNull(actual.getBody().getUserDetails().getAccounts()); - assertEquals(SUCCESSURL, actual.getBody().getNavigation().getSuccess().getUrl()); - assertEquals(CANCELURL, actual.getBody().getNavigation().getCancel().getUrl()); - assertEquals(ERRORURL, actual.getBody().getNavigation().getError().getUrl()); + assertEquals(TestHelpers.SUCCESS_URL, actual.getBody().getNavigationUrls().getSuccess()); + assertEquals(TestHelpers.CANCEL_URL, actual.getBody().getNavigationUrls().getCancel()); + assertEquals(TestHelpers.ERROR_URL, actual.getBody().getNavigationUrls().getError()); + + } + + @Test + @DisplayName("200: With user not having account details present") + public void withUserHavingNoAccountDetailsShouldReturnUserDetailsButNoAccount() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.getSubmissionConfig( + TestHelpers.CASE_4, + UUID.randomUUID()); + assertEquals(HttpStatus.OK, actual.getStatusCode()); + assertEquals(TestHelpers.SUCCESS_URL, actual.getBody().getNavigationUrls().getSuccess()); + assertEquals(TestHelpers.CANCEL_URL, actual.getBody().getNavigationUrls().getCancel()); + assertEquals(TestHelpers.ERROR_URL, actual.getBody().getNavigationUrls().getError()); + + } + + @Test + @DisplayName("403: With user not having universal id claim should throw MissingUniversalIdException") + public void withUserNotHavingUniversalIdShouldThrowMissingUniversalIdException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + MissingUniversalIdException exception = Assertions.assertThrows(MissingUniversalIdException.class, () -> sut.getSubmissionConfig(UUID.randomUUID(), TestHelpers.CASE_5)); + Assertions.assertEquals(ErrorCode.MISSING_UNIVERSAL_ID.toString(), exception.getErrorCode()); + Assertions.assertEquals("universal-id claim missing in jwt token.", exception.getMessage()); + } + + private List createFees() { + ServiceFees fee1 = new ServiceFees(BigDecimal.TEN, SERVICE_TYPE_CD); + ServiceFees fee2 = new ServiceFees(BigDecimal.ONE, SERVICE_TYPE_CD1); + return Arrays.asList(fee1, fee2); } } diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/PostRushProcessingTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/PostRushProcessingTest.java new file mode 100644 index 0000000000..32e878ad12 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/PostRushProcessingTest.java @@ -0,0 +1,156 @@ +package ca.bc.gov.open.jag.efilingapi.submission.submissionApiDelegateImpl; + +import ca.bc.gov.open.clamav.starter.ClamAvService; +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.Rush; +import ca.bc.gov.open.jag.efilingapi.api.model.RushDocument; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingapi.error.InvalidUniversalException; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.GenerateUrlResponseMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.RushProcessingMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingapi.submission.validator.GenerateUrlRequestValidator; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.util.Arrays; +import java.util.Optional; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; + + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class PostRushProcessingTest { + + private static final String FILE_PDF = "file.pdf"; + private static final String COUNTRY = "COUNTRY"; + private static final String COUNTRY_CODE = "CD"; + private static final String FIRST_NAME = "FIRSTNAME"; + private static final String LAST_NAME = "LASTNAME"; + private static final String ORGANIZATION = "ORGANIZATION"; + private static final String REASON = "REASON"; + private static final String PHONE_NUMBER = "1231231234"; + private static final String DATE = "2001-11-26T12:00:00Z"; + private SubmissionApiDelegateImpl sut; + + @Mock + private SubmissionService submissionServiceMock; + + @Mock + private SubmissionStore submissionStoreMock; + + @Mock + private GenerateUrlResponseMapper generateUrlResponseMapperMock; + + @Mock + private NavigationProperties navigationProperties; + + @Mock + private DocumentStore documentStoreMock; + + @Mock + private AccountService accountServiceMock; + + @Mock + private ClamAvService clamAvServiceMock; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @Mock + private GenerateUrlRequestValidator generateUrlRequestValidator; + + @BeforeEach + public void setUp() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + FilingPackageMapper filingPackageMapper = new FilingPackageMapperImpl(); + sut = new SubmissionApiDelegateImpl(submissionServiceMock, accountServiceMock, generateUrlResponseMapperMock, navigationProperties, submissionStoreMock, documentStoreMock, clamAvServiceMock, filingPackageMapper, generateUrlRequestValidator, new RushProcessingMapperImpl()); + + } + + @Test + @DisplayName("201") + public void withValidParamtersReturnDocumentProperties() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + Submission submission = TestHelpers.buildSubmission(); + + Mockito.when(submissionStoreMock.get(Mockito.any())).thenReturn(Optional.of(submission)); + + Rush rush = new Rush(); + rush.setCountry(COUNTRY); + rush.setCourtDate(DATE); + rush.setCountryCode(COUNTRY_CODE); + rush.setFirstName(FIRST_NAME); + rush.setLastName(LAST_NAME); + rush.setOrganization(ORGANIZATION); + rush.setPhoneNumber(PHONE_NUMBER); + rush.setReason(REASON); + RushDocument document = new RushDocument(); + document.setFileName(FILE_PDF); + rush.setSupportingDocuments(Arrays.asList(document)); + + ResponseEntity actual = sut.postRushProcessing(TestHelpers.CASE_1, UUID.randomUUID(), rush); + + Assertions.assertEquals(HttpStatus.CREATED, actual.getStatusCode()); + + } + + @Test + @DisplayName("404") + public void withNoSubmissionReturnNotFound() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.postRushProcessing(TestHelpers.CASE_2, UUID.randomUUID(), null); + + Assertions.assertEquals(HttpStatus.NOT_FOUND, actual.getStatusCode()); + + } + + + @Test + @DisplayName("403: with no universal id should throw InvalidUniversalException") + public void withUserNotHavingUniversalIdShouldThrowInvalidUniversalException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + InvalidUniversalException exception = Assertions.assertThrows(InvalidUniversalException.class, () -> sut.postRushProcessing(TestHelpers.CASE_2, UUID.randomUUID(), null)); + Assertions.assertEquals(ErrorCode.INVALIDUNIVERSAL.toString(), exception.getErrorCode()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/SubmitTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/SubmitTest.java new file mode 100644 index 0000000000..69e72fb290 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/SubmitTest.java @@ -0,0 +1,235 @@ +package ca.bc.gov.open.jag.efilingapi.submission.submissionApiDelegateImpl; + +import ca.bc.gov.open.clamav.starter.ClamAvService; +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.SubmitResponse; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingapi.error.InvalidUniversalException; +import ca.bc.gov.open.jag.efilingapi.error.PaymentException; +import ca.bc.gov.open.jag.efilingapi.error.SubmissionException; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.GenerateUrlResponseMapper; +import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingapi.submission.validator.GenerateUrlRequestValidator; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingPaymentException; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingSubmissionServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.RushProcessing; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Optional; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("SubmissionApiDelegateImpl test suite") +public class SubmitTest { + private SubmissionApiDelegateImpl sut; + + @Mock + private SubmissionService submissionServiceMock; + + @Mock + private GenerateUrlResponseMapper generateUrlResponseMapperMock; + + @Mock + private NavigationProperties navigationPropertiesMock; + + @Mock + private SubmissionStore submissionStoreMock; + + @Mock + private DocumentStore documentStoreMock; + + @Mock + private AccountService accountServiceMock; + + @Mock + private ClamAvService clamAvServiceMock; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private GenerateUrlRequestValidator generateUrlRequestValidator; + + @Mock + private Jwt jwtMock; + + @BeforeAll + public void setUp() { + + MockitoAnnotations.openMocks(this); + + Submission submissionExists = Submission + .builder() + .id(TestHelpers.CASE_1) + .navigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)) + .create(); + + Mockito + .doReturn(Optional.of(submissionExists)) + .when(submissionStoreMock).get(ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_1))); + + Submission submissionError = Submission + .builder() + .id(TestHelpers.CASE_2) + .navigationUrls(TestHelpers.createNavigation(null, null, null)) + .filingPackage( + FilingPackage.builder() + .rush(RushProcessing.builder() + .courtDate("2001-11-26T12:00:00Z") + .create()) + .create() + ) + .create(); + + Submission submissionPaymentError = Submission + .builder() + .id(TestHelpers.CASE_4) + .navigationUrls(TestHelpers.createNavigation(null, null, null)) + .create(); + + Mockito + .doReturn(Optional.of(submissionError)) + .when(submissionStoreMock) + .get(ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_2))); + + Mockito + .doReturn(Optional.of(submissionPaymentError)) + .when(submissionStoreMock) + .get(ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_4))); + + SubmitResponse result = new SubmitResponse(); + result.setPackageRef("packageref"); + + Mockito + .when(submissionServiceMock.createSubmission(Mockito.refEq(submissionExists), Mockito.any(), Mockito.any())) + .thenReturn(result); + + Mockito.doThrow(EfilingSubmissionServiceException.class).when(submissionServiceMock).createSubmission(ArgumentMatchers.argThat(x -> x.getId().equals(TestHelpers.CASE_2)), Mockito.any(), Mockito.any()); + Mockito.doThrow(EfilingPaymentException.class).when(submissionServiceMock).createSubmission(ArgumentMatchers.argThat(x -> x.getId().equals(TestHelpers.CASE_4)), Mockito.any(), Mockito.any()); + + FilingPackageMapper filingPackageMapper = new FilingPackageMapperImpl(); + sut = new SubmissionApiDelegateImpl(submissionServiceMock, accountServiceMock, generateUrlResponseMapperMock, navigationPropertiesMock, submissionStoreMock, documentStoreMock, clamAvServiceMock, filingPackageMapper, generateUrlRequestValidator, null); + + } + + @Test + @DisplayName("201: With valid request should return created and service id not early adopter") + public void withUserHavingValidRequestShouldReturnCreated() { + GrantedAuthority grantedAuthority = new GrantedAuthority() { + @Override + public String getAuthority() { + return "early-adopters"; + } + }; + + Collection collection = new HashSet(); + collection.add(grantedAuthority); + Mockito.when(authenticationMock.getAuthorities()).thenReturn(collection); + Mockito.when(jwtMock.getClaim(Mockito.any())).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + ResponseEntity actual = sut.submit(UUID.randomUUID(), TestHelpers.CASE_1, null); + assertEquals(HttpStatus.CREATED, actual.getStatusCode()); + assertEquals("packageref", actual.getBody().getPackageRef()); + + } + + @Test + @DisplayName("201: With valid request should return created and service id early adopter") + public void withUserHavingValidRequestEarlyAdopterShouldReturnCreated() { + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + Mockito.when(jwtMock.getClaim(Mockito.any())).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + SecurityContextHolder.setContext(securityContextMock); + + ResponseEntity actual = sut.submit(UUID.randomUUID(), TestHelpers.CASE_1, null); + assertEquals(HttpStatus.CREATED, actual.getStatusCode()); + assertEquals("packageref", actual.getBody().getPackageRef()); + + } + + @Test + @DisplayName("500: with valid request but soap service throws an exception should throw SubmissionException") + public void withErrorInServiceShouldThrowSubmissionException() { + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + Mockito.when(jwtMock.getClaim(Mockito.any())).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + SecurityContextHolder.setContext(securityContextMock); + + SubmissionException exception = Assertions.assertThrows(SubmissionException.class, () -> sut.submit(UUID.randomUUID(), TestHelpers.CASE_2, null)); + Assertions.assertEquals(ErrorCode.SUBMISSION_FAILURE.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("400: with valid request but bambora is thrown and caught should throw PaymentException") + public void withErrorInBamboraShouldThrowPaymentException() { + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + Mockito.when(jwtMock.getClaim(Mockito.any())).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + SecurityContextHolder.setContext(securityContextMock); + + PaymentException exception = Assertions.assertThrows(PaymentException.class, () -> sut.submit(UUID.randomUUID(), TestHelpers.CASE_4, null)); + Assertions.assertEquals(ErrorCode.PAYMENT_FAILURE.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("404: with submission request that does not exist 404 should be returned") + public void withSubmissionRequestThatDoesNotExist() { + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + Mockito.when(jwtMock.getClaim(Mockito.any())).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + SecurityContextHolder.setContext(securityContextMock); + + ResponseEntity actual = sut.submit(UUID.randomUUID(), TestHelpers.CASE_3, null); + assertEquals(HttpStatus.NOT_FOUND, actual.getStatusCode()); + + } + + @Test + @DisplayName("403: with no universal id should throw InvalidUniversalException") + public void withUserNotHavingUniversalIdShouldThrowInvalidUniversalException() { + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + Mockito.when(jwtMock.getClaim(Mockito.any())).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + SecurityContextHolder.setContext(securityContextMock); + + InvalidUniversalException exception = Assertions.assertThrows(InvalidUniversalException.class, () -> sut.submit(UUID.randomUUID(), TestHelpers.CASE_3, null)); + Assertions.assertEquals(ErrorCode.INVALIDUNIVERSAL.toString(), exception.getErrorCode()); + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/UpdateDocumentPropertiesTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/UpdateDocumentPropertiesTest.java new file mode 100644 index 0000000000..474ded2424 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/UpdateDocumentPropertiesTest.java @@ -0,0 +1,191 @@ +package ca.bc.gov.open.jag.efilingapi.submission.submissionApiDelegateImpl; + +import ca.bc.gov.open.clamav.starter.ClamAvService; +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.DocumentProperties; +import ca.bc.gov.open.jag.efilingapi.api.model.UpdateDocumentRequest; +import ca.bc.gov.open.jag.efilingapi.api.model.UpdateDocumentResponse; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.error.DocumentRequiredException; +import ca.bc.gov.open.jag.efilingapi.error.DocumentTypeException; +import ca.bc.gov.open.jag.efilingapi.error.ErrorCode; +import ca.bc.gov.open.jag.efilingapi.error.InvalidUniversalException; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.GenerateUrlResponseMapper; +import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingapi.submission.validator.GenerateUrlRequestValidator; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingDocumentServiceException; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Optional; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Upload Additional Submission Documents Test Suite") +public class UpdateDocumentPropertiesTest { + + private SubmissionApiDelegateImpl sut; + + @Mock + private SubmissionService submissionServiceMock; + + @Mock + private SubmissionStore submissionStoreMock; + + @Mock + private GenerateUrlResponseMapper generateUrlResponseMapperMock; + + @Mock + private NavigationProperties navigationProperties; + + @Mock + private DocumentStore documentStoreMock; + + @Mock + private AccountService accountServiceMock; + + @Mock + private ClamAvService clamAvServiceMock; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private GenerateUrlRequestValidator generateUrlRequestValidator; + + @Mock + private Jwt jwtMock; + + @BeforeEach + public void setUp() throws IOException { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + Submission submission = TestHelpers.buildSubmission(); + + Mockito.when(submissionStoreMock.get(ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_1)))).thenReturn(Optional.of(submission)); + + + FilingPackageMapper filingPackageMapper = new FilingPackageMapperImpl(); + sut = new SubmissionApiDelegateImpl(submissionServiceMock, accountServiceMock, generateUrlResponseMapperMock, navigationProperties, submissionStoreMock, documentStoreMock, clamAvServiceMock, filingPackageMapper, generateUrlRequestValidator, null); + + } + + @Test + @DisplayName("200") + public void withValidParamtersReturnDocumentProperties() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + UpdateDocumentRequest updateDocumentRequest = new UpdateDocumentRequest(); + DocumentProperties documentProperties = new DocumentProperties(); + documentProperties.setType("AAB"); + documentProperties.setName("test.txt"); + documentProperties.setIsAmendment(true); + documentProperties.setIsSupremeCourtScheduling(true); + updateDocumentRequest.addDocumentsItem(documentProperties); + + Mockito.when(submissionServiceMock.updateDocuments(any(), Mockito.refEq(updateDocumentRequest), Mockito.any())).thenReturn(Submission + .builder() + .filingPackage(TestHelpers.createPackage(TestHelpers.createCourt(), TestHelpers.createDocumentList(), TestHelpers.createPartyList(), TestHelpers.createOrganizationList())) + .navigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)) + .create()); + + ResponseEntity actual = sut.updateDocumentProperties(TestHelpers.CASE_1, UUID.randomUUID(), updateDocumentRequest); + + Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); + Assertions.assertEquals(1, actual.getBody().getDocuments().size()); + Assertions.assertEquals(TestHelpers.DESCRIPTION, actual.getBody().getDocuments().get(0).getDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getBody().getDocuments().get(0).getStatutoryFeeAmount()); + Assertions.assertEquals(true, actual.getBody().getDocuments().get(0).getIsSupremeCourtScheduling()); + Assertions.assertEquals(true, actual.getBody().getDocuments().get(0).getIsAmendment()); + } + + @Test + @DisplayName("400: with invalid parameters should throw DocumentRequiredException") + public void withInValidParamtersShouldThrowDocumentRequiredException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + DocumentRequiredException exception = Assertions.assertThrows(DocumentRequiredException.class, () -> sut.updateDocumentProperties(TestHelpers.CASE_1, UUID.randomUUID(), null)); + Assertions.assertEquals(ErrorCode.DOCUMENT_REQUIRED.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("500: with exception thrown from Soap should throw DocumentTypeException") + public void withExceptionThrownFromSoapShouldThrowDocumentTypeException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + UpdateDocumentRequest errorDocumentRequest = new UpdateDocumentRequest(); + errorDocumentRequest.addDocumentsItem(new DocumentProperties()); + + Mockito.when(submissionServiceMock.updateDocuments(any(), Mockito.refEq(errorDocumentRequest), Mockito.any())).thenThrow(new EfilingDocumentServiceException("NOOOOOOO")); + + DocumentTypeException exception = Assertions.assertThrows(DocumentTypeException.class, () -> sut.updateDocumentProperties(TestHelpers.CASE_1, UUID.randomUUID(), errorDocumentRequest)); + Assertions.assertEquals(ErrorCode.DOCUMENT_TYPE_ERROR.toString(), exception.getErrorCode()); + } + + + @Test + @DisplayName("404") + public void withNoSubmissionReturnNotFound() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + UpdateDocumentRequest updateDocumentRequest = new UpdateDocumentRequest(); + updateDocumentRequest.addDocumentsItem(new DocumentProperties()); + ResponseEntity actual = sut.updateDocumentProperties(TestHelpers.CASE_2, UUID.randomUUID(), updateDocumentRequest); + + Assertions.assertEquals(HttpStatus.NOT_FOUND, actual.getStatusCode()); + } + + + @Test + @DisplayName("403: with no universal id should throw InvalidUniversalException") + public void withUserNotHavingUniversalIdShouldThrowInvalidUniversalException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + UpdateDocumentRequest updateDocumentRequest = new UpdateDocumentRequest(); + updateDocumentRequest.addDocumentsItem(new DocumentProperties()); + + InvalidUniversalException exception = Assertions.assertThrows(InvalidUniversalException.class, () -> sut.updateDocumentProperties(TestHelpers.CASE_2, UUID.randomUUID(), updateDocumentRequest)); + Assertions.assertEquals(ErrorCode.INVALIDUNIVERSAL.toString(), exception.getErrorCode()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/UploadAdditionalSubmissionDocumentsTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/UploadAdditionalSubmissionDocumentsTest.java new file mode 100644 index 0000000000..0930ff78b9 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/UploadAdditionalSubmissionDocumentsTest.java @@ -0,0 +1,255 @@ +package ca.bc.gov.open.jag.efilingapi.submission.submissionApiDelegateImpl; + +import ca.bc.gov.open.clamav.starter.ClamAvService; +import ca.bc.gov.open.clamav.starter.VirusDetectedException; +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.UploadSubmissionDocumentsResponse; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.error.*; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.GenerateUrlResponseMapper; +import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingapi.submission.validator.GenerateUrlRequestValidator; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Upload Additional Submission Documents Test Suite") +public class UploadAdditionalSubmissionDocumentsTest { + + private SubmissionApiDelegateImpl sut; + + @Mock + private SubmissionService submissionServiceMock; + + @Mock + private SubmissionStore submissionStoreMock; + + @Mock + private GenerateUrlResponseMapper generateUrlResponseMapperMock; + + @Mock + private NavigationProperties navigationProperties; + + @Mock + private MultipartFile multipartFileMock; + + @Mock + private DocumentStore documentStoreMock; + + @Mock + private Resource resourceMock; + + @Mock + private AccountService accountServiceMock; + + @Mock + private ClamAvService clamAvServiceMock; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @Mock + private GenerateUrlRequestValidator generateUrlRequestValidator; + + @BeforeAll + public void setUp() throws IOException { + MockitoAnnotations.initMocks(this); + + Mockito.when(resourceMock.getFilename()).thenReturn("file.txt"); + Mockito.when(multipartFileMock.getResource()).thenReturn(resourceMock); + Mockito.when(multipartFileMock.getBytes()).thenThrow(new IOException("random")); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + + Submission submission = Submission + .builder() + .navigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)) + .create(); + + Mockito.when(submissionStoreMock.get(ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_1)))).thenReturn(Optional.of(submission)); + + FilingPackageMapper filingPackageMapper = new FilingPackageMapperImpl(); + sut = new SubmissionApiDelegateImpl(submissionServiceMock, accountServiceMock, generateUrlResponseMapperMock, navigationProperties, submissionStoreMock, documentStoreMock, clamAvServiceMock, filingPackageMapper, generateUrlRequestValidator, null); + + } + + @Test + @DisplayName("200: with pdf files should return ok") + public void withPdfFilesShouldReturnOk() throws IOException, VirusDetectedException { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + File file = new File("src/test/resources/test.pdf"); + + List files = new ArrayList<>(); + MultipartFile multipartFile = new MockMultipartFile("test.pdf", new FileInputStream(file)); + + files.add(multipartFile); + files.add(multipartFile); + + Mockito.doNothing().when(clamAvServiceMock).scan(any()); + + ResponseEntity actual = sut.uploadAdditionalSubmissionDocuments(TestHelpers.CASE_1, UUID.randomUUID(), files); + + Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); + Assertions.assertEquals(TestHelpers.CASE_1, actual.getBody().getSubmissionId()); + Assertions.assertEquals(new BigDecimal(2), actual.getBody().getReceived()); + + } + + @Test + @DisplayName("400: with non pdf files should throw FileTypeException") + public void withNonPdfFilesShouldThrowFileTypeException() throws IOException, VirusDetectedException { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + File file = new File("src/test/resources/test.txt"); + + List files = new ArrayList<>(); + MultipartFile multipartFile = new MockMultipartFile("test.txt", new FileInputStream(file)); + files.add(multipartFile); + files.add(multipartFile); + + Mockito.doNothing().when(clamAvServiceMock).scan(any()); + + FileTypeException exception = Assertions.assertThrows(FileTypeException.class, () -> sut.uploadAdditionalSubmissionDocuments(TestHelpers.CASE_1, UUID.randomUUID(), files)); + Assertions.assertEquals(ErrorCode.FILE_TYPE_ERROR.toString(), exception.getErrorCode()); + + } + + @Test + @DisplayName("400: with empty files should throw DocumentRequiredException") + public void withEmptyFilesShouldThrowDocumentRequiredException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + List files = new ArrayList<>(); + DocumentRequiredException exception = Assertions.assertThrows(DocumentRequiredException.class, () -> sut.uploadAdditionalSubmissionDocuments(TestHelpers.CASE_1, UUID.randomUUID(), files)); + Assertions.assertEquals(ErrorCode.DOCUMENT_REQUIRED.toString(), exception.getErrorCode()); + + } + + + @Test + @DisplayName("400: with null files should throw DocumentRequiredException") + public void withNullFilesShouldThrowDocumentRequiredException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + DocumentRequiredException exception = Assertions.assertThrows(DocumentRequiredException.class, () -> sut.uploadAdditionalSubmissionDocuments(TestHelpers.CASE_1, UUID.randomUUID(), null)); + Assertions.assertEquals(ErrorCode.DOCUMENT_REQUIRED.toString(), exception.getErrorCode()); + + } + + @Test + @DisplayName("404: with no submission present should return not found") + public void withNoSubmissionReturnNotFound() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.uploadAdditionalSubmissionDocuments(TestHelpers.CASE_2, UUID.randomUUID(), null); + + Assertions.assertEquals(HttpStatus.NOT_FOUND, actual.getStatusCode()); + + } + + @Test + @DisplayName("500: with ioException should return 500") + public void withIoExceptionShouldReturnInternalServerError() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + List files = new ArrayList<>(); + files.add(multipartFileMock); + + DocumentStorageException exception = Assertions.assertThrows(DocumentStorageException.class, () -> sut.uploadAdditionalSubmissionDocuments(TestHelpers.CASE_1, UUID.randomUUID(), files)); + Assertions.assertEquals(ErrorCode.DOCUMENT_STORAGE_FAILURE.toString(), exception.getErrorCode()); + + } + + @Test + @DisplayName("502: with ioException should return 502") + public void withScanFailureShouldReturnBadGateway() throws VirusDetectedException, IOException { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + File file = new File("src/test/resources/test.pdf"); + + List files = new ArrayList<>(); + MultipartFile multipartFile = new MockMultipartFile("test.pdf", new FileInputStream(file)); + files.add(multipartFile); + files.add(multipartFile); + + Mockito.doThrow(VirusDetectedException.class).when(clamAvServiceMock).scan(any()); + + DocumentStorageException exception = Assertions.assertThrows(DocumentStorageException.class, () -> sut.uploadAdditionalSubmissionDocuments(TestHelpers.CASE_1, UUID.randomUUID(), files)); + Assertions.assertEquals(ErrorCode.DOCUMENT_STORAGE_FAILURE.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("403: without universalId should throw InvalidUniversalException") + public void withoutUniversalIdShouldThrowInvalidUniversalException() throws VirusDetectedException, IOException { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + File file = new File("src/test/resources/test.pdf"); + + List files = new ArrayList<>(); + MultipartFile multipartFile = new MockMultipartFile("test.pdf", new FileInputStream(file)); + files.add(multipartFile); + files.add(multipartFile); + + Mockito.doThrow(VirusDetectedException.class).when(clamAvServiceMock).scan(any()); + + InvalidUniversalException exception = Assertions.assertThrows(InvalidUniversalException.class, () -> sut.uploadAdditionalSubmissionDocuments(TestHelpers.CASE_1, UUID.randomUUID(), files)); + Assertions.assertEquals(ErrorCode.INVALIDUNIVERSAL.toString(), exception.getErrorCode()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/UploadRushDocumentsTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/UploadRushDocumentsTest.java new file mode 100644 index 0000000000..02029dc6fa --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/UploadRushDocumentsTest.java @@ -0,0 +1,254 @@ +package ca.bc.gov.open.jag.efilingapi.submission.submissionApiDelegateImpl; + +import ca.bc.gov.open.clamav.starter.ClamAvService; +import ca.bc.gov.open.clamav.starter.VirusDetectedException; +import ca.bc.gov.open.jag.efilingapi.TestHelpers; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.UploadSubmissionDocumentsResponse; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.error.*; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.GenerateUrlResponseMapper; +import ca.bc.gov.open.jag.efilingapi.submission.models.Submission; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingapi.submission.validator.GenerateUrlRequestValidator; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Upload Rush Documents Test Suite") +public class UploadRushDocumentsTest { + + + private SubmissionApiDelegateImpl sut; + + @Mock + private SubmissionService submissionServiceMock; + + @Mock + private SubmissionStore submissionStoreMock; + + @Mock + private GenerateUrlResponseMapper generateUrlResponseMapperMock; + + @Mock + private NavigationProperties navigationProperties; + + @Mock + private MultipartFile multipartFileMock; + + @Mock + private DocumentStore documentStoreMock; + + @Mock + private Resource resourceMock; + + @Mock + private AccountService accountServiceMock; + + @Mock + private ClamAvService clamAvServiceMock; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @Mock + private GenerateUrlRequestValidator generateUrlRequestValidator; + + @BeforeAll + public void beforeAll() throws IOException { + MockitoAnnotations.openMocks(this); + + Mockito.when(resourceMock.getFilename()).thenReturn("file.txt"); + Mockito.when(multipartFileMock.getResource()).thenReturn(resourceMock); + Mockito.when(multipartFileMock.getBytes()).thenThrow(new IOException("random")); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + SecurityContextHolder.setContext(securityContextMock); + + Submission submission = Submission + .builder() + .navigationUrls(TestHelpers.createNavigation(TestHelpers.SUCCESS_URL, TestHelpers.CANCEL_URL, TestHelpers.ERROR_URL)) + .create(); + + Mockito.when(submissionStoreMock.get(ArgumentMatchers.argThat(x -> x.getSubmissionId().equals(TestHelpers.CASE_1)))).thenReturn(Optional.of(submission)); + + FilingPackageMapper filingPackageMapper = new FilingPackageMapperImpl(); + sut = new SubmissionApiDelegateImpl(submissionServiceMock, accountServiceMock, generateUrlResponseMapperMock, navigationProperties, submissionStoreMock, documentStoreMock, clamAvServiceMock, filingPackageMapper, generateUrlRequestValidator, null); + } + + @Test + @DisplayName("200: with pdf files should return ok") + public void withPdfFilesShouldReturnOk() throws IOException, VirusDetectedException { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + File file = new File("src/test/resources/test.pdf"); + + List files = new ArrayList<>(); + MultipartFile multipartFile = new MockMultipartFile("test.pdf", new FileInputStream(file)); + + files.add(multipartFile); + files.add(multipartFile); + + Mockito.doNothing().when(clamAvServiceMock).scan(any()); + + ResponseEntity actual = sut.uploadRushDocuments(TestHelpers.CASE_1, UUID.randomUUID(), files); + + Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); + Assertions.assertEquals(TestHelpers.CASE_1, actual.getBody().getSubmissionId()); + Assertions.assertEquals(new BigDecimal(2), actual.getBody().getReceived()); + } + + @Test + @DisplayName("400: with non pdf files should throw FileTypeException") + public void withNonPdfFilesShouldThrowFileTypeException() throws IOException, VirusDetectedException { + + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + File file = new File("src/test/resources/test.txt"); + + List files = new ArrayList<>(); + MultipartFile multipartFile = new MockMultipartFile("test.txt", new FileInputStream(file)); + files.add(multipartFile); + files.add(multipartFile); + + Mockito.doNothing().when(clamAvServiceMock).scan(any()); + + FileTypeException exception = Assertions.assertThrows(FileTypeException.class, () -> sut.uploadRushDocuments(TestHelpers.CASE_1, UUID.randomUUID(), files)); + Assertions.assertEquals(ErrorCode.FILE_TYPE_ERROR.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("400: with empty files should throw DocumentRequiredException") + public void withEmptyFilesShouldThrowDocumentRequiredException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + List files = new ArrayList<>(); + DocumentRequiredException exception = Assertions.assertThrows(DocumentRequiredException.class, () -> sut.uploadRushDocuments(TestHelpers.CASE_1, UUID.randomUUID(), files)); + Assertions.assertEquals(ErrorCode.DOCUMENT_REQUIRED.toString(), exception.getErrorCode()); + } + + + @Test + @DisplayName("400: with null files should throw DocumentRequiredException") + public void withNullFilesShouldThrowDocumentRequiredException() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + DocumentRequiredException exception = Assertions.assertThrows(DocumentRequiredException.class, () -> sut.uploadRushDocuments(TestHelpers.CASE_1, UUID.randomUUID(), null)); + Assertions.assertEquals(ErrorCode.DOCUMENT_REQUIRED.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("404: with no submission present should return not found") + public void withNoSubmissionReturnNotFound() { + + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + ResponseEntity actual = sut.uploadAdditionalSubmissionDocuments(TestHelpers.CASE_2, UUID.randomUUID(), null); + + Assertions.assertEquals(HttpStatus.NOT_FOUND, actual.getStatusCode()); + + } + + @Test + @DisplayName("500: with ioException should return 500") + public void withIoExceptionShouldReturnInternalServerError() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + List files = new ArrayList<>(); + files.add(multipartFileMock); + + DocumentStorageException exception = Assertions.assertThrows(DocumentStorageException.class, () -> sut.uploadRushDocuments(TestHelpers.CASE_1, UUID.randomUUID(), files)); + Assertions.assertEquals(ErrorCode.DOCUMENT_STORAGE_FAILURE.toString(), exception.getErrorCode()); + + } + + @Test + @DisplayName("502: with ioException should return 502") + public void withScanFailureShouldReturnBadGateway() throws VirusDetectedException, IOException { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(UUID.randomUUID().toString()); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + File file = new File("src/test/resources/test.pdf"); + + List files = new ArrayList<>(); + MultipartFile multipartFile = new MockMultipartFile("test.pdf", new FileInputStream(file)); + files.add(multipartFile); + files.add(multipartFile); + + Mockito.doThrow(VirusDetectedException.class).when(clamAvServiceMock).scan(any()); + + DocumentStorageException exception = Assertions.assertThrows(DocumentStorageException.class, () -> sut.uploadRushDocuments(TestHelpers.CASE_1, UUID.randomUUID(), files)); + Assertions.assertEquals(ErrorCode.DOCUMENT_STORAGE_FAILURE.toString(), exception.getErrorCode()); + + } + + @Test + @DisplayName("403: without universalId should throw InvalidUniversalException") + public void withoutUniversalIdShouldThrowInvalidUniversalException() throws VirusDetectedException, IOException { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(null); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + File file = new File("src/test/resources/test.pdf"); + + List files = new ArrayList<>(); + MultipartFile multipartFile = new MockMultipartFile("test.pdf", new FileInputStream(file)); + files.add(multipartFile); + files.add(multipartFile); + + Mockito.doThrow(VirusDetectedException.class).when(clamAvServiceMock).scan(any()); + + InvalidUniversalException exception = Assertions.assertThrows(InvalidUniversalException.class, () -> sut.uploadRushDocuments(TestHelpers.CASE_1, UUID.randomUUID(), files)); + Assertions.assertEquals(ErrorCode.INVALIDUNIVERSAL.toString(), exception.getErrorCode()); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/UploadSubmissionDocumentsTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/UploadSubmissionDocumentsTest.java new file mode 100644 index 0000000000..f5b578a142 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/submissionApiDelegateImpl/UploadSubmissionDocumentsTest.java @@ -0,0 +1,187 @@ +package ca.bc.gov.open.jag.efilingapi.submission.submissionApiDelegateImpl; + +import ca.bc.gov.open.clamav.starter.ClamAvService; +import ca.bc.gov.open.clamav.starter.VirusDetectedException; +import ca.bc.gov.open.jag.efilingapi.account.service.AccountService; +import ca.bc.gov.open.jag.efilingapi.api.model.UploadSubmissionDocumentsResponse; +import ca.bc.gov.open.jag.efilingapi.config.NavigationProperties; +import ca.bc.gov.open.jag.efilingapi.document.DocumentStore; +import ca.bc.gov.open.jag.efilingapi.error.*; +import ca.bc.gov.open.jag.efilingapi.submission.SubmissionApiDelegateImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapper; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.FilingPackageMapperImpl; +import ca.bc.gov.open.jag.efilingapi.submission.mappers.GenerateUrlResponseMapper; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionStore; +import ca.bc.gov.open.jag.efilingapi.submission.validator.GenerateUrlRequestValidator; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Upload Submission Documents Test Suite") +public class UploadSubmissionDocumentsTest { + + private SubmissionApiDelegateImpl sut; + + @Mock + private SubmissionService submissionServiceMock; + + @Mock + private SubmissionStore submissionStoreMock; + + @Mock + private GenerateUrlResponseMapper generateUrlResponseMapperMock; + + @Mock + private NavigationProperties navigationProperties; + + @Mock + private MultipartFile multipartFileMock; + + @Mock + private DocumentStore documentStoreMock; + + @Mock + private Resource resourceMock; + + @Mock + private AccountService accountServiceMock; + + @Mock + private ClamAvService clamAvServiceMock; + + @Mock + private GenerateUrlRequestValidator generateUrlRequestValidator; + + + @BeforeAll + public void setUp() throws IOException { + MockitoAnnotations.openMocks(this); + + Mockito.when(resourceMock.getFilename()).thenReturn("file.pdf"); + Mockito.when(multipartFileMock.getResource()).thenReturn(resourceMock); + Mockito.when(multipartFileMock.getBytes()).thenThrow(new IOException("random")); + + FilingPackageMapper filingPackageMapper = new FilingPackageMapperImpl(); + sut = new SubmissionApiDelegateImpl(submissionServiceMock, accountServiceMock, generateUrlResponseMapperMock, navigationProperties, submissionStoreMock, documentStoreMock, clamAvServiceMock, filingPackageMapper, generateUrlRequestValidator, null); + } + + @Test + @DisplayName("200: with files should return ok") + public void withFilesShouldReturnOk() throws IOException, VirusDetectedException { + + File file = new File("src/test/resources/test.pdf"); + + List files = new ArrayList<>(); + MultipartFile multipartFile = new MockMultipartFile("test.pdf", new FileInputStream(file)); + files.add(multipartFile); + files.add(multipartFile); + + Mockito.doNothing().when(clamAvServiceMock).scan(any()); + + ResponseEntity actual = sut.uploadSubmissionDocuments(UUID.randomUUID(), UUID.randomUUID().toString().replace("-", ""), files); + + Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); + Assertions.assertNotNull(actual.getBody().getSubmissionId()); + Assertions.assertEquals(new BigDecimal(2), actual.getBody().getReceived()); + } + + @Test + @DisplayName("400: with non pdf files should throw FileTypeException") + public void withNonPdfFilesShouldThrowFileTypeException() throws IOException, VirusDetectedException { + + File file = new File("src/test/resources/test.txt"); + + List files = new ArrayList<>(); + MultipartFile multipartFile = new MockMultipartFile("test.txt", new FileInputStream(file)); + files.add(multipartFile); + files.add(multipartFile); + + Mockito.doNothing().when(clamAvServiceMock).scan(any()); + + FileTypeException exception = Assertions.assertThrows(FileTypeException.class, () -> sut.uploadSubmissionDocuments(UUID.randomUUID(), UUID.randomUUID().toString().replace("-", ""), files)); + Assertions.assertEquals(ErrorCode.FILE_TYPE_ERROR.toString(), exception.getErrorCode()); + } + + + @Test + @DisplayName("400: with empty files should throw DocumentRequiredException") + public void withEmptyFilesShouldThrowDocumentRequiredException() { + + List files = new ArrayList<>(); + DocumentRequiredException exception = Assertions.assertThrows(DocumentRequiredException.class, () -> sut.uploadSubmissionDocuments(UUID.randomUUID(), UUID.randomUUID().toString().replace("-", ""), files)); + Assertions.assertEquals(ErrorCode.DOCUMENT_REQUIRED.toString(), exception.getErrorCode()); + } + + + @Test + @DisplayName("400: with null files should throw DocumentRequiredException") + public void withNullFilesShouldThrowDocumentRequiredException() { + + DocumentRequiredException exception = Assertions.assertThrows(DocumentRequiredException.class, () -> sut.uploadSubmissionDocuments(UUID.randomUUID(), UUID.randomUUID().toString().replace("-", ""), null)); + Assertions.assertEquals(ErrorCode.DOCUMENT_REQUIRED.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("500: with ioException should return 500") + public void withIoExceptionShouldReturnInternalServerError() { + + List files = new ArrayList<>(); + files.add(multipartFileMock); + + DocumentStorageException exception = Assertions.assertThrows(DocumentStorageException.class, () -> sut.uploadSubmissionDocuments(UUID.randomUUID(), UUID.randomUUID().toString().replace("-", ""), files)); + Assertions.assertEquals(ErrorCode.DOCUMENT_STORAGE_FAILURE.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("502: with ioException should return 502") + public void withScanFailureShouldReturnBadGateway() throws VirusDetectedException, IOException { + + + File file = new File("src/test/resources/test.pdf"); + + List files = new ArrayList<>(); + MultipartFile multipartFile = new MockMultipartFile("test.pdf", new FileInputStream(file)); + files.add(multipartFile); + files.add(multipartFile); + + Mockito.doThrow(VirusDetectedException.class).when(clamAvServiceMock).scan(any()); + + DocumentStorageException exception = Assertions.assertThrows(DocumentStorageException.class, () -> sut.uploadSubmissionDocuments(UUID.randomUUID(), UUID.randomUUID().toString().replace("-", ""), files)); + Assertions.assertEquals(ErrorCode.DOCUMENT_STORAGE_FAILURE.toString(), exception.getErrorCode()); + } + + @Test + @DisplayName("403: with missing id should throw InvalidUniversalException") + public void withBlankIdShouldThrowInvalidUniversalException() throws VirusDetectedException, IOException { + + File file = new File("src/test/resources/test.pdf"); + + List files = new ArrayList<>(); + MultipartFile multipartFile = new MockMultipartFile("test.pdf", new FileInputStream(file)); + files.add(multipartFile); + files.add(multipartFile); + + Mockito.doThrow(VirusDetectedException.class).when(clamAvServiceMock).scan(any()); + + InvalidUniversalException exception = Assertions.assertThrows(InvalidUniversalException.class, () -> sut.uploadSubmissionDocuments(UUID.randomUUID(), " ", files)); + Assertions.assertEquals(ErrorCode.INVALIDUNIVERSAL.toString(), exception.getErrorCode()); + } +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/validator/GenerateUrlRequestValidatorImplTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/validator/GenerateUrlRequestValidatorImplTest.java new file mode 100644 index 0000000000..768a84d219 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/submission/validator/GenerateUrlRequestValidatorImplTest.java @@ -0,0 +1,887 @@ +package ca.bc.gov.open.jag.efilingapi.submission.validator; + +import ca.bc.gov.open.jag.efilingapi.api.model.*; +import ca.bc.gov.open.jag.efilingapi.court.services.CourtService; +import ca.bc.gov.open.jag.efilingapi.document.DocumentService; +import ca.bc.gov.open.jag.efilingapi.filingpackage.service.FilingPackageService; +import ca.bc.gov.open.jag.efilingapi.submission.service.SubmissionService; +import ca.bc.gov.open.jag.efilingapi.utils.Notification; +import ca.bc.gov.open.jag.efilingcommons.model.CourtDetails; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class GenerateUrlRequestValidatorImplTest { + + private static final String COURT_CLASSIFICATION = "COURT_CLASSIFICATION"; + private static final String[] ROLE_TYPES = new String[] { "ADJ", "CIT" }; + private static final String COURT_LEVEL = "COURT_LEVEL"; + private static final String APPLICATION_CODE = "app_code"; + private static final String COURT_DESCRIPTION = "courtDescription"; + private static final String CLASS_DESCRIPTION = "classDescription"; + private static final String LEVEL_DESCRIPTION = "levelDescription"; + private static final BigDecimal COURT_ID = BigDecimal.ONE; + private static final String CASE_1 = "CASE1"; + private static final String CASE_2 = "case2"; + private static final BigDecimal COURT_ID_2 = BigDecimal.TEN; + private static final String FILE_NUMBER_SUCCESS = "filenumber"; + private static final String FILE_NUMBER_ERROR = "file_number_error"; + private static final String ORGANIZATION_NAME = "ORGANIZATION NAME"; + private static final String LAST_NAME = "LAST NAME"; + private static final BigDecimal EXISTING_PACKAGE = BigDecimal.ONE; + private static final BigDecimal EXISTING_DOCUMENT = BigDecimal.ONE; + + private GenerateUrlRequestValidatorImpl sut; + + @Mock + private SubmissionService submissionService; + + @Mock + private CourtService courtServiceMock; + + @Mock + private DocumentService documentServiceMock; + + @Mock + private FilingPackageService filingPackageServiceMock; + + @BeforeEach + public void beforeEach() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(submissionService + .getValidPartyRoles( + ArgumentMatchers.argThat(x -> x.getCourtClassification().equals(COURT_CLASSIFICATION)))) + .thenReturn(Arrays.asList(ROLE_TYPES)); + + CourtDetails courtDetails = new CourtDetails(COURT_ID, COURT_DESCRIPTION, CLASS_DESCRIPTION, LEVEL_DESCRIPTION); + + Mockito + .doReturn(Optional.of(courtDetails)) + .when(courtServiceMock) + .getCourtDetails(ArgumentMatchers.argThat(x -> x.getCourtLocation().equals(CASE_1))); + + Mockito + .doReturn(true) + .when(courtServiceMock).isValidCourt(ArgumentMatchers.argThat(x -> x.getCourtId().equals(COURT_ID))); + + CourtDetails courtDetails2 = new CourtDetails(COURT_ID_2, COURT_DESCRIPTION, CLASS_DESCRIPTION, LEVEL_DESCRIPTION); + + Mockito + .doReturn(Optional.of(courtDetails2)) + .when(courtServiceMock) + .getCourtDetails(ArgumentMatchers.argThat(x -> x.getCourtLocation().equals(CASE_2))); + + Mockito + .doReturn(false) + .when(courtServiceMock) + .isValidCourt(ArgumentMatchers.argThat(x -> x.getCourtId().equals(COURT_ID_2))); + + + Mockito + .doReturn(true) + .when(courtServiceMock) + .isValidCourtFileNumber(ArgumentMatchers.argThat(x -> x.getFileNumber().equals(FILE_NUMBER_SUCCESS))); + + Mockito + .doReturn(false) + .when(courtServiceMock) + .isValidCourtFileNumber(ArgumentMatchers.argThat(x -> x.getFileNumber().equals(FILE_NUMBER_ERROR))); + + List documentTypeDetails = new ArrayList<>(); + DocumentTypeDetails document = new DocumentTypeDetails("Description", "ACMW", BigDecimal.TEN,true, true, true); + documentTypeDetails.add(document); + + Mockito + .doReturn(documentTypeDetails) + .when(documentServiceMock) + .getValidDocumentTypes(ArgumentMatchers.argThat(x -> x.getCourtLevel().equals(COURT_LEVEL))); + + Optional optionalFilingPackage = Optional.of(setupPackage(EXISTING_PACKAGE, EXISTING_DOCUMENT)); + + Mockito.when(filingPackageServiceMock.getCSOFilingPackage(any(), ArgumentMatchers.eq(EXISTING_PACKAGE))).thenReturn(optionalFilingPackage); + + sut = new GenerateUrlRequestValidatorImpl(submissionService, courtServiceMock, documentServiceMock, filingPackageServiceMock); + + } + + @Test + @DisplayName("ok: new submission without error should return a notification without error") + public void newSubmissionWithoutErrorShouldReturnNoError() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setLocation(CASE_1); + initialFilingPackage.setCourt(court); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setRoleType(Individual.RoleTypeEnum.ADJ); + party.setLastName(LAST_NAME); + parties.add(party); + Individual party2 = new Individual(); + party2.setRoleType(Individual.RoleTypeEnum.CIT); + party2.setLastName(LAST_NAME); + parties.add(party2); + initialFilingPackage.setParties(parties); + + List documentList = new ArrayList<>(); + InitialDocument initialDocument = new InitialDocument(); + initialDocument.setType("ACMW"); + documentList.add(initialDocument); + initialFilingPackage.setDocuments(documentList); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertFalse(actual.hasError()); + + } + + @Test + @DisplayName("ok: returning submission without error should return a notification without error") + public void returningSubmissionWithoutErrorShouldReturnNoError() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setLocation(CASE_1); + court.setFileNumber(FILE_NUMBER_SUCCESS); + initialFilingPackage.setCourt(court); + + + List documentList = new ArrayList<>(); + InitialDocument initialDocument = new InitialDocument(); + initialDocument.setType("ACMW"); + documentList.add(initialDocument); + initialFilingPackage.setDocuments(documentList); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setRoleType(Individual.RoleTypeEnum.APP); + party.setLastName(LAST_NAME); + initialFilingPackage.setParties(parties); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertFalse(actual.hasError()); + + } + + @Test + @DisplayName("ok: returning submission with existing should return a notification without error") + public void returningSubmissionWithExistingPackageErrorShouldReturnNoError() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + initialFilingPackage.setPackageNumber(EXISTING_PACKAGE); + + CourtBase court = new CourtBase(); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setLocation(CASE_1); + court.setFileNumber(FILE_NUMBER_SUCCESS); + initialFilingPackage.setCourt(court); + + List documentList = new ArrayList<>(); + InitialDocument initialDocument = new InitialDocument(); + initialDocument.setType("ACMW"); + ActionDocument actionDocument = new ActionDocument(); + actionDocument.setId(EXISTING_DOCUMENT); + initialDocument.setActionDocument(actionDocument); + documentList.add(initialDocument); + initialFilingPackage.setDocuments(documentList); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setRoleType(Individual.RoleTypeEnum.APP); + party.setLastName(LAST_NAME); + initialFilingPackage.setParties(parties); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertFalse(actual.hasError()); + + } + + @Test + @DisplayName("error: with no navigation urls should return error") + public void newSubmissionWithoutNavigationUrlsShouldReturnError() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setLocation(CASE_1); + initialFilingPackage.setCourt(court); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setRoleType(Individual.RoleTypeEnum.ADJ); + party.setLastName(LAST_NAME); + parties.add(party); + Individual party2 = new Individual(); + party2.setRoleType(Individual.RoleTypeEnum.CIT); + party2.setLastName(LAST_NAME); + parties.add(party2); + initialFilingPackage.setParties(parties); + + List documentList = new ArrayList<>(); + InitialDocument initialDocument = new InitialDocument(); + initialDocument.setType("ACMW"); + documentList.add(initialDocument); + initialFilingPackage.setDocuments(documentList); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("Navigation Urls are required.", actual.getErrors().get(0)); + + } + + @Test + @DisplayName("error: with blank navigation urls should return error") + public void newSubmissionWithBlankNavigationUrlsShouldReturnError() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setLocation(CASE_1); + initialFilingPackage.setCourt(court); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setRoleType(Individual.RoleTypeEnum.ADJ); + party.setLastName(LAST_NAME); + parties.add(party); + Individual party2 = new Individual(); + party2.setRoleType(Individual.RoleTypeEnum.CIT); + party2.setLastName(LAST_NAME); + parties.add(party2); + initialFilingPackage.setParties(parties); + + List documentList = new ArrayList<>(); + InitialDocument initialDocument = new InitialDocument(); + initialDocument.setType("ACMW"); + documentList.add(initialDocument); + initialFilingPackage.setDocuments(documentList); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError(" "); + navigationUrls.setCancel(" "); + generateUrlRequest.setNavigationUrls(navigationUrls); + + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("Error url is required.", actual.getErrors().get(0)); + Assertions.assertEquals("Cancel url is required.", actual.getErrors().get(1)); + Assertions.assertEquals("Success url is required.", actual.getErrors().get(2)); + + } + + @Test + @DisplayName("error: with no courtDetails should return error") + public void withNoCourtDetailsShouldReturnError() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLocation("unknown"); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + initialFilingPackage.setCourt(court); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setLastName(LAST_NAME); + parties.add(party); + initialFilingPackage.setParties(parties); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("Court with Location: [unknown], Level: [COURT_LEVEL], Classification: [COURT_CLASSIFICATION] is not a valid court.", actual.getErrors().get(0)); + + } + + @Test + @DisplayName("ok: returning submission with invalid filenumber should return a notification with error") + public void returningSubmissionWithInvalidFileNumberShouldReturnNotificationWithErrors() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setLocation(CASE_1); + court.setFileNumber(FILE_NUMBER_ERROR); + initialFilingPackage.setCourt(court); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setRoleType(Individual.RoleTypeEnum.APP); + party.setLastName(LAST_NAME); + initialFilingPackage.setParties(parties); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("FileNumber [file_number_error] does not exists.", actual.getErrors().get(0)); + } + + + @Test + @DisplayName("error: with invalid court should return an error") + public void withInvalidCourtShouldReturnError() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setLocation(CASE_2); + initialFilingPackage.setCourt(court); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setRoleType(Individual.RoleTypeEnum.ADJ); + party.setLastName(LAST_NAME); + parties.add(party); + Individual party2 = new Individual(); + party2.setRoleType(Individual.RoleTypeEnum.CIT); + party2.setLastName(LAST_NAME); + parties.add(party2); + + initialFilingPackage.setParties(parties); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("Court with Location: [case2], Level: [COURT_LEVEL], Classification: [COURT_CLASSIFICATION] is not a valid court.", actual.getErrors().get(0)); + + } + + @Test + @DisplayName("error: without filing package should return an error") + public void withoutFilingPackageShouldReturnError() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("Initial Package is required.", actual.getErrors().get(0)); + + } + + + @Test + @DisplayName("error: without filing package should return an error") + public void withoutFilingPackageShouldReturnError2() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLocation(CASE_1); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + initialFilingPackage.setCourt(court); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("At least 1 party is required for new submission.", actual.getErrors().get(0)); + + } + + @Test + @DisplayName("error: with role type not in list should return multiple errors") + public void withRoleTypeNotInListShouldReturnMultipleErrors() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLocation(CASE_1); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + initialFilingPackage.setCourt(court); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setRoleType(Individual.RoleTypeEnum.CAV); + party.setLastName(LAST_NAME); + parties.add(party); + Individual party2 = new Individual(); + party2.setRoleType(Individual.RoleTypeEnum.DEO); + party2.setLastName(LAST_NAME); + parties.add(party2); + + initialFilingPackage.setParties(parties); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("Individual role type [CAV] is invalid.", actual.getErrors().get(0)); + Assertions.assertEquals("Individual role type [DEO] is invalid.", actual.getErrors().get(1)); + + } + + @Test + @DisplayName("error: with role type not in list and with fileNumber should return multiple errors") + public void withRoleTypeNotInListAnFileNumberSetShouldReturnMultipleErrors() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLocation(CASE_1); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setFileNumber(FILE_NUMBER_SUCCESS); + initialFilingPackage.setCourt(court); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setRoleType(Individual.RoleTypeEnum.CAV); + party.setLastName(LAST_NAME); + parties.add(party); + Individual party2 = new Individual(); + party2.setRoleType(Individual.RoleTypeEnum.DEO); + party2.setLastName(LAST_NAME); + parties.add(party2); + initialFilingPackage.setParties(parties); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("Individual role type [CAV] is invalid.", actual.getErrors().get(0)); + Assertions.assertEquals("Individual role type [DEO] is invalid.", actual.getErrors().get(1)); + + } + + @Test + @DisplayName("error: with role type Null should return error") + public void withRoleTypeNullNotInListShouldReturnMultipleErrors() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLocation(CASE_1); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + initialFilingPackage.setCourt(court); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setLastName(LAST_NAME); + parties.add(party); + initialFilingPackage.setParties(parties); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("Individual role type [null] is invalid.", actual.getErrors().get(0)); + + } + + @Test + @DisplayName("error: with invalid document type should return notification with Error") + public void withInvalidDocumentTypeShouldReturnNotificationWithError() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setLocation(CASE_1); + initialFilingPackage.setCourt(court); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setRoleType(Individual.RoleTypeEnum.ADJ); + party.setLastName(LAST_NAME); + parties.add(party); + Individual party2 = new Individual(); + party2.setRoleType(Individual.RoleTypeEnum.CIT); + party2.setLastName(LAST_NAME); + parties.add(party2); + initialFilingPackage.setParties(parties); + + List documentList = new ArrayList<>(); + InitialDocument initialDocument = new InitialDocument(); + initialDocument.setType("TAX"); + documentList.add(initialDocument); + initialFilingPackage.setDocuments(documentList); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("Document type [TAX] is invalid.", actual.getErrors().get(0)); + + } + + @Test + @DisplayName("error: with null parties should return notification with Error") + public void withNullPartiesShouldReturnNotificationWithError() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setLocation(CASE_1); + initialFilingPackage.setCourt(court); + + List documentList = new ArrayList<>(); + InitialDocument initialDocument = new InitialDocument(); + initialDocument.setType("TAX"); + documentList.add(initialDocument); + initialFilingPackage.setDocuments(documentList); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("At least 1 party is required for new submission.", actual.getErrors().get(0)); + + } + + @Test + @DisplayName("error: with role type not in list and with fileNumber should return multiple errors") + public void withOrganizeationRoleTypeNotInListAnFileNumberSetShouldReturnMultipleErrors() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLocation(CASE_1); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setFileNumber(FILE_NUMBER_SUCCESS); + initialFilingPackage.setCourt(court); + + List orgs = new ArrayList<>(); + Organization org1 = new Organization(); + org1.setRoleType(Organization.RoleTypeEnum.CAV); + org1.setName(ORGANIZATION_NAME); + orgs.add(org1); + Organization org2 = new Organization(); + org2.setRoleType(Organization.RoleTypeEnum.DEO); + org2.setName(ORGANIZATION_NAME); + orgs.add(org2); + initialFilingPackage.setOrganizationParties(orgs); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("Organization role type [CAV] is invalid.", actual.getErrors().get(0)); + Assertions.assertEquals("Organization role type [DEO] is invalid.", actual.getErrors().get(1)); + + } + + @Test + @DisplayName("error: with null org name and with fileNumber should return multiple errors") + public void withNullOrganizeationNameInListAnFileNumberSetShouldReturnMultipleErrors() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLocation(CASE_1); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setFileNumber(FILE_NUMBER_SUCCESS); + initialFilingPackage.setCourt(court); + + List orgs = new ArrayList<>(); + Organization org1 = new Organization(); + org1.setRoleType(Organization.RoleTypeEnum.ADJ); + orgs.add(org1); + Organization org2 = new Organization(); + org2.setRoleType(Organization.RoleTypeEnum.CIT); + orgs.add(org2); + initialFilingPackage.setOrganizationParties(orgs); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("Organization name is required.", actual.getErrors().get(0)); + Assertions.assertEquals("Organization name is required.", actual.getErrors().get(1)); + + } + + @Test + @DisplayName("error: with null last name and with fileNumber should return multiple errors") + public void withNullIndividualLastNameInListAnFileNumberSetShouldReturnMultipleErrors() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + CourtBase court = new CourtBase(); + court.setLocation(CASE_1); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setFileNumber(FILE_NUMBER_SUCCESS); + initialFilingPackage.setCourt(court); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setRoleType(Individual.RoleTypeEnum.ADJ); + parties.add(party); + Individual party2 = new Individual(); + party2.setRoleType(Individual.RoleTypeEnum.CIT); + parties.add(party2); + initialFilingPackage.setParties(parties); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + Assertions.assertEquals("Individual last name is required.", actual.getErrors().get(0)); + Assertions.assertEquals("Individual last name is required.", actual.getErrors().get(1)); + + } + + @Test + @DisplayName("error: returning submission with bad package number should return a error") + public void returningSubmissionWithBadPackageErrorShouldReturnError() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + initialFilingPackage.setPackageNumber(BigDecimal.TEN); + + CourtBase court = new CourtBase(); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setLocation(CASE_1); + court.setFileNumber(FILE_NUMBER_SUCCESS); + initialFilingPackage.setCourt(court); + + List documentList = new ArrayList<>(); + InitialDocument initialDocument = new InitialDocument(); + initialDocument.setType("ACMW"); + ActionDocument actionDocument = new ActionDocument(); + actionDocument.setId(EXISTING_DOCUMENT); + initialDocument.setActionDocument(actionDocument); + documentList.add(initialDocument); + initialFilingPackage.setDocuments(documentList); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setRoleType(Individual.RoleTypeEnum.APP); + party.setLastName(LAST_NAME); + initialFilingPackage.setParties(parties); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + + Assertions.assertEquals("For given package number and universal id no record was found in cso", actual.getErrors().get(0)); + + } + + + @Test + @DisplayName("error: returning submission with no documents should return a error") + public void returningSubmissionWithNoDocumentShouldReturnError() { + + GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(); + InitialPackage initialFilingPackage = new InitialPackage(); + + initialFilingPackage.setPackageNumber(EXISTING_PACKAGE); + + CourtBase court = new CourtBase(); + court.setLevel(COURT_LEVEL); + court.setCourtClass(COURT_CLASSIFICATION); + court.setLocation(CASE_1); + court.setFileNumber(FILE_NUMBER_SUCCESS); + initialFilingPackage.setCourt(court); + + NavigationUrls navigationUrls = new NavigationUrls(); + navigationUrls.setError("http://error"); + navigationUrls.setCancel("http://cancel"); + navigationUrls.setSuccess("http://success"); + generateUrlRequest.setNavigationUrls(navigationUrls); + + List parties = new ArrayList<>(); + Individual party = new Individual(); + party.setRoleType(Individual.RoleTypeEnum.APP); + party.setLastName(LAST_NAME); + initialFilingPackage.setParties(parties); + + generateUrlRequest.setFilingPackage(initialFilingPackage); + Notification actual = sut.validate(generateUrlRequest, APPLICATION_CODE, ""); + + Assertions.assertTrue(actual.hasError()); + + Assertions.assertEquals("For given package there are no documents present", actual.getErrors().get(0)); + + } + + private FilingPackage setupPackage(BigDecimal packageNumber, BigDecimal documentNumber) { + + FilingPackage filingPackage = new FilingPackage(); + + filingPackage.setPackageNumber(packageNumber); + + Document document = new Document(); + + document.setIdentifier(documentNumber.toPlainString()); + + filingPackage.getDocuments().add(document); + + return filingPackage; + + } + + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/utils/SecurityUtilsTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/utils/SecurityUtilsTest.java new file mode 100644 index 0000000000..519d51f549 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/utils/SecurityUtilsTest.java @@ -0,0 +1,106 @@ +package ca.bc.gov.open.jag.efilingapi.utils; + +import ca.bc.gov.open.jag.efilingapi.core.security.SecurityUtils; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.util.Optional; +import java.util.UUID; + +import static ca.bc.gov.open.jag.efilingapi.Keys.UNIVERSAL_ID_CLAIM_KEY; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Security Utils Test Suite") +public class SecurityUtilsTest { + + + private static final String EXPECTED_CLAIM = "claim_value"; + + @Mock + private SecurityContext securityContextMock; + + @Mock + private Authentication authenticationMock; + + @Mock + private Jwt jwtMock; + + @BeforeEach + public void setup() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(securityContextMock.getAuthentication()).thenReturn(authenticationMock); + + SecurityContextHolder.setContext(securityContextMock); + } + + @Test + public void shouldConvertToUUID() { + + String expectedUUID = UUID.randomUUID().toString(); + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(expectedUUID); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + Optional actual = SecurityUtils.getUniversalIdFromContext(); + + Assertions.assertTrue(actual.isPresent()); + Assertions.assertEquals(expectedUUID, actual.get()); + + } + + @Test + @DisplayName("client Id should return value") + public void withClientIdShouldReturnTrue() { + + String username = "username"; + + Mockito.when(jwtMock.getId()).thenReturn(username); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + Optional actual = SecurityUtils.getClientId(); + Assertions.assertTrue(actual.isPresent()); + Assertions.assertEquals(username, actual.get()); + + } + + @Test + @DisplayName("No client Id should return empty") + public void withNoClientIdShouldReturnFalse() { + + Mockito.when(securityContextMock.getAuthentication()).thenThrow(new RuntimeException()); + Optional actual = SecurityUtils.getClientId(); + Assertions.assertFalse(actual.isPresent()); + + } + + @Test + @DisplayName("Should return universal id") + public void shouldReturnClaim() { + + Mockito.when(jwtMock.getClaim(Mockito.eq(UNIVERSAL_ID_CLAIM_KEY))).thenReturn(EXPECTED_CLAIM); + Mockito.when(authenticationMock.getPrincipal()).thenReturn(jwtMock); + + Optional actual = SecurityUtils.getUniversalIdFromContext(); + + Assertions.assertTrue(actual.isPresent()); + Assertions.assertEquals(EXPECTED_CLAIM, actual.get()); + + } + + @Test + @DisplayName("null should throw") + public void exceptionIsInRoleThrows() { + + Assertions.assertFalse(SecurityUtils.isInRole("")); + + } + +} diff --git a/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/utils/TikaAnalysisTest.java b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/utils/TikaAnalysisTest.java new file mode 100644 index 0000000000..d4b74c8405 --- /dev/null +++ b/src/backend/efiling-api/src/test/java/ca/bc/gov/open/jag/efilingapi/utils/TikaAnalysisTest.java @@ -0,0 +1,45 @@ +package ca.bc.gov.open.jag.efilingapi.utils; + +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("TikaAnalysis Test Suite") +public class TikaAnalysisTest { + + @Mock + MultipartFile multipartFileMock; + + + @BeforeEach + public void setup() throws IOException { + + MockitoAnnotations.openMocks(this); + + Mockito.doThrow(IOException.class).when(multipartFileMock).getBytes(); + } + + @Test + @DisplayName("Test success") + public void withValidFileReturnTrue() throws IOException { + File file = new File("src/test/resources/test.pdf"); + + MultipartFile multipartFile = new MockMultipartFile("test.pdf", new FileInputStream(file)); + + Assertions.assertTrue(TikaAnalysis.isPdf(multipartFile)); + } + + @Test + @DisplayName("Test failure") + public void withInValidFileReturnFalse() { + Assertions.assertFalse(TikaAnalysis.isPdf(multipartFileMock)); + } +} diff --git a/src/backend/efiling-api/src/test/resources/test.pdf b/src/backend/efiling-api/src/test/resources/test.pdf new file mode 100644 index 0000000000..7f4fecbf04 Binary files /dev/null and b/src/backend/efiling-api/src/test/resources/test.pdf differ diff --git a/src/backend/efiling-api/src/test/resources/test.txt b/src/backend/efiling-api/src/test/resources/test.txt new file mode 100644 index 0000000000..69d5d8f93b --- /dev/null +++ b/src/backend/efiling-api/src/test/resources/test.txt @@ -0,0 +1 @@ +blorb \ No newline at end of file diff --git a/src/backend/efiling-backend-demo/README.md b/src/backend/efiling-backend-demo/README.md deleted file mode 100644 index 0481d4e768..0000000000 --- a/src/backend/efiling-backend-demo/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# efiling-backend-demo - -A demo backend for efiling software. - -This is for demo purpose only! diff --git a/src/backend/efiling-backend-demo/efiling-backend-demo.openapi.yaml b/src/backend/efiling-backend-demo/efiling-backend-demo.openapi.yaml deleted file mode 100644 index 4ecba87f7f..0000000000 --- a/src/backend/efiling-backend-demo/efiling-backend-demo.openapi.yaml +++ /dev/null @@ -1,34 +0,0 @@ -openapi: 3.0.0 -info: - version: 0.3.0 - title: efiling-backend-demo - description: Efiling Backend Demo -servers: - - url: 'http://localhost:8080' -tags: - - name: document - description: Document Api -paths: - '/document/{id}': - get: - summary: Get Document By Id - operationId: GetDocumentById - tags: - - document - parameters: - - name: id - in: path - description: a document id - required: true - schema: - type: string - responses: - '200': - description: Config found - content: - application/pdf: - schema: - type: string - format: binary - '404': - description: Config not found diff --git a/src/backend/efiling-backend-demo/pom.xml b/src/backend/efiling-backend-demo/pom.xml deleted file mode 100644 index eddc29470f..0000000000 --- a/src/backend/efiling-backend-demo/pom.xml +++ /dev/null @@ -1,215 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.3.1.RELEASE - - - ca.bc.gov.open.jag - efiling-backend-demo - 0.0.1-SNAPSHOT - efiling-backend-demo - A demo app for using the efiling system - - ca.bc.gov.open.jag.efilingbackenddemo - 1.8 - 1.3.1.Final - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - - - - org.springframework.boot - spring-boot-starter-actuator - - - - commons-codec - commons-codec - - - - joda-time - joda-time - - - javax.validation - validation-api - - - org.apache.commons - commons-lang3 - - - - io.opentracing.contrib - opentracing-spring-jaeger-web-starter - - - io.github.openfeign.opentracing - feign-opentracing - - - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - - - ch.qos.logback - logback-access - - - net.rakugakibox.spring.boot - logback-access-spring-boot-starter - - - - - io.swagger - swagger-annotations - - - org.springdoc - springdoc-openapi-ui - - - io.springfox - springfox-swagger2 - - - io.springfox - springfox-swagger-ui - - - - - - - - ca.bc.gov.open.jag - efiling-bom - 0.0.1-SNAPSHOT - pom - import - - - - - - - default - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - ca.bc.gov.open.jag.ca.bc.gov.open.jag.efilingbackenddemo.EfilingBackendDemoApplication - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - - - org.apache.maven.plugins - maven-failsafe-plugin - 2.22.2 - - - - - org.openapitools - openapi-generator-maven-plugin - 3.3.4 - - - spring-boot-api - - generate - - - ${project.basedir}/efiling-backend-demo.openapi.yaml - spring - - joda - true - - spring-boot - ${default-package}.api - ${default-package}.api.model - ${default-package}.api.handler - - - - - - - - org.jacoco - jacoco-maven-plugin - 0.8.5 - - - - **/*/mappers/*Impl.java - **/*/open/api/* - - - - - - - prepare-agent - - - - - - report - test - - report - - - - - - - - - \ No newline at end of file diff --git a/src/backend/efiling-backend-demo/src/main/java/ca/bc/gov/open/jag/efilingbackenddemo/DocumentService.java b/src/backend/efiling-backend-demo/src/main/java/ca/bc/gov/open/jag/efilingbackenddemo/DocumentService.java deleted file mode 100644 index 93517f2002..0000000000 --- a/src/backend/efiling-backend-demo/src/main/java/ca/bc/gov/open/jag/efilingbackenddemo/DocumentService.java +++ /dev/null @@ -1,22 +0,0 @@ -package ca.bc.gov.open.jag.efilingbackenddemo; - -import ca.bc.gov.open.jag.efilingbackenddemo.api.DocumentApiDelegate; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; - -@Service -public class DocumentService implements DocumentApiDelegate { - - private final ResourceLoader resourceLoader; - - public DocumentService(ResourceLoader resourceLoader) { - this.resourceLoader = resourceLoader; - } - - @Override - public ResponseEntity getDocumentById(String id) { - return ResponseEntity.ok(resourceLoader.getResource("classpath:dummy.pdf")); - } -} diff --git a/src/backend/efiling-backend-demo/src/main/java/ca/bc/gov/open/jag/efilingbackenddemo/EfilingBackendDemoApplication.java b/src/backend/efiling-backend-demo/src/main/java/ca/bc/gov/open/jag/efilingbackenddemo/EfilingBackendDemoApplication.java deleted file mode 100644 index 31cbfd6395..0000000000 --- a/src/backend/efiling-backend-demo/src/main/java/ca/bc/gov/open/jag/efilingbackenddemo/EfilingBackendDemoApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package ca.bc.gov.open.jag.efilingbackenddemo; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class EfilingBackendDemoApplication { - - public static void main(String[] args) { - SpringApplication.run(EfilingBackendDemoApplication.class, args); - } - -} diff --git a/src/backend/efiling-backend-demo/src/main/resources/application.properties b/src/backend/efiling-backend-demo/src/main/resources/application.properties deleted file mode 100644 index 8b13789179..0000000000 --- a/src/backend/efiling-backend-demo/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/backend/efiling-backend-demo/src/main/resources/dummy.pdf b/src/backend/efiling-backend-demo/src/main/resources/dummy.pdf deleted file mode 100644 index 774c2ea70c..0000000000 Binary files a/src/backend/efiling-backend-demo/src/main/resources/dummy.pdf and /dev/null differ diff --git a/src/backend/efiling-backend-demo/src/test/java/ca/bc/gov/open/jag/efilingbackenddemo/DocumentServiceTest.java b/src/backend/efiling-backend-demo/src/test/java/ca/bc/gov/open/jag/efilingbackenddemo/DocumentServiceTest.java deleted file mode 100644 index 4b06ea86ed..0000000000 --- a/src/backend/efiling-backend-demo/src/test/java/ca/bc/gov/open/jag/efilingbackenddemo/DocumentServiceTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package ca.bc.gov.open.jag.efilingbackenddemo; - -import org.junit.jupiter.api.*; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.springframework.core.io.ByteArrayResource; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; - -import java.io.IOException; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@DisplayName("DocumentService Test Suite") -public class DocumentServiceTest { - - private DocumentService sut; - - @Mock - private ResourceLoader resourceLoaderMock; - - @BeforeAll - public void setup() { - - MockitoAnnotations.initMocks(this); - - - Resource resource = new ByteArrayResource("content".getBytes()); - Mockito.when(resourceLoaderMock.getResource(Mockito.eq("classpath:dummy.pdf"))).thenReturn(resource); - sut = new DocumentService(resourceLoaderMock); - - } - - @Test - @DisplayName("CASE 1: the ") - public void getDocumentShouldReturnResource() throws IOException { - - ResponseEntity actual = sut.getDocumentById("random"); - - Assertions.assertEquals(HttpStatus.OK, actual.getStatusCode()); - Assertions.assertEquals(7, actual.getBody().contentLength()); - - } - - -} diff --git a/src/backend/efiling-worker/README.md b/src/backend/efiling-worker/README.md deleted file mode 100644 index 283a487cc3..0000000000 --- a/src/backend/efiling-worker/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# efiling-worker - -### Configuration - -You should use environment variables to configure the efiling worker - -| Environment Variable | Type | Description | Notes | -| -------------------- | ------- | -------------------------------------------- | ------------------------------ | -| SERVER_PORT | Integer | web application server port | defaulted to `8080` | -| RABBITMQ_HOST | String | RabbitMQ host | defaulted to `localhost` | -| RABBITMQ_PORT | Integer | RabbitMQ port | defaulted to `5672` | -| RABBITMQ_PASSWORD | String | RabbitMQ password | defaulted to `guest` | -| RABBITMQ_USERNAME | String | RabbitMQ Username | defaulted to `guest` | - - -## Backend Folder Structure - -The backend API will follow the standard Java Spring Boot MVC model for folder structure breakdown where there are `models` and `controllers`. diff --git a/src/backend/efiling-worker/pom.xml b/src/backend/efiling-worker/pom.xml deleted file mode 100644 index 14572dd24b..0000000000 --- a/src/backend/efiling-worker/pom.xml +++ /dev/null @@ -1,135 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.3.1.RELEASE - - - ca.bc.gov.open.jag - efiling-worker - 0.0.1-SNAPSHOT - efiling-worker - File Submission Worker - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter - - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - - - ch.qos.logback - logback-access - - - net.rakugakibox.spring.boot - logback-access-spring-boot-starter - - - - ca.bc.gov.open.jag - efiling-submission-client - 0.0.1-SNAPSHOT - compile - - - - org.springframework.boot - spring-boot-starter-amqp - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - - - - - - - - ca.bc.gov.open.jag - efiling-bom - 0.0.1-SNAPSHOT - pom - import - - - - - - - - openshift - - - - splunk-artifactory - Splunk Releases - https://splunk.jfrog.io/artifactory/ext-releases-local/ - - - - - - com.splunk.logging - splunk-library-javalogging - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.jacoco - jacoco-maven-plugin - 0.8.5 - - - - - prepare-agent - - - - - - report - test - - report - - - - - - - - diff --git a/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/EfilingMessageConsumer.java b/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/EfilingMessageConsumer.java deleted file mode 100644 index 0cc6e03a82..0000000000 --- a/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/EfilingMessageConsumer.java +++ /dev/null @@ -1,38 +0,0 @@ -package ca.bc.gov.open.jag.efilingworker; - -import ca.bc.gov.ag.csows.filing.FilingPackage; -import ca.bc.gov.open.jag.efilingsubmissionclient.EfilingSubmissionService; -import ca.bc.gov.open.jag.efilingworker.service.DocumentStoreService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.amqp.rabbit.annotation.RabbitListener; -import org.springframework.stereotype.Component; - -import java.io.File; - - -@Component -public class EfilingMessageConsumer { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - private final DocumentStoreService documentStoreService; - - private final EfilingSubmissionService efilingSubmissionService; - - public EfilingMessageConsumer(DocumentStoreService documentStoreService, EfilingSubmissionService efilingSubmissionService) { - this.documentStoreService = documentStoreService; - this.efilingSubmissionService = efilingSubmissionService; - } - - @RabbitListener(queues = Keys.QUEUE_NAME) - public void acceptMessage(String guid) { - logger.info("Message received"); - //TODO: get data from redis? - logger.info("Getting file"); - //TODO: get file - logger.info("Uploading file"); - documentStoreService.uploadFile(new File("")); - logger.info("Submitting"); - efilingSubmissionService.submitFiling(new FilingPackage()); - } -} diff --git a/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/EfilingWorkerApplication.java b/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/EfilingWorkerApplication.java deleted file mode 100644 index 9468c60e7d..0000000000 --- a/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/EfilingWorkerApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package ca.bc.gov.open.jag.efilingworker; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - - -@SpringBootApplication -public class EfilingWorkerApplication { - - public static void main(String[] args) { - SpringApplication.run(EfilingWorkerApplication.class, args); - } - -} diff --git a/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/Keys.java b/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/Keys.java deleted file mode 100644 index db65d61ac3..0000000000 --- a/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/Keys.java +++ /dev/null @@ -1,10 +0,0 @@ -package ca.bc.gov.open.jag.efilingworker; - -public class Keys { - - private Keys() { - } - public static final String QUEUE_NAME = "efiling.documentstore.q"; - - -} diff --git a/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/config/EfilingWorkerConfig.java b/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/config/EfilingWorkerConfig.java deleted file mode 100644 index c7e5a941a0..0000000000 --- a/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/config/EfilingWorkerConfig.java +++ /dev/null @@ -1,14 +0,0 @@ -package ca.bc.gov.open.jag.efilingworker.config; - -import ca.bc.gov.open.jag.efilingsubmissionclient.DemoSubmissionServiceImpl; -import ca.bc.gov.open.jag.efilingsubmissionclient.EfilingSubmissionService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class EfilingWorkerConfig { - @Bean - public EfilingSubmissionService efilingSubmissionService() { - return new DemoSubmissionServiceImpl(); - } -} diff --git a/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/service/DocumentStoreService.java b/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/service/DocumentStoreService.java deleted file mode 100644 index 874330899e..0000000000 --- a/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/service/DocumentStoreService.java +++ /dev/null @@ -1,7 +0,0 @@ -package ca.bc.gov.open.jag.efilingworker.service; - -import java.io.File; - -public interface DocumentStoreService { - String uploadFile(File file); -} diff --git a/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/service/MockDocumentStoreServiceImpl.java b/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/service/MockDocumentStoreServiceImpl.java deleted file mode 100644 index e33de8240a..0000000000 --- a/src/backend/efiling-worker/src/main/java/ca/bc/gov/open/jag/efilingworker/service/MockDocumentStoreServiceImpl.java +++ /dev/null @@ -1,14 +0,0 @@ -package ca.bc.gov.open.jag.efilingworker.service; - -import org.springframework.stereotype.Service; - -import java.io.File; -import java.util.UUID; - -@Service -public class MockDocumentStoreServiceImpl implements DocumentStoreService { - @Override - public String uploadFile(File file) { - return UUID.randomUUID().toString(); - } -} diff --git a/src/backend/efiling-worker/src/main/resources/application-splunk.yml b/src/backend/efiling-worker/src/main/resources/application-splunk.yml deleted file mode 100644 index 65fd1a8e73..0000000000 --- a/src/backend/efiling-worker/src/main/resources/application-splunk.yml +++ /dev/null @@ -1,2 +0,0 @@ -logging: - config: "classpath:logback-splunk.xml" diff --git a/src/backend/efiling-worker/src/main/resources/application.yml b/src/backend/efiling-worker/src/main/resources/application.yml deleted file mode 100644 index 6a78eb0d69..0000000000 --- a/src/backend/efiling-worker/src/main/resources/application.yml +++ /dev/null @@ -1,9 +0,0 @@ -server: - port: ${PORT:8080} - -spring: - rabbitmq: - host: ${RABBITMQ_HOST:localhost} - port: ${RABBITMQ_PORT:5672} - username: ${RABBITMQ_USERNAME:guest} - password: ${RABBITMQ_PASSWORD:guest} diff --git a/src/backend/efiling-worker/src/main/resources/logback-access.xml b/src/backend/efiling-worker/src/main/resources/logback-access.xml deleted file mode 100644 index 6b72900908..0000000000 --- a/src/backend/efiling-worker/src/main/resources/logback-access.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - combined - - - - - - - - - ${SPLUNK_URL} - ${SPLUNK_TOKEN} - jag-efiling-api - jag-efiling-access-logs - HttpEventCollectorUnitTestMiddleware - true - 1 - - combined - - - - - - - - diff --git a/src/backend/efiling-worker/src/main/resources/logback-splunk.xml b/src/backend/efiling-worker/src/main/resources/logback-splunk.xml deleted file mode 100644 index 7b41d26230..0000000000 --- a/src/backend/efiling-worker/src/main/resources/logback-splunk.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - ​ - - - - - ${SPLUNK_URL} - ${SPLUNK_TOKEN} - jag-efiling-api - jag-efiling-access-logs - HttpEventCollectorUnitTestMiddleware - true - 1 - - %msg - - - - - ${CONSOLE_LOG_PATTERN} - - - - - - - diff --git a/src/backend/efiling-worker/src/main/resources/logback.xml b/src/backend/efiling-worker/src/main/resources/logback.xml deleted file mode 100644 index 600dc8c69c..0000000000 --- a/src/backend/efiling-worker/src/main/resources/logback.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - ​ - - - - - - ${CONSOLE_LOG_PATTERN} - - - - - - diff --git a/src/backend/efiling-worker/src/test/java/ca/bc/gov/open/jag/efilingworker/EfilingMessageConsumerTest.java b/src/backend/efiling-worker/src/test/java/ca/bc/gov/open/jag/efilingworker/EfilingMessageConsumerTest.java deleted file mode 100644 index e91d3b5b6f..0000000000 --- a/src/backend/efiling-worker/src/test/java/ca/bc/gov/open/jag/efilingworker/EfilingMessageConsumerTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package ca.bc.gov.open.jag.efilingworker; - -import ca.bc.gov.open.jag.efilingsubmissionclient.DemoSubmissionServiceImpl; -import ca.bc.gov.open.jag.efilingworker.service.MockDocumentStoreServiceImpl; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import java.math.BigDecimal; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@DisplayName("EfilingMessageConsumer Test Suite") -public class EfilingMessageConsumerTest { - private static final String TEST = "TEST"; - @InjectMocks - EfilingMessageConsumer sut; - - @Mock - MockDocumentStoreServiceImpl mockDocumentStoreService; - - @Mock - DemoSubmissionServiceImpl mockCSOSubmissionService; - - @BeforeAll - public void init() { - MockitoAnnotations.initMocks(this); - Mockito.when(mockDocumentStoreService.uploadFile(any())).thenReturn(TEST); - Mockito.when(mockCSOSubmissionService.submitFiling(any())).thenReturn(BigDecimal.ONE); - } - - @DisplayName("CASE1: Test acceptMessage execution") - @Test - public void test() { - sut.acceptMessage("TEST"); - verify(mockDocumentStoreService, times(1)).uploadFile(any()); - verify(mockCSOSubmissionService, times(1)).submitFiling(any()); - } -} diff --git a/src/backend/efiling-worker/src/test/java/ca/bc/gov/open/jag/efilingworker/config/EfilingWorkerConfigTest.java b/src/backend/efiling-worker/src/test/java/ca/bc/gov/open/jag/efilingworker/config/EfilingWorkerConfigTest.java deleted file mode 100644 index 77f2290770..0000000000 --- a/src/backend/efiling-worker/src/test/java/ca/bc/gov/open/jag/efilingworker/config/EfilingWorkerConfigTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package ca.bc.gov.open.jag.efilingworker.config; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -@DisplayName("EfilingWorkerConfig Test Suite") -public class EfilingWorkerConfigTest { - ApplicationContextRunner context = new ApplicationContextRunner() - .withUserConfiguration(EfilingWorkerConfig.class); - - @Test - @DisplayName("CASE1: Test that beans are created") - public void testBeansAreGenerated() { - context.run(it -> { - assertThat(it).hasSingleBean(EfilingWorkerConfig.class); - }); - } -} diff --git a/src/backend/efiling-worker/src/test/java/ca/bc/gov/open/jag/efilingworker/service/MockDocumentStoreServiceImplTest.java b/src/backend/efiling-worker/src/test/java/ca/bc/gov/open/jag/efilingworker/service/MockDocumentStoreServiceImplTest.java deleted file mode 100644 index 9575fdc386..0000000000 --- a/src/backend/efiling-worker/src/test/java/ca/bc/gov/open/jag/efilingworker/service/MockDocumentStoreServiceImplTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package ca.bc.gov.open.jag.efilingworker.service; - -import org.junit.jupiter.api.*; - -import java.io.File; - -@DisplayName("MockDocumentStoreService uploadFile Test Suite") -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -public class MockDocumentStoreServiceImplTest { - - private MockDocumentStoreServiceImpl sut; - - @BeforeAll - public void setUp() { - sut = new MockDocumentStoreServiceImpl(); - } - - @Test - @DisplayName("CASE1: with any request should return a string") - public void withAnyRequestShouldReturnSeven() { - - String actual = sut.uploadFile(new File("")); - - Assertions.assertNotNull(actual); - - } - -} diff --git a/src/backend/jaeger-docker-compose.yml b/src/backend/jaeger-docker-compose.yml deleted file mode 100644 index 6b953bc8ed..0000000000 --- a/src/backend/jaeger-docker-compose.yml +++ /dev/null @@ -1,45 +0,0 @@ - -version: '2' - -services: - jaeger-collector: - image: jaegertracing/jaeger-collector - command: ["--cassandra.keyspace=jaeger_v1_dc1", "--cassandra.servers=cassandra", "--collector.zipkin.http-port=9411"] - ports: - - "14269" - - "14268:14268" - - "14250" - - "9411:9411" - restart: on-failure - depends_on: - - cassandra-schema - - jaeger-query: - image: jaegertracing/jaeger-query - command: ["--cassandra.keyspace=jaeger_v1_dc1", "--cassandra.servers=cassandra"] - ports: - - "16686:16686" - - "16687" - restart: on-failure - depends_on: - - cassandra-schema - - jaeger-agent: - image: jaegertracing/jaeger-agent - command: ["--reporter.grpc.host-port=jaeger-collector:14250"] - ports: - - "5775:5775/udp" - - "6831:6831/udp" - - "6832:6832/udp" - - "5778:5778" - restart: on-failure - depends_on: - - jaeger-collector - - cassandra: - image: cassandra:3.9 - - cassandra-schema: - image: jaegertracing/jaeger-cassandra-schema - depends_on: - - cassandra \ No newline at end of file diff --git a/src/backend/libs/efiling-account-client/src/main/java/ca/bc/gov/open/jag/efilingaccountclient/CsoAccountServiceImpl.java b/src/backend/libs/efiling-account-client/src/main/java/ca/bc/gov/open/jag/efilingaccountclient/CsoAccountServiceImpl.java deleted file mode 100644 index f880fbd01a..0000000000 --- a/src/backend/libs/efiling-account-client/src/main/java/ca/bc/gov/open/jag/efilingaccountclient/CsoAccountServiceImpl.java +++ /dev/null @@ -1,118 +0,0 @@ -package ca.bc.gov.open.jag.efilingaccountclient; - -import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.RegisteredRole; -import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.RoleRegistryPortType; -import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.UserRoles; -import ca.bc.gov.ag.csows.accounts.AccountFacadeBean; -import ca.bc.gov.ag.csows.accounts.ClientProfile; -import ca.bc.gov.ag.csows.accounts.NestedEjbException_Exception; -import ca.bc.gov.open.jag.efilingaccountclient.mappers.AccountDetailsMapper; -import ca.bc.gov.open.jag.efilingcommons.exceptions.CSOHasMultipleAccountException; -import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingAccountServiceException; -import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; -import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; -import ca.bceid.webservices.client.v9.*; - -import java.util.*; - -public class CsoAccountServiceImpl implements EfilingAccountService { - - private final AccountFacadeBean accountFacadeBean; - private final RoleRegistryPortType roleRegistryPortType; - private final BCeIDServiceSoap bCeIDServiceSoap; - private final AccountDetailsMapper accountDetailsMapper; - - private static final Map accountTypeLookup; - static { - Map tempMap = new HashMap(); - tempMap.put("business", BCeIDAccountTypeCode.BUSINESS); - tempMap.put("individual", BCeIDAccountTypeCode.INDIVIDUAL); - tempMap.put("verified individual", BCeIDAccountTypeCode.VERIFIED_INDIVIDUAL); - tempMap.put("eds", BCeIDAccountTypeCode.EDS); - tempMap.put("internal", BCeIDAccountTypeCode.INTERNAL); - tempMap.put("ldb", BCeIDAccountTypeCode.LDB); - tempMap.put("ths", BCeIDAccountTypeCode.THS); - - accountTypeLookup = Collections.unmodifiableMap(tempMap);; - } - - public CsoAccountServiceImpl(AccountFacadeBean accountFacadeBean, - RoleRegistryPortType roleRegistryPortType, - BCeIDServiceSoap bCeIDServiceSoap, - AccountDetailsMapper accountDetailsMapper) { - - this.accountFacadeBean = accountFacadeBean; - this.roleRegistryPortType = roleRegistryPortType; - this.bCeIDServiceSoap = bCeIDServiceSoap; - this.accountDetailsMapper = accountDetailsMapper; - } - - @Override - public AccountDetails getAccountDetails(UUID userGuid, String bceidAccountType) { - - AccountDetails accountDetails = getCsoDetails(CsoHelpers.formatUserGuid(userGuid)); - if (null == accountDetails) { - accountDetails = getBCeIDDetails(CsoHelpers.formatUserGuid(userGuid), bceidAccountType); - } - - return accountDetails; - } - - private AccountDetails getCsoDetails(String userGuid) { - - AccountDetails accountDetails = null; - List profiles = new ArrayList<>(); - try { - profiles.addAll(accountFacadeBean.findProfiles(userGuid)); - } catch (NestedEjbException_Exception e) { - throw new EfilingAccountServiceException("Exception while fetching account details", e); - } - // An account must have only one profile associated with it to proceed - if (profiles.size() == 1) { - accountDetails = accountDetailsMapper.toAccountDetails(profiles.get(0), hasFileRole(userGuid)); - } - else if (profiles.size() > 1) { - throw new CSOHasMultipleAccountException(profiles.get(0).getClientId().toString()); - } - - return accountDetails; - } - - private AccountDetails getBCeIDDetails(String userGuid, String accountType) { - - AccountDetails accountDetails = null; - BCeIDAccountTypeCode accountTypeCode = getBCeIDAccountType(accountType); - - if (accountTypeCode != BCeIDAccountTypeCode.VOID) { - - AccountDetailRequest request = new AccountDetailRequest(); - request.setOnlineServiceId("62B2-5550-4376-4DA7"); - request.setRequesterUserGuid(userGuid); - request.setRequesterAccountTypeCode(accountTypeCode); - request.setUserGuid(userGuid); - request.setAccountTypeCode(accountTypeCode); - AccountDetailResponse response = bCeIDServiceSoap.getAccountDetail(request); - - if (response.getCode() == ResponseCode.SUCCESS) { - accountDetails = accountDetailsMapper.toAccountDetails(response.getAccount()); - } - } - - return accountDetails; - } - - public boolean hasFileRole(String userGuid) { - - UserRoles userRoles = roleRegistryPortType.getRolesForIdentifier("Courts", "CSO", userGuid, "CAP"); - List roles = userRoles.getRoles(); - return roles != null && roles.stream().anyMatch(r -> r.getCode().equals("FILE")); - } - - private BCeIDAccountTypeCode getBCeIDAccountType(String bceidAccountType) { - String lookUp = bceidAccountType.toLowerCase(); - BCeIDAccountTypeCode code = accountTypeLookup.get(lookUp); - return code == null? BCeIDAccountTypeCode.VOID : code; - } - - -} diff --git a/src/backend/libs/efiling-account-client/src/main/java/ca/bc/gov/open/jag/efilingaccountclient/CsoHelpers.java b/src/backend/libs/efiling-account-client/src/main/java/ca/bc/gov/open/jag/efilingaccountclient/CsoHelpers.java deleted file mode 100644 index 0e94297b98..0000000000 --- a/src/backend/libs/efiling-account-client/src/main/java/ca/bc/gov/open/jag/efilingaccountclient/CsoHelpers.java +++ /dev/null @@ -1,21 +0,0 @@ -package ca.bc.gov.open.jag.efilingaccountclient; - -import java.util.UUID; - -/** - * Helper class for CSO - */ -public class CsoHelpers { - - private CsoHelpers() {} - - /** - * Converts UUID to CSO ID FORMAT: no hyphen and all upper case. - * @param id - * @return - */ - public static String formatUserGuid(UUID id) { - return id.toString().replace("-", "").toUpperCase(); - } - -} diff --git a/src/backend/libs/efiling-account-client/src/main/java/ca/bc/gov/open/jag/efilingaccountclient/config/AutoConfiguration.java b/src/backend/libs/efiling-account-client/src/main/java/ca/bc/gov/open/jag/efilingaccountclient/config/AutoConfiguration.java deleted file mode 100644 index 26ae6544c4..0000000000 --- a/src/backend/libs/efiling-account-client/src/main/java/ca/bc/gov/open/jag/efilingaccountclient/config/AutoConfiguration.java +++ /dev/null @@ -1,73 +0,0 @@ -package ca.bc.gov.open.jag.efilingaccountclient.config; - -import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.RoleRegistryPortType; -import ca.bc.gov.ag.csows.accounts.AccountFacadeBean; -import ca.bc.gov.open.jag.efilingaccountclient.CsoAccountServiceImpl; -import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; -import ca.bc.gov.open.jag.efilingaccountclient.mappers.AccountDetailsMapper; -import ca.bc.gov.open.jag.efilingaccountclient.mappers.AccountDetailsMapperImpl; -import ca.bc.gov.open.jag.efilingcommons.model.Clients; -import ca.bc.gov.open.jag.efilingcommons.model.EfilingSoapClientProperties; -import ca.bc.gov.open.jag.efilingcommons.model.SoapProperties; -import ca.bceid.webservices.client.v9.BCeIDServiceSoap; -import org.apache.commons.lang3.StringUtils; -import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - - - -@Configuration -@EnableConfigurationProperties(SoapProperties.class) -public class AutoConfiguration { - - private final SoapProperties soapProperties; - - - public AutoConfiguration(SoapProperties soapProperties) { - this.soapProperties = soapProperties; - } - - @Bean - public AccountFacadeBean accountFacadeBean() { - return getPort(Clients.ACCOUNT, AccountFacadeBean.class); - } - - @Bean - public RoleRegistryPortType roleRegistryPortType() { - return getPort(Clients.ROLE, RoleRegistryPortType.class); - } - - @Bean - public BCeIDServiceSoap bCeIDServiceSoap() { return getPort(Clients.BCEID, BCeIDServiceSoap.class); } - - @Bean - public AccountDetailsMapper accountDetailsMapper() { - return new AccountDetailsMapperImpl(); - } - - @Bean - @ConditionalOnMissingBean({EfilingAccountService.class}) - public EfilingAccountService efilingAccountService(AccountFacadeBean accountFacadeBean, - RoleRegistryPortType roleRegistryPortType, - BCeIDServiceSoap bCeIDServiceSoap, - AccountDetailsMapper accountDetailsMapper) { - return new CsoAccountServiceImpl(accountFacadeBean, roleRegistryPortType, - bCeIDServiceSoap, accountDetailsMapper); - } - - public T getPort(Clients clients, Class type) { - JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean(); - jaxWsProxyFactoryBean.setServiceClass(type); - EfilingSoapClientProperties efilingSoapClientProperties = soapProperties.findByEnum(clients); - jaxWsProxyFactoryBean.setAddress(efilingSoapClientProperties.getUri()); - if(StringUtils.isNotBlank(efilingSoapClientProperties.getUserName())) - jaxWsProxyFactoryBean.setUsername(efilingSoapClientProperties.getUserName()); - if(StringUtils.isNotBlank(efilingSoapClientProperties.getPassword())) - jaxWsProxyFactoryBean.setPassword(efilingSoapClientProperties.getPassword()); - return type.cast(jaxWsProxyFactoryBean.create()); - } - -} diff --git a/src/backend/libs/efiling-account-client/src/main/java/ca/bc/gov/open/jag/efilingaccountclient/mappers/AccountDetailsMapper.java b/src/backend/libs/efiling-account-client/src/main/java/ca/bc/gov/open/jag/efilingaccountclient/mappers/AccountDetailsMapper.java deleted file mode 100644 index d309bccae7..0000000000 --- a/src/backend/libs/efiling-account-client/src/main/java/ca/bc/gov/open/jag/efilingaccountclient/mappers/AccountDetailsMapper.java +++ /dev/null @@ -1,30 +0,0 @@ -package ca.bc.gov.open.jag.efilingaccountclient.mappers; - -import ca.bc.gov.ag.csows.accounts.ClientProfile; -import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; -import ca.bceid.webservices.client.v9.BCeIDAccount; -import org.mapstruct.Mapper; -import org.mapstruct.Mapping; - -@Mapper -public interface AccountDetailsMapper { - - @Mapping(target = "accountId", source = "clientProfile.accountId") - @Mapping(target = "clientId", source = "clientProfile.clientId") - @Mapping(target = "firstName", source = "clientProfile.account.accountManager.givenNm") - @Mapping(target = "lastName", source = "clientProfile.account.accountManager.surnameNm") - @Mapping(target = "middleName", source = "clientProfile.account.accountManager.middleNm") - @Mapping(target = "email", source = "clientProfile.account.accountManager.emailTxt") - @Mapping(target = "fileRolePresent", source = "fileRolePresent") - AccountDetails toAccountDetails(ClientProfile clientProfile, Boolean fileRolePresent); - - @Mapping(target = "accountId", defaultValue = "0") - @Mapping(target = "clientId", defaultValue = "0") - @Mapping(target = "firstName", source = "individualIdentity.name.firstname.value") - @Mapping(target = "lastName", source = "individualIdentity.name.surname.value") - @Mapping(target = "middleName", source = "individualIdentity.name.middleName.value") - @Mapping(target = "email", source = "contact.email.value") - @Mapping(target = "fileRolePresent", defaultValue = "false") - AccountDetails toAccountDetails(BCeIDAccount bceidAccount); - -} diff --git a/src/backend/libs/efiling-account-client/src/main/resources/META-INF/spring.factories b/src/backend/libs/efiling-account-client/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 0a6d7357bb..0000000000 --- a/src/backend/libs/efiling-account-client/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - ca.bc.gov.open.jag.efilingaccountclient.config.AutoConfiguration \ No newline at end of file diff --git a/src/backend/libs/efiling-account-client/src/main/resources/wsdl/BCeIDService.wsdl b/src/backend/libs/efiling-account-client/src/main/resources/wsdl/BCeIDService.wsdl deleted file mode 100644 index eb2c7008f2..0000000000 --- a/src/backend/libs/efiling-account-client/src/main/resources/wsdl/BCeIDService.wsdl +++ /dev/null @@ -1,1076 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Get Internal User Group Membership Information - - - - - Search for all BCeID accounts. - - - - - Search for all internal accounts. - - - - - Get details for a given list of accounts. - - - - - Get details for a given account. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/backend/libs/efiling-account-client/src/test/java/ca/bc/gov/open/jag/efilingaccountclient/config/AutoConfigurationTest.java b/src/backend/libs/efiling-account-client/src/test/java/ca/bc/gov/open/jag/efilingaccountclient/config/AutoConfigurationTest.java deleted file mode 100644 index 3fce6d52fe..0000000000 --- a/src/backend/libs/efiling-account-client/src/test/java/ca/bc/gov/open/jag/efilingaccountclient/config/AutoConfigurationTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package ca.bc.gov.open.jag.efilingaccountclient.config; - - -import ca.bc.gov.open.jag.efilingaccountclient.CsoAccountServiceImpl; -import ca.bc.gov.open.jag.efilingaccountclient.mappers.AccountDetailsMapperImpl; -import ca.bc.gov.open.jag.efilingcommons.model.Clients; -import ca.bc.gov.open.jag.efilingcommons.model.EfilingSoapClientProperties; -import ca.bc.gov.open.jag.efilingcommons.model.SoapProperties; -import org.junit.jupiter.api.*; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import java.util.ArrayList; - -@DisplayName("AutoConfiguration Test") -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -public class AutoConfigurationTest { - private static final String URI = "URI"; - private static final String USERNAME = "USERNAME"; - private static final String PASSWORD = "PASSWORD"; - ApplicationContextRunner context = new ApplicationContextRunner() - .withUserConfiguration(AutoConfiguration.class); - - private AutoConfiguration sut; - - @BeforeAll - public void setup() { - sut = new AutoConfiguration(initSoapProperties()); - } - - @Test - @DisplayName("Test that beans are created") - public void testBeansAreGenerated() { - - - Assertions.assertNotNull(sut.accountFacadeBean()); - Assertions.assertNotNull(sut.roleRegistryPortType()); - Assertions.assertNotNull(sut.bCeIDServiceSoap()); - Assertions.assertEquals(CsoAccountServiceImpl.class, sut.efilingAccountService(null, null, null, null).getClass()); - Assertions.assertEquals(AccountDetailsMapperImpl.class, sut.accountDetailsMapper().getClass()); - } - - private SoapProperties initSoapProperties() { - - ArrayList soapClientProperties = new ArrayList<>(); - - EfilingSoapClientProperties accountProperties = new EfilingSoapClientProperties(); - accountProperties.setClient(Clients.ACCOUNT); - accountProperties.setUri(URI); - accountProperties.setUserName(USERNAME); - accountProperties.setPassword(PASSWORD); - soapClientProperties.add(accountProperties); - - EfilingSoapClientProperties roleProperties = new EfilingSoapClientProperties(); - roleProperties.setClient(Clients.ROLE); - roleProperties.setUri(URI); - roleProperties.setUserName(USERNAME); - roleProperties.setPassword(PASSWORD); - soapClientProperties.add(roleProperties); - - EfilingSoapClientProperties bceidProperties = new EfilingSoapClientProperties(); - bceidProperties.setClient(Clients.BCEID); - bceidProperties.setUri(URI); - bceidProperties.setUserName(USERNAME); - bceidProperties.setPassword(PASSWORD); - soapClientProperties.add(bceidProperties); - - SoapProperties soapProperties = new SoapProperties(); - soapProperties.setClients(soapClientProperties); - - return soapProperties; - } -} diff --git a/src/backend/libs/efiling-bambora-api-client/payments-swagger.yaml b/src/backend/libs/efiling-bambora-api-client/payments-swagger.yaml new file mode 100644 index 0000000000..b280182535 --- /dev/null +++ b/src/backend/libs/efiling-bambora-api-client/payments-swagger.yaml @@ -0,0 +1,2460 @@ +swagger: "2.0" +info: + title: Bambora Payment APIs + description: "https://api.na.bambora.com/v1" + version: 1.0.5 +host: api.na.bambora.com +schemes: + - https +basePath: /v1 +consumes: + - application/json +produces: + - application/json +securityDefinitions: + Passcode: + type: apiKey + in: header + name: Authorization + description: 'Pass the authorization header in your request as "Authorization: Passcode Base64Encoded(merchant_id:passcode)"' + Sub-Merchant-Id: + type: apiKey + in: header + name: Sub-Merchant-Id + description: 'OPTIONAL: Only used by partners to make an API call on behalf of their subMerchant. Pass the header in your request as "Sub-Merchant-Id: sub_merchant_id"' +security: + - Passcode: [] + - Sub-Merchant-Id: [] +paths: + /payments: + post: + summary: Make payment + description: | + Make a payment using credit card, cash, cheque, profile, token, Apple Pay or Android Pay. Each payment type has its own json definition passed in the + body. For all payments you have the standard Billing, Shipping, Comments, etc. fields that are optional. Only the amount is required along with the + payment data for card, cash, cheque, profile, and token. You must change the payment_method for each payment type. Credit Card - "card", + Payment Profile - "payment_profile", Legato Token - "token", Cash - "cash", Cheque - "cheque", Interac - "interac", Apple Pay - "apple_pay", + Android Pay - "android_pay". + tags: + - Payments + operationId: makePayment + parameters: + - name: payment_request + in: body + schema: + $ref: "#/definitions/PaymentRequest" + responses: + 200: + description: Payment response containing the payment details as well as if the payment was approved or declined. + schema: + $ref: "#/definitions/PaymentResponse" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + "/payments/{transId}/returns": + post: + summary: Return payment + description: Return payment. + tags: + - Payments + operationId: returnPayment + parameters: + - name: transId + in: path + description: The transaction id. + required: true + type: number + format: double + - name: return + in: body + required: true + schema: + $ref: "#/definitions/Return" + responses: + 200: + description: Payment response containing the payment details as well as if the transaction was approved or declined. + schema: + $ref: "#/definitions/PaymentResponse" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + "/payments/{transId}/void": + post: + summary: Void transaction + description: "Void a transaction. You can void payments, returns, pre-auths, and completions. It will cancel that transaction." + tags: + - Payments + operationId: voidPayment + parameters: + - name: transId + in: path + description: The transaction id to void. + required: true + type: number + format: integer + - name: void + in: body + required: true + schema: + $ref: "#/definitions/Void" + responses: + 200: + description: Payment response containing the payment details as well as if the transaction was approved or declined. + schema: + $ref: "#/definitions/PaymentResponse" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + "/payments/{transId}/completions": + post: + summary: Complete pre-auth + description: Complete a pre-authorized payment. The amount of the transaction to complete must be less than or equal to the original pre-auth amount. Complete must be set to true. + tags: + - Payments + operationId: completePayment + parameters: + - name: transId + in: path + description: The transaction id. + required: true + type: number + format: double + - name: payment_request + in: body + schema: + $ref: "#/definitions/PaymentRequest" + responses: + 200: + description: Payment response containing the payment details as well as if the transaction was approved or declined. + schema: + $ref: "#/definitions/PaymentResponse" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + "/payments/{transId}": + get: + summary: Get payment + description: Get a previous payment (transaction). + tags: + - Payments + operationId: getPayment + parameters: + - name: transId + in: path + description: The transaction id. + required: true + type: number + format: integer + responses: + 200: + description: A transaction object. + schema: + $ref: "#/definitions/Transaction" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + "/payments/{merchant_data}/continue": + post: + summary: 3D Secure or Interac Online payments + description: Continues 3D Secure or Interac Online payment processing. + tags: + - Payments + operationId: continuePayment + parameters: + - name: merchant_data + in: path + description: "The merchant_data attribute value returned from the initiating Payments API request. The value represents a unique payment ID." + required: true + type: string + - name: continue_request + in: body + required: true + schema: + $ref: "#/definitions/ContinueRequest" + responses: + 200: + description: Payment response containing the payment details as well as if the transaction was approved or declined. + schema: + $ref: "#/definitions/PaymentResponse" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + /reports: + post: + summary: Search Query + description: "Query for transactions using a date range and optional search criteria. This method allows you to page your search results if you are expecting a lot of results to be returned. The page start value begins at 1. If no records are found the API will return a 200 response message with an empty array. For details on the parameters and allowed values for Criteria please visit the documentation http://dev.na.bambora.com" + tags: + - Reporting + operationId: getReport + parameters: + - name: search_query + in: body + schema: + $ref: "#/definitions/SearchQuery" + responses: + 200: + description: A transaction object. + schema: + $ref: "#/definitions/SearchResult" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + /profiles: + post: + summary: Create Profile + description: Create a new Payment Profile using either a card, a single-use token, a transaction id, or bank credentials. You must supply one of them. You may store a card and bank credentials on the same profile. + tags: + - Profiles + operationId: createProfile + parameters: + - name: createProfileBody + in: body + required: true + schema: + $ref: "#/definitions/ProfileBody" + responses: + 200: + description: The Profile. + schema: + $ref: "#/definitions/ProfileResponse" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + "/profiles/{profileId}": + get: + summary: Get profile + description: "Get a Payment Profile using the profile ID, also known as the Customer Code." + tags: + - Profiles + operationId: getProfile + parameters: + - name: profileId + in: path + description: The profile id. (aka CustomerCode) + required: true + type: string + responses: + 200: + description: The Profile. + schema: + $ref: "#/definitions/PaymentProfileResponse" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + put: + summary: Update Profile + description: | + Update an existing Payment Profile. For a single card profile supplying token or + card data will work. For multi-card profiles you have to update the card data with + the update and delete card endpoints. + tags: + - Profiles + operationId: updateProfile + parameters: + - name: profileId + in: path + description: The profile id. (aka CustomerCode) + required: true + type: string + - name: updateProfileBody + in: body + required: true + schema: + $ref: "#/definitions/ProfileBody" + responses: + 200: + description: The Profile. + schema: + $ref: "#/definitions/ProfileResponse" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + delete: + summary: Delete profile + description: "Delete a Payment Profile using the profile ID, also known as the Customer Code." + tags: + - Profiles + operationId: deleteProfile + parameters: + - name: profileId + in: path + description: The profile id. (aka CustomerCode) + required: true + type: string + responses: + 200: + description: The Profile. + schema: + $ref: "#/definitions/ProfileResponse" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + "/profiles/{profileId}/cards": + get: + summary: Get cards + description: Get all of the cards on the profile. + tags: + - Profiles + operationId: getAllCards + parameters: + - name: profileId + in: path + description: The profile id. (aka CustomerCode) + required: true + type: string + responses: + 200: + description: The Profile. + schema: + $ref: "#/definitions/ProfileGetCards" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + post: + summary: Add card + description: Add a card to the profile. Note that there is a default limit of 1 card per profile. You can change this in your Profiles settings in the back office. + tags: + - Profiles + operationId: addCard + parameters: + - name: profileId + in: path + description: The profile id. (aka CustomerCode) + required: true + type: string + - name: body + in: body + description: The card information that will be added to the profile. + required: true + schema: + $ref: "#/definitions/ProfileBodyCard" + responses: + 200: + description: The Profile. + schema: + $ref: "#/definitions/ProfileResponse" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + "/profiles/{profileId}/cards/{cardId}": + get: + summary: Get card + description: Get the details of a card on the profile. + tags: + - Profiles + operationId: getCard + parameters: + - name: profileId + in: path + description: The profile id. (aka CustomerCode) + required: true + type: string + - name: cardId + in: path + description: The card id. + required: true + type: number + format: integer + responses: + 200: + description: The Profile. + schema: + $ref: "#/definitions/ProfileCardResponse" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + put: + summary: Update card + description: Update the details of a card on the profile. A card number can only be updated when an account is configured to only allow 1 card per profile. + tags: + - Profiles + operationId: updateCard + parameters: + - name: profileId + in: path + description: The profile id. (aka CustomerCode) + required: true + type: string + - name: cardId + in: path + description: The card id. + required: true + type: number + format: integer + - name: body + in: body + description: The card information that will be updated on the profile. + required: true + schema: + $ref: "#/definitions/ProfileBodyCard" + responses: + 200: + description: The Profile. + schema: + $ref: "#/definitions/ProfileResponse" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + delete: + summary: Delete card + description: Delete a card on the profile. + tags: + - Profiles + operationId: deleteCard + parameters: + - name: profileId + in: path + description: The profile id. (aka CustomerCode) + required: true + type: string + - name: cardId + in: path + description: The card id. + required: true + type: number + format: integer + responses: + 200: + description: The Profile. + schema: + $ref: "#/definitions/ProfileResponse" + 400: + $ref: "#/responses/BadRequest" + 401: + $ref: "#/responses/Unauthorized" + 402: + $ref: "#/responses/PaymentRequired" + 403: + $ref: "#/responses/Forbidden" + 405: + $ref: "#/responses/MethodNotAllowed" + 500: + $ref: "#/responses/InternalServerError" + /scripts/tokenization/tokens: + post: + summary: Tokenize credit card + description: "NOTE that the full URL for this API call is https://api.na.bambora.com/scripts/tokenization/tokens. Turn a credit card into a token using this service. This helps lessen your PCI scope by not passing the credit card information to your server. Instead you turn the card number into a token in the client app, then send the token to the server. When you send the token to Bambora to make a payment, Bambora then looks up the card number from that token and makes the payment. Tokens can also be used to create payment profiles." + tags: + - Tokenization + operationId: tokenizeCard + parameters: + - name: token_request + in: body + schema: + $ref: "#/definitions/TokenRequest" + responses: + 200: + description: Token response object. One will always be returned even if the data or card is invalid. The validity of the card is not checked with this API call. + schema: + $ref: "#/definitions/TokenResponse" +responses: + BadRequest: + description: Bad Request + schema: + $ref: "#/definitions/ErrorResponse" + Unauthorized: + description: Authentication Failure + schema: + $ref: "#/definitions/ErrorResponse" + PaymentRequired: + description: Business Rule Violation or Decline + schema: + $ref: "#/definitions/ErrorResponse" + Forbidden: + description: Authorization Failure + schema: + $ref: "#/definitions/ErrorResponse" + MethodNotAllowed: + description: Invalid Request Method + schema: + $ref: "#/definitions/ErrorResponse" + InternalServerError: + description: Internal Server Error + schema: + $ref: "#/definitions/ErrorResponse" +definitions: + PaymentRequest: + required: + - amount + - payment_method + properties: + order_number: + type: string + maxLength: 30 + description: "A unique order number." + amount: + type: number + format: double + description: "A decimal value in dollars. Uses up to two decimal places. Max value is account specific. Default max value is 1000." + payment_method: + type: string + description: "The desired method of payment." + enum: + [ + "card", + "token", + "payment_profile", + "cash", + "cheque", + "interac", + "apple_pay", + "android_pay", + ] + language: + type: string + maxLength: 3 + description: characters + customer_ip: + type: string + maxLength: 30 + description: IP Address of the api consumer. Required if calculating risk score. + term_url: + type: string + maxLength: 256 + description: "Callback URL used with 3D Secure payment processing." + comments: + type: string + maxLength: 256 + description: alphanumeric + billing: + $ref: "#/definitions/RequestBillingAddress" + shipping: + $ref: "#/definitions/Address" + custom: + $ref: "#/definitions/Custom" + card: + $ref: "#/definitions/Card" + apple_pay: + $ref: "#/definitions/ApplePay" + android_pay: + $ref: "#/definitions/AndroidPay" + payment_profile: + $ref: "#/definitions/ProfilePurchase" + token: + $ref: "#/definitions/TokenPurchase" + recurring_payment: + type: boolean + description: | + A recurring transaction is a transaction where a cardholder had provided permission to a merchant to + periodically charge his/her account number for recurring goods or services. The recurring payment + indicator may be set for credit card based pre-auth, capture and purchase transactions. + level2: + $ref: "#/definitions/Level2" + card_on_file: + $ref: "#/definitions/CardOnFile" + Card: + description: "Payment with a credit card. The payment_method must be 'card'" + required: + - name + - number + - expiry_month + - expiry_year + properties: + number: + type: string + maxLength: 20 + description: Credit card number (PAN). + default: "5100000010001004" + name: + type: string + minLength: 1 + maxLength: 64 + description: Card holder name. + expiry_month: + type: string + maxLength: 2 + default: "02" + description: eg. 02 for February. + expiry_year: + type: string + maxLength: 2 + default: "18" + description: eg. 15 for 2015. + cvd: + type: string + minLength: 3 + maxLength: 4 + default: "123" + description: Security code on the back of the credit card. This can be set to mandatory in the back office. + 3d_secure: + $ref: "#/definitions/3DSecure" + masterpass_wallet_id: + type: string + maxLength: 3 + description: "The Masterpass code related to the wallet that the card information was sent from." + visa_checkout_call_id: + type: string + maxLength: 20 + description: "The Visa Checkout payment request ID." + complete: + type: boolean + default: true + description: "set to false for Pre-Authorize, and true to complete a payment" + is_accord_d: + type: boolean + default: false + description: "required flag for desjardin visa cards that want to make Accord D financing transactions. Accord D transactions require billing information as well" + accord_d: + $ref: "#/definitions/AccordD" + AccordD: + description: "Desjardin Visa Only - required for a complete Accord D financing transaction" + required: + - financing_type + - plan_number + - grace_period + - term + properties: + financing_type: + description: "Deferred(D) or Equal(E) payment" + default: "E" + type: string + maxLength: 1 + enum: ["D", "E"] + plan_number: + type: string + maxLength: 3 + description: "Must be a value between 000 - ZZZ" + grace_period: + type: integer + default: 00 + description: "Must be 0 if financing_type is not a deferred payment" + term: + type: integer + description: "Number of months. Must be 00 is financing_type is not a deferred payment" + ApplePay: + description: | + Apple Pay Only - required when attempting to process apple_pay transactions. + Note that the 'card' object returned in a successful response will have a 'last_four' property value that is based on the source Apple Pay Wallet and its Device Account Number. + required: + - apple_pay_merchant_id + - payment_token + properties: + apple_pay_merchant_id: + type: string + description: The Apple Pay merchant ID. + payment_token: + type: string + description: The encrypted token provided by Apple Pay that you then Base64 encode. + complete: + type: boolean + default: true + description: set to false for Pre-Authorize, and true to complete a payment + AndroidPay: + description: | + Android Pay Only - required when attempting to process android_pay transactions. + Note that the 'card' object returned in a successful response will have a 'last_four' property value that is based on the source Android Pay Wallet and its Device Account Number. + required: + - android_pay_merchant_id + - payment_token + properties: + android_pay_merchant_id: + type: string + description: The Android Pay merchant ID. + payment_token: + type: string + description: The encrypted token provided by Android Pay that you then Base64 encode. + complete: + type: boolean + default: true + description: set to false for Pre-Authorize, and true to complete a payment + ProfilePurchase: + description: "Payment with a Payment Profile. The payment_method must be 'payment_profile'" + required: + - customer_code + - card_id + properties: + complete: + type: boolean + default: true + description: "set to false for Pre-Authorize, and true to complete a payment" + customer_code: + type: string + maxLength: 32 + description: The payment profile ID. + card_id: + type: integer + maxLength: 1 + description: Which credit card to use. Starts at 1 for the first card. You must configure how many cards can be stored by visiting the profile options in the back office. + TokenPurchase: + description: "Payment with a single-use token. The payment_method must be 'token'" + required: + - code + - name + properties: + complete: + type: boolean + default: false + description: "set to false for Pre-Authorize, and true to complete a payment" + code: + type: string + maxLength: 36 + description: the payment token you retrieved from the Legato service. + name: + type: string + minLength: 4 + maxLength: 64 + description: Card holder name. + 3d_secure: + $ref: "#/definitions/3DSecure" + masterpass_wallet_id: + type: string + maxLength: 3 + description: "The Masterpass code related to the wallet that the card information was sent from." + visa_checkout_call_id: + type: string + maxLength: 20 + description: "The Visa Checkout payment request ID." + RequestBillingAddress: + properties: + name: + type: string + maxLength: 64 + description: Name of the person/business + address_line1: + type: string + maxLength: 64 + description: Street address. Impacts risk score. + address_line2: + type: string + maxLength: 64 + description: Additional address information(eg; suite number, apartment number, etc) + city: + type: string + maxLength: 32 + description: The city. Impacts risk score. + province: + type: string + description: 2 characters. Set to -- for any countries except for US and Canada. Impacts risk score. + country: + type: string + maxLength: 2 + description: "Valid ISO 3166-1 country code. Impacts risk score." + enum: + [ + "AD", + "AE", + "AF", + "AG", + "AI", + "AL", + "AM", + "AO", + "AQ", + "AR", + "AS", + "AT", + "AU", + "AW", + "AX", + "AZ", + "BA", + "BB", + "BD", + "BE", + "BF", + "BG", + "BH", + "BI", + "BJ", + "BL", + "BM", + "BN", + "BO", + "BQ", + "BR", + "BS", + "BT", + "BV", + "BW", + "BY", + "BZ", + "CA", + "CC", + "CD", + "CF", + "CG", + "CH", + "CI", + "CK", + "CL", + "CM", + "CN", + "CO", + "CR", + "CU", + "CV", + "CW", + "CX", + "CY", + "CZ", + "DE", + "DJ", + "DK", + "DM", + "DO", + "DZ", + "EC", + "EE", + "EG", + "EH", + "ER", + "ES", + "ET", + "FI", + "FJ", + "FK", + "FM", + "FO", + "FR", + "GA", + "GB", + "GD", + "GE", + "GF", + "GG", + "GH", + "GI", + "GL", + "GM", + "GN", + "GP", + "GQ", + "GR", + "GS", + "GT", + "GU", + "GW", + "GY", + "HK", + "HM", + "HN", + "HR", + "HT", + "HU", + "ID", + "IE", + "IL", + "IM", + "IN", + "IO", + "IQ", + "IR", + "IS", + "IT", + "JE", + "JM", + "JO", + "JP", + "KE", + "KG", + "KH", + "KI", + "KM", + "KN", + "KP", + "KR", + "KW", + "KY", + "KZ", + "LA", + "LB", + "LC", + "LI", + "LK", + "LR", + "LS", + "LT", + "LU", + "LV", + "LY", + "MA", + "MC", + "MD", + "ME", + "MF", + "MG", + "MH", + "MK", + "ML", + "MM", + "MN", + "MO", + "MP", + "MQ", + "MR", + "MS", + "MT", + "MU", + "MV", + "MW", + "MX", + "MY", + "MZ", + "NA", + "NC", + "NE", + "NF", + "NG", + "NI", + "NL", + "NO", + "NP", + "NR", + "NU", + "NZ", + "OM", + "PA", + "PE", + "PF", + "PG", + "PH", + "PK", + "PL", + "PM", + "PN", + "PR", + "PS", + "PT", + "PW", + "PY", + "QA", + "RE", + "RO", + "RS", + "RU", + "RW", + "SA", + "SB", + "SC", + "SD", + "SE", + "SG", + "SH", + "SI", + "SJ", + "SK", + "SL", + "SM", + "SN", + "SO", + "SR", + "SS", + "ST", + "SV", + "SX", + "SY", + "SZ", + "TC", + "TD", + "TF", + "TG", + "TH", + "TJ", + "TK", + "TL", + "TM", + "TN", + "TO", + "TR", + "TT", + "TV", + "TW", + "TZ", + "UA", + "UG", + "UM", + "US", + "UY", + "UZ", + "VA", + "VC", + "VE", + "VG", + "VI", + "VN", + "VU", + "WF", + "WS", + "YE", + "YT", + "ZA", + "ZM", + "ZW", + ] + postal_code: + type: string + maxLength: 16 + description: "Postal/Zip code. Impacts risk score." + phone_number: + type: string + description: "Phone number" + pattern: '^\d{1,20}$' + email_address: + type: string + maxLength: 64 + description: Email Address. Impacts risk score. + Address: + properties: + name: + type: string + maxLength: 64 + description: Name of the person/business + address_line1: + type: string + maxLength: 64 + description: Street address + address_line2: + type: string + maxLength: 64 + description: Additional address information(eg; suite number, apartment number, etc) + city: + type: string + maxLength: 32 + description: The city + province: + type: string + description: characters (2) + country: + type: string + maxLength: 2 + description: "Valid ISO 3166-1 country code" + enum: + [ + "AD", + "AE", + "AF", + "AG", + "AI", + "AL", + "AM", + "AO", + "AQ", + "AR", + "AS", + "AT", + "AU", + "AW", + "AX", + "AZ", + "BA", + "BB", + "BD", + "BE", + "BF", + "BG", + "BH", + "BI", + "BJ", + "BL", + "BM", + "BN", + "BO", + "BQ", + "BR", + "BS", + "BT", + "BV", + "BW", + "BY", + "BZ", + "CA", + "CC", + "CD", + "CF", + "CG", + "CH", + "CI", + "CK", + "CL", + "CM", + "CN", + "CO", + "CR", + "CU", + "CV", + "CW", + "CX", + "CY", + "CZ", + "DE", + "DJ", + "DK", + "DM", + "DO", + "DZ", + "EC", + "EE", + "EG", + "EH", + "ER", + "ES", + "ET", + "FI", + "FJ", + "FK", + "FM", + "FO", + "FR", + "GA", + "GB", + "GD", + "GE", + "GF", + "GG", + "GH", + "GI", + "GL", + "GM", + "GN", + "GP", + "GQ", + "GR", + "GS", + "GT", + "GU", + "GW", + "GY", + "HK", + "HM", + "HN", + "HR", + "HT", + "HU", + "ID", + "IE", + "IL", + "IM", + "IN", + "IO", + "IQ", + "IR", + "IS", + "IT", + "JE", + "JM", + "JO", + "JP", + "KE", + "KG", + "KH", + "KI", + "KM", + "KN", + "KP", + "KR", + "KW", + "KY", + "KZ", + "LA", + "LB", + "LC", + "LI", + "LK", + "LR", + "LS", + "LT", + "LU", + "LV", + "LY", + "MA", + "MC", + "MD", + "ME", + "MF", + "MG", + "MH", + "MK", + "ML", + "MM", + "MN", + "MO", + "MP", + "MQ", + "MR", + "MS", + "MT", + "MU", + "MV", + "MW", + "MX", + "MY", + "MZ", + "NA", + "NC", + "NE", + "NF", + "NG", + "NI", + "NL", + "NO", + "NP", + "NR", + "NU", + "NZ", + "OM", + "PA", + "PE", + "PF", + "PG", + "PH", + "PK", + "PL", + "PM", + "PN", + "PR", + "PS", + "PT", + "PW", + "PY", + "QA", + "RE", + "RO", + "RS", + "RU", + "RW", + "SA", + "SB", + "SC", + "SD", + "SE", + "SG", + "SH", + "SI", + "SJ", + "SK", + "SL", + "SM", + "SN", + "SO", + "SR", + "SS", + "ST", + "SV", + "SX", + "SY", + "SZ", + "TC", + "TD", + "TF", + "TG", + "TH", + "TJ", + "TK", + "TL", + "TM", + "TN", + "TO", + "TR", + "TT", + "TV", + "TW", + "TZ", + "UA", + "UG", + "UM", + "US", + "UY", + "UZ", + "VA", + "VC", + "VE", + "VG", + "VI", + "VN", + "VU", + "WF", + "WS", + "YE", + "YT", + "ZA", + "ZM", + "ZW", + ] + postal_code: + type: string + maxLength: 16 + description: "Postal/Zip code" + phone_number: + type: string + description: "Phone number" + pattern: '^\d{1,20}$' + email_address: + type: string + maxLength: 64 + description: Email Address + Custom: + properties: + ref1: + type: string + maxLength: 256 + description: "custom reference field 1" + ref2: + type: string + maxLength: 256 + description: "custom reference field 2" + ref3: + type: string + maxLength: 256 + description: "custom reference field 3" + ref4: + type: string + maxLength: 256 + description: "custom reference field 4" + ref5: + type: string + maxLength: 256 + description: "custom reference field 5" + PaymentResponse: + properties: + id: + type: string + maxLength: 9 + description: "transaction Id" + authorizing_merchant_id: + type: number + description: "The id of the merchant that authorized the transaction." + approved: + type: string + description: "Approval status of payment transaction. 0 if the transaction is not approved. 1 if the transaction is approved." + message_id: + type: string + maxLength: 3 + description: "Payment response code" + message: + type: string + maxLength: 256 + description: "Message containing information about the transactions status" + auth_code: + type: string + maxLength: 32 + description: "Auth Code" + created: + type: string + format: date-time + description: "Time stamp of when the transaction occurred" + order_number: + type: string + maxLength: 32 + default: "Transaction Id" + description: "Order number" + type: + type: string + maxLength: 16 + description: "Payment transaction type" + enum: ["P", "R", "VP", "VR", "PA", "PAC"] + risk_score: + type: number + format: double + description: The risk score represents the percentage of probability that the transaction is fraudulent. For example, a score of 10 represents a 10% possibility that the transaction is fraudulent. + amount: + type: number + format: double + maxLength: 9 + description: "A decimal value in dollars. Uses up to two decimal places." + payment_method: + type: string + description: "Payment method" + custom: + $ref: "#/definitions/Custom" + card: + $ref: "#/definitions/CardPurchaseResponse" + merchant_data: + type: string + maxLength: 32 + description: "Returned only for 'interac' or 3D Secure payment requests. This value can be used as the {id} value when creating your 'continue' endpoint URL." + contents: + type: string + description: "Returned only for 'interac' or 3D Secure payment requests. This should be embedded in the user's browser client and this needs to be displayed to the customer to redirect them to the Interac login or 3D Secure processing page." + interac_online: + $ref: "#/definitions/InteracOnlineResponse" + links: + type: object + card_on_file: + $ref: "#/definitions/CardOnFileResponse" + CardPurchaseResponse: + properties: + card_type: + type: string + maxLength: 2 + description: "The type of card used in the transaction. AM = American Express, DI = Diners, JB = JCB, MC = MasterCard, NN = Discover, VI = Visa" + enum: ["AM", "DI", "JB", "MC", "NN", "VI", "PV", "MD", "IO"] + last_four: + type: string + maxLength: 4 + description: "The last 4 digits of the credit card used in the transaction" + address_match: + type: integer + postal_result: + type: integer + avs_result: + type: string + cvd_result: + type: string + card_bin: + type: string + avs: + $ref: "#/definitions/AvsResponse" + AvsResponse: + properties: + id: + type: string + description: "A unique avs response code. For a description of each code see http://dev.na.bambora.com." + enum: + [ + "0", + "5", + "9", + "A", + "B", + "C", + "D", + "E", + "G", + "I", + "M", + "N", + "P", + "R", + "S", + "U", + "W", + "X", + "Y", + "Z", + ] + message: + type: string + description: 'Message containing details of the avs status. Corresponding to each avs\_id, there is an avs_message describing the status of address verification service. For example If avs\_id = 5 then avs\_message = Invalid AVS Response.' + processed: + type: boolean + description: "Is true if the issuing bank has successfully processed an AVS check on the transaction. Is false if no AVS check was performed." + InteracOnlineResponse: + description: "Returned only in the final response from the 'continue' endpoint." + properties: + idebit_issconf: + type: string + description: "A numeric confirmation code of the payment" + idebit_issname: + type: string + description: "Name of the account holder's financial institution" + CardGetTransactionResponse: + properties: + card_type: + type: string + maxLength: 2 + description: "The type of card used in the transaction. AM = American Express, DI = Diners, JB = JCB, MC = MasterCard, NN = Discover, VI = Visa" + enum: ["AM", "DI", "JB", "MC", "NN", "VI"] + last_four: + type: string + maxLength: 4 + description: "The last 4 digits of the credit card used in the transaction" + cvd_result: + $ref: "#/definitions/CvdResult" + address_match: + type: integer + description: "Result of Address verification. 0 if Adddress Verification Service(AVS) is disabled or AVS fails. 1 if AVS is enabled and address and postal/zip code match." + avs_result: + type: integer + description: "Result of street address and Postal/Zip match/mismatch. 0 in case of mismatch. 1 in case of match." + expiry_month: + type: string + maxLength: 2 + description: "a 2 digit representation of the expiry month. For example March is 03." + expiry_year: + type: string + maxLength: 2 + description: "a 2 digit representation of the expiry year. For example 2016 is 16." + cavv_result: + $ref: "#/definitions/CavvResult" + Link: + type: object + properties: + ref: + type: string + href: + type: string + method: + type: string + Return: + required: + - amount + properties: + order_number: + type: string + maxLength: 30 + description: A unique order number. + amount: + type: number + format: double + description: "A decimal value in dollars. Must be less than or equal to the original purchase amount." + Void: + required: + - amount + properties: + amount: + type: number + format: double + description: "A decimal value in dollars. Must be equal to the original purchase amount. You can void purchases as well as pre-auths and returns." + order_number: + type: string + maxLength: 30 + description: A unique order number. + Transaction: + properties: + id: + type: number + format: integer + authorizing_merchant_id: + type: integer + description: "The id of the merchant that authorized the transaction." + approved: + type: boolean + message_id: + type: number + format: integer + message: + type: string + auth_code: + type: string + created: + type: string + format: date-time + description: "Time stamp of when the transaction occurred" + amount: + type: number + format: double + description: "A decimal value in dollars. Uses up to two decimal places." + order_number: + type: string + type: + type: string + comments: + type: string + batch_number: + type: string + total_refunds: + type: number + format: double + total_completions: + type: number + format: double + payment_method: + type: string + card: + $ref: "#/definitions/CardGetTransactionResponse" + billing: + $ref: "#/definitions/Address" + shipping: + $ref: "#/definitions/Address" + custom: + $ref: "#/definitions/Custom" + adjusted_by: + type: array + items: + $ref: "#/definitions/Adjustment" + links: + type: array + items: + $ref: "#/definitions/Link" + Adjustment: + properties: + id: + type: number + format: integer + type: + type: string + approval: + type: number + format: integer + message: + type: string + amount: + type: number + format: double + description: "A decimal value in dollars. Uses up to two decimal places." + created: + type: string + description: "The date it was created '2015-04-22T10:03:19.323-07:00'" + url: + type: string + SearchQuery: + required: + - name + - start_date + - end_date + - start_row + - end_row + properties: + name: + type: string + description: "Can be either 'Search' for all fields or 'TransHistoryMinimal' for a subset of the fields returned in the results." + enum: ["Search", "TransHistoryMinimal"] + start_date: + type: string + description: "The start date (inclusive) '2015-04-22T10:03:19' in the timezone of your merchant account." + end_date: + type: string + description: "The end date (inclusive) '2015-04-22T10:03:19' in the timezone of your merchant account." + start_row: + type: number + format: integer + description: Used to page the results. 1-based + default: 1 + end_row: + type: number + format: integer + description: Used to page the results. 1-based. This should always be 1 larger than start_row. + default: 2 + criteria: + description: Optional search criteria. All criteria are ANDed together. + type: array + items: + $ref: "#/definitions/Criteria" + Criteria: + properties: + field: + type: number + format: integer + description: "Refer to the table on this page for the searchable fields http://dev.na.bambora.com" + operator: + type: string + description: "URL encoded comparators such as less than, greater than, equals... Refer to the table on this page for the full list of comparators http://dev.na.bambora.com" + enum: ["%3D", "%3C", "%3E", "%3C%3D", "%3E%3D", "START%20WITH"] + value: + type: string + description: The value you want to match against. + SearchResult: + properties: + records: + type: array + items: + $ref: "#/definitions/SearchRecord" + SearchRecord: + properties: + row_id: + type: number + format: integer + trn_id: + type: number + format: integer + trn_date_time: + type: string + description: "2015-04-22T10:03:19.323-07:00" + trn_type: + type: string + trn_order_number: + type: string + trn_payment_method: + type: string + trn_comments: + type: string + trn_masked_card: + type: string + description: "The credit card with the middle digits redacted with X's" + trn_amount: + type: number + format: float32 + trn_returns: + type: number + format: float32 + trn_completions: + type: number + format: float32 + trn_voided: + type: number + format: integer + trn_response: + type: number + format: integer + trn_card_type: + type: string + description: MC VI etc + trn_batch_no: + type: number + format: integer + trn_avs_result: + type: string + description: Address Verification Service + trn_cvd_result: + type: number + format: integer + trn_cavv_result: + type: string + description: 3D Secure Code Result + trn_card_expiry: + type: string + message_id: + type: number + format: integer + message_text: + type: string + trn_card_owner: + type: string + trn_ip: + type: string + trn_approval_code: + type: string + trn_reference: + type: number + format: integer + b_name: + type: string + b_email: + type: string + b_phone: + type: string + b_address1: + type: string + b_address2: + type: string + b_city: + type: string + b_province: + type: string + b_postal: + type: string + b_country: + type: string + s_name: + type: string + s_email: + type: string + s_phone: + type: string + s_address1: + type: string + s_address2: + type: string + s_city: + type: string + s_province: + type: string + s_postal: + type: string + s_country: + type: string + ref1: + type: string + ref2: + type: string + ref3: + type: string + ref4: + type: string + ref5: + type: string + product_name: + type: string + product_id: + type: string + customer_code: + type: string + description: "The Payment Profile ID used in this transaction, if appropriate." + currency_abbr: + type: string + maxLength: 3 + description: "The currency for this transaction." + merchant_id: + type: integer + description: "The id of the merchant for this transaction." + merchant_name: + type: string + description: "The name of the merchant for this transaction." + entry_method: + type: string + maxLength: 1 + description: "How the transaction was initiated. N = Standard Entry, A = Apple Pay, G = Android Pay, M = MasterPass, S = EMV Swipe, V = Visa Checkout, Y = Unimag Card Swiper, T = EMV Chip Tap, E = EMV Chip Dip" + enum: ["N", "A", "G", "M", "S", "V", "Y", "T", "E"] + authorizing_merchant_id: + type: integer + description: "The id of the merchant that authorized this transaction." + PaymentProfileResponse: + properties: + code: + type: integer + format: int32 + maxLength: 2 + description: "Code" + message: + type: string + maxLength: 64 + description: "Message containing contextual information about the response" + customer_code: + type: string + maxLength: 32 + description: "Unique payment profile ID" + status: + type: string + description: characters(1) + last_transaction: + type: string + maxLength: 24 + format: date-time + description: date and time of last transaction + modified_date: + type: string + maxLength: 24 + format: date-time + description: date and time the profile was last modified + language: + type: string + maxLength: 3 + description: Language + velocity_group: + type: string + profile_group: + type: string + account_ref: + type: string + card: + $ref: "#/definitions/GetProfileDefaultCard" + billing: + $ref: "#/definitions/Address" + custom: + $ref: "#/definitions/Custom" + GetProfileDefaultCard: + properties: + name: + type: string + maxLength: 64 + description: cardholder name + number: + type: string + maxLength: 20 + description: masked credit card number + expiry_month: + type: string + maxLength: 2 + default: "02" + description: eg. 02 for February. + expiry_year: + type: string + maxLength: 2 + default: "17" + description: eg. 17 for 2017. + card_type: + type: string + maxLength: 2 + description: "The type of card associated with the profile. AM = American Express, DI = Diners, JB = JCB, MC = MasterCard, NN = Discover, VI = Visa" + enum: ["AM", "DI", "JB", "MC", "NN", "VI"] + ProfileGetCards: + properties: + code: + type: number + format: integer + maxLength: 2 + description: "code" + message: + type: string + maxLength: 64 + description: "Message containing details of the request status" + customer_code: + type: string + maxLength: 32 + description: "Unique payment profile ID" + card: + type: array + items: + $ref: "#/definitions/ProfileCards" + ProfileCards: + properties: + card_id: + type: string + description: 1-indexed card ID. Total number of cards allowed is configured in your merchant account. + function: + type: string + description: Will say DEF for the default card + name: + type: string + maxLength: 64 + description: Card holder name. + number: + type: string + maxLength: 20 + description: Credit card number (PAN). + default: "5100000010001004" + expiry_month: + type: string + maxLength: 2 + default: "02" + description: eg. 02 for February. + expiry_year: + type: string + maxLength: 2 + default: "17" + description: eg. 17 for 2017. + card_type: + type: string + maxLength: 2 + description: "The type of card associated with the profile. AM: American Express, DI: Diners, JB: JCB, MC: MasterCard, NN: Discover, VI = Visa" + enum: ["AM", "DI", "JB", "MC", "NN'VI"] + ProfileBody: + properties: + card: + $ref: "#/definitions/ProfileFromCard" + bank_account: + $ref: "#/definitions/ProfileFromBankAccount" + create_from_id: + $ref: "#/definitions/ProfileFromTransactionId" + token: + $ref: "#/definitions/ProfileFromToken" + billing: + $ref: "#/definitions/Address" + custom: + $ref: "#/definitions/Custom" + language: + type: string + maxLength: 3 + description: characters + comment: + type: string + maxLength: 256 + description: "Any comments that a user would like to attach to the Payment Profile" + validate: + type: boolean + default: false + description: "Set to true to automatically process a pre-auth transaction for validation purposes" + ProfileBodyCard: + properties: + card: + $ref: "#/definitions/ProfileFromCard" + token: + $ref: "#/definitions/ProfileFromToken" + comment: + type: string + maxLength: 256 + description: "Any comments that a user would like to attach to the Payment Profile" + validate: + type: boolean + default: false + description: "Set to true to automatically process a pre-auth transaction for validation purposes" + ProfileFromCard: + required: + - name + - number + - expiry_month + - expiry_year + properties: + name: + type: string + maxLength: 64 + description: Card holder name. + number: + type: string + maxLength: 20 + description: Credit card number (PAN) + expiry_month: + type: string + maxLength: 2 + default: "02" + description: eg. 02 for February. + expiry_year: + type: string + maxLength: 2 + default: "17" + description: eg. 17 for 2017. + cvd: + type: string + default: "123" + maxLength: 4 + description: Security code on the back of the credit card. This can be set to mandatory in the back office. + ProfileFromBankAccount: + required: + - account_number + - bank_account_holder + - bank_account_type + properties: + account_number: + type: string + maxLength: 17 + description: For U.S. and Canadian bank accounts. Specify the customer’s bank account number. Account number may vary in length. + bank_account_holder: + type: string + maxLength: 20 + description: Account holder name. + bank_account_type: + type: string + minLength: 2 + maxLength: 2 + description: PC=U.S. Personal Checking account. + + PS=U.S. Personal Saving account. + + CC=U.S. Corporate Checking account. + + CS=U.S. Corporate Savings account. + + CA=Canadian account. + branch_number: + type: string + minLength: 5 + maxLength: 5 + description: For Canadian bank accounts only. Specify the customer’s bank branch number. + institution_number: + type: string + minLength: 3 + maxLength: 3 + description: For Canadian bank accounts only. Specify the institution number of the customer’s financial institution. + routing_number: + type: string + minLength: 9 + maxLength: 9 + description: For U.S. bank accounts only. Specify the customer’s routing number. + ProfileFromTransactionId: + required: + - create_from_id + properties: + create_from_id: + type: number + format: integer + minLength: 8 + maxLength: 8 + description: The id of the transaction the user wishes to create a profile from. + ProfileFromToken: + required: + - name + - code + properties: + name: + type: string + maxLength: 64 + description: Card holder name. + code: + type: string + maxLength: 64 + description: The token received from the client-side tokenization service. + ProfileResponse: + properties: + code: + type: number + format: integer + message: + type: string + customer_code: + type: string + description: the ID of the payment profile. You need to keep track of this value. + validation: + $ref: "#/definitions/CardValidation" + ProfileCardResponse: + properties: + code: + type: number + format: integer + message: + type: string + customer_code: + type: string + description: the ID of the payment profile. You need to keep track of this value. + card: + $ref: "#/definitions/ProfileCards" + ErrorResponse: + properties: + code: + type: integer + format: int32 + category: + type: integer + format: int32 + message: + type: string + reference: + type: string + description: Not used. Always returns an empty string. + details: + type: array + items: + $ref: "#/definitions/Detail" + validation: + $ref: "#/definitions/CardValidation" + CardValidation: + properties: + id: + type: string + maxLength: 9 + description: Transaction ID + approved: + type: integer + description: "Approval status of payment transaction. 0 if the transaction is not approved. 1 if the transaction is approved." + message_id: + type: integer + maxLength: 3 + description: "Payment response code" + message: + type: string + maxLength: 256 + description: "Message containing information about the transactions status" + auth_code: + type: string + maxLength: 32 + description: "Auth Code" + trans_date: + type: string + description: "The date it was created '2015-04-22T10:03:19.323-07:00'" + order_number: + type: string + maxLength: 32 + default: "Transaction Id" + description: "Order number" + type: + type: string + description: "Payment transaction type" + enum: ["P", "R", "VP", "VR", "PA", "PAC"] + amount: + type: number + format: double + description: "A decimal value in dollars. Uses up to two decimal places." + cvd_id: + type: integer + maxLength: 2 + description: "CVD Response ID" + Detail: + properties: + field: + type: string + message: + type: string + TokenRequest: + required: + - number + - expiry_month + - expiry_year + - cvd + properties: + number: + type: string + description: "The credit card number" + expiry_month: + type: string + maxLength: 2 + default: "02" + description: eg. 02 for February. + expiry_year: + type: string + maxLength: 2 + default: "17" + description: eg. 17 for 2017. + cvd: + type: string + default: "123" + maxLength: 4 + description: Security code on the back of the credit card. + TokenResponse: + required: + - token + properties: + token: + type: string + description: "The token representing the credit card number that you will send for purchases. You will always receive a token, even if the request data is wrong or the card is invalid." + code: + type: string + description: "Response code for the message. It can be ignored." + version: + type: integer + description: "Message version number. Can be ignored." + message: + type: string + description: "Response message with any hints as to what might have gone wrong, if something went wrong." + CvdResult: + type: integer + description: "Result of CVD verification. 1=CVD Match, 2=CVD Mismatch, 3=CVD Not Verified, 4=CVD Should have been present, 5=CVD Issuer unable to process request, 6=CVD Not Provided" + CavvResult: + type: string + description: "Result code returned back from performing the 3D Secure Code validation." + Level2: + description: "Level 2 processing is for B2B customers. Additional information can be provided, to the benefit of corporate/government/industrial customers, that includes a customer code & tax amounts." + required: + - customer_code + - order_tax1_price + - order_tax2_price + properties: + customer_code: + type: string + maxLength: 17 + description: | + * Visa - Used by merchant to identify the purchase (i.e. SKU number). + * Master Card - Code the cardholder supplied to the merchant. + * American Express - Customer reference number. + order_tax1_price: + type: number + format: double + maxLength: 12 + description: | + * Visa - Amount of state or provincial tax included in the transaction amount - Must between 0.1% and 22% of the transaction amount. + * Master Card - Sales tax/VAT on the total purchase - Must be between 0.1% and 30% of the transaction amount. + * American Express - Transaction tax amount (calculated or entered). + order_tax2_price: + type: number + format: double + maxLength: 12 + description: | + * Visa - Amount of state or provincial tax included in the transaction amount - Must between 0.1% and 22% of the transaction amount. + * Master Card - Sales tax/VAT on the total purchase - Must be between 0.1% and 30% of the transaction amount. + * American Express - Transaction tax amount (calculated or entered). + CardOnFile: + description: "When processing a transaction where the credit card information is stored on file, you must pass along an indicator showing the type of credential-on-file transaction that is being processed." + required: + - type + properties: + type: + type: string + description: | + * not\_card\_on_file - A transaction where the credit card information is not stored on file. + * first_installment - The first payment in a series of installment payments. (Eg. Initial installment payment when purchasing a fridge.) + * subsequent_installment - A subsequent payment (ie. not the first) in a series of installment payments. (Eg. Next installment payment when purchasing a fridge.) + * first_recurring - The first payment in a series of scheduled payments with no expected end date. (Eg. Initial payment for a subscription service.) + * subsequent_recurring - A subsequent payment (ie. not the first) in a series of scheduled payments with no expected end date. (Eg. Next payment for a subscription service.) + * subsequent\_customer_initiated - A recurring transaction that is initiated by the customer. (Eg. Customer reloads a prepaid cash card.) + * subsequent_unscheduled - An unscheduled recurring transaction that is initiated by the merchant. (Eg. Merchant auto-reloads a prepaid cash card for the customer when the balance on the card reaches a predetermined threshold.) + enum: + [ + "not_card_on_file", + "first_installment", + "subsequent_installment", + "first_recurring", + "subsequent_recurring", + "subsequent_customer_initiated", + "subsequent_unscheduled", + ] + series_id: + type: number + format: integer + description: 'The identifier for the set of transactions that this transaction belongs to. This field is required for "subsequent\_installment", "subsequent\_recurring", and "subsequent\_unscheduled" credential-on-file transaction types.' + ContinueRequest: + required: + - payment_method + properties: + payment_method: + type: string + description: "For a 3D Secure payment process the value for this property will always be 'card'. For an Interac Online process the value for this property will always be 'interac'." + card_response: + $ref: "#/definitions/CardResponse" + interac_response: + $ref: "#/definitions/InteracResponse" + CardResponse: + description: "For a 3D Secure payment process." + required: + - pa_res + properties: + pa_res: + type: string + description: "For a 3D Secure payment process this stores the Authentication Code (PaRes)." + 3DSecure: + description: | + Payment with 3D Secure (Verified by Visa, Mastercard SecureCode, American Express SafeKey). + Note that 3D Secure must be enabled on the merchant account in order to process transactions with 3D Secure. + required: + - enabled + properties: + enabled: + type: boolean + default: true + description: "If 3D Secure is enabled on the merchant account, set to false to process transactions without 3D Secure. Otherwise, set to true to process transactions with 3D Secure." + xid: + type: string + description: "The transaction ID (XID) used for processing transactions with 3D Secure." + cavv: + type: string + description: "The cardholder authentication verification value (CAVV/UCAF/AEVV) used for processing transactions with 3D Secure." + eci: + type: integer + description: "The electronic commerce indicator (ECI) used for processing transactions with 3D Secure." + InteracResponse: + description: "For an Interac Online payment process." + required: + - idebit_track2 + - idebit_isslang + - idebit_version + - idebit_issconf + - idebit_issname + - idebit_amount + - idebit_invoice + properties: + idebit_track2: + type: string + maxLength: 256 + description: "Assigned by financial institution. Contains PAN, Expiry Date, and Transaction ID." + idebit_isslang: + type: string + maxLength: 2 + description: "The payments language code that is en or fr." + idebit_version: + type: number + format: integer + description: "Always 1. This value is in the redirect Bambora initially sends." + idebit_issconf: + type: string + maxLength: 32 + description: "Issuer Confirmation Number from online banking to be displayed on the merchant's confirmation page. Must be URL decoded." + idebit_issname: + type: string + maxLength: 32 + description: "Financial institution's name to be displayed on the merchant's confirmation page. Must be URL decoded." + idebit_amount: + type: number + format: integer + description: "This is the amount of the transaction, in cents. For example, $13.25 would be represented by 1325." + idebit_invoice: + type: string + maxLength: 32 + description: "The original trnOrderNumber you submitted to Bambora." + CardOnFileResponse: + properties: + type: + type: string + description: | + * not\_card\_on\_file - A transaction where the credit card information is not stored on file. + * first_installment - The first payment in a series of installment payments. (Eg. Initial installment payment when purchasing a fridge.) + * subsequent_installment - A subsequent payment (ie. not the first) in a series of installment payments. (Eg. Next installment payment when purchasing a fridge.) + * first_recurring - The first payment in a series of scheduled payments with no expected end date. (Eg. Initial payment for a subscription service.) + * subsequent_recurring - A subsequent payment (ie. not the first) in a series of scheduled payments with no expected end date. (Eg. Next payment for a subscription service.) + * subsequent\_customer_initiated - A recurring transaction that is initiated by the customer. (Eg. Customer reloads a prepaid cash card.) + * subsequent_unscheduled - An unscheduled recurring transaction that is initiated by the merchant. (Eg. Merchant auto-reloads a prepaid cash card for the customer when the balance on the card reaches a predetermined threshold.) + enum: + [ + "not_card_on_file", + "first_installment", + "subsequent_installment", + "first_recurring", + "subsequent_recurring", + "subsequent_customer_initiated", + "subsequent_unscheduled", + ] + series_id: + type: number + format: integer + description: "The identifier for the set of transactions that this transaction belongs to." diff --git a/src/backend/libs/efiling-bambora-api-client/pom.xml b/src/backend/libs/efiling-bambora-api-client/pom.xml new file mode 100644 index 0000000000..446fd4f906 --- /dev/null +++ b/src/backend/libs/efiling-bambora-api-client/pom.xml @@ -0,0 +1,193 @@ + + + 4.0.0 + ca.bc.gov.open.jag + efiling-bambora-api-client + 2.0.12-SNAPSHOT + efiling-bambora-api-client + Client for Bambora + + + ca.bc.gov.open.jag.efilingbamboraapiclient + 17 + 2.17.1 + + + jdt_apt + + + + + io.swagger.core.v3 + swagger-annotations + + + org.glassfish.jersey.core + jersey-client + + + org.glassfish.jersey.media + jersey-media-multipart + + + org.glassfish.jersey.media + jersey-media-json-jackson + + + + org.glassfish.jersey.inject + jersey-hk2 + + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-base + + + com.fasterxml.jackson.core + jackson-core + + + com.fasterxml.jackson.core + jackson-annotations + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + + + com.brsanthu + migbase64 + + + junit + junit + test + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-web + + + io.springfox + springfox-swagger2 + + + io.springfox + springfox-swagger-ui + + + org.threeten + threetenbp + + + com.github.joschi.jackson + jackson-datatype-threetenbp + + + org.openapitools + jackson-databind-nullable + + + + com.google.code.findbugs + jsr305 + + + + ca.bc.gov.open.jag + efiling-commons + 2.0.12-SNAPSHOT + compile + + + + + + + org.springframework.boot + spring-boot-dependencies + 3.5.0 + pom + import + + + ca.bc.gov.open.jag + efiling-bom + 2.0.12-SNAPSHOT + pom + import + + + + + + + + org.openapitools + openapi-generator-maven-plugin + 7.0.0 + + + spring-boot-api + + generate + + + ${project.basedir}/payments-swagger.yaml + java + + joda + false + + + true + true + + jersey2 + ${default-package}.api + ${default-package}.api.model + ${default-package}.api.handler + false + false + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${java.version} + ${java.version} + + + + maven-deploy-plugin + + + default-deploy + deploy + + deploy + + + + + + + diff --git a/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/AutoConfiguration.java b/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/AutoConfiguration.java new file mode 100644 index 0000000000..8565a821e4 --- /dev/null +++ b/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/AutoConfiguration.java @@ -0,0 +1,40 @@ +package ca.bc.gov.open.jag.bambora; + +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.PaymentsApi; +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.handler.ApiClient; +import ca.bc.gov.open.jag.efilingcommons.payment.PaymentAdapter; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.text.MessageFormat; + +@Configuration +@EnableConfigurationProperties(BamboraProperties.class) +public class AutoConfiguration { + + @Bean + @ConditionalOnMissingBean(ApiClient.class) + public ApiClient apiClient(BamboraProperties bamboraProperties) { + + ApiClient apiClient = new ApiClient(); + //Setting this to null will make it use the base path + apiClient.setServerIndex(null); + apiClient.setBasePath(bamboraProperties.getApiBasePath()); + apiClient.setApiKey(MessageFormat.format("Passcode {0}", bamboraProperties.getEncodedKey())); + return apiClient; + + } + + @Bean + public PaymentsApi paymentsApi(ApiClient apiClient) { + return new PaymentsApi(apiClient); + } + + + @Bean + public PaymentAdapter paymentAdapter(PaymentsApi paymentsApi) { + return new BamboraPaymentAdapter(paymentsApi); + } +} diff --git a/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/BamboraPaymentAdapter.java b/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/BamboraPaymentAdapter.java new file mode 100644 index 0000000000..3a194a8ac1 --- /dev/null +++ b/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/BamboraPaymentAdapter.java @@ -0,0 +1,92 @@ +package ca.bc.gov.open.jag.bambora; + +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.PaymentsApi; +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.handler.ApiException; +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.model.Custom; +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.model.PaymentRequest; +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.model.PaymentResponse; +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.model.ProfilePurchase; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingPaymentException; +import ca.bc.gov.open.jag.efilingcommons.model.EfilingPayment; +import ca.bc.gov.open.jag.efilingcommons.model.PaymentTransaction; +import ca.bc.gov.open.jag.efilingcommons.payment.PaymentAdapter; +import org.joda.time.DateTime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +import java.math.BigDecimal; + +public class BamboraPaymentAdapter implements PaymentAdapter { + + Logger logger = LoggerFactory.getLogger(BamboraPaymentAdapter.class); + + private final PaymentsApi paymentsApi; + + public BamboraPaymentAdapter(PaymentsApi paymentsApi) { + this.paymentsApi = paymentsApi; + } + + public PaymentTransaction makePayment(EfilingPayment efilingPayment) { + PaymentTransaction result = new PaymentTransaction(); + + logger.info("Making payment call"); + + try { + + PaymentRequest payload = buildPaymentRequest(efilingPayment); + PaymentResponse response = paymentsApi.makePayment(payload); + result.setEcommerceTransactionId(new BigDecimal(response.getId())); + result.setEntDtm(DateTime.now()); + result.setInvoiceNo(response.getOrderNumber()); + result.setTransactonDtm(DateTime.now()); + result.setTransactionAmt(BigDecimal.valueOf(response.getAmount())); + if (response.getApproved().equals(PaymentConstants.BAMBORA_APPROVAL_RESPONSE)) { + MDC.put(PaymentConstants.MDC_EFILING_SUBMISSION_FEE, response.getAmount().toString()); + logger.info("Successful payment of [{}]", response.getAmount()); + MDC.remove(PaymentConstants.MDC_EFILING_SUBMISSION_FEE); + result.setTransactionStateCd(PaymentConstants.TRANSACTION_STATE_APPROVED); + } else { + logger.info("Failed payment"); + result.setTransactionStateCd(PaymentConstants.TRANSACTION_STATE_DECLINED); + } + result.setApprovalCd(response.getAuthCode()); + result.setReferenceMessageTxt(response.getMessage()); + result.setCreditCardTypeCd(PaymentConstants.CARD_TYPES.get(response.getCard().getCardType())); + result.setProcessDt(response.getCreated()); + result.setInternalClientNo(response.getCustom().getRef1()); + + return result; + + } catch (ApiException e) { + + logger.error("Bambora payment exception", e); + throw new EfilingPaymentException("Bambora payment exception", e.getCause()); + + } + + } + + private PaymentRequest buildPaymentRequest(EfilingPayment efilingPayment) { + + PaymentRequest paymentRequest = new PaymentRequest(); + + paymentRequest.setPaymentMethod(PaymentRequest.PaymentMethodEnum.PAYMENT_PROFILE); + paymentRequest.amount(efilingPayment.getPaymentAmount().doubleValue()); + paymentRequest.setOrderNumber(efilingPayment.getInvoiceNumber()); + + Custom customReference = new Custom(); + customReference.setRef1(efilingPayment.getInternalClientNumber()); + customReference.setRef2(PaymentConstants.COURT_SERVICES); + customReference.setRef3(efilingPayment.getServiceId().toString()); + paymentRequest.setCustom(customReference); + + ProfilePurchase profilePurchase = new ProfilePurchase(); + profilePurchase.setCustomerCode(efilingPayment.getInternalClientNumber()); + profilePurchase.setCardId(PaymentConstants.CARD_ID); + profilePurchase.setComplete(true); + paymentRequest.setPaymentProfile(profilePurchase); + return paymentRequest; + + } +} diff --git a/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/BamboraProperties.java b/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/BamboraProperties.java new file mode 100644 index 0000000000..d9730ee8ef --- /dev/null +++ b/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/BamboraProperties.java @@ -0,0 +1,38 @@ +package ca.bc.gov.open.jag.bambora; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.text.MessageFormat; +import java.util.Base64; + +@ConfigurationProperties(prefix = "bambora") +public class BamboraProperties { + private String apiBasePath; + private String apiPasscode; + private String merchantId; + + public String getApiBasePath() { return apiBasePath; } + + public void setApiBasePath(String apiBasePath) { this.apiBasePath = apiBasePath; } + + public String getApiPasscode() { + return apiPasscode; + } + + public void setApiPasscode(String apiPasscode) { + this.apiPasscode = apiPasscode; + } + + public String getMerchantId() { + return merchantId; + } + + public void setMerchantId(String merchantId) { + this.merchantId = merchantId; + } + + public String getEncodedKey() { + String apiKey = MessageFormat.format("{0}:{1}", this.merchantId,this.apiPasscode); + return Base64.getEncoder().encodeToString(apiKey.getBytes()); + } +} diff --git a/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/PaymentConstants.java b/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/PaymentConstants.java new file mode 100644 index 0000000000..fc75ecb5f2 --- /dev/null +++ b/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/PaymentConstants.java @@ -0,0 +1,34 @@ +package ca.bc.gov.open.jag.bambora; + +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.model.CardPurchaseResponse; + +import java.util.HashMap; +import java.util.Map; + +public class PaymentConstants { + private PaymentConstants() { + + } + public static final String COURT_SERVICES = "COURT SERVICES"; + public static final Integer CARD_ID = 1; + public static final String BAMBORA_APPROVAL_RESPONSE = "1"; + + public static final String TRANSACTION_STATE_DECLINED = "DEC"; + public static final String TRANSACTION_STATE_APPROVED = "APP"; + public static Map CARD_TYPES; + static { + CARD_TYPES = new HashMap<>(); + CARD_TYPES.put(CardPurchaseResponse.CardTypeEnum.AM,"AX"); + CARD_TYPES.put(CardPurchaseResponse.CardTypeEnum.NN,"NN"); + CARD_TYPES.put(CardPurchaseResponse.CardTypeEnum.MC,"M"); + CARD_TYPES.put(CardPurchaseResponse.CardTypeEnum.VI,"V"); + CARD_TYPES.put(CardPurchaseResponse.CardTypeEnum.IO, "IO"); + CARD_TYPES.put(CardPurchaseResponse.CardTypeEnum.MD, "MD"); + CARD_TYPES.put(CardPurchaseResponse.CardTypeEnum.PV, "PV"); + // TODO: this card are not in used, they will fail in CSO + CARD_TYPES.put(CardPurchaseResponse.CardTypeEnum.DI,"DI"); + CARD_TYPES.put(CardPurchaseResponse.CardTypeEnum.JB,"JB"); + } + public static final String EFILING_APP = "efiling"; + public static final String MDC_EFILING_SUBMISSION_FEE = EFILING_APP + ".submissionFee"; +} diff --git a/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/PaymentProfileResponseCodes.java b/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/PaymentProfileResponseCodes.java new file mode 100644 index 0000000000..c10d1a354a --- /dev/null +++ b/src/backend/libs/efiling-bambora-api-client/src/main/java/ca/bc/gov/open/jag/bambora/PaymentProfileResponseCodes.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.bambora; + +public enum PaymentProfileResponseCodes { + + + +} diff --git a/src/backend/libs/efiling-bambora-api-client/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/backend/libs/efiling-bambora-api-client/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 0000000000..fd03bc3c50 --- /dev/null +++ b/src/backend/libs/efiling-bambora-api-client/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +ca.bc.gov.open.jag.bambora.AutoConfiguration \ No newline at end of file diff --git a/src/backend/libs/efiling-bambora-api-client/src/test/java/ca/bc/gov/ca/open/jag/bambora/AutoConfigurationTest.java b/src/backend/libs/efiling-bambora-api-client/src/test/java/ca/bc/gov/ca/open/jag/bambora/AutoConfigurationTest.java new file mode 100644 index 0000000000..7e9952f31a --- /dev/null +++ b/src/backend/libs/efiling-bambora-api-client/src/test/java/ca/bc/gov/ca/open/jag/bambora/AutoConfigurationTest.java @@ -0,0 +1,28 @@ +package ca.bc.gov.ca.open.jag.bambora; + +import ca.bc.gov.open.jag.bambora.AutoConfiguration; +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.PaymentsApi; +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.handler.ApiClient; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import static org.assertj.core.api.Assertions.assertThat; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("AutoConfiguration") +public class AutoConfigurationTest { + ApplicationContextRunner context = new ApplicationContextRunner() + .withUserConfiguration(AutoConfiguration.class); + + @Test + public void testConfigure() throws Exception { + + context.run(it -> { + assertThat(it).hasSingleBean(PaymentsApi.class); + assertThat(it).hasSingleBean(ApiClient.class); + }); + + } + +} diff --git a/src/backend/libs/efiling-bambora-api-client/src/test/java/ca/bc/gov/ca/open/jag/bambora/BamboraPaymentAdapterTest.java b/src/backend/libs/efiling-bambora-api-client/src/test/java/ca/bc/gov/ca/open/jag/bambora/BamboraPaymentAdapterTest.java new file mode 100644 index 0000000000..c3f8e247b1 --- /dev/null +++ b/src/backend/libs/efiling-bambora-api-client/src/test/java/ca/bc/gov/ca/open/jag/bambora/BamboraPaymentAdapterTest.java @@ -0,0 +1,115 @@ +package ca.bc.gov.ca.open.jag.bambora; + +import ca.bc.gov.open.jag.bambora.BamboraPaymentAdapter; +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.PaymentsApi; +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.handler.ApiException; +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.model.CardPurchaseResponse; +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.model.Custom; +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.model.PaymentResponse; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingPaymentException; +import ca.bc.gov.open.jag.efilingcommons.model.EfilingPayment; +import ca.bc.gov.open.jag.efilingcommons.model.PaymentTransaction; +import ca.bc.gov.open.jag.efilingcommons.payment.PaymentAdapter; +import org.joda.time.DateTime; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("BamboraPaymentAdapter") +public class BamboraPaymentAdapterTest { + + + private static final String AUTH_CODE = "ACODE"; + private static final String ORDER_NUMBER = "TEST"; + private static final String INTERNAL_CLIENT_NUMBER = "INTERNALCLIENT"; + private static final String MESSAGE = "AMESSAGE"; + @Mock + PaymentsApi paymentsApiMock; + + PaymentAdapter sut; + + @BeforeEach + void initialize() { + MockitoAnnotations.initMocks(this); + + sut = new BamboraPaymentAdapter(paymentsApiMock); + } + + @Test + @DisplayName("Test Approved") + public void withValidRequestPaymentIsApproved() throws ApiException { + + Mockito.when(paymentsApiMock.makePayment(any())).thenReturn(createPaymentResponse("123","1")); + + EfilingPayment payment = new EfilingPayment(BigDecimal.TEN, BigDecimal.TEN, ORDER_NUMBER, INTERNAL_CLIENT_NUMBER); + + PaymentTransaction efilingTransaction = sut.makePayment(payment); + Assertions.assertEquals(AUTH_CODE, efilingTransaction.getApprovalCd()); + Assertions.assertEquals("APP", efilingTransaction.getTransactionStateCd()); + Assertions.assertEquals(BigDecimal.valueOf(1), efilingTransaction.getEcommerceTransactionId()); + Assertions.assertEquals(BigDecimal.valueOf(10.00), efilingTransaction.getTransactionAmt()); + Assertions.assertEquals(ORDER_NUMBER, efilingTransaction.getInvoiceNo()); + Assertions.assertEquals("AX", efilingTransaction.getCreditCardTypeCd()); + Assertions.assertEquals(MESSAGE, efilingTransaction.getReferenceMessageTxt()); + Assertions.assertNotNull(efilingTransaction.getEntDtm()); + Assertions.assertNotNull(efilingTransaction.getTransactonDtm()); + Assertions.assertNotNull(efilingTransaction.getProcessDt()); + + } + + @Test + @DisplayName("Test Failed") + public void withValidRequestPaymentIsFailed() throws ApiException { + Mockito.when(paymentsApiMock.makePayment(any())).thenReturn(createPaymentResponse("123","2")); + EfilingPayment payment = new EfilingPayment(BigDecimal.TEN, BigDecimal.TEN, ORDER_NUMBER, INTERNAL_CLIENT_NUMBER); + + PaymentTransaction efilingTransaction = sut.makePayment(payment); + Assertions.assertEquals(AUTH_CODE, efilingTransaction.getApprovalCd()); + Assertions.assertEquals("DEC", efilingTransaction.getTransactionStateCd()); + Assertions.assertEquals(BigDecimal.valueOf(1), efilingTransaction.getEcommerceTransactionId()); + Assertions.assertEquals(BigDecimal.valueOf(10.00), efilingTransaction.getTransactionAmt()); + Assertions.assertEquals("AX", efilingTransaction.getCreditCardTypeCd()); + Assertions.assertEquals(MESSAGE, efilingTransaction.getReferenceMessageTxt()); + Assertions.assertNotNull(efilingTransaction.getEntDtm()); + Assertions.assertNotNull(efilingTransaction.getTransactonDtm()); + Assertions.assertNotNull(efilingTransaction.getProcessDt()); + + } + + @Test + @DisplayName("Test Exception") + public void withInValidRequestException() throws ApiException { + Mockito.when(paymentsApiMock.makePayment(any())).thenThrow(ApiException.class); + EfilingPayment payment = new EfilingPayment(BigDecimal.TEN, BigDecimal.TEN, ORDER_NUMBER, INTERNAL_CLIENT_NUMBER); + + Assertions.assertThrows(EfilingPaymentException.class, () -> sut.makePayment(payment)); + } + + private PaymentResponse createPaymentResponse(String messageId, String approved) { + + PaymentResponse paymentResponse = new PaymentResponse(); + paymentResponse.setId("1"); + paymentResponse.setApproved(approved); + paymentResponse.setMessageId(messageId); + paymentResponse.setMessage(MESSAGE); + paymentResponse.setAmount(10.00); + paymentResponse.setAuthCode(AUTH_CODE); + paymentResponse.setOrderNumber(ORDER_NUMBER); + CardPurchaseResponse card = new CardPurchaseResponse(); + card.setCardType(CardPurchaseResponse.CardTypeEnum.AM); + paymentResponse.setCard(card); + paymentResponse.setCreated(DateTime.now()); + + Custom custom = new Custom(); + + paymentResponse.setCustom(custom); + return paymentResponse; + + } +} diff --git a/src/backend/libs/efiling-bambora-api-client/src/test/java/ca/bc/gov/ca/open/jag/bambora/BamboraPropertiesTest.java b/src/backend/libs/efiling-bambora-api-client/src/test/java/ca/bc/gov/ca/open/jag/bambora/BamboraPropertiesTest.java new file mode 100644 index 0000000000..46d99f9689 --- /dev/null +++ b/src/backend/libs/efiling-bambora-api-client/src/test/java/ca/bc/gov/ca/open/jag/bambora/BamboraPropertiesTest.java @@ -0,0 +1,37 @@ +package ca.bc.gov.ca.open.jag.bambora; + +import ca.bc.gov.open.jag.bambora.BamboraProperties; +import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.TestInstance; + +import java.text.MessageFormat; +import java.util.Base64; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("BamboraProperties") +public class BamboraPropertiesTest { + + private static final String PASSCODE = "AVALUE"; + private static final String MERCHANT_ID = "AVALUE"; + + @Test + public void testProperties() { + BamboraProperties bamboraProperties = new BamboraProperties(); + bamboraProperties.setMerchantId(MERCHANT_ID); + bamboraProperties.setApiPasscode(PASSCODE); + Assertions.assertEquals(MERCHANT_ID, bamboraProperties.getMerchantId()); + Assertions.assertEquals(PASSCODE, bamboraProperties.getApiPasscode()); + } + + @Test + public void testEncode() { + BamboraProperties bamboraProperties = new BamboraProperties(); + bamboraProperties.setMerchantId(MERCHANT_ID); + bamboraProperties.setApiPasscode(PASSCODE); + + String result = new String(Base64.getDecoder().decode(bamboraProperties.getEncodedKey())); + Assertions.assertEquals(MessageFormat.format("{0}:{1}", MERCHANT_ID, PASSCODE), result); + } +} diff --git a/src/backend/libs/efiling-bambora-api-client/src/test/java/ca/bc/gov/ca/open/jag/bambora/PaymentConstantsTest.java b/src/backend/libs/efiling-bambora-api-client/src/test/java/ca/bc/gov/ca/open/jag/bambora/PaymentConstantsTest.java new file mode 100644 index 0000000000..63fbf024ad --- /dev/null +++ b/src/backend/libs/efiling-bambora-api-client/src/test/java/ca/bc/gov/ca/open/jag/bambora/PaymentConstantsTest.java @@ -0,0 +1,33 @@ +package ca.bc.gov.ca.open.jag.bambora; + +import ca.bc.gov.open.jag.bambora.PaymentConstants; +import ca.bc.gov.open.jag.efilingbamboraapiclient.api.model.CardPurchaseResponse; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +import java.util.Map; + + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class PaymentConstantsTest { + + + @Test + public void TestMapping() { + + Map map = PaymentConstants.CARD_TYPES; + Assertions.assertEquals("AX", map.get(CardPurchaseResponse.CardTypeEnum.AM));; + Assertions.assertEquals("NN", map.get(CardPurchaseResponse.CardTypeEnum.NN));; + Assertions.assertEquals("M", map.get(CardPurchaseResponse.CardTypeEnum.MC));; + Assertions.assertEquals("V", map.get(CardPurchaseResponse.CardTypeEnum.VI));; + Assertions.assertEquals( "IO", map.get(CardPurchaseResponse.CardTypeEnum.IO));; + Assertions.assertEquals( "MD", map.get(CardPurchaseResponse.CardTypeEnum.MD));; + Assertions.assertEquals( "PV", map.get(CardPurchaseResponse.CardTypeEnum.PV));; + Assertions.assertEquals("DI", map.get(CardPurchaseResponse.CardTypeEnum.DI));; + Assertions.assertEquals("JB", map.get(CardPurchaseResponse.CardTypeEnum.JB));; + + } + + +} diff --git a/src/backend/libs/efiling-bom/pom.xml b/src/backend/libs/efiling-bom/pom.xml index 8ea5124244..91365ce682 100644 --- a/src/backend/libs/efiling-bom/pom.xml +++ b/src/backend/libs/efiling-bom/pom.xml @@ -3,28 +3,46 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - ca.bc.gov.open.jag efiling-bom - 0.0.1-SNAPSHOT - - pom + 2.0.12-SNAPSHOT - 0.4.1 - 3.1.2 - 2.9.2 - 1.6.2 + 2.17.1 + 1.0.5 + 2.2 + 2.19.0 + 2.18.2 + 3.0.2 + 1.11.8 + 2.18.0 + 3.0.0 + 2.2.29 + 17 2.0.1.Final - 2.10.6 + 2.3.1 + 2.13.0 2.7.1 - 3.10 - 1.3.1.Final - 1.4.3 - 1.8.0 - 0.2.1 - 3.3.7 - 2.11.1 + 3.18.0 + 4.4 + 4.1.0 + 1.24.1 + 9.4.0 + 3.1.12 + 3.1.10 + 5.12.2 + 1.6.3 + 1.10.19 + 5.17.0 + 0.2.6 + 1.7.0 + 1.7.0 + 1.5.18 + 2.0.6 + [11.0.8,) + 20250517 + 6.5.0 + 6.2.10 @@ -34,113 +52,282 @@ https://splunk.jfrog.io/artifactory/ext-releases-local/ - - - org.apache.commons - commons-lang3 - ${org.apache.commons.version} + ca.bc.gov.open + spring-bceid-starter + ${ca.bc.gov.open.version} + - joda-time - joda-time - ${joda-time.version} + ca.bc.gov.open + spring-clamav-starter + ${ca.bc.gov.open.version} + - javax.validation - validation-api - ${javax.validation.version} + ca.bc.gov.open + spring-sftp-starter + ${ca.bc.gov.open.version} - - org.mapstruct - mapstruct - ${org.mapstruct.version} + ca.bc.gov.open + bambora-payment-starter + ${ca.bc.gov.open.version} - - io.swagger - swagger-annotations - ${io.swagger.version} + com.brsanthu + migbase64 + ${com.brsanthu.version} + - org.springdoc - springdoc-openapi-ui - ${org.springdoc.version} + com.fasterxml.jackson.core + jackson-annotations + ${com.fasterxml.jackson.core.version} + + + + com.github.joschi.jackson + jackson-datatype-threetenbp + ${com.github.joschi.jackson.version} + + + + com.google.code.findbugs + jsr305 + ${com.google.code.findbugs.version} + + + + com.splunk.logging + splunk-library-javalogging + ${com.splunk.logging.version} + + + commons-io + commons-io + ${commons-io.version} + + io.springfox springfox-swagger2 ${io.springfox.version} + io.springfox springfox-swagger-ui ${io.springfox.version} + - org.openapitools - jackson-databind-nullable - ${org.openapitools.version} + io.swagger.core.v3 + swagger-annotations + ${io.swagger.version} + + + + javax.validation + validation-api + ${javax.validation.version} + + + + javax.xml.bind + jaxb-api + ${javax.xml.bind.version} + + + + joda-time + joda-time + ${joda-time.version} - net.rakugakibox.spring.boot logback-access-spring-boot-starter ${net.rakugakibox.spring.boot.version} + - com.splunk.logging - splunk-library-javalogging - ${com.splunk.logging.version} + org.apache.commons + commons-lang3 + ${org.apache.commons.version} - - - io.opentracing.contrib - opentracing-spring-jaeger-web-starter - ${io.opentracing.contrib.version} + org.apache.commons + commons-collections4 + ${org.apache.commons.collections.collections.version} + - io.github.openfeign.opentracing - feign-opentracing - ${io.github.openfeign.opentracing.version} + org.apache.cxf + cxf-rt-features-logging + ${org.apache.cxf.version} - org.apache.cxf cxf-rt-frontend-jaxws ${org.apache.cxf.version} + org.apache.cxf cxf-rt-transports-http ${org.apache.cxf.version} + org.apache.cxf cxf-rt-transports-http-jetty ${org.apache.cxf.version} - - com.fasterxml.jackson.core - jackson-annotations - ${com.fasterxml.jackson.core.version} + org.apache.tika + tika-core + ${org.apache.tika.version} + + + + org.apache.skywalking + apm-toolkit-logback-1.x + ${org.apache.skywalking.version} + + + + org.apache.skywalking + apm-toolkit-trace + ${org.apache.skywalking.version} + + + + org.codehaus.janino + janino + ${org.codehaus.janino} + + org.glassfish.jersey.inject + jersey-hk2 + ${org.glassfish.jersey.inject.version} + + + + org.junit.jupiter + junit-jupiter-api + ${org.junit.jupiter.version} + test + + + + org.junit.jupiter + junit-jupiter-engine + ${org.junit.jupiter.version} + + + + org.mapstruct + mapstruct + ${org.mapstruct.version} + + + org.mockito + mockito-all + ${org.mockito.mockito-all.version} + + + + org.mockito + mockito-core + ${org.mockito.mockito-core.version} + + + + org.openapitools + jackson-databind-nullable + ${org.openapitools.version} + + + + org.threeten + threetenbp + ${org.threeten.version} + + + + org.springdoc + springdoc-openapi-ui + ${org.springdoc.version} + + + + ch.qos.logback + logback-classic + ${ch.qos.logback.version} + + + ch.qos.logback + logback-core + ${ch.qos.logback.version} + + + ch.qos.logback.access + logback-access-common + ${logback.access.common.version} + + + + org.apache.tomcat.embed + tomcat-embed-core + ${org.apache.tomcat.embed.version} + + + + org.json + json + ${org.json.version} + + + org.springframework.security + spring-security-core + ${org.springframework.security.version} + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${java.version} + ${java.version} + + + + - \ No newline at end of file + diff --git a/src/backend/libs/efiling-ceis-api-client/ceis-ords-swagger.yaml b/src/backend/libs/efiling-ceis-api-client/ceis-ords-swagger.yaml new file mode 100644 index 0000000000..7727907d1e --- /dev/null +++ b/src/backend/libs/efiling-ceis-api-client/ceis-ords-swagger.yaml @@ -0,0 +1,88 @@ +swagger: "2.0" +info: + title: ORDS generated API for web + version: 1.0.0 +host: dev.jag.gov.bc.ca +basePath: /ords/devj/ceisords/web +schemes: + - https +produces: + - application/json +securityDefinitions: + basicAuth: + type: basic + description: HTTP Basic Authentication. +paths: + /courtLocations: + get: + security: + - basicAuth: [] + description: Get a list of the court locations + responses: + "200": + description: output of the endpoint + schema: + $ref: "#/definitions/CourtLocations" + parameters: [] + /health: + get: + description: Dummy endpoint to check that API calls are working + responses: + "200": + description: output of the endpoint + schema: + type: object + properties: {} +definitions: + CourtLocations: + properties: + courtlocations: + type: array + items: + $ref: "#/definitions/CourtLocation" + CourtLocation: + type: object + description: "Court related information" + properties: + courtid: + type: number + courtname: + type: string + courtcode: + type: string + timezone: + type: string + daylightsavings: + type: string + courtidentifiercode: + type: string + addressline1: + type: string + addressline2: + type: string + addressline3: + type: string + postalcode: + type: string + citysequencenumber: + type: integer + cityabbreviation: + type: string + cityname: + type: string + provincesequencenumber: + type: integer + provinceabbreviation: + type: string + provincename: + type: string + countryid: + type: integer + countryabbreviation: + type: string + countryname: + type: string + isprovincialcourt: + type: string + issupremecourt: + type: string diff --git a/src/backend/libs/efiling-ceis-api-client/pom.xml b/src/backend/libs/efiling-ceis-api-client/pom.xml new file mode 100644 index 0000000000..31673e7982 --- /dev/null +++ b/src/backend/libs/efiling-ceis-api-client/pom.xml @@ -0,0 +1,222 @@ + + + 4.0.0 + ca.bc.gov.open.jag + efiling-ceis-api-client + 2.0.12-SNAPSHOT + efiling-ceis-api-client + Client for CEIS ORDS + + + ca.bc.gov.open.jag.efilingceisapiclient + 17 + 1.4.2.Final + 3.8.1 + 2.17.1 + + + jdt_apt + + + + + io.swagger.core.v3 + swagger-annotations + + + org.glassfish.jersey.core + jersey-client + + + org.glassfish.jersey.media + jersey-media-multipart + + + org.glassfish.jersey.media + jersey-media-json-jackson + + + + org.glassfish.jersey.inject + jersey-hk2 + + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-base + + + com.fasterxml.jackson.core + jackson-core + + + com.fasterxml.jackson.core + jackson-annotations + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + + + com.brsanthu + migbase64 + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-web + + + io.springfox + springfox-swagger2 + + + io.springfox + springfox-swagger-ui + + + org.threeten + threetenbp + + + com.github.joschi.jackson + jackson-datatype-threetenbp + + + org.openapitools + jackson-databind-nullable + + + + com.google.code.findbugs + jsr305 + + + + org.apache.commons + commons-lang3 + + + + org.mapstruct + mapstruct + + + + junit + junit + test + + + ca.bc.gov.open.jag + efiling-commons + 2.0.12-SNAPSHOT + compile + + + + + + + org.springframework.boot + spring-boot-dependencies + 3.5.0 + pom + import + + + ca.bc.gov.open.jag + efiling-bom + 2.0.12-SNAPSHOT + pom + import + + + + + + + + org.openapitools + openapi-generator-maven-plugin + 7.0.0 + + + spring-boot-api + + generate + + + ${project.basedir}/ceis-ords-swagger.yaml + java + + joda + false + + + true + true + + jersey2 + ${default-package}.api + ${default-package}.api.model + ${default-package}.api.handler + false + false + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + maven-deploy-plugin + + + default-deploy + deploy + + deploy + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + + + + + + + diff --git a/src/backend/libs/efiling-ceis-api-client/src/main/java/ca/bc/gov/open/jag/ceis/AutoConfiguration.java b/src/backend/libs/efiling-ceis-api-client/src/main/java/ca/bc/gov/open/jag/ceis/AutoConfiguration.java new file mode 100644 index 0000000000..a3a1c59638 --- /dev/null +++ b/src/backend/libs/efiling-ceis-api-client/src/main/java/ca/bc/gov/open/jag/ceis/AutoConfiguration.java @@ -0,0 +1,46 @@ +package ca.bc.gov.open.jag.ceis; + +import ca.bc.gov.open.jag.efilingceisapiclient.api.DefaultApi; +import ca.bc.gov.open.jag.efilingceisapiclient.api.handler.ApiClient; +import ca.bc.gov.open.jag.efilingcommons.court.EfilingCourtLocationService; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties(CeisProperties.class) +public class AutoConfiguration { + + @Bean({"ceisApiClient"}) + public ApiClient ceisApiClient(CeisProperties ceisProperties) { + + ApiClient apiClient = new ApiClient(); + //Setting this to null will make it use the base path + apiClient.setServerIndex(null); + apiClient.setBasePath(ceisProperties.getCeisBasePath()); + if(!StringUtils.isEmpty(ceisProperties.getCeisUsername())) { + apiClient.setUsername(ceisProperties.getCeisUsername()); + apiClient.setPassword(ceisProperties.getCeisPassword()); + } + return apiClient; + + } + + @Bean + public DefaultApi defaultApi(@Qualifier("ceisApiClient") final ApiClient apiClient) { + return new DefaultApi(apiClient); + } + + @Bean + public CeisCourtLocationMapper ceisCourtLocationMapper() { + return new CeisCourtLocationMapperImpl(); + } + + @Bean + public EfilingCourtLocationService efilingCourtLocationService(DefaultApi defaultApi, CeisCourtLocationMapper courtLocationMapper) { + return new CeisCourtLocationServiceImpl(defaultApi, courtLocationMapper); + } + +} diff --git a/src/backend/libs/efiling-ceis-api-client/src/main/java/ca/bc/gov/open/jag/ceis/CeisCourtLocationMapper.java b/src/backend/libs/efiling-ceis-api-client/src/main/java/ca/bc/gov/open/jag/ceis/CeisCourtLocationMapper.java new file mode 100644 index 0000000000..71961d4793 --- /dev/null +++ b/src/backend/libs/efiling-ceis-api-client/src/main/java/ca/bc/gov/open/jag/ceis/CeisCourtLocationMapper.java @@ -0,0 +1,25 @@ +package ca.bc.gov.open.jag.ceis; + +import ca.bc.gov.open.jag.efilingcommons.model.InternalCourtLocation; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper +public interface CeisCourtLocationMapper { + + @Mapping(target = "id", source="courtid") + @Mapping(target = "identifierCode", source="courtidentifiercode") + @Mapping(target = "name", source="courtname") + @Mapping(target = "code", source="courtcode") + @Mapping(target = "isSupremeCourt", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.BooleanUtils.toBoolean(courtLocation.getIssupremecourt()))") + @Mapping(target = "address.addressLine1", source="addressline1") + @Mapping(target = "address.addressLine2", source="addressline2") + @Mapping(target = "address.addressLine3", source="addressline3") + @Mapping(target = "address.postalCode", source="postalcode") + @Mapping(target = "address.cityName", source="cityname") + @Mapping(target = "address.provinceName", source="provincename") + @Mapping(target = "address.countryName", source="countryname") + InternalCourtLocation toCourtLocation(ca.bc.gov.open.jag.efilingceisapiclient.api.model.CourtLocation courtLocation); + + +} diff --git a/src/backend/libs/efiling-ceis-api-client/src/main/java/ca/bc/gov/open/jag/ceis/CeisCourtLocationServiceImpl.java b/src/backend/libs/efiling-ceis-api-client/src/main/java/ca/bc/gov/open/jag/ceis/CeisCourtLocationServiceImpl.java new file mode 100644 index 0000000000..114532f9fa --- /dev/null +++ b/src/backend/libs/efiling-ceis-api-client/src/main/java/ca/bc/gov/open/jag/ceis/CeisCourtLocationServiceImpl.java @@ -0,0 +1,53 @@ +package ca.bc.gov.open.jag.ceis; + +import ca.bc.gov.open.jag.efilingceisapiclient.api.DefaultApi; +import ca.bc.gov.open.jag.efilingceisapiclient.api.handler.ApiException; +import ca.bc.gov.open.jag.efilingcommons.court.EfilingCourtLocationService; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingCourtLocationServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.InternalCourtLocation; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.stream.Collectors; + +public class CeisCourtLocationServiceImpl implements EfilingCourtLocationService { + + private Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + private final DefaultApi defaultApi; + private final CeisCourtLocationMapper ceisCourtLocationMapper; + + public CeisCourtLocationServiceImpl( + DefaultApi defaultApi, + CeisCourtLocationMapper courtLocationMapper) { + this.defaultApi = defaultApi; + this.ceisCourtLocationMapper = courtLocationMapper; + } + + @Override + public List getCourtLocations(String courtType) { + + try { + return defaultApi.courtLocationsGet().getCourtlocations().stream() + .filter(courtLocation -> isSearchedType(courtLocation.getIssupremecourt(), courtLocation.getIsprovincialcourt(), courtType)) + .map(ceisCourtLocationMapper::toCourtLocation) + .collect(Collectors.toList()); + + } catch (ApiException e) { + logger.error(e.getMessage(), e); + throw new EfilingCourtLocationServiceException("Exception while retrieving court location", e); + } + + } + + private boolean isSearchedType(String isSupreme, String isProvincial, String courtType) { + + if (StringUtils.isBlank(courtType)) return true; + if (courtType.equals("S") && StringUtils.equals(isSupreme, "Y")) return true; + if (courtType.equals("P") && StringUtils.equals(isProvincial, "Y")) return true; + + return false; + } +} diff --git a/src/backend/libs/efiling-ceis-api-client/src/main/java/ca/bc/gov/open/jag/ceis/CeisProperties.java b/src/backend/libs/efiling-ceis-api-client/src/main/java/ca/bc/gov/open/jag/ceis/CeisProperties.java new file mode 100644 index 0000000000..9bd47af46f --- /dev/null +++ b/src/backend/libs/efiling-ceis-api-client/src/main/java/ca/bc/gov/open/jag/ceis/CeisProperties.java @@ -0,0 +1,35 @@ +package ca.bc.gov.open.jag.ceis; + + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "ceis") +public class CeisProperties { + private String ceisBasePath; + private String ceisUsername; + private String ceisPassword; + + public String getCeisBasePath() { + return ceisBasePath; + } + + public void setCeisBasePath(String ceisBasePath) { + this.ceisBasePath = ceisBasePath; + } + + public String getCeisUsername() { + return ceisUsername; + } + + public void setCeisUsername(String ceisUsername) { + this.ceisUsername = ceisUsername; + } + + public String getCeisPassword() { + return ceisPassword; + } + + public void setCeisPassword(String ceisPassword) { + this.ceisPassword = ceisPassword; + } +} diff --git a/src/backend/libs/efiling-ceis-api-client/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/backend/libs/efiling-ceis-api-client/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 0000000000..7ddd9252aa --- /dev/null +++ b/src/backend/libs/efiling-ceis-api-client/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +ca.bc.gov.open.jag.ceis.AutoConfiguration diff --git a/src/backend/libs/efiling-ceis-api-client/src/test/java/ca/bc/gov/ca/open/jag/ceis/AutoConfigurationTest.java b/src/backend/libs/efiling-ceis-api-client/src/test/java/ca/bc/gov/ca/open/jag/ceis/AutoConfigurationTest.java new file mode 100644 index 0000000000..2c00c2951d --- /dev/null +++ b/src/backend/libs/efiling-ceis-api-client/src/test/java/ca/bc/gov/ca/open/jag/ceis/AutoConfigurationTest.java @@ -0,0 +1,33 @@ +package ca.bc.gov.ca.open.jag.ceis; + +import ca.bc.gov.open.jag.ceis.AutoConfiguration; +import ca.bc.gov.open.jag.ceis.CeisCourtLocationMapper; +import ca.bc.gov.open.jag.efilingceisapiclient.api.DefaultApi; +import ca.bc.gov.open.jag.efilingceisapiclient.api.handler.ApiClient; +import ca.bc.gov.open.jag.efilingcommons.court.EfilingCourtLocationService; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("AutoConfiguration") +public class AutoConfigurationTest { + ApplicationContextRunner context = new ApplicationContextRunner() + .withUserConfiguration(AutoConfiguration.class); + + @Test + public void testConfigure() throws Exception { + + context.run(it -> { + assertThat(it).hasSingleBean(DefaultApi.class); + assertThat(it).hasSingleBean(ApiClient.class); + assertThat(it).hasSingleBean(CeisCourtLocationMapper.class); + assertThat(it).hasSingleBean(EfilingCourtLocationService.class); + }); + + } + +} diff --git a/src/backend/libs/efiling-ceis-api-client/src/test/java/ca/bc/gov/ca/open/jag/ceis/CeisPropertiesTest.java b/src/backend/libs/efiling-ceis-api-client/src/test/java/ca/bc/gov/ca/open/jag/ceis/CeisPropertiesTest.java new file mode 100644 index 0000000000..173c23f053 --- /dev/null +++ b/src/backend/libs/efiling-ceis-api-client/src/test/java/ca/bc/gov/ca/open/jag/ceis/CeisPropertiesTest.java @@ -0,0 +1,29 @@ +package ca.bc.gov.ca.open.jag.ceis; + +import ca.bc.gov.open.jag.ceis.CeisProperties; +import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.TestInstance; + + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("CeisProperties") +public class CeisPropertiesTest { + + private static final String BASEPATH = "AVALUE"; + private static final String USERNAME = "USERNAME"; + private static final String PASSWORD = "PASSWORD"; + + @Test + public void testProperties() { + CeisProperties bamboraProperties = new CeisProperties(); + bamboraProperties.setCeisBasePath(BASEPATH); + bamboraProperties.setCeisUsername(USERNAME); + bamboraProperties.setCeisPassword(PASSWORD); + Assertions.assertEquals(BASEPATH, bamboraProperties.getCeisBasePath()); + Assertions.assertEquals(USERNAME, bamboraProperties.getCeisUsername()); + Assertions.assertEquals(PASSWORD, bamboraProperties.getCeisPassword()); + } + +} diff --git a/src/backend/libs/efiling-ceis-api-client/src/test/java/ca/bc/gov/ca/open/jag/ceis/EfilingCeisCourtLocationServiceImplTest.java b/src/backend/libs/efiling-ceis-api-client/src/test/java/ca/bc/gov/ca/open/jag/ceis/EfilingCeisCourtLocationServiceImplTest.java new file mode 100644 index 0000000000..c77c0aa340 --- /dev/null +++ b/src/backend/libs/efiling-ceis-api-client/src/test/java/ca/bc/gov/ca/open/jag/ceis/EfilingCeisCourtLocationServiceImplTest.java @@ -0,0 +1,179 @@ +package ca.bc.gov.ca.open.jag.ceis; + +import ca.bc.gov.open.jag.ceis.CeisCourtLocationMapperImpl; +import ca.bc.gov.open.jag.ceis.CeisCourtLocationServiceImpl; +import ca.bc.gov.open.jag.efilingceisapiclient.api.DefaultApi; +import ca.bc.gov.open.jag.efilingceisapiclient.api.handler.ApiException; +import ca.bc.gov.open.jag.efilingceisapiclient.api.model.CourtLocation; +import ca.bc.gov.open.jag.efilingceisapiclient.api.model.CourtLocations; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingCourtLocationServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.InternalCourtLocation; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class EfilingCeisCourtLocationServiceImplTest { + + private final String PROVINCIAL = "P"; + private final String SUPREME = "S"; + + private CeisCourtLocationServiceImpl sut; + + @Mock + private DefaultApi defaultApiMock; + + @BeforeEach + public void beforeEach() throws ApiException { + + MockitoAnnotations.openMocks(this); + + sut = new CeisCourtLocationServiceImpl(defaultApiMock, new CeisCourtLocationMapperImpl()); + } + + @Test + @DisplayName("OK: Get Provincial") + public void withPAsParameterReturnOnlyProvincial() throws ApiException { + + Mockito.when(defaultApiMock.courtLocationsGet()).thenReturn(buildMockData()); + + List actual = sut.getCourtLocations(PROVINCIAL); + + Assertions.assertEquals(2, actual.size()); + + Assertions.assertEquals(BigDecimal.valueOf(1031), actual.get(0).getId()); + Assertions.assertEquals("Campbell River", actual.get(0).getName()); + Assertions.assertEquals("MockCode", actual.get(0).getCode()); + Assertions.assertEquals(true, actual.get(0).getIsSupremeCourt()); + Assertions.assertEquals("500 - 13th Avenue", actual.get(0).getAddress().getAddressLine1()); + Assertions.assertEquals(null, actual.get(0).getAddress().getAddressLine2()); + Assertions.assertEquals(null, actual.get(0).getAddress().getAddressLine3()); + Assertions.assertEquals("V9W 6P1", actual.get(0).getAddress().getPostalCode()); + Assertions.assertEquals("Campbell River", actual.get(0).getAddress().getCityName()); + Assertions.assertEquals("British Columbia", actual.get(0).getAddress().getProvinceName()); + Assertions.assertEquals("Canada", actual.get(0).getAddress().getCountryName()); + + Assertions.assertEquals(BigDecimal.valueOf(3521), actual.get(1).getId()); + Assertions.assertEquals("Chilliwack", actual.get(1).getName()); + Assertions.assertEquals("MockCode", actual.get(1).getCode()); + Assertions.assertEquals(false, actual.get(1).getIsSupremeCourt()); + Assertions.assertEquals("46085 Yale Road", actual.get(1).getAddress().getAddressLine1()); + Assertions.assertEquals(" ", actual.get(1).getAddress().getAddressLine2()); + Assertions.assertEquals(" ", actual.get(1).getAddress().getAddressLine3()); + Assertions.assertEquals("V2P 2L8", actual.get(1).getAddress().getPostalCode()); + Assertions.assertEquals("Chilliwack", actual.get(1).getAddress().getCityName()); + Assertions.assertEquals("British Columbia", actual.get(1).getAddress().getProvinceName()); + Assertions.assertEquals("Canada", actual.get(1).getAddress().getCountryName()); + + } + + @Test + @DisplayName("OK: Get Supreme") + public void withSAsParameterReturnOnlySupreme() throws ApiException { + + Mockito.when(defaultApiMock.courtLocationsGet()).thenReturn(buildMockData()); + + List actual = sut.getCourtLocations(SUPREME); + + Assertions.assertEquals(1, actual.size()); + Assertions.assertEquals(BigDecimal.valueOf(1031), actual.get(0).getId()); + Assertions.assertEquals("Campbell River", actual.get(0).getName()); + Assertions.assertEquals("MockCode", actual.get(0).getCode()); + Assertions.assertEquals(true, actual.get(0).getIsSupremeCourt()); + Assertions.assertEquals("500 - 13th Avenue", actual.get(0).getAddress().getAddressLine1()); + Assertions.assertEquals(null, actual.get(0).getAddress().getAddressLine2()); + Assertions.assertEquals(null, actual.get(0).getAddress().getAddressLine3()); + Assertions.assertEquals("V9W 6P1", actual.get(0).getAddress().getPostalCode()); + Assertions.assertEquals("Campbell River", actual.get(0).getAddress().getCityName()); + Assertions.assertEquals("British Columbia", actual.get(0).getAddress().getProvinceName()); + Assertions.assertEquals("Canada", actual.get(0).getAddress().getCountryName()); + + } + + @Test + @DisplayName("OK: Get All") + public void withNullAsParameterReturnAll() throws ApiException { + + Mockito.when(defaultApiMock.courtLocationsGet()).thenReturn(buildMockData()); + + List actual = sut.getCourtLocations(null); + + Assertions.assertEquals(2, actual.size()); + + Assertions.assertEquals(BigDecimal.valueOf(1031), actual.get(0).getId()); + Assertions.assertEquals("Campbell River", actual.get(0).getName()); + Assertions.assertEquals("MockCode", actual.get(0).getCode()); + Assertions.assertEquals(true, actual.get(0).getIsSupremeCourt()); + Assertions.assertEquals("500 - 13th Avenue", actual.get(0).getAddress().getAddressLine1()); + Assertions.assertEquals(null, actual.get(0).getAddress().getAddressLine2()); + Assertions.assertEquals(null, actual.get(0).getAddress().getAddressLine3()); + Assertions.assertEquals("V9W 6P1", actual.get(0).getAddress().getPostalCode()); + Assertions.assertEquals("Campbell River", actual.get(0).getAddress().getCityName()); + Assertions.assertEquals("British Columbia", actual.get(0).getAddress().getProvinceName()); + Assertions.assertEquals("Canada", actual.get(0).getAddress().getCountryName()); + + Assertions.assertEquals(BigDecimal.valueOf(3521), actual.get(1).getId()); + Assertions.assertEquals("Chilliwack", actual.get(1).getName()); + Assertions.assertEquals("MockCode", actual.get(1).getCode()); + Assertions.assertEquals(false, actual.get(1).getIsSupremeCourt()); + Assertions.assertEquals("46085 Yale Road", actual.get(1).getAddress().getAddressLine1()); + Assertions.assertEquals(" ", actual.get(1).getAddress().getAddressLine2()); + Assertions.assertEquals(" ", actual.get(1).getAddress().getAddressLine3()); + Assertions.assertEquals("V2P 2L8", actual.get(1).getAddress().getPostalCode()); + Assertions.assertEquals("Chilliwack", actual.get(1).getAddress().getCityName()); + Assertions.assertEquals("British Columbia", actual.get(1).getAddress().getProvinceName()); + Assertions.assertEquals("Canada", actual.get(1).getAddress().getCountryName()); + + } + + + private CourtLocations buildMockData() { + + CourtLocation courtLocationOne = new ca.bc.gov.open.jag.efilingceisapiclient.api.model.CourtLocation(); + courtLocationOne.setCourtid(BigDecimal.valueOf(1031)); + courtLocationOne.setCourtname("Campbell River"); + courtLocationOne.setCourtcode("MockCode"); + courtLocationOne.setIssupremecourt("Y"); + courtLocationOne.setIsprovincialcourt("Y"); + courtLocationOne.setAddressline1("500 - 13th Avenue"); + courtLocationOne.setPostalcode("V9W 6P1"); + courtLocationOne.setCityname("Campbell River"); + courtLocationOne.setProvincename("British Columbia"); + courtLocationOne.setCountryname("Canada"); + + + CourtLocation courtLocationTwo = new ca.bc.gov.open.jag.efilingceisapiclient.api.model.CourtLocation(); + courtLocationTwo.setCourtid(BigDecimal.valueOf(3521)); + courtLocationTwo.setCourtname("Chilliwack"); + courtLocationTwo.setCourtcode("MockCode"); + courtLocationTwo.setIssupremecourt("N"); + courtLocationTwo.setIsprovincialcourt("Y"); + courtLocationTwo.setAddressline1("46085 Yale Road"); + courtLocationTwo.setAddressline2(" "); + courtLocationTwo.setAddressline3(" "); + courtLocationTwo.setPostalcode("V2P 2L8"); + courtLocationTwo.setCityname("Chilliwack"); + courtLocationTwo.setProvincename("British Columbia"); + courtLocationTwo.setCountryname("Canada"); + + CourtLocations courtLocations = new CourtLocations(); + courtLocations.setCourtlocations(Arrays.asList(courtLocationOne,courtLocationTwo)); + return courtLocations; + + } + + @Test + @DisplayName("Error: return null") + public void withExceptionReturnNull() throws ApiException { + + Mockito.when(defaultApiMock.courtLocationsGet()).thenThrow(new ApiException()); + Assertions.assertThrows(EfilingCourtLocationServiceException.class, () -> sut.getCourtLocations(null)); + + } + +} diff --git a/src/backend/libs/efiling-commons/pom.xml b/src/backend/libs/efiling-commons/pom.xml index fba417a291..99ae17b76e 100644 --- a/src/backend/libs/efiling-commons/pom.xml +++ b/src/backend/libs/efiling-commons/pom.xml @@ -4,25 +4,30 @@ 4.0.0 ca.bc.gov.open.jag efiling-commons - 0.0.1-SNAPSHOT + 2.0.12-SNAPSHOT efiling-commons Contains common functionality to efiling - 1.8 + 17 + 2.17.1 - - org.springframework.boot - spring-boot-starter - com.fasterxml.jackson.core jackson-annotations + + com.fasterxml.jackson.core + jackson-databind + + + javax.xml.bind + jaxb-api + joda-time joda-time @@ -30,20 +35,28 @@ - org.springframework.boot - spring-boot-starter-test + org.apache.commons + commons-lang3 + + + + org.junit.jupiter + junit-jupiter-api test - - - org.junit.vintage - junit-vintage-engine - - + - joda-time - joda-time + org.junit.jupiter + junit-jupiter-engine + test + + + + org.mockito + mockito-core + test + @@ -51,14 +64,14 @@ org.springframework.boot spring-boot-dependencies - 2.3.1.RELEASE + 3.5.0 pom import ca.bc.gov.open.jag efiling-bom - 0.0.1-SNAPSHOT + 2.0.12-SNAPSHOT pom import @@ -67,12 +80,18 @@ + + + maven-surefire-plugin + 3.5.3 + + org.apache.maven.plugins maven-compiler-plugin - 8 - 8 + ${java.version} + ${java.version} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/Keys.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/Keys.java new file mode 100644 index 0000000000..df7fc833ea --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/Keys.java @@ -0,0 +1,8 @@ +package ca.bc.gov.open.jag.efilingcommons; + +public class Keys { + private Keys() {} + + public static final String WITHDRAWN_STATUS_CD = "WDRN"; + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/court/EfilingCourtLocationService.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/court/EfilingCourtLocationService.java new file mode 100644 index 0000000000..fa5f007c4c --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/court/EfilingCourtLocationService.java @@ -0,0 +1,13 @@ +package ca.bc.gov.open.jag.efilingcommons.court; + +import ca.bc.gov.open.jag.efilingcommons.model.InternalCourtLocation; + +import java.util.List; + +public interface EfilingCourtLocationService { + + + List getCourtLocations(String courtType); + + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingCourtLocationServiceException.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingCourtLocationServiceException.java new file mode 100644 index 0000000000..0b9255e6e1 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingCourtLocationServiceException.java @@ -0,0 +1,8 @@ +package ca.bc.gov.open.jag.efilingcommons.exceptions; + +public class EfilingCourtLocationServiceException extends RuntimeException { + + public EfilingCourtLocationServiceException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingCourtServiceException.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingCourtServiceException.java new file mode 100644 index 0000000000..6ff8c84265 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingCourtServiceException.java @@ -0,0 +1,12 @@ +package ca.bc.gov.open.jag.efilingcommons.exceptions; + +public class EfilingCourtServiceException extends RuntimeException { + + public EfilingCourtServiceException(String message) { + super(message); + } + + public EfilingCourtServiceException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingDocumentServiceException.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingDocumentServiceException.java new file mode 100644 index 0000000000..73285df87d --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingDocumentServiceException.java @@ -0,0 +1,12 @@ +package ca.bc.gov.open.jag.efilingcommons.exceptions; + +public class EfilingDocumentServiceException extends RuntimeException { + + public EfilingDocumentServiceException(String message) { + super(message); + } + + public EfilingDocumentServiceException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingLookupServiceException.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingLookupServiceException.java index 70bbe29b6d..deeb084f89 100644 --- a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingLookupServiceException.java +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingLookupServiceException.java @@ -2,6 +2,10 @@ public class EfilingLookupServiceException extends RuntimeException { + public EfilingLookupServiceException(String message) { + super(message); + } + public EfilingLookupServiceException(String message, Throwable cause) { super(message, cause); } diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingPaymentException.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingPaymentException.java new file mode 100644 index 0000000000..d5b15b0022 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingPaymentException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingcommons.exceptions; + +public class EfilingPaymentException extends RuntimeException { + public EfilingPaymentException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingReviewServiceException.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingReviewServiceException.java new file mode 100644 index 0000000000..f30df4430a --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingReviewServiceException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingcommons.exceptions; + +public class EfilingReviewServiceException extends RuntimeException { + public EfilingReviewServiceException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingStatusServiceException.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingStatusServiceException.java new file mode 100644 index 0000000000..701e364a18 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingStatusServiceException.java @@ -0,0 +1,12 @@ +package ca.bc.gov.open.jag.efilingcommons.exceptions; + +public class EfilingStatusServiceException extends RuntimeException { + + public EfilingStatusServiceException(String message) { + super(message); + } + + public EfilingStatusServiceException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingSubmissionServiceException.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingSubmissionServiceException.java new file mode 100644 index 0000000000..51840a62f5 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/exceptions/EfilingSubmissionServiceException.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingcommons.exceptions; + +public class EfilingSubmissionServiceException extends RuntimeException { + public EfilingSubmissionServiceException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/AccountDetails.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/AccountDetails.java index a0f385f0b5..dea976d062 100644 --- a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/AccountDetails.java +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/AccountDetails.java @@ -7,23 +7,21 @@ public class AccountDetails { + private String universalId; private BigDecimal accountId; private BigDecimal clientId; - private String firstName; - private String lastName; - private String email; - private String middleName; + private String internalClientNumber; private boolean fileRolePresent; + private boolean cardRegistered; protected AccountDetails(AccountDetails.Builder builder) { + this.universalId = builder.universalId; this.accountId = builder.accountId; this.clientId = builder.clientId; - this.firstName = builder.firstName; - this.lastName = builder.lastName; - this.email = builder.email; - this.middleName = builder.middleName; this.fileRolePresent = builder.fileRolePresent; + this.cardRegistered = builder.cardRegistered; + this.internalClientNumber = builder.internalClientNumber; } @@ -33,20 +31,27 @@ public static AccountDetails.Builder builder() { } @JsonCreator - public AccountDetails(@JsonProperty("accountId") BigDecimal accountId, - @JsonProperty("clientId") BigDecimal clientId, - @JsonProperty("fileRolePresent") boolean fileRolePresent, - @JsonProperty("firstName") String firstName, - @JsonProperty("lastName") String lastName, - @JsonProperty("middleName") String middleName, - @JsonProperty("email") String email) { + public AccountDetails( + @JsonProperty("universalId") String universalId, + @JsonProperty("accountId") BigDecimal accountId, + @JsonProperty("clientId") BigDecimal clientId, + @JsonProperty("internalClientNumber") String internalClientNumber, + @JsonProperty("fileRolePresent") boolean fileRolePresent, + @JsonProperty("firstName") String firstName, + @JsonProperty("lastName") String lastName, + @JsonProperty("middleName") String middleName, + @JsonProperty("email") String email, + @JsonProperty("cardRegistered") Boolean cardRegistered) { + this.universalId = universalId; this.accountId = accountId; this.clientId = clientId; - this.firstName = firstName; - this.lastName = lastName; - this.email = email; - this.middleName = middleName; + this.internalClientNumber = internalClientNumber; this.fileRolePresent = fileRolePresent; + this.cardRegistered = cardRegistered; + } + + public String getUniversalId() { + return universalId; } public BigDecimal getAccountId() { @@ -57,68 +62,56 @@ public BigDecimal getClientId() { return clientId; } - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } + public String getInternalClientNumber() { return internalClientNumber; } - public String getEmail() { - return email; + public boolean isFileRolePresent() { + return fileRolePresent; } - public String getMiddleName() { - return middleName; - } + public boolean isCardRegistered() { return cardRegistered; } - public boolean isFileRolePresent() { - return fileRolePresent; + public void updateInternalClientNumber(String internalClientNumber) { + this.internalClientNumber = internalClientNumber; + this.cardRegistered = this.internalClientNumber != null; } public static class Builder { + private String universalId; private BigDecimal accountId; private BigDecimal clientId; - private String firstName; - private String lastName; - private String email; - private String middleName; + private String internalClientNumber; private boolean fileRolePresent; + private boolean cardRegistered; - public Builder accountId(BigDecimal accountId) { - this.accountId = accountId; - return this; - } - public Builder clientId(BigDecimal clientId) { - this.clientId = clientId; + public Builder universalId(String universalId) { + this.universalId = universalId; return this; } - public Builder firstName(String firstName) { - this.firstName = firstName; + public Builder accountId(BigDecimal accountId) { + this.accountId = accountId; return this; } - public Builder lastName(String lastName) { - this.lastName = lastName; + public Builder clientId(BigDecimal clientId) { + this.clientId = clientId; return this; } - public Builder email(String email) { - this.email = email; + public Builder internalClientNumber(String internalClientNumber) { + this.internalClientNumber = internalClientNumber; return this; } - public Builder middleName(String middleName) { - this.middleName = middleName; + public Builder fileRolePresent(boolean fileRolePresent) { + this.fileRolePresent = fileRolePresent; return this; } - public Builder fileRolePresent(boolean fileRolePresent) { - this.fileRolePresent = fileRolePresent; + public Builder cardRegistered(boolean cardRegistered) { + this.cardRegistered = cardRegistered; return this; } diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/ActionDocument.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/ActionDocument.java new file mode 100644 index 0000000000..7e73c5e9d6 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/ActionDocument.java @@ -0,0 +1,71 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.math.BigDecimal; + +public class ActionDocument { + + private BigDecimal documentId; + private String status; + private String type; + + @JsonCreator + public ActionDocument( + @JsonProperty("documentId") BigDecimal documentId, + @JsonProperty("status") String status, + @JsonProperty("type") String type) { + this.documentId = documentId; + this.status = status; + this.type = type; + } + + public ActionDocument(ActionDocument.Builder builder) { + this.documentId = builder.documentId; + this.status = builder.status; + this.type = builder.type; + } + + public BigDecimal getDocumentId() { return documentId; } + + public String getStatus() { + return status; + } + + public String getType() { + return type; + } + + public static ActionDocument.Builder builder() { + return new ActionDocument.Builder(); + } + + public static class Builder { + + private BigDecimal documentId; + private String status; + private String type; + + public ActionDocument.Builder documentId(BigDecimal documentId) { + this.documentId = documentId; + return this; + } + + public ActionDocument.Builder status(String status) { + this.status = status; + return this; + } + + public ActionDocument.Builder type(String type) { + this.type = type; + return this; + } + + public ActionDocument create() { + return new ActionDocument(this); + } + + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Address.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Address.java new file mode 100644 index 0000000000..29f04e7889 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Address.java @@ -0,0 +1,75 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +public class Address { + private String addressLine1; + + private String addressLine2; + + private String addressLine3; + + private String postalCode; + + private String cityName; + + private String provinceName; + + private String countryName; + + public String getAddressLine1() { + return addressLine1; + } + + public void setAddressLine1(String addressLine1) { + this.addressLine1 = addressLine1; + } + + public String getAddressLine2() { + return addressLine2; + } + + public void setAddressLine2(String addressLine2) { + this.addressLine2 = addressLine2; + } + + public String getAddressLine3() { + return addressLine3; + } + + public void setAddressLine3(String addressLine3) { + this.addressLine3 = addressLine3; + } + + public String getPostalCode() { + return postalCode; + } + + public void setPostalCode(String postalCode) { + this.postalCode = postalCode; + } + + public String getCityName() { + return cityName; + } + + public void setCityName(String cityName) { + this.cityName = cityName; + } + + public String getProvinceName() { + return provinceName; + } + + public void setProvinceName(String provinceName) { + this.provinceName = provinceName; + } + + public String getCountryName() { + return countryName; + } + + public void setCountryName(String countryName) { + this.countryName = countryName; + } + +} + diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Clients.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Clients.java index e434232cf9..db24bb7154 100644 --- a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Clients.java +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Clients.java @@ -4,5 +4,10 @@ public enum Clients { ACCOUNT, ROLE, LOOKUP, - BCEID; + STATUS, + CSOWS, + FILING, + SERVICE, + SEARCH, + REPORT; } diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Court.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Court.java new file mode 100644 index 0000000000..19ac45815e --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Court.java @@ -0,0 +1,172 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.math.BigDecimal; + +public class Court { + + private BigDecimal agencyId; + private String locationDescription; + private String location; + private String level; + private String levelDescription; + private String courtClass; + private String classDescription; + private String division; + private String fileNumber; + private String participatingClass; + + + public Court(Builder builder) { + this.agencyId = builder.agencyId; + this.location = builder.location; + this.locationDescription = builder.locationDescription; + this.level = builder.level; + this.levelDescription = builder.levelDescription; + this.courtClass = builder.courtClass; + this.classDescription = builder.classDescription; + this.division = builder.division; + this.fileNumber = builder.fileNumber; + this.participatingClass = builder.participatingClass; + } + + @JsonCreator + public Court( + @JsonProperty("agencyId") BigDecimal agencyId, + @JsonProperty("location") String location, + @JsonProperty("locationDescription") String locationDescription, + @JsonProperty("level") String level, + @JsonProperty("levelDescription") String levelDescription, + @JsonProperty("courtClass") String courtClass, + @JsonProperty("classDescription") String classDescription, + @JsonProperty("division") String division, + @JsonProperty("fileNumber") String fileNumber, + @JsonProperty("participatingClass") String participatingClass) { + this.agencyId = agencyId; + this.location = location; + this.locationDescription = locationDescription; + this.level = level; + this.levelDescription = levelDescription; + this.courtClass = courtClass; + this.classDescription = classDescription; + this.division = division; + this.fileNumber = fileNumber; + this.participatingClass = participatingClass; + } + + public String getLocation() { + return location; + } + + public String getLevel() { + return level; + } + + public String getCourtClass() { + return courtClass; + } + + public String getDivision() { + return division; + } + + public String getFileNumber() { + return fileNumber; + } + + public String getParticipatingClass() { + return participatingClass; + } + + public BigDecimal getAgencyId() { + return agencyId; + } + + public String getLocationDescription() { + return locationDescription; + } + + public String getLevelDescription() { + return levelDescription; + } + + public String getClassDescription() { + return classDescription; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private BigDecimal agencyId; + private String location; + private String locationDescription; + private String level; + private String levelDescription; + private String courtClass; + private String classDescription; + private String division; + private String fileNumber; + private String participatingClass; + + public Builder agencyId(BigDecimal agencyId) { + this.agencyId = agencyId; + return this; + } + + public Builder location(String location) { + this.location = location; + return this; + } + + public Builder locationDescription(String locationDescription) { + this.locationDescription = locationDescription; + return this; + } + + public Builder level(String level) { + this.level = level; + return this; + } + + public Builder levelDescription(String levelDescription) { + this.levelDescription = levelDescription; + return this; + } + + public Builder courtClass(String courtClass) { + this.courtClass = courtClass; + return this; + } + + public Builder classDescription(String classDescription) { + this.classDescription = classDescription; + return this; + } + + public Builder division(String division) { + this.division = division; + return this; + } + + public Builder fileNumber(String fileNumber) { + this.fileNumber = fileNumber; + return this; + } + + public Builder participatingClass(String participatingClass) { + this.participatingClass = participatingClass; + return this; + } + + public Court create() { + return new Court(this); + } + + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/CourtDetails.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/CourtDetails.java new file mode 100644 index 0000000000..b5f9604238 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/CourtDetails.java @@ -0,0 +1,50 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.math.BigDecimal; + +public class CourtDetails { + @JsonCreator + public CourtDetails( + @JsonProperty("courtId") BigDecimal courtId, + @JsonProperty("courtDescription") String courtDescription, + @JsonProperty("classDescription") String classDescription, + @JsonProperty("levelDescription") String levelDescription) { + this.courtId = courtId; + this.courtDescription = courtDescription; + this.classDescription = classDescription; + this.levelDescription = levelDescription; + } + + + public BigDecimal getCourtId() { + return courtId; + } + + public void setCourtId(BigDecimal courtId) { + this.courtId = courtId; + } + + public String getCourtDescription() { + return courtDescription; + } + + public void setCourtDescription(String courtDescription) { + this.courtDescription = courtDescription; + } + + public String getClassDescription() { return classDescription; } + + public void setClassDescription(String classDescription) { this.classDescription = classDescription; } + + public String getLevelDescription() { return levelDescription; } + + public void setLevelDescription(String levelDescription) { this.levelDescription = levelDescription; } + + BigDecimal courtId; + String courtDescription; + String classDescription; + String levelDescription; +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/CreateAccountRequest.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/CreateAccountRequest.java new file mode 100644 index 0000000000..f135f22f29 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/CreateAccountRequest.java @@ -0,0 +1,122 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + + +/** + * Represents a request to create an account + */ +public class CreateAccountRequest { + + private String universalId; + private String firstName; + private String lastName; + private String middleName; + private String email; + private String identityProvider; + + protected CreateAccountRequest(CreateAccountRequest.Builder builder) { + + this.universalId = builder.universalId; + this.firstName = builder.firstName; + this.lastName = builder.lastName; + this.middleName = builder.middleName; + this.email = builder.email; + this.identityProvider = builder.identityProvider; + + } + + public static CreateAccountRequest.Builder builder() { + return new CreateAccountRequest.Builder(); + } + + /** + * Get the universalId + * @return + */ + public String getUniversalId() { + return universalId; + } + + /** + * Get the account First Name + * @return + */ + public String getFirstName() { + return firstName; + } + + /** + * Get the account Last Name + * @return + */ + public String getLastName() { + return lastName; + } + + /** + * Get the account Middle Name + * @return + */ + public String getMiddleName() { + return middleName; + } + + /** + * Get the account Email + * @return + */ + public String getEmail() { + return email; + } + + /** + * Get the identity provider + * @return + */ + public String getIdentityProvider() { return identityProvider; } + + public static class Builder { + + private String universalId; + private String firstName; + private String lastName; + private String middleName; + private String email; + private String identityProvider; + + public Builder universalId(String universalId) { + this.universalId = universalId; + return this; + } + + public Builder firstName(String firstName) { + this.firstName = firstName; + return this; + } + + public Builder lastName(String lastName) { + this.lastName = lastName; + return this; + } + + public Builder middleName(String middleName) { + this.middleName = middleName; + return this; + } + + public Builder email(String email) { + this.email = email; + return this; + } + + public Builder identityProvider(String identityProvider) { + this.identityProvider = identityProvider; + return this; + } + + public CreateAccountRequest create() { + return new CreateAccountRequest(this); + } + + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Document.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Document.java new file mode 100644 index 0000000000..4656852383 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Document.java @@ -0,0 +1,199 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.math.BigDecimal; + +public class Document { + + private String name; + private String type; + private String subType; + private Boolean isAmendment; + private Boolean isSupremeCourtScheduling; + private Object data; + private String description; + private BigDecimal statutoryFeeAmount; + private String mimeType; + private String documentId; + private String serverFileName; + private ActionDocument actionDocument; + + @JsonCreator + public Document(@JsonProperty("name") String name, + @JsonProperty("type") String type, + @JsonProperty("subType") String subType, + @JsonProperty("isAmendment") Boolean isAmendment, + @JsonProperty("isSupremeCourtScheduling") Boolean isSupremeCourtScheduling, + @JsonProperty("data") Object data, + @JsonProperty("description") String description, + @JsonProperty("statutoryFeeAmount") BigDecimal statutoryFeeAmount, + @JsonProperty("mimeType") String mimeType, + @JsonProperty("documentId") String documentId, + @JsonProperty("serverFileName") String serverFileName, + @JsonProperty("actionDocument") ActionDocument actionDocument) { + this.name = name; + this.type = type; + this.subType = subType; + this.isAmendment = isAmendment; + this.isSupremeCourtScheduling = isSupremeCourtScheduling; + this.data = data; + this.description = description; + this.statutoryFeeAmount = statutoryFeeAmount; + this.mimeType = mimeType; + this.documentId = documentId; + this.serverFileName = serverFileName; + this.actionDocument = actionDocument; + } + + public Document(Builder builder) { + this.name = builder.name; + this.type = builder.type; + this.subType = builder.subType; + this.isAmendment = builder.isAmendment; + this.isSupremeCourtScheduling = builder.isSupremeCourtScheduling; + this.data = builder.data; + this.description = builder.description; + this.statutoryFeeAmount = builder.statutoryFeeAmount; + this.mimeType = builder.mimeType; + this.documentId = builder.documentId; + this.serverFileName = builder.serverFileName; + this.actionDocument = builder.actionDocument; + } + + public String getName() { + return name; + } + + public String getType() { + return type; + } + + public String getSubType() { + return subType; + } + + public Boolean getIsAmendment() { + return isAmendment; + } + + public Boolean getIsSupremeCourtScheduling() { + return isSupremeCourtScheduling; + } + + public Object getData() { + return data; + } + + public String getDescription() { + return description; + } + + public BigDecimal getStatutoryFeeAmount() { + return statutoryFeeAmount; + } + + public String getMimeType() { + return mimeType; + } + + public String getDocumentId() { + return documentId; + } + + public String getServerFileName() { + return serverFileName; + } + + public void setServerFileName(String serverFileName) { + this.serverFileName = serverFileName; + } + + public ActionDocument getActionDocument() { return actionDocument; } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private String name; + private String type; + private String subType; + private Boolean isAmendment; + private Boolean isSupremeCourtScheduling; + private Object data; + private String description; + private BigDecimal statutoryFeeAmount; + private String mimeType; + private String documentId; + private String serverFileName; + private ActionDocument actionDocument; + + public Builder name(String name) { + this.name = name; + return this; + } + + public Builder type(String type) { + this.type = type; + return this; + } + + public Builder subType(String subType) { + this.subType = subType; + return this; + } + + public Builder isAmendment(Boolean isAmendment) { + this.isAmendment = isAmendment; + return this; + } + + public Builder isSupremeCourtScheduling(Boolean isSupremeCourtScheduling) { + this.isSupremeCourtScheduling = isSupremeCourtScheduling; + return this; + } + + public Builder data(Object data) { + this.data = data; + return this; + } + + public Builder description(String description) { + this.description = description; + return this; + } + + public Builder statutoryFeeAmount(BigDecimal statutoryFeeAmount) { + this.statutoryFeeAmount = statutoryFeeAmount; + return this; + } + + public Builder mimeType(String mimeType) { + this.mimeType = mimeType; + return this; + } + + public Builder documentId(String documentId) { + this.documentId = documentId; + return this; + } + + public Builder serverFileName(String serverFileName) { + this.serverFileName = serverFileName; + return this; + } + + public Builder actionDocument(ActionDocument actionDocument) { + this.actionDocument = actionDocument; + return this; + } + + public Document create() { + return new Document(this); + } + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/DocumentTypeDetails.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/DocumentTypeDetails.java new file mode 100644 index 0000000000..2fbd72f589 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/DocumentTypeDetails.java @@ -0,0 +1,65 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.math.BigDecimal; + +public class DocumentTypeDetails { + + private String description; + + private String type; + + private Boolean autoProcessing; + + private BigDecimal statutoryFeeAmount; + + private Boolean orderDocument; + + private Boolean rushRequired; + + public String getDescription() { return description; } + + public void setDescription(String description) { this.description = description; } + + public BigDecimal getStatutoryFeeAmount() { return statutoryFeeAmount; } + + public void setStatutoryFeeAmount(BigDecimal statutoryFeeAmount) { this.statutoryFeeAmount = statutoryFeeAmount; } + + public Boolean isOrderDocument() { return orderDocument; } + + public void setOrderDocument(Boolean orderDocument) { this.orderDocument = orderDocument; } + + public Boolean isRushRequired() { + return rushRequired; + } + + public void setRushRequired(Boolean rushRequired) { + this.rushRequired = rushRequired; + } + + public String getType() { return type; } + + public void setType(String type) { this.type = type; } + + public Boolean isAutoProcessing() { return autoProcessing; } + + public void setAutoProcessing(Boolean autoProcessing) { this.autoProcessing = autoProcessing; } + + @JsonCreator + public DocumentTypeDetails(@JsonProperty("description") String description, + @JsonProperty("type") String type, + @JsonProperty("statutoryFeeAmount") BigDecimal statutoryFeeAmount, + @JsonProperty("orderDocument") boolean orderDocument, + @JsonProperty("rushRequired") boolean rushRequired, + @JsonProperty("autoProcessing") boolean autoProcessing) { + this.description = description; + this.type = type; + this.statutoryFeeAmount = statutoryFeeAmount; + this.orderDocument = orderDocument; + this.rushRequired = rushRequired; + this.autoProcessing = autoProcessing; + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/EfilingPayment.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/EfilingPayment.java new file mode 100644 index 0000000000..876f469ca3 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/EfilingPayment.java @@ -0,0 +1,32 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +import java.math.BigDecimal; + +public class EfilingPayment { + + private BigDecimal serviceId; + private BigDecimal paymentAmount; + private String invoiceNumber; + private String internalClientNumber; + + public EfilingPayment(BigDecimal serviceId, BigDecimal paymentAmount, String invoiceNumber, String internalClientNumber) { + + this.serviceId = serviceId; + this.paymentAmount = paymentAmount; + this.invoiceNumber = invoiceNumber; + this.internalClientNumber = internalClientNumber; + + } + + public BigDecimal getServiceId() { + return serviceId; + } + + public BigDecimal getPaymentAmount() { + return paymentAmount; + } + + public String getInvoiceNumber() { return invoiceNumber; } + + public String getInternalClientNumber() { return internalClientNumber; } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/EfilingSoapClientProperties.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/EfilingSoapClientProperties.java index 27b4540d39..9150bb5a06 100644 --- a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/EfilingSoapClientProperties.java +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/EfilingSoapClientProperties.java @@ -38,4 +38,5 @@ public Clients getClient() { public void setClient(Clients client) { this.client = client; } + } diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Individual.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Individual.java new file mode 100644 index 0000000000..33dc124db0 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Individual.java @@ -0,0 +1,127 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Individual { + + private String partyTypeDesc; + private String roleTypeCd; + private String roleTypeDesc; + private String firstName; + private String middleName; + private String lastName; + private String nameTypeCd; + + @JsonCreator + public Individual( + @JsonProperty("partyTypeDesc") String partyTypeDesc, + @JsonProperty("roleTypeCd") String roleTypeCd, + @JsonProperty("roleTypeDesc") String roleTypeDesc, + @JsonProperty("firstName") String firstName, + @JsonProperty("middleName") String middleName, + @JsonProperty("lastName") String lastName, + @JsonProperty("nameTypeCd") String nameTypeCd) { + this.partyTypeDesc = partyTypeDesc; + this.roleTypeCd = roleTypeCd; + this.roleTypeDesc = roleTypeDesc; + this.firstName = firstName; + this.middleName = middleName; + this.lastName = lastName; + this.nameTypeCd = nameTypeCd; + } + + public Individual(Builder builder) { + this.partyTypeDesc = builder.partyTypeDesc; + this.roleTypeCd = builder.roleTypeCd; + this.roleTypeDesc = builder.roleTypeDesc; + this.firstName = builder.firstName; + this.middleName = builder.middleName; + this.lastName = builder.lastName; + this.nameTypeCd = builder.nameTypeCd; + } + + public String getPartyTypeDesc() { + return partyTypeDesc; + } + + public String getRoleTypeCd() { + return roleTypeCd; + } + + public String getRoleTypeDesc() { + return roleTypeDesc; + } + + public String getFirstName() { + return firstName; + } + + public String getMiddleName() { + return middleName; + } + + public String getLastName() { + return lastName; + } + + public String getNameTypeCd() { + return nameTypeCd; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private String partyTypeDesc; + private String roleTypeCd; + private String roleTypeDesc; + private String firstName; + private String middleName; + private String lastName; + private String nameTypeCd; + + public Builder partyTypeDesc(String partyTypeDesc) { + this.partyTypeDesc = partyTypeDesc; + return this; + } + + public Builder roleTypeCd(String roleTypeCd) { + this.roleTypeCd = roleTypeCd; + return this; + } + + public Builder roleTypeDesc(String roleTypeDesc) { + this.roleTypeDesc = roleTypeDesc; + return this; + } + + public Builder firstName(String firstName) { + this.firstName = firstName; + return this; + } + + public Builder middleName(String middleName) { + this.middleName = middleName; + return this; + } + + public Builder lastName(String lastName) { + this.lastName = lastName; + return this; + } + + public Builder nameTypeCd(String nameTypeCd) { + this.nameTypeCd = nameTypeCd; + return this; + } + + public Individual create() { + return new Individual(this); + } + + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/InternalCourtLocation.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/InternalCourtLocation.java new file mode 100644 index 0000000000..4377228576 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/InternalCourtLocation.java @@ -0,0 +1,67 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +import java.math.BigDecimal; + +public class InternalCourtLocation { + + private BigDecimal id; + + private String identifierCode; + + private String name; + + private String code; + + private Boolean isSupremeCourt; + + private Address address; + + public BigDecimal getId() { + return id; + } + + public void setId(BigDecimal id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public Boolean getIsSupremeCourt() { + return isSupremeCourt; + } + + public void setIsSupremeCourt(Boolean isSupremeCourt) { + this.isSupremeCourt = isSupremeCourt; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public String getIdentifierCode() { + return identifierCode; + } + + public void setIdentifierCode(String identifierCode) { + this.identifierCode = identifierCode; + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Organization.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Organization.java new file mode 100644 index 0000000000..c4d704bddd --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/Organization.java @@ -0,0 +1,96 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Organization { + private String partyTypeDesc; + private String roleTypeCd; + private String roleTypeDesc; + private String name; + private String nameTypeCd; + + @JsonCreator + public Organization( + @JsonProperty("partyTypeDesc") String partyTypeDesc, + @JsonProperty("roleTypeCd") String roleTypeCd, + @JsonProperty("roleTypeDesc") String roleTypeDesc, + @JsonProperty("name") String name, + @JsonProperty("nameTypeCd") String nameTypeCd) { + this.partyTypeDesc = partyTypeDesc; + this.roleTypeCd = roleTypeCd; + this.roleTypeDesc = roleTypeDesc; + this.name = name; + this.nameTypeCd = nameTypeCd; + } + + public Organization(Organization.Builder builder) { + this.partyTypeDesc = builder.partyTypeDesc; + this.roleTypeCd = builder.roleTypeCd; + this.roleTypeDesc = builder.roleTypeDesc; + this.name = builder.name; + this.nameTypeCd = builder.nameTypeCd; + } + + public String getPartyTypeDesc() { + return partyTypeDesc; + } + + public String getRoleTypeCd() { + return roleTypeCd; + } + + public String getRoleTypeDesc() { + return roleTypeDesc; + } + + public String getName() { + return name; + } + + public String getNameTypeCd() { + return nameTypeCd; + } + + public static Organization.Builder builder() { + return new Organization.Builder(); + } + + public static class Builder { + + private String partyTypeDesc; + private String roleTypeCd; + private String roleTypeDesc; + private String name; + private String nameTypeCd; + + public Organization.Builder partyTypeDesc(String partyTypeDesc) { + this.partyTypeDesc = partyTypeDesc; + return this; + } + + public Organization.Builder roleTypeCd(String roleTypeCd) { + this.roleTypeCd = roleTypeCd; + return this; + } + + public Organization.Builder roleTypeDesc(String roleTypeDesc) { + this.roleTypeDesc = roleTypeDesc; + return this; + } + + public Organization.Builder name(String name) { + this.name = name; + return this; + } + + public Organization.Builder nameTypeCd(String nameTypeCd) { + this.nameTypeCd = nameTypeCd; + return this; + } + + public Organization create() { + return new Organization(this); + } + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/PaymentTransaction.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/PaymentTransaction.java new file mode 100644 index 0000000000..a4a5f32650 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/PaymentTransaction.java @@ -0,0 +1,156 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +import org.joda.time.DateTime; + +import java.math.BigDecimal; + +public class PaymentTransaction { + + private String approvalCd; + private String creditCardTypeCd; + private BigDecimal ecommerceTransactionId; + private DateTime entDtm; + private String entUserId; + private String internalClientNo; + private String invoiceNo; + private DateTime processDt; + private String referenceMessageTxt; + private BigDecimal serviceId; + private BigDecimal transactionAmt; + private String transactionStateCd; + private DateTime transactonDtm; + + public PaymentTransaction(String approvalCd, + String creditCardTypeCd, + BigDecimal ecommerceTransactionId, + DateTime entDtm, + String entUserId, + String internalClientNo, + String invoiceNo, + DateTime processDt, + String referenceMessageTxt, + BigDecimal serviceId, + BigDecimal transactionAmt, + String transactionStateCd, + DateTime transactonDtm) { + this.approvalCd = approvalCd; + this.creditCardTypeCd = creditCardTypeCd; + this.ecommerceTransactionId = ecommerceTransactionId; + this.entDtm = entDtm; + this.entUserId = entUserId; + this.internalClientNo = internalClientNo; + this.invoiceNo = invoiceNo; + this.processDt = processDt; + this.referenceMessageTxt = referenceMessageTxt; + this.serviceId = serviceId; + this.transactionAmt = transactionAmt; + this.transactionStateCd = transactionStateCd; + this.transactonDtm = transactonDtm; + } + + public PaymentTransaction() { + + } + + + public String getApprovalCd() { + return approvalCd; + } + + public void setApprovalCd(String approvalCd) { + this.approvalCd = approvalCd; + } + + public String getCreditCardTypeCd() { + return creditCardTypeCd; + } + + public void setCreditCardTypeCd(String creditCardTypeCd) { + this.creditCardTypeCd = creditCardTypeCd; + } + + public BigDecimal getEcommerceTransactionId() { + return ecommerceTransactionId; + } + + public void setEcommerceTransactionId(BigDecimal ecommerceTransactionId) { this.ecommerceTransactionId = ecommerceTransactionId; } + + public DateTime getEntDtm() { return entDtm; } + + public void setEntDtm(DateTime entDtm) { + this.entDtm = entDtm; + } + + public String getEntUserId() { + return entUserId; + } + + public void setEntUserId(String entUserId) { + this.entUserId = entUserId; + } + + public String getInternalClientNo() { + return internalClientNo; + } + + public void setInternalClientNo(String internalClientNo) { + this.internalClientNo = internalClientNo; + } + + public String getInvoiceNo() { + return invoiceNo; + } + + public void setInvoiceNo(String invoiceNo) { + this.invoiceNo = invoiceNo; + } + + public DateTime getProcessDt() { + return processDt; + } + + public void setProcessDt(DateTime processDt) { + this.processDt = processDt; + } + + public String getReferenceMessageTxt() { + return referenceMessageTxt; + } + + public void setReferenceMessageTxt(String referenceMessageTxt) { + this.referenceMessageTxt = referenceMessageTxt; + } + + public BigDecimal getServiceId() { + return serviceId; + } + + public void setServiceId(BigDecimal serviceId) { + this.serviceId = serviceId; + } + + public BigDecimal getTransactionAmt() { + return transactionAmt; + } + + public void setTransactionAmt(BigDecimal transactionAmt) { + this.transactionAmt = transactionAmt; + } + + public String getTransactionStateCd() { + return transactionStateCd; + } + + public void setTransactionStateCd(String transactionStateCd) { + this.transactionStateCd = transactionStateCd; + } + + public DateTime getTransactonDtm() { + return transactonDtm; + } + + public void setTransactonDtm(DateTime transactonDtm) { + this.transactonDtm = transactonDtm; + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/RushDocumentRequest.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/RushDocumentRequest.java new file mode 100644 index 0000000000..4596f0261a --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/RushDocumentRequest.java @@ -0,0 +1,41 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +import java.math.BigDecimal; + +public class RushDocumentRequest { + private BigDecimal procReqId; + private BigDecimal procItemSeqNo; + private BigDecimal docSeqNo; + + public RushDocumentRequest(RushDocumentRequest.Builder builder) { + this.procReqId = builder.procReqId; + this.procItemSeqNo = builder.procItemSeqNo; + this.docSeqNo = builder.docSeqNo; + } + + public BigDecimal getProcReqId() { return procReqId; } + + public BigDecimal getProcItemSeqNo() { return procItemSeqNo; } + + public BigDecimal getDocSeqNo() { return docSeqNo; } + + public static RushDocumentRequest.Builder builder() { + return new RushDocumentRequest.Builder(); + } + + public static class Builder { + + private BigDecimal procReqId; + private BigDecimal procItemSeqNo; + private BigDecimal docSeqNo; + + public RushDocumentRequest.Builder procReqId(BigDecimal procReqId) { this.procReqId = procReqId; return this;} + public RushDocumentRequest.Builder procItemSeqNo(BigDecimal procItemSeqNo) { this.procItemSeqNo = procItemSeqNo; return this;} + public RushDocumentRequest.Builder docSeqNo(BigDecimal docSeqNo) { this.docSeqNo = docSeqNo; return this;} + + public RushDocumentRequest create() { + return new RushDocumentRequest(this); + } + + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/RushProcessing.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/RushProcessing.java new file mode 100644 index 0000000000..96df58bfb4 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/RushProcessing.java @@ -0,0 +1,180 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.ArrayList; +import java.util.List; + +public class RushProcessing { + + private String rushType; + private String firstName; + private String lastName; + private String email; + private String organization; + private String phoneNumber; + private String courtDate; + private String country; + private String countryCode; + private String reason; + private List supportingDocuments = new ArrayList<>(); + + public RushProcessing(RushProcessing.Builder builder) { + this.rushType = builder.rushType; + this.firstName = builder.firstName; + this.lastName = builder.lastName; + this.email = builder.email; + this.organization = builder.organization; + this.phoneNumber = builder.phoneNumber; + this.courtDate = builder.courtDate; + this.country = builder.country; + this.countryCode = builder.countryCode; + this.reason = builder.reason; + this.supportingDocuments.addAll(builder.supportingDocuments); + } + + @JsonCreator + public RushProcessing( + @JsonProperty("rushType") String rushType, + @JsonProperty("firstName") String firstName, + @JsonProperty("lastName") String lastName, + @JsonProperty("email") String email, + @JsonProperty("organization") String organization, + @JsonProperty("phoneNumber") String phoneNumber, + @JsonProperty("courtDate") String courtDate, + @JsonProperty("country") String country, + @JsonProperty("countryCode") String countryCode, + @JsonProperty("reason") String reason, + @JsonProperty("supportingDocuments") List supportingDocuments) { + this.rushType = rushType; + this.firstName = firstName; + this.lastName = lastName; + this.email = email; + this.organization = organization; + this.phoneNumber = phoneNumber; + this.courtDate = courtDate; + this.country = country; + this.countryCode = countryCode; + this.reason = reason; + this.supportingDocuments.addAll(supportingDocuments); + } + + public String getRushType() { return rushType; } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public String getEmail() { return email; } + + public String getOrganization() { + return organization; + } + + public String getPhoneNumber() { + return phoneNumber; + } + + public String getCourtDate() { return courtDate; } + + public String getCountry() { + return country; + } + + public String getCountryCode() { + return countryCode; + } + + public String getReason() { + return reason; + } + + public List getSupportingDocuments() { + return supportingDocuments; + } + + public static RushProcessing.Builder builder() { + return new RushProcessing.Builder(); + } + + public static class Builder { + + private String rushType; + private String firstName; + private String lastName; + private String email; + private String organization; + private String phoneNumber; + private String courtDate; + private String country; + private String countryCode; + private String reason; + private List supportingDocuments = new ArrayList<>(); + + public RushProcessing.Builder rushType(String rushType) { + this.rushType = rushType; + return this; + } + + public RushProcessing.Builder firstName(String firstName) { + this.firstName = firstName; + return this; + } + + public RushProcessing.Builder lastName(String lastName) { + this.lastName = lastName; + return this; + } + + public RushProcessing.Builder email(String email) { + this.email = email; + return this; + } + + public RushProcessing.Builder organization(String organization) { + this.organization = organization; + return this; + } + + public RushProcessing.Builder phoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + return this; + } + + public RushProcessing.Builder courtDate(String courtDate) { + this.courtDate = courtDate; + return this; + } + + public RushProcessing.Builder country(String country) { + this.country = country; + return this; + } + + public RushProcessing.Builder countryCode(String countryCode) { + this.countryCode = countryCode; + return this; + } + + public RushProcessing.Builder reason(String reason) { + this.reason = reason; + return this; + } + + public RushProcessing.Builder supportingDocuments(List supportingDocuments) { + this.supportingDocuments.addAll(supportingDocuments); + return this; + } + + public RushProcessing create() { + return new RushProcessing(this); + } + + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/ServiceFees.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/ServiceFees.java index 31551c3258..f731476bc6 100644 --- a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/ServiceFees.java +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/ServiceFees.java @@ -2,58 +2,30 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -import org.joda.time.*; import java.math.BigDecimal; public class ServiceFees { + // Allowing 8 params to constructor as it is a map to SOAP reply @SuppressWarnings("squid:S00107") @JsonCreator public ServiceFees( - @JsonProperty("udpDtm") DateTime udpDtm, - @JsonProperty("feeAmt") BigDecimal feeAmt, - @JsonProperty("entUserId") String entUserId, - @JsonProperty("serviceTypeCd") String serviceTypeCd, - @JsonProperty("effectiveDt") DateTime effectiveDt, - @JsonProperty("updUserId") String updUserId, - @JsonProperty("entDtm") DateTime entDtm, - @JsonProperty("expiryDt") DateTime expiryDt) { - - this.udpDtm = udpDtm; - this.feeAmt = feeAmt; - this.entUserId = entUserId; + @JsonProperty("feeAmount") BigDecimal feeAmount, + @JsonProperty("serviceTypeCd") String serviceTypeCd) { + this.feeAmount = feeAmount; this.serviceTypeCd = serviceTypeCd; - this.effectiveDt = effectiveDt; - this.updUserId = updUserId; - this.entDtm = entDtm; - this.expiryDt = expiryDt; - } - - public DateTime getUdpDtm() { - return udpDtm; } - public void setUdpDtm(DateTime udpDtm) { - this.udpDtm = udpDtm; - } - - public BigDecimal getFeeAmt() { - return feeAmt; - } - public void setFeeAmt(BigDecimal feeAmt) { - this.feeAmt = feeAmt; + public BigDecimal getFeeAmount() { + return feeAmount; } - public String getEntUserId() { - return entUserId; - } - - public void setEntUserId(String entUserId) { - this.entUserId = entUserId; + public void setFeeAmount(BigDecimal feeAmount) { + this.feeAmount = feeAmount; } public String getServiceTypeCd() { @@ -64,44 +36,6 @@ public void setServiceTypeCd(String serviceTypeCd) { this.serviceTypeCd = serviceTypeCd; } - public DateTime getEffectiveDt() { - return effectiveDt; - } - - public void setEffectiveDt(DateTime effectiveDt) { - this.effectiveDt = effectiveDt; - } - - public String getUpdUserId() { - return updUserId; - } - - public void setUpdUserId(String updUserId) { - this.updUserId = updUserId; - } - - public DateTime getEntDtm() { - return entDtm; - } - - public void setEntDtm(DateTime entDtm) { - this.entDtm = entDtm; - } - - public DateTime getExpiryDt() { - return expiryDt; - } - - public void setExpiryDt(DateTime expiryDt) { - this.expiryDt = expiryDt; - } - - DateTime udpDtm; - BigDecimal feeAmt; - String entUserId; + BigDecimal feeAmount; String serviceTypeCd; - DateTime effectiveDt; - String updUserId; - DateTime entDtm; - DateTime expiryDt; } diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/SubmissionFeeRequest.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/SubmissionFeeRequest.java new file mode 100644 index 0000000000..598a526b9a --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/SubmissionFeeRequest.java @@ -0,0 +1,63 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +public class SubmissionFeeRequest { + private String serviceType; + private String application; + private String division; + private String level; + private String classification; + + + public SubmissionFeeRequest(SubmissionFeeRequest.Builder builder) { + this.serviceType = builder.serviceType; + this.application = builder.application; + this.division = builder.division; + this.level = builder.level; + this.classification = builder.classification; + } + + + public String getServiceType() { + return serviceType; + } + + public String getApplication() { + return application; + } + + public String getDivision() { + return division; + } + + public String getLevel() { + return level; + } + + public String getClassification() { + return classification; + } + + public static SubmissionFeeRequest.Builder builder() { + return new SubmissionFeeRequest.Builder(); + } + + public static class Builder { + + private String serviceType; + private String application; + private String division; + private String level; + private String classification; + + public SubmissionFeeRequest.Builder serviceType(String serviceType) { this.serviceType = serviceType; return this;} + public SubmissionFeeRequest.Builder application(String application) { this.application = application; return this;} + public SubmissionFeeRequest.Builder division(String division) { this.division = division; return this;} + public SubmissionFeeRequest.Builder level(String level) { this.level = level; return this;} + public SubmissionFeeRequest.Builder classification(String classification) { this.classification = classification; return this;} + + public SubmissionFeeRequest create() { + return new SubmissionFeeRequest(this); + } + + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/SubmitPackageResponse.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/SubmitPackageResponse.java new file mode 100644 index 0000000000..25f4879ac2 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/SubmitPackageResponse.java @@ -0,0 +1,41 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +import java.math.BigDecimal; + +public class SubmitPackageResponse { + + private String packageLink; + private BigDecimal transactionId; + + public SubmitPackageResponse(Builder builder) { + this.packageLink = builder.packageLink; + this.transactionId = builder.transactionId; + } + + public String getPackageLink() { + return packageLink; + } + + public BigDecimal getTransactionId() { + return transactionId; + } + + public static Builder builder() { + return new SubmitPackageResponse.Builder(); + } + + public static class Builder { + + private String packageLink; + private BigDecimal transactionId; + + public Builder packageLink(String packageLink) { this.packageLink = packageLink; return this;} + public Builder transactionId(BigDecimal transactionId) { this.transactionId = transactionId; return this;} + + public SubmitPackageResponse create() { + return new SubmitPackageResponse(this); + } + + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/payment/PaymentAdapter.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/payment/PaymentAdapter.java new file mode 100644 index 0000000000..1923d3fe07 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/payment/PaymentAdapter.java @@ -0,0 +1,10 @@ +package ca.bc.gov.open.jag.efilingcommons.payment; + +import ca.bc.gov.open.jag.efilingcommons.model.EfilingPayment; +import ca.bc.gov.open.jag.efilingcommons.model.PaymentTransaction; + +public interface PaymentAdapter { + + PaymentTransaction makePayment(EfilingPayment efilingPayment); + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingAccountService.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingAccountService.java index 92428e8204..2ab0c67264 100644 --- a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingAccountService.java +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingAccountService.java @@ -1,14 +1,29 @@ package ca.bc.gov.open.jag.efilingcommons.service; import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; - -import java.util.UUID; +import ca.bc.gov.open.jag.efilingcommons.model.CreateAccountRequest; /** - * Interface for getting CSO account details based on a user GUID + * Interface for getting account details based on a user GUID */ public interface EfilingAccountService { - AccountDetails getAccountDetails(UUID userGuid, String bceidAccountType); + /** + * Get the account details + * @param universalId + * @return + */ + AccountDetails getAccountDetails(String universalId); + + /** + * Creates a new account + * @param createAccountRequest + * @return + */ + AccountDetails createAccount(CreateAccountRequest createAccountRequest); + + void updateClient(AccountDetails accountDetails); + + String getOrderNumber(); } diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingCourtService.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingCourtService.java new file mode 100644 index 0000000000..68f055c93e --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingCourtService.java @@ -0,0 +1,16 @@ +package ca.bc.gov.open.jag.efilingcommons.service; + +import ca.bc.gov.open.jag.efilingcommons.model.CourtDetails; + +import java.math.BigDecimal; +import java.util.Optional; + +public interface EfilingCourtService { + + Optional getCourtDescription(String agencyIdentifierCd, String courtLevel, String courtClass); + + boolean checkValidLevelClassLocation(BigDecimal agencyId, String courtLevel, String courtClass, String applicationCode); + + boolean checkValidCourtFileNumber(String fileNumber, BigDecimal agencyId, String courtLevel, String courtClass, String applicationCode); + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingDocumentService.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingDocumentService.java new file mode 100644 index 0000000000..cb30ecbbb8 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingDocumentService.java @@ -0,0 +1,26 @@ +package ca.bc.gov.open.jag.efilingcommons.service; + +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; + +import java.util.List; + +public interface EfilingDocumentService { + + /** + * Search for details related to the document type + * @param courtLevel level code used by cso + * @param courtClass class code used by cso + * @param documentType type code used by cso + * @return All details related to request document type + */ + DocumentTypeDetails getDocumentTypeDetails(String courtLevel, String courtClass, String documentType); + + /** + * Search for are document types(with details) by parameters + * @param courtLevel level code used by cso + * @param courtClass class code used by cso + * @return list of document types + */ + List getDocumentTypes(String courtLevel, String courtClass); + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingLookupService.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingLookupService.java index e81a39b95c..9a170c4423 100644 --- a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingLookupService.java +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingLookupService.java @@ -1,12 +1,21 @@ package ca.bc.gov.open.jag.efilingcommons.service; - import ca.bc.gov.open.jag.efilingcommons.model.ServiceFees; +import ca.bc.gov.open.jag.efilingcommons.model.SubmissionFeeRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.LookupItem; -import javax.xml.datatype.DatatypeConfigurationException; +import java.util.List; public interface EfilingLookupService { - ServiceFees getServiceFee(String serviceId) throws DatatypeConfigurationException; + ServiceFees getServiceFee(SubmissionFeeRequest submissionFeeRequest); + + List getValidPartyRoles(String courtLevel, String courtClass, String documentTypes); + + /** + * Get countries code table lookup + * @return a list of country code/description + */ + List getCountries(); } diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingPaymentService.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingPaymentService.java new file mode 100644 index 0000000000..407de50b46 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingPaymentService.java @@ -0,0 +1,8 @@ +package ca.bc.gov.open.jag.efilingcommons.service; + +import ca.bc.gov.open.jag.efilingcommons.model.EfilingPayment; +import ca.bc.gov.open.jag.efilingcommons.model.PaymentTransaction; + +public interface EfilingPaymentService { + PaymentTransaction makePayment(EfilingPayment efilingPayment); +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingSearchService.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingSearchService.java new file mode 100644 index 0000000000..2466f2dec9 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingSearchService.java @@ -0,0 +1,5 @@ +package ca.bc.gov.open.jag.efilingcommons.service; + +public interface EfilingSearchService { + boolean caseNumberExists(String caseNumber); +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingSubmissionService.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingSubmissionService.java new file mode 100644 index 0000000000..10afc83751 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/service/EfilingSubmissionService.java @@ -0,0 +1,13 @@ +package ca.bc.gov.open.jag.efilingcommons.service; + +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.SubmitPackageResponse; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; + +public interface EfilingSubmissionService { + + SubmitPackageResponse submitFilingPackage( + AccountDetails accountDetails, + FilingPackage efilingPackage, + EfilingPaymentService payment); +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/EfilingReviewService.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/EfilingReviewService.java new file mode 100644 index 0000000000..b7d25f42ef --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/EfilingReviewService.java @@ -0,0 +1,32 @@ +package ca.bc.gov.open.jag.efilingcommons.submission; + +import ca.bc.gov.open.jag.efilingcommons.model.RushDocumentRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.DeleteSubmissionDocumentRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackageRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.ReportRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewFilingPackage; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Optional; + +public interface EfilingReviewService { + + Optional findStatusByPackage(FilingPackageRequest filingPackageRequest); + + List findStatusByClient(FilingPackageRequest filingPackageRequest); + + Optional getReport(ReportRequest reportRequest); + + Optional getSubmittedDocument(BigDecimal documentIdentifier); + + void deleteSubmittedDocument(DeleteSubmissionDocumentRequest deleteSubmissionDocumentRequest); + + /** + * Call cso to get the byte array + * @param rushDocumentRequest requested document identifiers + * @return optional byte array + */ + Optional getRushDocument(RushDocumentRequest rushDocumentRequest); + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/DeleteSubmissionDocumentRequest.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/DeleteSubmissionDocumentRequest.java new file mode 100644 index 0000000000..deb0c8331d --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/DeleteSubmissionDocumentRequest.java @@ -0,0 +1,16 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models; + +import java.math.BigDecimal; + +public class DeleteSubmissionDocumentRequest extends FilingPackageRequest { + private String documentId; + + public DeleteSubmissionDocumentRequest(BigDecimal clientId, BigDecimal packageNo, String parentApplication, String documentId) { + super(clientId, null, packageNo, parentApplication); + this.documentId = documentId; + } + + public String getDocumentId() { + return documentId; + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/FilingPackage.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/FilingPackage.java new file mode 100644 index 0000000000..79f01410d8 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/FilingPackage.java @@ -0,0 +1,206 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models; + +import ca.bc.gov.open.jag.efilingcommons.model.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +public class FilingPackage { + + private BigDecimal submissionFeeAmount; + private BigDecimal packageNumber; + private Court court; + private List documents = new ArrayList<>(); + private List parties = new ArrayList<>(); + private List organizations = new ArrayList<>(); + private RushProcessing rush; + private boolean rushedSubmission = false; + private boolean autoProcessing = false; + private String applicationCode; + + public FilingPackage( + @JsonProperty("submissionFeeAmount") BigDecimal submissionFeeAmount, + @JsonProperty("packageNumber") BigDecimal packageNumber, + @JsonProperty("court") Court court, + @JsonProperty("documents") List documents, + @JsonProperty("parties") List parties, + @JsonProperty("organizations") List organizations, + @JsonProperty("rush") RushProcessing rush, + @JsonProperty("rushedSubmission") boolean rushedSubmission, + @JsonProperty("autoProcessing") boolean autoProcessing, + @JsonProperty("applicationCode") String applicationCode + ) { + + this.submissionFeeAmount = submissionFeeAmount; + this.packageNumber = packageNumber; + this.court = court; + this.documents.addAll(documents); + this.parties.addAll(parties); + this.organizations.addAll(organizations); + this.rush = rush; + this.applicationCode = applicationCode; + this.rushedSubmission = rushedSubmission; + this.autoProcessing = autoProcessing; + } + + public FilingPackage(Builder builder) { + this.submissionFeeAmount = builder.submissionFeeAmount; + this.packageNumber = builder.packageNumber; + this.court = builder.court; + this.documents.addAll(builder.documents); + this.parties.addAll(builder.parties); + this.organizations.addAll(builder.organizations); + this.rush = builder.rush; + this.applicationCode = builder.applicationCode; + this.rushedSubmission = builder.rushedSubmission; + this.autoProcessing = builder.autoProcessing; + } + + public BigDecimal getSubmissionFeeAmount() { + return submissionFeeAmount; + } + + public BigDecimal getPackageNumber() { return packageNumber; } + + public Court getCourt() { + return court; + } + + public List getDocuments() { + return documents; + } + + public List getParties() { + return parties; + } + + public List getOrganizations() { return organizations; } + + public RushProcessing getRush() { return rush; } + + public boolean isRushedSubmission() { return rushedSubmission; } + + public boolean isAutoProcessing() { return autoProcessing; } + + //Created to support mapstruct which does not support standard boolean object naming + public boolean getAutoProcessing() { return autoProcessing; } + + public String getApplicationCode() { return applicationCode; } + + public void setSubmissionFeeAmount(BigDecimal submissionFeeAmount) { + this.submissionFeeAmount = submissionFeeAmount; + } + + public void setPackageNumber(BigDecimal packageNumber) { this.packageNumber = packageNumber; } + + public void setCourt(Court court) { + this.court = court; + } + + public void setDocuments(List documents) { + this.documents = documents; + } + + public void setParties(List parties) { + this.parties = parties; + } + + public void setOrganizations(List organizations) { + this.organizations = organizations; + } + + public void setIsAutoProcessing(boolean isAutoProcessing) { + this.autoProcessing = isAutoProcessing; + } + + public void setRushedSubmission(boolean rushedSubmission) { + this.rushedSubmission = rushedSubmission; + } + + public void setApplicationCode(String applicationCode) { + this.applicationCode = applicationCode; + } + + public void setRush(RushProcessing rush) { this.rush = rush; } + + public static Builder builder() { + return new Builder(); + } + + public void addDocument(Document document) { + if(this.documents == null) this.documents = new ArrayList<>(); + this.documents.add(document); + } + + public static class Builder { + + private BigDecimal submissionFeeAmount; + private BigDecimal packageNumber; + private Court court; + private List documents = new ArrayList<>(); + private List parties = new ArrayList<>(); + private List organizations = new ArrayList<>(); + private RushProcessing rush; + private String applicationCode; + private boolean rushedSubmission; + private boolean autoProcessing; + + public Builder rushedSubmission(boolean rushedSubmission) { + this.rushedSubmission = rushedSubmission; + return this; + } + + public Builder autoProcessing(boolean autoProcessing) { + this.autoProcessing = autoProcessing; + return this; + } + + public Builder applicationCode(String applicationCode) { + this.applicationCode = applicationCode; + return this; + } + + public Builder submissionFeeAmount(BigDecimal submissionFeeAmount) { + this.submissionFeeAmount = submissionFeeAmount; + return this; + } + + public Builder packageNumber(BigDecimal packageNumber) { + this.packageNumber = packageNumber; + return this; + } + + public Builder court(Court court) { + this.court = court; + return this; + } + + public Builder rush(RushProcessing rush) { + this.rush = rush; + return this; + } + + public Builder documents(List documents) { + this.documents = documents; + return this; + } + + public Builder parties(List parties) { + this.parties = parties; + return this; + } + + public Builder organizations(List organizations) { + this.organizations = organizations; + return this; + } + + public FilingPackage create() { + return new FilingPackage(this); + } + } +} + + diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/FilingPackageRequest.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/FilingPackageRequest.java new file mode 100644 index 0000000000..39a7007c82 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/FilingPackageRequest.java @@ -0,0 +1,33 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models; + +import java.math.BigDecimal; + +public class FilingPackageRequest { + + private BigDecimal clientId; + private BigDecimal accountId; + private BigDecimal packageNo; + private String parentApplication; + + public FilingPackageRequest(BigDecimal clientId, BigDecimal accountId, BigDecimal packageNo, String parentApplication) { + this.clientId = clientId; + this.accountId = accountId; + this.packageNo = packageNo; + this.parentApplication = parentApplication; + } + + public BigDecimal getClientId() { + return clientId; + } + + public BigDecimal getPackageNo() { + return packageNo; + } + + public String getParentApplication() { return parentApplication; } + + public BigDecimal getAccountId() { + return accountId; + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/LookupItem.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/LookupItem.java new file mode 100644 index 0000000000..61730877f9 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/LookupItem.java @@ -0,0 +1,46 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models; + +public class LookupItem { + private String code; + private String description; + + + public String getCode() { return code; } + + public String getDescription() { return description; } + + protected LookupItem(LookupItem.Builder builder) { + + this.code = builder.code; + this.description = builder.description; + + } + + public static LookupItem.Builder builder() { + + return new LookupItem.Builder(); + + } + + public static class Builder { + + private String code; + private String description; + + public LookupItem.Builder code(String code) { + this.code = code; + return this; + } + + public LookupItem.Builder description(String description) { + this.description = description; + return this; + } + + public LookupItem create() { + return new LookupItem(this); + } + + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/ReportRequest.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/ReportRequest.java new file mode 100644 index 0000000000..a9704f77f5 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/ReportRequest.java @@ -0,0 +1,68 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models; + +import java.math.BigDecimal; + +public class ReportRequest { + + ReportsTypes report; + BigDecimal packageId; + String fileName; + String universalId; + + public ReportsTypes getReport() { return report; } + + public BigDecimal getPackageId() { return packageId; } + + public String getFileName() { return fileName; } + + public String getUniversalId() { return universalId; } + + public void setUniversalId(String universalId) { this.universalId = universalId; } + + protected ReportRequest(ReportRequest.Builder builder) { + + this.report = builder.report; + this.packageId = builder.packageId; + this.fileName = builder.fileName; + this.universalId = builder.universalId; + + } + + public static ReportRequest.Builder builder() { + + return new ReportRequest.Builder(); + } + + public static class Builder { + + private ReportsTypes report; + private BigDecimal packageId; + private String fileName; + private String universalId; + + public ReportRequest.Builder report(ReportsTypes report) { + this.report = report; + return this; + } + + public ReportRequest.Builder packageId(BigDecimal packageId) { + this.packageId = packageId; + return this; + } + + public ReportRequest.Builder fileName(String fileName) { + this.fileName = fileName; + return this; + } + + public ReportRequest.Builder universalId(String universalId) { + this.universalId = universalId; + return this; + } + + public ReportRequest create() { + return new ReportRequest(this); + } + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/ReportsTypes.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/ReportsTypes.java new file mode 100644 index 0000000000..1f914647df --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/ReportsTypes.java @@ -0,0 +1,7 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models; + +public enum ReportsTypes { + SUBMISSION_SHEET, + PAYMENT_RECEIPT, + REGISTRY_NOTICE +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/PackageLinks.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/PackageLinks.java new file mode 100644 index 0000000000..5d1e432034 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/PackageLinks.java @@ -0,0 +1,38 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models.review; + +public class PackageLinks { + + private String packageHistoryUrl; + + public String getPackageHistoryUrl() { + return packageHistoryUrl; + } + + public PackageLinks(String packageHistoryUrl) { + this.packageHistoryUrl = packageHistoryUrl; + } + + public PackageLinks(Builder builder) { + this.packageHistoryUrl = builder.packageHistoryUrl; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private String packageHistoryUrl; + + public Builder packageHistoryUrl(String packageHistoryUrl) { + this.packageHistoryUrl = packageHistoryUrl; + return this; + } + + public PackageLinks create() { + return new PackageLinks(this); + } + + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/PackagePayment.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/PackagePayment.java new file mode 100644 index 0000000000..bd7dc00f59 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/PackagePayment.java @@ -0,0 +1,75 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models.review; + +import org.joda.time.DateTime; + +import java.math.BigDecimal; + +public class PackagePayment { + private Boolean feeExmpt; + private BigDecimal paymentCategory; + private BigDecimal processedAmt; + private BigDecimal serviceId; + private BigDecimal submittedAmt; + private String transactionDesc; + private DateTime transactionDtm; + + public PackagePayment() { + + } + + public Boolean getFeeExmpt() { + return feeExmpt; + } + + public void setFeeExmpt(Boolean feeExmpt) { + this.feeExmpt = feeExmpt; + } + + public BigDecimal getPaymentCategory() { + return paymentCategory; + } + + public void setPaymentCategory(BigDecimal paymentCategory) { + this.paymentCategory = paymentCategory; + } + + public BigDecimal getProcessedAmt() { + return processedAmt; + } + + public void setProcessedAmt(BigDecimal processedAmt) { + this.processedAmt = processedAmt; + } + + public BigDecimal getServiceId() { + return serviceId; + } + + public void setServiceId(BigDecimal serviceId) { + this.serviceId = serviceId; + } + + public BigDecimal getSubmittedAmt() { + return submittedAmt; + } + + public void setSubmittedAmt(BigDecimal submittedAmt) { + this.submittedAmt = submittedAmt; + } + + public String getTransactionDesc() { + return transactionDesc; + } + + public void setTransactionDesc(String transactionDesc) { + this.transactionDesc = transactionDesc; + } + + public DateTime getTransactionDtm() { + return transactionDtm; + } + + public void setTransactionDtm(DateTime transactionDtm) { + this.transactionDtm = transactionDtm; + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewCourt.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewCourt.java new file mode 100644 index 0000000000..3ac44b8d71 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewCourt.java @@ -0,0 +1,118 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models.review; + +import java.math.BigDecimal; + +public class ReviewCourt { + private String locationDescription; + private String locationCd; + private String locationName; + private String level; + private String levelDescription; + private String courtClass; + private String classDescription; + private String division; + private String fileNumber; + private String participatingClass; + private BigDecimal locationId; + private Boolean existingFileYN; + + public ReviewCourt() { + + } + + public String getLocationDescription() { + return locationDescription; + } + + public void setLocationDescription(String locationDescription) { + this.locationDescription = locationDescription; + } + + public String getLocationName() { + return locationName; + } + + public void setLocationName(String locationName) { + this.locationName = locationName; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public String getLevelDescription() { + return levelDescription; + } + + public void setLevelDescription(String levelDescription) { + this.levelDescription = levelDescription; + } + + public String getCourtClass() { + return courtClass; + } + + public void setCourtClass(String courtClass) { + this.courtClass = courtClass; + } + + public String getClassDescription() { + return classDescription; + } + + public void setClassDescription(String classDescription) { + this.classDescription = classDescription; + } + + public String getDivision() { + return division; + } + + public void setDivision(String division) { + this.division = division; + } + + public String getFileNumber() { + return fileNumber; + } + + public void setFileNumber(String fileNumber) { + this.fileNumber = fileNumber; + } + + public String getParticipatingClass() { + return participatingClass; + } + + public void setParticipatingClass(String participatingClass) { + this.participatingClass = participatingClass; + } + + public BigDecimal getLocationId() { + return locationId; + } + + public void setLocationId(BigDecimal locationId) { + this.locationId = locationId; + } + + public Boolean getExistingFileYN() { + return existingFileYN; + } + + public void setExistingFileYN(Boolean existingFileYN) { + this.existingFileYN = existingFileYN; + } + + public String getLocationCd() { + return locationCd; + } + + public void setLocationCd(String locationCd) { + this.locationCd = locationCd; + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewDocument.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewDocument.java new file mode 100644 index 0000000000..f38073d7a1 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewDocument.java @@ -0,0 +1,178 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models.review; + +import org.joda.time.DateTime; + +public class ReviewDocument { + private DateTime dateFiled; + private DateTime dateWithdrawn; + private String documentId; + private String parentDocumentId; + private String documentType; + private String documentTypeCd; + private String documentUploadStatusCd; + private String fileName; + private Boolean initiatingDoc; + private String largeFileYn; + private String packageId; + private String packageSeqNo; + private Boolean paymentProcessed; + private String status; + private String statusCode; + private DateTime statusDate; + private Boolean trialDivision; + private Boolean xmlDoc; + private Boolean rushRequired; + + public ReviewDocument() { + + } + + public String getDocumentType() { + return documentType; + } + + public void setDocumentType(String documentType) { + this.documentType = documentType; + } + + public String getDocumentTypeCd() { + return documentTypeCd; + } + + public void setDocumentTypeCd(String documentTypeCd) { + this.documentTypeCd = documentTypeCd; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public DateTime getDateFiled() { + return dateFiled; + } + + public void setDateFiled(DateTime dateFiled) { + this.dateFiled = dateFiled; + } + + public DateTime getDateWithdrawn() { + return dateWithdrawn; + } + + public void setDateWithdrawn(DateTime dateWithdrawn) { + this.dateWithdrawn = dateWithdrawn; + } + + public String getDocumentId() { + return documentId; + } + + public void setDocumentId(String documentId) { + this.documentId = documentId; + } + + public String getDocumentUploadStatusCd() { + return documentUploadStatusCd; + } + + public void setDocumentUploadStatusCd(String documentUploadStatusCd) { + this.documentUploadStatusCd = documentUploadStatusCd; + } + + public Boolean getInitiatingDoc() { + return initiatingDoc; + } + + public void setInitiatingDoc(Boolean initiatingDoc) { + this.initiatingDoc = initiatingDoc; + } + + public String getLargeFileYn() { + return largeFileYn; + } + + public void setLargeFileYn(String largeFileYn) { + this.largeFileYn = largeFileYn; + } + + public String getPackageId() { + return packageId; + } + + public void setPackageId(String packageId) { + this.packageId = packageId; + } + + public String getPackageSeqNo() { + return packageSeqNo; + } + + public void setPackageSeqNo(String packageSeqNo) { + this.packageSeqNo = packageSeqNo; + } + + public Boolean getPaymentProcessed() { + return paymentProcessed; + } + + public void setPaymentProcessed(Boolean paymentProcessed) { + this.paymentProcessed = paymentProcessed; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getStatusCode() { + return statusCode; + } + + public void setStatusCode(String statusCode) { + this.statusCode = statusCode; + } + + public DateTime getStatusDate() { + return statusDate; + } + + public void setStatusDate(DateTime statusDate) { + this.statusDate = statusDate; + } + + public Boolean getTrialDivision() { + return trialDivision; + } + + public void setTrialDivision(Boolean trialDivision) { + this.trialDivision = trialDivision; + } + + public Boolean getXmlDoc() { + return xmlDoc; + } + + public void setXmlDoc(Boolean xmlDoc) { + this.xmlDoc = xmlDoc; + } + + public Boolean getRushRequired() { return rushRequired; } + + public void setRushRequired(Boolean rushRequired) { this.rushRequired = rushRequired; } + + public String getParentDocumentId() { + return parentDocumentId; + } + + public void setParentDocumentId(String parentDocumentId) { + this.parentDocumentId = parentDocumentId; + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewFilingPackage.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewFilingPackage.java new file mode 100644 index 0000000000..f56267702a --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewFilingPackage.java @@ -0,0 +1,192 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models.review; + +import ca.bc.gov.open.jag.efilingcommons.model.Individual; +import ca.bc.gov.open.jag.efilingcommons.model.Organization; +import org.joda.time.DateTime; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +public class ReviewFilingPackage { + + private String clientFileNo; + private String status; + private BigDecimal submissionFeeAmount; + private ReviewCourt court; + private List documents = new ArrayList<>(); + private List parties = new ArrayList<>(); + private List organizations = new ArrayList<>(); + private boolean rushedSubmission = false; + private String applicationCode; + private Boolean existingCourtFileYN; + private String filingCommentsTxt; + private String firstName; + private Boolean hasChecklist; + private Boolean hasRegistryNotice; + private String lastName; + private String packageNo; + private List packageRequests; + private List payments; + private ReviewRushOrder rushOrder; + private DateTime submittedDate; + private PackageLinks packageLinks; + + public ReviewFilingPackage() { } + + public BigDecimal getSubmissionFeeAmount() { + return submissionFeeAmount; + } + + public ReviewCourt getCourt() { + return court; + } + + public List getDocuments() { + return documents; + } + + public List getParties() { + return parties; + } + + public boolean isRushedSubmission() { + return rushedSubmission; + } + + public String getApplicationCode() { + return applicationCode; + } + + public String getClientFileNo() { + return clientFileNo; + } + + public Boolean getExistingCourtFileYN() { + return existingCourtFileYN; + } + + public String getFilingCommentsTxt() { + return filingCommentsTxt; + } + + public String getFirstName() { + return firstName; + } + + public Boolean getHasChecklist() { + return hasChecklist; + } + + public Boolean getHasRegistryNotice() { + return hasRegistryNotice; + } + + public String getLastName() { + return lastName; + } + + public String getPackageNo() { + return packageNo; + } + + public List getPackageRequests() { + return packageRequests; + } + + public List getPayments() { + return payments; + } + + public DateTime getSubmittedDate() { + return submittedDate; + } + + public void setClientFileNo(String clientFileNo) { + this.clientFileNo = clientFileNo; + } + + public void setSubmissionFeeAmount(BigDecimal submissionFeeAmount) { + this.submissionFeeAmount = submissionFeeAmount; + } + + public void setCourt(ReviewCourt court) { + this.court = court; + } + + public void setDocuments(List documents) { + this.documents = documents; + } + + public void setParties(List parties) { + this.parties = parties; + } + + public void setRushedSubmission(boolean rushedSubmission) { + this.rushedSubmission = rushedSubmission; + } + + public void setApplicationCode(String applicationCode) { + this.applicationCode = applicationCode; + } + + public void setExistingCourtFileYN(Boolean existingCourtFileYN) { + this.existingCourtFileYN = existingCourtFileYN; + } + + public void setFilingCommentsTxt(String filingCommentsTxt) { + this.filingCommentsTxt = filingCommentsTxt; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public void setHasChecklist(Boolean hasChecklist) { + this.hasChecklist = hasChecklist; + } + + public void setHasRegistryNotice(Boolean hasRegistryNotice) { + this.hasRegistryNotice = hasRegistryNotice; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public void setPackageNo(String packageNo) { + this.packageNo = packageNo; + } + + public void setPackageRequests(List packageRequests) { + this.packageRequests = packageRequests; + } + + public void setPayments(List payments) { + this.payments = payments; + } + + public void setSubmittedDate(DateTime submittedDate) { + this.submittedDate = submittedDate; + } + + public PackageLinks getPackageLinks() { + return packageLinks; + } + + public void setPackageLinks(PackageLinks packageLinks) { + this.packageLinks = packageLinks; + } + + public List getOrganizations() { return organizations; } + + public void setOrganizations(List organizations) { this.organizations = organizations; } + + public ReviewRushOrder getRushOrder() { return rushOrder; } + + public void setRushOrder(ReviewRushOrder rushOrder) { this.rushOrder = rushOrder; } + + public String getStatus() { return status; } + + public void setStatus(String status) { this.status = status; } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewPackageRequest.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewPackageRequest.java new file mode 100644 index 0000000000..bb99c4ff86 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewPackageRequest.java @@ -0,0 +1,187 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models.review; + +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.access.Period; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.access.Status; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.party.Authorizing; +import org.joda.time.DateTime; + +import java.math.BigDecimal; +import java.util.List; + +public class ReviewPackageRequest { + private String accessEntitlementCd; + private DateTime accessRequestDt; + private BigDecimal accessRequestId; + private String accessStatusTypeDesc; + private String accrTypeCd; + private BigDecimal ceisPhysicalFileId; + private BigDecimal createdForAccountId; + private BigDecimal createdForClientId; + private DateTime entDtm; + private String entUserId; + private BigDecimal justinPhysId; + private BigDecimal packageId; + private BigDecimal requestedByAccountId; + private BigDecimal requestedByClientId; + private DateTime updDtm; + private String updUserId; + private Status accessStatus; + private Period accessPeriod; + private List authorizingParties; + + public ReviewPackageRequest() { + + } + + public String getAccessEntitlementCd() { + return accessEntitlementCd; + } + + public void setAccessEntitlementCd(String accessEntitlementCd) { + this.accessEntitlementCd = accessEntitlementCd; + } + + public DateTime getAccessRequestDt() { + return accessRequestDt; + } + + public void setAccessRequestDt(DateTime accessRequestDt) { + this.accessRequestDt = accessRequestDt; + } + + public BigDecimal getAccessRequestId() { + return accessRequestId; + } + + public void setAccessRequestId(BigDecimal accessRequestId) { + this.accessRequestId = accessRequestId; + } + + public String getAccessStatusTypeDesc() { + return accessStatusTypeDesc; + } + + public void setAccessStatusTypeDesc(String accessStatusTypeDesc) { + this.accessStatusTypeDesc = accessStatusTypeDesc; + } + + public String getAccrTypeCd() { + return accrTypeCd; + } + + public void setAccrTypeCd(String accrTypeCd) { + this.accrTypeCd = accrTypeCd; + } + + public BigDecimal getCeisPhysicalFileId() { + return ceisPhysicalFileId; + } + + public void setCeisPhysicalFileId(BigDecimal ceisPhysicalFileId) { + this.ceisPhysicalFileId = ceisPhysicalFileId; + } + + public BigDecimal getCreatedForAccountId() { + return createdForAccountId; + } + + public void setCreatedForAccountId(BigDecimal createdForAccountId) { + this.createdForAccountId = createdForAccountId; + } + + public BigDecimal getCreatedForClientId() { + return createdForClientId; + } + + public void setCreatedForClientId(BigDecimal createdForClientId) { + this.createdForClientId = createdForClientId; + } + + public DateTime getEntDtm() { + return entDtm; + } + + public void setEntDtm(DateTime entDtm) { + this.entDtm = entDtm; + } + + public String getEntUserId() { + return entUserId; + } + + public void setEntUserId(String entUserId) { + this.entUserId = entUserId; + } + + public BigDecimal getJustinPhysId() { + return justinPhysId; + } + + public void setJustinPhysId(BigDecimal justinPhysId) { + this.justinPhysId = justinPhysId; + } + + public BigDecimal getPackageId() { + return packageId; + } + + public void setPackageId(BigDecimal packageId) { + this.packageId = packageId; + } + + public BigDecimal getRequestedByAccountId() { + return requestedByAccountId; + } + + public void setRequestedByAccountId(BigDecimal requestedByAccountId) { + this.requestedByAccountId = requestedByAccountId; + } + + public BigDecimal getRequestedByClientId() { + return requestedByClientId; + } + + public void setRequestedByClientId(BigDecimal requestedByClientId) { + this.requestedByClientId = requestedByClientId; + } + + public DateTime getUpdDtm() { + return updDtm; + } + + public void setUpdDtm(DateTime updDtm) { + this.updDtm = updDtm; + } + + public String getUpdUserId() { + return updUserId; + } + + public void setUpdUserId(String updUserId) { + this.updUserId = updUserId; + } + + public Status getAccessStatus() { + return accessStatus; + } + + public void setAccessStatus(Status accessStatus) { + this.accessStatus = accessStatus; + } + + public Period getAccessPeriod() { + return accessPeriod; + } + + public void setAccessPeriod(Period accessPeriod) { + this.accessPeriod = accessPeriod; + } + + public List getAuthorizingParties() { + return authorizingParties; + } + + public void setAuthorizingParties(List authorizingParties) { + this.authorizingParties = authorizingParties; + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewProcessRequest.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewProcessRequest.java new file mode 100644 index 0000000000..72812f9ce8 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewProcessRequest.java @@ -0,0 +1,163 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models.review; + +import org.joda.time.DateTime; + +import java.math.BigDecimal; + +public class ReviewProcessRequest { + private DateTime clientNotificationSentDtm; + private String contactEmailTxt; + private String contactFirstGivenNm; + private String contactOrganizationNm; + private String contactPhoneNo; + private String contactSurnameNm; + private String countryCallingNo; + private BigDecimal ctryId; + private DateTime entDtm; + private String entUserId; + private DateTime processNotificationSentDtm; + private BigDecimal processRequestId; + private String processTypeCd; + private String processingCommentTxt; + private DateTime requestDt; + private DateTime updDtm; + private String updUserId; + + public ReviewProcessRequest() {} + + public DateTime getClientNotificationSentDtm() { + return clientNotificationSentDtm; + } + + public void setClientNotificationSentDtm(DateTime clientNotificationSentDtm) { + this.clientNotificationSentDtm = clientNotificationSentDtm; + } + + public String getContactEmailTxt() { + return contactEmailTxt; + } + + public void setContactEmailTxt(String contactEmailTxt) { + this.contactEmailTxt = contactEmailTxt; + } + + public String getContactFirstGivenNm() { + return contactFirstGivenNm; + } + + public void setContactFirstGivenNm(String contactFirstGivenNm) { + this.contactFirstGivenNm = contactFirstGivenNm; + } + + public String getContactOrganizationNm() { + return contactOrganizationNm; + } + + public void setContactOrganizationNm(String contactOrganizationNm) { + this.contactOrganizationNm = contactOrganizationNm; + } + + public String getContactPhoneNo() { + return contactPhoneNo; + } + + public void setContactPhoneNo(String contactPhoneNo) { + this.contactPhoneNo = contactPhoneNo; + } + + public String getContactSurnameNm() { + return contactSurnameNm; + } + + public void setContactSurnameNm(String contactSurnameNm) { + this.contactSurnameNm = contactSurnameNm; + } + + public String getCountryCallingNo() { + return countryCallingNo; + } + + public void setCountryCallingNo(String countryCallingNo) { + this.countryCallingNo = countryCallingNo; + } + + public BigDecimal getCtryId() { + return ctryId; + } + + public void setCtryId(BigDecimal ctryId) { + this.ctryId = ctryId; + } + + public DateTime getEntDtm() { + return entDtm; + } + + public void setEntDtm(DateTime entDtm) { + this.entDtm = entDtm; + } + + public String getEntUserId() { + return entUserId; + } + + public void setEntUserId(String entUserId) { + this.entUserId = entUserId; + } + + public DateTime getProcessNotificationSentDtm() { + return processNotificationSentDtm; + } + + public void setProcessNotificationSentDtm(DateTime processNotificationSentDtm) { + this.processNotificationSentDtm = processNotificationSentDtm; + } + + public BigDecimal getProcessRequestId() { + return processRequestId; + } + + public void setProcessRequestId(BigDecimal processRequestId) { + this.processRequestId = processRequestId; + } + + public String getProcessTypeCd() { + return processTypeCd; + } + + public void setProcessTypeCd(String processTypeCd) { + this.processTypeCd = processTypeCd; + } + + public String getProcessingCommentTxt() { + return processingCommentTxt; + } + + public void setProcessingCommentTxt(String processingCommentTxt) { + this.processingCommentTxt = processingCommentTxt; + } + + public DateTime getRequestDt() { + return requestDt; + } + + public void setRequestDt(DateTime requestDt) { + this.requestDt = requestDt; + } + + public DateTime getUpdDtm() { + return updDtm; + } + + public void setUpdDtm(DateTime updDtm) { + this.updDtm = updDtm; + } + + public String getUpdUserId() { + return updUserId; + } + + public void setUpdUserId(String updUserId) { + this.updUserId = updUserId; + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewRushOrder.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewRushOrder.java new file mode 100644 index 0000000000..9045befa97 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/ReviewRushOrder.java @@ -0,0 +1,97 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models.review; + +import org.joda.time.DateTime; + +import java.math.BigDecimal; +import java.util.List; + +public class ReviewRushOrder { + protected DateTime courtOrderDt; + protected BigDecimal packageId; + protected String rushFilingReasonTxt; + protected String contactEmailTxt; + protected String contactFirstGivenNm; + protected String contactOrganizationNm; + protected String contactPhoneNo; + protected String contactSurnameNm; + protected BigDecimal ctryId; + protected String countryDsc; + protected String currentStatusDsc; + protected String processReasonCd; + protected String processingCommentTxt; + protected List supportDocs; + + public ReviewRushOrder() {} + + public DateTime getCourtOrderDt() { + return courtOrderDt; + } + + public void setCourtOrderDt(DateTime courtOrderDt) { + this.courtOrderDt = courtOrderDt; + } + + public BigDecimal getPackageId() { + return packageId; + } + + public void setPackageId(BigDecimal packageId) { + this.packageId = packageId; + } + + public String getRushFilingReasonTxt() { + return rushFilingReasonTxt; + } + + public void setRushFilingReasonTxt(String rushFilingReasonTxt) { + this.rushFilingReasonTxt = rushFilingReasonTxt; + } + + public String getContactEmailTxt() { return contactEmailTxt; } + + public void setContactEmailTxt(String contactEmailTxt) { this.contactEmailTxt = contactEmailTxt; } + + public String getContactFirstGivenNm() { return contactFirstGivenNm; } + + public void setContactFirstGivenNm(String contactFirstGivenNm) { this.contactFirstGivenNm = contactFirstGivenNm; } + + public String getContactOrganizationNm() { return contactOrganizationNm; } + + public void setContactOrganizationNm(String contactOrganizationNm) { this.contactOrganizationNm = contactOrganizationNm; } + + public String getContactPhoneNo() { return contactPhoneNo; } + + public void setContactPhoneNo(String contactPhoneNo) { this.contactPhoneNo = contactPhoneNo; } + + public String getContactSurnameNm() { return contactSurnameNm; } + + public void setContactSurnameNm(String contactSurnameNm) { this.contactSurnameNm = contactSurnameNm; } + + public BigDecimal getCtryId() { return ctryId; } + + public void setCtryId(BigDecimal ctryId) { this.ctryId = ctryId; } + + public String getCountryDsc() { return countryDsc; } + + public void setCountryDsc(String countryDsc) { this.countryDsc = countryDsc; } + + public String getCurrentStatusDsc() { return currentStatusDsc; } + + public void setCurrentStatusDsc(String currentStatusDsc) { this.currentStatusDsc = currentStatusDsc; } + + public String getProcessReasonCd() { return processReasonCd; } + + public void setProcessReasonCd(String processReasonCd) { this.processReasonCd = processReasonCd; } + + public String getProcessingCommentTxt() { return processingCommentTxt; } + + public void setProcessingCommentTxt(String processingCommentTxt) { this.processingCommentTxt = processingCommentTxt; } + + public List getSupportDocs() { + return supportDocs; + } + + public void setSupportDocs(List supportDocs) { + this.supportDocs = supportDocs; + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/RushDocument.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/RushDocument.java new file mode 100644 index 0000000000..aeeeff1d6e --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/RushDocument.java @@ -0,0 +1,109 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models.review; + +import org.joda.time.DateTime; + +import java.math.BigDecimal; + +public class RushDocument { + protected String clientFileNm; + protected DateTime entDtm; + protected String entUserId; + protected String fileServer; + protected String objectGuid; + protected BigDecimal processItemSeqNo; + protected BigDecimal processRequestId; + protected BigDecimal processSupportDocSeqNo; + protected String tempFileName; + protected DateTime updDtm; + protected String updUserId; + + public RushDocument() {} + + public String getClientFileNm() { + return clientFileNm; + } + + public void setClientFileNm(String clientFileNm) { + this.clientFileNm = clientFileNm; + } + + public DateTime getEntDtm() { + return entDtm; + } + + public void setEntDtm(DateTime entDtm) { + this.entDtm = entDtm; + } + + public String getEntUserId() { + return entUserId; + } + + public void setEntUserId(String entUserId) { + this.entUserId = entUserId; + } + + public String getFileServer() { + return fileServer; + } + + public void setFileServer(String fileServer) { + this.fileServer = fileServer; + } + + public String getObjectGuid() { + return objectGuid; + } + + public void setObjectGuid(String objectGuid) { + this.objectGuid = objectGuid; + } + + public BigDecimal getProcessItemSeqNo() { + return processItemSeqNo; + } + + public void setProcessItemSeqNo(BigDecimal processItemSeqNo) { + this.processItemSeqNo = processItemSeqNo; + } + + public BigDecimal getProcessRequestId() { + return processRequestId; + } + + public void setProcessRequestId(BigDecimal processRequestId) { + this.processRequestId = processRequestId; + } + + public BigDecimal getProcessSupportDocSeqNo() { + return processSupportDocSeqNo; + } + + public void setProcessSupportDocSeqNo(BigDecimal processSupportDocSeqNo) { + this.processSupportDocSeqNo = processSupportDocSeqNo; + } + + public String getTempFileName() { + return tempFileName; + } + + public void setTempFileName(String tempFileName) { + this.tempFileName = tempFileName; + } + + public DateTime getUpdDtm() { + return updDtm; + } + + public void setUpdDtm(DateTime updDtm) { + this.updDtm = updDtm; + } + + public String getUpdUserId() { + return updUserId; + } + + public void setUpdUserId(String updUserId) { + this.updUserId = updUserId; + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/access/Period.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/access/Period.java new file mode 100644 index 0000000000..bdbdecfdb8 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/access/Period.java @@ -0,0 +1,102 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models.review.access; + +import org.joda.time.DateTime; + +import java.math.BigDecimal; + +public class Period { + private BigDecimal accessPeriodSeqNo; + private BigDecimal accessRequestId; + private DateTime corAcknowledgeDt; + private DateTime endDt; + private DateTime entDtm; + private String entUserId; + private Boolean expiryNotificationSentYn; + private DateTime startDt; + private DateTime updDtm; + private String updUserId; + + public Period() { + + } + + public BigDecimal getAccessPeriodSeqNo() { + return accessPeriodSeqNo; + } + + public void setAccessPeriodSeqNo(BigDecimal accessPeriodSeqNo) { + this.accessPeriodSeqNo = accessPeriodSeqNo; + } + + public BigDecimal getAccessRequestId() { + return accessRequestId; + } + + public void setAccessRequestId(BigDecimal accessRequestId) { + this.accessRequestId = accessRequestId; + } + + public DateTime getCorAcknowledgeDt() { + return corAcknowledgeDt; + } + + public void setCorAcknowledgeDt(DateTime corAcknowledgeDt) { + this.corAcknowledgeDt = corAcknowledgeDt; + } + + public DateTime getEndDt() { + return endDt; + } + + public void setEndDt(DateTime endDt) { + this.endDt = endDt; + } + + public DateTime getEntDtm() { + return entDtm; + } + + public void setEntDtm(DateTime entDtm) { + this.entDtm = entDtm; + } + + public String getEntUserId() { + return entUserId; + } + + public void setEntUserId(String entUserId) { + this.entUserId = entUserId; + } + + public Boolean getExpiryNotificationSentYn() { + return expiryNotificationSentYn; + } + + public void setExpiryNotificationSentYn(Boolean expiryNotificationSentYn) { + this.expiryNotificationSentYn = expiryNotificationSentYn; + } + + public DateTime getStartDt() { + return startDt; + } + + public void setStartDt(DateTime startDt) { + this.startDt = startDt; + } + + public DateTime getUpdDtm() { + return updDtm; + } + + public void setUpdDtm(DateTime updDtm) { + this.updDtm = updDtm; + } + + public String getUpdUserId() { + return updUserId; + } + + public void setUpdUserId(String updUserId) { + this.updUserId = updUserId; + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/access/Status.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/access/Status.java new file mode 100644 index 0000000000..3f328ad688 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/access/Status.java @@ -0,0 +1,138 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models.review.access; + +import org.joda.time.DateTime; + +import java.math.BigDecimal; + +public class Status { + private BigDecimal accessRequestId; + private BigDecimal accessStatusSeqNo; + private String accessStatusTypeCd; + private BigDecimal accountId; + private BigDecimal agenId; + private BigDecimal clientId; + private String commentTxt; + private DateTime entDtm; + private String entUserId; + private BigDecimal paasSeqNo; + private BigDecimal partId; + private DateTime statusDtm; + private DateTime updDtm; + private String updUserId; + + public Status() { + + } + + public BigDecimal getAccessRequestId() { + return accessRequestId; + } + + public void setAccessRequestId(BigDecimal accessRequestId) { + this.accessRequestId = accessRequestId; + } + + public BigDecimal getAccessStatusSeqNo() { + return accessStatusSeqNo; + } + + public void setAccessStatusSeqNo(BigDecimal accessStatusSeqNo) { + this.accessStatusSeqNo = accessStatusSeqNo; + } + + public String getAccessStatusTypeCd() { + return accessStatusTypeCd; + } + + public void setAccessStatusTypeCd(String accessStatusTypeCd) { + this.accessStatusTypeCd = accessStatusTypeCd; + } + + public BigDecimal getAccountId() { + return accountId; + } + + public void setAccountId(BigDecimal accountId) { + this.accountId = accountId; + } + + public BigDecimal getAgenId() { + return agenId; + } + + public void setAgenId(BigDecimal agenId) { + this.agenId = agenId; + } + + public BigDecimal getClientId() { + return clientId; + } + + public void setClientId(BigDecimal clientId) { + this.clientId = clientId; + } + + public String getCommentTxt() { + return commentTxt; + } + + public void setCommentTxt(String commentTxt) { + this.commentTxt = commentTxt; + } + + public DateTime getEntDtm() { + return entDtm; + } + + public void setEntDtm(DateTime entDtm) { + this.entDtm = entDtm; + } + + public String getEntUserId() { + return entUserId; + } + + public void setEntUserId(String entUserId) { + this.entUserId = entUserId; + } + + public BigDecimal getPaasSeqNo() { + return paasSeqNo; + } + + public void setPaasSeqNo(BigDecimal paasSeqNo) { + this.paasSeqNo = paasSeqNo; + } + + public BigDecimal getPartId() { + return partId; + } + + public void setPartId(BigDecimal partId) { + this.partId = partId; + } + + public DateTime getStatusDtm() { + return statusDtm; + } + + public void setStatusDtm(DateTime statusDtm) { + this.statusDtm = statusDtm; + } + + public DateTime getUpdDtm() { + return updDtm; + } + + public void setUpdDtm(DateTime updDtm) { + this.updDtm = updDtm; + } + + public String getUpdUserId() { + return updUserId; + } + + public void setUpdUserId(String updUserId) { + this.updUserId = updUserId; + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/party/Authorizing.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/party/Authorizing.java new file mode 100644 index 0000000000..7074aaa47b --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/submission/models/review/party/Authorizing.java @@ -0,0 +1,120 @@ +package ca.bc.gov.open.jag.efilingcommons.submission.models.review.party; + +import org.joda.time.DateTime; + +import java.math.BigDecimal; + +public class Authorizing { + private BigDecimal accessRequestId; + private BigDecimal authorizingPartySeqNo; + private BigDecimal ceisPartyId; + private BigDecimal ceisPhysicalFileId; + private String ceisRoleTypeCd; + private String displayName; + private DateTime entDtm; + private String entUserId; + private BigDecimal partyId; + private String roleDesc; + private DateTime updDtm; + private String updUserId; + + public Authorizing() { + + } + + public BigDecimal getAccessRequestId() { + return accessRequestId; + } + + public void setAccessRequestId(BigDecimal accessRequestId) { + this.accessRequestId = accessRequestId; + } + + public BigDecimal getAuthorizingPartySeqNo() { + return authorizingPartySeqNo; + } + + public void setAuthorizingPartySeqNo(BigDecimal authorizingPartySeqNo) { + this.authorizingPartySeqNo = authorizingPartySeqNo; + } + + public BigDecimal getCeisPartyId() { + return ceisPartyId; + } + + public void setCeisPartyId(BigDecimal ceisPartyId) { + this.ceisPartyId = ceisPartyId; + } + + public BigDecimal getCeisPhysicalFileId() { + return ceisPhysicalFileId; + } + + public void setCeisPhysicalFileId(BigDecimal ceisPhysicalFileId) { + this.ceisPhysicalFileId = ceisPhysicalFileId; + } + + public String getCeisRoleTypeCd() { + return ceisRoleTypeCd; + } + + public void setCeisRoleTypeCd(String ceisRoleTypeCd) { + this.ceisRoleTypeCd = ceisRoleTypeCd; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public DateTime getEntDtm() { + return entDtm; + } + + public void setEntDtm(DateTime entDtm) { + this.entDtm = entDtm; + } + + public String getEntUserId() { + return entUserId; + } + + public void setEntUserId(String entUserId) { + this.entUserId = entUserId; + } + + public BigDecimal getPartyId() { + return partyId; + } + + public void setPartyId(BigDecimal partyId) { + this.partyId = partyId; + } + + public String getRoleDesc() { + return roleDesc; + } + + public void setRoleDesc(String roleDesc) { + this.roleDesc = roleDesc; + } + + public DateTime getUpdDtm() { + return updDtm; + } + + public void setUpdDtm(DateTime updDtm) { + this.updDtm = updDtm; + } + + public String getUpdUserId() { + return updUserId; + } + + public void setUpdUserId(String updUserId) { + this.updUserId = updUserId; + } +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/utils/BooleanUtils.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/utils/BooleanUtils.java new file mode 100644 index 0000000000..93589c0e54 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/utils/BooleanUtils.java @@ -0,0 +1,14 @@ +package ca.bc.gov.open.jag.efilingcommons.utils; + + +import org.apache.commons.lang3.StringUtils; + +public class BooleanUtils { + + private BooleanUtils() {} + + public static boolean toBoolean(String value) { + return StringUtils.equalsIgnoreCase(value, "Y"); + } + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/utils/DateUtils.java b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/utils/DateUtils.java new file mode 100644 index 0000000000..45918a4ea5 --- /dev/null +++ b/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/utils/DateUtils.java @@ -0,0 +1,42 @@ +package ca.bc.gov.open.jag.efilingcommons.utils; + + +import org.joda.time.DateTime; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import java.util.Date; +import java.util.GregorianCalendar; + +public class DateUtils { + + private DateUtils() {} + + public static XMLGregorianCalendar getXmlDate(DateTime dateTime) throws DatatypeConfigurationException { + GregorianCalendar entryDate = new GregorianCalendar(); + entryDate.setTime(dateTime.toDate()); + return DatatypeFactory.newInstance().newXMLGregorianCalendar(entryDate); + } + + public static XMLGregorianCalendar getXmlDate(Date date) throws DatatypeConfigurationException { + GregorianCalendar entryDate = new GregorianCalendar(); + entryDate.setTime(date); + return DatatypeFactory.newInstance().newXMLGregorianCalendar(entryDate); + } + + public static XMLGregorianCalendar getCurrentXmlDate() { + try { + return getXmlDate(DateTime.now().toDate()); + } catch (DatatypeConfigurationException e) { + //This will never execute + throw new RuntimeException("Impossible"); + } + } + + public static String toIsoDate(DateTime date) { + if (date == null) return null; + return date.toDateTimeISO().toString(); + } + +} diff --git a/src/backend/libs/efiling-commons/src/test/java/ca/bc/gov/open/jag/efilingcommons/model/CreateAccountRequestTest.java b/src/backend/libs/efiling-commons/src/test/java/ca/bc/gov/open/jag/efilingcommons/model/CreateAccountRequestTest.java new file mode 100644 index 0000000000..b9f9f52efc --- /dev/null +++ b/src/backend/libs/efiling-commons/src/test/java/ca/bc/gov/open/jag/efilingcommons/model/CreateAccountRequestTest.java @@ -0,0 +1,21 @@ +package ca.bc.gov.open.jag.efilingcommons.model; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class CreateAccountRequestTest { + + @Test + public void shouldBuildACreateAccountRequest() { + + + CreateAccountRequest actual = CreateAccountRequest.builder() + .firstName("firstName") + .middleName("middleName") + .lastName("lastName") + .create(); + + } + +} diff --git a/src/backend/libs/efiling-account-client/pom.xml b/src/backend/libs/efiling-cso-client/pom.xml similarity index 62% rename from src/backend/libs/efiling-account-client/pom.xml rename to src/backend/libs/efiling-cso-client/pom.xml index 36c668a31b..a62f983f65 100644 --- a/src/backend/libs/efiling-account-client/pom.xml +++ b/src/backend/libs/efiling-cso-client/pom.xml @@ -3,56 +3,42 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - - - org.springframework.boot - spring-boot-starter-parent - 2.3.1.RELEASE - - - ca.bc.gov.open.jag - efiling-account-client - 0.0.1-SNAPSHOT + efiling-cso-client + 2.0.12-SNAPSHOT - 1.8 - 1.3.1.Final + 17 + 1.4.2.Final + 3.8.1 + 2.17.1 + 4.2.7-1 + 2.3.1 + + + jdt_apt - - org.springframework.boot - spring-boot-starter-web-services - - - org.springframework.boot - spring-boot-starter-tomcat - - + org.apache.cxf + cxf-rt-frontend-jaxws - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - + jakarta.jws + jakarta.jws-api + 3.0.0 org.apache.cxf - cxf-rt-frontend-jaxws + cxf-rt-transports-http org.apache.cxf - cxf-rt-transports-http + cxf-rt-features-logging @@ -73,9 +59,30 @@ ca.bc.gov.open.jag efiling-commons - 0.0.1-SNAPSHOT + 2.0.12-SNAPSHOT + + + + org.junit.jupiter + junit-jupiter-api + test + + org.junit.jupiter + junit-jupiter-engine + test + + + + org.mockito + mockito-core + test + + + org.springframework + spring-web + @@ -83,7 +90,7 @@ ca.bc.gov.open.jag efiling-bom - 0.0.1-SNAPSHOT + 2.0.12-SNAPSHOT pom import @@ -93,10 +100,16 @@ + + maven-surefire-plugin + 3.5.3 + + org.apache.maven.plugins maven-compiler-plugin + ${org.maven.version} ${java.version} ${java.version} @@ -114,7 +127,7 @@ org.apache.cxf cxf-codegen-plugin - 3.3.7 + 4.0.1 generate-sources @@ -124,8 +137,6 @@ ${project.basedir}/src/main/resources/wsdl/AccountFacade.wsdl - ${project.basedir}/src/main/resources/wsdl/RoleRegistry.wsdl - ${project.basedir}/src/main/resources/wsdl/BCeIDService.wsdl -client -autoNameResolution @@ -140,6 +151,26 @@ + + org.codehaus.mojo + build-helper-maven-plugin + 3.2.0 + + + add-source + generate-sources + + add-source + + + + ${project.build.directory}/generated-sources/annotations + + + + + + diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoAccountServiceImpl.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoAccountServiceImpl.java new file mode 100644 index 0000000000..44598be78d --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoAccountServiceImpl.java @@ -0,0 +1,201 @@ +package ca.bc.gov.open.jag.efilingcsoclient; + +import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.RegisteredRole; +import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.RoleRegistryPortType; +import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.UserRoles; +import ca.bc.gov.ag.csows.accounts.*; +import ca.bc.gov.open.jag.efilingcommons.exceptions.CSOHasMultipleAccountException; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingAccountServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.CreateAccountRequest; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; +import ca.bc.gov.open.jag.efilingcommons.utils.DateUtils; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.AccountDetailsMapper; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.ClientProfileMapper; +import jakarta.xml.ws.WebServiceException; +import org.apache.commons.lang3.StringUtils; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.XMLGregorianCalendar; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +public class CsoAccountServiceImpl implements EfilingAccountService { + + + private final AccountFacadeBean accountFacadeBean; + private final RoleRegistryPortType roleRegistryPortType; + private final AccountDetailsMapper accountDetailsMapper; + private final ClientProfileMapper clientProfileMapper; + + public CsoAccountServiceImpl(AccountFacadeBean accountFacadeBean, + RoleRegistryPortType roleRegistryPortType, + AccountDetailsMapper accountDetailsMapper, ClientProfileMapper clientProfileMapper) { + + this.accountFacadeBean = accountFacadeBean; + this.roleRegistryPortType = roleRegistryPortType; + this.accountDetailsMapper = accountDetailsMapper; + this.clientProfileMapper = clientProfileMapper; + + } + + @Override + public AccountDetails getAccountDetails(String universalId) { + + return getCsoDetails(universalId); + + } + + @Override + public AccountDetails createAccount(CreateAccountRequest createAccountRequest) { + + // Validate the incoming data + if (StringUtils.isEmpty(createAccountRequest.getFirstName())) throw new IllegalArgumentException("First Name is required"); + if (StringUtils.isEmpty(createAccountRequest.getLastName())) throw new IllegalArgumentException("Last Name is required"); + if (StringUtils.isEmpty(createAccountRequest.getEmail())) throw new IllegalArgumentException("Email is required"); + if (StringUtils.isEmpty(createAccountRequest.getUniversalId())) throw new IllegalArgumentException("Universal ID is required"); + if (StringUtils.isEmpty(createAccountRequest.getIdentityProvider()) || Keys.IDENTITY_PROVIDERS.get(createAccountRequest.getIdentityProvider().toUpperCase()) == null) throw new IllegalArgumentException("Valid identity provider is required"); + + AccountDetails accountDetails = null; + + try { + + Account account = setCreateAccountDetails(createAccountRequest); + Client client = setCreateAccountClientDetails(createAccountRequest); + List roles = setCreateAccountRoles(); + ClientProfile clientProfile = accountFacadeBean.createAccount(account, client, roles, CsoHelpers.date2XMLGregorian(new Date()), CsoHelpers.date2XMLGregorian(new Date()), createAccountRequest.getEmail(), null); + + if (null != clientProfile) { + accountDetails = accountDetailsMapper.toAccountDetails( + createAccountRequest.getUniversalId(), + clientProfileMapper.toClientProfile(clientProfile), + hasFileRole(CsoHelpers.formatUserGuid(createAccountRequest.getUniversalId()))); + } + } + catch (DatatypeConfigurationException | NestedEjbException_Exception | WebServiceException e) { + throw new EfilingAccountServiceException("Exception while creating CSO account", e.getCause()); + } + + return accountDetails; + } + + @Override + public void updateClient(AccountDetails accountDetails) { + if (accountDetails == null) throw new IllegalArgumentException("account details required"); + if (accountDetails.getClientId() == null) throw new IllegalArgumentException("client id is required"); + if (StringUtils.isBlank(accountDetails.getInternalClientNumber())) throw new IllegalArgumentException("internal client number is required"); + + try { + Client client = accountFacadeBean.getClient(accountDetails.getClientId()); + + client.setInternalClientNo(accountDetails.getInternalClientNumber()); + client.setRegisteredCreditCardYnBoolean(accountDetails.isCardRegistered()); + client.setUpdDtm(DateUtils.getCurrentXmlDate()); + client.setUpdUserId(accountDetails.getClientId().toString()); + + accountFacadeBean.updateClient(client); + } catch (NestedEjbException_Exception e) { + throw new EfilingAccountServiceException("Exception while updating client", e); + } + + } + + @Override + public String getOrderNumber() { + try { + return accountFacadeBean.getNextOrderNumber().toString(); + } catch (NestedEjbException_Exception e) { + throw new EfilingAccountServiceException("Exception while fetching next order number", e); + } + } + + private AccountDetails getCsoDetails(String universalId) { + + AccountDetails accountDetails = null; + List profiles = new ArrayList<>(); + try { + profiles.addAll(accountFacadeBean.findProfiles(CsoHelpers.formatUserGuid(universalId))); + } catch (NestedEjbException_Exception | WebServiceException e) { + throw new EfilingAccountServiceException("Exception while fetching account details", e); + } + // An account must have only one profile associated with it to proceed + if (profiles.size() == 1) { + accountDetails = accountDetailsMapper.toAccountDetails(universalId, clientProfileMapper.toClientProfile(profiles.get(0)), hasFileRole(CsoHelpers.formatUserGuid(universalId))); + } + else if (profiles.size() > 1) { + throw new CSOHasMultipleAccountException(profiles.get(0).getClientId().toString()); + } + + return accountDetails; + + } + + public boolean hasFileRole(String userGuid) { + + UserRoles userRoles = roleRegistryPortType.getRolesForIdentifier("Courts", "CSO", userGuid, "CAP"); + List roles = userRoles.getRoles(); + return roles != null && roles.stream().anyMatch(r -> r.getCode().equals(Keys.CSO_USER_ROLE_FILE)); + + } + + + private Account setCreateAccountDetails(CreateAccountRequest createAccountRequest) throws DatatypeConfigurationException { + + Account account = new Account(); + String accountName = createAccountRequest.getFirstName() + " " + createAccountRequest.getLastName(); + + account.setAccountNm(accountName); + account.setAccountPrefixTxt("SA"); + account.setAccountStatusCd("ACT"); + account.setAuthenticatedAccountGuid(CsoHelpers.formatUserGuid(createAccountRequest.getUniversalId())); + account.setEmailTxt(createAccountRequest.getEmail()); + account.setEntDtm(CsoHelpers.date2XMLGregorian(new Date())); + account.setFeeExemptYnBoolean(false); + account.setRegisteredCreditCardYnBoolean(false); + + return account; + + } + + private Client setCreateAccountClientDetails(CreateAccountRequest createAccountRequest) throws DatatypeConfigurationException { + Client client = new Client(); + XMLGregorianCalendar date = CsoHelpers.date2XMLGregorian(new Date()); + + client.setAuthenticatedClientGuid(CsoHelpers.formatUserGuid(createAccountRequest.getUniversalId())); + client.setAuthoritativePartyId(Keys.IDENTITY_PROVIDERS.get(createAccountRequest.getIdentityProvider().toUpperCase())); + client.setClientPrefixTxt("CS"); + client.setClientStatusCd("ACT"); + client.setEntDtm(date); + client.setGivenNm(createAccountRequest.getFirstName()); + client.setMiddleNm(createAccountRequest.getMiddleName()); + client.setRegisteredCreditCardYnBoolean(false); + client.setSurnameNm(createAccountRequest.getLastName()); + + return client; + + } + + private List setCreateAccountRoles() { + + List roles = new ArrayList<>(); + RoleAssignment roleInd = new RoleAssignment(); + roleInd.setActiveYn(true); + roleInd.setRegisteredClientRoleCd(Keys.INDIVIDUAL_ROLE_TYPE_CD); + roles.add(roleInd); + + RoleAssignment roleCaef = new RoleAssignment(); + roleCaef.setActiveYn(true); + roleCaef.setRegisteredClientRoleCd(Keys.CSO_USER_ROLE_CAEF); + roles.add(roleCaef); + + RoleAssignment roleFile = new RoleAssignment(); + roleFile.setActiveYn(true); + roleFile.setRegisteredClientRoleCd(Keys.CSO_USER_ROLE_FILE); + roles.add(roleFile); + + return roles; + + } + +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoCourtServiceImpl.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoCourtServiceImpl.java new file mode 100644 index 0000000000..723f836eb5 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoCourtServiceImpl.java @@ -0,0 +1,90 @@ +package ca.bc.gov.open.jag.efilingcsoclient; + +import ca.bc.gov.ag.csows.ceis.*; +import ca.bc.gov.ag.csows.filing.status.FilingStatusFacadeBean; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingCourtServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.CourtDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingCourtService; +import org.apache.commons.lang3.StringUtils; + +import java.math.BigDecimal; +import java.util.Optional; + + +public class CsoCourtServiceImpl implements EfilingCourtService { + + private final Csows csows; + private final FilingStatusFacadeBean filingStatusFacadeBean; + + public CsoCourtServiceImpl(Csows csows, FilingStatusFacadeBean filingStatusFacadeBean) { + this.filingStatusFacadeBean = filingStatusFacadeBean; + this.csows = csows; + } + + @Override + public Optional getCourtDescription(String agencyIdentifierCd, String courtLevel, String courtClass) { + + if (StringUtils.isBlank(agencyIdentifierCd)) throw new IllegalArgumentException("Agency identifier is required"); + if (StringUtils.isBlank(courtLevel)) throw new IllegalArgumentException("Level identifier is required"); + if (StringUtils.isBlank(courtClass)) throw new IllegalArgumentException("Class identifier is required"); + + return csows.getCourtLocations().getArray().stream() + .filter(court -> court.getAgenAgencyIdentifierCd().equals(agencyIdentifierCd)) + .findFirst() + .map(court -> new CourtDetails(court.getAgenId(), court.getAgenAgencyNm(), getClassDescription(courtClass), getCourLevelDescription(courtLevel))); + } + + @Override + public boolean checkValidLevelClassLocation(BigDecimal agencyId, String courtLevel, String courtClass, String appplicationCode) { + try { + // Call CSO for isParticipatingClass + return filingStatusFacadeBean.isParticipatingClass( + agencyId, + courtLevel, + courtClass, + appplicationCode + ); + } catch (ca.bc.gov.ag.csows.filing.status.NestedEjbException_Exception e) { + throw new EfilingCourtServiceException("Exception while checking isParticipatingClass"); + } + } + + @Override + public boolean checkValidCourtFileNumber(String fileNumber, BigDecimal agencyId, String courtLevel, String courtClass, String applicationCode) { + // Call CSO for fileNumberSearch + CsoFileSrchResultRet fileNumberSearchResult = csows.fileNumberSearch( + BigDecimal.ZERO, + fileNumber, + agencyId, + courtLevel, + courtClass, + null, + null, + BigDecimal.ONE, + Boolean.TRUE, + applicationCode + ); + + // check if total records is greater than zero + return (fileNumberSearchResult.getTotalRecords().compareTo(BigDecimal.ZERO) == 1); + } + + private String getCourLevelDescription(String courtLevel) { + CsoCourtLevelArr levels = csows.getCourtLevels(); + return levels.getArray().stream() + .filter(court -> court.getLevelCd().equals(courtLevel)) + .findFirst() + .map(CsoCourtLevelRec::getLevelDsc) + .orElseThrow(() -> new EfilingCourtServiceException("Level not found")); + } + + private String getClassDescription(String courtClass) { + CsoCourtClassArr classes = csows.getCourtClasses(null); + return classes.getArray().stream() + .filter(court -> court.getClassCd().equals(courtClass)) + .findFirst() + .map(CsoCourtClassRec::getClassDsc) + .orElseThrow(() -> new EfilingCourtServiceException("Class not found")); + } + +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoDocumentServiceImpl.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoDocumentServiceImpl.java new file mode 100644 index 0000000000..bdf47d0bd6 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoDocumentServiceImpl.java @@ -0,0 +1,76 @@ +package ca.bc.gov.open.jag.efilingcsoclient; + +import ca.bc.gov.ag.csows.filing.status.DocumentType; +import ca.bc.gov.ag.csows.filing.status.FilingStatusFacadeBean; +import ca.bc.gov.ag.csows.filing.status.NestedEjbException_Exception; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingDocumentServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import static ca.bc.gov.open.jag.efilingcsoclient.Keys.OTHER_DOCUMENT_TYPE; + + +public class CsoDocumentServiceImpl implements EfilingDocumentService { + + private final FilingStatusFacadeBean filingStatusFacadeBean; + + public CsoDocumentServiceImpl(FilingStatusFacadeBean filingStatusFacadeBean) { + this.filingStatusFacadeBean = filingStatusFacadeBean; + } + + /** + * P --> level + * F --> class + * + * @param documentType + * @return + */ + @Override + public DocumentTypeDetails getDocumentTypeDetails(String courtLevel, String courtClass, String documentType) { + + if (StringUtils.isBlank(courtLevel)) throw new IllegalArgumentException("courtLevel is required."); + if (StringUtils.isBlank(courtClass)) throw new IllegalArgumentException("courtClass level is required."); + if (StringUtils.isBlank(documentType)) throw new IllegalArgumentException("documentType level is required."); + + return getSoapDocumentTypes(courtLevel, courtClass).stream() + .filter(doc -> doc.getDocumentTypeCd().equals(documentType)) + .findFirst() + .map(doc -> new DocumentTypeDetails(doc.getDocumentTypeDesc(), doc.getDocumentTypeCd(), doc.getDefaultStatutoryFee(), doc.isOrderDocumentYn(),doc.isRushRequiredYn(), doc.isAutoProcessYn())) + .orElseThrow(() -> new EfilingDocumentServiceException("Document type does not exists")); + + } + + public List getDocumentTypes(String courtLevel, String courtClass) { + + if (StringUtils.isBlank(courtLevel)) throw new IllegalArgumentException("courtLevel is required."); + if (StringUtils.isBlank(courtClass)) throw new IllegalArgumentException("courtClass level is required."); + + return getSoapDocumentTypes(courtLevel, courtClass).stream() + .map(doc -> new DocumentTypeDetails(doc.getDocumentTypeDesc(), doc.getDocumentTypeCd(), doc.getDefaultStatutoryFee(), doc.isOrderDocumentYn(),doc.isRushRequiredYn(), doc.isAutoProcessYn())).collect(Collectors.toList()); + + } + + private List getSoapDocumentTypes(String courtLevel, String courtClass) { + + List documentTypes; + + try { + documentTypes = new ArrayList<>(filingStatusFacadeBean.getDocumentTypes(courtLevel, courtClass)); + //Remove other document types. NOTE these are cached and redis requires a restart + //TODO: consider feature flagging this + documentTypes.removeIf(documentType -> documentType.getDocumentTypeCd().equals(OTHER_DOCUMENT_TYPE)); + } catch (NestedEjbException_Exception e) { + throw new EfilingDocumentServiceException("Exception while retrieving document details", e.getCause()); + } + + return documentTypes; + + } + + +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoHelpers.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoHelpers.java new file mode 100644 index 0000000000..37ae05f062 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoHelpers.java @@ -0,0 +1,52 @@ +package ca.bc.gov.open.jag.efilingcsoclient; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +/** + * Helper class for CSO + */ +public class CsoHelpers { + + private CsoHelpers() {} + + /** + * Converts UUID to CSO ID FORMAT: no hyphen and all upper case. + * @param id + * @return + */ + public static String formatUserGuid(String id) { + return id.replace("-", "").toUpperCase(); + } + + /** + * Helper function to convert a Date to an XMLGregorianCalendar date for sending to SOAP + * @param date + * @return XMLGregorianCalendar + * @throws DatatypeConfigurationException + */ + public static XMLGregorianCalendar date2XMLGregorian(Date date) throws DatatypeConfigurationException { + GregorianCalendar c = new GregorianCalendar(); + c.setTime(date); + return DatatypeFactory.newInstance().newXMLGregorianCalendar(c); + } + + /** + * Helper function to convert an XMLGregorianCalendar date to a Date + * @param gCalendar + * @return Date + */ + public static Date xmlGregorian2Date(XMLGregorianCalendar gCalendar) { + + if (gCalendar != null) { + Calendar calendarInstance = Calendar.getInstance(); + calendarInstance.setTime(gCalendar.toGregorianCalendar().getTime()); + return calendarInstance.getTime(); + } + return null; + } +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoLookupServiceImpl.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoLookupServiceImpl.java new file mode 100644 index 0000000000..53dd15ad96 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoLookupServiceImpl.java @@ -0,0 +1,116 @@ +package ca.bc.gov.open.jag.efilingcsoclient; + + +import ca.bc.gov.ag.csows.lookups.CodeValue; +import ca.bc.gov.ag.csows.lookups.LookupFacadeBean; +import ca.bc.gov.ag.csows.lookups.NestedEjbException_Exception; +import ca.bc.gov.ag.csows.lookups.ServiceFee; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingLookupServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.ServiceFees; +import ca.bc.gov.open.jag.efilingcommons.model.SubmissionFeeRequest; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.LookupItem; +import org.apache.commons.lang3.StringUtils; + +import javax.xml.datatype.DatatypeConfigurationException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +public class CsoLookupServiceImpl implements EfilingLookupService { + + private LookupFacadeBean lookupFacade; + + public CsoLookupServiceImpl(LookupFacadeBean lookupFacade) { + this.lookupFacade = lookupFacade; + } + + @Override + public ServiceFees getServiceFee(SubmissionFeeRequest submissionFeeRequest) { + + // NOTE- "DCFL" is the only string that will work here until we get our service types setup + if (StringUtils.isEmpty(submissionFeeRequest.getServiceType())) throw new IllegalArgumentException("service type is required"); + if (StringUtils.isEmpty(submissionFeeRequest.getApplication())) throw new IllegalArgumentException("application code is required"); + if (StringUtils.isEmpty(submissionFeeRequest.getClassification())) throw new IllegalArgumentException("class code is required"); + if (StringUtils.isEmpty(submissionFeeRequest.getDivision())) throw new IllegalArgumentException("division code is required"); + if (StringUtils.isEmpty(submissionFeeRequest.getLevel())) throw new IllegalArgumentException("level code is required"); + + try { + ServiceFee fee = lookupFacade.getServiceFeeByClassification(submissionFeeRequest.getServiceType(), + CsoHelpers.date2XMLGregorian(new Date()), + submissionFeeRequest.getApplication(), + submissionFeeRequest.getDivision(), + submissionFeeRequest.getLevel(), + submissionFeeRequest.getClassification()); + if (fee == null) + return new ServiceFees( + BigDecimal.ZERO, + null); + + return new ServiceFees( + fee.getFeeAmt(), + fee.getServiceTypeCd()); + + } + catch(DatatypeConfigurationException | NestedEjbException_Exception e) { + throw new EfilingLookupServiceException("Exception while retrieving service fee", e.getCause()); + } + + } + + @Override + public List getValidPartyRoles(String courtLevel, String courtClass, String documentTypes) { + try { + List partyRolesResponse = lookupFacade.getEfilingPartyRoles(courtLevel, courtClass, documentTypes); + List validRoles = new ArrayList<>(); + + for (CodeValue partyRole : partyRolesResponse) { + validRoles.add(partyRole.getCode()); + } + + return validRoles; + + } catch(NestedEjbException_Exception e) { + throw new EfilingLookupServiceException("Exception while getting party roles", e.getCause()); + } + } + + @Override + public List getCountries() { + + try { + + List countryCodes = lookupFacade.getCountryCodes(); + List countries = lookupFacade.getCountries(); + + return countryCodes.stream() + .map(country -> LookupItem.builder().code(country.getCode()).description( + countries.stream() + .filter(codeValue -> codeValue.getCode().equals(country.getParentCode())) + .findFirst() + .orElseGet(this::setMissingCodeValue).getDescription() + ).create()) + .collect(Collectors.toList()); + } catch(NestedEjbException_Exception e) { + throw new EfilingLookupServiceException("Exception while getting countries", e.getCause()); + } + + } + + /** + * If the parent is missing ensure drop down populates + * @return Generic message + */ + private CodeValue setMissingCodeValue() { + + CodeValue codeValue = new CodeValue(); + + codeValue.setDescription("Missing Description"); + + return codeValue; + + } + +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoReviewServiceImpl.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoReviewServiceImpl.java new file mode 100644 index 0000000000..1ef64a85d1 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoReviewServiceImpl.java @@ -0,0 +1,324 @@ +package ca.bc.gov.open.jag.efilingcsoclient; + +import ca.bc.gov.ag.csows.filing.DocumentStatuses; +import ca.bc.gov.ag.csows.filing.FilingFacadeBean; +import ca.bc.gov.ag.csows.filing.status.*; +import ca.bc.gov.ag.csows.reports.Report; +import ca.bc.gov.ag.csows.reports.ReportService; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingReviewServiceException; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingStatusServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.RushDocumentRequest; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.DeleteSubmissionDocumentRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackageRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.LookupItem; +import ca.bc.gov.open.jag.efilingcommons.submission.models.ReportRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewFilingPackage; +import ca.bc.gov.open.jag.efilingcommons.utils.DateUtils; +import ca.bc.gov.open.jag.efilingcsoclient.config.CsoProperties; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.FilePackageMapper; +import org.joda.time.DateTime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import javax.xml.datatype.DatatypeConfigurationException; +import java.math.BigDecimal; +import java.text.MessageFormat; +import java.util.*; +import java.util.stream.Collectors; + +public class CsoReviewServiceImpl implements EfilingReviewService { + + Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final FilingStatusFacadeBean filingStatusFacadeBean; + + private final ReportService reportService; + + private final FilingFacadeBean filingFacadeBean; + + private final FilePackageMapper filePackageMapper; + + private final CsoProperties csoProperties; + + private final RestTemplate restTemplate; + + private final EfilingLookupService lookupService; + + public CsoReviewServiceImpl(FilingStatusFacadeBean filingStatusFacadeBean, ReportService reportService, FilingFacadeBean filingFacadeBean, FilePackageMapper filePackageMapper, CsoProperties csoProperties, RestTemplate restTemplate, EfilingLookupService lookupService) { + + this.filingStatusFacadeBean = filingStatusFacadeBean; + this.reportService = reportService; + this.filingFacadeBean = filingFacadeBean; + this.filePackageMapper = filePackageMapper; + this.csoProperties = csoProperties; + this.restTemplate = restTemplate; + this.lookupService = lookupService; + + } + + @Override + public Optional findStatusByPackage(FilingPackageRequest filingPackageRequest) { + + try { + + logger.info("Calling soap findStatusBySearchCriteria by client id and package service "); + //Is account ID required? It is the variable after client ID + FilingStatus filingStatus = filingStatusFacadeBean + .findStatusBySearchCriteria(null, null, null, null, null, null, filingPackageRequest.getPackageNo(), filingPackageRequest.getClientId(), filingPackageRequest.getAccountId(), null, null, null, null, BigDecimal.ONE, null, null, null); + + if (filingStatus.getFilePackages() == null || filingStatus.getFilePackages().isEmpty()) return Optional.empty(); + + return Optional.of(filePackageMapper.toFilingPackage( + filingStatus.getFilePackages().get(0), + getViewAllPackagesUrl(), + filingStatus.getFilePackages().get(0).getParties().stream() + .filter(individual -> individual.getPartyTypeCd().equalsIgnoreCase(Keys.INDIVIDUAL_ROLE_TYPE_CD)) + .map(filePackageMapper::toParty) + .collect(Collectors.toList()), + filingStatus.getFilePackages().get(0).getParties().stream() + .filter(individual -> individual.getPartyTypeCd().equalsIgnoreCase(Keys.ORGANIZATION_ROLE_TYPE_CD)) + .map(filePackageMapper::toOrganization) + .collect(Collectors.toList()), + getRushOrderItem(filingStatus.getFilePackages().get(0)), + getCountryDescription(filingStatus.getFilePackages().get(0)), + getPackageStatus(filingStatus.getFilePackages().get(0).getFiles()))); + + } catch (NestedEjbException_Exception e) { + + throw new EfilingStatusServiceException("Exception while finding status", e.getCause()); + + } + + } + + @Override + public List findStatusByClient(FilingPackageRequest filingPackageRequest) { + try { + + logger.info("Calling soap findStatusBySearchCriteria by client id service "); + + DateTime endDate = DateTime.now(); + DateTime startDate = endDate.minusYears(1); + //Is account ID required? It is the variable after client ID + FilingStatus filingStatus = filingStatusFacadeBean + .findStatusBySearchCriteria(null, null, null, DateUtils.getXmlDate(startDate), DateUtils.getXmlDate(endDate), null , null, filingPackageRequest.getClientId(), filingPackageRequest.getAccountId(), null, null, null, null, BigDecimal.valueOf(100), null, filingPackageRequest.getParentApplication(), null); + + if (filingStatus.getFilePackages().isEmpty()) return new ArrayList<>(); + + return filingStatus.getFilePackages().stream().map(filePackage -> filePackageMapper.toFilingPackage(filePackage, + getViewAllPackagesUrl(), + filePackage.getParties().stream() + .filter(individual -> individual.getPartyTypeCd().equalsIgnoreCase(Keys.INDIVIDUAL_ROLE_TYPE_CD)) + .map(filePackageMapper::toParty) + .collect(Collectors.toList()), + filePackage.getParties().stream() + .filter(individual -> individual.getPartyTypeCd().equalsIgnoreCase(Keys.ORGANIZATION_ROLE_TYPE_CD)) + .map(filePackageMapper::toOrganization) + .collect(Collectors.toList()), + getRushOrderItem(filingStatus.getFilePackages().get(0)), + getCountryDescription(filingStatus.getFilePackages().get(0)), + getPackageStatus(filingStatus.getFilePackages().get(0).getFiles()))).collect(Collectors.toList()); + + } catch (NestedEjbException_Exception | DatatypeConfigurationException e) { + + throw new EfilingStatusServiceException("Exception while finding status list", e.getCause()); + + } + } + + @Override + public Optional getReport(ReportRequest reportRequest) { + String reportName; + String parameterName; + switch (reportRequest.getReport()) { + case SUBMISSION_SHEET: + reportName = Keys.SUBMISSION_REPORT_NAME; + parameterName = Keys.SUBMISSION_REPORT_PARAMETER; + break; + case PAYMENT_RECEIPT: + reportName = Keys.RECEIPT_REPORT_NAME; + parameterName = Keys.PARAM_REPORT_PARAMETER; + break; + case REGISTRY_NOTICE: + reportName = Keys.REGISTRY_NOTICE_NAME; + parameterName = Keys.PARAM_REPORT_PARAMETER; + break; + default: + throw new IllegalStateException("Unexpected value: " + reportRequest.getReport()); + } + + logger.info("Calling soap to retrieve {} report ", reportName); + + Report report = new Report(); + report.setName(reportName); + report.getParameters().addAll(Arrays.asList(parameterName, reportRequest.getPackageId().toPlainString())); + + byte[] result = reportService.runReport(report); + + if (result == null || result.length == 0) return Optional.empty(); + + return Optional.of(result); + + } + + @Override + public Optional getSubmittedDocument(BigDecimal documentIdentifier) { + + String url = ""; + + try { + url = filingFacadeBean.getActiveDocumentURL(documentIdentifier); + } catch (ca.bc.gov.ag.csows.filing.NestedEjbException_Exception e) { + logger.error("Error in [updateDocumentStatus] call"); + throw new EfilingReviewServiceException("Failed to retrieved document", e.getCause()); + } + + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Arrays.asList(MediaType.APPLICATION_PDF)); + HttpEntity entity = new HttpEntity<>(headers); + ResponseEntity response = restTemplate.getForEntity(url, byte[].class, entity); + + return Optional.of(response.getBody()); + + } + + @Override + public void deleteSubmittedDocument(DeleteSubmissionDocumentRequest deleteSubmissionDocumentRequest) { + try { + + logger.debug("Calling soap [updateDocumentStatus] "); + + DocumentStatuses documentStatuses = new DocumentStatuses(); + documentStatuses.setDocumentId(new BigDecimal(deleteSubmissionDocumentRequest.getDocumentId())); + documentStatuses.setEntDtm(DateUtils.getCurrentXmlDate()); + documentStatuses.setDocumentStatusTypeCd(ca.bc.gov.open.jag.efilingcommons.Keys.WITHDRAWN_STATUS_CD); + documentStatuses.setCreatedByPartId(deleteSubmissionDocumentRequest.getClientId()); + documentStatuses.setEntUserId(deleteSubmissionDocumentRequest.getClientId().toEngineeringString()); + documentStatuses.setUpdUserId(deleteSubmissionDocumentRequest.getClientId().toEngineeringString()); + documentStatuses.setStatusDtm(DateUtils.getCurrentXmlDate()); + + filingFacadeBean.updateDocumentStatus(documentStatuses); + + logger.info(" [updateDocumentStatus] Successful "); + + } catch (ca.bc.gov.ag.csows.filing.NestedEjbException_Exception e) { + + logger.error("Error in [updateDocumentStatus] call"); + + throw new EfilingReviewServiceException("Failed to updateDocumentStatus", e.getCause()); + + } + + try { + + logger.debug("Calling soap [inactivateReferrals] "); + + filingFacadeBean.inactivateReferrals(deleteSubmissionDocumentRequest.getClientId(), DateUtils.getCurrentXmlDate(), deleteSubmissionDocumentRequest.getDocumentId()); + + logger.info(" [updateDocumentStatus] Successful "); + + } catch (ca.bc.gov.ag.csows.filing.NestedEjbException_Exception e) { + + logger.error("Error in [inactivateReferrals] call"); + + throw new EfilingReviewServiceException("Failed in inactivateReferrals", e.getCause()); + + } + + try { + + logger.debug("Calling soap [removePackageParties] "); + + filingFacadeBean.removePackageParties(deleteSubmissionDocumentRequest.getPackageNo()); + + logger.info(" [updateDocumentStatus] Successful "); + + } catch (ca.bc.gov.ag.csows.filing.NestedEjbException_Exception e) { + + logger.error("Error in [removePackageParties] call"); + + throw new EfilingReviewServiceException("Failed in removePackageParties", e.getCause()); + + } + + } + + @Override + public Optional getRushDocument(RushDocumentRequest rushDocumentRequest) { + + logger.info("Calling soap service to retrieve rush document"); + + String url = ""; + + try { + url = filingFacadeBean.getActiveSuppDocURL(rushDocumentRequest.getProcReqId(), rushDocumentRequest.getProcItemSeqNo(), rushDocumentRequest.getDocSeqNo()); + } catch (ca.bc.gov.ag.csows.filing.NestedEjbException_Exception e) { + logger.error("Error in [getActiveSuppDocURL] call"); + throw new EfilingReviewServiceException("Failed to retrieved document", e.getCause()); + } + + HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_PDF)); + HttpEntity entity = new HttpEntity<>(headers); + ResponseEntity response = restTemplate.getForEntity(url, byte[].class, entity); + + return Optional.of(response.getBody()); + + } + + private String getViewAllPackagesUrl() { + return MessageFormat.format("{0}/{1}", csoProperties.getCsoBasePath(), Keys.VIEW_ALL_PACKAGE_SUBPATH); + } + + private RushOrderRequestItem getRushOrderItem(FilePackage filePackage) { + if (filePackage.getProcRequest() == null) return new RushOrderRequestItem(); + + return filePackage.getProcRequest().getItem(); + + } + + private String getCountryDescription(FilePackage filePackage) { + if (filePackage.getProcRequest() == null || filePackage.getProcRequest().getCtryId() == null) return null; + + Optional countryItem = lookupService.getCountries().stream() + .filter(country -> country.getCode().equals(filePackage.getProcRequest().getCtryId().toEngineeringString())) + .findFirst(); + + return countryItem.map(LookupItem::getDescription).orElse(null); + + } + + private String getPackageStatus(List documents) { + + boolean pending = false; + + if (documents != null && !documents.isEmpty()) { + //Package status is calculated based on document status + for (File document : documents) { + + if (document.getStatus().equalsIgnoreCase(Keys.CSO_DOCUMENT_REJECTED) || + document.getStatus().equalsIgnoreCase(Keys.CSO_DOCUMENT_COURTESY_CORRECTED)) + return Keys.PACKAGE_STATUS_ACTION_REQUIRED; + + if (document.getStatus().equalsIgnoreCase(Keys.CSO_DOCUMENT_RE_SUBMITTED) || + document.getStatus().equalsIgnoreCase(Keys.CSO_DOCUMENT_REFERRED) || + document.getStatus().equalsIgnoreCase(Keys.CSO_DOCUMENT_SUBMITTED)) + pending = true; + } + + } + + if (pending) return Keys.PACKAGE_STATUS_PENDING; + + return Keys.PACKAGE_STATUS_COMPLETE; + + } + +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoSearchServiceImpl.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoSearchServiceImpl.java new file mode 100644 index 0000000000..6a63390c6c --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoSearchServiceImpl.java @@ -0,0 +1,32 @@ +package ca.bc.gov.open.jag.efilingcsoclient; + +import ca.bc.gov.courts.appeal.ws.services.COACase; +import ca.bc.gov.courts.appeal.ws.services.CSOSearchSoap; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSearchService; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CsoSearchServiceImpl implements EfilingSearchService { + + Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final CSOSearchSoap csoSearchSoap; + + public CsoSearchServiceImpl(CSOSearchSoap csoSearchSoap) { + this.csoSearchSoap = csoSearchSoap; + } + + @Override + public boolean caseNumberExists(String caseNumber) { + + logger.info("search for case number request received"); + + if (StringUtils.isBlank(caseNumber)) throw new IllegalArgumentException("caseNumber is required."); + + COACase result = csoSearchSoap.searchByCaseNumber(caseNumber); + + return (result != null); + + } +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoSubmissionServiceImpl.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoSubmissionServiceImpl.java new file mode 100644 index 0000000000..6e365f5d44 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/CsoSubmissionServiceImpl.java @@ -0,0 +1,455 @@ +package ca.bc.gov.open.jag.efilingcsoclient; + +import ca.bc.gov.ag.csows.filing.NestedEjbException_Exception; +import ca.bc.gov.ag.csows.filing.ProcessItemStatus; +import ca.bc.gov.ag.csows.filing.*; +import ca.bc.gov.ag.csows.services.*; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingSubmissionServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.*; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingPaymentService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSubmissionService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; +import ca.bc.gov.open.jag.efilingcommons.utils.DateUtils; +import ca.bc.gov.open.jag.efilingcsoclient.config.CsoProperties; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.*; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.XMLGregorianCalendar; +import java.math.BigDecimal; +import java.text.MessageFormat; +import java.util.*; + +import static ca.bc.gov.open.jag.efilingcsoclient.CsoHelpers.xmlGregorian2Date; +import static ca.bc.gov.open.jag.efilingcsoclient.Keys.*; + +public class CsoSubmissionServiceImpl implements EfilingSubmissionService { + + Logger logger = LoggerFactory.getLogger(CsoSubmissionServiceImpl.class); + + private final FilingFacadeBean filingFacadeBean; + private final ServiceFacadeBean serviceFacadeBean; + private final ServiceMapper serviceMapper; + private final FilingPackageMapper filingPackageMapper; + private final FinancialTransactionMapper financialTransactionMapper; + private final CsoProperties csoProperties; + private final DocumentMapper documentMapper; + private final CsoPartyMapper csoPartyMapper; + private final PackageAuthorityMapper packageAuthorityMapper; + private final EfilingDocumentService efilingDocumentService; + + public CsoSubmissionServiceImpl(FilingFacadeBean filingFacadeBean, + ServiceFacadeBean serviceFacadeBean, + ServiceMapper serviceMapper, + FilingPackageMapper filingPackageMapper, + FinancialTransactionMapper financialTransactionMapper, + CsoProperties csoProperties, + DocumentMapper documentMapper, CsoPartyMapper csoPartyMapper, PackageAuthorityMapper packageAuthorityMapper, EfilingDocumentService efilingDocumentService) { + this.filingFacadeBean = filingFacadeBean; + this.serviceFacadeBean = serviceFacadeBean; + this.serviceMapper = serviceMapper; + this.filingPackageMapper = filingPackageMapper; + this.financialTransactionMapper = financialTransactionMapper; + this.csoProperties = csoProperties; + this.documentMapper = documentMapper; + this.csoPartyMapper = csoPartyMapper; + this.packageAuthorityMapper = packageAuthorityMapper; + this.efilingDocumentService = efilingDocumentService; + } + + @Override + public SubmitPackageResponse submitFilingPackage( + AccountDetails accountDetails, + FilingPackage efilingPackage, + EfilingPaymentService paymentService) { + + if (accountDetails == null) throw new IllegalArgumentException("Account Details are required"); + if (accountDetails.getClientId() == null) throw new IllegalArgumentException("Client id is required."); + if (efilingPackage == null) throw new IllegalArgumentException("EfilingPackage is required."); + if (StringUtils.isBlank(efilingPackage.getApplicationCode())) throw new IllegalArgumentException("Application Type code is required."); + + logger.info("Beginning submission process"); + + ServiceSession serviceSession = getServiceSession(accountDetails.getClientId().toString()); + + Service createdService = createEfilingService(efilingPackage, accountDetails, serviceSession); + + //When there is no fee skip + if (efilingPackage.getSubmissionFeeAmount() != null && + efilingPackage.getSubmissionFeeAmount().compareTo(BigDecimal.ZERO) > 0) { + + logger.info("Fee detected making payment"); + + updatePaymentForService( + createdService, + true, + createPayment(paymentService, createdService, efilingPackage.getSubmissionFeeAmount(), accountDetails.getInternalClientNumber())); + + } + + ca.bc.gov.ag.csows.filing.FilingPackage csoFilingPackage = buildFilingPackage(accountDetails, efilingPackage, createdService); + + if (efilingPackage.isRushedSubmission() || efilingPackage.getRush() != null) { + + logger.info("Submission is a rush"); + + csoFilingPackage.setProcRequest(buildRushedOrderRequest(accountDetails, efilingPackage.getRush(), efilingPackage.isRushedSubmission())); + + } + + determineAutoProcessingFlagFromDocuments(efilingPackage, csoFilingPackage); + + BigDecimal filingResult = filePackage(csoFilingPackage); + + updateServiceComplete(createdService); + + return SubmitPackageResponse + .builder() + .packageLink(MessageFormat + .format("{0}{1}{2}", csoProperties.getCsoBasePath(), csoProperties.getCsoPackagePath(), filingResult.toPlainString())) + .transactionId(filingResult) + .create(); + + } + + private ca.bc.gov.ag.csows.filing.FilingPackage buildFilingPackage(AccountDetails accountDetails, FilingPackage efilingPackage, Service createdService) { + + XMLGregorianCalendar submittedDate = ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate(); + XMLGregorianCalendar computedSubmittedDate = getComputedSubmittedDate(efilingPackage.getCourt().getLocation()); + + return filingPackageMapper.toFilingPackage( + efilingPackage, + accountDetails, + createdService.getServiceId(), + submittedDate, + buildCivilDocuments(accountDetails, efilingPackage, computedSubmittedDate), + buildCsoParties(accountDetails, efilingPackage), + buildPackageAuthorities(accountDetails)); + + } + + private List buildPackageAuthorities(AccountDetails accountDetails) { + + return Arrays.asList(packageAuthorityMapper.toPackageAuthority(accountDetails)); + + } + + private List buildCsoParties(AccountDetails accountDetails, FilingPackage efilingPackage) { + + List csoParties = new ArrayList<>(); + + Integer sequence = 0; + + for (int i = 0; i < efilingPackage.getParties().size(); i++) { + //Due to a bug in mapstructs code generation when using expressions that refer to a specfic object + //string formatting has to done here + sequence++; + csoParties.add(csoPartyMapper.toEfilingParties(sequence, + efilingPackage.getParties().get(i), + accountDetails, + StringUtils.capitalize(efilingPackage.getParties().get(i).getFirstName()), + StringUtils.upperCase(efilingPackage.getParties().get(i).getLastName()))); + } + + for (int i = 0; i < efilingPackage.getOrganizations().size(); i++) { + sequence++; + csoParties.add(csoPartyMapper.toEfilingOrganization(sequence, + efilingPackage.getOrganizations().get(i), + accountDetails)); + } + + return csoParties; + + } + + + private List buildCivilDocuments(AccountDetails accountDetails, FilingPackage efilingPackage, XMLGregorianCalendar computedSubmittedDate) { + + List documents = new ArrayList<>(); + + for (int i = 0; i < efilingPackage.getDocuments().size(); i++) { + List payments = Collections.singletonList(documentMapper.toEfilingDocumentPayment(efilingPackage.getDocuments().get(i), accountDetails, + ((efilingPackage.getDocuments().get(i).getStatutoryFeeAmount() == null || efilingPackage.getDocuments().get(i).getStatutoryFeeAmount().equals(BigDecimal.ZERO)) + ? Keys.NOT_REQUIRED_PAYMENT_STATUS_CD : Keys.NOT_PROCESSED_PAYMENT_STATUS_CD))); + List milestones = Arrays.asList(documentMapper.toActualSubmittedDate(accountDetails), + documentMapper.toComputedSubmittedDate(accountDetails, computedSubmittedDate)); + List statuses = Collections.singletonList(documentMapper.toEfilingDocumentStatus(efilingPackage.getDocuments().get(i), accountDetails)); + + + documents.add(documentMapper.toEfilingDocument( + i + 1, + efilingPackage.getDocuments().get(i), + accountDetails, + efilingPackage, + csoProperties.getFileServerHost(), + milestones, + payments, + statuses, + setDocumentId(efilingPackage.getDocuments().get(i).getActionDocument()) + )); + } + + return documents; + + } + + private RushOrderRequest buildRushedOrderRequest(AccountDetails accountDetails, RushProcessing rushProcessing, Boolean requiredRush) { + + logger.info("build rush processing object"); + + RushOrderRequest processRequest = new RushOrderRequest(); + processRequest.setEntDtm(DateUtils.getCurrentXmlDate()); + processRequest.setContactFirstGivenNm((rushProcessing != null ? rushProcessing.getFirstName() : null)); + processRequest.setContactSurnameNm((rushProcessing != null ? rushProcessing.getLastName() : null)); + processRequest.setContactPhoneNo((rushProcessing != null ? rushProcessing.getPhoneNumber() : null)); + processRequest.setCtryId((rushProcessing != null ? new BigDecimal(rushProcessing.getCountryCode()) : null)); + processRequest.setContactEmailTxt((rushProcessing != null ? rushProcessing.getEmail() : null)); + processRequest.setEntUserId(accountDetails.getClientId().toString()); + if (rushProcessing != null && !StringUtils.isBlank(rushProcessing.getCourtDate())) { + try { + processRequest.setRequestDt(DateUtils.getXmlDate(DateTime.parse(rushProcessing.getCourtDate()))); + } catch (DatatypeConfigurationException e) { + logger.error("Court date is invalid"); + } + } else { + processRequest.setRequestDt(DateUtils.getCurrentXmlDate()); + } + RushOrderRequestItem rushOrderRequestItem = new RushOrderRequestItem(); + rushOrderRequestItem.setEntDtm(DateUtils.getCurrentXmlDate()); + rushOrderRequestItem.setEntUserId(accountDetails.getClientId().toString()); + rushOrderRequestItem.setRushFilingReasonTxt((rushProcessing != null ? rushProcessing.getReason() : null)); + rushOrderRequestItem.setProcessReasonCd((rushProcessing != null ? RUSH_TYPES.get(rushProcessing.getRushType().toUpperCase()): RUSH_TYPES.get(RUSH_PROCESS_REASON_CD))); + rushOrderRequestItem.getItemStatuses().add(getProcessItemStatusRequest(accountDetails)); + + if (requiredRush) { + rushOrderRequestItem.getItemStatuses().add(getProcessItemStatusApproved(accountDetails)); + } + + if (rushProcessing != null) { + rushOrderRequestItem.getSupportDocs().addAll(buildSupportingDocuments(accountDetails, rushProcessing.getSupportingDocuments())); + } + + processRequest.setItem(rushOrderRequestItem); + return processRequest; + + } + + private List buildSupportingDocuments(AccountDetails accountDetails, List documents) { + + List supportDocuments = new ArrayList<>(); + for (int i = 0; i < documents.size(); i++) { + supportDocuments.add(documentMapper.toEfilingRushProcessingDocument(i+1, + documents.get(i), + accountDetails, + csoProperties.getFileServerHost())); + } + + return supportDocuments; + + } + + private ProcessItemStatus getProcessItemStatusRequest(AccountDetails accountDetails) { + + return getProcessItemStatus(accountDetails, Keys.REQUEST_PROCESS_STATUS_CD); + + } + + private ProcessItemStatus getProcessItemStatusApproved(AccountDetails accountDetails) { + + return getProcessItemStatus(accountDetails, Keys.APPROVED_PROCESS_STATUS_CD); + + } + + private ProcessItemStatus getProcessItemStatus(AccountDetails accountDetails, String proccessStatusCd) { + + ProcessItemStatus processItemStatus = new ProcessItemStatus(); + processItemStatus.setAccountId(accountDetails.getAccountId()); + processItemStatus.setClientId(accountDetails.getClientId()); + processItemStatus.setEntDtm(DateUtils.getCurrentXmlDate()); + processItemStatus.setEntUserId(accountDetails.getClientId().toString()); + processItemStatus.setProcessStatusCd(proccessStatusCd); + return processItemStatus; + + } + + private String generateInvoiceNumber(String data) { + + try { + return serviceFacadeBean.getNextInvoiceNumber(data); + } catch (ca.bc.gov.ag.csows.services.NestedEjbException_Exception e) { + throw new EfilingSubmissionServiceException("Exception while generating next invoice number", e.getCause()); + } + + } + + private ServiceSession getServiceSession(String clientId) { + + logger.info("Getting session"); + + try { + UserSession userSession = serviceFacadeBean.createUserSession(clientId); + return serviceFacadeBean.createServiceSession(userSession, "request"); + } catch (ca.bc.gov.ag.csows.services.NestedEjbException_Exception e) { + throw new EfilingSubmissionServiceException("Exception while getting user session", e.getCause()); + } + + } + + private Service createEfilingService(FilingPackage efilingPackage, AccountDetails accountDetails, ServiceSession serviceSession) { + + logger.info("Creating service"); + + Service serviceToCreate = serviceMapper.toCreateService(efilingPackage, accountDetails, serviceSession); + + try { + return serviceFacadeBean.addService(serviceToCreate); + } catch (ca.bc.gov.ag.csows.services.NestedEjbException_Exception e) { + throw new EfilingSubmissionServiceException("Exception while creating efiling service", e.getCause()); + } + + } + + private void updatePaymentForService(Service service, Boolean feePaid, FinancialTransaction financialTransaction) { + + logger.info("Update payment"); + + service.setFeePaidYn(feePaid); + service.getTransactions().add(financialTransaction); + + try { + serviceFacadeBean.updateService(service); + } catch (ca.bc.gov.ag.csows.services.NestedEjbException_Exception e) { + throw new EfilingSubmissionServiceException("Exception while updating payment on service", e.getCause()); + } + + } + + private FinancialTransaction createPayment(EfilingPaymentService paymentService, Service service, BigDecimal submissionFeeAmount, String internalClientNumber) { + + logger.info("Create payment"); + + EfilingPayment efilingPayment = new EfilingPayment(service.getServiceId(), submissionFeeAmount, generateInvoiceNumber(Keys.INVOICE_PREFIX), internalClientNumber); + PaymentTransaction payment = paymentService.makePayment(efilingPayment); + return financialTransactionMapper.toTransaction(payment, service); + + } + + private BigDecimal filePackage(ca.bc.gov.ag.csows.filing.FilingPackage csoFilingPackage) { + + logger.info("Submit filing"); + + try { + return filingFacadeBean.submitFiling(csoFilingPackage); + } catch (NestedEjbException_Exception e) { + throw new EfilingSubmissionServiceException("Exception while filing package", e.getCause()); + } + + } + + private void updateServiceComplete(Service service) { + + logger.info("Update service"); + + service.setServiceReceivedDtm(DateUtils.getCurrentXmlDate()); + try { + serviceFacadeBean.updateService(service); + } catch (ca.bc.gov.ag.csows.services.NestedEjbException_Exception e) { + throw new EfilingSubmissionServiceException("Exception while updating payment on service", e.getCause()); + } + + } + + private XMLGregorianCalendar getComputedSubmittedDate(String location) { + + try { + return filingFacadeBean.calculateSubmittedDate(DateUtils.getCurrentXmlDate(), location); + } catch (NestedEjbException_Exception e) { + throw new EfilingSubmissionServiceException("Exception while retrieving submitted date", e.getCause()); + } + + } + + private void determineAutoProcessingFlagFromDocuments(FilingPackage efilingPackage, ca.bc.gov.ag.csows.filing.FilingPackage csoFilingPackage) { + + logger.info("Determining whether auto processing flag needs to be set"); + + String courtClass = efilingPackage.getCourt().getCourtClass(); + String courtLevel = efilingPackage.getCourt().getLevel(); + List documentTypeDetailsList = efilingDocumentService.getDocumentTypes(courtLevel, courtClass); + + List documents = csoFilingPackage.getDocuments(); + for(CivilDocument document : documents) { + String documentTypeCd = document.getDocumentTypeCd(); + for(DocumentTypeDetails documentTypeDetail : documentTypeDetailsList) { + if(documentTypeDetail.getType().equals(documentTypeCd) && documentTypeDetail.isAutoProcessing()) { + csoFilingPackage.setAutomatedProcessYn(true); + //Set document processing + document.setFilingProcessCd(AUTO_PROCESSING_STATE); + csoFilingPackage.setDelayProcessing(determineDelayProcessing(document)); + } else { + document.setFilingProcessCd(MANUAL_PROCESSING_STATE); + } + } + } + + } + + private Boolean determineDelayProcessing(CivilDocument document) { + + List milestones = document.getMilestones(); + Calendar actualSubmittedCalendar = Calendar.getInstance(); + Calendar calculatedCalendar = Calendar.getInstance(); + for(Milestones milestone : milestones) { + if(milestone.getMilestoneTypeCd().equals(CSO_ACTUAL_SUBMITTED_DATE)) { + actualSubmittedCalendar.setTime(xmlGregorian2Date(milestone.getMilestoneDtm())); + } else if (milestone.getMilestoneTypeCd().equals(CSO_CALCULATED_SUBMITTED_DATE)) { + calculatedCalendar.setTime(xmlGregorian2Date(milestone.getMilestoneDtm())); + } + } + + return (actualSubmittedCalendar.get(Calendar.YEAR) != calculatedCalendar.get(Calendar.YEAR)) || + (actualSubmittedCalendar.get(Calendar.MONTH) != calculatedCalendar.get(Calendar.MONTH)) || + (actualSubmittedCalendar.get(Calendar.DATE) != calculatedCalendar.get(Calendar.DATE)); + + } + + //This function will be used when cso has the valid flag available + private Boolean validateJson(Object json) { + + if (json == null) return false; + logger.info("Validate form data"); + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY); + JsonFactory factory = mapper.getFactory(); + JsonParser parser = factory.createParser(json.toString()); + mapper.readTree(parser); + logger.info("Form data is valid"); + return true; + } catch (Exception ex) { + logger.info("Form data is invalid"); + return false; + } + + } + + private BigDecimal setDocumentId(ActionDocument actionDocument) { + + if (actionDocument == null) return null; + + //Rejected documents do get the document id applied + if (actionDocument.getStatus().equalsIgnoreCase(CSO_DOCUMENT_REJECTED)) return null; + + return actionDocument.getDocumentId(); + + } + +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/Keys.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/Keys.java new file mode 100644 index 0000000000..e2250df69b --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/Keys.java @@ -0,0 +1,69 @@ +package ca.bc.gov.open.jag.efilingcsoclient; + +import java.math.BigDecimal; +import java.util.AbstractMap; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class Keys { + + private Keys() {} + + public static final String INVOICE_PREFIX = "15"; + public static final String TRANSACTION_TYPE_CD = "12"; + public static final String TRANSACTION_SUB_TYPE_CD = "BNST"; + public static final String RUSH_PROCESS_REASON_CD = "PRO"; + public static final String REQUEST_PROCESS_STATUS_CD = "RQST"; + public static final String APPROVED_PROCESS_STATUS_CD = "APP"; + public static final String SERVICE_SUBTYPE_CD = "FSVC"; + public static final String SERVICE_TYPE_CD = "DCFL"; + public static final String SUBMISSION_UPLOAD_STATE_CD = "CMPL"; + public static final String SUBMISSION_DOCUMENT_STATUS_TYPE_CD = "SUB"; + public static final String NOT_REQUIRED_PAYMENT_STATUS_CD = "NREQ"; + public static final String NOT_PROCESSED_PAYMENT_STATUS_CD = "NOPR"; + public static final String XML_DOCUMENT_INSTANCE_YN = "false"; + public static final String DOCUMENT_SUB_TYPE_CD = "ODOC"; + public static final String INDIVIDUAL_ROLE_TYPE_CD = "IND"; + public static final String ORGANIZATION_ROLE_TYPE_CD = "ORG"; + public static final String PARTY_TYPE_CD = "CLA"; + public static final String PARTY_NAME_TYPE_CD = "CUR"; + public static final String PRIVILEGE_CD = "UPDT"; + public static final String SUBMISSION_REPORT_NAME = "submission"; + public static final String RECEIPT_REPORT_NAME = "receipt"; + public static final String REGISTRY_NOTICE_NAME = "notice"; + public static final String SUBMISSION_REPORT_PARAMETER = "prm_package_id"; + public static final String PARAM_REPORT_PARAMETER = "param1"; + public static final Map IDENTITY_PROVIDERS = Stream.of( + new AbstractMap.SimpleImmutableEntry<>( "BCEID", BigDecimal.ONE ), + new AbstractMap.SimpleImmutableEntry<>( "BCSC", new BigDecimal(2) )) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + public static final String VIEW_ALL_PACKAGE_SUBPATH = "accounts/filingStatus.do?actionType=filterStatus&useFilter=ALL"; + public static final String CSO_USER_ROLE_FILE = "FILE"; + public static final String CSO_USER_ROLE_CAEF = "CAEF"; + public static final String CSO_ACTUAL_SUBMITTED_DATE = "ASUB"; + public static final String CSO_CALCULATED_SUBMITTED_DATE = "CSUB"; + + public static final Map RUSH_TYPES = Stream.of( + new AbstractMap.SimpleImmutableEntry<>( "PRO", "PRO" ), + new AbstractMap.SimpleImmutableEntry<>( "RULE", "CRTR" ), + new AbstractMap.SimpleImmutableEntry<>( "COURT", "CRTD" ), + new AbstractMap.SimpleImmutableEntry<>( "OTHER", "OTHR" )) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + + + public static final String CSO_DOCUMENT_REJECTED = "REJ"; + public static final String CSO_DOCUMENT_COURTESY_CORRECTED = "CCOR"; + public static final String CSO_DOCUMENT_SUBMITTED = "SUB"; + public static final String CSO_DOCUMENT_RE_SUBMITTED = "RSUB"; + public static final String CSO_DOCUMENT_REFERRED = "REF"; + public static final String PACKAGE_STATUS_PENDING = "Pending"; + public static final String PACKAGE_STATUS_ACTION_REQUIRED = "Action Required"; + public static final String PACKAGE_STATUS_COMPLETE = "Complete"; + + public static final String AUTO_PROCESSING_STATE = "AUTO"; + public static final String MANUAL_PROCESSING_STATE = "MANUAL"; + + public static final String OTHER_DOCUMENT_TYPE = "OTH"; + +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/SoapUtils.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/SoapUtils.java new file mode 100644 index 0000000000..4007bb09e9 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/SoapUtils.java @@ -0,0 +1,33 @@ +package ca.bc.gov.open.jag.efilingcsoclient; + +import ca.bc.gov.open.jag.efilingcommons.model.EfilingSoapClientProperties; +import org.apache.commons.lang3.StringUtils; +import org.apache.cxf.ext.logging.LoggingInInterceptor; +import org.apache.cxf.ext.logging.LoggingOutInterceptor; +import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; + +public class SoapUtils { + + private SoapUtils() {} + + public static T getPort(Class type, EfilingSoapClientProperties efilingSoapClientProperties, boolean debugEnabled) { + JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean(); + jaxWsProxyFactoryBean.setServiceClass(type); + jaxWsProxyFactoryBean.setAddress(efilingSoapClientProperties.getUri()); + if(StringUtils.isNotBlank(efilingSoapClientProperties.getUserName())) + jaxWsProxyFactoryBean.setUsername(efilingSoapClientProperties.getUserName()); + if(StringUtils.isNotBlank(efilingSoapClientProperties.getPassword())) + jaxWsProxyFactoryBean.setPassword(efilingSoapClientProperties.getPassword()); + + if(debugEnabled) { + LoggingInInterceptor loggingInInterceptor = new LoggingInInterceptor(); + loggingInInterceptor.setPrettyLogging(true); + LoggingOutInterceptor loggingOutInterceptor = new LoggingOutInterceptor(); + loggingOutInterceptor.setPrettyLogging(true); + jaxWsProxyFactoryBean.getOutInterceptors().add(0, loggingOutInterceptor); + jaxWsProxyFactoryBean.getInInterceptors().add(0, loggingInInterceptor); + } + + return type.cast(jaxWsProxyFactoryBean.create()); + } +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/config/CsoProperties.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/config/CsoProperties.java new file mode 100644 index 0000000000..752b94af03 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/config/CsoProperties.java @@ -0,0 +1,40 @@ +package ca.bc.gov.open.jag.efilingcsoclient.config; + +public class CsoProperties { + + private String fileServerHost; + + private String csoBasePath; + + private String csoPackagePath; + + private boolean debugEnabled = false; + + public String getFileServerHost() { + return fileServerHost; + } + + public void setFileServerHost(String fileServerHost) { + this.fileServerHost = fileServerHost; + } + + public String getCsoBasePath() { + return csoBasePath; + } + + public void setCsoBasePath(String csoBasePath) { + this.csoBasePath = csoBasePath; + } + + public String getCsoPackagePath() { return csoPackagePath; } + + public void setCsoPackagePath(String csoPackagePath) { this.csoPackagePath = csoPackagePath; } + + public boolean isDebugEnabled() { + return debugEnabled; + } + + public void setDebugEnabled(boolean debugEnabled) { + this.debugEnabled = debugEnabled; + } +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/AccountDetailsMapper.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/AccountDetailsMapper.java new file mode 100644 index 0000000000..a6323660a5 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/AccountDetailsMapper.java @@ -0,0 +1,19 @@ +package ca.bc.gov.open.jag.efilingcsoclient.mappers; + +import ca.bc.gov.ag.csows.accounts.ClientProfile; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper +public interface AccountDetailsMapper { + + @Mapping(target = "accountId", source = "clientProfile.accountId") + @Mapping(target = "clientId", source = "clientProfile.clientId") + @Mapping(target = "internalClientNumber", source = "clientProfile.client.internalClientNo") + @Mapping(target = "fileRolePresent", source = "fileRolePresent") + @Mapping(target = "universalId", source = "universalId") + @Mapping(target = "cardRegistered", source = "clientProfile.client.registeredCreditCardYnBoolean") + AccountDetails toAccountDetails(String universalId, ClientProfile clientProfile, Boolean fileRolePresent); + +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/ClientProfileMapper.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/ClientProfileMapper.java new file mode 100644 index 0000000000..c7b8cdd482 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/ClientProfileMapper.java @@ -0,0 +1,11 @@ +package ca.bc.gov.open.jag.efilingcsoclient.mappers; + +import ca.bc.gov.ag.csows.accounts.ClientProfile; +import org.mapstruct.Mapper; + +@Mapper +public interface ClientProfileMapper { + + ClientProfile toClientProfile(ca.bc.gov.ag.csows.accounts.ClientProfile previewClientProfile); + +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/CsoPartyMapper.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/CsoPartyMapper.java new file mode 100644 index 0000000000..738eb63950 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/CsoPartyMapper.java @@ -0,0 +1,38 @@ +package ca.bc.gov.open.jag.efilingcsoclient.mappers; + +import ca.bc.gov.ag.csows.filing.CsoParty; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.Individual; +import ca.bc.gov.open.jag.efilingcommons.model.Organization; +import ca.bc.gov.open.jag.efilingcsoclient.Keys; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper +public interface CsoPartyMapper { + + @Mapping(target = "partyTypeCd", constant = Keys.INDIVIDUAL_ROLE_TYPE_CD) + @Mapping(target = "roleTypeCd", source = "individual.roleTypeCd") + @Mapping(target = "current.entDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + @Mapping(target = "current.entUserId", source = "accountDetails.clientId") + @Mapping(target = "current.firstGivenNm", source = "firstName") + @Mapping(target = "current.identificationDetailSeqNo", source = "sequenceNumber") + @Mapping(target = "current.nameTypeCd", source= "individual.nameTypeCd", defaultValue = Keys.PARTY_NAME_TYPE_CD) + @Mapping(target = "current.secondGivenNm", source = "individual.middleName") + @Mapping(target = "current.surnameNm", source = "lastName") + @Mapping(target = "entUserId", source = "accountDetails.clientId") + @Mapping(target = "entDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + CsoParty toEfilingParties(Integer sequenceNumber, Individual individual, AccountDetails accountDetails, String firstName, String lastName); + + @Mapping(target = "partyTypeCd", constant = Keys.ORGANIZATION_ROLE_TYPE_CD) + @Mapping(target = "roleTypeCd", source = "organization.roleTypeCd") + @Mapping(target = "current.entDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + @Mapping(target = "current.entUserId", source = "accountDetails.clientId") + @Mapping(target = "current.organizationNm", source = "organization.name") + @Mapping(target = "current.identificationDetailSeqNo", source = "sequenceNumber") + @Mapping(target = "current.nameTypeCd", source= "organization.nameTypeCd", defaultValue = Keys.PARTY_NAME_TYPE_CD) + @Mapping(target = "entUserId", source = "accountDetails.clientId") + @Mapping(target = "entDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + CsoParty toEfilingOrganization(Integer sequenceNumber, Organization organization, AccountDetails accountDetails); + +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/DocumentMapper.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/DocumentMapper.java new file mode 100644 index 0000000000..aad2eeb6a1 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/DocumentMapper.java @@ -0,0 +1,92 @@ +package ca.bc.gov.open.jag.efilingcsoclient.mappers; + +import ca.bc.gov.ag.csows.filing.*; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.Document; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; +import ca.bc.gov.open.jag.efilingcsoclient.Keys; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +import javax.xml.datatype.XMLGregorianCalendar; +import java.math.BigDecimal; +import java.util.List; + +import static ca.bc.gov.open.jag.efilingcsoclient.Keys.CSO_ACTUAL_SUBMITTED_DATE; +import static ca.bc.gov.open.jag.efilingcsoclient.Keys.CSO_CALCULATED_SUBMITTED_DATE; + +@Mapper +public interface DocumentMapper { + //Civil Document Mappings + @Mapping(target = "packageSeqNo", source = "index") + @Mapping(target = "documentId", source = "documentId") + @Mapping(target = "amendsAnotherDocumentYn", source = "document.isAmendment", defaultValue = "false") + @Mapping(target = "clientFileNameTxt", source = "document.name") + @Mapping(target = "documentSubtypeCd", constant = Keys.DOCUMENT_SUB_TYPE_CD) + @Mapping(target = "documentTypeCd", source = "document.type") + @Mapping(target = "entUserId", source = "accountDetails.clientId") + @Mapping(target = "entDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + @Mapping(target = "filePath", source = "document.serverFileName") + @Mapping(target = "fileServer", source = "serverHost") + @Mapping(target = "uploadStateCd", constant = Keys.SUBMISSION_UPLOAD_STATE_CD) + @Mapping(target = "jsonObject", expression = "java(java.lang.String.valueOf(document.getData()))") + @Mapping(target = "xmlDocumentInstanceYn", constant = Keys.XML_DOCUMENT_INSTANCE_YN) + @Mapping(target = "milestones", source = "milestones") + @Mapping(target = "payments", source = "payments") + @Mapping(target = "statuses", source = "statuses") + @Mapping(target = "parentDocumentId", source = "document.documentId") + CivilDocument toEfilingDocument( + Integer index, + Document document, + AccountDetails accountDetails, + FilingPackage filingPackage, + String serverHost, + List milestones, + List payments, + List statuses, + BigDecimal documentId); + + @Mapping(target = "entUserId", source = "accountDetails.clientId") + @Mapping(target = "entDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + @Mapping(target = "milestoneDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + @Mapping(target = "milestoneTypeCd", constant = CSO_ACTUAL_SUBMITTED_DATE) + @Mapping(target = "milestoneSeqNo", constant = "1") + Milestones toActualSubmittedDate(AccountDetails accountDetails); + + @Mapping(target = "entUserId", source = "accountDetails.clientId") + @Mapping(target = "entDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + @Mapping(target = "milestoneDtm", source = "submittedDate") + @Mapping(target = "milestoneTypeCd", constant = CSO_CALCULATED_SUBMITTED_DATE) + @Mapping(target = "milestoneSeqNo", constant = "2") + Milestones toComputedSubmittedDate(AccountDetails accountDetails, XMLGregorianCalendar submittedDate); + + @Mapping(target = "entUserId", source = "accountDetails.clientId") + @Mapping(target = "entDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + @Mapping(target = "paymentStatusCd", source = "paymentStatus") + @Mapping(target = "statutoryFeeAmt", source = "document.statutoryFeeAmount", defaultValue = "0") + @Mapping(target = "paymentSeqNo", constant = "1") + @Mapping(target = "documentId", ignore = true) + DocumentPayments toEfilingDocumentPayment(Document document, AccountDetails accountDetails, String paymentStatus); + + @Mapping(target = "entUserId", source = "accountDetails.clientId") + @Mapping(target = "entDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + @Mapping(target = "statusDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + @Mapping(target = "documentStatusTypeCd", constant = Keys.SUBMISSION_DOCUMENT_STATUS_TYPE_CD) + @Mapping(target = "documentStatusSeqNo", constant = "1") + @Mapping(target = "documentId", ignore = true) + DocumentStatuses toEfilingDocumentStatus(Document document, AccountDetails accountDetails); + + //Rush Processing Document + @Mapping(target = "processItemSeqNo", source = "index") + @Mapping(target = "clientFileNm", source = "document.name") + @Mapping(target = "tempFileName", source = "document.serverFileName") + @Mapping(target = "entUserId", source = "accountDetails.clientId") + @Mapping(target = "entDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + @Mapping(target = "fileServer", source = "serverHost") + ProcessSupportDocument toEfilingRushProcessingDocument( + Integer index, + Document document, + AccountDetails accountDetails, + String serverHost); + +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/FilePackageMapper.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/FilePackageMapper.java new file mode 100644 index 0000000000..0cde756656 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/FilePackageMapper.java @@ -0,0 +1,57 @@ +package ca.bc.gov.open.jag.efilingcsoclient.mappers; + +import ca.bc.gov.ag.csows.filing.status.File; +import ca.bc.gov.ag.csows.filing.status.PackageParties; +import ca.bc.gov.ag.csows.filing.status.ProcessSupportDocument; +import ca.bc.gov.ag.csows.filing.status.RushOrderRequestItem; +import ca.bc.gov.open.jag.efilingcommons.model.Individual; +import ca.bc.gov.open.jag.efilingcommons.model.Organization; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewDocument; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewFilingPackage; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.RushDocument; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +import java.util.List; + + +@Mapper +public interface FilePackageMapper { + + @Mapping(target = "court.courtClass", source = "filePackage.courtClassCd") + @Mapping(target = "court.fileNumber", source = "filePackage.courtFileNo") + @Mapping(target = "court.level", source = "filePackage.courtLevelCd") + @Mapping(target = "court.locationCd", source = "filePackage.courtLocationCd") + @Mapping(target = "court.locationName", source = "filePackage.courtLocationName") + @Mapping(target = "documents", source = "filePackage.files") + @Mapping(target = "packageLinks.packageHistoryUrl", source = "csoHistoryLink") + @Mapping(target = "parties", source = "individuals") + @Mapping(target = "organizations", source = "organizations") + @Mapping(target = "rushOrder", source = "rushOrderRequestItem") + @Mapping(target = "rushOrder.contactEmailTxt", source = "filePackage.procRequest.contactEmailTxt") + @Mapping(target = "rushOrder.contactFirstGivenNm", source = "filePackage.procRequest.contactFirstGivenNm") + @Mapping(target = "rushOrder.contactOrganizationNm", source = "filePackage.procRequest.contactOrganizationNm") + @Mapping(target = "rushOrder.contactPhoneNo", source = "filePackage.procRequest.contactPhoneNo") + @Mapping(target = "rushOrder.contactSurnameNm", source = "filePackage.procRequest.contactSurnameNm") + @Mapping(target = "rushOrder.ctryId", source = "filePackage.procRequest.ctryId") + @Mapping(target = "rushOrder.processingCommentTxt", source = "filePackage.procRequest.processingCommentTxt") + @Mapping(target = "rushOrder.countryDsc", source = "countryDsc") + ReviewFilingPackage toFilingPackage(ca.bc.gov.ag.csows.filing.status.FilePackage filePackage, String csoHistoryLink, List individuals, List organizations, RushOrderRequestItem rushOrderRequestItem, String countryDsc, String status); + + List toDocuments(List file); + + //TODO: extend document to add additional fields + ReviewDocument toDocument(File file); + + + @Mapping(target = "middleName", source = "secondName") + @Mapping(target = "lastName", source = "surname") + Individual toParty(PackageParties packageParties); + + + @Mapping(target = "name", source = "organizationName") + Organization toOrganization(PackageParties packageParties); + + RushDocument toRushDocument(ProcessSupportDocument processSupportDocument); + +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/FilingPackageMapper.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/FilingPackageMapper.java new file mode 100644 index 0000000000..d5e52c1cbc --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/FilingPackageMapper.java @@ -0,0 +1,52 @@ +package ca.bc.gov.open.jag.efilingcsoclient.mappers; + +import ca.bc.gov.ag.csows.filing.CivilDocument; +import ca.bc.gov.ag.csows.filing.CsoParty; +import ca.bc.gov.ag.csows.filing.FilingPackage; +import ca.bc.gov.ag.csows.filing.PackageAuthority; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +import javax.xml.datatype.XMLGregorianCalendar; +import java.math.BigDecimal; +import java.util.List; + +@Mapper +public interface FilingPackageMapper { + + @Mapping(target = "existingCourtFileYn", expression = "java(org.apache.commons.lang3.StringUtils.isNotBlank(filingPackage.getCourt().getFileNumber()))") + @Mapping(target = "processingCompleteYn", constant = "false") + @Mapping(target = "feeExemptYn", expression = "java(!(filingPackage.getSubmissionFeeAmount() != null && filingPackage.getSubmissionFeeAmount().compareTo(BigDecimal.ZERO) > 0))") + @Mapping(target = "cfcsaYn", constant = "false") + @Mapping(target = "notificationRequiredYn", constant = "true") + @Mapping(target = "resubmissionOfPackageId", source = "filingPackage.packageNumber") + + @Mapping(target = "entDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + + @Mapping(target = "courtFileNo", source = "filingPackage.court.fileNumber") + @Mapping(target = "ldcxCourtClassCd", source = "filingPackage.court.courtClass") + @Mapping(target = "ldcxCourtLevelCd", source = "filingPackage.court.level") + @Mapping(target = "submittedToAgenId", source = "filingPackage.court.agencyId") + @Mapping(target = "ldcxCourtDivisionCd", source = "filingPackage.court.division") + @Mapping(target = "applicationCd", source = "filingPackage.applicationCode") + @Mapping(target = "automatedProcessYn", source = "filingPackage.autoProcessing") + + @Mapping(target = "entUserId", source = "accountDetails.clientId") + @Mapping(target = "submittedByAccountId", source = "accountDetails.accountId") + @Mapping(target = "submittedByClientId", source = "accountDetails.clientId") + + @Mapping(target = "serviceId", source = "serviceId") + @Mapping(target = "submitDtm", source = "submittedDate") + @Mapping(target = "documents", source = "documents") + @Mapping(target = "parties", source = "csoParties") + @Mapping(target = "packageControls", source = "packageControls") + FilingPackage toFilingPackage( + ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage filingPackage, + AccountDetails accountDetails, + BigDecimal serviceId, + XMLGregorianCalendar submittedDate, + List documents, + List csoParties, + List packageControls); +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/FinancialTransactionMapper.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/FinancialTransactionMapper.java new file mode 100644 index 0000000000..a5be4214cc --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/FinancialTransactionMapper.java @@ -0,0 +1,44 @@ +package ca.bc.gov.open.jag.efilingcsoclient.mappers; + +import ca.bc.gov.ag.csows.services.FinancialTransaction; +import ca.bc.gov.ag.csows.services.Service; +import ca.bc.gov.open.jag.efilingcommons.model.PaymentTransaction; +import ca.bc.gov.open.jag.efilingcommons.utils.DateUtils; +import ca.bc.gov.open.jag.efilingcsoclient.Keys; +import org.joda.time.DateTime; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.Named; +import org.mapstruct.ReportingPolicy; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.XMLGregorianCalendar; + +@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE) +public interface FinancialTransactionMapper { + + @Mapping(target = "approvalCd", source = "efilingTransaction.approvalCd") + @Mapping(target = "ecommerceTransactionId", source = "efilingTransaction.ecommerceTransactionId") + @Mapping(target = "transactionAmt", source = "efilingTransaction.transactionAmt") + @Mapping(target = "transactonDtm", source = "efilingTransaction.transactonDtm" , qualifiedByName = "toXmlGregorianDate") + @Mapping(target = "transactionStateCd", source = "efilingTransaction.transactionStateCd") + @Mapping(target = "transactionTypeCd", constant = Keys.TRANSACTION_TYPE_CD) + @Mapping(target = "transactionSubtypeCd", constant = Keys.TRANSACTION_SUB_TYPE_CD) + @Mapping(target = "creditCardTypeCd", source = "efilingTransaction.creditCardTypeCd") + @Mapping(target = "processDt", source = "efilingTransaction.processDt" , qualifiedByName = "toXmlGregorianDate") + @Mapping(target = "invoiceNo", source = "efilingTransaction.invoiceNo") + @Mapping(target = "entDtm", source = "efilingTransaction.entDtm", qualifiedByName = "toXmlGregorianDate") + @Mapping(target = "entUserId", source = "service.entUserId") + @Mapping(target = "serviceId", source = "service.serviceId") + @Mapping(target = "updDtm", ignore = true) + @Mapping(target = "updUserId", ignore = true) + FinancialTransaction toTransaction(PaymentTransaction efilingTransaction, Service service); + + + @Named("toXmlGregorianDate") + public static XMLGregorianCalendar toXmlGregorianDate(DateTime dateTime) throws DatatypeConfigurationException { + return DateUtils.getXmlDate(dateTime); + } + + +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/PackageAuthorityMapper.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/PackageAuthorityMapper.java new file mode 100644 index 0000000000..b728434b74 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/PackageAuthorityMapper.java @@ -0,0 +1,20 @@ +package ca.bc.gov.open.jag.efilingcsoclient.mappers; + +import ca.bc.gov.ag.csows.filing.PackageAuthority; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcsoclient.Keys; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper +public interface PackageAuthorityMapper { + + @Mapping(target = "clientId", source = "accountDetails.clientId") + @Mapping(target = "accountId", source = "accountDetails.accountId") + @Mapping(target = "entUserId", source = "accountDetails.clientId") + @Mapping(target = "entDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + @Mapping(target = "privilegeCd", constant = Keys.PRIVILEGE_CD) + PackageAuthority toPackageAuthority(AccountDetails accountDetails); + + +} diff --git a/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/ServiceMapper.java b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/ServiceMapper.java new file mode 100644 index 0000000000..b9cd9e6e1b --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/java/ca/bc/gov/open/jag/efilingcsoclient/mappers/ServiceMapper.java @@ -0,0 +1,29 @@ +package ca.bc.gov.open.jag.efilingcsoclient.mappers; + +import ca.bc.gov.ag.csows.services.Service; +import ca.bc.gov.ag.csows.services.ServiceSession; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; +import ca.bc.gov.open.jag.efilingcsoclient.Keys; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper +public interface ServiceMapper { + + @Mapping(target = "accountId", source = "accountDetails.accountId") + @Mapping(target = "clientId", source = "accountDetails.clientId") + @Mapping(target = "entDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + @Mapping(target = "courtFileNo", source = "filingPackage.court.fileNumber") + @Mapping(target = "entUserId", source = "accountDetails.clientId") + @Mapping(target = "serviceReceivedDtm", expression = "java(ca.bc.gov.open.jag.efilingcommons.utils.DateUtils.getCurrentXmlDate())") + @Mapping(target = "serviceSubtypeCd", constant = Keys.SERVICE_SUBTYPE_CD) + @Mapping(target = "serviceTypeCd", constant = Keys.SERVICE_TYPE_CD) + @Mapping(target = "feePaidYn", constant = "false") + @Mapping(target = "userSessionId", source = "serviceSession.userSessionId") + @Mapping(target = "serviceSessionId", source = "serviceSession.serviceSessionId") + @Mapping(target = "updUserId", ignore = true) + @Mapping(target = "updDtm", ignore = true) + Service toCreateService(FilingPackage filingPackage, AccountDetails accountDetails, ServiceSession serviceSession); + +} diff --git a/src/backend/libs/efiling-account-client/src/main/resources/wsdl/AccountFacade.wsdl b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/AccountFacade.wsdl similarity index 86% rename from src/backend/libs/efiling-account-client/src/main/resources/wsdl/AccountFacade.wsdl rename to src/backend/libs/efiling-cso-client/src/main/resources/wsdl/AccountFacade.wsdl index 4007adaa77..871e5cfd6d 100644 --- a/src/backend/libs/efiling-account-client/src/main/resources/wsdl/AccountFacade.wsdl +++ b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/AccountFacade.wsdl @@ -1,4 +1,6 @@ - + @@ -9,12 +11,16 @@ + + + + @@ -25,6 +31,8 @@ + + @@ -40,6 +48,8 @@ + + @@ -48,6 +58,8 @@ + + @@ -67,36 +79,14 @@ - + - - - - - - - - - - - - - - - - - - - - - + - - - + @@ -114,7 +104,9 @@ + + @@ -140,43 +132,147 @@ + - - - - - + + + + + + + + + + + + + + + - + + + + + + + - - - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -186,14 +282,18 @@ + + + + @@ -222,54 +322,45 @@ - + - - - + + + + + + + + - + - + - + + + + - + - + + - - - - - - - - - - - - - - - - - - - + - + @@ -289,41 +380,17 @@ - - - - - - - - - - - - - - - - + + - + - - - - - - - - - - @@ -335,61 +402,57 @@ - - - - + - + - - - - + - + - + - + - + - + - + + + + + + + + - + - - - - - - - - - + - + - - - + + + + + + - + - + @@ -402,171 +465,197 @@ - - - - - - - - - + - + - + - + - + - + - + + + + + + + - + - + - + - - - + - + - - + - + - + - + - + + + + + + + - + - + - + - + + + - + - + - - - - - - + + - + - + - + - - + - + - + - + - + - + - + - + - + - + + + + - - - - + - + + + + - + - - + + + + + + + - + - + - + - - + - + - + - + + + + + + + + + - + + + + - + + + + + + + + + + + @@ -577,265 +666,281 @@ - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + + + + + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + + + + + + + + + + + + + - - + + + + + + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + + + + + + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + + + + - - + + - - - - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - - - - - - - - - - - - - - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + @@ -843,14 +948,14 @@ - - - + + + - - - + + + @@ -858,64 +963,87 @@ - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + + + + + - - - + + + + + + + + + + + + + + + + + + + + + + @@ -923,356 +1051,392 @@ - - - + + + + + + + + + + + + + + + + + + - - - + + + - - - + + + - - - + + + - + - + - + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + + + + + + + + + + - + - + - + - + - + - + + + + + + + + + + - + - + - + - + - + - + @@ -1291,48 +1455,84 @@ - + - + - + - + - + - + - + - + - + - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/CSOSearch.asmx.wsdl b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/CSOSearch.asmx.wsdl new file mode 100644 index 0000000000..47a45d884a --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/CSOSearch.asmx.wsdl @@ -0,0 +1,1004 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Returns the hearing list for the specified location and hearing day. + + + + + Get a list of lookup items based on type. Types include: Appeal From Civil, Appeal From Criminal, Appeal Type, Bookset Type, Case Status, Case Type, Chambers Decision, Chambers Hearing Method, City, Court Decision, Disposition, File Location, Filing Format, Hearing Location, Hearing Type, Judgment Type, Party Type, Previous Court Level, Previous Court Location, Prompt Type, Province, Representation, Role in Previous Court, Salutation, Security Flags, User Location, User Role. + + + + + Determines whether the hearing list for the specified location and hearing day exists. + + + + + Search for a case by case number. + + + + + Search for cases based on a party as individual (first name and/or last name), intCaseTypeId (where 0 = any case type), intPartyRoleId (where 0 = any party role), intCaseStatusId (where -1 = Active and Inactive, 0 = any case status), intResultPage, intRecordsPerPage and intMaxResultRecords. If a page is requested that is beyond the intMaxResultRecords range, or outside the search results, the last search result will be returned. + + + + + Search for cases based on a party as individual (first name and/or last name), intCaseTypeId (where 0 = any case type), intPartyRoleId (where 0 = any party role), and intCaseStatusId (where -1 = Active and Inactive, 0 = any case status) and and intMaxResultRecords. Return result count. + + + + + Search for cases based on a party as organization, intCaseTypeId (where 0 = any case type), intPartyRoleId (where 0 = any party role), intCaseStatusId (where -1 = Active and Inactive, 0 = any case status), intResultPage, intRecordsPerPage and intMaxResultRecords. If a page is requested that is beyond the intMaxResultRecords range, or outside the search results, the last search result will be returned. + + + + + Search for cases based on a party as organization, intCaseTypeId (where 0 = any case type), intPartyRoleId (where 0 = any party role), intCaseStatusId (where -1 = Active and Inactive, 0 = any case status) and and intMaxResultRecords. Return result count. + + + + + View the basics of a case. + + + + + View a case with chambers hearing information. + + + + + View a case with court hearing information. + + + + + View a case with filing information. + + + + + View a case with party information. + + + + + View a case summary. + + + + + Search for a case by case number for use with eFiling. Limited information will be displayed for purposes of verification only. Note: Security Type and User Access should never be displayed on public servers + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/Csows.wsdl b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/Csows.wsdl new file mode 100644 index 0000000000..0117d2a5a3 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/Csows.wsdl @@ -0,0 +1,2643 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/backend/libs/efiling-submission-client/src/main/resources/wsdl/FilingFacade.wsdl b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/FilingFacade.wsdl similarity index 82% rename from src/backend/libs/efiling-submission-client/src/main/resources/wsdl/FilingFacade.wsdl rename to src/backend/libs/efiling-cso-client/src/main/resources/wsdl/FilingFacade.wsdl index fbd85c1b32..0b11dd5aa5 100644 --- a/src/backend/libs/efiling-submission-client/src/main/resources/wsdl/FilingFacade.wsdl +++ b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/FilingFacade.wsdl @@ -1,12 +1,18 @@ - + + + + + + + @@ -19,10 +25,16 @@ + + + + + + @@ -39,6 +51,8 @@ + + @@ -89,20 +103,24 @@ + + + + @@ -114,6 +132,7 @@ + @@ -124,16 +143,23 @@ + + + + + + + @@ -527,6 +553,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -540,6 +593,7 @@ + @@ -557,6 +611,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -602,6 +725,7 @@ + @@ -609,6 +733,17 @@ + + + + + + + + + + + @@ -700,6 +835,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -732,19 +893,6 @@ - - - - - - - - - - - - - @@ -817,6 +965,16 @@ + + + + + + + + + + @@ -833,6 +991,7 @@ + @@ -866,6 +1025,9 @@ + + + @@ -881,18 +1043,33 @@ + + + + + + + + + + + + + + + @@ -908,15 +1085,24 @@ + + + + + + + + + @@ -947,6 +1133,9 @@ + + + @@ -956,6 +1145,9 @@ + + + @@ -971,6 +1163,9 @@ + + + @@ -980,6 +1175,9 @@ + + + @@ -1004,6 +1202,9 @@ + + + @@ -1020,6 +1221,11 @@ + + + + + @@ -1035,6 +1241,21 @@ + + + + + + + + + + + + + + + @@ -1060,6 +1281,11 @@ + + + + + @@ -1083,6 +1309,11 @@ + + + + + @@ -1128,6 +1359,11 @@ + + + + + @@ -1157,6 +1393,18 @@ + + + + + + + + + + + + @@ -1193,6 +1441,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1253,6 +1537,18 @@ + + + + + + + + + + + + @@ -1307,6 +1603,18 @@ + + + + + + + + + + + + @@ -1415,6 +1723,18 @@ + + + + + + + + + + + + diff --git a/src/backend/libs/efiling-status-client/src/main/resources/wsdl/FilingStatusFacade.wsdl b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/FilingStatusFacade.wsdl similarity index 96% rename from src/backend/libs/efiling-status-client/src/main/resources/wsdl/FilingStatusFacade.wsdl rename to src/backend/libs/efiling-cso-client/src/main/resources/wsdl/FilingStatusFacade.wsdl index 96ad9af9c9..9e6decc210 100644 --- a/src/backend/libs/efiling-status-client/src/main/resources/wsdl/FilingStatusFacade.wsdl +++ b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/FilingStatusFacade.wsdl @@ -1,6 +1,6 @@ - + @@ -53,7 +53,8 @@ - + + @@ -128,11 +129,21 @@ + + + + + + + + + + @@ -172,6 +183,7 @@ + @@ -210,6 +222,7 @@ + @@ -228,7 +241,8 @@ - + + @@ -246,6 +260,8 @@ + + @@ -278,13 +294,16 @@ + + + @@ -477,11 +496,14 @@ - + - + - + + + + diff --git a/src/backend/libs/efiling-lookup-client/src/main/resources/wsdl/LookupFacade.wsdl b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/LookupFacade.wsdl similarity index 85% rename from src/backend/libs/efiling-lookup-client/src/main/resources/wsdl/LookupFacade.wsdl rename to src/backend/libs/efiling-cso-client/src/main/resources/wsdl/LookupFacade.wsdl index d64321b116..2b172c75ff 100644 --- a/src/backend/libs/efiling-lookup-client/src/main/resources/wsdl/LookupFacade.wsdl +++ b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/LookupFacade.wsdl @@ -1,6 +1,6 @@ - + @@ -17,6 +17,10 @@ + + + + @@ -29,6 +33,8 @@ + + @@ -37,6 +43,8 @@ + + @@ -54,6 +62,8 @@ + + @@ -61,6 +71,22 @@ + + + + + + + + + + + + + + + + @@ -161,6 +187,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -210,6 +263,14 @@ + + + + + + + + @@ -291,6 +352,14 @@ + + + + + + + + @@ -319,18 +388,6 @@ - - - - - - - - - - - - @@ -375,6 +432,14 @@ + + + + + + + + @@ -481,6 +546,9 @@ + + + @@ -496,12 +564,18 @@ + + + + + + @@ -511,6 +585,9 @@ + + + @@ -526,6 +603,9 @@ + + + @@ -541,6 +621,12 @@ + + + + + + @@ -559,9 +645,18 @@ + + + + + + + + + @@ -593,6 +688,11 @@ + + + + + @@ -638,6 +738,11 @@ + + + + + @@ -653,6 +758,11 @@ + + + + + @@ -693,6 +803,11 @@ + + + + + @@ -728,6 +843,11 @@ + + + + + @@ -758,6 +878,18 @@ + + + + + + + + + + + + @@ -830,6 +962,18 @@ + + + + + + + + + + + + @@ -842,12 +986,12 @@ - + - + - + @@ -890,6 +1034,18 @@ + + + + + + + + + + + + @@ -986,6 +1142,18 @@ + + + + + + + + + + + + @@ -1070,6 +1238,18 @@ + + + + + + + + + + + + diff --git a/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/ReportService.wsdl b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/ReportService.wsdl new file mode 100644 index 0000000000..a29d515912 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/ReportService.wsdl @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/backend/libs/efiling-account-client/src/main/resources/wsdl/RoleRegistry.wsdl b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/RoleRegistry.wsdl similarity index 71% rename from src/backend/libs/efiling-account-client/src/main/resources/wsdl/RoleRegistry.wsdl rename to src/backend/libs/efiling-cso-client/src/main/resources/wsdl/RoleRegistry.wsdl index 48da519bed..b8e0268e2b 100644 --- a/src/backend/libs/efiling-account-client/src/main/resources/wsdl/RoleRegistry.wsdl +++ b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/RoleRegistry.wsdl @@ -1,4 +1,9 @@ - + @@ -49,12 +54,31 @@ + + + + + + + + + + + + + + + + + + + @@ -67,7 +91,14 @@ + + + + + + + @@ -79,6 +110,15 @@ + + + + + + + + + diff --git a/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/ServiceFacade.wsdl b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/ServiceFacade.wsdl new file mode 100644 index 0000000000..53c1f7b96f --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/main/resources/wsdl/ServiceFacade.wsdl @@ -0,0 +1,1804 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/SoapUtilsTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/SoapUtilsTest.java new file mode 100644 index 0000000000..5ce0288128 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/SoapUtilsTest.java @@ -0,0 +1,49 @@ +package ca.bc.gov.open.jag.efilingcsoclient; + +import ca.bc.gov.ag.csows.filing.status.FilingStatusFacadeBean; +import ca.bc.gov.open.jag.efilingcommons.model.Clients; +import ca.bc.gov.open.jag.efilingcommons.model.EfilingSoapClientProperties; +import ca.bc.gov.open.jag.efilingcsoclient.config.CsoProperties; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class SoapUtilsTest { + + @Test + @DisplayName("OK: should create a soap port") + public void withValidConfigShouldCreateSoapPort() { + + EfilingSoapClientProperties client = new EfilingSoapClientProperties(); + client.setClient(Clients.STATUS); + client.setUserName("username"); + client.setPassword("password"); + client.setUri("http://localhost:8080"); + CsoProperties csoProperties = new CsoProperties(); + csoProperties.setDebugEnabled(false); + + Assertions.assertDoesNotThrow(() -> SoapUtils.getPort(FilingStatusFacadeBean.class, client, false)); + + + } + + @Test + @DisplayName("OK: should create a soap port with logging enabled") + public void withValidConfigShouldCreateSoapPortWithLoggingEnabled() { + + EfilingSoapClientProperties client = new EfilingSoapClientProperties(); + client.setClient(Clients.STATUS); + client.setUserName("username"); + client.setPassword("password"); + client.setUri("http://localhost:8080"); + CsoProperties csoProperties = new CsoProperties(); + csoProperties.setDebugEnabled(true); + + Assertions.assertDoesNotThrow(() -> SoapUtils.getPort(FilingStatusFacadeBean.class, client, true)); + + + } + +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/TestHelpers.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/TestHelpers.java new file mode 100644 index 0000000000..2dd2addeec --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/TestHelpers.java @@ -0,0 +1,75 @@ +package ca.bc.gov.open.jag.efilingcsoclient; + +import ca.bc.gov.ag.csows.services.Service; +import org.joda.time.DateTime; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import java.math.BigDecimal; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.UUID; + +public class TestHelpers { + public static final UUID CASE_1 = UUID.fromString("77da92db-0791-491e-8c58-1a969e67d2fe"); + public static final String CLIENT_REFERENCE_TXT = "CLIENTREFERENCETXT"; + public static final String COURT_FILE_NUMBER = "COURTFILENUMBER"; + public static final String DOCUMENTS_PROCESSED = "DOCUMENTPROCESSED"; + public static final DateTime DATE_TIME = DateTime.parse("2018-05-05T11:50:55"); + public static final Date DATE = DateTime.parse("2018-05-05T11:50:55").toDate(); + public static final String SERVICE_RECEIVED_DTM_TEXT = "SERVICERECIEVEDTXT"; + public static final String SERVICE_SUBTYPE_CD = "SUBTYPE"; + public static final String SERVICE_TYPE_CD = "TYPE_CD"; + public static final String SERVICE_TYPE_DESC = "TYPE_DESC"; + private static final String APPROVAL_CD = "APPROVALCD"; + private static final String BC_ONLINE_ACCOUNT_NO = "bcOnlineAccountNo"; + private static final String BC_ONLINE_FEE_CODE_TXT = "bcOnlineFeeCodeTxt"; + private static final String BC_ONLINE_RESPONSE_TYPE_TXT = "bcOnlineResponseTypeTxt"; + private static final String BC_ONLINE_RETURN_CD = "bcOnlineReturnCd"; + private static final String BC_ONLINE_RETURN_MESSAGE_TXT = "bcOnlineReturnMessageTxt"; + private static final String BC_ONLINE_SEQUENCE_TXT = "bcOnlineSequenceTxt"; + private static final String BC_ONLINE_TRANSACTION_TYPE_CD = "bcOnlineTransactionTypeCd"; + private static final String CREDIT_CARD_TYPE_CD = "creditCardTypeCd"; + private static final String ENT_USER_ID = "entUserId"; + private static final String INTERNAL_CLIENT_NO = "internalClientNo"; + private static final String INVOICE_NO = "invoiceNo"; + private static final String REFERENCE_MESSAGE_TXT = "referenceMessageTxt"; + private static final String RESPONSE_CD = "responseCd"; + private static final String SESSION_KEY_NO = "sessionKeyNo"; + private static final String TERMINAL_IDENTIFIER_NO = "terminalIdentifierNo"; + private static final String TRANSACTION_STATE_CD = "transactionStateCd"; + private static final String TRANSACTION_SUBTYPE_CD = "transactionSubtypeCd"; + private static final String TRANSACTION_TYPE_CD = "transactionTypeCd"; + private static final String UPD_USER_ID = "updUserId"; + private static final String INTERNAL_CLIENT_NUMBER = "INTERNAL_NUM"; + + private TestHelpers() { + + } + + public static XMLGregorianCalendar getXmlDate(Date date) throws DatatypeConfigurationException { + GregorianCalendar entryDate = new GregorianCalendar(); + entryDate.setTime(date); + return DatatypeFactory.newInstance().newXMLGregorianCalendar(entryDate); + } + + public static Service createService() throws DatatypeConfigurationException { + Service service = new Service(); + service.setAccountId(BigDecimal.TEN); + service.setClientId(BigDecimal.TEN); + service.setClientReferenceTxt(TestHelpers.CLIENT_REFERENCE_TXT); + service.setCourtFileNo(TestHelpers.COURT_FILE_NUMBER); + service.setDocumentsProcessed(TestHelpers.DOCUMENTS_PROCESSED); + service.setEntDtm(TestHelpers.getXmlDate(TestHelpers.DATE)); + service.setEntUserId("10"); + service.setServiceId(BigDecimal.TEN); + service.setServiceReceivedDtm(TestHelpers.getXmlDate(TestHelpers.DATE)); + service.setServiceReceivedDtmText(TestHelpers.SERVICE_RECEIVED_DTM_TEXT); + service.setServiceSessionId(BigDecimal.TEN); + service.setServiceSubtypeCd(TestHelpers.SERVICE_SUBTYPE_CD); + service.setServiceTypeCd(TestHelpers.SERVICE_TYPE_CD); + service.setServiceTypeDesc(TestHelpers.SERVICE_TYPE_DESC); + return service; + } +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoAccountServiceImpl/CreateAccountTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoAccountServiceImpl/CreateAccountTest.java new file mode 100644 index 0000000000..586e8aa295 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoAccountServiceImpl/CreateAccountTest.java @@ -0,0 +1,210 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoAccountServiceImpl; + +import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.RegisteredRole; +import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.RoleRegistryPortType; +import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.UserRoles; +import ca.bc.gov.ag.csows.accounts.*; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingAccountServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.CreateAccountRequest; +import ca.bc.gov.open.jag.efilingcsoclient.CsoAccountServiceImpl; +import ca.bc.gov.open.jag.efilingcsoclient.CsoHelpers; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.AccountDetailsMapper; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.AccountDetailsMapperImpl; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.ClientProfileMapperImpl; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import javax.xml.datatype.DatatypeConfigurationException; +import java.math.BigDecimal; +import java.util.Date; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Create Account Test Suite") +public class CreateAccountTest { + + public static final String UNIVERSAL_ID = "77da92db-0791-491e-8c58-1a969e67d2fe"; + private static final String FIRST_NAME = "FIRSTNAME"; + private static final String LAST_NAME = "LASTNAME"; + private static final String EMAIL = "EMAIL"; + private static final String MIDDLE_NAME = "MIDDLENAME"; + private static final String ACCOUNT_PREFIX_TXT = "SA"; + private static final String ACCOUNT_STATUS_CD = "ACT"; + private static final Date DATE = new Date(); + private static final String CLIENT_PREFIX_TXT = "CS"; + private static final String CLIENT_STATUS_CD = "ACT"; + private static final String REGISTERED_CLIENT_ROLE_CD2 = "FILE"; + public static final String DOMAIN = "Courts"; + public static final String APPLICATION = "CSO"; + public static final String IDENTIFIER_TYPE = "CAP"; + public static final String BCEID = "BCEID"; + public static final String IDENTITY_PROVIDER = "TEST"; + + @Mock + AccountFacadeBean accountFacadeBeanMock; + + @Mock + RoleRegistryPortType roleRegistryPortTypeMock; + + @Mock + AccountDetailsMapper accountDetailsMapperMock; + + private CsoAccountServiceImpl sut; + + @BeforeAll + public void setUp() throws NestedEjbException_Exception, DatatypeConfigurationException { + + MockitoAnnotations.openMocks(this); + accountDetailsMapperMock = new AccountDetailsMapperImpl(); + Mockito.when(accountFacadeBeanMock.createAccount(any(), any(), any(), any(), any(), any(), any())).thenReturn(createClientProfile()); + + RegisteredRole fileRole = new RegisteredRole(); + fileRole.setCode(REGISTERED_CLIENT_ROLE_CD2); + UserRoles userRolesWithFileRole = new UserRoles(); + userRolesWithFileRole.getRoles().add(fileRole); + Mockito.when(roleRegistryPortTypeMock.getRolesForIdentifier(DOMAIN, APPLICATION, CsoHelpers.formatUserGuid(UNIVERSAL_ID), IDENTIFIER_TYPE)).thenReturn(userRolesWithFileRole); + sut = new CsoAccountServiceImpl(accountFacadeBeanMock, roleRegistryPortTypeMock, accountDetailsMapperMock, new ClientProfileMapperImpl()); + } + + @Test + @DisplayName("No account details missing first name") + public void withMissingFirstNameThrowIllegalArgument() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.createAccount(CreateAccountRequest.builder().create())); + + } + + @Test + @DisplayName("No account details missing last name") + public void withMissingLastNameRequestThrowIllegalArgument() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.createAccount(CreateAccountRequest.builder() + .firstName(FIRST_NAME) + .create())); + + } + + @Test + @DisplayName("No account details missing email") + public void withMissingEmalRequestThrowIllegalArgument() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.createAccount(CreateAccountRequest.builder() + .firstName(FIRST_NAME) + .lastName(LAST_NAME) + .create())); + + } + + @Test + @DisplayName("No account details universal id") + public void withMissingUniversalIdRequestThrowIllegalArgument() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.createAccount(CreateAccountRequest.builder() + .firstName(FIRST_NAME) + .lastName(LAST_NAME) + .email(EMAIL) + .create())); + + } + + @Test + @DisplayName("No account details missing identity provider") + public void withMissingIdentityProviderRequestThrowIllegalArgument() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.createAccount(CreateAccountRequest.builder() + .firstName(FIRST_NAME) + .lastName(LAST_NAME) + .email(EMAIL) + .middleName(MIDDLE_NAME) + .universalId(UNIVERSAL_ID) + .create())); + + } + + @Test + @DisplayName("No account details invalid identity provider") + public void withInvalidIdentityProviderRequestThrowIllegalArgument() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.createAccount(CreateAccountRequest.builder() + .firstName(FIRST_NAME) + .lastName(LAST_NAME) + .email(EMAIL) + .middleName(MIDDLE_NAME) + .universalId(UNIVERSAL_ID) + .identityProvider(IDENTITY_PROVIDER) + .create())); + + } + + @Test + @DisplayName("Success account created ") + public void withValidAccountRequestAccountCreated() { + AccountDetails result = sut.createAccount(createAccountRequest()); + Assertions.assertEquals(UNIVERSAL_ID, result.getUniversalId()); + Assertions.assertTrue(result.isFileRolePresent()); + Assertions.assertEquals(BigDecimal.TEN, result.getAccountId()); + Assertions.assertEquals(BigDecimal.TEN, result.getClientId()); + } + + @Test + @DisplayName("Facade throws exception") + public void withValidValuesFacadeThrowsException() throws NestedEjbException_Exception { + Mockito.when(accountFacadeBeanMock.createAccount(any(), any(), any(), any(), any(), any(), any())).thenThrow(NestedEjbException_Exception.class); + Assertions.assertThrows(EfilingAccountServiceException.class, () -> sut.createAccount(createAccountRequest())); + } + + private CreateAccountRequest createAccountRequest() { + return CreateAccountRequest.builder() + .firstName(FIRST_NAME) + .lastName(LAST_NAME) + .email(EMAIL) + .middleName(MIDDLE_NAME) + .universalId(UNIVERSAL_ID) + .identityProvider(BCEID) + .create(); + } + + private ClientProfile createClientProfile() throws DatatypeConfigurationException { + ClientProfile clientProfile = new ClientProfile(); + clientProfile.setAccount(createAccountDetails()); + + clientProfile.setClient(createAccountClientDetails()); + clientProfile.setAccountId(BigDecimal.TEN); + clientProfile.setClientId(BigDecimal.TEN); + return clientProfile; + } + private Account createAccountDetails() throws DatatypeConfigurationException { + + Account account = new Account(); + account.setAccountNm(String.format("%s %s", FIRST_NAME, LAST_NAME)); + account.setAccountPrefixTxt(ACCOUNT_PREFIX_TXT); + account.setAccountStatusCd(ACCOUNT_STATUS_CD); + account.setAuthenticatedAccountGuid(CsoHelpers.formatUserGuid(UNIVERSAL_ID)); + account.setEmailTxt(EMAIL); + account.setEntDtm(CsoHelpers.date2XMLGregorian(DATE)); + account.setFeeExemptYnBoolean(false); + account.setRegisteredCreditCardYnBoolean(false); + account.setAccountManager(createAccountClientDetails()); + + return account; + } + + private Client createAccountClientDetails() throws DatatypeConfigurationException { + Client client = new Client(); + + client.setAuthenticatedClientGuid(CsoHelpers.formatUserGuid(UNIVERSAL_ID)); + client.setClientPrefixTxt(CLIENT_PREFIX_TXT); + client.setClientStatusCd(CLIENT_STATUS_CD); + client.setEntDtm(CsoHelpers.date2XMLGregorian(DATE)); + client.setGivenNm(FIRST_NAME); + client.setMiddleNm(MIDDLE_NAME); + client.setRegisteredCreditCardYnBoolean(false); + client.setSurnameNm(LAST_NAME); + + return client; + } +} diff --git a/src/backend/libs/efiling-account-client/src/test/java/ca/bc/gov/open/jag/efilingaccountclient/CsoAccountServiceImplTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoAccountServiceImpl/GetAccountDetailsTest.java similarity index 50% rename from src/backend/libs/efiling-account-client/src/test/java/ca/bc/gov/open/jag/efilingaccountclient/CsoAccountServiceImplTest.java rename to src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoAccountServiceImpl/GetAccountDetailsTest.java index 6941f2c02a..2514fc3db6 100644 --- a/src/backend/libs/efiling-account-client/src/test/java/ca/bc/gov/open/jag/efilingaccountclient/CsoAccountServiceImplTest.java +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoAccountServiceImpl/GetAccountDetailsTest.java @@ -1,18 +1,18 @@ -package ca.bc.gov.open.jag.efilingaccountclient; +package ca.bc.gov.open.jag.efilingcsoclient.csoAccountServiceImpl; import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.RegisteredRole; import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.RoleRegistry; import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.RoleRegistryPortType; import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.UserRoles; -import ca.bc.gov.ag.csows.accounts.AccountFacade; -import ca.bc.gov.ag.csows.accounts.AccountFacadeBean; -import ca.bc.gov.ag.csows.accounts.ClientProfile; -import ca.bc.gov.ag.csows.accounts.NestedEjbException_Exception; -import ca.bc.gov.open.jag.efilingaccountclient.mappers.AccountDetailsMapper; +import ca.bc.gov.ag.csows.accounts.*; import ca.bc.gov.open.jag.efilingcommons.exceptions.CSOHasMultipleAccountException; import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingAccountServiceException; import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; -import ca.bceid.webservices.client.v9.*; +import ca.bc.gov.open.jag.efilingcsoclient.CsoAccountServiceImpl; +import ca.bc.gov.open.jag.efilingcsoclient.CsoHelpers; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.AccountDetailsMapper; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.AccountDetailsMapperImpl; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.ClientProfileMapperImpl; import org.junit.jupiter.api.*; import org.mockito.Mock; import org.mockito.Mockito; @@ -23,19 +23,19 @@ import java.util.List; import java.util.UUID; -import static org.mockito.ArgumentMatchers.any; - @TestInstance(TestInstance.Lifecycle.PER_CLASS) -public class CsoAccountServiceImplTest { - - private static final UUID USER_GUID_NO_ROLE = UUID.randomUUID(); - private static final UUID USER_GUID_WITH_FILE_ROLE = UUID.randomUUID(); - private static final UUID USER_GUID_WITH_NO_CSO = UUID.randomUUID(); - private static final UUID USER_GUID_WITH_EJB_EXCEPTION = UUID.randomUUID(); - private static final UUID USER_GUID_WITH_MULTI_PROFILE = UUID.randomUUID(); +@DisplayName("Get Account Details Test Suite") +public class GetAccountDetailsTest { + + private static final String USER_GUID_NO_ROLE = UUID.randomUUID().toString(); + private static final String USER_GUID_WITH_FILE_ROLE = UUID.randomUUID().toString(); + private static final String USER_GUID_WITH_NO_CSO = UUID.randomUUID().toString(); + private static final String USER_GUID_WITH_EJB_EXCEPTION = UUID.randomUUID().toString(); + private static final String USER_GUID_WITH_MULTI_PROFILE = UUID.randomUUID().toString(); public static final String DOMAIN = "Courts"; public static final String APPLICATION = "CSO"; public static final String IDENTIFIER_TYPE = "CAP"; + private static final String INTERNAL_CLIENT_NUMBER = "123"; CsoAccountServiceImpl sut; @@ -51,24 +51,19 @@ public class CsoAccountServiceImplTest { @Mock RoleRegistryPortType roleRegistryPortTypeMock; - @Mock - BCeIDService bCeIDService; - - @Mock - BCeIDServiceSoap bCeIDServiceSoap; - - @Mock - AccountDetailsMapper accountDetailsMapperMock; + AccountDetailsMapper accountDetailsMapper; @BeforeEach - public void init() throws NestedEjbException_Exception { + public void beforeEach() throws NestedEjbException_Exception { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); initAccountFacadeMocks(); initRoleRegistryMocks(); - initBceIdAccountMocks(); - sut = new CsoAccountServiceImpl(accountFacadeBeanMock, roleRegistryPortTypeMock, bCeIDServiceSoap, accountDetailsMapperMock); + accountDetailsMapper = new AccountDetailsMapperImpl(); + + sut = new CsoAccountServiceImpl(accountFacadeBeanMock, roleRegistryPortTypeMock, accountDetailsMapper, new ClientProfileMapperImpl()); + } private void initAccountFacadeMocks() throws NestedEjbException_Exception { @@ -78,20 +73,24 @@ private void initAccountFacadeMocks() throws NestedEjbException_Exception { ClientProfile profile = new ClientProfile(); profile.setAccountId(BigDecimal.TEN); profile.setClientId(BigDecimal.TEN); + Client client = new Client(); + client.setInternalClientNo(INTERNAL_CLIENT_NUMBER); + profile.setClient(client); + List profiles = new ArrayList(); profiles.add(profile); - Mockito.when(accountFacadeBeanMock.findProfiles(CsoHelpers.formatUserGuid(USER_GUID_NO_ROLE))).thenReturn(profiles); - Mockito.when(accountFacadeBeanMock.findProfiles(CsoHelpers.formatUserGuid(USER_GUID_WITH_FILE_ROLE))).thenReturn(profiles); + Mockito.when(accountFacadeBeanMock.findProfiles(Mockito.eq(CsoHelpers.formatUserGuid(USER_GUID_NO_ROLE)))).thenReturn(profiles); + Mockito.when(accountFacadeBeanMock.findProfiles(Mockito.eq(CsoHelpers.formatUserGuid(USER_GUID_WITH_FILE_ROLE)))).thenReturn(profiles); List emptyProfiles = new ArrayList(); - Mockito.when(accountFacadeBeanMock.findProfiles(CsoHelpers.formatUserGuid(USER_GUID_WITH_NO_CSO))).thenReturn(emptyProfiles); - Mockito.when(accountFacadeBeanMock.findProfiles(CsoHelpers.formatUserGuid(USER_GUID_WITH_EJB_EXCEPTION))).thenThrow(new NestedEjbException_Exception("random")); + Mockito.when(accountFacadeBeanMock.findProfiles(Mockito.eq(CsoHelpers.formatUserGuid(USER_GUID_WITH_NO_CSO)))).thenReturn(emptyProfiles); + Mockito.when(accountFacadeBeanMock.findProfiles(Mockito.eq(CsoHelpers.formatUserGuid(USER_GUID_WITH_EJB_EXCEPTION)))).thenThrow(new NestedEjbException_Exception("random")); List multiProfiles = new ArrayList<>(); multiProfiles.add(profile); multiProfiles.add(profile); - Mockito.when(accountFacadeBeanMock.findProfiles(CsoHelpers.formatUserGuid(USER_GUID_WITH_MULTI_PROFILE))).thenReturn(multiProfiles); + Mockito.when(accountFacadeBeanMock.findProfiles(Mockito.eq(CsoHelpers.formatUserGuid(USER_GUID_WITH_MULTI_PROFILE)))).thenReturn(multiProfiles); } @@ -111,58 +110,18 @@ private void initRoleRegistryMocks() { Mockito.when(roleRegistryPortTypeMock.getRolesForIdentifier(DOMAIN, APPLICATION, CsoHelpers.formatUserGuid(USER_GUID_WITH_FILE_ROLE), IDENTIFIER_TYPE)).thenReturn(userRolesWithFileRole); Mockito.when(roleRegistryPortTypeMock.getRolesForIdentifier(DOMAIN, APPLICATION, CsoHelpers.formatUserGuid(USER_GUID_NO_ROLE), IDENTIFIER_TYPE)).thenReturn(userRolesWithoutFileRole); - AccountDetails csoUserDetailsWithRole = new AccountDetails(BigDecimal.TEN, BigDecimal.TEN, true, "firstName", "lastName", "middleName", "email"); - Mockito.when(accountDetailsMapperMock.toAccountDetails(Mockito.any(), Mockito.eq(true))).thenReturn(csoUserDetailsWithRole); - - AccountDetails csoUserDetailsWithoutRole = new AccountDetails(BigDecimal.TEN, BigDecimal.TEN, false, "firstName", "lastName", "middleName","email"); - Mockito.when(accountDetailsMapperMock.toAccountDetails(Mockito.any(), Mockito.eq(false))).thenReturn(csoUserDetailsWithoutRole); - } - - private void initBceIdAccountMocks() { - - BCeIDAccountContact contact = new BCeIDAccountContact(); - BCeIDString str = new BCeIDString(); - str.setValue("email@email.com"); - contact.setEmail(str); - - BCeIDName name = new BCeIDName(); - str.setValue("first"); - name.setFirstname(str); - str.setValue("middle"); - name.setMiddleName(str); - str.setValue("surname"); - name.setSurname(str); - - BCeIDIndividualIdentity identity = new BCeIDIndividualIdentity(); - identity.setName(name); - - BCeIDAccount bCeIDAccount = new BCeIDAccount(); - bCeIDAccount.setContact(contact); - bCeIDAccount.setIndividualIdentity(identity); - - AccountDetailResponse bCeIDResponse = new AccountDetailResponse(); - bCeIDResponse.setCode(ResponseCode.SUCCESS); - bCeIDResponse.setAccount(bCeIDAccount); - - Mockito.when(bCeIDService.getBCeIDServiceSoap()).thenReturn(bCeIDServiceSoap); - Mockito.when(bCeIDServiceSoap.getAccountDetail(any())).thenReturn(bCeIDResponse); - - AccountDetails accountDetailsWithNoCso = new AccountDetails(BigDecimal.ZERO, BigDecimal.ZERO, false, "firstName", "lastName", "middleName","email"); - Mockito.when(accountDetailsMapperMock.toAccountDetails(Mockito.any())).thenReturn(accountDetailsWithNoCso); } @DisplayName("OK: getAccountDetails called with userGuid with file role") @Test public void testWithFileRoleEnabled() throws NestedEjbException_Exception { - AccountDetails details = sut.getAccountDetails(USER_GUID_WITH_FILE_ROLE, ""); + AccountDetails details = sut.getAccountDetails(USER_GUID_WITH_FILE_ROLE); Assertions.assertNotEquals(null, details); Assertions.assertEquals(BigDecimal.TEN, details.getAccountId()); Assertions.assertEquals(BigDecimal.TEN, details.getClientId()); + Assertions.assertEquals(INTERNAL_CLIENT_NUMBER, details.getInternalClientNumber()); Assertions.assertEquals(true, details.isFileRolePresent()); - Assertions.assertEquals("firstName", details.getFirstName()); - Assertions.assertEquals("lastName", details.getLastName()); - Assertions.assertEquals("email", details.getEmail()); } @@ -170,29 +129,21 @@ public void testWithFileRoleEnabled() throws NestedEjbException_Exception { @Test public void testWithFileRoleDisabled() throws NestedEjbException_Exception { - AccountDetails details = sut.getAccountDetails(USER_GUID_NO_ROLE, ""); + AccountDetails details = sut.getAccountDetails(USER_GUID_NO_ROLE); Assertions.assertNotEquals(null, details); Assertions.assertEquals(BigDecimal.TEN, details.getAccountId()); Assertions.assertEquals(BigDecimal.TEN, details.getClientId()); + Assertions.assertEquals(INTERNAL_CLIENT_NUMBER, details.getInternalClientNumber()); Assertions.assertEquals(false, details.isFileRolePresent()); - Assertions.assertEquals("firstName", details.getFirstName()); - Assertions.assertEquals("lastName", details.getLastName()); - Assertions.assertEquals("email", details.getEmail()); } - @DisplayName("OK: getAccountDetails called with a userGuid that does not have cso account") + @DisplayName("OK: getAccountDetails called with a userGuid that does not have cso account should return null") @Test - public void withNoCsoAccountShouldReturnBceidUser() throws NestedEjbException_Exception { + public void withNoCsoAccountShouldReturnNull() throws NestedEjbException_Exception { - AccountDetails details = sut.getAccountDetails(USER_GUID_WITH_NO_CSO, "Individual"); - Assertions.assertNotEquals(null, details); - Assertions.assertEquals(BigDecimal.ZERO, details.getAccountId()); - Assertions.assertEquals(BigDecimal.ZERO, details.getClientId()); - Assertions.assertEquals(false, details.isFileRolePresent()); - Assertions.assertEquals("firstName", details.getFirstName()); - Assertions.assertEquals("lastName", details.getLastName()); - Assertions.assertEquals("email", details.getEmail()); + AccountDetails actual = sut.getAccountDetails(USER_GUID_WITH_NO_CSO); + Assertions.assertNull(actual); } @DisplayName("Exception: with NestedEjbException_Exception should throw EfilingAccountServiceException") @@ -201,7 +152,7 @@ public void withNestedEjbExceptionExceptionShouldThrowEfilingAccountServiceExcep EfilingAccountServiceException actual = Assertions.assertThrows(EfilingAccountServiceException.class, () -> { - sut.getAccountDetails(USER_GUID_WITH_EJB_EXCEPTION, "Individual"); + sut.getAccountDetails(USER_GUID_WITH_EJB_EXCEPTION); }); Assertions.assertEquals(NestedEjbException_Exception.class, actual.getCause().getClass()); @@ -215,14 +166,10 @@ public void withMultiProflieShouldThrowCSOHasMultipleAccountException() { CSOHasMultipleAccountException actual = Assertions.assertThrows(CSOHasMultipleAccountException.class, () -> { - sut.getAccountDetails(USER_GUID_WITH_MULTI_PROFILE, "Individual"); + sut.getAccountDetails(USER_GUID_WITH_MULTI_PROFILE); }); Assertions.assertEquals("Client 10 has multiple CSO profiles", actual.getMessage()); } - - - - } diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoAccountServiceImpl/GetOrderNumberTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoAccountServiceImpl/GetOrderNumberTest.java new file mode 100644 index 0000000000..fc99cf971a --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoAccountServiceImpl/GetOrderNumberTest.java @@ -0,0 +1,61 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoAccountServiceImpl; + +import ca.bc.gov.ag.csows.accounts.AccountFacadeBean; +import ca.bc.gov.ag.csows.accounts.NestedEjbException_Exception; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingAccountServiceException; +import ca.bc.gov.open.jag.efilingcsoclient.CsoAccountServiceImpl; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.ClientProfileMapperImpl; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; + + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("GetOrderNumber") +public class GetOrderNumberTest { + + + CsoAccountServiceImpl sut; + + + @Mock + AccountFacadeBean accountFacadeBeanMock; + + + @BeforeEach + public void init() throws NestedEjbException_Exception { + + MockitoAnnotations.openMocks(this); + + sut = new CsoAccountServiceImpl(accountFacadeBeanMock, null, null, new ClientProfileMapperImpl()); + } + + + + @DisplayName("OK: getNextOrderNumber") + @Test + public void testNextOrderReturned() throws NestedEjbException_Exception { + + Mockito.when(accountFacadeBeanMock.getNextOrderNumber()).thenReturn(BigDecimal.TEN); + + String actual = sut.getOrderNumber(); + + Assertions.assertEquals(BigDecimal.TEN.toString(), actual); + } + + + @DisplayName("Exception: when soap service throws exception throw EfilingAccountServiceException") + @Test + public void withMultiProflieShouldThrowCSOHasMultipleAccountException() throws NestedEjbException_Exception { + Mockito.when(accountFacadeBeanMock.getNextOrderNumber()).thenThrow(NestedEjbException_Exception.class); + + Assertions.assertThrows(EfilingAccountServiceException.class, () -> { + sut.getOrderNumber(); + }); + + + } +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoAccountServiceImpl/UpdateClientTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoAccountServiceImpl/UpdateClientTest.java new file mode 100644 index 0000000000..cd39dd710f --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoAccountServiceImpl/UpdateClientTest.java @@ -0,0 +1,120 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoAccountServiceImpl; + +import ca.bc.gov.ag.csows.accounts.AccountFacadeBean; +import ca.bc.gov.ag.csows.accounts.Client; +import ca.bc.gov.ag.csows.accounts.NestedEjbException_Exception; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingAccountServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcsoclient.CsoAccountServiceImpl; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.ClientProfileMapperImpl; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("UpdateClient") +public class UpdateClientTest { + + private static final String INTERNAL_CLIENT_NUMBER = "123"; + private static final String FAIL_INTERNAL_CLIENT_NUMBER = "1234"; + + CsoAccountServiceImpl sut; + + @Mock + AccountFacadeBean accountFacadeBeanMock; + + + @BeforeEach + public void init() throws NestedEjbException_Exception { + + MockitoAnnotations.openMocks(this); + initAccountFacadeMocks(); + + sut = new CsoAccountServiceImpl(accountFacadeBeanMock, null, null, new ClientProfileMapperImpl()); + } + + private void initAccountFacadeMocks() throws NestedEjbException_Exception { + + Client client = new Client(); + client.setClientId(BigDecimal.TEN); + + Mockito.doReturn(client).when(accountFacadeBeanMock) + .getClient(Mockito.eq(BigDecimal.TEN)); + + Mockito.doReturn(null).when(accountFacadeBeanMock) + .updateClient(ArgumentMatchers.argThat(x -> x.getInternalClientNo().equals(INTERNAL_CLIENT_NUMBER))); + + + Mockito.doThrow(NestedEjbException_Exception.class).when(accountFacadeBeanMock) + .updateClient(ArgumentMatchers.argThat(x -> x.getInternalClientNo().equals(FAIL_INTERNAL_CLIENT_NUMBER))); + } + + @DisplayName("OK: update client executes") + @Test + public void testWithClientNumberUpdateClientExecuted() throws NestedEjbException_Exception { + + sut.updateClient(AccountDetails.builder() + .internalClientNumber(INTERNAL_CLIENT_NUMBER) + .cardRegistered(true) + .clientId(BigDecimal.TEN) + .create()); + + Mockito.verify(accountFacadeBeanMock,Mockito.times(1)).updateClient(ArgumentMatchers.argThat(x -> x.getInternalClientNo().equals(INTERNAL_CLIENT_NUMBER))); + } + + @DisplayName("Exception: with NestedEjbException_Exception should throw EfilingAccountServiceException") + @Test + public void withNestedEjbExceptionExceptionShouldThrowEfilingAccountServiceException() { + + + Assertions.assertThrows(EfilingAccountServiceException.class, () -> { + sut.updateClient(AccountDetails.builder() + .internalClientNumber(FAIL_INTERNAL_CLIENT_NUMBER) + .cardRegistered(true) + .clientId(BigDecimal.TEN) + .create()); + }); + + } + + @DisplayName("Exception: with null account should throw IllegalArgumentException") + @Test + public void withNullAccountReturnIllegalArgumentException() { + + + Assertions.assertThrows(IllegalArgumentException.class, () -> { + sut.updateClient(null); + }); + + } + + @DisplayName("Exception: with null client id should throw IllegalArgumentException") + @Test + public void withNullClientIdReturnIllegalArgumentException() { + + + Assertions.assertThrows(IllegalArgumentException.class, () -> { + sut.updateClient(AccountDetails.builder() + .internalClientNumber(INTERNAL_CLIENT_NUMBER) + .create()); + }); + + } + + @DisplayName("Exception: with null client number should throw IllegalArgumentException") + @Test + public void withNullClientNumberReturnIllegalArgumentException() { + + + Assertions.assertThrows(IllegalArgumentException.class, () -> { + sut.updateClient(AccountDetails.builder() + .clientId(BigDecimal.TEN) + .create()); + }); + + } +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoCourtService/GetCourtDescriptionTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoCourtService/GetCourtDescriptionTest.java new file mode 100644 index 0000000000..6733418904 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoCourtService/GetCourtDescriptionTest.java @@ -0,0 +1,167 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoCourtService; + +import ca.bc.gov.ag.csows.ceis.*; +import ca.bc.gov.ag.csows.filing.status.FilingStatusFacadeBean; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingCourtServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.CourtDetails; +import ca.bc.gov.open.jag.efilingcsoclient.CsoCourtServiceImpl; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class GetCourtDescriptionTest { + private static final String NOVALUE = "NOVALUE"; + private static final String AGEN_AGENCY_NM = "FOUNDAGENCY"; + private static final String AGEN_AGENCY_IDENTIFIER_CD = "FOUND"; + private static final String AGEN_AGENCY_IDENTIFIER_CD1 = "OTHER"; + private static final String AGEN_AGENCY_NM1 = "OTHERAGENCY"; + private static final String COURT_LEVEL = "LEVEL"; + private static final String COURT_CLASS = "CLASS"; + private static final String AGENCY = "AGENCY"; + private static final String LEVELCD_1 = "LEVELCD1"; + private static final String LEVEL_1 = "LEVEL1"; + private static final String LEVELCD_2 = "LEVELCD2"; + private static final String LEVEL_2 = "LEVEL2"; + private static final String CLASSCD_1 = "CLASSCD1"; + private static final String CLASS_1 = "CLASS1"; + private static final String CLASSCD_2 = "CLASSCD2"; + private static final String CLASS_2 = "CLASS2"; + @Mock + Csows csowsMock; + + @Mock + FilingStatusFacadeBean filingStatusFacadeBeanMock; + + @Mock + CsoAgencyArr csoAgencyArrMock; + + + @Mock + CsoCourtLevelArr csoCourtLevelArrMock; + + + @Mock + CsoCourtClassArr csoCourtClassArrMock; + + + private static CsoCourtServiceImpl sut; + + @BeforeAll + public void setUp() { + + MockitoAnnotations.openMocks(this); + + Mockito.when(csoCourtLevelArrMock.getArray()).thenReturn(createLevelArray()); + Mockito.when(csowsMock.getCourtLevels()).thenReturn(csoCourtLevelArrMock); + + Mockito.when(csoCourtClassArrMock.getArray()).thenReturn(createClassArray()); + Mockito.when(csowsMock.getCourtClasses(any())).thenReturn(csoCourtClassArrMock); + + Mockito.when(csoAgencyArrMock.getArray()).thenReturn(createAgencyArray()); + Mockito.when(csowsMock.getCourtLocations()).thenReturn(csoAgencyArrMock); + + sut = new CsoCourtServiceImpl(csowsMock, filingStatusFacadeBeanMock); + } + @DisplayName("Exception: with null parameter throws Illegal Argument exception") + @Test + public void withNullParameterThrowsIllegalArgument() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getCourtDescription(null, COURT_LEVEL, COURT_CLASS)); + + } + @DisplayName("Exception: with null parameter throws Illegal Argument exception") + @Test + public void withNullLevelParameterThrowsIllegalArgument() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getCourtDescription(AGENCY, null, COURT_CLASS)); + + } + @DisplayName("Exception: with null parameter throws Illegal Argument exception") + @Test + public void withNullClassParameterThrowsIllegalArgument() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getCourtDescription(AGENCY, COURT_LEVEL, null)); + + } + @DisplayName("Ok: with valid string and existing location return description") + @Test + public void withValidStringAndExistingLocationReturnDescriptions() { + + CourtDetails actual = sut.getCourtDescription(AGEN_AGENCY_IDENTIFIER_CD, LEVELCD_1, CLASSCD_1).get(); + + Assertions.assertEquals(AGEN_AGENCY_NM, actual.getCourtDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.getCourtId()); + Assertions.assertEquals(CLASS_1, actual.getClassDescription()); + Assertions.assertEquals(LEVEL_1, actual.getLevelDescription()); + + } + + @DisplayName("Exception: with missing level throw exception") + @Test + public void withValidStringAndMissingLevelReturnDescriptions() { + + Assertions.assertThrows(EfilingCourtServiceException.class, () -> sut.getCourtDescription(AGEN_AGENCY_IDENTIFIER_CD, COURT_LEVEL, CLASSCD_1)); + + } + + @DisplayName("Exception: with missing class throw exception") + @Test + public void withValidStringAndMissingClassReturnDescriptions() { + + Assertions.assertThrows(EfilingCourtServiceException.class, () -> sut.getCourtDescription(AGEN_AGENCY_IDENTIFIER_CD, LEVELCD_1, COURT_CLASS)); + + } + + @DisplayName("Ok: with no result should return Empty") + @Test + public void withNoFoundResultShouldReturnEmpty() { + + Optional actual = sut.getCourtDescription(NOVALUE, COURT_LEVEL, COURT_CLASS); + + Assertions.assertFalse(actual.isPresent()); + + } + + private List createAgencyArray() { + CsoAgencyRec csoAgencyRec1 = new CsoAgencyRec(); + csoAgencyRec1.setAgenAgencyIdentifierCd(AGEN_AGENCY_IDENTIFIER_CD); + csoAgencyRec1.setAgenAgencyNm(AGEN_AGENCY_NM); + csoAgencyRec1.setAgenId(BigDecimal.TEN); + CsoAgencyRec csoAgencyRec2 = new CsoAgencyRec(); + csoAgencyRec2.setAgenAgencyIdentifierCd(AGEN_AGENCY_IDENTIFIER_CD1); + csoAgencyRec2.setAgenAgencyNm(AGEN_AGENCY_NM1); + csoAgencyRec2.setAgenId(BigDecimal.TEN); + return Arrays.asList(csoAgencyRec1, csoAgencyRec2); + } + + private List createLevelArray() { + CsoCourtLevelRec csoLevelRec1 = new CsoCourtLevelRec(); + csoLevelRec1.setLevelCd(LEVELCD_1); + csoLevelRec1.setLevelDsc(LEVEL_1); + CsoCourtLevelRec csoLevelRec2 = new CsoCourtLevelRec(); + csoLevelRec2.setLevelCd(LEVELCD_2); + csoLevelRec2.setLevelDsc(LEVEL_2); + return Arrays.asList(csoLevelRec1, csoLevelRec2); + } + + private List createClassArray() { + CsoCourtClassRec csoClassRec1 = new CsoCourtClassRec(); + csoClassRec1.setClassCd(CLASSCD_1); + csoClassRec1.setClassDsc(CLASS_1); + CsoCourtClassRec csoClassRec2 = new CsoCourtClassRec(); + csoClassRec2.setClassCd(CLASSCD_2); + csoClassRec2.setClassDsc(CLASS_2); + return Arrays.asList(csoClassRec1, csoClassRec2); + } + + +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoDocumentServiceImpl/GetDocumentDetailsTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoDocumentServiceImpl/GetDocumentDetailsTest.java new file mode 100644 index 0000000000..fe2ce467e9 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoDocumentServiceImpl/GetDocumentDetailsTest.java @@ -0,0 +1,112 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoDocumentServiceImpl; + +import ca.bc.gov.ag.csows.filing.status.DocumentType; +import ca.bc.gov.ag.csows.filing.status.FilingStatusFacadeBean; +import ca.bc.gov.ag.csows.filing.status.NestedEjbException_Exception; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingDocumentServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import ca.bc.gov.open.jag.efilingcsoclient.CsoDocumentServiceImpl; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Arrays; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Get Document Details Test Suite") +public class GetDocumentDetailsTest { + + private static final String DOCUMENT_TYPE_CD = "ACODE"; + private static final String DESCRIPTION = "DESCRIPTION"; + private static final String NODOC = "NODOC"; + public static final String COURT_LEVEL = "level1"; + public static final String COURT_CLASS = "class1"; + public static final String EXCEPTION = "exception"; + @Mock + FilingStatusFacadeBean filingStatusFacadeBean; + + private static CsoDocumentServiceImpl sut; + + @BeforeAll + public void setUp() throws NestedEjbException_Exception { + + MockitoAnnotations.openMocks(this); + DocumentType documentType = new DocumentType(); + documentType.setDocumentTypeCd(DOCUMENT_TYPE_CD); + documentType.setDocumentTypeDesc(DESCRIPTION); + documentType.setDefaultStatutoryFee(BigDecimal.TEN); + documentType.setOrderDocumentYn(true); + documentType.setRushRequiredYn(true); + documentType.setAutoProcessYn(false); + + + Mockito.when(filingStatusFacadeBean.getDocumentTypes(Mockito.eq(COURT_LEVEL),any())).thenReturn(Arrays.asList(documentType)); + Mockito.when(filingStatusFacadeBean.getDocumentTypes(Mockito.eq(NODOC),any())).thenReturn(new ArrayList<>()); + + Mockito.when(filingStatusFacadeBean.getDocumentTypes(Mockito.eq(EXCEPTION),any())).thenThrow(NestedEjbException_Exception.class); + + sut = new CsoDocumentServiceImpl(filingStatusFacadeBean); + } + + @DisplayName("OK: test returns document ") + @Test + public void testWithFoundResult() { + DocumentTypeDetails result = sut.getDocumentTypeDetails(COURT_LEVEL, COURT_CLASS, DOCUMENT_TYPE_CD); + Assertions.assertEquals(DESCRIPTION, result.getDescription()); + Assertions.assertEquals(BigDecimal.TEN, result.getStatutoryFeeAmount()); + Assertions.assertTrue(result.isOrderDocument()); + Assertions.assertTrue(result.isRushRequired()); + Assertions.assertFalse(result.isAutoProcessing()); + } + + @DisplayName("Exception: when not finding document should throw exception") + @Test + public void whenNotFindingDocumentsShouldThrowError() { + + Assertions.assertThrows(EfilingDocumentServiceException.class, () -> sut.getDocumentTypeDetails(NODOC, COURT_CLASS, NODOC)); + } + + @DisplayName("Failure: when SOAP service throws NestedEjbException_Exception, service should throw EfilingDocumentServiceException") + @Test + public void testThrowException() throws NestedEjbException_Exception { + + Assertions.assertThrows(EfilingDocumentServiceException.class, () -> sut.getDocumentTypeDetails(EXCEPTION, COURT_CLASS,"type")); + } + + @DisplayName("Exception: courtLevel is required") + @Test + public void whenCourtLevelIsBlankShouldThrowIllegalArgumentException() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypeDetails(null, "class", "type")); + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypeDetails("", "class", "type")); + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypeDetails(" ", "class", "type")); + + } + + @DisplayName("Exception: courtClass is required") + @Test + public void whenCourtClassIsBlankShouldThrowIllegalArgumentException() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypeDetails("level", null, "type")); + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypeDetails("level", "", "type")); + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypeDetails("level", " ", "type")); + + } + + + @DisplayName("Exception: documentType is required") + @Test + public void whenDocumentTypeIsBlankShouldThrowIllegalArgumentException() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypeDetails("level", "class", null)); + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypeDetails("level", "class", "")); + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypeDetails("level", "class", " ")); + + } + +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoDocumentServiceImpl/GetDocumentTypesTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoDocumentServiceImpl/GetDocumentTypesTest.java new file mode 100644 index 0000000000..307d33e99e --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoDocumentServiceImpl/GetDocumentTypesTest.java @@ -0,0 +1,111 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoDocumentServiceImpl; + +import ca.bc.gov.ag.csows.filing.status.DocumentType; +import ca.bc.gov.ag.csows.filing.status.FilingStatusFacadeBean; +import ca.bc.gov.ag.csows.filing.status.NestedEjbException_Exception; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingDocumentServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import ca.bc.gov.open.jag.efilingcsoclient.CsoDocumentServiceImpl; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Get Document Type Test Suite") +public class GetDocumentTypesTest { + private static final String DOCUMENT_TYPE_CD = "ACODE"; + private static final String DOCUMENT_TYPE_OTHER_CD = "OTH"; + private static final String DESCRIPTION = "DESCRIPTION"; + private static final String NODOC = "NODOC"; + public static final String COURT_LEVEL = "level1"; + public static final String COURT_CLASS = "class1"; + public static final String EXCEPTION = "exception"; + @Mock + FilingStatusFacadeBean filingStatusFacadeBean; + + private static CsoDocumentServiceImpl sut; + + @BeforeAll + public void setUp() throws NestedEjbException_Exception { + + MockitoAnnotations.openMocks(this); + + Mockito.when(filingStatusFacadeBean.getDocumentTypes(Mockito.eq(COURT_LEVEL),any())).thenReturn(createDocumentTypeList()); + Mockito.when(filingStatusFacadeBean.getDocumentTypes(Mockito.eq(NODOC),any())).thenReturn(new ArrayList<>()); + + Mockito.when(filingStatusFacadeBean.getDocumentTypes(Mockito.eq(EXCEPTION),any())).thenThrow(NestedEjbException_Exception.class); + + sut = new CsoDocumentServiceImpl(filingStatusFacadeBean); + } + + @DisplayName("OK: test returns document ") + @Test + public void testWithFoundResult() { + List result = sut.getDocumentTypes(COURT_LEVEL, COURT_CLASS); + + Assertions.assertEquals(1, result.size()); + Assertions.assertEquals(DESCRIPTION, result.get(0).getDescription()); + Assertions.assertEquals(DOCUMENT_TYPE_CD, result.get(0).getType()); + + } + + @DisplayName("Failure: when SOAP service throws NestedEjbException_Exception, service should throw EfilingDocumentServiceException") + @Test + public void testThrowException() throws NestedEjbException_Exception { + + Assertions.assertThrows(EfilingDocumentServiceException.class, () -> sut.getDocumentTypes(EXCEPTION, COURT_CLASS)); + + } + + @DisplayName("Exception: courtLevel is required") + @Test + public void whenCourtLevelIsBlankShouldThrowIllegalArgumentException() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypes(null, "class")); + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypes("", "class")); + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypes(" ", "class")); + + } + + @DisplayName("Exception: courtClass is required") + @Test + public void whenCourtClassIsBlankShouldThrowIllegalArgumentException() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypes("level", null)); + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypes("level", "")); + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getDocumentTypes("level", " ")); + + } + + private List createDocumentTypeList() { + + DocumentType documentType1 = new DocumentType(); + documentType1.setDocumentTypeCd(DOCUMENT_TYPE_CD); + documentType1.setDocumentTypeDesc(DESCRIPTION); + documentType1.setDefaultStatutoryFee(BigDecimal.TEN); + documentType1.setOrderDocumentYn(true); + documentType1.setRushRequiredYn(true); + documentType1.setAutoProcessYn(false); + + DocumentType documentType2 = new DocumentType(); + documentType2.setDocumentTypeCd(DOCUMENT_TYPE_OTHER_CD); + documentType2.setDocumentTypeDesc(DESCRIPTION); + documentType2.setDefaultStatutoryFee(BigDecimal.TEN); + documentType2.setOrderDocumentYn(true); + documentType2.setRushRequiredYn(true); + documentType2.setAutoProcessYn(false); + + return Arrays.asList(documentType1, documentType2); + + } + + +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoLookupService/CsoLookupServiceImplTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoLookupService/CsoLookupServiceImplTest.java new file mode 100644 index 0000000000..9bd4f8a639 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoLookupService/CsoLookupServiceImplTest.java @@ -0,0 +1,157 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoLookupService; + +import ca.bc.gov.ag.csows.lookups.LookupFacadeBean; +import ca.bc.gov.ag.csows.lookups.NestedEjbException_Exception; +import ca.bc.gov.ag.csows.lookups.ServiceFee; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingLookupServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.ServiceFees; +import ca.bc.gov.open.jag.efilingcommons.model.SubmissionFeeRequest; +import ca.bc.gov.open.jag.efilingcsoclient.CsoLookupServiceImpl; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.math.BigDecimal; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("CSO Efiling Lookup Client Test Suite") +public class CsoLookupServiceImplTest { + + private static final String SERVICE_TYPE = "ServiceId"; + private static final String SERVICE_ID_NULL = "ServiceIdNull"; + public static final String SERVICE_TYPE_CD = "serviceTypeCd"; + public static final String SERVICE_ID_EXCEPTION = "exception"; + public static final String TEST = "TEST"; + + CsoLookupServiceImpl sut; + + @Mock + LookupFacadeBean lookupFacadeBeanMock; + + @BeforeAll + public void beforeEach() throws NestedEjbException_Exception { + + MockitoAnnotations.openMocks(this); + + ServiceFee serviceFee = new ServiceFee(); + + serviceFee.setFeeAmt(BigDecimal.TEN); + serviceFee.setServiceTypeCd(SERVICE_TYPE_CD); + + Mockito + .when(lookupFacadeBeanMock.getServiceFeeByClassification(ArgumentMatchers.eq(SERVICE_TYPE), any(), any(), any(), any(), any())) + .thenReturn(serviceFee); + + Mockito + .when(lookupFacadeBeanMock.getServiceFeeByClassification(ArgumentMatchers.eq(SERVICE_ID_EXCEPTION), any(), any(), any(), any(), any())) + .thenThrow(new NestedEjbException_Exception("random")); + + Mockito + .when(lookupFacadeBeanMock.getServiceFeeByClassification(ArgumentMatchers.eq(SERVICE_ID_NULL), any(), any(), any(), any(), any())) + .thenReturn(null); + + sut = new CsoLookupServiceImpl(lookupFacadeBeanMock); + + } + + @DisplayName("Exception: with null service id should throw IllegalArgumentException") + @Test + public void testWithEmptyServiceType() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getServiceFee(SubmissionFeeRequest.builder().create())); + } + + @DisplayName("Exception: with null service id should throw IllegalArgumentException") + @Test + public void testWithEmptyApplication() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getServiceFee(SubmissionFeeRequest.builder() + .serviceType(TEST) + .create())); + + } + + @DisplayName("Exception: with null service id should throw IllegalArgumentException") + @Test + public void testWithEmptyClassification() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getServiceFee(SubmissionFeeRequest.builder() + .serviceType(TEST) + .application(TEST) + .create())); + + } + + @DisplayName("Exception: with null service id should throw IllegalArgumentException") + @Test + public void testWithEmptyDivision() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getServiceFee(SubmissionFeeRequest.builder() + .serviceType(TEST) + .application(TEST) + .classification(TEST) + .create())); + + } + + @DisplayName("Exception: with null service id should throw IllegalArgumentException") + @Test + public void testWithEmptyLevel() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getServiceFee(SubmissionFeeRequest.builder() + .serviceType(TEST) + .application(TEST) + .classification(TEST) + .division(TEST) + .create())); + + } + + @DisplayName("OK: getServiceFee called with any non-empty serviceId") + @Test + public void testWithPopulatedServiceId() { + + ServiceFees actual = sut.getServiceFee(SubmissionFeeRequest.builder() + .application(TEST) + .classification(TEST) + .division(TEST) + .level(TEST) + .serviceType(SERVICE_TYPE).create()); + Assertions.assertEquals(BigDecimal.TEN, actual.getFeeAmount()); + Assertions.assertEquals(SERVICE_TYPE_CD, actual.getServiceTypeCd()); + } + + @DisplayName("Exception: with NestedEjbException_Exception should throw EfilingLookupServiceException") + @Test + public void whenNestedEjbException_ExceptionShouldThrowEfilingLookupServiceException() { + + Assertions.assertThrows(EfilingLookupServiceException.class, () -> sut.getServiceFee(SubmissionFeeRequest.builder() + .application(TEST) + .classification(TEST) + .division(TEST) + .level(TEST) + .serviceType(SERVICE_ID_EXCEPTION).create())); + + } + + @DisplayName("OK: with null result should throw EfilingLookupServiceException") + @Test + public void whenNullResultShouldThrowEfilingLookupServiceException() { + + ServiceFees actual = sut.getServiceFee(SubmissionFeeRequest.builder() + .application(TEST) + .classification(TEST) + .division(TEST) + .level(TEST) + .serviceType(SERVICE_ID_NULL).create()); + + Assertions.assertEquals(BigDecimal.ZERO, actual.getFeeAmount()); + Assertions.assertNull(actual.getServiceTypeCd()); + + } + +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoLookupService/GetCountriesTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoLookupService/GetCountriesTest.java new file mode 100644 index 0000000000..f773a4e3ec --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoLookupService/GetCountriesTest.java @@ -0,0 +1,126 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoLookupService; + +import ca.bc.gov.ag.csows.lookups.CodeValue; +import ca.bc.gov.ag.csows.lookups.LookupFacadeBean; +import ca.bc.gov.ag.csows.lookups.NestedEjbException_Exception; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingLookupServiceException; +import ca.bc.gov.open.jag.efilingcommons.submission.models.LookupItem; +import ca.bc.gov.open.jag.efilingcsoclient.CsoLookupServiceImpl; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Efiling Get Countries Test") +public class GetCountriesTest { + + private static final String TEST = "TEST"; + private static final String TEST_1 = "TEST_1"; + private static final String TEST_2 = "TEST_2"; + + CsoLookupServiceImpl sut; + + @Mock + LookupFacadeBean lookupFacadeBeanMock; + + @BeforeEach + public void beforeEach() throws NestedEjbException_Exception { + + MockitoAnnotations.openMocks(this); + + sut = new CsoLookupServiceImpl(lookupFacadeBeanMock); + + } + + @DisplayName("OK: getCountries called ") + @Test + public void testGetCountriesNoError() throws NestedEjbException_Exception { + + Mockito + .when(lookupFacadeBeanMock.getCountryCodes()) + .thenReturn(createCodeList()); + + Mockito + .when(lookupFacadeBeanMock.getCountries()) + .thenReturn(createCodeList()); + + List actual = sut.getCountries(); + Assertions.assertEquals(2, actual.size()); + + Assertions.assertEquals(TEST_1, actual.get(0).getCode()); + Assertions.assertEquals(TEST, actual.get(0).getDescription()); + + Assertions.assertEquals(TEST_2, actual.get(1).getCode()); + Assertions.assertEquals(TEST, actual.get(1).getDescription()); + + } + + @DisplayName("OK: getCountries missing description ") + @Test + public void testGetCountriesMissingDescription() throws NestedEjbException_Exception { + + Mockito + .when(lookupFacadeBeanMock.getCountryCodes()) + .thenReturn(createCodeList()); + + Mockito + .when(lookupFacadeBeanMock.getCountries()) + .thenReturn(createMissingCountryList()); + + List actual = sut.getCountries(); + Assertions.assertEquals(2, actual.size()); + + Assertions.assertEquals(TEST_1, actual.get(0).getCode()); + Assertions.assertEquals("Missing Description", actual.get(0).getDescription()); + + Assertions.assertEquals(TEST_2, actual.get(1).getCode()); + Assertions.assertEquals(TEST, actual.get(1).getDescription()); + + } + + @DisplayName("Exception: with NestedEjbException_Exception should throw EfilingLookupServiceException") + @Test + public void whenNestedEjbException_ExceptionShouldThrowEfilingLookupServiceException() throws NestedEjbException_Exception { + + + Mockito + .when(lookupFacadeBeanMock.getCountryCodes()) + .thenThrow(new NestedEjbException_Exception("random")); + + Assertions.assertThrows(EfilingLookupServiceException.class, () -> sut.getCountries()); + + } + + private List createCodeList() { + + CodeValue codeOne = new CodeValue(); + codeOne.setCode(TEST_1); + codeOne.setParentCode(TEST_1); + codeOne.setDescription(GetCountriesTest.TEST); + + CodeValue codeTwo = new CodeValue(); + codeTwo.setCode(TEST_2); + codeTwo.setParentCode(TEST_2); + codeTwo.setDescription(TEST); + + return Arrays.asList(codeOne, codeTwo); + + } + + private List createMissingCountryList() { + + CodeValue codeTwo = new CodeValue(); + codeTwo.setCode(TEST_2); + codeTwo.setDescription(TEST); + + return Collections.singletonList(codeTwo); + + } + +} + diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoLookupService/ServiceFeesTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoLookupService/ServiceFeesTest.java new file mode 100644 index 0000000000..aa1d67fb02 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoLookupService/ServiceFeesTest.java @@ -0,0 +1,26 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoLookupService; + +import ca.bc.gov.open.jag.efilingcommons.model.ServiceFees; +import org.junit.jupiter.api.*; + +import java.math.BigDecimal; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Efiling ServiceFees Test") +public class ServiceFeesTest { + + private ServiceFees sut; + private static final String serviceId = "ServiceID"; + + @BeforeAll + public void setUp() { + sut = new ServiceFees(BigDecimal.ZERO, serviceId); + } + + @DisplayName("CASE 1: Testing Service Fees Constructor") + @Test + public void testServiceFeesConstructor() { + Assertions.assertEquals(serviceId, sut.getServiceTypeCd()); + Assertions.assertEquals(BigDecimal.ZERO, sut.getFeeAmount()); + } +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/DeleteSubmittedDocumentTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/DeleteSubmittedDocumentTest.java new file mode 100644 index 0000000000..8ac32a04c2 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/DeleteSubmittedDocumentTest.java @@ -0,0 +1,89 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoReviewServiceImpl; + +import ca.bc.gov.ag.csows.filing.FilingFacadeBean; +import ca.bc.gov.ag.csows.filing.NestedEjbException_Exception; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingReviewServiceException; +import ca.bc.gov.open.jag.efilingcommons.submission.models.DeleteSubmissionDocumentRequest; +import ca.bc.gov.open.jag.efilingcsoclient.CsoReviewServiceImpl; +import ca.bc.gov.open.jag.efilingcsoclient.config.CsoProperties; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.FilePackageMapperImpl; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.web.client.RestTemplate; + +import java.math.BigDecimal; + + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Review Service Test Suite") +public class DeleteSubmittedDocumentTest { + @Mock + FilingFacadeBean filingFacadeBeanMock; + + private static CsoReviewServiceImpl sut; + + @Mock + private RestTemplate restTemplateMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + + CsoProperties csoProperties = new CsoProperties(); + csoProperties.setCsoBasePath("http://locahost:8080"); + sut = new CsoReviewServiceImpl(null, null, filingFacadeBeanMock, new FilePackageMapperImpl(), csoProperties, restTemplateMock, null); + } + + @DisplayName("OK: document withdrawn") + @Test + public void testWithFoundResult() throws NestedEjbException_Exception { + + Mockito.doNothing().when(filingFacadeBeanMock).updateDocumentStatus(Mockito.any()); + Mockito.doNothing().when(filingFacadeBeanMock).inactivateReferrals(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doNothing().when(filingFacadeBeanMock).removePackageParties(Mockito.any()); + + Assertions.assertDoesNotThrow(() -> sut.deleteSubmittedDocument(new DeleteSubmissionDocumentRequest(BigDecimal.ONE, BigDecimal.ONE, null,"1"))); + + } + + @DisplayName("Exception: updateDocumentStatus document not withdrawn") + @Test + public void testWithUpdateDocumentStatusException() throws NestedEjbException_Exception { + + Mockito.doThrow(NestedEjbException_Exception.class).when(filingFacadeBeanMock).updateDocumentStatus(Mockito.any()); + Mockito.doNothing().when(filingFacadeBeanMock).inactivateReferrals(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doNothing().when(filingFacadeBeanMock).removePackageParties(Mockito.any()); + + Assertions.assertThrows(EfilingReviewServiceException.class, () -> sut.deleteSubmittedDocument(new DeleteSubmissionDocumentRequest(BigDecimal.ONE, BigDecimal.ONE, null,"1"))); + + } + + @DisplayName("Exception: inactivateReferrals document not withdrawn") + @Test + public void testWithInactivateReferralsException() throws NestedEjbException_Exception { + + Mockito.doNothing().when(filingFacadeBeanMock).updateDocumentStatus(Mockito.any()); + Mockito.doThrow(NestedEjbException_Exception.class).when(filingFacadeBeanMock).inactivateReferrals(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doNothing().when(filingFacadeBeanMock).removePackageParties(Mockito.any()); + + Assertions.assertThrows(EfilingReviewServiceException.class, () -> sut.deleteSubmittedDocument(new DeleteSubmissionDocumentRequest(BigDecimal.ONE, BigDecimal.ONE, null,"1"))); + + } + + @DisplayName("Exception: removePackageParties document not withdrawn") + @Test + public void testWithRemovePackagePartiesException() throws NestedEjbException_Exception { + + Mockito.doNothing().when(filingFacadeBeanMock).updateDocumentStatus(Mockito.any()); + Mockito.doNothing().when(filingFacadeBeanMock).inactivateReferrals(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doThrow(NestedEjbException_Exception.class).when(filingFacadeBeanMock).removePackageParties(Mockito.any()); + + Assertions.assertThrows(EfilingReviewServiceException.class, () -> sut.deleteSubmittedDocument(new DeleteSubmissionDocumentRequest(BigDecimal.ONE, BigDecimal.ONE,null, "1"))); + + } + +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/FindPackageByIdTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/FindPackageByIdTest.java new file mode 100644 index 0000000000..0580936aaa --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/FindPackageByIdTest.java @@ -0,0 +1,290 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoReviewServiceImpl; + +import ca.bc.gov.ag.csows.filing.status.*; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingStatusServiceException; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackageRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.LookupItem; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewFilingPackage; +import ca.bc.gov.open.jag.efilingcommons.utils.DateUtils; +import ca.bc.gov.open.jag.efilingcsoclient.CsoReviewServiceImpl; +import ca.bc.gov.open.jag.efilingcsoclient.Keys; +import ca.bc.gov.open.jag.efilingcsoclient.config.CsoProperties; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.FilePackageMapperImpl; +import org.joda.time.DateTime; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.web.client.RestTemplate; + +import javax.xml.datatype.DatatypeConfigurationException; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Review Service Test Suite") +public class FindPackageByIdTest { + private static final String CLIENT_FILE_NO = "CLIENTFILENO"; + private static final String COURT_CLASS_CD = "CLASSCD"; + private static final String COURT_FILE_NO = "FILENO"; + private static final String COURT_LEVEL_CD = "LEVELCD"; + private static final String COURT_LOCATION_CD = "LOCATIONCD"; + private static final String COURT_LOCATION_NAME = "LOCATIONAME"; + private static final String FILING_COMMENTS_TXT = "COMMENTSTXT"; + private static final String FIRST_NAME = "FIRSTNAME"; + private static final String LAST_NAME = "LASTNAME"; + private static final String PACKAGE_NO = "PACKAGENO"; + private static final String REASON_TXT = "ReasonTxt"; + private static final DateTime SUBMITED_DATE = new DateTime(2020, 12, 12, 1, 1); + private static final String EMAIL = "EMAIL"; + private static final String PHONE = "PHONE"; + private static final String COUNTRY_ONE = "COUNTRY ONE"; + private static final String COUNTRY_TEN = "COUNTRY TEN"; + private static final String PROCESSING_COMMENT_TXT = "PROCESSTEXT"; + private static final String FILE_GUID = UUID.randomUUID().toString(); + private static final String FILE_PDF = "FILE.pdf"; + + @Mock + FilingStatusFacadeBean filingStatusFacadeBean; + + @Mock + private RestTemplate restTemplateMock; + + @Mock + private EfilingLookupService efilingLookupService; + + private final BigDecimal SUCCESS_CLIENT = BigDecimal.ONE; + + private final BigDecimal SUCCESS_PACKAGE = BigDecimal.ONE; + + private final BigDecimal SUCCESS_REJECTED_CLIENT = BigDecimal.valueOf(11); + private final BigDecimal SUCCESS_REJECTED_PACKAGE = BigDecimal.valueOf(11); + + private final BigDecimal SUCCESS_COMPLETE_CLIENT = BigDecimal.valueOf(12); + private final BigDecimal SUCCESS_COMPLETE_PACKAGE = BigDecimal.valueOf(12); + + private final BigDecimal EXCEPTION_CLIENT = BigDecimal.TEN; + private final BigDecimal EXCEPTION_PACKAGE = BigDecimal.TEN; + + private final BigDecimal NOTFOUND_CLIENT = BigDecimal.ZERO; + private final BigDecimal NOTFOUND_PACKAGE = BigDecimal.ZERO; + + private final BigDecimal ACCOUNT = BigDecimal.ONE; + + private static CsoReviewServiceImpl sut; + + + @BeforeAll + public void beforeAll() throws NestedEjbException_Exception, DatatypeConfigurationException { + + MockitoAnnotations.openMocks(this); + + FilingStatus filingStatus = createFilingStatus(); + FilePackage pendingFilePackage = createFilePackage(); + File documentPending = new File(); + documentPending.setStatus(Keys.CSO_DOCUMENT_REFERRED); + pendingFilePackage.getFiles().add(documentPending); + filingStatus.getFilePackages().add(pendingFilePackage); + + FilingStatus filingRejectedStatus = createFilingStatus(); + FilePackage rejectedFilePackage = createFilePackage(); + File documentRejected = new File(); + documentRejected.setStatus(Keys.CSO_DOCUMENT_REJECTED); + rejectedFilePackage.getFiles().add(documentRejected); + filingRejectedStatus.getFilePackages().add(rejectedFilePackage); + + FilingStatus filingCompleteStatus = createFilingStatus(); + FilePackage completeFilePackage = createFilePackage(); + File documentComplete = new File(); + documentComplete.setStatus("COMPLETE"); + rejectedFilePackage.getFiles().add(documentComplete); + filingCompleteStatus.getFilePackages().add(completeFilePackage); + + Mockito.when(filingStatusFacadeBean.findStatusBySearchCriteria(any(), any(), any(), any(), any(), any(), ArgumentMatchers.eq(SUCCESS_PACKAGE), ArgumentMatchers.eq(SUCCESS_CLIENT), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(filingStatus); + + Mockito.when(filingStatusFacadeBean.findStatusBySearchCriteria(any(), any(), any(), any(), any(), any(), ArgumentMatchers.eq(SUCCESS_REJECTED_PACKAGE), ArgumentMatchers.eq(SUCCESS_REJECTED_CLIENT), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(filingRejectedStatus); + + Mockito.when(filingStatusFacadeBean.findStatusBySearchCriteria(any(), any(), any(), any(), any(), any(), ArgumentMatchers.eq(SUCCESS_COMPLETE_PACKAGE), ArgumentMatchers.eq(SUCCESS_COMPLETE_CLIENT), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(filingCompleteStatus); + + Mockito.when(filingStatusFacadeBean.findStatusBySearchCriteria(any(), any(), any(), any(), any(), any(), ArgumentMatchers.eq(NOTFOUND_PACKAGE), ArgumentMatchers.eq(NOTFOUND_CLIENT), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(createFilingStatus()); + + Mockito.when(filingStatusFacadeBean.findStatusBySearchCriteria(any(), any(), any(), any(), any(), any(), ArgumentMatchers.eq(EXCEPTION_PACKAGE), ArgumentMatchers.eq(EXCEPTION_CLIENT), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenThrow(new NestedEjbException_Exception()); + + Mockito.when(efilingLookupService.getCountries()).thenReturn(createCountryList()); + + CsoProperties csoProperties = new CsoProperties(); + csoProperties.setCsoBasePath("http://locahost:8080"); + + sut = new CsoReviewServiceImpl(filingStatusFacadeBean, null, null, new FilePackageMapperImpl(), csoProperties, restTemplateMock, efilingLookupService); + } + + @DisplayName("OK: package found pending status") + @Test + public void testWithFoundResult() throws DatatypeConfigurationException { + + Optional result = sut.findStatusByPackage(new FilingPackageRequest(SUCCESS_CLIENT, ACCOUNT, SUCCESS_PACKAGE, null)); + + Assertions.assertEquals(COURT_FILE_NO, result.get().getCourt().getFileNumber()); + Assertions.assertEquals(COURT_CLASS_CD, result.get().getCourt().getCourtClass()); + Assertions.assertEquals(COURT_LEVEL_CD, result.get().getCourt().getLevel()); + Assertions.assertEquals(COURT_LOCATION_CD, result.get().getCourt().getLocationCd()); + Assertions.assertEquals(COURT_LOCATION_NAME, result.get().getCourt().getLocationName()); + Assertions.assertEquals(COURT_LOCATION_NAME, result.get().getCourt().getLocationName()); + Assertions.assertEquals(REASON_TXT, result.get().getRushOrder().getRushFilingReasonTxt()); + Assertions.assertEquals(COUNTRY_ONE, result.get().getRushOrder().getCountryDsc()); + Assertions.assertEquals(EMAIL, result.get().getRushOrder().getContactEmailTxt()); + Assertions.assertEquals(FIRST_NAME, result.get().getRushOrder().getContactFirstGivenNm()); + Assertions.assertEquals(PHONE, result.get().getRushOrder().getContactPhoneNo()); + Assertions.assertEquals(LAST_NAME, result.get().getRushOrder().getContactSurnameNm()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getPackageId()); + Assertions.assertEquals(PROCESSING_COMMENT_TXT, result.get().getRushOrder().getProcessingCommentTxt()); + Assertions.assertEquals(1, result.get().getRushOrder().getSupportDocs().size()); + Assertions.assertEquals(FILE_GUID, result.get().getRushOrder().getSupportDocs().get(0).getObjectGuid()); + Assertions.assertEquals(FILE_PDF, result.get().getRushOrder().getSupportDocs().get(0).getClientFileNm()); + Assertions.assertEquals(Keys.PACKAGE_STATUS_PENDING, result.get().getStatus()); + + } + + @DisplayName("OK: package found rejected status") + @Test + public void testWithFoundResultRejected() throws DatatypeConfigurationException { + + Optional result = sut.findStatusByPackage(new FilingPackageRequest(SUCCESS_REJECTED_CLIENT, ACCOUNT, SUCCESS_REJECTED_PACKAGE, null)); + + Assertions.assertEquals(COURT_FILE_NO, result.get().getCourt().getFileNumber()); + Assertions.assertEquals(COURT_CLASS_CD, result.get().getCourt().getCourtClass()); + Assertions.assertEquals(COURT_LEVEL_CD, result.get().getCourt().getLevel()); + Assertions.assertEquals(COURT_LOCATION_CD, result.get().getCourt().getLocationCd()); + Assertions.assertEquals(COURT_LOCATION_NAME, result.get().getCourt().getLocationName()); + Assertions.assertEquals(COURT_LOCATION_NAME, result.get().getCourt().getLocationName()); + Assertions.assertEquals(REASON_TXT, result.get().getRushOrder().getRushFilingReasonTxt()); + Assertions.assertEquals(COUNTRY_ONE, result.get().getRushOrder().getCountryDsc()); + Assertions.assertEquals(EMAIL, result.get().getRushOrder().getContactEmailTxt()); + Assertions.assertEquals(FIRST_NAME, result.get().getRushOrder().getContactFirstGivenNm()); + Assertions.assertEquals(PHONE, result.get().getRushOrder().getContactPhoneNo()); + Assertions.assertEquals(LAST_NAME, result.get().getRushOrder().getContactSurnameNm()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getPackageId()); + Assertions.assertEquals(PROCESSING_COMMENT_TXT, result.get().getRushOrder().getProcessingCommentTxt()); + Assertions.assertEquals(1, result.get().getRushOrder().getSupportDocs().size()); + Assertions.assertEquals(FILE_GUID, result.get().getRushOrder().getSupportDocs().get(0).getObjectGuid()); + Assertions.assertEquals(FILE_PDF, result.get().getRushOrder().getSupportDocs().get(0).getClientFileNm()); + Assertions.assertEquals(Keys.PACKAGE_STATUS_ACTION_REQUIRED, result.get().getStatus()); + + } + + @DisplayName("OK: package found complete status") + @Test + public void testWithFoundResultComplete() throws DatatypeConfigurationException { + + Optional result = sut.findStatusByPackage(new FilingPackageRequest(SUCCESS_COMPLETE_CLIENT, ACCOUNT, SUCCESS_COMPLETE_PACKAGE, null)); + + Assertions.assertEquals(COURT_FILE_NO, result.get().getCourt().getFileNumber()); + Assertions.assertEquals(COURT_CLASS_CD, result.get().getCourt().getCourtClass()); + Assertions.assertEquals(COURT_LEVEL_CD, result.get().getCourt().getLevel()); + Assertions.assertEquals(COURT_LOCATION_CD, result.get().getCourt().getLocationCd()); + Assertions.assertEquals(COURT_LOCATION_NAME, result.get().getCourt().getLocationName()); + Assertions.assertEquals(COURT_LOCATION_NAME, result.get().getCourt().getLocationName()); + Assertions.assertEquals(REASON_TXT, result.get().getRushOrder().getRushFilingReasonTxt()); + Assertions.assertEquals(COUNTRY_ONE, result.get().getRushOrder().getCountryDsc()); + Assertions.assertEquals(EMAIL, result.get().getRushOrder().getContactEmailTxt()); + Assertions.assertEquals(FIRST_NAME, result.get().getRushOrder().getContactFirstGivenNm()); + Assertions.assertEquals(PHONE, result.get().getRushOrder().getContactPhoneNo()); + Assertions.assertEquals(LAST_NAME, result.get().getRushOrder().getContactSurnameNm()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getPackageId()); + Assertions.assertEquals(PROCESSING_COMMENT_TXT, result.get().getRushOrder().getProcessingCommentTxt()); + Assertions.assertEquals(1, result.get().getRushOrder().getSupportDocs().size()); + Assertions.assertEquals(FILE_GUID, result.get().getRushOrder().getSupportDocs().get(0).getObjectGuid()); + Assertions.assertEquals(FILE_PDF, result.get().getRushOrder().getSupportDocs().get(0).getClientFileNm()); + Assertions.assertEquals(Keys.PACKAGE_STATUS_COMPLETE, result.get().getStatus()); + + } + + @DisplayName("Ok: no packages found") + @Test + public void testWithNoResult() { + + Optional result = sut.findStatusByPackage(new FilingPackageRequest(NOTFOUND_CLIENT, ACCOUNT, NOTFOUND_PACKAGE, null)); + Assertions.assertFalse(result.isPresent()); + + } + + @DisplayName("Exception: filing status facade throws an exception") + @Test + public void testWithException() { + Assertions.assertThrows(EfilingStatusServiceException.class, () -> sut.findStatusByPackage(new FilingPackageRequest(EXCEPTION_CLIENT, ACCOUNT, EXCEPTION_PACKAGE, null))); + } + + private FilingStatus createFilingStatus() { + FilingStatus filingStatus = new FilingStatus(); + filingStatus.setRecordsFrom(BigDecimal.ONE); + filingStatus.setRecordsTo(BigDecimal.ONE); + filingStatus.setTotalRecords(BigDecimal.ONE); + return filingStatus; + } + + private FilePackage createFilePackage() throws DatatypeConfigurationException { + FilePackage filePackage = new FilePackage(); + filePackage.setClientFileNo(CLIENT_FILE_NO); + filePackage.setCourtClassCd(COURT_CLASS_CD); + filePackage.setCourtFileNo(COURT_FILE_NO); + filePackage.setCourtLevelCd(COURT_LEVEL_CD); + filePackage.setCourtLocationCd(COURT_LOCATION_CD); + filePackage.setCourtLocationId(BigDecimal.ONE); + filePackage.setCourtLocationName(COURT_LOCATION_NAME); + filePackage.setExistingCourtFileYN(true); + filePackage.setFilingCommentsTxt(FILING_COMMENTS_TXT); + filePackage.setFirstName(FIRST_NAME); + filePackage.setHasChecklist(true); + filePackage.setHasRegistryNotice(true); + filePackage.setLastName(LAST_NAME); + filePackage.setPackageNo(PACKAGE_NO); + + filePackage.setProcRequest(createRushOrderRequest()); + filePackage.setSubmittedDate(DateUtils.getXmlDate(SUBMITED_DATE)); + return filePackage; + } + + private RushOrderRequest createRushOrderRequest() { + RushOrderRequest rushOrderRequest = new RushOrderRequest(); + + rushOrderRequest.setContactEmailTxt(EMAIL); + rushOrderRequest.setContactFirstGivenNm(FIRST_NAME); + rushOrderRequest.setContactPhoneNo(PHONE); + rushOrderRequest.setContactSurnameNm(LAST_NAME); + rushOrderRequest.setCtryId(BigDecimal.ONE); + rushOrderRequest.setProcessingCommentTxt(PROCESSING_COMMENT_TXT); + + RushOrderRequestItem rushOrderRequestItem = new RushOrderRequestItem(); + + rushOrderRequestItem.setPackageId(BigDecimal.ONE); + rushOrderRequestItem.setRushFilingReasonTxt(REASON_TXT); + + ProcessSupportDocument processSupportDocument = new ProcessSupportDocument(); + processSupportDocument.setClientFileNm(FILE_PDF); + processSupportDocument.setObjectGuid(FILE_GUID); + rushOrderRequestItem.getSupportDocs().add(processSupportDocument); + + rushOrderRequest.setItem(rushOrderRequestItem); + + return rushOrderRequest; + } + + private List createCountryList() { + return Arrays.asList(LookupItem.builder() + .code(BigDecimal.ONE.toEngineeringString()) + .description(COUNTRY_ONE) + .create(), + LookupItem.builder() + .code(BigDecimal.TEN.toEngineeringString()) + .description(COUNTRY_TEN) + .create()); + } + +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/FindPackagesByClientIdTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/FindPackagesByClientIdTest.java new file mode 100644 index 0000000000..201165d8ff --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/FindPackagesByClientIdTest.java @@ -0,0 +1,139 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoReviewServiceImpl; + +import ca.bc.gov.ag.csows.filing.status.FilePackage; +import ca.bc.gov.ag.csows.filing.status.FilingStatus; +import ca.bc.gov.ag.csows.filing.status.FilingStatusFacadeBean; +import ca.bc.gov.ag.csows.filing.status.NestedEjbException_Exception; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingStatusServiceException; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackageRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewFilingPackage; +import ca.bc.gov.open.jag.efilingcommons.utils.DateUtils; +import ca.bc.gov.open.jag.efilingcsoclient.CsoReviewServiceImpl; +import ca.bc.gov.open.jag.efilingcsoclient.config.CsoProperties; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.FilePackageMapperImpl; +import org.joda.time.DateTime; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.web.client.RestTemplate; + +import javax.xml.datatype.DatatypeConfigurationException; +import java.math.BigDecimal; +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Review Service Test Suite") +public class FindPackagesByClientIdTest { + private static final String CLIENT_FILE_NO = "CLIENTFILENO"; + private static final String COURT_CLASS_CD = "CLASSCD"; + private static final String COURT_FILE_NO = "FILENO"; + private static final String COURT_LEVEL_CD = "LEVELCD"; + private static final String COURT_LOCATION_CD = "LOCATIONCD"; + private static final String COURT_LOCATION_NAME = "LOCATIONAME"; + private static final String FILING_COMMENTS_TXT = "COMMENTSTXT"; + private static final String FIRST_NAME = "FIRSTNAME"; + private static final String LAST_NAME = "LASTNAME"; + private static final String PACKAGE_NO = "PACKAGENO"; + private static final DateTime SUBMITED_DATE = new DateTime(2020, 12, 12, 1, 1); + private static final String PARENT_APPLICATION = "PARENTAPP"; + private static final BigDecimal ACCOUNT = BigDecimal.ONE; + + @Mock + FilingStatusFacadeBean filingStatusFacadeBean; + + @Mock + private RestTemplate restTemplateMock; + + @Mock + private EfilingLookupService efilingLookupService; + + private final BigDecimal SUCCESS_CLIENT = BigDecimal.ONE; + + private final BigDecimal EXCEPTION_CLIENT = BigDecimal.TEN; + + private final BigDecimal NOTFOUND_CLIENT = BigDecimal.ZERO; + + private static CsoReviewServiceImpl sut; + + @BeforeAll + public void beforeAll() throws NestedEjbException_Exception, DatatypeConfigurationException { + + MockitoAnnotations.openMocks(this); + + FilingStatus filingStatus = createFilingStatus(); + filingStatus.getFilePackages().add(createFilePackage()); + + Mockito.when(filingStatusFacadeBean.findStatusBySearchCriteria(any(), any(), any(), any(), any(), any(), any(), ArgumentMatchers.eq(SUCCESS_CLIENT), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(filingStatus); + + Mockito.when(filingStatusFacadeBean.findStatusBySearchCriteria(any(), any(), any(), any(), any(), any(), any(), ArgumentMatchers.eq(NOTFOUND_CLIENT), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(createFilingStatus()); + + Mockito.when(filingStatusFacadeBean.findStatusBySearchCriteria(any(), any(), any(), any(), any(), any(), any(), ArgumentMatchers.eq(EXCEPTION_CLIENT), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenThrow(new NestedEjbException_Exception()); + + CsoProperties csoProperties = new CsoProperties(); + csoProperties.setCsoBasePath("http://locahost:8080"); + sut = new CsoReviewServiceImpl(filingStatusFacadeBean, null, null, new FilePackageMapperImpl(), csoProperties, restTemplateMock, null); + } + + @DisplayName("OK: packages found") + @Test + public void testWithFoundResult() throws DatatypeConfigurationException { + List result = sut.findStatusByClient(new FilingPackageRequest(SUCCESS_CLIENT, ACCOUNT, null, PARENT_APPLICATION)); + + Assertions.assertEquals(1, result.size()); + Assertions.assertEquals(COURT_FILE_NO, result.get(0).getCourt().getFileNumber()); + Assertions.assertEquals(COURT_CLASS_CD, result.get(0).getCourt().getCourtClass()); + Assertions.assertEquals(COURT_LEVEL_CD, result.get(0).getCourt().getLevel()); + Assertions.assertEquals(COURT_LOCATION_CD, result.get(0).getCourt().getLocationCd()); + Assertions.assertEquals(COURT_LOCATION_NAME, result.get(0).getCourt().getLocationName()); + Assertions.assertEquals("http://locahost:8080/accounts/filingStatus.do?actionType=filterStatus&useFilter=ALL", result.get(0).getPackageLinks().getPackageHistoryUrl()); + + } + + @DisplayName("Ok: no packages found") + @Test + public void testWithNoResult() { + List result = sut.findStatusByClient(new FilingPackageRequest(NOTFOUND_CLIENT, ACCOUNT, null, PARENT_APPLICATION)); + + Assertions.assertTrue(result.isEmpty()); + + } + + @DisplayName("Exception: filing status facade throws an exception") + @Test + public void testWithException() { + Assertions.assertThrows(EfilingStatusServiceException.class, () -> sut.findStatusByClient(new FilingPackageRequest(EXCEPTION_CLIENT, ACCOUNT, null, PARENT_APPLICATION))); + } + + private FilingStatus createFilingStatus() { + FilingStatus filingStatus = new FilingStatus(); + filingStatus.setRecordsFrom(BigDecimal.ONE); + filingStatus.setRecordsTo(BigDecimal.ONE); + filingStatus.setTotalRecords(BigDecimal.ONE); + return filingStatus; + } + + private FilePackage createFilePackage() throws DatatypeConfigurationException { + FilePackage filePackage = new FilePackage(); + filePackage.setClientFileNo(CLIENT_FILE_NO); + filePackage.setCourtClassCd(COURT_CLASS_CD); + filePackage.setCourtFileNo(COURT_FILE_NO); + filePackage.setCourtLevelCd(COURT_LEVEL_CD); + filePackage.setCourtLocationCd(COURT_LOCATION_CD); + filePackage.setCourtLocationId(BigDecimal.ONE); + filePackage.setCourtLocationName(COURT_LOCATION_NAME); + filePackage.setExistingCourtFileYN(true); + filePackage.setFilingCommentsTxt(FILING_COMMENTS_TXT); + filePackage.setFirstName(FIRST_NAME); + filePackage.setHasChecklist(true); + filePackage.setHasRegistryNotice(true); + filePackage.setLastName(LAST_NAME); + filePackage.setPackageNo(PACKAGE_NO); + filePackage.setSubmittedDate(DateUtils.getXmlDate(SUBMITED_DATE)); + return filePackage; + } +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/GetReportTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/GetReportTest.java new file mode 100644 index 0000000000..8fd5d40145 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/GetReportTest.java @@ -0,0 +1,104 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoReviewServiceImpl; + +import ca.bc.gov.ag.csows.reports.ReportService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.ReportRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.ReportsTypes; +import ca.bc.gov.open.jag.efilingcsoclient.CsoReviewServiceImpl; +import ca.bc.gov.open.jag.efilingcsoclient.config.CsoProperties; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.FilePackageMapperImpl; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.web.client.RestTemplate; + +import java.math.BigDecimal; +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("GetPaymentReceiptTest") +public class GetReportTest { + public static final String FILE_NAME = "TEST"; + @Mock + ReportService reportServiceMock; + + @Mock + private RestTemplate restTemplateMock; + + private static final byte[] SUCCESS = "TEST".getBytes(); + + private static CsoReviewServiceImpl sut; + + @BeforeEach + public void beforeEach() { + + MockitoAnnotations.openMocks(this); + + CsoProperties csoProperties = new CsoProperties(); + csoProperties.setCsoBasePath("http://locahost:8080"); + + sut = new CsoReviewServiceImpl(null, reportServiceMock, null, new FilePackageMapperImpl(), csoProperties, restTemplateMock, null); + } + + @DisplayName("OK: submission sheet return") + @Test + public void testWithSubmissionSheetFoundResult() { + + Mockito.when(reportServiceMock.runReport(any())).thenReturn(SUCCESS); + + Optional result = sut.getReport(ReportRequest.builder().fileName(FILE_NAME).packageId(BigDecimal.ONE).report(ReportsTypes.SUBMISSION_SHEET).create()); + + Assertions.assertTrue(result.isPresent()); + Assertions.assertEquals(SUCCESS, result.get()); + + } + + @DisplayName("OK: receipt return") + @Test + public void testWithReceiptFoundResult() { + + Mockito.when(reportServiceMock.runReport(any())).thenReturn(SUCCESS); + + Optional result = sut.getReport(ReportRequest.builder().fileName(FILE_NAME).packageId(BigDecimal.ONE).report(ReportsTypes.PAYMENT_RECEIPT).create()); + + Assertions.assertTrue(result.isPresent()); + Assertions.assertEquals(SUCCESS, result.get()); + + } + + @DisplayName("OK: registry notice return") + @Test + public void testWithRegistryNoticeResult() { + + Mockito.when(reportServiceMock.runReport(any())).thenReturn(SUCCESS); + + Optional result = sut.getReport(ReportRequest.builder().fileName(FILE_NAME).packageId(BigDecimal.ONE).report(ReportsTypes.REGISTRY_NOTICE).create()); + + Assertions.assertTrue(result.isPresent()); + Assertions.assertEquals(SUCCESS, result.get()); + + } + + @DisplayName("OK: null result ") + @Test + public void testWithNullResult() { + Mockito.when(reportServiceMock.runReport(any())).thenReturn(null); + + Optional result = sut.getReport(ReportRequest.builder().fileName(FILE_NAME).packageId(BigDecimal.ONE).report(ReportsTypes.PAYMENT_RECEIPT).create()); + + Assertions.assertFalse(result.isPresent()); + } + + @DisplayName("OK: empty ") + @Test + public void testWithExceptionResult() { + Mockito.when(reportServiceMock.runReport(any())).thenReturn(new byte[0]); + + Optional result = sut.getReport(ReportRequest.builder().fileName(FILE_NAME).packageId(BigDecimal.ONE).report(ReportsTypes.PAYMENT_RECEIPT).create()); + + Assertions.assertFalse(result.isPresent()); + + } +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/GetRushDocumentTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/GetRushDocumentTest.java new file mode 100644 index 0000000000..4bb0dd961c --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/GetRushDocumentTest.java @@ -0,0 +1,86 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoReviewServiceImpl; + +import ca.bc.gov.ag.csows.filing.FilingFacadeBean; +import ca.bc.gov.ag.csows.filing.NestedEjbException_Exception; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingReviewServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.RushDocumentRequest; +import ca.bc.gov.open.jag.efilingcsoclient.CsoReviewServiceImpl; +import ca.bc.gov.open.jag.efilingcsoclient.config.CsoProperties; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.FilePackageMapperImpl; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import java.math.BigDecimal; +import java.util.Optional; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("GetRushDocumentTest") +public class GetRushDocumentTest { + + @Mock + private RestTemplate restTemplateMock; + + @Mock + FilingFacadeBean filingFacadeBeanMock; + + private static CsoReviewServiceImpl sut; + + @BeforeEach + public void beforeEach() throws NestedEjbException_Exception { + + MockitoAnnotations.openMocks(this); + + byte[] someBytes = "test".getBytes(); + + Mockito.when(filingFacadeBeanMock.getActiveSuppDocURL(Mockito.eq(BigDecimal.TEN), Mockito.eq(BigDecimal.TEN), Mockito.eq(BigDecimal.TEN))).thenThrow(new NestedEjbException_Exception()); + + Mockito.when(filingFacadeBeanMock.getActiveSuppDocURL(Mockito.eq(BigDecimal.ONE), Mockito.eq(BigDecimal.ONE), Mockito.eq(BigDecimal.ONE))).thenReturn("http://localhost/acdc/1"); + + + Mockito.when(restTemplateMock.getForEntity( + Mockito.eq("http://localhost/acdc/1"), Mockito.eq(byte[].class), Mockito.any(HttpEntity.class))) + .thenReturn(new ResponseEntity(someBytes, HttpStatus.OK)); + + CsoProperties csoProperties = new CsoProperties(); + csoProperties.setCsoBasePath("http://locahost:8080"); + + sut = new CsoReviewServiceImpl(null, null, filingFacadeBeanMock, new FilePackageMapperImpl(), null, restTemplateMock, null); + + } + + @DisplayName("OK: it is working") + @Test + public void testWithFoundResult() { + + Optional actual = sut.getRushDocument( + RushDocumentRequest.builder() + .procReqId(BigDecimal.ONE) + .docSeqNo(BigDecimal.ONE) + .procItemSeqNo(BigDecimal.ONE) + .create()); + Assertions.assertEquals("test", new String(actual.get())); + + } + + @DisplayName("Error: it can't generate URL") + @Test + public void testWhenCantGenerateUrl() { + + Assertions.assertThrows(EfilingReviewServiceException.class, () -> { + sut.getRushDocument( + RushDocumentRequest.builder() + .procItemSeqNo(BigDecimal.TEN) + .docSeqNo(BigDecimal.TEN) + .procReqId(BigDecimal.TEN) + .create()); + }); + + } + +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/GetSubmissionDocumentTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/GetSubmissionDocumentTest.java new file mode 100644 index 0000000000..ca374eba97 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoReviewServiceImpl/GetSubmissionDocumentTest.java @@ -0,0 +1,80 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoReviewServiceImpl; + +import ca.bc.gov.ag.csows.filing.FilingFacadeBean; +import ca.bc.gov.ag.csows.filing.NestedEjbException_Exception; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingReviewServiceException; +import ca.bc.gov.open.jag.efilingcsoclient.CsoReviewServiceImpl; +import ca.bc.gov.open.jag.efilingcsoclient.config.CsoProperties; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.FilePackageMapperImpl; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import java.math.BigDecimal; +import java.util.Optional; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("GetSubmissionDocumentTest") +public class GetSubmissionDocumentTest { + + + @Mock + private RestTemplate restTemplateMock; + + @Mock + FilingFacadeBean filingFacadeBeanMock; + + private static CsoReviewServiceImpl sut; + + @BeforeEach + public void beforeEach() throws NestedEjbException_Exception { + + MockitoAnnotations.openMocks(this); + + byte[] someBytes = "test".getBytes(); + + Mockito.when(filingFacadeBeanMock.getActiveDocumentURL(Mockito.eq(BigDecimal.TEN))).thenThrow(new NestedEjbException_Exception()); + + Mockito.when(filingFacadeBeanMock.getActiveDocumentURL(Mockito.eq(BigDecimal.ONE))).thenReturn("http://localhost/acdc/1"); + + + Mockito.when(restTemplateMock.getForEntity( + Mockito.eq("http://localhost/acdc/1"), Mockito.eq(byte[].class), Mockito.any(HttpEntity.class))) + .thenReturn(new ResponseEntity(someBytes, HttpStatus.OK)); + + Mockito.when(restTemplateMock.getForEntity( + Mockito.eq("http://localhost/acdc/1"), Mockito.eq(byte[].class), Mockito.any(HttpEntity.class))) + .thenReturn(new ResponseEntity(someBytes, HttpStatus.OK)); + + CsoProperties csoProperties = new CsoProperties(); + csoProperties.setCsoBasePath("http://locahost:8080"); + + sut = new CsoReviewServiceImpl(null, null, filingFacadeBeanMock, new FilePackageMapperImpl(), csoProperties, restTemplateMock, null); + + } + + @DisplayName("OK: it is working") + @Test + public void testWithFoundResult() { + + Optional actual = sut.getSubmittedDocument(BigDecimal.ONE); + Assertions.assertEquals("test", new String(actual.get())); + + } + + @DisplayName("Error: it can't generate URL") + @Test + public void testWhenCantGenerateUrl() { + + Assertions.assertThrows(EfilingReviewServiceException.class, () -> { + sut.getSubmittedDocument(BigDecimal.TEN); + }); + + } + +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoSearchServiceImpl/CaseNumberExistsTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoSearchServiceImpl/CaseNumberExistsTest.java new file mode 100644 index 0000000000..f3a3723621 --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoSearchServiceImpl/CaseNumberExistsTest.java @@ -0,0 +1,56 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoSearchServiceImpl; + +import ca.bc.gov.courts.appeal.ws.services.COACase; +import ca.bc.gov.courts.appeal.ws.services.CSOSearchSoap; +import ca.bc.gov.open.jag.efilingcsoclient.CsoSearchServiceImpl; +import org.junit.jupiter.api.*; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import static org.mockito.ArgumentMatchers.any; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Efiling Search Service Test") +public class CaseNumberExistsTest { + + public static final String CASE_NUMBER = "TEST"; + CsoSearchServiceImpl sut; + + @Mock + CSOSearchSoap csoSearchSoapMock; + + @BeforeAll + public void beforeAll() { + + MockitoAnnotations.openMocks(this); + + sut = new CsoSearchServiceImpl(csoSearchSoapMock); + + } + + @DisplayName("Exception: with null case number, service should throw IllegalArgumentException") + @Test + public void testWithEmptyCaseNumber() { + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.caseNumberExists(null)); + } + + @DisplayName("OK: existing caseNumber") + @Test + public void testExistingCaseNumber() { + + Mockito.when(csoSearchSoapMock.searchByCaseNumber(any())).thenReturn(new COACase()); + Assertions.assertTrue(sut.caseNumberExists(CASE_NUMBER)); + + } + + @DisplayName("OK: non existing caseNumber") + @Test + public void testNonExistingCaseNumber() { + + Mockito.when(csoSearchSoapMock.searchByCaseNumber(any())).thenReturn(null); + Assertions.assertFalse(sut.caseNumberExists(CASE_NUMBER)); + + } + +} diff --git a/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoSubmissionServiceImpl/SubmitFilingPackageTest.java b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoSubmissionServiceImpl/SubmitFilingPackageTest.java new file mode 100644 index 0000000000..5a517c489d --- /dev/null +++ b/src/backend/libs/efiling-cso-client/src/test/java/ca/bc/gov/open/jag/efilingcsoclient/csoSubmissionServiceImpl/SubmitFilingPackageTest.java @@ -0,0 +1,983 @@ +package ca.bc.gov.open.jag.efilingcsoclient.csoSubmissionServiceImpl; + +import ca.bc.gov.ag.csows.filing.FilingFacadeBean; +import ca.bc.gov.ag.csows.services.*; +import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingSubmissionServiceException; +import ca.bc.gov.open.jag.efilingcommons.model.*; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingPaymentService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; +import ca.bc.gov.open.jag.efilingcommons.utils.DateUtils; +import ca.bc.gov.open.jag.efilingcsoclient.CsoSubmissionServiceImpl; +import ca.bc.gov.open.jag.efilingcsoclient.Keys; +import ca.bc.gov.open.jag.efilingcsoclient.TestHelpers; +import ca.bc.gov.open.jag.efilingcsoclient.config.CsoProperties; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.*; +import org.joda.time.DateTime; +import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.XMLGregorianCalendar; +import java.math.BigDecimal; +import java.util.*; + +import static ca.bc.gov.open.jag.efilingcsoclient.Keys.RUSH_TYPES; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Efiling Submission Test") +public class SubmitFilingPackageTest { + + private static final String INTERNAL_CLIENT_NUMBER = "internalClientNumber"; + private static final String CARD_TYPE_CD = "V"; + private static final String REFERENCE_MESSAGE_TXT = "message"; + private static final String TRANSACTION_STATE_CD = "12"; + private static final String APPROVAL_CD = "APP"; + private static final String INVOICE_NO = "1234"; + private static final String USER_ID = "userId"; + private static final BigDecimal SERVICE_ID1 = new BigDecimal(5); + private static final BigDecimal TRANSACTION_AMT = new BigDecimal(2); + private static final DateTime TRANSACTON_DTM = DateTime.now(); + private static final DateTime PROCESS_DT = DateTime.now(); + private static final DateTime ENT_DTM = DateTime.now(); + private static final String APPROVED = "Approved"; + private static final String UNIVERSAL_ID = UUID.randomUUID().toString(); + private static final String LOCATION = "LOCATION"; + private static final String BAD_LOCATION = "BADLOCATION"; + private static final String COURT_CLASS = "courtClass"; + private static final String DIVISION = "DIVISION"; + private static final String LEVEL = "level"; + private static final BigDecimal AGENCY_ID = BigDecimal.TEN; + private static final String FILE_NUMBER = "fileNumber"; + private static final String DOCUMENT = "document"; + private static final String SERVERFILENAME = "serverfilename"; + private static final boolean IS_AMENDMENT = true; + private static final boolean IS_SUPREME_COURT_SCHEDULING = false; + private static final String APP_CODE = "APP_CODE"; + private static final String COUNTRY = "COUNTRY"; + private static final String COUNTRY_CODE = "123"; + private static final String FIRST_NAME = "FIRSTNAME"; + private static final String LAST_NAME = "LASTNAME"; + private static final String ORGANIZATION = "ORGANIZATION"; + private static final String PHONE_NUMBER = "1231231234"; + private static final String REASON = "REASON"; + private static final String RUSH_TYPE = "RULE"; + private final String TYPE = "type"; + private static final BigDecimal STATUTORY_FEE_AMOUNT = BigDecimal.TEN; + + CsoSubmissionServiceImpl sut; + + @Mock + private FilingFacadeBean filingFacadeBeanMock; + + @Mock + private ServiceFacadeBean serviceFacadeBean; + + @Mock + private EfilingPaymentService efilingPaymentServiceMock; + + @Mock + private CsoProperties csoPropertiesMock; + + @Mock + private EfilingDocumentService efilingDocumentServiceMock; + + @BeforeEach + public void beforeEach() throws NestedEjbException_Exception, ca.bc.gov.ag.csows.filing.NestedEjbException_Exception { + + MockitoAnnotations.openMocks(this); + + Mockito.when(csoPropertiesMock.getFileServerHost()).thenReturn("localhost"); + Mockito.when(csoPropertiesMock.getCsoBasePath()).thenReturn("http://cso"); + Mockito.when(csoPropertiesMock.getCsoPackagePath()).thenReturn("/accounts/bceidNotification.do?packageNo="); + + UserSession userSession = new UserSession(); + userSession.setStartDtm(DateUtils.getCurrentXmlDate()); + userSession.setUpdUserId("1234"); + userSession.setUserSessionId(new BigDecimal(1234)); + + Mockito.when(serviceFacadeBean.createUserSession(Mockito.anyString())).thenReturn(userSession); + ServiceSession serviceSession = new ServiceSession(); + serviceSession.setUserSessionId(new BigDecimal(1234)); + serviceSession.setServiceSessionId(new BigDecimal(5678)); + Mockito.doReturn(serviceSession).when(serviceFacadeBean) + .createServiceSession(ArgumentMatchers.argThat(x -> x.getUserSessionId().equals(userSession.getUserSessionId())), Mockito.anyString()); + + // Testing mapper + DocumentMapper documentMapper = new DocumentMapperImpl(); + CsoPartyMapper csoPartyMapper = new CsoPartyMapperImpl(); + + Mockito.doReturn(DateUtils.getCurrentXmlDate()).when(filingFacadeBeanMock) + .calculateSubmittedDate(any(), Mockito.eq(LOCATION)); + + Mockito.doThrow(ca.bc.gov.ag.csows.filing.NestedEjbException_Exception.class).when(filingFacadeBeanMock) + .calculateSubmittedDate(any(), Mockito.eq(BAD_LOCATION)); + + DocumentTypeDetails documentTypeDetailsNoAutoProcessing = new DocumentTypeDetails("description", "type1", BigDecimal.ONE, false, false, false); + DocumentTypeDetails documentTypeDetailsAutoProcessing = new DocumentTypeDetails("description", "type2", BigDecimal.ONE, false, false, true); + List documentTypeDetailsList = Arrays.asList(documentTypeDetailsNoAutoProcessing, documentTypeDetailsAutoProcessing); + Mockito.when(efilingDocumentServiceMock.getDocumentTypes(Mockito.anyString(), Mockito.anyString())).thenReturn(documentTypeDetailsList); + + sut = new CsoSubmissionServiceImpl(filingFacadeBeanMock, serviceFacadeBean, new ServiceMapperImpl(), new FilingPackageMapperImpl(), new FinancialTransactionMapperImpl(), csoPropertiesMock, documentMapper, csoPartyMapper, new PackageAuthorityMapperImpl(), efilingDocumentServiceMock); + + } + + + @DisplayName("Exception: with null account details service should throw IllegalArgumentException") + @Test + public void testWithEmptyAccountDetails() { + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.submitFilingPackage( + null, + null, + null)); + } + + + @DisplayName("Exception: with null filingPackage should throw IllegalArgumentException") + @Test + public void testWithEmptyFilingPackageDetails() { + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.submitFilingPackage( + null, + FilingPackage.builder().create(), + null)); + } + + @DisplayName("Exception: with null filingpackage should throw IllegalArgumentException") + @Test + public void testWithEmptyFilingPackage() { + + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.submitFilingPackage( + AccountDetails.builder().create(), + FilingPackage.builder().create() + , null)); + } + + + @DisplayName("Exception: with null clientId should throw IllegalArgumentException") + @Test + public void testWithEmptyClientId() { + Assertions.assertThrows(IllegalArgumentException.class, () -> sut.submitFilingPackage( + AccountDetails.builder().create(), + FilingPackage.builder().create(), + null)); + } + + @DisplayName("OK: submitFilingPackage called with any non-empty submissionId && empty fee") + @Test + public void testWithPopulatedSubmissionId() throws DatatypeConfigurationException, ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, NestedEjbException_Exception { + + Mockito.when(filingFacadeBeanMock.submitFiling(any())).thenReturn(BigDecimal.TEN); + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + Mockito.doNothing().when(serviceFacadeBean).updateService(any()); + + AccountDetails accountDetails = getAccountDetails(); + + SubmitPackageResponse actual = sut.submitFilingPackage(accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .rushedSubmission(false) + .court(Court.builder() + .location(LOCATION) + .agencyId(AGENCY_ID) + .courtClass(COURT_CLASS) + .division(DIVISION) + .level(LEVEL) + .fileNumber(FILE_NUMBER) + .create()) + .documents(Arrays.asList(Document.builder() + .name(DOCUMENT) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .subType(TYPE) + .statutoryFeeAmount(STATUTORY_FEE_AMOUNT) + .create())) + .create(), + efilingPaymentServiceMock); + + Mockito.verify(filingFacadeBeanMock, Mockito.times(1)) + .submitFiling(ArgumentMatchers.argThat(filingPackage -> + filingPackage.getProcRequest() == null && + filingPackage.isFeeExemptYn().equals(true) && + filingPackage.getApplicationCd().equals(APP_CODE) && + filingPackage.getCourtFileNo().equals(FILE_NUMBER) && + filingPackage.getLdcxCourtClassCd().equals(COURT_CLASS) && + filingPackage.getLdcxCourtDivisionCd().equals(DIVISION) && + filingPackage.getLdcxCourtLevelCd().equals(LEVEL) && + filingPackage.getSubmittedToAgenId().equals(AGENCY_ID) && + filingPackage.getDocuments().get(0).getPayments().get(0).getStatutoryFeeAmt().equals(STATUTORY_FEE_AMOUNT))); + + Assertions.assertEquals(BigDecimal.TEN, actual.getTransactionId()); + Assertions.assertEquals("http://cso/accounts/bceidNotification.do?packageNo=10", actual.getPackageLink()); + } + + @DisplayName("OK: submitFilingPackage called with any non-empty submissionId & fee") + @Test + public void testWithPopulatedSubmissionIdAndFee() throws DatatypeConfigurationException, ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, NestedEjbException_Exception { + + Mockito.when(filingFacadeBeanMock.submitFiling(any())).thenReturn(BigDecimal.TEN); + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + Mockito.doNothing().when(serviceFacadeBean).updateService(any()); + + AccountDetails accountDetails = getAccountDetails(); + + SubmitPackageResponse actual = sut.submitFilingPackage(accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .rushedSubmission(false) + .submissionFeeAmount(BigDecimal.TEN) + .court(Court.builder() + .location(LOCATION) + .agencyId(AGENCY_ID) + .courtClass(COURT_CLASS) + .division(DIVISION) + .level(LEVEL) + .fileNumber(FILE_NUMBER) + .create()) + .documents(Arrays.asList(Document.builder() + .name(DOCUMENT) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .subType(TYPE) + .statutoryFeeAmount(STATUTORY_FEE_AMOUNT) + .create())) + .create(), + efilingPaymentServiceMock); + + Mockito.verify(filingFacadeBeanMock, Mockito.times(1)) + .submitFiling(ArgumentMatchers.argThat(filingPackage -> + filingPackage.getProcRequest() == null && + filingPackage.isFeeExemptYn().equals(false) && + filingPackage.getApplicationCd().equals(APP_CODE) && + filingPackage.getCourtFileNo().equals(FILE_NUMBER) && + filingPackage.getLdcxCourtClassCd().equals(COURT_CLASS) && + filingPackage.getLdcxCourtDivisionCd().equals(DIVISION) && + filingPackage.getLdcxCourtLevelCd().equals(LEVEL) && + filingPackage.getSubmittedToAgenId().equals(AGENCY_ID) && + filingPackage.getDocuments().get(0).getPayments().get(0).getStatutoryFeeAmt().equals(STATUTORY_FEE_AMOUNT))); + + Assertions.assertEquals(BigDecimal.TEN, actual.getTransactionId()); + Assertions.assertEquals("http://cso/accounts/bceidNotification.do?packageNo=10", actual.getPackageLink()); + } + + @DisplayName("OK: submitFilingPackage called with any non-empty submissionId and rushed flag") + @Test + public void withRushedSubmissionShouldAddRushedParams() throws DatatypeConfigurationException, ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, NestedEjbException_Exception { + + Mockito.when(filingFacadeBeanMock.submitFiling(any())).thenReturn(BigDecimal.TEN); + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + Mockito.doNothing().when(serviceFacadeBean).updateService(any()); + + AccountDetails accountDetails = getAccountDetails(); + + SubmitPackageResponse actual = sut.submitFilingPackage(accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .rushedSubmission(true) + .rush(RushProcessing.builder() + .rushType(RUSH_TYPE) + .courtDate("2001-11-26T12:00:00Z") + .country(COUNTRY) + .countryCode(COUNTRY_CODE) + .firstName(FIRST_NAME) + .lastName(LAST_NAME) + .organization(ORGANIZATION) + .phoneNumber(PHONE_NUMBER) + .reason(REASON) + .supportingDocuments(new ArrayList<>()) + .create()) + .court(Court.builder() + .location(LOCATION) + .agencyId(AGENCY_ID) + .courtClass(COURT_CLASS) + .division(DIVISION) + .level(LEVEL) + .fileNumber(FILE_NUMBER) + .create()) + .documents(Arrays.asList(Document.builder() + .name(DOCUMENT) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .subType(TYPE) + .statutoryFeeAmount(STATUTORY_FEE_AMOUNT) + .create())) + .create(), + efilingPaymentServiceMock); + + Mockito.verify(filingFacadeBeanMock, Mockito.times(1)) + .submitFiling(ArgumentMatchers.argThat(filingPackage -> + filingPackage.getProcRequest().getItem().getProcessReasonCd().equals(RUSH_TYPES.get(RUSH_TYPE)) && + filingPackage.getProcRequest().getEntDtm().compare(DateUtils.getCurrentXmlDate()) == -1 && + filingPackage.getProcRequest().getEntUserId().equals(accountDetails.getClientId().toString()) && + filingPackage.getProcRequest().getRequestDt().compare(DateUtils.getCurrentXmlDate()) == -1 && + filingPackage.getProcRequest().getItem().getEntDtm().compare(DateUtils.getCurrentXmlDate()) == -1 && + filingPackage.getProcRequest().getItem().getEntUserId().equals(accountDetails.getClientId().toString()) && + filingPackage.getProcRequest().getItem().getProcessReasonCd().equals(RUSH_TYPES.get(RUSH_TYPE)) && + filingPackage.getApplicationCd().equals(APP_CODE) && + filingPackage.getCourtFileNo().equals(FILE_NUMBER) && + filingPackage.getLdcxCourtClassCd().equals(COURT_CLASS) && + filingPackage.getLdcxCourtDivisionCd().equals(DIVISION) && + filingPackage.getLdcxCourtLevelCd().equals(LEVEL) && + filingPackage.getSubmittedToAgenId().equals(AGENCY_ID) && + filingPackage.getDocuments().get(0).getPayments().get(0).getStatutoryFeeAmt().equals(STATUTORY_FEE_AMOUNT))); + + Assertions.assertEquals(BigDecimal.TEN, actual.getTransactionId()); + Assertions.assertEquals("http://cso/accounts/bceidNotification.do?packageNo=10", actual.getPackageLink()); + } + + @DisplayName("OK: submitFilingPackage called with a invalid court date") + @Test + public void withInvalidCourDateNullIsApplied() throws DatatypeConfigurationException, ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, NestedEjbException_Exception { + + Mockito.when(filingFacadeBeanMock.submitFiling(any())).thenReturn(BigDecimal.TEN); + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + Mockito.doNothing().when(serviceFacadeBean).updateService(any()); + + AccountDetails accountDetails = getAccountDetails(); + + SubmitPackageResponse actual = sut.submitFilingPackage(accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .rushedSubmission(true) + .rush(RushProcessing.builder() + .rushType(RUSH_TYPE) + .courtDate("") + .country(COUNTRY) + .countryCode(COUNTRY_CODE) + .firstName(FIRST_NAME) + .lastName(LAST_NAME) + .organization(ORGANIZATION) + .phoneNumber(PHONE_NUMBER) + .reason(REASON) + .supportingDocuments(new ArrayList<>()) + .create()) + .court(Court.builder() + .location(LOCATION) + .agencyId(AGENCY_ID) + .courtClass(COURT_CLASS) + .division(DIVISION) + .level(LEVEL) + .fileNumber(FILE_NUMBER) + .create()) + .documents(Arrays.asList(Document.builder() + .name(DOCUMENT) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .subType(TYPE) + .statutoryFeeAmount(STATUTORY_FEE_AMOUNT) + .create())) + .create(), + efilingPaymentServiceMock); + + Mockito.verify(filingFacadeBeanMock, Mockito.times(1)) + .submitFiling(ArgumentMatchers.argThat(filingPackage -> + filingPackage.getProcRequest().getItem().getProcessReasonCd().equals(RUSH_TYPES.get(RUSH_TYPE)) && + filingPackage.getProcRequest().getEntDtm().compare(DateUtils.getCurrentXmlDate()) == -1 && + filingPackage.getProcRequest().getEntUserId().equals(accountDetails.getClientId().toString()) && + filingPackage.getProcRequest().getRequestDt().compare(DateUtils.getCurrentXmlDate()) == -1 && + filingPackage.getProcRequest().getItem().getEntDtm().compare(DateUtils.getCurrentXmlDate()) == -1 && + filingPackage.getProcRequest().getItem().getEntUserId().equals(accountDetails.getClientId().toString()) && + filingPackage.getProcRequest().getItem().getProcessReasonCd().equals(RUSH_TYPES.get(RUSH_TYPE)) && + filingPackage.getApplicationCd().equals(APP_CODE) && + filingPackage.getCourtFileNo().equals(FILE_NUMBER) && + filingPackage.getLdcxCourtClassCd().equals(COURT_CLASS) && + filingPackage.getLdcxCourtDivisionCd().equals(DIVISION) && + filingPackage.getLdcxCourtLevelCd().equals(LEVEL) && + filingPackage.getSubmittedToAgenId().equals(AGENCY_ID) && + filingPackage.getDocuments().get(0).getPayments().get(0).getStatutoryFeeAmt().equals(STATUTORY_FEE_AMOUNT))); + + Assertions.assertEquals(BigDecimal.TEN, actual.getTransactionId()); + Assertions.assertEquals("http://cso/accounts/bceidNotification.do?packageNo=10", actual.getPackageLink()); + } + + + @DisplayName("OK: with no fees should default to 0") + @Test + public void withNoFeeShouldDefaultToZero() throws DatatypeConfigurationException, ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, NestedEjbException_Exception { + + Mockito.when(filingFacadeBeanMock.submitFiling(any())).thenReturn(BigDecimal.TEN); + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + Mockito.doNothing().when(serviceFacadeBean).updateService(any()); + + AccountDetails accountDetails = getAccountDetails(); + + SubmitPackageResponse actual = sut.submitFilingPackage(accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .court( + Court.builder() + .location(LOCATION) + .agencyId(AGENCY_ID) + .courtClass(COURT_CLASS) + .division(DIVISION) + .level(LEVEL) + .fileNumber(FILE_NUMBER) + .create()) + .documents(Arrays.asList(Document.builder() + .name(DOCUMENT) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .subType(TYPE) + .create())) + .parties(Collections.singletonList( + Individual.builder() + .firstName("TEST") + .middleName("TEST") + .lastName("TEST") + .nameTypeCd("TYPE") + .roleTypeCd("CODE") + .create())) + .organizations(Collections.singletonList( + Organization.builder() + .name("TEST") + .nameTypeCd("TYPE") + .roleTypeCd("CODE") + .create() + )) + .create(), + efilingPaymentServiceMock); + + Mockito.verify(filingFacadeBeanMock, Mockito.times(1)) + .submitFiling(ArgumentMatchers.argThat(filingPackage -> + filingPackage.getCourtFileNo().equals(FILE_NUMBER) && + filingPackage.getLdcxCourtClassCd().equals(COURT_CLASS) && + filingPackage.getLdcxCourtDivisionCd().equals(DIVISION) && + filingPackage.getLdcxCourtLevelCd().equals(LEVEL) && + filingPackage.getSubmittedToAgenId().equals(AGENCY_ID) && + filingPackage.getDocuments().get(0).getPayments().get(0).getStatutoryFeeAmt().equals(BigDecimal.ZERO))); + + Assertions.assertEquals(BigDecimal.TEN, actual.getTransactionId()); + Assertions.assertEquals("http://cso/accounts/bceidNotification.do?packageNo=10", actual.getPackageLink()); + } + + @DisplayName("OK: with statutory fee change payment status") + @Test + public void withSubmissionFeeShouldSuccessfully() throws DatatypeConfigurationException, ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, NestedEjbException_Exception { + + Mockito.when(filingFacadeBeanMock.submitFiling(any())).thenReturn(BigDecimal.TEN); + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + Mockito.doNothing().when(serviceFacadeBean).updateService(any()); + + AccountDetails accountDetails = getAccountDetails(); + + SubmitPackageResponse actual = sut.submitFilingPackage(accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .court( + Court.builder() + .location(LOCATION) + .agencyId(AGENCY_ID) + .courtClass(COURT_CLASS) + .division(DIVISION) + .level(LEVEL) + .fileNumber(FILE_NUMBER) + .create()) + .documents(Arrays.asList(Document.builder() + .name(DOCUMENT) + .statutoryFeeAmount(BigDecimal.TEN) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .subType(TYPE) + .create())) + .parties(Collections.singletonList( + Individual.builder() + .firstName("TEST") + .middleName("TEST") + .lastName("TEST") + .nameTypeCd("TYPE") + .roleTypeCd("CODE") + .create())) + .organizations(Collections.singletonList( + Organization.builder() + .name("TEST") + .nameTypeCd("TYPE") + .roleTypeCd("CODE") + .create() + )) + .create(), + efilingPaymentServiceMock); + + Mockito.verify(filingFacadeBeanMock, Mockito.times(1)) + .submitFiling(ArgumentMatchers.argThat(filingPackage -> + filingPackage.getCourtFileNo().equals(FILE_NUMBER) && + filingPackage.getLdcxCourtClassCd().equals(COURT_CLASS) && + filingPackage.getLdcxCourtDivisionCd().equals(DIVISION) && + filingPackage.getLdcxCourtLevelCd().equals(LEVEL) && + filingPackage.getSubmittedToAgenId().equals(AGENCY_ID) && + filingPackage.getDocuments().get(0).getPayments().get(0).getStatutoryFeeAmt().equals(BigDecimal.TEN) && + filingPackage.getDocuments().get(0).getPayments().get(0).getPaymentStatusCd().equals(Keys.NOT_PROCESSED_PAYMENT_STATUS_CD))); + + Assertions.assertEquals(BigDecimal.TEN, actual.getTransactionId()); + Assertions.assertEquals("http://cso/accounts/bceidNotification.do?packageNo=10", actual.getPackageLink()); + } + + @DisplayName("OK: submitFilingPackage called with any non-empty submissionId") + @Test + public void testWithPopulatedSubmissionIdBigDecimalValue() throws DatatypeConfigurationException, ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, NestedEjbException_Exception { + + Mockito.when(filingFacadeBeanMock.submitFiling(any())).thenReturn(new BigDecimal(100000)); + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + Mockito.doNothing().when(serviceFacadeBean).updateService(any()); + + AccountDetails accountDetails = getAccountDetails(); + + SubmitPackageResponse actual = sut.submitFilingPackage(accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .court( + Court.builder() + .location(LOCATION) + .create()) + .create(), + efilingPaymentServiceMock); + Assertions.assertEquals(new BigDecimal(100000), actual.getTransactionId()); + Assertions.assertEquals("http://cso/accounts/bceidNotification.do?packageNo=100000", actual.getPackageLink()); + + } + + @DisplayName("OK: submitFilingPackage called with rushed Processing") + @Test + public void testWithRushedProcessing() throws DatatypeConfigurationException, ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, NestedEjbException_Exception { + Mockito.when(filingFacadeBeanMock.submitFiling(any())).thenReturn(BigDecimal.TEN); + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + Mockito.doNothing().when(serviceFacadeBean).updateService(any()); + + AccountDetails accountDetails = getAccountDetails(); + + SubmitPackageResponse actual = sut.submitFilingPackage(accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .court( + Court.builder() + .location(LOCATION) + .create()) + .create(), + efilingPaymentServiceMock); + + Assertions.assertEquals(BigDecimal.TEN, actual.getTransactionId()); + Assertions.assertEquals("http://cso/accounts/bceidNotification.do?packageNo=10", actual.getPackageLink()); + } + + @DisplayName("OK: set auto processing flag if package contains auto processing document type") + @Test + public void testWithAutoProcessingDocumentTypes() throws ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, NestedEjbException_Exception, DatatypeConfigurationException { + Mockito.when(filingFacadeBeanMock.submitFiling(argThat(filingPackage -> filingPackage.isAutomatedProcessYn() == true))).thenReturn(BigDecimal.ONE); + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + Mockito.doNothing().when(serviceFacadeBean).updateService(any()); + + AccountDetails accountDetails = getAccountDetails(); + + SubmitPackageResponse actual = sut.submitFilingPackage(accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .court(Court.builder() + .location(LOCATION) + .agencyId(AGENCY_ID) + .courtClass(COURT_CLASS) + .division(DIVISION) + .level(LEVEL) + .fileNumber(FILE_NUMBER) + .create()) + .documents(Arrays.asList(Document.builder() + .name(DOCUMENT) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .type("type2") + .subType(TYPE) + .statutoryFeeAmount(STATUTORY_FEE_AMOUNT) + .create(), + Document.builder() + .name(DOCUMENT) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .type("type1") + .subType(TYPE) + .statutoryFeeAmount(STATUTORY_FEE_AMOUNT) + .create())) + .create(), + efilingPaymentServiceMock); + + Assertions.assertEquals(BigDecimal.ONE, actual.getTransactionId()); + } + + @DisplayName("OK: don't set auto processing flag if package does not contains auto processing document type") + @Test + public void testWithoutAutoProcessingDocumentTypes() throws ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, NestedEjbException_Exception, DatatypeConfigurationException { + Mockito.when(filingFacadeBeanMock.submitFiling(argThat(filingPackage -> filingPackage.isAutomatedProcessYn() == false))).thenReturn(BigDecimal.TEN); + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + Mockito.doNothing().when(serviceFacadeBean).updateService(any()); + + AccountDetails accountDetails = getAccountDetails(); + + SubmitPackageResponse actual = sut.submitFilingPackage(accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .court(Court.builder() + .location(LOCATION) + .agencyId(AGENCY_ID) + .courtClass(COURT_CLASS) + .division(DIVISION) + .level(LEVEL) + .fileNumber(FILE_NUMBER) + .create()) + .documents(Arrays.asList(Document.builder() + .name(DOCUMENT) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .type("type1") + .subType(TYPE) + .statutoryFeeAmount(STATUTORY_FEE_AMOUNT) + .create())) + .create(), + efilingPaymentServiceMock); + + Assertions.assertEquals(BigDecimal.TEN, actual.getTransactionId()); + } + + @DisplayName("OK: set delay processing flag if document calculated submitted date does not match the actual submitted date") + @Test + public void testWithDelayProcessing() throws ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, NestedEjbException_Exception, DatatypeConfigurationException { + Mockito.when(filingFacadeBeanMock.submitFiling(argThat(filingPackage -> filingPackage.isDelayProcessing()))).thenReturn(BigDecimal.ONE); + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + XMLGregorianCalendar mockDate = DateUtils.getCurrentXmlDate(); + mockDate.setYear(mockDate.getYear() + 5000); + Mockito.doReturn(mockDate).when(filingFacadeBeanMock) + .calculateSubmittedDate(any(), Mockito.eq(LOCATION)); + Mockito.doNothing().when(serviceFacadeBean).updateService(any()); + + AccountDetails accountDetails = getAccountDetails(); + + SubmitPackageResponse actual = sut.submitFilingPackage(accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .court(Court.builder() + .location(LOCATION) + .agencyId(AGENCY_ID) + .courtClass(COURT_CLASS) + .division(DIVISION) + .level(LEVEL) + .fileNumber(FILE_NUMBER) + .create()) + .documents(Arrays.asList(Document.builder() + .name(DOCUMENT) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .type("type2") + .subType(TYPE) + .statutoryFeeAmount(STATUTORY_FEE_AMOUNT) + .create(), + Document.builder() + .name(DOCUMENT) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .type("type1") + .subType(TYPE) + .statutoryFeeAmount(STATUTORY_FEE_AMOUNT) + .create())) + .create(), + efilingPaymentServiceMock); + + Assertions.assertEquals(BigDecimal.ONE, actual.getTransactionId()); + } + + @DisplayName("OK: submitting a action document that is courtesy corrected ") + @Test + public void testWithCourtesyCorrection() throws ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, NestedEjbException_Exception, DatatypeConfigurationException { + Mockito.when(filingFacadeBeanMock.submitFiling(argThat(filingPackage -> filingPackage.isDelayProcessing()))).thenReturn(BigDecimal.ONE); + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + XMLGregorianCalendar mockDate = DateUtils.getCurrentXmlDate(); + mockDate.setYear(mockDate.getYear() + 5000); + Mockito.doReturn(mockDate).when(filingFacadeBeanMock) + .calculateSubmittedDate(any(), Mockito.eq(LOCATION)); + Mockito.doNothing().when(serviceFacadeBean).updateService(any()); + + AccountDetails accountDetails = getAccountDetails(); + + SubmitPackageResponse actual = sut.submitFilingPackage(accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .court(Court.builder() + .location(LOCATION) + .agencyId(AGENCY_ID) + .courtClass(COURT_CLASS) + .division(DIVISION) + .level(LEVEL) + .fileNumber(FILE_NUMBER) + .create()) + .documents(Arrays.asList(Document.builder() + .name(DOCUMENT) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .type("type2") + .subType(TYPE) + .statutoryFeeAmount(STATUTORY_FEE_AMOUNT) + .create(), + Document.builder() + .name(DOCUMENT) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .type("type1") + .subType(TYPE) + .statutoryFeeAmount(STATUTORY_FEE_AMOUNT) + .actionDocument( + ActionDocument.builder() + .type("TEST") + .status("CCOR") + .documentId(BigDecimal.TEN) + .create() + ) + .create())) + .create(), + efilingPaymentServiceMock); + + Assertions.assertEquals(BigDecimal.ONE, actual.getTransactionId()); + } + + @DisplayName("OK: submitting a action document that is rejected") + @Test + public void testWithRejected() throws ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, NestedEjbException_Exception, DatatypeConfigurationException { + Mockito.when(filingFacadeBeanMock.submitFiling(argThat(filingPackage -> filingPackage.isDelayProcessing()))).thenReturn(BigDecimal.ONE); + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + XMLGregorianCalendar mockDate = DateUtils.getCurrentXmlDate(); + mockDate.setYear(mockDate.getYear() + 5000); + Mockito.doReturn(mockDate).when(filingFacadeBeanMock) + .calculateSubmittedDate(any(), Mockito.eq(LOCATION)); + Mockito.doNothing().when(serviceFacadeBean).updateService(any()); + + AccountDetails accountDetails = getAccountDetails(); + + SubmitPackageResponse actual = sut.submitFilingPackage(accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .court(Court.builder() + .location(LOCATION) + .agencyId(AGENCY_ID) + .courtClass(COURT_CLASS) + .division(DIVISION) + .level(LEVEL) + .fileNumber(FILE_NUMBER) + .create()) + .documents(Arrays.asList(Document.builder() + .name(DOCUMENT) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .type("type2") + .subType(TYPE) + .statutoryFeeAmount(STATUTORY_FEE_AMOUNT) + .create(), + Document.builder() + .name(DOCUMENT) + .serverFileName(SERVERFILENAME) + .isAmendment(IS_AMENDMENT) + .isSupremeCourtScheduling(IS_SUPREME_COURT_SCHEDULING) + .type("type1") + .subType(TYPE) + .statutoryFeeAmount(STATUTORY_FEE_AMOUNT) + .actionDocument( + ActionDocument.builder() + .type("TEST") + .status("REJ") + .documentId(BigDecimal.TEN) + .create() + ) + .create())) + .create(), + efilingPaymentServiceMock); + + Assertions.assertEquals(BigDecimal.ONE, actual.getTransactionId()); + } + + @DisplayName("Exception: payment to bambora throw exception") + @Test + public void testWithValidRequestPaymentThrowsException() throws DatatypeConfigurationException, ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, NestedEjbException_Exception { + Mockito.when(filingFacadeBeanMock.submitFiling(any())).thenReturn(BigDecimal.TEN); + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenThrow(new EfilingSubmissionServiceException("Bad Bambora", new Throwable())); + + AccountDetails accountDetails = getAccountDetails(); + + Assertions.assertThrows(EfilingSubmissionServiceException.class, () -> sut.submitFilingPackage( + accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .submissionFeeAmount(BigDecimal.TEN) + .create(), + efilingPaymentServiceMock)); + } + + + @DisplayName("Exception: with NestedEjbException_Exception should throw EfilingLookupServiceException") + @Test + public void whenFilingFacadeNestedEjbException_ExceptionShouldThrowEfilingSubmissionServiceException() throws NestedEjbException_Exception, DatatypeConfigurationException, ca.bc.gov.ag.csows.filing.NestedEjbException_Exception { + + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(filingFacadeBeanMock.submitFiling(any())).thenThrow(new ca.bc.gov.ag.csows.filing.NestedEjbException_Exception()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + AccountDetails accountDetails = getAccountDetails(); + + Assertions.assertThrows(EfilingSubmissionServiceException.class, () -> sut.submitFilingPackage( + accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .court( + Court.builder() + .location(LOCATION) + .create()) + .create(), + efilingPaymentServiceMock)); + + } + + @DisplayName("Exception: with NestedEjbException_Exception should throw EfilingLookupServiceException") + @Test + public void whenServiceFacadeNestedEjbException_ExceptionShouldThrowEfilingSubmissionServiceException() throws NestedEjbException_Exception { + Mockito.when(serviceFacadeBean.addService(any())).thenThrow(new NestedEjbException_Exception()); + + AccountDetails accountDetails = getAccountDetails(); + + Assertions.assertThrows(EfilingSubmissionServiceException.class, () -> sut.submitFilingPackage( + accountDetails, + FilingPackage + .builder() + .applicationCode(APP_CODE) + .create(), + null)); + } + + private AccountDetails getAccountDetails() { + return AccountDetails + .builder() + .clientId(BigDecimal.TEN) + .internalClientNumber(INTERNAL_CLIENT_NUMBER) + .universalId(UNIVERSAL_ID) + .cardRegistered(true) + .accountId(BigDecimal.ONE) + .fileRolePresent(true) + .create(); + } + + + @DisplayName("Exception: with NestedEjbException_Exception when getting user session should throw EfilingLookupServiceException") + @Test + public void whenCreateServiceSessionThrowsNestedEjbException_Exception() throws NestedEjbException_Exception { + + Mockito.doThrow(new NestedEjbException_Exception()).when(serviceFacadeBean).createServiceSession(Mockito.any(), Mockito.anyString()); + + Assertions.assertThrows(EfilingSubmissionServiceException.class, () -> sut.submitFilingPackage( + getAccountDetails(), + FilingPackage + .builder() + .applicationCode(APP_CODE) + .create(), + null)); + } + + @DisplayName("Exception: with NestedEjbException_Exception when getting user session should throw EfilingLookupServiceException") + @Test + public void whenCreateUserSessionThrowsNestedEjbException_Exception() throws NestedEjbException_Exception { + Mockito.doThrow(new NestedEjbException_Exception()).when(serviceFacadeBean).createUserSession(Mockito.anyString()); + Assertions.assertThrows(EfilingSubmissionServiceException.class, () -> sut.submitFilingPackage( + getAccountDetails(), + FilingPackage.builder() + .applicationCode(APP_CODE) + .create(), + null)); + } + + + @DisplayName("Exception: with NestedEjbException_Exception when getting user session should throw EfilingLookupServiceException") + @Test + public void whenUpdatePaymentForServiceThrowsNestedEjbException_Exception() throws NestedEjbException_Exception { + + Mockito.doThrow(new NestedEjbException_Exception()).when(serviceFacadeBean).updateService(any()); + Service service = new Service(); + Mockito.when(serviceFacadeBean.addService(Mockito.any())).thenReturn(service); + + AccountDetails accountDetails = getAccountDetails(); + + Assertions.assertThrows(EfilingSubmissionServiceException.class, () -> sut.submitFilingPackage( + accountDetails, + FilingPackage + .builder() + .submissionFeeAmount(BigDecimal.TEN) + .applicationCode(APP_CODE) + .create(), + efilingPaymentServiceMock)); + + } + + @DisplayName("Exception: with NestedEjbException_Exception on calculate submitted date throw EfilingLookupServiceException") + @Test + public void whenComputedSubmittedDateFailsThrowEfilingLookupServiceException() throws NestedEjbException_Exception, ca.bc.gov.ag.csows.filing.NestedEjbException_Exception, DatatypeConfigurationException { + + Mockito.when(serviceFacadeBean.addService(any())).thenReturn(TestHelpers.createService()); + Mockito.when(filingFacadeBeanMock.submitFiling(any())).thenThrow(new ca.bc.gov.ag.csows.filing.NestedEjbException_Exception()); + Mockito.when(efilingPaymentServiceMock.makePayment(any())).thenReturn(createTransaction()); + + AccountDetails accountDetails = getAccountDetails(); + + Assertions.assertThrows(EfilingSubmissionServiceException.class, () -> sut.submitFilingPackage( + accountDetails, + FilingPackage.builder() + .applicationCode(APP_CODE) + .court( + Court.builder() + .location(BAD_LOCATION) + .create()) + .create(), + efilingPaymentServiceMock)); + + } + + + private PaymentTransaction createTransaction() { + PaymentTransaction efilingTransaction = new PaymentTransaction(); + efilingTransaction.setApprovalCd(APPROVED); + efilingTransaction.setEcommerceTransactionId(BigDecimal.TEN); + efilingTransaction.setInternalClientNo(INTERNAL_CLIENT_NUMBER); + efilingTransaction.setCreditCardTypeCd(CARD_TYPE_CD); + efilingTransaction.setReferenceMessageTxt(REFERENCE_MESSAGE_TXT); + efilingTransaction.setTransactionStateCd(TRANSACTION_STATE_CD); + efilingTransaction.setApprovalCd(APPROVAL_CD); + efilingTransaction.setEntDtm(ENT_DTM); + efilingTransaction.setInvoiceNo(INVOICE_NO); + efilingTransaction.setProcessDt(PROCESS_DT); + efilingTransaction.setTransactionAmt(TRANSACTION_AMT); + efilingTransaction.setTransactonDtm(TRANSACTON_DTM); + efilingTransaction.setEntUserId(USER_ID); + efilingTransaction.setServiceId(SERVICE_ID1); + return efilingTransaction; + } + +} diff --git a/src/backend/libs/efiling-account-client/README.md b/src/backend/libs/efiling-cso-starter/README.md similarity index 100% rename from src/backend/libs/efiling-account-client/README.md rename to src/backend/libs/efiling-cso-starter/README.md diff --git a/src/backend/libs/efiling-lookup-client/pom.xml b/src/backend/libs/efiling-cso-starter/pom.xml similarity index 51% rename from src/backend/libs/efiling-lookup-client/pom.xml rename to src/backend/libs/efiling-cso-starter/pom.xml index 8554f41332..627a96270d 100644 --- a/src/backend/libs/efiling-lookup-client/pom.xml +++ b/src/backend/libs/efiling-cso-starter/pom.xml @@ -7,15 +7,19 @@ org.springframework.boot spring-boot-starter-parent - 2.3.1.RELEASE + 3.5.4 ca.bc.gov.open.jag - efiling-lookup-client - 0.0.1-SNAPSHOT - efiling-lookup-client - Client for handling info lookup for CSO filings + efiling-cso-starter + 2.0.12-SNAPSHOT + + + 17 + 1.4.2.Final + 2.17.1 + @@ -30,29 +34,41 @@ + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + org.apache.cxf cxf-rt-frontend-jaxws + org.apache.cxf cxf-rt-transports-http + + + org.apache.cxf + cxf-rt-features-logging + + org.apache.cxf cxf-rt-transports-http-jetty - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - + org.mapstruct + mapstruct @@ -61,15 +77,15 @@ - joda-time - joda-time - compile + ca.bc.gov.open.jag + efiling-commons + 2.0.12-SNAPSHOT ca.bc.gov.open.jag - efiling-commons - 0.0.1-SNAPSHOT + efiling-cso-client + 2.0.12-SNAPSHOT @@ -79,7 +95,7 @@ ca.bc.gov.open.jag efiling-bom - 0.0.1-SNAPSHOT + 2.0.12-SNAPSHOT pom import @@ -89,64 +105,16 @@ - + - org.apache.cxf - cxf-codegen-plugin - 3.3.7 - - - generate-sources - generate-sources - - ${project.build.directory}/generated-sources/cxf - - - ${project.basedir}/src/main/resources/wsdl/LookupFacade.wsdl - - -client - - - - - - wsdl2java - - - - - - - - org.jacoco - jacoco-maven-plugin - 0.8.5 - + org.apache.maven.plugins + maven-compiler-plugin - - **/*/lookups/*.java - + ${java.version} + ${java.version} - - - - - prepare-agent - - - - - - report - test - - report - - - - diff --git a/src/backend/libs/efiling-cso-starter/src/main/java/ca/bc/gov/open/jag/efilingcsostarter/config/AutoConfiguration.java b/src/backend/libs/efiling-cso-starter/src/main/java/ca/bc/gov/open/jag/efilingcsostarter/config/AutoConfiguration.java new file mode 100644 index 0000000000..cbb6ca3151 --- /dev/null +++ b/src/backend/libs/efiling-cso-starter/src/main/java/ca/bc/gov/open/jag/efilingcsostarter/config/AutoConfiguration.java @@ -0,0 +1,187 @@ +package ca.bc.gov.open.jag.efilingcsostarter.config; + +import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.RoleRegistryPortType; +import ca.bc.gov.ag.csows.accounts.AccountFacadeBean; +import ca.bc.gov.ag.csows.ceis.Csows; +import ca.bc.gov.ag.csows.filing.FilingFacadeBean; +import ca.bc.gov.ag.csows.filing.status.FilingStatusFacadeBean; +import ca.bc.gov.ag.csows.lookups.LookupFacadeBean; +import ca.bc.gov.ag.csows.reports.ReportService; +import ca.bc.gov.ag.csows.services.ServiceFacadeBean; +import ca.bc.gov.courts.appeal.ws.services.CSOSearchSoap; +import ca.bc.gov.open.jag.efilingcommons.model.Clients; +import ca.bc.gov.open.jag.efilingcommons.model.EfilingSoapClientProperties; +import ca.bc.gov.open.jag.efilingcommons.service.*; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import ca.bc.gov.open.jag.efilingcsoclient.*; +import ca.bc.gov.open.jag.efilingcsoclient.config.CsoProperties; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.*; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +@Configuration +@EnableConfigurationProperties({SoapProperties.class, SpringCsoProperties.class}) +public class AutoConfiguration { + + private final SoapProperties soapProperties; + + private final CsoProperties csoProperties; + + public AutoConfiguration(SoapProperties soapProperties, SpringCsoProperties csoProperties) { + this.soapProperties = soapProperties; + this.csoProperties = csoProperties; + } + + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } + + @Bean + public AccountFacadeBean accountFacadeBean() { + EfilingSoapClientProperties efilingSoapClientProperties = soapProperties.findByEnum(Clients.ACCOUNT); + return SoapUtils.getPort(AccountFacadeBean.class, efilingSoapClientProperties, csoProperties.isDebugEnabled()); + } + + @Bean + public RoleRegistryPortType roleRegistryPortType() { + EfilingSoapClientProperties efilingSoapClientProperties = soapProperties.findByEnum(Clients.ROLE); + return SoapUtils.getPort(RoleRegistryPortType.class, efilingSoapClientProperties, csoProperties.isDebugEnabled()); + } + + @Bean + public FilingStatusFacadeBean filingStatusFacadeBean() { + EfilingSoapClientProperties efilingSoapClientProperties = soapProperties.findByEnum(Clients.STATUS); + return SoapUtils.getPort(FilingStatusFacadeBean.class, efilingSoapClientProperties, csoProperties.isDebugEnabled()); } + + @Bean + public LookupFacadeBean lookupFacadeBean() { + EfilingSoapClientProperties efilingSoapClientProperties = soapProperties.findByEnum(Clients.LOOKUP); + return SoapUtils.getPort(LookupFacadeBean.class, efilingSoapClientProperties, csoProperties.isDebugEnabled()); } + + @Bean + public Csows csows() { + EfilingSoapClientProperties efilingSoapClientProperties = soapProperties.findByEnum(Clients.CSOWS); + return SoapUtils.getPort(Csows.class, efilingSoapClientProperties, csoProperties.isDebugEnabled()); } + + @Bean + public FilingFacadeBean filingFacadeBean() { + EfilingSoapClientProperties efilingSoapClientProperties = soapProperties.findByEnum(Clients.FILING); + return SoapUtils.getPort(FilingFacadeBean.class, efilingSoapClientProperties, csoProperties.isDebugEnabled()); } + + @Bean + public ServiceFacadeBean serviceFacadeBean() { + EfilingSoapClientProperties efilingSoapClientProperties = soapProperties.findByEnum(Clients.SERVICE); + return SoapUtils.getPort(ServiceFacadeBean.class, efilingSoapClientProperties, csoProperties.isDebugEnabled()); } + + @Bean + public ReportService reportService() { + EfilingSoapClientProperties efilingSoapClientProperties = soapProperties.findByEnum(Clients.REPORT); + return SoapUtils.getPort(ReportService.class, efilingSoapClientProperties, csoProperties.isDebugEnabled()); } + + @Bean + public CSOSearchSoap csoSearch() { + EfilingSoapClientProperties efilingSoapClientProperties = soapProperties.findByEnum(Clients.SEARCH); + return SoapUtils.getPort(CSOSearchSoap.class, efilingSoapClientProperties, csoProperties.isDebugEnabled()); } + + + @Bean + public AccountDetailsMapper accountDetailsMapper() { + return new AccountDetailsMapperImpl(); + } + + @Bean + public ServiceMapper serviceMapper() { + return new ServiceMapperImpl(); + } + + @Bean + public FilingPackageMapper filingPackageMapper() { + return new FilingPackageMapperImpl(); + } + + @Bean + public FinancialTransactionMapper financialTransactionMapper() { return new FinancialTransactionMapperImpl(); } + + @Bean + public FilePackageMapper filePackageMapper() { return new FilePackageMapperImpl(); } + + + @Bean + public DocumentMapper documentMapper() { + return new DocumentMapperImpl(); + } + + @Bean + public CsoPartyMapper csoPartyMapper() { return new CsoPartyMapperImpl(); } + + @Bean + public PackageAuthorityMapper packageAuthorityMapper() { return new PackageAuthorityMapperImpl(); } + + @Bean + public EfilingAccountService efilingAccountService(AccountFacadeBean accountFacadeBean, + RoleRegistryPortType roleRegistryPortType, + AccountDetailsMapper accountDetailsMapper, + ClientProfileMapper clientProfileMapper) { + return new CsoAccountServiceImpl(accountFacadeBean, roleRegistryPortType, accountDetailsMapper, clientProfileMapper); + } + + @Bean + public ClientProfileMapper clientProfileMapper() { + return new ClientProfileMapperImpl(); + } + + @Bean + public EfilingDocumentService efilingDocumentService(FilingStatusFacadeBean filingStatusFacadeBean) { + return new CsoDocumentServiceImpl(filingStatusFacadeBean); + } + + @Bean + public EfilingLookupService efilingLookupService(LookupFacadeBean lookupFacadeBean) { + return new CsoLookupServiceImpl(lookupFacadeBean); + } + + @Bean + public CsoCourtServiceImpl efilingCourtService(Csows csows, FilingStatusFacadeBean filingStatusFacadeBean) { + return new CsoCourtServiceImpl(csows, filingStatusFacadeBean); + } + + @Bean + public EfilingReviewService efilingReviewService(FilingStatusFacadeBean filingStatusFacadeBean, ReportService reportService, FilingFacadeBean filingFacadeBean, RestTemplate restTemplate, EfilingLookupService efilingLookupService) { + return new CsoReviewServiceImpl(filingStatusFacadeBean, reportService, filingFacadeBean, new FilePackageMapperImpl(), csoProperties, restTemplate, efilingLookupService); + } + + @Bean + public EfilingSearchService efilingSearchService(CSOSearchSoap csoSearchSoap) { + return new CsoSearchServiceImpl(csoSearchSoap); + } + + + @Bean + public EfilingSubmissionService efilingSubmissionService(FilingFacadeBean filingFacadeBean, + ServiceFacadeBean serviceFacadeBean, + ServiceMapper serviceMapper, + FilingPackageMapper filingPackageMapper, + FinancialTransactionMapper financialTransactionMapper, + DocumentMapper documentMapper, + CsoPartyMapper csoPartyMapper, + PackageAuthorityMapper packageAuthorityMapper, + EfilingDocumentService efilingDocumentService) { + + return new CsoSubmissionServiceImpl( + filingFacadeBean, + serviceFacadeBean, + serviceMapper, + filingPackageMapper, + financialTransactionMapper, + csoProperties, + documentMapper, + csoPartyMapper, + packageAuthorityMapper, + efilingDocumentService); } + + + +} diff --git a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/SoapProperties.java b/src/backend/libs/efiling-cso-starter/src/main/java/ca/bc/gov/open/jag/efilingcsostarter/config/SoapProperties.java similarity index 80% rename from src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/SoapProperties.java rename to src/backend/libs/efiling-cso-starter/src/main/java/ca/bc/gov/open/jag/efilingcsostarter/config/SoapProperties.java index 8b7cf3ef2a..74d10abafd 100644 --- a/src/backend/libs/efiling-commons/src/main/java/ca/bc/gov/open/jag/efilingcommons/model/SoapProperties.java +++ b/src/backend/libs/efiling-cso-starter/src/main/java/ca/bc/gov/open/jag/efilingcsostarter/config/SoapProperties.java @@ -1,5 +1,7 @@ -package ca.bc.gov.open.jag.efilingcommons.model; +package ca.bc.gov.open.jag.efilingcsostarter.config; +import ca.bc.gov.open.jag.efilingcommons.model.Clients; +import ca.bc.gov.open.jag.efilingcommons.model.EfilingSoapClientProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import java.util.List; diff --git a/src/backend/libs/efiling-cso-starter/src/main/java/ca/bc/gov/open/jag/efilingcsostarter/config/SpringCsoProperties.java b/src/backend/libs/efiling-cso-starter/src/main/java/ca/bc/gov/open/jag/efilingcsostarter/config/SpringCsoProperties.java new file mode 100644 index 0000000000..4fe3d9509d --- /dev/null +++ b/src/backend/libs/efiling-cso-starter/src/main/java/ca/bc/gov/open/jag/efilingcsostarter/config/SpringCsoProperties.java @@ -0,0 +1,8 @@ +package ca.bc.gov.open.jag.efilingcsostarter.config; + +import ca.bc.gov.open.jag.efilingcsoclient.config.CsoProperties; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "cso") +public class SpringCsoProperties extends CsoProperties { +} diff --git a/src/backend/libs/efiling-cso-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/backend/libs/efiling-cso-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 0000000000..6cd600a26b --- /dev/null +++ b/src/backend/libs/efiling-cso-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +ca.bc.gov.open.jag.efilingcsostarter.config.AutoConfiguration \ No newline at end of file diff --git a/src/backend/libs/efiling-cso-starter/src/test/java/ca/bc/gov/open/jag/efilingcsostarter/config/AutoConfigurationTest.java b/src/backend/libs/efiling-cso-starter/src/test/java/ca/bc/gov/open/jag/efilingcsostarter/config/AutoConfigurationTest.java new file mode 100644 index 0000000000..bc05195802 --- /dev/null +++ b/src/backend/libs/efiling-cso-starter/src/test/java/ca/bc/gov/open/jag/efilingcsostarter/config/AutoConfigurationTest.java @@ -0,0 +1,84 @@ +package ca.bc.gov.open.jag.efilingcsostarter.config; + + +import ca.bc.gov.open.jag.efilingcommons.service.*; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import ca.bc.gov.open.jag.efilingcsoclient.config.CsoProperties; +import ca.bc.gov.open.jag.efilingcsoclient.mappers.AccountDetailsMapper; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@DisplayName("AutoConfiguration Test") +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class AutoConfigurationTest { + + ApplicationContextRunner context; + + private AutoConfiguration sut; + + @BeforeAll + public void setup() { + context = new ApplicationContextRunner() + .withUserConfiguration(AutoConfiguration.class) + .withPropertyValues("cso.fileServerHost=localhost", + "jag.efiling.soap.clients[0].client=ACCOUNT", + "jag.efiling.soap.clients[0].userName=username", + "jag.efiling.soap.clients[0].password=password", + "jag.efiling.soap.clients[0].uri=http://locahost", + "jag.efiling.soap.clients[1].client=ROLE", + "jag.efiling.soap.clients[1].userName=username", + "jag.efiling.soap.clients[1].password=password", + "jag.efiling.soap.clients[1].uri=http://locahost", + "jag.efiling.soap.clients[2].client=LOOKUP", + "jag.efiling.soap.clients[2].userName=username", + "jag.efiling.soap.clients[2].password=password", + "jag.efiling.soap.clients[2].uri=http://locahost", + "jag.efiling.soap.clients[3].client=STATUS", + "jag.efiling.soap.clients[3].userName=username", + "jag.efiling.soap.clients[3].password=password", + "jag.efiling.soap.clients[3].uri=http://locahost", + "jag.efiling.soap.clients[4].client=CSOWS", + "jag.efiling.soap.clients[4].userName=username", + "jag.efiling.soap.clients[4].password=password", + "jag.efiling.soap.clients[4].uri=http://locahost", + "jag.efiling.soap.clients[5].client=FILING", + "jag.efiling.soap.clients[5].userName=username", + "jag.efiling.soap.clients[5].password=password", + "jag.efiling.soap.clients[5].uri=http://locahost", + "jag.efiling.soap.clients[6].client=SERVICE", + "jag.efiling.soap.clients[6].userName=username", + "jag.efiling.soap.clients[6].password=password", + "jag.efiling.soap.clients[6].uri=http://locahost", + "jag.efiling.soap.clients[7].client=REPORT", + "jag.efiling.soap.clients[7].userName=username", + "jag.efiling.soap.clients[7].password=password", + "jag.efiling.soap.clients[7].uri=http://locahost", + "jag.efiling.soap.clients[8].client=SEARCH", + "jag.efiling.soap.clients[8].userName=username", + "jag.efiling.soap.clients[8].password=password", + "jag.efiling.soap.clients[8].uri=http://locahost") + .withUserConfiguration(CsoProperties.class); + } + + @Test + @DisplayName("Test that beans are created") + public void testBeansAreGenerated() { + + context.run(it -> { + assertThat(it).hasSingleBean(EfilingAccountService.class); + assertThat(it).hasSingleBean(EfilingDocumentService.class); + assertThat(it).hasSingleBean(EfilingLookupService.class); + assertThat(it).hasSingleBean(EfilingCourtService.class); + assertThat(it).hasSingleBean(EfilingSubmissionService.class); + assertThat(it).hasSingleBean(EfilingReviewService.class); + assertThat(it).hasSingleBean(EfilingSearchService.class); + assertThat(it).hasSingleBean(AccountDetailsMapper.class); + }); + + } +} diff --git a/src/backend/libs/efiling-demo-starter/pom.xml b/src/backend/libs/efiling-demo-starter/pom.xml index 3a82e87a45..c068a2d3b7 100644 --- a/src/backend/libs/efiling-demo-starter/pom.xml +++ b/src/backend/libs/efiling-demo-starter/pom.xml @@ -1,86 +1,113 @@ - - - 4.0.0 - - ca.bc.gov.open.jag - efiling-demo-starter - 0.0.1-SNAPSHOT - - - 1.8 - 1.3.1.Final - - - - - - org.springframework.boot - spring-boot-starter - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - - - - - - org.apache.commons - commons-lang3 - - - - ca.bc.gov.open.jag - efiling-commons - 0.0.1-SNAPSHOT - - - - - - - - org.springframework.boot - spring-boot-dependencies - 2.3.1.RELEASE - pom - import - - - ca.bc.gov.open.jag - efiling-bom - 0.0.1-SNAPSHOT - pom - import - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - ${java.version} - ${java.version} - - - - - - - - + + + 4.0.0 + + ca.bc.gov.open.jag + efiling-demo-starter + 2.0.12-SNAPSHOT + + + 17 + 1.4.2.Final + 2.17.1 + + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + org.apache.commons + commons-lang3 + + + + ca.bc.gov.open + spring-bceid-starter + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.data + spring-data-redis + + + redis.clients + jedis + 6.0.0 + + + + ca.bc.gov.open.jag + efiling-commons + 2.0.12-SNAPSHOT + + + + ca.bc.gov.open + spring-sftp-starter + + + + + + + + org.springframework.boot + spring-boot-dependencies + 3.5.0 + pom + import + + + ca.bc.gov.open.jag + efiling-bom + 2.0.12-SNAPSHOT + pom + import + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + -parameters + + ${java.version} + ${java.version} + + + + + + + + diff --git a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/AccountDetailsCache.java b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/AccountDetailsCache.java new file mode 100644 index 0000000000..6212ad9cb7 --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/AccountDetailsCache.java @@ -0,0 +1,12 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; + +public interface AccountDetailsCache { + + + AccountDetails put(AccountDetails accountDetails); + + AccountDetails get(String userGuid); + +} diff --git a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/AccountDetailsCacheImpl.java b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/AccountDetailsCacheImpl.java new file mode 100644 index 0000000000..9292d987c2 --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/AccountDetailsCacheImpl.java @@ -0,0 +1,21 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; + +public class AccountDetailsCacheImpl implements AccountDetailsCache { + + @Override + @CachePut(cacheNames = "account", key = "#accountDetails.universalId", cacheManager = "demoAccountCacheManager", unless="#result == null") + public AccountDetails put(AccountDetails accountDetails) { + return null; + } + + @Override + @Cacheable(cacheNames = "account", key = "#userGuid", cacheManager = "demoAccountCacheManager", unless="#result == null") + public AccountDetails get(String userGuid) { + return null; + } + +} diff --git a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/AutoConfiguration.java b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/AutoConfiguration.java index 610945c50d..6dcfa0438e 100644 --- a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/AutoConfiguration.java +++ b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/AutoConfiguration.java @@ -1,16 +1,49 @@ package ca.bc.gov.open.jag.efiling.demo; -import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; -import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.bceid.starter.account.BCeIDAccountService; +import ca.bc.gov.open.bceid.starter.account.GetAccountRequest; +import ca.bc.gov.open.bceid.starter.account.models.IndividualIdentity; +import ca.bc.gov.open.bceid.starter.account.models.Name; +import ca.bc.gov.open.jag.efilingcommons.court.EfilingCourtLocationService; +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.EfilingPayment; +import ca.bc.gov.open.jag.efilingcommons.model.PaymentTransaction; +import ca.bc.gov.open.jag.efilingcommons.payment.PaymentAdapter; +import ca.bc.gov.open.jag.efilingcommons.service.*; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import ca.bc.gov.open.sftp.starter.SftpService; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.Cacheable; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.math.BigDecimal; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; @Configuration +@ComponentScan public class AutoConfiguration { + + public static final String TRANSACTION_STATE_DECLINED = "DEC"; + public static final String TRANSACTION_STATE_APPROVED = "APP"; + @Bean - public EfilingAccountService efilingAccountService() { - return new EfilingAccountServiceDemoImpl(); + public EfilingAccountService efilingAccountService(AccountDetailsCache accountDetailsCache) { + return new EfilingAccountServiceDemoImpl(accountDetailsCache); } @Bean @@ -18,4 +51,127 @@ public EfilingLookupService efilingLookupService() { return new EfilingLookupServiceDemoImpl(); } + @Bean + public EfilingDocumentService efilingDocumentService() { return new EfilingDocumentServiceDemoImpl(); } + + @Bean + public EfilingCourtService efilingCourtService() { return new EfilingCourtServiceDemoImpl(); } + + @Bean + public EfilingSubmissionService efilingSubmissionService() { return new EfilingSubmissionServiceDemoImpl(); } + + @Bean + public EfilingCourtLocationService efilingCourtLocationService() { return new EfilingCourtLocationServiceDemoImpl(); } + + @Bean + public EfilingReviewService efilingReviewService() { return new EfilingReviewServiceDemoImpl(); } + + @Bean + public AccountDetailsCache accountDetailsCache() { return new AccountDetailsCacheImpl(); } + + @Bean + public EfilingSearchService efilingSearchService() { return new EfilingSearchServiceDemoImpl(); } + + /** + * Configures the cache manager for demo accounts + * @param jedisConnectionFactory A jedisConnectionFactory + * @return + */ + @Bean(name = "demoAccountCacheManager") + public CacheManager demoAccountCacheManager(JedisConnectionFactory jedisConnectionFactory, + @Qualifier("accountSerializer") Jackson2JsonRedisSerializer jackson2JsonRedisSerializer) { + + RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() + .disableCachingNullValues() + .serializeValuesWith(RedisSerializationContext + .SerializationPair.fromSerializer(jackson2JsonRedisSerializer)); + + redisCacheConfiguration.usePrefix(); + + return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(jedisConnectionFactory) + .cacheDefaults(redisCacheConfiguration).build(); + + } + + @Bean(name = "accountSerializer") + public Jackson2JsonRedisSerializer jackson2JsonRedisSerializer() { + return new Jackson2JsonRedisSerializer(AccountDetails.class); + } + + /** + * Configures the cache manager + * @param jedisConnectionFactory A jedisConnectionFactory + * @return + */ + @Bean(name = "demoDocumentCacheManager") + public CacheManager demoDocumentCacheManager( + JedisConnectionFactory jedisConnectionFactory) { + + RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() + .disableCachingNullValues() + .entryTtl(Duration.ofHours(24)); + + redisCacheConfiguration.usePrefix(); + + return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(jedisConnectionFactory) + .cacheDefaults(redisCacheConfiguration).build(); + } + + @Bean(name = "demoSftpService") + @Primary + public SftpService sftpService() { + return new SftpService() { + @Override + public ByteArrayInputStream getContent(String s) { + return null; + } + + @Override + public void moveFile(String s, String s1) { + // not in use in demo so left without implementation + } + + @Override + @Cacheable(cacheNames = "demoDocument", key = "#s", cacheManager = "demoDocumentCacheManager", unless = "#result == null") + public void put(InputStream inputStream, String s) { + // not in use in demo so left without implementation + } + + @Override + public List listFiles(String s) { + return new ArrayList<>(); + } + }; + } + + @Bean + public BCeIDAccountService bCeIDAccountService() { + return new BCeIDAccountService() { + @Override + public Optional getIndividualIdentity(GetAccountRequest getAccountRequest) { + IndividualIdentity individualIdentity = IndividualIdentity.builder().name(Name.builder().firstName("efilehub test account").middleName("").surname("efile tester").create()).create(); + return Optional.of(individualIdentity); + } + }; + } + + + @Bean + public PaymentAdapter paymentAdapter() { + return new PaymentAdapter() { + @Override + public PaymentTransaction makePayment(EfilingPayment efilingPayment) { + PaymentTransaction paymentTransaction = new PaymentTransaction(); + if(efilingPayment.getPaymentAmount().equals(new BigDecimal(10))) { + paymentTransaction.setApprovalCd(TRANSACTION_STATE_DECLINED); + } else { + paymentTransaction.setApprovalCd(TRANSACTION_STATE_APPROVED); + } + return paymentTransaction; + + } + }; + } + + } diff --git a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingAccountServiceDemoImpl.java b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingAccountServiceDemoImpl.java index 137ce09f81..867cd61458 100644 --- a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingAccountServiceDemoImpl.java +++ b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingAccountServiceDemoImpl.java @@ -2,32 +2,53 @@ import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.CreateAccountRequest; import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; -import org.springframework.stereotype.Service; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; import java.math.BigDecimal; -import java.util.*; -@Service public class EfilingAccountServiceDemoImpl implements EfilingAccountService { - public static final UUID ACCOUNT_WITH_EFILING_ROLE = UUID.fromString("77da92db-0791-491e-8c58-1a969e67d2fa"); - public static final UUID ACCOUNT_WITHOUT_EFILING_ROLE = UUID.fromString("77da92db-0791-491e-8c58-1a969e67d2fb"); + private final AccountDetailsCache accountDetailsCache; + public EfilingAccountServiceDemoImpl(AccountDetailsCache accountDetailsCache) { + this.accountDetailsCache = accountDetailsCache; + } + + @Cacheable(cacheNames = "account", key = "#userGuid", unless="#result == null", cacheManager = "demoAccountCacheManager") + public AccountDetails getAccountDetails(String userGuid) { + + return accountDetailsCache.get(userGuid); + + } + + @CachePut(cacheNames = "account", key = "#p0.universalId", cacheManager = "demoAccountCacheManager") + public AccountDetails createAccount(CreateAccountRequest createAccountRequest) { - private Map csoAccounts = new HashMap<>(); + AccountDetails accountDetails = new AccountDetails.Builder() + .universalId(createAccountRequest.getUniversalId()) + .accountId(BigDecimal.valueOf(437)) + .clientId(BigDecimal.valueOf(752)) + .fileRolePresent(createAccountRequest.getUniversalId() != Keys.ACCOUNT_WITHOUT_EFILING_ROLE) + .cardRegistered(true) + .create(); - public EfilingAccountServiceDemoImpl() { + this.accountDetailsCache.put(accountDetails); - AccountDetails accountWithEfilingRole = new AccountDetails(BigDecimal.TEN, BigDecimal.TEN, true, "", "", "", ""); - AccountDetails accountWithoutEfilingRole = new AccountDetails(BigDecimal.TEN, BigDecimal.TEN, false, "", "", "", ""); + return accountDetails; - csoAccounts.put(ACCOUNT_WITH_EFILING_ROLE, accountWithEfilingRole); - csoAccounts.put(ACCOUNT_WITHOUT_EFILING_ROLE, accountWithoutEfilingRole); } + @Override + public void updateClient(AccountDetails accountDetails) { + this.accountDetailsCache.put(accountDetails); + } - public AccountDetails getAccountDetails(UUID userGuid, String bceidAccountType) { - return csoAccounts.get(userGuid); + @Override + public String getOrderNumber() { + return "1234"; } + } diff --git a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingCourtLocationServiceDemoImpl.java b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingCourtLocationServiceDemoImpl.java new file mode 100644 index 0000000000..c8967e6737 --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingCourtLocationServiceDemoImpl.java @@ -0,0 +1,48 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.court.EfilingCourtLocationService; +import ca.bc.gov.open.jag.efilingcommons.model.Address; +import ca.bc.gov.open.jag.efilingcommons.model.InternalCourtLocation; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; + +public class EfilingCourtLocationServiceDemoImpl implements EfilingCourtLocationService { + + @Override + public List getCourtLocations(String courtType) { + + InternalCourtLocation courtLocationOne = new InternalCourtLocation(); + courtLocationOne.setId(BigDecimal.valueOf(10264)); + courtLocationOne.setIdentifierCode("5871"); + courtLocationOne.setName("Campbell River"); + courtLocationOne.setCode("OMH"); + courtLocationOne.setIsSupremeCourt(true); + Address addressOne = new Address(); + addressOne.setAddressLine1("500 - 13th Avenue"); + addressOne.setPostalCode("V9W 6P1"); + addressOne.setCityName("Campbell River"); + addressOne.setProvinceName("British Columbia"); + addressOne.setCountryName("Canada"); + courtLocationOne.setAddress(addressOne); + + InternalCourtLocation courtLocationTwo = new InternalCourtLocation(); + courtLocationTwo.setId(BigDecimal.valueOf(9393)); + courtLocationTwo.setIdentifierCode("3561"); + courtLocationTwo.setName("Chilliwack"); + courtLocationTwo.setCode("ABB"); + courtLocationTwo.setIsSupremeCourt(true); + Address addressTwo = new Address(); + addressTwo.setAddressLine1("46085 Yale Road"); + addressTwo.setAddressLine2(" "); + addressTwo.setAddressLine3(" "); + addressTwo.setPostalCode("V2P 2L8"); + addressTwo.setCityName("Chilliwack"); + addressTwo.setProvinceName("British Columbia"); + addressTwo.setCountryName("Canada"); + courtLocationTwo.setAddress(addressTwo); + + return Arrays.asList(courtLocationOne,courtLocationTwo); + } +} diff --git a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingCourtServiceDemoImpl.java b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingCourtServiceDemoImpl.java new file mode 100644 index 0000000000..ca077c9f79 --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingCourtServiceDemoImpl.java @@ -0,0 +1,24 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.model.CourtDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingCourtService; + +import java.math.BigDecimal; +import java.util.Optional; + +public class EfilingCourtServiceDemoImpl implements EfilingCourtService { + @Override + public Optional getCourtDescription(String agencyIdentifierCd, String courtLevel, String courtClass) { + return Optional.of(new CourtDetails(BigDecimal.TEN, "Imma Court", "Imma Class", "Imma Level")); + } + + @Override + public boolean checkValidLevelClassLocation(BigDecimal agencyId, String courtLevel, String courtClass, String applicationCode) { + return true; + } + + @Override + public boolean checkValidCourtFileNumber(String fileNumber, BigDecimal agencyId, String courtLevel, String courtClass, String applicationCode) { + return true; + } +} diff --git a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingDocumentServiceDemoImpl.java b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingDocumentServiceDemoImpl.java new file mode 100644 index 0000000000..5d2b14e88d --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingDocumentServiceDemoImpl.java @@ -0,0 +1,20 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingDocumentService; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; + +public class EfilingDocumentServiceDemoImpl implements EfilingDocumentService { + @Override + public DocumentTypeDetails getDocumentTypeDetails(String courtLevel, String courtClass, String documentType) { + return new DocumentTypeDetails("This is a doc", documentType, BigDecimal.valueOf(7), true, true, false); + } + + @Override + public List getDocumentTypes(String courtLevel, String courtClass) { + return Arrays.asList(new DocumentTypeDetails("Description1", "AFF", BigDecimal.valueOf(7),true, true, false), new DocumentTypeDetails("Description2", "Type2", BigDecimal.valueOf(7),true, true, false), new DocumentTypeDetails("Description2", "POR", BigDecimal.valueOf(7),true, true, false)); + } +} diff --git a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingLookupServiceDemoImpl.java b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingLookupServiceDemoImpl.java index 55c6bade4d..4b67406535 100644 --- a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingLookupServiceDemoImpl.java +++ b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingLookupServiceDemoImpl.java @@ -1,24 +1,39 @@ package ca.bc.gov.open.jag.efiling.demo; import ca.bc.gov.open.jag.efilingcommons.model.ServiceFees; +import ca.bc.gov.open.jag.efilingcommons.model.SubmissionFeeRequest; import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; -import org.joda.time.DateTime; +import ca.bc.gov.open.jag.efilingcommons.submission.models.LookupItem; import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; public class EfilingLookupServiceDemoImpl implements EfilingLookupService { @Override - public ServiceFees getServiceFee(String serviceId) { + public List getCountries() { + return Arrays.asList( + LookupItem.builder().code("1").description("Canada").create(), + LookupItem.builder().code("1").description("United States").create(), + LookupItem.builder().code("34").description("Spain").create()); + } + + @Override + public ServiceFees getServiceFee(SubmissionFeeRequest submissionFeeRequest) { - return new ServiceFees(DateTime.now(), + return new ServiceFees( BigDecimal.valueOf(7), - "entUserId", - "serviceTypeCd", - DateTime.now(), - "updUserId", - DateTime.now(), - DateTime.now()); + "serviceTypeCd"); + + } + + @Override + public List getValidPartyRoles(String courtLevel, String courtClass, String documentTypes) { + List validRoles = new ArrayList<>(); + validRoles.add("APP"); + return validRoles; } } diff --git a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingReviewServiceDemoImpl.java b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingReviewServiceDemoImpl.java new file mode 100644 index 0000000000..03bd1c3a2b --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingReviewServiceDemoImpl.java @@ -0,0 +1,277 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.model.Individual; +import ca.bc.gov.open.jag.efilingcommons.model.Organization; +import ca.bc.gov.open.jag.efilingcommons.model.RushDocumentRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.DeleteSubmissionDocumentRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackageRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.ReportRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.*; +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; + +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.text.MessageFormat; +import java.util.*; + +public class EfilingReviewServiceDemoImpl implements EfilingReviewService { + + @Override + public Optional findStatusByPackage(FilingPackageRequest filingPackageRequest) { + if (filingPackageRequest.getPackageNo().equals(BigDecimal.ONE)) { + return Optional.of(createReviewPackage("1", true)); + } else if (filingPackageRequest.getPackageNo().equals(new BigDecimal(2))) { + return Optional.of(createReviewPackage("2", false)); + } else if (filingPackageRequest.getPackageNo().equals(new BigDecimal(3))) { + return Optional.of(createReviewPackage("3", false)); + } else { + return Optional.empty(); + } + } + + @Override + public List findStatusByClient(FilingPackageRequest filingPackageRequest) { + + if (StringUtils.isBlank(filingPackageRequest.getParentApplication())) { + return Arrays.asList(createReviewPackage("1", true), createReviewPackage("2", false), createReviewPackage("3", true)); + } else if (filingPackageRequest.getParentApplication().equals(Keys.PARENT_APPLICATION_FLA)) { + return Arrays.asList(createReviewPackage("1", true), createReviewPackage("2", false)); + } else if (filingPackageRequest.getParentApplication().equals(Keys.PARENT_APPLICATION_COA)) { + return Collections.singletonList(createReviewPackage("3", true)); + } else if (filingPackageRequest.getParentApplication().equals(Keys.PARENT_APPLICATION_OTHER)) { + return Collections.singletonList(createReviewPackage("4", true)); + } else { + return new ArrayList<>(); + } + + } + + @Override + public Optional getReport(ReportRequest reportRequest) { + + return getDocument(); + + } + + @Override + public Optional getSubmittedDocument(BigDecimal documentIdentifier) { + + return getDocument(); + + } + + @Override + public void deleteSubmittedDocument(DeleteSubmissionDocumentRequest deleteSubmissionDocumentRequest) { + //Do nothing + } + + @Override + public Optional getRushDocument(RushDocumentRequest rushDocumentRequest) { + + return getDocument(); + + } + + private Optional getDocument() { + try { + InputStream initialStream = getClass().getResourceAsStream("/demo-file/test-document.pdf"); + byte[] targetArray = new byte[initialStream.available()]; + initialStream.read(targetArray); + return Optional.of(targetArray); + } catch (IOException e) { + return Optional.empty(); + } + } + + private ReviewFilingPackage createReviewPackage(String packageNo, Boolean hasRegistry) { + ReviewFilingPackage reviewFilingPackage = new ReviewFilingPackage(); + reviewFilingPackage.setFirstName("Han"); + reviewFilingPackage.setLastName("Solo"); + reviewFilingPackage.setFilingCommentsTxt(MessageFormat.format("Lorem ipsum dolor sit amet, consectetur adipiscing elit, {1} sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.{0}{0}Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", System.lineSeparator(), "")); + reviewFilingPackage.setHasChecklist(false); + reviewFilingPackage.setHasRegistryNotice(hasRegistry); + reviewFilingPackage.setPackageNo(packageNo); + reviewFilingPackage.setSubmittedDate(DateTime.parse("2020-5-5")); + reviewFilingPackage.setCourt(createCourt()); + reviewFilingPackage.setParties(createParty()); + reviewFilingPackage.setDocuments(createReviewDocuments()); + reviewFilingPackage.setPayments(createPayment()); + reviewFilingPackage.setPackageLinks(PackageLinks.builder().packageHistoryUrl("http://localhost:8080/wherearemypackage").create()); + reviewFilingPackage.setOrganizations(createOrganizations()); + reviewFilingPackage.setRushOrder(createRushOrder()); + return reviewFilingPackage; + } + + private ReviewCourt createCourt() { + ReviewCourt reviewCourt = new ReviewCourt(); + reviewCourt.setFileNumber("123"); + reviewCourt.setCourtClass("F"); + reviewCourt.setLevel("P"); + reviewCourt.setLocationCd("KEL"); + reviewCourt.setLocationId(BigDecimal.ONE); + reviewCourt.setLocationName("Kelowna Law Courts"); + reviewCourt.setExistingFileYN(false); + reviewCourt.setDivision("DIVISION"); + reviewCourt.setLocationDescription("DESCRIPTION"); + reviewCourt.setParticipatingClass("DESCRIPTION"); + reviewCourt.setLocationDescription("DESCRIPTION"); + reviewCourt.setLevelDescription("DESCRIPTION"); + reviewCourt.setClassDescription("DESCRIPTION"); + return reviewCourt; + } + + private List createReviewDocuments() { + + List documents = new ArrayList<>(); + documents.add(createReviewDocument("1","SUB","Submitted", "test-document.pdf","1")); + documents.add(createReviewDocument("2", "REF", "Referred", "test-document-hello.pdf","2")); + documents.add(createReviewDocument("3", "FILE", "Filed", "File12341234.pdf","3")); + documents.add(createReviewDocument("4", "WDRN", "Withdrawn", "Registration-of-divorce-proceedings2020265814.pdf","4")); + documents.add(createReviewDocument("5", "CCOR", "Courtesy Correction", "loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong-filename.pdf","5")); + documents.add(createReviewDocument("6", "RSUB", "Resubmitted", "123.pdf","6")); + documents.add(createReviewDocument("7", "REJ", "Rejected", "rejected-document.pdf","7")); + + return documents; + + } + + private ReviewDocument createReviewDocument(String documentId, String statusCd, String status, String filename, + String seqNo) { + ReviewDocument reviewDocument = new ReviewDocument(); + reviewDocument.setDateFiled(DateTime.parse("2020-5-5")); + reviewDocument.setDocumentId(documentId); + reviewDocument.setDocumentType("Affidavit"); + reviewDocument.setDocumentTypeCd("AFF"); + reviewDocument.setDocumentUploadStatusCd("CMPL"); + reviewDocument.setFileName(filename); + reviewDocument.setInitiatingDoc(false); + reviewDocument.setLargeFileYn("N"); + reviewDocument.setPackageId("1"); + reviewDocument.setPackageSeqNo(seqNo); + reviewDocument.setPaymentProcessed(false); + reviewDocument.setStatus(status); + reviewDocument.setStatusCode(statusCd); + reviewDocument.setStatusDate(DateTime.parse("2020-12-17")); + reviewDocument.setTrialDivision(false); + reviewDocument.setXmlDoc(false); + return reviewDocument; + } + + private List createParty() { + + Individual individualOne = Individual.builder() + .firstName("Bob") + .middleName("Q") + .lastName("Ross") + .roleTypeCd("APP") + .roleTypeDesc("Applicant") + .partyTypeDesc("Individual") + .create(); + + Individual individualTwo = Individual.builder() + .firstName("Looooooongname") + .middleName("Q") + .lastName("Loooooooooong-Looooooooooonglast") + .roleTypeCd("APP") + .roleTypeDesc("Applicant") + .partyTypeDesc("Individual") + .create(); + + return Arrays.asList(individualOne, individualTwo); + + } + + private List createOrganizations() { + + Organization organizationOne = Organization.builder() + .name("The Organization Org.") + .roleTypeCd("APP") + .roleTypeDesc("Applicant") + .partyTypeDesc("Organization") + .create(); + + Organization organizationTwo = Organization.builder() + .name("This is a very very very very loooooong organization name") + .roleTypeCd("APP") + .roleTypeDesc("Applicant") + .partyTypeDesc("Organization") + .create(); + + return Arrays.asList(organizationOne, organizationTwo); + + } + + private List createPayment() { + PackagePayment packagePaymentOne = new PackagePayment(); + packagePaymentOne.setFeeExmpt(false); + packagePaymentOne.setPaymentCategory(BigDecimal.ONE); + packagePaymentOne.setProcessedAmt(new BigDecimal(7)); + packagePaymentOne.setServiceId(BigDecimal.ONE); + packagePaymentOne.setSubmittedAmt(new BigDecimal(7)); + packagePaymentOne.setTransactionDtm(DateTime.parse("2020-12-17")); + PackagePayment packagePaymentTwo = new PackagePayment(); + packagePaymentTwo.setFeeExmpt(true); + packagePaymentTwo.setPaymentCategory(new BigDecimal(3)); + packagePaymentTwo.setSubmittedAmt(BigDecimal.ONE); + packagePaymentTwo.setTransactionDesc("Affidavit"); + PackagePayment packagePaymentThree = new PackagePayment(); + packagePaymentThree.setFeeExmpt(true); + packagePaymentThree.setPaymentCategory(new BigDecimal(3)); + packagePaymentThree.setSubmittedAmt(BigDecimal.ONE); + packagePaymentThree.setTransactionDesc("Affidavit"); + return Arrays.asList(packagePaymentOne, packagePaymentTwo, packagePaymentThree); + } + + private ReviewRushOrder createRushOrder() { + ReviewRushOrder reviewRushOrder = new ReviewRushOrder(); + reviewRushOrder.setContactEmailTxt("hello@hello.com"); + reviewRushOrder.setContactFirstGivenNm("Bob"); + reviewRushOrder.setContactSurnameNm("Ross"); + reviewRushOrder.setContactOrganizationNm("Paint It"); + reviewRushOrder.setContactPhoneNo("1231231234"); + reviewRushOrder.setCurrentStatusDsc("Processing"); + reviewRushOrder.setCtryId(BigDecimal.ONE); + reviewRushOrder.setCountryDsc("Canada"); + reviewRushOrder.setCourtOrderDt(DateTime.parse("2020-12-17")); + reviewRushOrder.setPackageId(BigDecimal.ONE); + reviewRushOrder.setProcessReasonCd("OTHR"); + reviewRushOrder.setProcessingCommentTxt("Registry notice reason text"); + reviewRushOrder.setRushFilingReasonTxt("This is a reason. This is a reason. This is a reason. This is a reason."); + reviewRushOrder.setSupportDocs(createRushDocuments()); + return reviewRushOrder; + } + + private List createRushDocuments() { + RushDocument rushDocumentOne = new RushDocument(); + rushDocumentOne.setClientFileNm("Test.pdf"); + rushDocumentOne.setEntDtm(new DateTime()); + rushDocumentOne.setEntUserId("1"); + rushDocumentOne.setFileServer("www.google.com"); + rushDocumentOne.setObjectGuid("9b35f5d6-50e9-4cd5-9d46-8ce1f9e484c8"); + rushDocumentOne.setProcessItemSeqNo(BigDecimal.ONE); + rushDocumentOne.setProcessRequestId(BigDecimal.ONE); + rushDocumentOne.setProcessSupportDocSeqNo(BigDecimal.ONE); + rushDocumentOne.setTempFileName("Test.pdf"); + rushDocumentOne.setUpdUserId("1"); + rushDocumentOne.setUpdDtm(new DateTime()); + + RushDocument rushDocumentTwo = new RushDocument(); + rushDocumentTwo.setClientFileNm("Test1.pdf"); + rushDocumentTwo.setEntDtm(new DateTime()); + rushDocumentTwo.setEntUserId("1"); + rushDocumentTwo.setFileServer("www.google.com"); + rushDocumentTwo.setObjectGuid("9b35f5d6-50e9-4cd5-9d46-8ce1f9e484c8"); + rushDocumentTwo.setProcessItemSeqNo(BigDecimal.ONE); + rushDocumentTwo.setProcessRequestId(BigDecimal.ONE); + rushDocumentTwo.setProcessSupportDocSeqNo(BigDecimal.ONE); + rushDocumentTwo.setTempFileName("Test.pdf"); + rushDocumentTwo.setUpdUserId("1"); + rushDocumentTwo.setUpdDtm(new DateTime()); + + return Arrays.asList(rushDocumentOne, rushDocumentTwo); + + } +} diff --git a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingSearchServiceDemoImpl.java b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingSearchServiceDemoImpl.java new file mode 100644 index 0000000000..51013cff74 --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingSearchServiceDemoImpl.java @@ -0,0 +1,12 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSearchService; +import org.apache.commons.lang3.StringUtils; + +public class EfilingSearchServiceDemoImpl implements EfilingSearchService { + + @Override + public boolean caseNumberExists(String caseNumber) { + return StringUtils.equals("1", caseNumber); + } +} diff --git a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingSubmissionServiceDemoImpl.java b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingSubmissionServiceDemoImpl.java new file mode 100644 index 0000000000..8d09a17d3e --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/EfilingSubmissionServiceDemoImpl.java @@ -0,0 +1,17 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.SubmitPackageResponse; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingPaymentService; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingSubmissionService; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackage; + +import java.math.BigDecimal; + +public class EfilingSubmissionServiceDemoImpl implements EfilingSubmissionService { + + @Override + public SubmitPackageResponse submitFilingPackage(AccountDetails accountDetails, FilingPackage efilingPackage, EfilingPaymentService payment) { + return SubmitPackageResponse.builder().transactionId(BigDecimal.ONE).packageLink("http://demo").create(); + } +} diff --git a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/Keys.java b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/Keys.java new file mode 100644 index 0000000000..6f7f964bf8 --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/Keys.java @@ -0,0 +1,13 @@ +package ca.bc.gov.open.jag.efiling.demo; + +public class Keys { + + protected Keys() {} + + public static final String ACCOUNT_WITH_EFILING_ROLE = "77da92db-0791-491e-8c58-1a969e67d2fa"; + public static final String ACCOUNT_WITHOUT_EFILING_ROLE = "77da92db-0791-491e-8c58-1a969e67d2fb"; + public static final String PARENT_APPLICATION_FLA = "FLA"; + public static final String PARENT_APPLICATION_COA = "COA"; + public static final String PARENT_APPLICATION_OTHER = "OTHER"; + +} diff --git a/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/SeedAccount.java b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/SeedAccount.java new file mode 100644 index 0000000000..ae9f4fb43c --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/main/java/ca/bc/gov/open/jag/efiling/demo/SeedAccount.java @@ -0,0 +1,58 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.CreateAccountRequest; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +@Component +public class SeedAccount { + + private static final Logger logger = LoggerFactory.getLogger(SeedAccount.class); + + private final EfilingAccountService efilingAccountService; + + public SeedAccount(EfilingAccountService efilingAccountService){ + + this.efilingAccountService = efilingAccountService; + + } + + @EventListener + public void onApplicationEvent(ContextRefreshedEvent event) { + init(); + } + + private void init() { + + CreateAccountRequest createAccount1 = CreateAccountRequest + .builder() + .universalId(Keys.ACCOUNT_WITH_EFILING_ROLE) + .firstName("Vivian") + .lastName("Brown") + .email("vbrown@paintit.com") + .create(); + + AccountDetails account1 = efilingAccountService.createAccount(createAccount1); + + logger.info("Account 1 created {}", account1.getUniversalId()); + + CreateAccountRequest createAccount2 = CreateAccountRequest + .builder() + .universalId(Keys.ACCOUNT_WITHOUT_EFILING_ROLE) + .firstName("Lynda") + .lastName("Ridge") + .email("lridge@paintit.com") + .create(); + + AccountDetails account2 = efilingAccountService.createAccount(createAccount2); + + logger.info("Account 2 created {}", account2.getUniversalId()); + + } + +} diff --git a/src/backend/libs/efiling-demo-starter/src/main/resources/META-INF/spring.factories b/src/backend/libs/efiling-demo-starter/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 91b4434459..0000000000 --- a/src/backend/libs/efiling-demo-starter/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - ca.bc.gov.open.jag.efiling.demo.AutoConfiguration diff --git a/src/backend/libs/efiling-demo-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/backend/libs/efiling-demo-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 0000000000..187d3d572b --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +ca.bc.gov.open.jag.efiling.demo.AutoConfiguration diff --git a/src/backend/libs/efiling-demo-starter/src/main/resources/demo-file/test-document.pdf b/src/backend/libs/efiling-demo-starter/src/main/resources/demo-file/test-document.pdf new file mode 100644 index 0000000000..98c48e0602 Binary files /dev/null and b/src/backend/libs/efiling-demo-starter/src/main/resources/demo-file/test-document.pdf differ diff --git a/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/AccountDetailsCacheImplTest.java b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/AccountDetailsCacheImplTest.java new file mode 100644 index 0000000000..2ba628293f --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/AccountDetailsCacheImplTest.java @@ -0,0 +1,27 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +import java.math.BigDecimal; +import java.util.UUID; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class AccountDetailsCacheImplTest { + + private AccountDetailsCacheImpl sut; + + @Test + @DisplayName("Cache test are useles") + public void testCache() { + sut = new AccountDetailsCacheImpl(); + Assertions.assertDoesNotThrow(() -> sut.get(UUID.randomUUID().toString())); + Assertions.assertDoesNotThrow(() -> sut.put(AccountDetails.builder().clientId(BigDecimal.TEN).create())); + + } + + +} diff --git a/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/AutoConfigurationTest.java b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/AutoConfigurationTest.java index 2af1f52471..7b0bfecd38 100644 --- a/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/AutoConfigurationTest.java +++ b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/AutoConfigurationTest.java @@ -1,36 +1,74 @@ package ca.bc.gov.open.jag.efiling.demo; -import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; -import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; +import ca.bc.gov.open.bceid.starter.account.BCeIDAccountService; +import ca.bc.gov.open.bceid.starter.account.GetAccountRequest; +import ca.bc.gov.open.jag.efilingcommons.court.EfilingCourtLocationService; +import ca.bc.gov.open.jag.efilingcommons.model.EfilingPayment; +import ca.bc.gov.open.jag.efilingcommons.payment.PaymentAdapter; +import ca.bc.gov.open.jag.efilingcommons.service.*; +import ca.bc.gov.open.jag.efilingcommons.submission.EfilingReviewService; +import ca.bc.gov.open.sftp.starter.SftpService; import org.junit.jupiter.api.*; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; + +import java.io.ByteArrayInputStream; +import java.math.BigDecimal; + +import static org.assertj.core.api.Assertions.assertThat; @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class AutoConfigurationTest { - private AutoConfiguration sut; + private ApplicationContextRunner context; - @BeforeAll - public void setUp() { - sut = new AutoConfiguration(); + @BeforeEach + public void beforeAll() { + context = new ApplicationContextRunner() + .withUserConfiguration(AutoConfiguration.class) + .withBean(JedisConnectionFactory.class); } @Test @DisplayName("OK: AutoConfiguration should return instance of EfilingAccountServiceDemoImpl") public void autoConfigurationShouldReturnDemoAccountServiceImpl() { + context.run(it -> { - EfilingAccountService actual = sut.efilingAccountService(); - Assertions.assertEquals(EfilingAccountServiceDemoImpl.class, actual.getClass()); - } + assertThat(it).hasSingleBean(EfilingAccountService.class); + assertThat(it).hasSingleBean(EfilingLookupService.class); + assertThat(it).hasSingleBean(EfilingDocumentService.class); + assertThat(it).hasSingleBean(EfilingCourtService.class); + assertThat(it).hasSingleBean(EfilingSubmissionService.class); + assertThat(it).hasSingleBean(EfilingCourtLocationService.class); + assertThat(it).hasSingleBean(EfilingReviewService.class); + assertThat(it).hasBean("demoAccountCacheManager"); + assertThat(it).hasBean("demoDocumentCacheManager"); + assertThat(it).hasSingleBean(Jackson2JsonRedisSerializer.class); + assertThat(it).hasSingleBean(BCeIDAccountService.class); - @Test - @DisplayName("OK: AutoConfiguration should return instance of EfilingLookupServiceDemoImpl") - public void autoConfigurationShouldReturnEfilingLookupServiceDemoImpl() { + assertThat(it).hasSingleBean(PaymentAdapter.class); - EfilingLookupService actual = sut.efilingLookupService(); - Assertions.assertEquals(EfilingLookupServiceDemoImpl.class, actual.getClass()); - - } + PaymentAdapter paymentAdapter = it.getBean(PaymentAdapter.class); + BCeIDAccountService bCeIDAccountService = it.getBean(BCeIDAccountService.class); + + Assertions.assertEquals("APP", paymentAdapter.makePayment(new EfilingPayment(BigDecimal.TEN, BigDecimal.ONE, "invoice", "client")).getApprovalCd()); + Assertions.assertEquals("DEC", paymentAdapter.makePayment(new EfilingPayment(BigDecimal.TEN, BigDecimal.TEN, "invoice", "client")).getApprovalCd()); + GetAccountRequest request = GetAccountRequest.BusinessSelfRequest("test"); + Assertions.assertEquals("efilehub test account", bCeIDAccountService.getIndividualIdentity(request).get().getName().getFirstName()); + assertThat(it).hasSingleBean(SftpService.class); + + SftpService sut = it.getBean(SftpService.class); + + Assertions.assertDoesNotThrow(() -> sut.put(new ByteArrayInputStream("test".getBytes()), "location")); + Assertions.assertDoesNotThrow(() -> sut.getContent("any")); + Assertions.assertDoesNotThrow(() -> sut.listFiles("any")); + Assertions.assertDoesNotThrow(() -> sut.moveFile("a", "b")); + + + }); + } } diff --git a/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingAccountServiceDemoImplTest.java b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingAccountServiceDemoImplTest.java index 2d65659435..0afbd1c55a 100644 --- a/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingAccountServiceDemoImplTest.java +++ b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingAccountServiceDemoImplTest.java @@ -1,45 +1,70 @@ package ca.bc.gov.open.jag.efiling.demo; import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.model.CreateAccountRequest; import org.junit.jupiter.api.*; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; import java.math.BigDecimal; -import java.util.UUID; @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class EfilingAccountServiceDemoImplTest { - public static final UUID ACCOUNT_WITH_EFILING_ROLE = UUID.fromString("77da92db-0791-491e-8c58-1a969e67d2fa"); - public static final UUID ACCOUNT_WITHOUT_EFILING_ROLE = UUID.fromString("77da92db-0791-491e-8c58-1a969e67d2fb"); + public static final String ACCOUNT_ID = "77da92db-0791-491e-8c58-1a969e67d2fa"; + public static final String ACCOUNT_ID_NOT_EXIST = "17da92db-0791-491e-8c58-1a969e67d2fa"; + public static final String FIRST_NAME = "firstName"; - EfilingAccountServiceDemoImpl sut; + private EfilingAccountServiceDemoImpl sut; + + @Mock + private AccountDetailsCache accountDetailsCacheMock; @BeforeAll public void setup() { - sut = new EfilingAccountServiceDemoImpl(); - } - @Test - @DisplayName("OK: should return id with file role") - public void id1ShouldReturnAccountWithFileRole() { + MockitoAnnotations.openMocks(this); - AccountDetails actual = sut.getAccountDetails(ACCOUNT_WITH_EFILING_ROLE, ""); + AccountDetails accountDetails = AccountDetails.builder().accountId(BigDecimal.ONE).universalId(ACCOUNT_ID).create(); - Assertions.assertEquals(BigDecimal.TEN, actual.getAccountId()); - Assertions.assertEquals(BigDecimal.TEN, actual.getClientId()); - Assertions.assertEquals(true, actual.isFileRolePresent()); + Mockito.when(accountDetailsCacheMock.get(Mockito.eq(ACCOUNT_ID))).thenReturn(accountDetails); + Mockito.when(accountDetailsCacheMock.put(ArgumentMatchers.argThat(x -> x.getUniversalId() == ACCOUNT_ID))).thenReturn(accountDetails); + sut = new EfilingAccountServiceDemoImpl(accountDetailsCacheMock); } @Test - @DisplayName("OK: should return id without file role") - public void id2ShouldReturnAccountWithoutFileRole() { + @DisplayName("OK: with empty cache should return null") + @Order(1) + public void withEmptyCacheShouldReturnNull() { + AccountDetails actual = sut.getAccountDetails(ACCOUNT_ID_NOT_EXIST); + Assertions.assertNull(actual); + } - AccountDetails actual = sut.getAccountDetails(ACCOUNT_WITHOUT_EFILING_ROLE, ""); + @Test + @DisplayName("OK: should create an account") + @Order(2) + public void shouldCreateAnAccount() { - Assertions.assertEquals(BigDecimal.TEN, actual.getAccountId()); - Assertions.assertEquals(BigDecimal.TEN, actual.getClientId()); - Assertions.assertEquals(false, actual.isFileRolePresent()); + AccountDetails actual = sut.createAccount(CreateAccountRequest.builder().universalId(ACCOUNT_ID).firstName(FIRST_NAME).create()); + Assertions.assertEquals(ACCOUNT_ID, actual.getUniversalId()); + } + + @Test + @DisplayName("OK: should return order number as string") + @Order(3) + public void shouldReturnOrderNumber() { + String actual = sut.getOrderNumber(); + Assertions.assertEquals("1234", actual); + } + + @Test + @DisplayName("OK: should put account in cache") + @Order(3) + public void shouldPutAAccountinCache() { + Assertions.assertDoesNotThrow(() -> sut.updateClient(AccountDetails.builder().clientId(BigDecimal.TEN).create())); } } diff --git a/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingCourtServiceDemoImplTest.java b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingCourtServiceDemoImplTest.java new file mode 100644 index 0000000000..2e6a187a2e --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingCourtServiceDemoImplTest.java @@ -0,0 +1,29 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.model.CourtDetails; +import org.junit.jupiter.api.*; + +import java.math.BigDecimal; +import java.util.Optional; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class EfilingCourtServiceDemoImplTest { + private static final String SOMEVALUE = "SOMEVALUE"; + EfilingCourtServiceDemoImpl sut; + + @BeforeAll + public void setup() { + sut = new EfilingCourtServiceDemoImpl(); + } + + @Test + @DisplayName("OK: with empty cache should return a value") + public void withEmptyCacheShouldReturnAValue() { + + Optional actual = sut.getCourtDescription(SOMEVALUE, SOMEVALUE, SOMEVALUE); + Assertions.assertEquals("Imma Court", actual.get().getCourtDescription()); + Assertions.assertEquals("Imma Level", actual.get().getLevelDescription()); + Assertions.assertEquals("Imma Class", actual.get().getClassDescription()); + Assertions.assertEquals(BigDecimal.TEN, actual.get().getCourtId()); + } +} diff --git a/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingDocumentServiceDemoImplTest.java b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingDocumentServiceDemoImplTest.java new file mode 100644 index 0000000000..b37e722597 --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingDocumentServiceDemoImplTest.java @@ -0,0 +1,50 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.model.DocumentTypeDetails; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.mockito.Mockito; + +import java.math.BigDecimal; +import java.util.List; + + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Demo Efiling Stats Client Test Suite") +public class EfilingDocumentServiceDemoImplTest { + @DisplayName("CASE 1: Testing Demo getDocumentDetails") + @Test + public void testDemoLookupServiceTest() { + + EfilingDocumentServiceDemoImpl service = new EfilingDocumentServiceDemoImpl(); + + String serviceId = "TestServiceId"; + DocumentTypeDetails actual = service.getDocumentTypeDetails(serviceId, "", ""); + + Assertions.assertEquals("This is a doc", actual.getDescription()); + Assertions.assertEquals(BigDecimal.valueOf(7), actual.getStatutoryFeeAmount()); + Assertions.assertTrue(actual.isOrderDocument()); + Assertions.assertTrue(actual.isRushRequired()); + Assertions.assertFalse(actual.isAutoProcessing()); + + } + @DisplayName("CASE 2: Testing Demo getDocumentTypes") + @Test + public void testDemoDocumentServiceTest() { + + EfilingDocumentServiceDemoImpl service = new EfilingDocumentServiceDemoImpl(); + + List actual = service.getDocumentTypes("", ""); + + Assertions.assertEquals(3, actual.size()); + Assertions.assertEquals("Description1", actual.get(0).getDescription()); + Assertions.assertEquals("AFF", actual.get(0).getType()); + Assertions.assertEquals(BigDecimal.valueOf(7), actual.get(0).getStatutoryFeeAmount()); + Assertions.assertTrue(actual.get(0).isOrderDocument()); + Assertions.assertTrue(actual.get(0).isRushRequired()); + Assertions.assertFalse(actual.get(0).isAutoProcessing()); + + } +} diff --git a/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingEfilingCourtLocationServiceDemoImplTest.java b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingEfilingCourtLocationServiceDemoImplTest.java new file mode 100644 index 0000000000..61e4e7123f --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingEfilingCourtLocationServiceDemoImplTest.java @@ -0,0 +1,50 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.model.InternalCourtLocation; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +import java.math.BigDecimal; +import java.util.List; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class EfilingEfilingCourtLocationServiceDemoImplTest { + @DisplayName("Test list returned") + @Test + public void testDemoCourtLookupServiceTest() { + + EfilingCourtLocationServiceDemoImpl service = new EfilingCourtLocationServiceDemoImpl(); + + List actual = service.getCourtLocations("TYPE"); + + Assertions.assertEquals(2, actual.size()); + Assertions.assertEquals(BigDecimal.valueOf(10264), actual.get(0).getId()); + Assertions.assertEquals("5871", actual.get(0).getIdentifierCode()); + Assertions.assertEquals("Campbell River", actual.get(0).getName()); + Assertions.assertEquals("OMH", actual.get(0).getCode()); + Assertions.assertEquals(true, actual.get(0).getIsSupremeCourt()); + Assertions.assertEquals("500 - 13th Avenue", actual.get(0).getAddress().getAddressLine1()); + Assertions.assertNull(actual.get(0).getAddress().getAddressLine2()); + Assertions.assertNull(actual.get(0).getAddress().getAddressLine3()); + Assertions.assertEquals("V9W 6P1", actual.get(0).getAddress().getPostalCode()); + Assertions.assertEquals("Campbell River", actual.get(0).getAddress().getCityName()); + Assertions.assertEquals("British Columbia", actual.get(0).getAddress().getProvinceName()); + Assertions.assertEquals("Canada", actual.get(0).getAddress().getCountryName()); + + Assertions.assertEquals(BigDecimal.valueOf(9393), actual.get(1).getId()); + Assertions.assertEquals("3561", actual.get(1).getIdentifierCode()); + Assertions.assertEquals("Chilliwack", actual.get(1).getName()); + Assertions.assertEquals("ABB", actual.get(1).getCode()); + Assertions.assertEquals(true, actual.get(1).getIsSupremeCourt()); + Assertions.assertEquals("46085 Yale Road", actual.get(1).getAddress().getAddressLine1()); + Assertions.assertEquals(" ", actual.get(1).getAddress().getAddressLine2()); + Assertions.assertEquals(" ", actual.get(1).getAddress().getAddressLine3()); + Assertions.assertEquals("V2P 2L8", actual.get(1).getAddress().getPostalCode()); + Assertions.assertEquals("Chilliwack", actual.get(1).getAddress().getCityName()); + Assertions.assertEquals("British Columbia", actual.get(1).getAddress().getProvinceName()); + Assertions.assertEquals("Canada", actual.get(1).getAddress().getCountryName()); + + } +} diff --git a/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingLookupServiceDemoImplTest.java b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingLookupServiceDemoImplTest.java index 63dc27e888..4fabeba217 100644 --- a/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingLookupServiceDemoImplTest.java +++ b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingLookupServiceDemoImplTest.java @@ -1,13 +1,15 @@ package ca.bc.gov.open.jag.efiling.demo; import ca.bc.gov.open.jag.efilingcommons.model.ServiceFees; -import org.joda.time.DateTime; +import ca.bc.gov.open.jag.efilingcommons.model.SubmissionFeeRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.LookupItem; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import java.math.BigDecimal; +import java.util.List; @TestInstance(TestInstance.Lifecycle.PER_CLASS) @@ -20,18 +22,31 @@ public void testDemoLookupServiceTest() { EfilingLookupServiceDemoImpl service = new EfilingLookupServiceDemoImpl(); - String serviceId = "TestServiceId"; - ServiceFees actual = service.getServiceFee(serviceId); + ServiceFees actual = service.getServiceFee(SubmissionFeeRequest.builder().create()); - Assertions.assertEquals(BigDecimal.valueOf(7), actual.getFeeAmt()); - Assertions.assertEquals(DateTime.now().getDayOfMonth(), actual.getEffectiveDt().getDayOfMonth()); - Assertions.assertEquals(DateTime.now().getDayOfMonth(), actual.getEntDtm().getDayOfMonth()); - Assertions.assertEquals("entUserId", actual.getEntUserId()); - Assertions.assertEquals(DateTime.now().getDayOfMonth(), actual.getExpiryDt().getDayOfMonth()); + Assertions.assertEquals(BigDecimal.valueOf(7), actual.getFeeAmount()); Assertions.assertEquals("serviceTypeCd", actual.getServiceTypeCd()); - Assertions.assertEquals("updUserId", actual.getUpdUserId()); - Assertions.assertEquals(DateTime.now().getDayOfMonth(), actual.getUdpDtm().getDayOfMonth()); + } + + @DisplayName("CASE 2: Testing Demo getCountries") + @Test + public void testDemoLookupServiceCountriesTest() { + + EfilingLookupServiceDemoImpl service = new EfilingLookupServiceDemoImpl(); + + List actual = service.getCountries(); + + Assertions.assertEquals(3, actual.size()); + + Assertions.assertEquals("1", actual.get(0).getCode()); + Assertions.assertEquals("Canada", actual.get(0).getDescription()); + + Assertions.assertEquals("1", actual.get(1).getCode()); + Assertions.assertEquals("United States", actual.get(1).getDescription()); + + Assertions.assertEquals("34", actual.get(2).getCode()); + Assertions.assertEquals("Spain", actual.get(2).getDescription()); } diff --git a/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingReviewServiceDemoImplTest.java b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingReviewServiceDemoImplTest.java new file mode 100644 index 0000000000..01c55cb291 --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingReviewServiceDemoImplTest.java @@ -0,0 +1,425 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.model.RushDocumentRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.DeleteSubmissionDocumentRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.FilingPackageRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.ReportRequest; +import ca.bc.gov.open.jag.efilingcommons.submission.models.review.ReviewFilingPackage; +import org.joda.time.DateTime; +import org.junit.jupiter.api.*; + +import java.math.BigDecimal; +import java.text.MessageFormat; +import java.util.Optional; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class EfilingReviewServiceDemoImplTest { + public static final String DESCRIPTION = "DESCRIPTION"; + public static final String COMMENTS = MessageFormat.format("Lorem ipsum dolor sit amet, consectetur adipiscing elit, {1} sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.{0}{0}Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", System.lineSeparator(), ""); + EfilingReviewServiceDemoImpl sut; + + @BeforeAll + public void setup() { + sut = new EfilingReviewServiceDemoImpl(); + } + + @Test + @DisplayName("OK: with correct id return payload") + public void requestPackageOneShouldReturnData() { + Optional result = sut.findStatusByPackage(new FilingPackageRequest(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE, "")); + + Assertions.assertTrue(result.isPresent()); + //Package + Assertions.assertEquals("Han", result.get().getFirstName()); + Assertions.assertEquals("Solo", result.get().getLastName()); + Assertions.assertFalse(result.get().getHasChecklist()); + Assertions.assertTrue(result.get().getHasRegistryNotice()); + Assertions.assertEquals("1", result.get().getPackageNo()); + Assertions.assertEquals(DateTime.parse("2020-5-5"), result.get().getSubmittedDate()); + Assertions.assertEquals(COMMENTS, result.get().getFilingCommentsTxt()); + + //Court + Assertions.assertEquals("F", result.get().getCourt().getCourtClass()); + Assertions.assertEquals("P", result.get().getCourt().getLevel()); + Assertions.assertEquals("KEL", result.get().getCourt().getLocationCd()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getCourt().getLocationId()); + Assertions.assertEquals("Kelowna Law Courts", result.get().getCourt().getLocationName()); + Assertions.assertEquals("DIVISION", result.get().getCourt().getDivision()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getLocationDescription()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getParticipatingClass()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getLocationDescription()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getLevelDescription()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getClassDescription()); + Assertions.assertEquals("123", result.get().getCourt().getFileNumber()); + Assertions.assertFalse(result.get().getCourt().getExistingFileYN()); + + //Documents + Assertions.assertEquals(7, result.get().getDocuments().size()); + Assertions.assertEquals(DateTime.parse("2020-5-5"), result.get().getDocuments().get(0).getDateFiled()); + Assertions.assertEquals("1", result.get().getDocuments().get(0).getDocumentId()); + Assertions.assertEquals("Affidavit", result.get().getDocuments().get(0).getDocumentType()); + Assertions.assertEquals("AFF", result.get().getDocuments().get(0).getDocumentTypeCd()); + Assertions.assertEquals("CMPL", result.get().getDocuments().get(0).getDocumentUploadStatusCd()); + Assertions.assertEquals("test-document.pdf", result.get().getDocuments().get(0).getFileName()); + Assertions.assertFalse(result.get().getDocuments().get(0).getInitiatingDoc()); + Assertions.assertEquals("N", result.get().getDocuments().get(0).getLargeFileYn()); + Assertions.assertEquals("1", result.get().getDocuments().get(0).getPackageId()); + Assertions.assertEquals("1", result.get().getDocuments().get(0).getPackageSeqNo()); + Assertions.assertFalse(result.get().getDocuments().get(0).getPaymentProcessed()); + Assertions.assertEquals("Submitted", result.get().getDocuments().get(0).getStatus()); + Assertions.assertEquals("SUB", result.get().getDocuments().get(0).getStatusCode()); + Assertions.assertEquals(DateTime.parse("2020-12-17"), result.get().getDocuments().get(0).getStatusDate()); + Assertions.assertFalse(result.get().getDocuments().get(0).getTrialDivision()); + Assertions.assertFalse(result.get().getDocuments().get(0).getXmlDoc()); + + //Parties + Assertions.assertEquals(2, result.get().getParties().size()); + Assertions.assertEquals("Bob", result.get().getParties().get(0).getFirstName()); + Assertions.assertEquals("Q", result.get().getParties().get(0).getMiddleName()); + Assertions.assertEquals("Ross", result.get().getParties().get(0).getLastName()); + Assertions.assertEquals("APP", result.get().getParties().get(0).getRoleTypeCd()); + Assertions.assertEquals("Applicant", result.get().getParties().get(0).getRoleTypeDesc()); + Assertions.assertEquals("Individual", result.get().getParties().get(0).getPartyTypeDesc()); + + //Organization + Assertions.assertEquals(2, result.get().getOrganizations().size()); + Assertions.assertEquals("The Organization Org.", result.get().getOrganizations().get(0).getName()); + Assertions.assertEquals("APP", result.get().getOrganizations().get(0).getRoleTypeCd()); + Assertions.assertEquals("Applicant", result.get().getOrganizations().get(0).getRoleTypeDesc()); + Assertions.assertEquals("Organization", result.get().getOrganizations().get(0).getPartyTypeDesc()); + + //Payments + Assertions.assertEquals(3, result.get().getPayments().size()); + Assertions.assertFalse(result.get().getPayments().get(0).getFeeExmpt()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getPayments().get(0).getPaymentCategory()); + Assertions.assertEquals(new BigDecimal(7), result.get().getPayments().get(0).getProcessedAmt()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getPayments().get(0).getServiceId()); + Assertions.assertEquals(new BigDecimal(7), result.get().getPayments().get(0).getSubmittedAmt()); + Assertions.assertEquals(DateTime.parse("2020-12-17"), result.get().getPayments().get(0).getTransactionDtm()); + + Assertions.assertTrue(result.get().getPayments().get(1).getFeeExmpt()); + Assertions.assertEquals(new BigDecimal(3), result.get().getPayments().get(1).getPaymentCategory()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getPayments().get(1).getSubmittedAmt()); + Assertions.assertEquals("Affidavit", result.get().getPayments().get(1).getTransactionDesc()); + + //Rush + Assertions.assertEquals("hello@hello.com", result.get().getRushOrder().getContactEmailTxt()); + Assertions.assertEquals("Bob", result.get().getRushOrder().getContactFirstGivenNm()); + Assertions.assertEquals("Ross", result.get().getRushOrder().getContactSurnameNm()); + Assertions.assertEquals("Paint It", result.get().getRushOrder().getContactOrganizationNm()); + Assertions.assertEquals("1231231234", result.get().getRushOrder().getContactPhoneNo()); + Assertions.assertEquals("Processing", result.get().getRushOrder().getCurrentStatusDsc()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getCtryId()); + Assertions.assertEquals("Canada", result.get().getRushOrder().getCountryDsc()); + Assertions.assertNotNull(result.get().getRushOrder().getCourtOrderDt()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getPackageId()); + Assertions.assertEquals(DateTime.parse("2020-12-17"), result.get().getRushOrder().getCourtOrderDt()); + Assertions.assertEquals("Registry notice reason text", result.get().getRushOrder().getProcessingCommentTxt()); + Assertions.assertEquals("This is a reason. This is a reason. This is a reason. This is a reason.", result.get().getRushOrder().getRushFilingReasonTxt()); + + //Rush Documents + Assertions.assertEquals(2, result.get().getRushOrder().getSupportDocs().size()); + + Assertions.assertEquals("Test.pdf", result.get().getRushOrder().getSupportDocs().get(0).getClientFileNm()); + Assertions.assertNotNull(result.get().getRushOrder().getSupportDocs().get(0).getEntDtm()); + Assertions.assertEquals("1", result.get().getRushOrder().getSupportDocs().get(0).getEntUserId()); + Assertions.assertEquals("www.google.com", result.get().getRushOrder().getSupportDocs().get(0).getFileServer()); + Assertions.assertEquals("9b35f5d6-50e9-4cd5-9d46-8ce1f9e484c8", result.get().getRushOrder().getSupportDocs().get(0).getObjectGuid()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getSupportDocs().get(0).getProcessItemSeqNo()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getSupportDocs().get(0).getProcessRequestId()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getSupportDocs().get(0).getProcessSupportDocSeqNo()); + Assertions.assertEquals("Test.pdf", result.get().getRushOrder().getSupportDocs().get(0).getTempFileName()); + Assertions.assertEquals("1", result.get().getRushOrder().getSupportDocs().get(0).getUpdUserId()); + Assertions.assertNotNull(result.get().getRushOrder().getSupportDocs().get(0)); + + Assertions.assertEquals("Test1.pdf", result.get().getRushOrder().getSupportDocs().get(1).getClientFileNm()); + Assertions.assertNotNull(result.get().getRushOrder().getSupportDocs().get(1).getEntDtm()); + Assertions.assertEquals("1", result.get().getRushOrder().getSupportDocs().get(1).getEntUserId()); + Assertions.assertEquals("www.google.com", result.get().getRushOrder().getSupportDocs().get(1).getFileServer()); + Assertions.assertEquals("9b35f5d6-50e9-4cd5-9d46-8ce1f9e484c8", result.get().getRushOrder().getSupportDocs().get(1).getObjectGuid()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getSupportDocs().get(1).getProcessItemSeqNo()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getSupportDocs().get(1).getProcessRequestId()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getSupportDocs().get(1).getProcessSupportDocSeqNo()); + Assertions.assertEquals("Test.pdf", result.get().getRushOrder().getSupportDocs().get(1).getTempFileName()); + Assertions.assertEquals("1", result.get().getRushOrder().getSupportDocs().get(1).getUpdUserId()); + Assertions.assertNotNull(result.get().getRushOrder().getSupportDocs().get(1).getUpdDtm()); + + Assertions.assertEquals("http://localhost:8080/wherearemypackage", result.get().getPackageLinks().getPackageHistoryUrl()); + + } + + @Test + @DisplayName("OK: with correct id return payload") + public void requestPackageTwoShouldReturnData() { + Optional result = sut.findStatusByPackage(new FilingPackageRequest(BigDecimal.ONE, BigDecimal.ONE, new BigDecimal(2), "")); + + Assertions.assertTrue(result.isPresent()); + //Package + Assertions.assertEquals("Han", result.get().getFirstName()); + Assertions.assertEquals("Solo", result.get().getLastName()); + Assertions.assertFalse(result.get().getHasChecklist()); + Assertions.assertFalse(result.get().getHasRegistryNotice()); + Assertions.assertEquals("2", result.get().getPackageNo()); + Assertions.assertEquals(DateTime.parse("2020-5-5"), result.get().getSubmittedDate()); + Assertions.assertEquals(COMMENTS, result.get().getFilingCommentsTxt()); + + //Court + Assertions.assertEquals("F", result.get().getCourt().getCourtClass()); + Assertions.assertEquals("P", result.get().getCourt().getLevel()); + Assertions.assertEquals("KEL", result.get().getCourt().getLocationCd()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getCourt().getLocationId()); + Assertions.assertEquals("Kelowna Law Courts", result.get().getCourt().getLocationName()); + Assertions.assertEquals("DIVISION", result.get().getCourt().getDivision()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getLocationDescription()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getParticipatingClass()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getLocationDescription()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getLevelDescription()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getClassDescription()); + Assertions.assertEquals("123", result.get().getCourt().getFileNumber()); + Assertions.assertFalse(result.get().getCourt().getExistingFileYN()); + + Assertions.assertEquals(7, result.get().getDocuments().size()); + Assertions.assertEquals(DateTime.parse("2020-5-5"), result.get().getDocuments().get(0).getDateFiled()); + Assertions.assertEquals("1", result.get().getDocuments().get(0).getDocumentId()); + Assertions.assertEquals("Affidavit", result.get().getDocuments().get(0).getDocumentType()); + Assertions.assertEquals("AFF", result.get().getDocuments().get(0).getDocumentTypeCd()); + Assertions.assertEquals("CMPL", result.get().getDocuments().get(0).getDocumentUploadStatusCd()); + Assertions.assertEquals("test-document.pdf", result.get().getDocuments().get(0).getFileName()); + Assertions.assertFalse(result.get().getDocuments().get(0).getInitiatingDoc()); + Assertions.assertEquals("N", result.get().getDocuments().get(0).getLargeFileYn()); + Assertions.assertEquals("1", result.get().getDocuments().get(0).getPackageId()); + Assertions.assertEquals("1", result.get().getDocuments().get(0).getPackageSeqNo()); + Assertions.assertFalse(result.get().getDocuments().get(0).getPaymentProcessed()); + Assertions.assertEquals("Submitted", result.get().getDocuments().get(0).getStatus()); + Assertions.assertEquals("SUB", result.get().getDocuments().get(0).getStatusCode()); + Assertions.assertEquals(DateTime.parse("2020-12-17"), result.get().getDocuments().get(0).getStatusDate()); + Assertions.assertFalse(result.get().getDocuments().get(0).getTrialDivision()); + Assertions.assertFalse(result.get().getDocuments().get(0).getXmlDoc()); + + Assertions.assertEquals(2, result.get().getParties().size()); + Assertions.assertEquals("Bob", result.get().getParties().get(0).getFirstName()); + Assertions.assertEquals("Q", result.get().getParties().get(0).getMiddleName()); + Assertions.assertEquals("Ross", result.get().getParties().get(0).getLastName()); + Assertions.assertEquals("APP", result.get().getParties().get(0).getRoleTypeCd()); + Assertions.assertEquals("Applicant", result.get().getParties().get(0).getRoleTypeDesc()); + Assertions.assertEquals("Individual", result.get().getParties().get(0).getPartyTypeDesc()); + + Assertions.assertEquals(2, result.get().getOrganizations().size()); + Assertions.assertEquals("The Organization Org.", result.get().getOrganizations().get(0).getName()); + Assertions.assertEquals("APP", result.get().getOrganizations().get(0).getRoleTypeCd()); + Assertions.assertEquals("Applicant", result.get().getOrganizations().get(0).getRoleTypeDesc()); + Assertions.assertEquals("Organization", result.get().getOrganizations().get(0).getPartyTypeDesc()); + + Assertions.assertEquals(3, result.get().getPayments().size()); + Assertions.assertFalse(result.get().getPayments().get(0).getFeeExmpt()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getPayments().get(0).getPaymentCategory()); + Assertions.assertEquals(new BigDecimal(7), result.get().getPayments().get(0).getProcessedAmt()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getPayments().get(0).getServiceId()); + Assertions.assertEquals(new BigDecimal(7), result.get().getPayments().get(0).getSubmittedAmt()); + Assertions.assertEquals(DateTime.parse("2020-12-17"), result.get().getPayments().get(0).getTransactionDtm()); + + Assertions.assertTrue(result.get().getPayments().get(1).getFeeExmpt()); + Assertions.assertEquals(new BigDecimal(3), result.get().getPayments().get(1).getPaymentCategory()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getPayments().get(1).getSubmittedAmt()); + Assertions.assertEquals("Affidavit", result.get().getPayments().get(1).getTransactionDesc()); + + + Assertions.assertEquals(new BigDecimal(1), result.get().getRushOrder().getPackageId()); + Assertions.assertNotNull(result.get().getRushOrder().getCourtOrderDt()); + Assertions.assertEquals("This is a reason. This is a reason. This is a reason. This is a reason.", result.get().getRushOrder().getRushFilingReasonTxt()); + Assertions.assertEquals(2, result.get().getRushOrder().getSupportDocs().size()); + + Assertions.assertEquals("Test.pdf", result.get().getRushOrder().getSupportDocs().get(0).getClientFileNm()); + Assertions.assertNotNull(result.get().getRushOrder().getSupportDocs().get(0).getEntDtm()); + Assertions.assertEquals("1", result.get().getRushOrder().getSupportDocs().get(0).getEntUserId()); + Assertions.assertEquals("www.google.com",result.get().getRushOrder().getSupportDocs().get(0).getFileServer()); + Assertions.assertEquals("9b35f5d6-50e9-4cd5-9d46-8ce1f9e484c8", result.get().getRushOrder().getSupportDocs().get(0).getObjectGuid()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getSupportDocs().get(0).getProcessItemSeqNo()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getSupportDocs().get(0).getProcessRequestId()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getSupportDocs().get(0).getProcessSupportDocSeqNo()); + Assertions.assertEquals("Test.pdf", result.get().getRushOrder().getSupportDocs().get(0).getTempFileName()); + Assertions.assertEquals("1", result.get().getRushOrder().getSupportDocs().get(0).getUpdUserId()); + Assertions.assertNotNull(result.get().getRushOrder().getSupportDocs().get(0).getUpdDtm()); + + Assertions.assertEquals("Test1.pdf", result.get().getRushOrder().getSupportDocs().get(1).getClientFileNm()); + Assertions.assertNotNull(result.get().getRushOrder().getSupportDocs().get(1).getEntDtm()); + Assertions.assertEquals("1", result.get().getRushOrder().getSupportDocs().get(1).getEntUserId()); + Assertions.assertEquals("www.google.com",result.get().getRushOrder().getSupportDocs().get(1).getFileServer()); + Assertions.assertEquals("9b35f5d6-50e9-4cd5-9d46-8ce1f9e484c8", result.get().getRushOrder().getSupportDocs().get(1).getObjectGuid()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getSupportDocs().get(1).getProcessItemSeqNo()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getSupportDocs().get(1).getProcessRequestId()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getRushOrder().getSupportDocs().get(1).getProcessSupportDocSeqNo()); + Assertions.assertEquals("Test.pdf", result.get().getRushOrder().getSupportDocs().get(1).getTempFileName()); + Assertions.assertEquals("1", result.get().getRushOrder().getSupportDocs().get(1).getUpdUserId()); + Assertions.assertNotNull(result.get().getRushOrder().getSupportDocs().get(1).getUpdDtm()); + + Assertions.assertEquals("http://localhost:8080/wherearemypackage", result.get().getPackageLinks().getPackageHistoryUrl()); + + } + + @Test + @DisplayName("OK: with correct id return payload") + public void requestPackageThreeShouldReturnData() { + Optional result = sut.findStatusByPackage(new FilingPackageRequest(BigDecimal.ONE, BigDecimal.ONE, new BigDecimal(3), "")); + + Assertions.assertTrue(result.isPresent()); + //Package + Assertions.assertEquals("Han", result.get().getFirstName()); + Assertions.assertEquals("Solo", result.get().getLastName()); + Assertions.assertFalse(result.get().getHasChecklist()); + Assertions.assertFalse(result.get().getHasRegistryNotice()); + Assertions.assertEquals("3", result.get().getPackageNo()); + Assertions.assertEquals(DateTime.parse("2020-5-5"), result.get().getSubmittedDate()); + Assertions.assertEquals(COMMENTS, result.get().getFilingCommentsTxt()); + + //Court + Assertions.assertEquals("F", result.get().getCourt().getCourtClass()); + Assertions.assertEquals("P", result.get().getCourt().getLevel()); + Assertions.assertEquals("KEL", result.get().getCourt().getLocationCd()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getCourt().getLocationId()); + Assertions.assertEquals("Kelowna Law Courts", result.get().getCourt().getLocationName()); + Assertions.assertEquals("DIVISION", result.get().getCourt().getDivision()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getLocationDescription()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getParticipatingClass()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getLocationDescription()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getLevelDescription()); + Assertions.assertEquals(DESCRIPTION, result.get().getCourt().getClassDescription()); + Assertions.assertEquals("123", result.get().getCourt().getFileNumber()); + Assertions.assertFalse(result.get().getCourt().getExistingFileYN()); + + Assertions.assertEquals(7, result.get().getDocuments().size()); + Assertions.assertEquals(DateTime.parse("2020-5-5"), result.get().getDocuments().get(0).getDateFiled()); + Assertions.assertEquals("1", result.get().getDocuments().get(0).getDocumentId()); + Assertions.assertEquals("Affidavit", result.get().getDocuments().get(0).getDocumentType()); + Assertions.assertEquals("AFF", result.get().getDocuments().get(0).getDocumentTypeCd()); + Assertions.assertEquals("CMPL", result.get().getDocuments().get(0).getDocumentUploadStatusCd()); + Assertions.assertEquals("test-document.pdf", result.get().getDocuments().get(0).getFileName()); + Assertions.assertFalse(result.get().getDocuments().get(0).getInitiatingDoc()); + Assertions.assertEquals("N", result.get().getDocuments().get(0).getLargeFileYn()); + Assertions.assertEquals("1", result.get().getDocuments().get(0).getPackageId()); + Assertions.assertEquals("1", result.get().getDocuments().get(0).getPackageSeqNo()); + Assertions.assertFalse(result.get().getDocuments().get(0).getPaymentProcessed()); + Assertions.assertEquals("Submitted", result.get().getDocuments().get(0).getStatus()); + Assertions.assertEquals("SUB", result.get().getDocuments().get(0).getStatusCode()); + Assertions.assertEquals(DateTime.parse("2020-12-17"), result.get().getDocuments().get(0).getStatusDate()); + Assertions.assertFalse(result.get().getDocuments().get(0).getTrialDivision()); + Assertions.assertFalse(result.get().getDocuments().get(0).getXmlDoc()); + + Assertions.assertEquals(2, result.get().getParties().size()); + Assertions.assertEquals("Bob", result.get().getParties().get(0).getFirstName()); + Assertions.assertEquals("Q", result.get().getParties().get(0).getMiddleName()); + Assertions.assertEquals("Ross", result.get().getParties().get(0).getLastName()); + Assertions.assertEquals("APP", result.get().getParties().get(0).getRoleTypeCd()); + Assertions.assertEquals("Applicant", result.get().getParties().get(0).getRoleTypeDesc()); + Assertions.assertEquals("Individual", result.get().getParties().get(0).getPartyTypeDesc()); + + Assertions.assertEquals(2, result.get().getOrganizations().size()); + Assertions.assertEquals("The Organization Org.", result.get().getOrganizations().get(0).getName()); + Assertions.assertEquals("APP", result.get().getOrganizations().get(0).getRoleTypeCd()); + Assertions.assertEquals("Applicant", result.get().getOrganizations().get(0).getRoleTypeDesc()); + Assertions.assertEquals("Organization", result.get().getOrganizations().get(0).getPartyTypeDesc()); + + Assertions.assertEquals(3, result.get().getPayments().size()); + Assertions.assertFalse(result.get().getPayments().get(0).getFeeExmpt()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getPayments().get(0).getPaymentCategory()); + Assertions.assertEquals(new BigDecimal(7), result.get().getPayments().get(0).getProcessedAmt()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getPayments().get(0).getServiceId()); + Assertions.assertEquals(new BigDecimal(7), result.get().getPayments().get(0).getSubmittedAmt()); + Assertions.assertEquals(DateTime.parse("2020-12-17"), result.get().getPayments().get(0).getTransactionDtm()); + + Assertions.assertTrue(result.get().getPayments().get(1).getFeeExmpt()); + Assertions.assertEquals(new BigDecimal(3), result.get().getPayments().get(1).getPaymentCategory()); + Assertions.assertEquals(BigDecimal.ONE, result.get().getPayments().get(1).getSubmittedAmt()); + Assertions.assertEquals("Affidavit", result.get().getPayments().get(1).getTransactionDesc()); + + Assertions.assertEquals("http://localhost:8080/wherearemypackage", result.get().getPackageLinks().getPackageHistoryUrl()); + + } + + @Test + @DisplayName("No result: with not 1 return empty") + public void withEmptyCacheShouldReturnEmpty() { + + Assertions.assertFalse(sut.findStatusByPackage(new FilingPackageRequest(BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.ZERO, "")).isPresent()); + + } + + @Test + @DisplayName("OK: demo returns a 3 element array") + public void withRequestReturnThreeElementArray() { + + Assertions.assertEquals(3, sut.findStatusByClient(new FilingPackageRequest(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE, null)).size()); + + } + + @Test + @DisplayName("OK: demo returns a 2 element array") + public void withFLARequestReturnTwoElementArray() { + + Assertions.assertEquals(2, sut.findStatusByClient(new FilingPackageRequest(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE, Keys.PARENT_APPLICATION_FLA)).size()); + + } + + @Test + @DisplayName("OK: demo returns a 1 element array") + public void withCOARequestReturnOneElementArray() { + + Assertions.assertEquals(1, sut.findStatusByClient(new FilingPackageRequest(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE, Keys.PARENT_APPLICATION_COA)).size()); + + } + + @Test + @DisplayName("OK: demo returns a 1 element array") + public void withOTHERRequestReturnOneElementArray() { + + Assertions.assertEquals(1, sut.findStatusByClient(new FilingPackageRequest(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE, Keys.PARENT_APPLICATION_OTHER)).size()); + + } + + @Test + @DisplayName("OK: demo returns a empty array") + public void withUNKNOWNRequestReturnEmptyArray() { + + Assertions.assertEquals(0, sut.findStatusByClient(new FilingPackageRequest(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE, "UNKNOWN")).size()); + + } + + @Test + @DisplayName("OK: demo returns a document byte array") + public void withRequestReturnByteArray() { + + Optional result = sut.getReport(ReportRequest.builder().create()); + + Assertions.assertTrue(result.isPresent()); + + } + + @Test + @DisplayName("OK: demo returns a document byte array") + public void withDocumentRequestReturnByteArray() { + + Optional result = sut.getSubmittedDocument(BigDecimal.ONE); + + Assertions.assertTrue(result.isPresent()); + + } + + @Test + @DisplayName("OK: demo returns a document byte array") + public void withRushDocumentRequestReturnByteArray() { + + Optional result = sut.getRushDocument(RushDocumentRequest.builder().create()); + + Assertions.assertTrue(result.isPresent()); + + } + + @Test + @DisplayName("OK: demo returns a boolean") + public void withDocumentRequestBoolean() { + + Assertions.assertDoesNotThrow(() -> sut.deleteSubmittedDocument(new DeleteSubmissionDocumentRequest(BigDecimal.ONE, BigDecimal.ONE, "","TEST"))); + + } + +} diff --git a/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingSubmissionServiceDemoImplTest.java b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingSubmissionServiceDemoImplTest.java new file mode 100644 index 0000000000..7a0bada4bd --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/EfilingSubmissionServiceDemoImplTest.java @@ -0,0 +1,26 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.model.SubmitPackageResponse; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +import java.math.BigDecimal; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@DisplayName("Demo Efiling Submission Client Test Suite") +public class EfilingSubmissionServiceDemoImplTest { + @DisplayName("CASE 1: Testing Demo submitFilingPackage") + @Test + public void testDemoLookupFilingPackageServiceTest() { + + EfilingSubmissionServiceDemoImpl service = new EfilingSubmissionServiceDemoImpl(); + + SubmitPackageResponse actual = service.submitFilingPackage(null, null, null); + + Assertions.assertEquals(BigDecimal.ONE, actual.getTransactionId()); + Assertions.assertEquals("http://demo", actual.getPackageLink()); + + } +} diff --git a/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/SeedAccountTest.java b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/SeedAccountTest.java new file mode 100644 index 0000000000..24771017f7 --- /dev/null +++ b/src/backend/libs/efiling-demo-starter/src/test/java/ca/bc/gov/open/jag/efiling/demo/SeedAccountTest.java @@ -0,0 +1,45 @@ +package ca.bc.gov.open.jag.efiling.demo; + +import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; +import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.springframework.context.event.ContextRefreshedEvent; + +import java.util.UUID; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class SeedAccountTest { + + private SeedAccount sut; + + @Mock + private EfilingAccountService efilingAccountServiceMock; + + @Mock + private ContextRefreshedEvent eventMock; + + @BeforeAll + public void setUp() { + MockitoAnnotations.initMocks(this); + Mockito.when(efilingAccountServiceMock.createAccount(Mockito.any())).thenReturn(AccountDetails.builder().universalId(UUID.randomUUID().toString()).create()); + sut = new SeedAccount(efilingAccountServiceMock); + } + + @Test + @DisplayName("OK: on application start should seed 2 accounts") + public void whenInitShouldCreate2Accounts() { + + sut.onApplicationEvent(eventMock); + + Mockito.verify(efilingAccountServiceMock, Mockito.times(2)) + .createAccount(Mockito.any()); + + } + +} diff --git a/src/backend/libs/efiling-lookup-client/src/main/java/ca/bc/gov/open/jag/efilinglookupclient/CSOLookupServiceImpl.java b/src/backend/libs/efiling-lookup-client/src/main/java/ca/bc/gov/open/jag/efilinglookupclient/CSOLookupServiceImpl.java deleted file mode 100644 index b7120b40de..0000000000 --- a/src/backend/libs/efiling-lookup-client/src/main/java/ca/bc/gov/open/jag/efilinglookupclient/CSOLookupServiceImpl.java +++ /dev/null @@ -1,72 +0,0 @@ -package ca.bc.gov.open.jag.efilinglookupclient; - - -import ca.bc.gov.ag.csows.lookups.LookupFacadeBean; -import ca.bc.gov.ag.csows.lookups.NestedEjbException_Exception; -import ca.bc.gov.ag.csows.lookups.ServiceFee; -import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingLookupServiceException; -import ca.bc.gov.open.jag.efilingcommons.model.ServiceFees; -import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; -import org.apache.commons.lang3.StringUtils; -import org.joda.time.DateTime; - -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; -import java.util.Date; -import java.util.GregorianCalendar; - -public class CSOLookupServiceImpl implements EfilingLookupService { - - private LookupFacadeBean lookupFacadeItf; - - public CSOLookupServiceImpl(LookupFacadeBean lookupFacadeItf) { - this.lookupFacadeItf = lookupFacadeItf; - } - - @Override - public ServiceFees getServiceFee(String serviceId) { - - // NOTE- "DCFL" is the only string that will work here until we get our service types setup - // TODO: throw exception when service fee is null - if (StringUtils.isEmpty(serviceId)) throw new IllegalArgumentException("service Id is required"); - - try { - ServiceFee fee = lookupFacadeItf.getServiceFee(serviceId, date2XMLGregorian(new Date())); - - return new ServiceFees( - toJoda(fee.getUpdDtm()), - fee.getFeeAmt(), - fee.getEntUserId(), - fee.getServiceTypeCd(), - toJoda(fee.getEffectiveDt()), - fee.getUpdUserId(), - toJoda(fee.getEntDtm()), - toJoda(fee.getExpiryDt())); - - } - catch(DatatypeConfigurationException | NestedEjbException_Exception e) { - throw new EfilingLookupServiceException("Exception while retrieving service fee", e.getCause()); - } - - } - - /** - * Helper function to convert a Date to an XMLGregorianCalendar date for sending to SOAP - * @param date - * @return XMLGregorianCalendar - * @throws DatatypeConfigurationException - */ - private XMLGregorianCalendar date2XMLGregorian(Date date) throws DatatypeConfigurationException { - - GregorianCalendar c = new GregorianCalendar(); - c.setTime(date); - XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); - return date2; - } - - private DateTime toJoda(XMLGregorianCalendar date) { - return new DateTime(date.toGregorianCalendar().getTime()); - } - -} diff --git a/src/backend/libs/efiling-lookup-client/src/main/java/ca/bc/gov/open/jag/efilinglookupclient/config/AutoConfiguration.java b/src/backend/libs/efiling-lookup-client/src/main/java/ca/bc/gov/open/jag/efilinglookupclient/config/AutoConfiguration.java deleted file mode 100644 index 2d6a505b38..0000000000 --- a/src/backend/libs/efiling-lookup-client/src/main/java/ca/bc/gov/open/jag/efilinglookupclient/config/AutoConfiguration.java +++ /dev/null @@ -1,49 +0,0 @@ -package ca.bc.gov.open.jag.efilinglookupclient.config; - -import ca.bc.gov.ag.csows.lookups.LookupFacadeBean; -import ca.bc.gov.open.jag.efilingcommons.model.Clients; -import ca.bc.gov.open.jag.efilingcommons.model.EfilingSoapClientProperties; -import ca.bc.gov.open.jag.efilingcommons.model.SoapProperties; -import ca.bc.gov.open.jag.efilinglookupclient.CSOLookupServiceImpl; -import ca.bc.gov.open.jag.efilingcommons.service.EfilingLookupService; -import org.apache.commons.lang3.StringUtils; -import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableConfigurationProperties(SoapProperties.class) -public class AutoConfiguration { - - private final SoapProperties soapProperties; - - public AutoConfiguration(SoapProperties soapProperties) { this.soapProperties = soapProperties; } - - @Bean - public LookupFacadeBean lookupFacadeItf() { - return getPort(Clients.LOOKUP, LookupFacadeBean.class); - } - - @Bean - @ConditionalOnMissingBean({EfilingLookupService.class}) - public EfilingLookupService efilingLookupService(LookupFacadeBean lookupFacadeItf) { - - return new CSOLookupServiceImpl(lookupFacadeItf); - } - - public T getPort(Clients clients, Class type) { - - JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean(); - jaxWsProxyFactoryBean.setServiceClass(type); - EfilingSoapClientProperties efilingSoapClientProperties = soapProperties.findByEnum(clients); - jaxWsProxyFactoryBean.setAddress(efilingSoapClientProperties.getUri()); - if(StringUtils.isNotBlank(efilingSoapClientProperties.getUserName())) - jaxWsProxyFactoryBean.setUsername(efilingSoapClientProperties.getUserName()); - if(StringUtils.isNotBlank(efilingSoapClientProperties.getPassword())) - jaxWsProxyFactoryBean.setPassword(efilingSoapClientProperties.getPassword()); - return type.cast(jaxWsProxyFactoryBean.create()); - } - -} diff --git a/src/backend/libs/efiling-lookup-client/src/main/resources/META-INF/spring.factories b/src/backend/libs/efiling-lookup-client/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 382f2bc9b6..0000000000 --- a/src/backend/libs/efiling-lookup-client/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - ca.bc.gov.open.jag.efilinglookupclient.config.AutoConfiguration \ No newline at end of file diff --git a/src/backend/libs/efiling-lookup-client/src/test/java/ca/bc/gov/open/jag/efilinglookupclient/CSOLookupServiceImplTest.java b/src/backend/libs/efiling-lookup-client/src/test/java/ca/bc/gov/open/jag/efilinglookupclient/CSOLookupServiceImplTest.java deleted file mode 100644 index 2940e2ba23..0000000000 --- a/src/backend/libs/efiling-lookup-client/src/test/java/ca/bc/gov/open/jag/efilinglookupclient/CSOLookupServiceImplTest.java +++ /dev/null @@ -1,115 +0,0 @@ -package ca.bc.gov.open.jag.efilinglookupclient; - -import ca.bc.gov.ag.csows.lookups.LookupFacadeBean; -import ca.bc.gov.ag.csows.lookups.NestedEjbException_Exception; -import ca.bc.gov.ag.csows.lookups.ServiceFee; -import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingLookupServiceException; -import ca.bc.gov.open.jag.efilingcommons.model.ServiceFees; -import org.joda.time.DateTime; -import org.junit.jupiter.api.*; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.XMLGregorianCalendar; -import java.math.BigDecimal; - -import static org.mockito.ArgumentMatchers.any; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@DisplayName("CSO Efiling Lookup Client Test Suite") -public class CSOLookupServiceImplTest { - - private static final String SERVICE_ID = "ServiceId"; - public static final String ENT_USER_ID = "entUserId"; - public static final String SERVICE_TYPE_CD = "serviceTypeCd"; - public static final String UPD_USER_ID = "updUserId"; - public static final String SERVICE_ID_EXCEPTION = "exception"; - - CSOLookupServiceImpl sut; - - @Mock - LookupFacadeBean lookupFacadeBeanMock; - - @Mock - ServiceFee serviceFeeMock; - @Mock - private XMLGregorianCalendar updDtmMock; - @Mock - private XMLGregorianCalendar expiryDtMock; - @Mock - private XMLGregorianCalendar entDtmMock; - @Mock - private XMLGregorianCalendar effectiveDtMock; - - - @BeforeEach - public void init() throws NestedEjbException_Exception, DatatypeConfigurationException { - - MockitoAnnotations.initMocks(this); - Mockito.when(serviceFeeMock.getFeeAmt()).thenReturn(BigDecimal.TEN); - Mockito.when(serviceFeeMock.getEntUserId()).thenReturn(ENT_USER_ID); - Mockito.when(serviceFeeMock.getServiceTypeCd()).thenReturn(SERVICE_TYPE_CD); - Mockito.when(serviceFeeMock.getUpdUserId()).thenReturn(UPD_USER_ID); - Mockito.when(updDtmMock.toGregorianCalendar()).thenReturn(new DateTime(2020, 7, 1, 10,10).toGregorianCalendar()); - Mockito.when(expiryDtMock.toGregorianCalendar()).thenReturn(new DateTime(2020, 7, 2, 10,10).toGregorianCalendar()); - Mockito.when(entDtmMock.toGregorianCalendar()).thenReturn(new DateTime(2020, 7, 3, 10,10).toGregorianCalendar()); - Mockito.when(effectiveDtMock.toGregorianCalendar()).thenReturn(new DateTime(2020, 7, 4, 10,10).toGregorianCalendar()); - Mockito - .when(serviceFeeMock.getEffectiveDt()) - .thenReturn(effectiveDtMock); - Mockito - .when(serviceFeeMock.getEntDtm()) - .thenReturn(entDtmMock); - Mockito - .when(serviceFeeMock.getExpiryDt()) - .thenReturn(expiryDtMock); - Mockito - .when(serviceFeeMock.getUpdDtm()) - .thenReturn(updDtmMock); - - Mockito - .when(lookupFacadeBeanMock.getServiceFee(Mockito.eq(SERVICE_ID), any())) - .thenReturn(serviceFeeMock); - - Mockito - .when(lookupFacadeBeanMock.getServiceFee(Mockito.eq(SERVICE_ID_EXCEPTION), Mockito.any())) - .thenThrow(new NestedEjbException_Exception("random")); - - sut = new CSOLookupServiceImpl(lookupFacadeBeanMock); - - } - - @DisplayName("Exception: with null service id should throw IllegalArgumentException") - @Test - public void testWithEmptyServiceId() { - - Assertions.assertThrows(IllegalArgumentException.class, () -> sut.getServiceFee("")); - } - - @DisplayName("OK: getServiceFee called with any non-empty serviceId") - @Test - public void testWithPopulatedServiceId() { - - ServiceFees actual = sut.getServiceFee(SERVICE_ID); - Assertions.assertEquals(BigDecimal.TEN, actual.getFeeAmt()); - Assertions.assertEquals(4, actual.getEffectiveDt().getDayOfMonth()); - Assertions.assertEquals(3, actual.getEntDtm().getDayOfMonth()); - Assertions.assertEquals(ENT_USER_ID, actual.getEntUserId()); - Assertions.assertEquals(2, actual.getExpiryDt().getDayOfMonth()); - Assertions.assertEquals(SERVICE_TYPE_CD, actual.getServiceTypeCd()); - Assertions.assertEquals(UPD_USER_ID, actual.getUpdUserId()); - Assertions.assertEquals(1, actual.getUdpDtm().getDayOfMonth()); - - } - - @DisplayName("Exception: with NestedEjbException_Exception should throw EfilingLookupServiceException") - @Test - public void whenNestedEjbException_ExceptionShouldThrowEfilingLookupServiceException() { - - Assertions.assertThrows(EfilingLookupServiceException.class, () -> sut.getServiceFee(SERVICE_ID_EXCEPTION)); - - } - -} diff --git a/src/backend/libs/efiling-lookup-client/src/test/java/ca/bc/gov/open/jag/efilinglookupclient/ServiceFeesTest.java b/src/backend/libs/efiling-lookup-client/src/test/java/ca/bc/gov/open/jag/efilinglookupclient/ServiceFeesTest.java deleted file mode 100644 index 2eb2a97217..0000000000 --- a/src/backend/libs/efiling-lookup-client/src/test/java/ca/bc/gov/open/jag/efilinglookupclient/ServiceFeesTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package ca.bc.gov.open.jag.efilinglookupclient; - -import ca.bc.gov.open.jag.efilingcommons.model.ServiceFees; -import org.joda.time.DateTime; -import org.junit.jupiter.api.*; - -import java.math.BigDecimal; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@DisplayName("Efiling ServiceFees Test") -public class ServiceFeesTest { - - private ServiceFees sut; - private static final DateTime dt = DateTime.now(); - private static final String serviceId = "ServiceID"; - private static final String entUserId = "EntUserID"; - private static final String updUserId = "UpdUserID"; - - @BeforeAll - public void setUp() { - sut = new ServiceFees(dt, BigDecimal.ZERO, entUserId, serviceId, dt, updUserId, dt, dt); - } - - @DisplayName("CASE 1: Testing Service Fees Constructor") - @Test - public void testServiceFeesConstructor() { - - Assertions.assertEquals(dt, sut.getEntDtm()); - Assertions.assertEquals(dt, sut.getEffectiveDt()); - Assertions.assertEquals(dt, sut.getExpiryDt()); - Assertions.assertEquals(dt, sut.getUdpDtm()); - Assertions.assertEquals(serviceId, sut.getServiceTypeCd()); - Assertions.assertEquals(entUserId, sut.getEntUserId()); - Assertions.assertEquals(updUserId, sut.getUpdUserId()); - Assertions.assertEquals(BigDecimal.ZERO, sut.getFeeAmt()); - } -} diff --git a/src/backend/libs/efiling-lookup-client/src/test/java/ca/bc/gov/open/jag/efilinglookupclient/config/AutoConfigurationTest.java b/src/backend/libs/efiling-lookup-client/src/test/java/ca/bc/gov/open/jag/efilinglookupclient/config/AutoConfigurationTest.java deleted file mode 100644 index 7cf06c8e2b..0000000000 --- a/src/backend/libs/efiling-lookup-client/src/test/java/ca/bc/gov/open/jag/efilinglookupclient/config/AutoConfigurationTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package ca.bc.gov.open.jag.efilinglookupclient.config; - -import ca.bc.gov.open.jag.efilingcommons.model.Clients; -import ca.bc.gov.open.jag.efilingcommons.model.EfilingSoapClientProperties; -import ca.bc.gov.open.jag.efilingcommons.model.SoapProperties; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import java.util.ArrayList; - -@DisplayName("AutoConfiguration Test") -public class AutoConfigurationTest { - private static final String URI = "URI"; - private static final String USERNAME = "USERNAME"; - private static final String PASSWORD = "PASSWORD"; - ApplicationContextRunner context = new ApplicationContextRunner() - .withUserConfiguration(AutoConfiguration.class); - - - private AutoConfiguration sut; - - @Test - @DisplayName("CASE1: Test that beans are created") - public void testBeansAreGenerated() { - ArrayList soapClientProperties = new ArrayList<>(); - - EfilingSoapClientProperties lookupProperties = new EfilingSoapClientProperties(); - lookupProperties.setClient(Clients.LOOKUP); - lookupProperties.setUri(URI); - lookupProperties.setUserName(USERNAME); - lookupProperties.setPassword(PASSWORD); - soapClientProperties.add(lookupProperties); - - SoapProperties soapProperties = new SoapProperties(); - soapProperties.setClients(soapClientProperties); - - sut = new AutoConfiguration(soapProperties); - - Assertions.assertNotNull(sut.lookupFacadeItf()); - Assertions.assertNotNull(sut.efilingLookupService(null)); - } -} diff --git a/src/backend/libs/efiling-status-client/pom.xml b/src/backend/libs/efiling-status-client/pom.xml deleted file mode 100644 index 5686b7d78a..0000000000 --- a/src/backend/libs/efiling-status-client/pom.xml +++ /dev/null @@ -1,115 +0,0 @@ - - - 4.0.0 - - - org.springframework.boot - spring-boot-starter-parent - 2.3.1.RELEASE - - - - ca.bc.gov.open.jag - efiling-status-client - 0.0.1-SNAPSHOT - efiling-status-client - Client for status for CSO efiling submissions - - - - - org.springframework.boot - spring-boot-starter-web-services - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - - - - - - - - ca.bc.gov.open.jag - efiling-bom - 0.0.1-SNAPSHOT - pom - import - - - - - - - - org.jvnet.jaxb2.maven2 - maven-jaxb2-plugin - 0.14.0 - - - - generate - - - - - WSDL - ${project.basedir}/src/main/resources/wsdl - ca.bc.gov.ag.csows.filing.status - - FilingStatusFacade.wsdl - - - - - - - org.jacoco - jacoco-maven-plugin - 0.8.5 - - - - **/*/status/*.java - - - - - - - prepare-agent - - - - - - report - test - - report - - - - - - - - - diff --git a/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/CSOStatusServiceImpl.java b/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/CSOStatusServiceImpl.java deleted file mode 100644 index 042887fd32..0000000000 --- a/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/CSOStatusServiceImpl.java +++ /dev/null @@ -1,9 +0,0 @@ -package ca.bc.gov.open.jag.efilingstatusclient; - -import org.springframework.stereotype.Service; -import org.springframework.ws.client.core.support.WebServiceGatewaySupport; - -@Service -public class CSOStatusServiceImpl extends WebServiceGatewaySupport implements EfilingStatusService { - -} diff --git a/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/EfilingStatusService.java b/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/EfilingStatusService.java deleted file mode 100644 index d0384185aa..0000000000 --- a/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/EfilingStatusService.java +++ /dev/null @@ -1,8 +0,0 @@ -package ca.bc.gov.open.jag.efilingstatusclient; - -/** - * Interface for accessing status information of a CSO e-Filing submission - */ -public interface EfilingStatusService { - -} diff --git a/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/MockCSOStatusServiceImpl.java b/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/MockCSOStatusServiceImpl.java deleted file mode 100644 index 1a17a89f6f..0000000000 --- a/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/MockCSOStatusServiceImpl.java +++ /dev/null @@ -1,7 +0,0 @@ -package ca.bc.gov.open.jag.efilingstatusclient; - - -public class MockCSOStatusServiceImpl implements EfilingStatusService { - - -} diff --git a/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/config/AutoConfiguration.java b/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/config/AutoConfiguration.java deleted file mode 100644 index 4d23733fc1..0000000000 --- a/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/config/AutoConfiguration.java +++ /dev/null @@ -1,40 +0,0 @@ -package ca.bc.gov.open.jag.efilingstatusclient.config; - -import ca.bc.gov.open.jag.efilingstatusclient.CSOStatusServiceImpl; -import ca.bc.gov.open.jag.efilingstatusclient.EfilingStatusService; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.oxm.jaxb.Jaxb2Marshaller; - -@Configuration -@EnableConfigurationProperties(CSOStatusProperties.class) -public class AutoConfiguration { - - private final CSOStatusProperties csoStatusProperties; - - public AutoConfiguration(CSOStatusProperties csoStatusProperties) { - this.csoStatusProperties = csoStatusProperties; - } - - @Bean(name = "CSOStatusMarshaller") - public Jaxb2Marshaller marshaller() { - - Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); - jaxb2Marshaller.setContextPath("ca.bc.gov.ag.csows.filing.status"); - return jaxb2Marshaller; - } - - @Bean - @ConditionalOnMissingBean(value = {EfilingStatusService.class}) - public EfilingStatusService eFilingLookupClient(@Qualifier("CSOStatusMarshaller") Jaxb2Marshaller jaxb2Marshaller) { - - CSOStatusServiceImpl eFilingStatusServiceImpl = new CSOStatusServiceImpl(); - eFilingStatusServiceImpl.setDefaultUri(csoStatusProperties.getFilingStatusSoapUri()); - eFilingStatusServiceImpl.setMarshaller(jaxb2Marshaller); - eFilingStatusServiceImpl.setUnmarshaller(jaxb2Marshaller); - return eFilingStatusServiceImpl; - } -} diff --git a/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/config/CSOStatusProperties.java b/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/config/CSOStatusProperties.java deleted file mode 100644 index e9f16f8cd8..0000000000 --- a/src/backend/libs/efiling-status-client/src/main/java/ca/bc/gov/open/jag/efilingstatusclient/config/CSOStatusProperties.java +++ /dev/null @@ -1,17 +0,0 @@ -package ca.bc.gov.open.jag.efilingstatusclient.config; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -@ConfigurationProperties(prefix = "jag.efiling.status.client") -public class CSOStatusProperties { - - private String filingStatusSoapUri; - - public String getFilingStatusSoapUri() { - return filingStatusSoapUri; - } - - public void setFilingStatusSoapUri(String filingStatusSoapUri) { - this.filingStatusSoapUri = filingStatusSoapUri; - } -} diff --git a/src/backend/libs/efiling-status-client/src/main/resources/META-INF/spring.factories b/src/backend/libs/efiling-status-client/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 2b3fc41cf4..0000000000 --- a/src/backend/libs/efiling-status-client/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - ca.bc.gov.open.jag.efilingstatusclient.config.AutoConfiguration \ No newline at end of file diff --git a/src/backend/libs/efiling-status-client/src/test/java/ca/bc/gov/open/jag/efilingstatusclient/EfilingStatusClientTest.java b/src/backend/libs/efiling-status-client/src/test/java/ca/bc/gov/open/jag/efilingstatusclient/EfilingStatusClientTest.java deleted file mode 100644 index c61eee9571..0000000000 --- a/src/backend/libs/efiling-status-client/src/test/java/ca/bc/gov/open/jag/efilingstatusclient/EfilingStatusClientTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package ca.bc.gov.open.jag.efilingstatusclient; - -import org.junit.jupiter.api.*; - - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@DisplayName("Efiling Status Client Test Suite") -public class EfilingStatusClientTest { - - - @DisplayName("CASE 1:") - @Test - public void callStatusTest() { - - } - -} diff --git a/src/backend/libs/efiling-status-client/src/test/java/ca/bc/gov/open/jag/efilingstatusclient/config/AutoConfigurationTest.java b/src/backend/libs/efiling-status-client/src/test/java/ca/bc/gov/open/jag/efilingstatusclient/config/AutoConfigurationTest.java deleted file mode 100644 index 399afb8576..0000000000 --- a/src/backend/libs/efiling-status-client/src/test/java/ca/bc/gov/open/jag/efilingstatusclient/config/AutoConfigurationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package ca.bc.gov.open.jag.efilingstatusclient.config; - -import ca.bc.gov.open.jag.efilingstatusclient.EfilingStatusService; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -@DisplayName("AutoConfiguration Test") -public class AutoConfigurationTest { - ApplicationContextRunner context = new ApplicationContextRunner() - .withUserConfiguration(AutoConfiguration.class); - - @Test - @DisplayName("CASE1: Test that beans are created") - public void testBeansAreGenerated() { - context.run(it -> { - assertThat(it).hasBean("CSOStatusMarshaller"); - Object bean = assertThat(it).getBean(EfilingStatusService.class); - Assertions.assertNotNull(bean); - }); - } -} diff --git a/src/backend/libs/efiling-status-client/src/test/java/ca/bc/gov/open/jag/efilingstatusclient/config/CSOStatusPropertiesTest.java b/src/backend/libs/efiling-status-client/src/test/java/ca/bc/gov/open/jag/efilingstatusclient/config/CSOStatusPropertiesTest.java deleted file mode 100644 index 54f2627a99..0000000000 --- a/src/backend/libs/efiling-status-client/src/test/java/ca/bc/gov/open/jag/efilingstatusclient/config/CSOStatusPropertiesTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package ca.bc.gov.open.jag.efilingstatusclient.config; - - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -@DisplayName("AutoConfiguration Test") -public class CSOStatusPropertiesTest { - - private static final String SOMEURL = "someurl"; - - @Test - @DisplayName("CASE1: test properties") - public void testProperties() { - CSOStatusProperties result = new CSOStatusProperties(); - result.setFilingStatusSoapUri(SOMEURL); - - Assertions.assertEquals(SOMEURL, result.getFilingStatusSoapUri()); - } -} diff --git a/src/backend/libs/efiling-submission-client/pom.xml b/src/backend/libs/efiling-submission-client/pom.xml deleted file mode 100644 index 1e6fbf6c27..0000000000 --- a/src/backend/libs/efiling-submission-client/pom.xml +++ /dev/null @@ -1,122 +0,0 @@ - - - 4.0.0 - - - org.springframework.boot - spring-boot-starter-parent - 2.3.1.RELEASE - - - - ca.bc.gov.open.jag - efiling-submission-client - 0.0.1-SNAPSHOT - efiling-submission-client - Client for handling submission of filings to CSO - - - - - org.springframework.boot - spring-boot-starter-web-services - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - - - - - - - ca.bc.gov.open.jag - efiling-bom - 0.0.1-SNAPSHOT - pom - import - - - - - - - - - - org.apache.cxf - cxf-codegen-plugin - 3.3.7 - - - generate-sources - generate-sources - - ${project.build.directory}/generated-sources/cxf - - - ${project.basedir}/src/main/resources/wsdl/FilingFacade.wsdl - - -client - - - - - - wsdl2java - - - - - - - - org.jacoco - jacoco-maven-plugin - 0.8.5 - - - - **/*/filing/*.java - - - - - - - prepare-agent - - - - - - report - test - - report - - - - - - - - - - \ No newline at end of file diff --git a/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/CsoSubmissionServiceImpl.java b/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/CsoSubmissionServiceImpl.java deleted file mode 100644 index 9574b18fb5..0000000000 --- a/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/CsoSubmissionServiceImpl.java +++ /dev/null @@ -1,38 +0,0 @@ -package ca.bc.gov.open.jag.efilingsubmissionclient; - -import ca.bc.gov.ag.csows.filing.FilingFacade; -import ca.bc.gov.ag.csows.filing.FilingFacadeBean; -import ca.bc.gov.ag.csows.filing.FilingPackage; -import ca.bc.gov.ag.csows.filing.NestedEjbException_Exception; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import java.math.BigDecimal; - -@Service -public class CsoSubmissionServiceImpl implements EfilingSubmissionService { - - private FilingFacade filingFacade; - private static final Logger LOGGER = LoggerFactory.getLogger(CsoSubmissionServiceImpl.class); - - public CsoSubmissionServiceImpl(FilingFacade filingFacade) { - - this.filingFacade = filingFacade; - } - - @Override - public BigDecimal submitFiling(FilingPackage filingPackage) { - - // TODO - validate incoming package? - - FilingFacadeBean port = filingFacade.getFilingFacadeBeanPort(); - - try { - return port.submitFiling(filingPackage); - } catch (NestedEjbException_Exception e) { - LOGGER.error("Expected exception: NestedEjbException has occurred :" + e.toString()); - return BigDecimal.valueOf(-1); - } - } -} diff --git a/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/DemoSubmissionServiceImpl.java b/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/DemoSubmissionServiceImpl.java deleted file mode 100644 index afa405b922..0000000000 --- a/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/DemoSubmissionServiceImpl.java +++ /dev/null @@ -1,15 +0,0 @@ -package ca.bc.gov.open.jag.efilingsubmissionclient; - -import ca.bc.gov.ag.csows.filing.FilingPackage; -import org.springframework.stereotype.Service; - -import java.math.BigDecimal; -@Service -public class DemoSubmissionServiceImpl implements EfilingSubmissionService { - - @Override - public BigDecimal submitFiling(FilingPackage filingPackage) { - - return BigDecimal.ONE; - } -} diff --git a/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/EfilingSubmissionService.java b/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/EfilingSubmissionService.java deleted file mode 100644 index af0424dc92..0000000000 --- a/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/EfilingSubmissionService.java +++ /dev/null @@ -1,11 +0,0 @@ -package ca.bc.gov.open.jag.efilingsubmissionclient; - -import ca.bc.gov.ag.csows.filing.FilingPackage; - -import java.math.BigDecimal; - - -public interface EfilingSubmissionService { - - public BigDecimal submitFiling(FilingPackage filingPackage); -} diff --git a/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/config/AutoConfiguration.java b/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/config/AutoConfiguration.java deleted file mode 100644 index 0813e89542..0000000000 --- a/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/config/AutoConfiguration.java +++ /dev/null @@ -1,34 +0,0 @@ -package ca.bc.gov.open.jag.efilingsubmissionclient.config; - -import ca.bc.gov.ag.csows.filing.FilingFacade; -import ca.bc.gov.open.jag.efilingsubmissionclient.EfilingSubmissionService; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import javax.xml.namespace.QName; -import java.net.MalformedURLException; -import java.net.URL; - -@Configuration -@EnableConfigurationProperties(CsoSubmissionProperties.class) -public class AutoConfiguration { - - private final CsoSubmissionProperties csoSubmissionProperties; - - public AutoConfiguration(CsoSubmissionProperties csoSubmissionProperties) { - - this.csoSubmissionProperties = csoSubmissionProperties; - } - - @Bean - @ConditionalOnMissingBean(value = {EfilingSubmissionService.class}) - public FilingFacade eFilingSubmissionService() throws MalformedURLException { - - QName serviceName = new QName("http://filing.csows.ag.gov.bc.ca/", "FilingFacade"); - URL url = new URL(csoSubmissionProperties.getFilingSubmissionSoapUri()); - return new FilingFacade(url, serviceName); - - } -} diff --git a/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/config/CsoSubmissionProperties.java b/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/config/CsoSubmissionProperties.java deleted file mode 100644 index 930c00030c..0000000000 --- a/src/backend/libs/efiling-submission-client/src/main/java/ca/bc/gov/open/jag/efilingsubmissionclient/config/CsoSubmissionProperties.java +++ /dev/null @@ -1,17 +0,0 @@ -package ca.bc.gov.open.jag.efilingsubmissionclient.config; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -@ConfigurationProperties(prefix = "jag.efiling.submission.client") -public class CsoSubmissionProperties { - - private String filingSubmissionSoapUri; - - public String getFilingSubmissionSoapUri() { - return filingSubmissionSoapUri; - } - - public void setFilingSubmissionSoapUri(String filingSubmissionSoapUri) { - this.filingSubmissionSoapUri = filingSubmissionSoapUri; - } -} diff --git a/src/backend/libs/efiling-submission-client/src/main/resources/META-INF/spring.factories b/src/backend/libs/efiling-submission-client/src/main/resources/META-INF/spring.factories deleted file mode 100644 index e91a1005e8..0000000000 --- a/src/backend/libs/efiling-submission-client/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - ca.bc.gov.open.jag.efilingsubmissionclient.config.AutoConfiguration \ No newline at end of file diff --git a/src/backend/libs/efiling-submission-client/src/test/java/ca/bc/gov/open/jag/efilingsubmissionclient/CsoSubmissionServiceImplTest.java b/src/backend/libs/efiling-submission-client/src/test/java/ca/bc/gov/open/jag/efilingsubmissionclient/CsoSubmissionServiceImplTest.java deleted file mode 100644 index 8873b680fd..0000000000 --- a/src/backend/libs/efiling-submission-client/src/test/java/ca/bc/gov/open/jag/efilingsubmissionclient/CsoSubmissionServiceImplTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package ca.bc.gov.open.jag.efilingsubmissionclient; - -import ca.bc.gov.ag.csows.filing.FilingFacade; -import ca.bc.gov.ag.csows.filing.FilingFacadeBean; -import ca.bc.gov.ag.csows.filing.FilingPackage; -import ca.bc.gov.ag.csows.filing.NestedEjbException_Exception; -import org.junit.jupiter.api.*; -import org.mockito.*; - -import java.math.BigDecimal; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@DisplayName("CSO Submission Service Suite") -public class CsoSubmissionServiceImplTest { - - private static final String CASE_1 = "CASE_1"; - private static final String CASE_2 = "CASE 2"; - - CsoSubmissionServiceImpl sut; - - @Mock - FilingFacade mockFilingFacade; - - @Mock - FilingFacadeBean mockFilingFacadeBean; - - @BeforeEach - public void init() throws NestedEjbException_Exception { - - MockitoAnnotations.initMocks(this); - - Mockito.when(mockFilingFacade.getFilingFacadeBeanPort()).thenReturn(mockFilingFacadeBean); - - Mockito - .doReturn(BigDecimal.ONE) - .when(mockFilingFacadeBean) - .submitFiling(ArgumentMatchers.argThat(x -> x.getApplicationCd().equals(CASE_1))); - - Mockito - .doThrow(new NestedEjbException_Exception("random")) - .when(mockFilingFacadeBean) - .submitFiling(ArgumentMatchers.argThat(x -> x.getApplicationCd().equals(CASE_2))); - - sut = new CsoSubmissionServiceImpl(mockFilingFacade); - - } - - @Test - @DisplayName("CASE 1: With valid params should return submission status") - public void testSubmission() throws NestedEjbException_Exception { - - - FilingPackage filingPackage = new FilingPackage(); - filingPackage.setApplicationCd(CASE_1); - BigDecimal response = sut.submitFiling(filingPackage); - - Assertions.assertEquals(BigDecimal.ONE, response); - verify(mockFilingFacade, times(1)).getFilingFacadeBeanPort(); - verify(mockFilingFacadeBean, times(1)).submitFiling(any()); - } - - @Test - @DisplayName("CASE 2: With exception should return default value") - public void withExceptionShouldReturnDefault() throws NestedEjbException_Exception { - - FilingPackage filingPackage = new FilingPackage(); - filingPackage.setApplicationCd(CASE_2); - - BigDecimal response = sut.submitFiling(filingPackage); - - Assertions.assertEquals(BigDecimal.valueOf(-1), response); - - } - -} diff --git a/src/backend/libs/efiling-submission-client/src/test/java/ca/bc/gov/open/jag/efilingsubmissionclient/DemoSubmissionServiceImplTest.java b/src/backend/libs/efiling-submission-client/src/test/java/ca/bc/gov/open/jag/efilingsubmissionclient/DemoSubmissionServiceImplTest.java deleted file mode 100644 index 4f4cc76744..0000000000 --- a/src/backend/libs/efiling-submission-client/src/test/java/ca/bc/gov/open/jag/efilingsubmissionclient/DemoSubmissionServiceImplTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package ca.bc.gov.open.jag.efilingsubmissionclient; - -import ca.bc.gov.ag.csows.filing.FilingPackage; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; - -import java.math.BigDecimal; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@DisplayName("DemoSubmissionServiceImpl Test Suite") -public class DemoSubmissionServiceImplTest { - @Test - @DisplayName("CASE1: Test Demo Submission") - public void testSubmission() { - - DemoSubmissionServiceImpl demoSubmissionService = new DemoSubmissionServiceImpl(); - BigDecimal result = demoSubmissionService.submitFiling(new FilingPackage()); - Assertions.assertEquals(BigDecimal.valueOf(1), result); - } -} diff --git a/src/backend/libs/efiling-submission-client/src/test/java/ca/bc/gov/open/jag/efilingsubmissionclient/config/AutoConfigurationTest.java b/src/backend/libs/efiling-submission-client/src/test/java/ca/bc/gov/open/jag/efilingsubmissionclient/config/AutoConfigurationTest.java deleted file mode 100644 index 4e895f17fe..0000000000 --- a/src/backend/libs/efiling-submission-client/src/test/java/ca/bc/gov/open/jag/efilingsubmissionclient/config/AutoConfigurationTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package ca.bc.gov.open.jag.efilingsubmissionclient.config; - -import ca.bc.gov.ag.csows.filing.FilingFacade; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import java.net.MalformedURLException; - -@DisplayName("AutoConfiguration Test") -public class AutoConfigurationTest { - - private AutoConfiguration sut; - - @Test - @DisplayName("CASE2: with malformed url should throw MalformedException") - public void withMalformedUrlShouldTrhowException() { - - CsoSubmissionProperties properties = new CsoSubmissionProperties(); - properties.setFilingSubmissionSoapUri("test"); - - sut = new AutoConfiguration(properties); - - Assertions.assertThrows(MalformedURLException.class, () -> { - - - FilingFacade actual = sut.eFilingSubmissionService(); - - }); - - } -} diff --git a/src/backend/pom.xml b/src/backend/pom.xml index 106b39a38a..b60e2a7ed4 100644 --- a/src/backend/pom.xml +++ b/src/backend/pom.xml @@ -6,44 +6,85 @@ ca.bc.gov.open jag-efiling-backend - 0.0.1-SNAPSHOT + 2.0.12-SNAPSHOT - FLA Document Upload + EfilingHub Backend services jag-efiling-backend pom https://github.com/bcgov/jag-file-submission - 1.8 + 17 + 2.17.1 all + libs/efiling-bambora-api-client + libs/efiling-ceis-api-client libs/efiling-commons - libs/efiling-submission-client - libs/efiling-lookup-client - libs/efiling-status-client - libs/efiling-account-client + libs/efiling-cso-client + libs/efiling-cso-starter libs/efiling-bom libs/efiling-demo-starter efiling-api - efiling-worker - efiling-backend-demo libs + + libs/efiling-bambora-api-client + libs/efiling-ceis-api-client + libs/efiling-commons + libs/efiling-cso-client + libs/efiling-cso-starter + libs/efiling-bom + + + + efiling-api-demo libs/efiling-bom libs/efiling-commons - libs/efiling-lookup-client - libs/efiling-account-client libs/efiling-demo-starter + efiling-api + + + + efiling-api + + libs/efiling-bom + libs/efiling-commons + libs/efiling-bambora-api-client + libs/efiling-ceis-api-client + libs/efiling-cso-client + libs/efiling-cso-starter + efiling-api + + + + efiling-reviewer + + libs/efiling-bom + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + ${java.version} + ${java.version} + + + + + diff --git a/src/frontend/.dockerignore b/src/frontend/.dockerignore index f19f614b24..2b503d9341 100644 --- a/src/frontend/.dockerignore +++ b/src/frontend/.dockerignore @@ -1,7 +1,6 @@ node_modules efiling-demo/node_modules efiling-frontend/node_modules -shared-components/node_modules build .dockerignore Dockerfile diff --git a/src/frontend/.gitignore b/src/frontend/.gitignore new file mode 100644 index 0000000000..d50829563b --- /dev/null +++ b/src/frontend/.gitignore @@ -0,0 +1 @@ +env-config.js diff --git a/src/frontend/Dockerfile b/src/frontend/Dockerfile deleted file mode 100644 index 5c19334254..0000000000 --- a/src/frontend/Dockerfile +++ /dev/null @@ -1,36 +0,0 @@ -# pull official base image -FROM node:13.12.0-alpine - -ARG SERVICE_NAME - -RUN npm install -g linklocal - -COPY . . - -WORKDIR /shared-components - -RUN yarn install - -# set working directory -WORKDIR /${SERVICE_NAME} - -# add `/node_modules/.bin` to $PATH -ENV PATH ./node_modules/.bin:$PATH - -ENV REACT_APP_API_BASE_URL=http://localhost:8080 - -# install dependencies -RUN yarn install -RUN yarn global add react-scripts@3.4.1 - -WORKDIR /shared-components - -RUN npm link ../${SERVICE_NAME}/node_modules/react - -# set working directory -WORKDIR /${SERVICE_NAME} - -RUN linklocal - -# start app -CMD ["yarn", "start"] diff --git a/src/frontend/efiling-demo/.dockerignore b/src/frontend/efiling-demo/.dockerignore new file mode 100644 index 0000000000..54d44788eb --- /dev/null +++ b/src/frontend/efiling-demo/.dockerignore @@ -0,0 +1,4 @@ +/.vscode +/build +/coverage +/node_modules diff --git a/src/frontend/efiling-demo/.env.example b/src/frontend/efiling-demo/.env.example index 0be8b55ff8..bdb462bf1a 100644 --- a/src/frontend/efiling-demo/.env.example +++ b/src/frontend/efiling-demo/.env.example @@ -1 +1,8 @@ -REACT_APP_API_BASE_URL= +REACT_APP_DEFAULT_IDENTITY_PROVIDER=bceid +REACT_APP_KEYCLOAK_REALM=Efiling-Hub +REACT_APP_KEYCLOAK_CLIENT_ID=efiling-admin +REACT_APP_KEYCLOAK_URL=http://localhost:8081/auth +REACT_APP_API_BASE_URL=http://localhost:8080 +PORT=3001 +SKIP_PREFLIGHT_CHECK=true +ESLINT_NO_DEV_ERRORS=true diff --git a/src/frontend/efiling-demo/.env.production b/src/frontend/efiling-demo/.env.production new file mode 100644 index 0000000000..27339e49ea --- /dev/null +++ b/src/frontend/efiling-demo/.env.production @@ -0,0 +1,2 @@ +SKIP_PREFLIGHT_CHECK=true +DISABLE_ESLINT_PLUGIN=true diff --git a/src/frontend/efiling-demo/.env.template b/src/frontend/efiling-demo/.env.template new file mode 100644 index 0000000000..62f02a369d --- /dev/null +++ b/src/frontend/efiling-demo/.env.template @@ -0,0 +1,4 @@ +REACT_APP_KEYCLOAK_REALM=Efiling-Hub +REACT_APP_KEYCLOAK_CLIENT_ID=efiling-admin +REACT_APP_KEYCLOAK_URL=http://localhost:8081/auth +REACT_APP_API_BASE_URL=http://localhost:8080 diff --git a/src/frontend/efiling-demo/.eslintrc.js b/src/frontend/efiling-demo/.eslintrc.js index 6ac023e5dd..8337991c85 100644 --- a/src/frontend/efiling-demo/.eslintrc.js +++ b/src/frontend/efiling-demo/.eslintrc.js @@ -2,28 +2,35 @@ module.exports = { env: { browser: true, es6: true, - jest: true + jest: true, }, extends: ["plugin:react/recommended", "airbnb", "prettier"], globals: { Atomics: "readonly", - SharedArrayBuffer: "readonly" + SharedArrayBuffer: "readonly", }, parserOptions: { ecmaFeatures: { - jsx: true + jsx: true, }, ecmaVersion: 2018, - sourceType: "module" + sourceType: "module", }, - plugins: ["react", "prettier"], + plugins: ["prettier"], ignorePatterns: ["node_modules/", "build/"], rules: { "import/no-unresolved": "off", + "react/forbid-prop-types": "off", "react/jsx-filename-extension": "off", "react/jsx-curly-brace-presence": "off", "import/no-extraneous-dependencies": "off", "import/prefer-default-export": "off", - "prettier/prettier": ["error"] - } + "no-param-reassign": "off", + "prettier/prettier": [ + "error", + { + endOfLine: "auto", + }, + ], + }, }; diff --git a/src/frontend/efiling-demo/.gitignore b/src/frontend/efiling-demo/.gitignore index 675bdf1d74..99c954ac59 100644 --- a/src/frontend/efiling-demo/.gitignore +++ b/src/frontend/efiling-demo/.gitignore @@ -13,6 +13,7 @@ # misc .DS_Store +.env.dev .env.local .env.development.local .env.development @@ -22,3 +23,5 @@ npm-debug.log* yarn-debug.log* yarn-error.log* + +.vscode/launch.json diff --git a/src/frontend/efiling-demo/Dockerfile b/src/frontend/efiling-demo/Dockerfile new file mode 100644 index 0000000000..a86e79787a --- /dev/null +++ b/src/frontend/efiling-demo/Dockerfile @@ -0,0 +1,43 @@ +# pull official base image +FROM node:18-alpine as build + +WORKDIR /app + +COPY ./package.json ./yarn.lock ./ + +RUN yarn install --production=true \ + && yarn add --dev react-app-rewired # this line makes sure that react-app-rewired scripts will be in the PATH. It can + # be removed when the react-app-rewired module is no longer required to the project. + +COPY . . + +RUN yarn build --production=true + +############################################################################################# +### PRODUCTION IMAGE ### +############################################################################################# +FROM nginx:1.28.0-alpine + +RUN apk update && apk add --upgrade --no-cache libexpat libxml2 libxslt + +RUN rm -rf /usr/share/nginx/html/ +COPY --from=build /app/build /usr/share/nginx/html +WORKDIR /usr/share/nginx/html + +RUN rm /etc/nginx/conf.d/default.conf +COPY nginx.conf /etc/nginx/conf.d + +COPY ./env.sh . +COPY ./.env.template .env + +# CMD ["nginx", "-g", "daemon off;"] +RUN chmod g+rwx /var/cache/nginx /var/run /var/log/nginx +RUN chmod g+rwx /usr/share/nginx/html/ + +# Add bash +RUN apk add --no-cache bash + +# Make our shell script executable +RUN chmod g+rwx env.sh + +CMD ["/bin/bash", "-c", "/usr/share/nginx/html/env.sh && nginx -g \"daemon off;\""] diff --git a/src/frontend/efiling-demo/README.md b/src/frontend/efiling-demo/README.md index fe3ad403ec..4aa6f303af 100644 --- a/src/frontend/efiling-demo/README.md +++ b/src/frontend/efiling-demo/README.md @@ -4,21 +4,53 @@ Welcome to the eFiling demo! ## Running the Frontend -In the project directory (`efiling-demo`), you can run: +### Running against local dockerized backend -### `yarn install` +In the project directory `efiling-demo`: + +Create a `.env.development` file and populate the environment variables as +shown in the `.env.example` file. + +To bring up all the backend docker containers locally, in the root directory +`jag-file-submission`, run: + +```bash +docker-compose up efiling-api efiling-frontend keycloak keycloak-config redis +``` + +Continue below with `yarn install` + +### Running the Frontend against the dockerized containers on DEV + +It's possible to run the demo application locally, but use keycloak, the api, +and the other backend containers running on DEV (dev.justice.gov.bc.ca). + +In the project directory `efiling-demo`: + +Create a `.env.development` file and populate the environment variables as +shown in the `.env.example` with values from OpenShift. + +In the project directory `efiling-demo` open a new terminal and run: + +```bash +yarn install +``` Installs all the required dependencies to get the application up and running. -### `yarn start` +```bash +yarn start +``` Runs the app in the development mode.
-Open [http://localhost:3000](http://localhost:3000) to view it in the browser. +Open [http://localhost:3001](http://localhost:3001) to view it in the browser. The page will reload if you make edits.
You will also see any lint errors in the console. -### `yarn run build` +```bash +yarn run build +``` Builds the app for production to the `build` folder.
It correctly bundles React in production mode and optimizes the build for the best performance. @@ -26,7 +58,9 @@ It correctly bundles React in production mode and optimizes the build for the be The build is minified and the filenames include the hashes.
Your app is ready to be deployed! -### `yarn run eject` +```bash +yarn run eject +``` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** @@ -40,11 +74,15 @@ You don’t have to ever use `eject`. The curated feature set is suitable for sm This project uses ESLint and Prettier to ensure that the code being written follows standard guidelines and standards, and that the code styling is kept consistent throughout the application. -### `npx eslint .` +```bash +npx eslint . +``` Runs the linter on the entire frontend codebase and reports any errors or warnings that may be present. -### `prettier [opts] [filename ...]` +```bash +prettier [opts] [filename ...] +``` Runs prettier and formats your file. This has been setup by Husky to run on every commit, so prettier will check all the files within the directory and format them on every commit. @@ -52,7 +90,9 @@ Runs prettier and formats your file. This has been setup by Husky to run on ever This project uses component-driven development and storybook in order to create stories for frontend components. In order to run the storybook locally, you can run: -### `yarn run storybook` +```bash +yarn run storybook +``` Storybook should start, on a random open port in dev-mode. Now you can develop your components and write stories and see the changes in Storybook immediately since it uses Webpack’s hot module reloading.
@@ -62,6 +102,8 @@ Open [http://localhost:9009](http://localhost:9009) to view it in the browser. This project uses Jest for snapshot component testing. Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly. A typical snapshot test case renders a UI component, takes a snapshot, then compares it to a reference snapshot file stored alongside the test. The test will fail if the two snapshots do not match: either the change is unexpected, or the reference snapshot needs to be updated to the new version of the UI component. -### `yarn run test` +```bash +yarn run test +``` Launches the test runner in the interactive watch mode. diff --git a/src/frontend/efiling-demo/config-overrides.js b/src/frontend/efiling-demo/config-overrides.js new file mode 100644 index 0000000000..744fa45017 --- /dev/null +++ b/src/frontend/efiling-demo/config-overrides.js @@ -0,0 +1,22 @@ +const webpack = require("webpack"); + +module.exports = function override(config) { + const fallback = config.resolve.fallback || {}; + Object.assign(fallback, { + crypto: require.resolve("crypto-browserify"), + stream: require.resolve("stream-browserify"), + assert: require.resolve("assert"), + http: require.resolve("stream-http"), + https: require.resolve("https-browserify"), + os: require.resolve("os-browserify"), + url: require.resolve("url"), + }); + config.resolve.fallback = fallback; + config.plugins = (config.plugins || []).concat([ + new webpack.ProvidePlugin({ + process: "process/browser", + Buffer: ["buffer", "Buffer"], + }), + ]); + return config; +}; diff --git a/src/frontend/efiling-demo/env.sh b/src/frontend/efiling-demo/env.sh new file mode 100644 index 0000000000..bf9ba23b25 --- /dev/null +++ b/src/frontend/efiling-demo/env.sh @@ -0,0 +1,31 @@ +#!/bin/bash + +# Recreate config file +rm -rf ./env-config.js +touch ./env-config.js + +# Add assignment +echo "window.env = {" >> ./env-config.js + +# Read each line in .env file +# Each line represents key=value pairs +while read -r line || [[ -n "$line" ]]; +do + # Split env variables by character `=` + if printf '%s\n' "$line" | grep -q -e '='; then + varname=$(printf '%s\n' "$line" | sed -e 's/=.*//') + varvalue=$(printf '%s\n' "$line" | sed -e 's/^[^=]*=//') + fi + + # Read value of current variable if exists as Environment variable + value=$(printf '%s\n' "${!varname}") + # Otherwise use value from .env file + [[ -z $value ]] && value=${varvalue} + # Fix the line ending if it is a windows one + value="$(echo "$value" | sed -e 's/\r//g')" + + # Append configuration property to JS file + echo " $varname: \"$value\"," >> ./env-config.js +done < .env + +echo "}" >> ./env-config.js diff --git a/src/frontend/efiling-demo/nginx.conf b/src/frontend/efiling-demo/nginx.conf new file mode 100644 index 0000000000..67e13ae46a --- /dev/null +++ b/src/frontend/efiling-demo/nginx.conf @@ -0,0 +1,29 @@ +server { + + listen 8080; + + location / { + root /usr/share/nginx/html; + index index.html index.htm; + try_files $uri $uri/ /index.html; + } + + location ~* \.env-config\.js$ { + expires -1; + add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'; + add_header X-Content-Type-Options "nosniff" always; + add_header X-XSS-Protection "1; mode=block"; + add_header X-Content-Type-Options "nosniff" always; + add_header Cache-Control "no-store"; + add_header "Pragma" "no-cache"; + add_header Content-Security-Policy "default-src 'self';"; + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + } + + error_page 500 502 503 504 /50x.html; + + location = /50x.html { + root /usr/share/nginx/html; + } + +} diff --git a/src/frontend/efiling-demo/package.json b/src/frontend/efiling-demo/package.json index fef647ada7..fe6da3ae06 100644 --- a/src/frontend/efiling-demo/package.json +++ b/src/frontend/efiling-demo/package.json @@ -1,38 +1,71 @@ { "name": "efiling-demo", - "version": "0.1.0", - "homepage": "/efiling-demo", + "version": "2.0.11", + "homepage": ".", "private": true, "dependencies": { - "@babel/preset-react": "^7.8.3", + "@babel/preset-react": "^7.13.13", "@bcgov/bootstrap-theme": "github:bcgov/bootstrap-theme", - "axios": "^0.19.2", + "@csstools/normalize.css": "csstools/normalize.css", + "axios": "^0.30.0", "babel-plugin-transform-export-extensions": "^6.22.0", - "bootstrap": "^4.4.1", - "enzyme": "^3.11.0", - "enzyme-adapter-react-16": "^1.15.2", - "history": "^4.10.1", + "bootstrap": "^4.5.3", + "browserslist": "^4.19.1", + "eslint-plugin-airbnb": "^0.0.1-security", + "history": "^5.0.0", + "install-peerdeps": "^3.0.3", + "jest-canvas-mock": "^2.5.0", + "jsonwebtoken": "^9.0.0", + "keycloak-js": "^25.0.6", + "node": "^17.3.0", + "object-path": "^0.11.8", + "postcss-normalize": "^10.0.1", "prop-types": "^15.7.2", - "react": "^16.13.1", - "react-app-polyfill": "^1.0.6", + "query-string": "^6.13.6", + "react": "^17.0.2", + "react-app-polyfill": "^3.0.0", "react-dom": "^16.13.1", - "react-router-dom": "^5.1.2", - "react-scripts": "3.4.1", - "react-test-renderer": "^16.12.0", + "react-dropzone": "^11.3.2", + "react-router-dom": "^6.1.1", + "react-scripts": "^5.0.1", "regenerator-runtime": "^0.13.5", - "shared-components": "file:./../shared-components", - "webpack": "4.42.0" + "shared-components": "https://github.com/bcgov/react-shared-components/releases/download/v1.3.1/shared-components-1.3.1.tgz", + "uuid": "^8.3.1" }, "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "jest", - "eject": "react-scripts eject", + "start": "react-app-rewired start", + "build": "react-app-rewired build", + "test": "jest --env='jsdom'", + "eject": "react-app-rewired eject", "storybook": "start-storybook -p 9009 -s public", "build-storybook": "build-storybook -s public", "lint": "eslint .", "lint:fix": "eslint --fix .", - "coverage": "jest --coverage" + "coverage": "jest --coverage --env='jsdom'", + "precommit": "pretty-quick --staged" + }, + "resolutions": { + "form-data": "4.0.4", + "immer": "9.0.6", + "trim": "0.0.3", + "glob-parent": "5.1.2", + "loader-utils": "^2.0.4", + "nth-check": "^2.0.1", + "terser": "^5.14.2", + "json5": "^2.2.2", + "minimatch": "^3.0.5", + "webpack": "^5.76.0", + "braces": "^3.0.3", + "webpack-dev-middleware": "^5.3.4", + "browserify-sign": "4.2.2", + "ws": "^8.17.1", + "rollup": "^2.79.2", + "body-parser": "^1.20.3", + "path-to-regexp": "^0.1.12", + "http-proxy-middleware": "^2.0.7", + "elliptic": "^6.6.1", + "cross-spawn": "^7.0.5", + "semver": "^7.5.2" }, "eslintConfig": { "extends": "react-app" @@ -50,32 +83,46 @@ ] }, "devDependencies": { - "@babel/core": "^7.8.4", - "@babel/preset-env": "^7.8.4", - "@storybook/addon-actions": "^5.3.19", - "@storybook/addon-links": "^5.3.19", - "@storybook/addon-storyshots": "^5.3.14", - "@storybook/addon-viewport": "^5.3.13", - "@storybook/addons": "^5.3.19", - "@storybook/preset-create-react-app": "^3.0.0", - "@storybook/react": "^5.3.19", - "@testing-library/jest-dom": "^4.2.4", - "@testing-library/react": "^9.3.2", - "@testing-library/react-hooks": "3.2.1", - "@testing-library/user-event": "^7.1.2", + "@babel/core": "^7.13.16", + "@babel/preset-env": "^7.16.11", + "@storybook/addon-actions": "^6.5.15", + "@storybook/addon-links": "^6.4.19", + "@storybook/addon-storyshots": "^6.4.19", + "@storybook/addon-viewport": "^6.4.19", + "@storybook/addons": "^6.4.19", + "@storybook/preset-create-react-app": "^4.0.0", + "@storybook/react": "^6.4.19", + "@testing-library/jest-dom": "^5.12.0", + "@testing-library/react": "^12.1.5", + "@testing-library/react-hooks": "7.0.2", + "@testing-library/user-event": "^13.1.1", + "assert": "^2.0.0", "axios-mock-adapter": "^1.18.1", - "eslint": "^6.8.0", + "babel-loader": "9.1.0", + "buffer": "^6.0.3", + "crypto-browserify": "^3.12.0", + "enzyme": "^3.11.0", + "enzyme-adapter-react-16": "^1.15.6", + "enzyme-to-json": "^3.6.2", "eslint-config-airbnb": "^18.0.1", - "eslint-config-prettier": "^6.11.0", - "eslint-plugin-import": "^2.20.1", - "eslint-plugin-jsx-a11y": "^6.2.3", - "eslint-plugin-prettier": "^3.1.2", - "eslint-plugin-react": "^7.18.3", - "eslint-plugin-react-hooks": "^1.7.0", - "husky": "^4.2.5", + "eslint-config-prettier": "^8.6.0", + "eslint-plugin-import": "^2.23.4", + "eslint-plugin-jsx-a11y": "^6.5.1", + "eslint-plugin-prettier": "^4.0.0", + "eslint-plugin-react": "^7.24.0", + "eslint-plugin-react-hooks": "^4.6.0", + "https-browserify": "^1.0.0", + "jest-environment-jsdom-sixteen": "^2.0.0", "jest-sonar-reporter": "^2.0.0", - "prettier": "1.19.1", - "pretty-quick": "^2.0.1" + "os-browserify": "^0.3.0", + "prettier": "2.8.0", + "pretty-quick": "^3.1.0", + "process": "^0.11.10", + "react-app-rewired": "^2.2.1", + "react-test-renderer": "^18.2.0", + "stream-browserify": "^3.0.0", + "stream-http": "^3.2.0", + "url": "^0.11.0" }, "jest": { "watchPathIgnorePatterns": [ @@ -83,7 +130,8 @@ ], "collectCoverageFrom": [ "src/**/*.js", - "!src/index.js", + "!src/*.js", + "!src/components/hoc/*.js", "!**/node_modules/**", "!**/vendor/**" ], @@ -111,11 +159,5 @@ "reportPath": "coverage", "reportFile": "test-report.xml", "indent": 4 - }, - "husky": { - "hooks": { - "pre-commit": "pretty-quick --staged", - "pre-push": "npx eslint ." - } } } diff --git a/src/frontend/efiling-demo/public/favicon.ico b/src/frontend/efiling-demo/public/favicon.ico new file mode 100644 index 0000000000..1841396d21 Binary files /dev/null and b/src/frontend/efiling-demo/public/favicon.ico differ diff --git a/src/frontend/efiling-demo/public/index.html b/src/frontend/efiling-demo/public/index.html index c9ad8c568f..c15c8f889f 100644 --- a/src/frontend/efiling-demo/public/index.html +++ b/src/frontend/efiling-demo/public/index.html @@ -9,7 +9,6 @@ name="description" content="Web site created using create-react-app" /> - + + eFiling Demo Client diff --git a/src/frontend/efiling-demo/public/manifest.json b/src/frontend/efiling-demo/public/manifest.json index 5cb68e4ad3..e312fdaff4 100644 --- a/src/frontend/efiling-demo/public/manifest.json +++ b/src/frontend/efiling-demo/public/manifest.json @@ -1,6 +1,6 @@ { - "short_name": "eFiling Frontend", - "name": "JAG File Submission Frontend App", + "short_name": "eFiling Demo", + "name": "JAG File Submission Demo App", "start_url": ".", "display": "standalone", "theme_color": "#000000", diff --git a/src/frontend/efiling-demo/src/App.js b/src/frontend/efiling-demo/src/App.js index eb8647b43c..fdace7a328 100644 --- a/src/frontend/efiling-demo/src/App.js +++ b/src/frontend/efiling-demo/src/App.js @@ -1,45 +1,48 @@ import React from "react"; -import { - Switch, - Route, - Redirect, - useHistory, - useLocation -} from "react-router-dom"; +import { Routes, Route, useNavigate, useLocation } from "react-router-dom"; import queryString from "query-string"; -import Home from "./components/page/home/Home"; +import AuthenticationGuard from "./components/hoc/AuthenticationGuard"; import Cancel from "./components/page/cancel/Cancel"; import Error from "./components/page/error/Error"; import Success from "./components/page/success/Success"; +import UpdateCreditCard from "./components/page/payment/creditcard/UpdateCreditCard"; export default function App() { const location = useLocation(); const queryParams = queryString.parse(location.search); - const { error } = queryParams; + const { status, message, packageRef } = queryParams; const header = { name: "eFiling Demo Client", - history: useHistory() + history: useNavigate(), }; return (
- - - - - - - - - - - - - - - + + } + /> + } /> + } + /> + } + /> + } + /> +
); } diff --git a/src/frontend/efiling-demo/src/AssetsTransformer.js b/src/frontend/efiling-demo/src/AssetsTransformer.js index 1e9329ec1c..8bacdbcae1 100644 --- a/src/frontend/efiling-demo/src/AssetsTransformer.js +++ b/src/frontend/efiling-demo/src/AssetsTransformer.js @@ -6,5 +6,5 @@ const path = require("path"); module.exports = { process(src, filename) { return `module.exports = ${JSON.stringify(path.basename(filename))};`; - } + }, }; diff --git a/src/frontend/efiling-demo/src/__snapshots__/storyshots.test.js.snap b/src/frontend/efiling-demo/src/__snapshots__/storyshots.test.js.snap deleted file mode 100644 index 82e6bb5742..0000000000 --- a/src/frontend/efiling-demo/src/__snapshots__/storyshots.test.js.snap +++ /dev/null @@ -1,1301 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Storyshots Cancel Default 1`] = ` -
-
- -
-
-
-

- You have cancelled your submission. Please click the button below to go back home. -

-
- -
-
-
- -
-`; - -exports[`Storyshots Cancel Mobile 1`] = ` -
-
- -
-
-
-

- You have cancelled your submission. Please click the button below to go back home. -

-
- -
-
-
- -
-`; - -exports[`Storyshots Error Default 1`] = ` -
-
- -
-
-
-

- The following error occurred with your submission. Please click the button below to go back home. -

-

- - Could not communicate with CSO. - -

-
-
- -
-
-
- -
-`; - -exports[`Storyshots Error Mobile 1`] = ` -
-
- -
-
-
-

- The following error occurred with your submission. Please click the button below to go back home. -

-

- - Could not communicate with CSO. - -

-
-
- -
-
-
- -
-`; - -exports[`Storyshots Home Default 1`] = ` -
-
- -
-
-
-
- - -
- -
-
-
- -
-
-
-
- -
-`; - -exports[`Storyshots Home Mobile 1`] = ` -
-
- -
-
-
-
- - -
- -
-
-
- -
-
-
-
- -
-`; - -exports[`Storyshots Success Default 1`] = ` -
-
- -
-
-
-

- You have successfully completed your submission. Please click the button below to go back home. -

-
- -
-
-
- -
-`; - -exports[`Storyshots Success Mobile 1`] = ` -
-
- -
-
-
-

- You have successfully completed your submission. Please click the button below to go back home. -

-
- -
-
-
- -
-`; diff --git a/src/frontend/efiling-demo/src/actionStatusList.json b/src/frontend/efiling-demo/src/actionStatusList.json new file mode 100644 index 0000000000..7aba601b65 --- /dev/null +++ b/src/frontend/efiling-demo/src/actionStatusList.json @@ -0,0 +1,7 @@ +[ + { "id": "SUB", "desc": "Submitted" }, + { "id": "RSUB", "desc": "Resubmitted" }, + { "id": "REF", "desc": "Referred" }, + { "id": "REJ", "desc": "Reject" }, + { "id": "CCOR", "desc": "Courtesy Correction" } +] diff --git a/src/frontend/efiling-demo/src/components/hoc/AuthenticationGuard.js b/src/frontend/efiling-demo/src/components/hoc/AuthenticationGuard.js new file mode 100644 index 0000000000..b321763ab2 --- /dev/null +++ b/src/frontend/efiling-demo/src/components/hoc/AuthenticationGuard.js @@ -0,0 +1,68 @@ +import React, { useState, useEffect } from "react"; +import PropTypes from "prop-types"; +import Keycloak from "keycloak-js"; +import Home from "../page/home/Home"; +import { propTypes } from "../../types/propTypes"; + +const url = window.env + ? window.env.REACT_APP_KEYCLOAK_URL + : process.env.REACT_APP_KEYCLOAK_URL; +const realm = window.env + ? window.env.REACT_APP_KEYCLOAK_REALM + : process.env.REACT_APP_KEYCLOAK_REALM; +const clientId = window.env + ? window.env.REACT_APP_KEYCLOAK_CLIENT_ID + : process.env.REACT_APP_KEYCLOAK_CLIENT_ID; + +const KEYCLOAK = { + realm, + url, + clientId, +}; + +/** + * @constant authenticationGuard - a higher order component that checks for user authorization and returns the wrapped component if the user is authenticated + */ + +export default function AuthenticationGuard({ page: { header } }) { + const [authedKeycloak, setAuthedKeycloak] = useState(null); + + async function keycloakInit() { + // Initialize client + const keycloak = new Keycloak(KEYCLOAK); + + await keycloak + .init({ + checkLoginIframe: false, + }) + .then((authenticated) => { + if (authenticated) { + keycloak.loadUserInfo().then(); + localStorage.setItem("jwt", keycloak.token); + setAuthedKeycloak(keycloak); + } else { + keycloak.login(); + } + }) + .catch((exception) => { + console.log(exception); + }); + } + + useEffect(() => { + keycloakInit(); + }, []); + + return ( + <> + {authedKeycloak && } + {!authedKeycloak && null} + + ); +} + +AuthenticationGuard.propTypes = { + page: PropTypes.shape({ + header: propTypes.header, + }).isRequired, +}; diff --git a/src/frontend/efiling-demo/src/components/page/cancel/Cancel.js b/src/frontend/efiling-demo/src/components/page/cancel/Cancel.js index 8a0269abea..1449ac30a2 100644 --- a/src/frontend/efiling-demo/src/components/page/cancel/Cancel.js +++ b/src/frontend/efiling-demo/src/components/page/cancel/Cancel.js @@ -14,9 +14,10 @@ export default function Cancel({ page: { header } }) { go back home.

+ + + + + +`; + +exports[`Storyshots Cancel Mobile 1`] = ` + +
+
+ +
+
+
+

+ You have cancelled your submission. Please click the button below to go back home. +

+ +
+
+ +
+
+`; diff --git a/src/frontend/efiling-demo/src/components/page/cancel/__snapshots__/Cancel.test.js.snap b/src/frontend/efiling-demo/src/components/page/cancel/__snapshots__/Cancel.test.js.snap index 2701b74779..43a741bb85 100644 --- a/src/frontend/efiling-demo/src/components/page/cancel/__snapshots__/Cancel.test.js.snap +++ b/src/frontend/efiling-demo/src/components/page/cancel/__snapshots__/Cancel.test.js.snap @@ -3,39 +3,45 @@ exports[`Cancel Component matches the snapshot 1`] = `
-
+
@@ -48,20 +54,20 @@ exports[`Cancel Component matches the snapshot 1`] = `

You have cancelled your submission. Please click the button below to go back home.

-
- -
+
+
+`; + +exports[`Storyshots Error Mobile 1`] = ` + +
+
+ +
+
+
+

+ The following error occurred with your submission. Please click the button below to go back home. +

+

+ + Status: 400 + + + Message: Could not communicate with CSO. + +

+
+ +
+
+ +
+
+`; diff --git a/src/frontend/efiling-demo/src/components/page/error/__snapshots__/Error.test.js.snap b/src/frontend/efiling-demo/src/components/page/error/__snapshots__/Error.test.js.snap index 48a991d90b..58995be2f7 100644 --- a/src/frontend/efiling-demo/src/components/page/error/__snapshots__/Error.test.js.snap +++ b/src/frontend/efiling-demo/src/components/page/error/__snapshots__/Error.test.js.snap @@ -3,39 +3,45 @@ exports[`Error Component matches the snapshot 1`] = `
-
+
@@ -48,26 +54,31 @@ exports[`Error Component matches the snapshot 1`] = `

The following error occurred with your submission. Please click the button below to go back home.

-

+

+ + Status: 400 + - Could not communicate with CSO. + Message: Could not communicate with CSO.


-
- -
+